コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
ef4d7e8024
|
||
|
|
299da15bb8
|
||
|
|
ffba68aeb0
|
||
|
|
1085294aa0
|
||
|
|
cb7e4622e8
|
||
|
|
06e2afa7ed
|
||
|
|
3e60c6d77f
|
||
|
|
594517b436
|
||
|
|
1d3b924492
|
||
|
|
b6cd4bb43e
|
||
|
|
5c0745e039
|
||
|
|
c5fd507ab5
|
||
|
|
dfc39e9e19
|
||
|
|
48d7969a84
|
||
|
|
9eb5a44f2d
|
||
|
|
fc2fc6ab77
|
||
|
|
bc7fa914a4
|
||
|
|
c436f24ee0
|
||
|
|
5a192f5a6f
|
||
|
|
a032f0728f
|
||
|
|
548432f3a9
|
||
|
|
3bd1e5384e
|
||
|
|
738da05e59
|
||
|
|
d457b65f44
|
||
|
|
270cf025ff
|
||
|
|
c657892b7b
|
||
|
|
87cdd4ed90
|
||
|
|
5c1c1272db
|
検索条件に一致するファイルはありません
+39
-63
@@ -1,84 +1,60 @@
|
|||||||
# v1.8.0 - Lua スクリプト for YMM4
|
# v1.9.2 - Lua スクリプト for YMM4
|
||||||
|
|
||||||
AviUtl 互換の描画合成・メディア読み込み・値/オプション API を新たに実装し、
|
スクリプトのエラーを、スクリプトエディタ上で視覚的に把握できるようにしたマイナー
|
||||||
従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の両方で対称に動作させた
|
リリースです。コンパイルエラー・実行時エラー・タイムアウトが発生すると、該当箇所に
|
||||||
リリースです。あわせて全 8 言語のドキュメントを実装状況へ同期しました。
|
赤い波線が表示され、ポイントするとローカライズされたエラー内容がツールチップで
|
||||||
|
確認できます。従来のエラー時挙動(当該フレームは元の状態を出力し、内容をログへ出力)は
|
||||||
|
変わらず、波線表示はそれに加わる UI です。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 新機能・機能改善
|
## 新機能・機能改善
|
||||||
|
|
||||||
### 1. 描画合成 obj.draw / obj.drawpoly
|
### 1. エラー箇所への赤い波線表示
|
||||||
|
|
||||||
オブジェクト画像を蓄積バッファへ重ねて合成する描画 API に対応しました。
|
スクリプトの実行でエラーが発生すると、スクリプトエディタの該当箇所へ赤い波線を
|
||||||
残像・パーティクル・敷き詰めなど、複数回の描画を伴う表現が利用できます。
|
表示します。エラーが明示的に伝わるようになり、原因箇所を素早く特定できます。
|
||||||
|
|
||||||
- `obj.draw([ox, oy, oz [, 拡大率 [, 不透明度 [, アスペクト]]]])` で、現在の
|
- 対象は、コンパイルエラー・実行時エラー・実行タイムアウトです。
|
||||||
オブジェクト画像を任意のオフセット・拡大率・不透明度で合成します。複数回
|
- エラーの行・列は実行時のエラーメッセージから解析し、その位置へ波線を描画します。
|
||||||
呼び出すと重ね描画されます。
|
- 位置を特定できないエラー(タイムアウト等)は、スクリプト先頭行に表示します。
|
||||||
- `obj.drawpoly(...)` で 4 頂点へオブジェクト画像をテクスチャ描画します。UV
|
|
||||||
指定による部分描画、UV を省略した不透明度のみ指定(座標 12 個 + 不透明度)に
|
|
||||||
対応します。アフィン変換で写像します。
|
|
||||||
- `obj.setoption("antialias", ...)` の指定が描画時の補間(最近傍/線形)へ
|
|
||||||
反映されます。
|
|
||||||
- いずれかの描画 API を呼び出すと標準描画は抑制され、合成結果が出力されます。
|
|
||||||
|
|
||||||
### 2. メディア読み込み obj.load("text" / "image" / "movie") と obj.setfont
|
### 2. エラー内容のツールチップ表示
|
||||||
|
|
||||||
`obj.load` の対象を図形("figure")のみから、テキスト・画像ファイル・動画
|
波線部分にマウスポインタを合わせると、エラー内容をツールチップで表示します。
|
||||||
ファイルへ拡張しました。
|
|
||||||
|
|
||||||
- `obj.load("text", 文字列)`:`obj.setfont` で指定したフォント・サイズ・
|
- 先頭にエラー種別(構文エラー / 実行時エラー / タイムアウト)を表示し、続けて
|
||||||
スタイル・色で文字列を描画します(DirectWrite)。
|
エラーメッセージ本文を表示します。
|
||||||
- `obj.load("image", パス)`:画像ファイルを読み込みます(WIC)。
|
- エラー種別の表記は全 8 言語(日本語・英語・簡体字中国語・繁体字中国語・韓国語・
|
||||||
- `obj.load("movie", パス [, 時間])`:動画の指定時間のフレームを読み込みます
|
スペイン語・インドネシア語・アラビア語)にローカライズされています。
|
||||||
(Media Foundation)。
|
|
||||||
- 読み込み後は `obj.w` / `obj.h` 等が生成サイズへ更新され、`obj.load` 直後の
|
|
||||||
`getpixel` でも参照できます。
|
|
||||||
|
|
||||||
### 3. バッファ操作 obj.copybuffer
|
### 3. AviUtl 互換セクション使用時の行位置補正
|
||||||
|
|
||||||
バッファ間で画像をコピーする `obj.copybuffer(コピー先, コピー元)` に対応しま
|
`--dialog:` / `--param:` ヘッダを用いた AviUtl 互換スクリプトでは、実行用コードへの
|
||||||
した。`"obj"`(オブジェクト画像)・`"tmp"`(一時バッファ)・`"cache:名前"`
|
変換時に行番号がずれますが、変換時の行マッピングを保持して元スクリプト上の正しい行へ
|
||||||
(フレーム間で保持する名前付きキャッシュ)を識別子の先頭文字で判定します。
|
波線を表示します。
|
||||||
|
|
||||||
### 4. 値・オプション API
|
|
||||||
|
|
||||||
スクリプトから現在値やオプションを扱う API を追加しました。
|
|
||||||
|
|
||||||
- `obj.getvalue(対象)`:`obj.x` や `obj.track0` 等の現在値を取得します。
|
|
||||||
- `obj.setoption(名前, 値)` / `obj.getoption(名前)`:オプションを設定・取得
|
|
||||||
します。未対応の項目も受理してスクリプトを停止させません。
|
|
||||||
- `obj.pixeloption(名前, 値)`:ピクセル操作のオプションを状態として保持します。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## セキュリティ / 安全性
|
## 互換性・後方互換
|
||||||
|
|
||||||
- `obj.load("image" / "movie")` は、ファイルの先頭ヘッダー(マジックバイト)を
|
- エラー発生時の処理結果(当該フレームでは座標・透明度・回転・ピクセルの変更を
|
||||||
検証し、真正なメディアと確認できたファイルのみを読み込みます。対応形式は
|
適用せず、元の状態をそのまま出力し、内容をログへ出力する)は従来どおりです。
|
||||||
画像が PNG / JPEG / GIF / BMP / TIFF / WebP、動画が MP4 / MOV / MKV / WebM /
|
波線表示は加算的に働く UI であり、レンダリング結果には影響しません。
|
||||||
AVI / FLV / ASF です。
|
- スクリプト言語・実行エンジン(MoonSharp / LuaJIT)・入力補完・折り畳み・テーマ
|
||||||
- スクリプトへ生のファイルアクセス(`require` / `io` / `dofile`)は引き続き
|
連動など、エディタの既存挙動は変わりません。
|
||||||
公開せず、サンドボックスを維持したままメディア読み込みを実現しました。
|
- 波線を描画できない環境であっても、エディタの動作や既存挙動には一切影響しません。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 内部実装の最適化(リファクタリング)
|
## 内部実装
|
||||||
|
|
||||||
新機能を両エンジンで対称に提供するため、設計の一貫性を重視した実装を行いました。
|
- 診断情報はスクリプト本文をキーとする診断サービスを介して受け渡し、フレームワークの
|
||||||
|
コードエディタを再利用したまま、AvalonEdit の背景描画(`IBackgroundRenderer`)で
|
||||||
- **描画・メディア生成パイプライン**
|
波線を描画します。専用エディタの新設は行いません。
|
||||||
- 描画合成は専用の蓄積描画ターゲットで処理し、複数回の `obj.draw` を破綻なく
|
- エディタの `TextView` 参照は、折り畳み戦略フックが受け取る `FoldingManager` から
|
||||||
重ね合わせます。
|
型ベースのフィールド探索で解決します。フィールド名の変更に耐性があり、解決できない
|
||||||
- テキスト・画像・動画はスレッド非依存の CPU 生成(DirectWrite / WIC /
|
場合は波線表示を無効化するのみで他の挙動には影響しません。
|
||||||
Media Foundation)で実体化し、既存の図形即時反映パスへ合流させることで、
|
- 診断サービスの購読は弱参照で行い、エディタを閉じた際のメモリリークを防ぎます。
|
||||||
`obj.load` 直後のピクセル参照を両エンジンで成立させました。
|
描画スレッドからの通知は UI スレッドへマーシャリングして再描画します。
|
||||||
- **ネイティブ通信プロトコルの拡張**
|
- エラー種別のローカライズ文字列を 3 件、全 8 言語へ追加しました。
|
||||||
- 高速ランタイムからホストへの描画・読み込みコールバックを拡充し、図形・
|
|
||||||
テキスト・画像・動画の生成と描画合成をネイティブ環境でも同一仕様で動作
|
|
||||||
させました。
|
|
||||||
- **ドキュメントの同期**
|
|
||||||
- 日本語・英語・簡体字中国語・繁体字中国語・韓国語・スペイン語・インドネシア
|
|
||||||
語・アラビア語の全 8 言語について、新 API・対応状況・制限事項を実装に合わせて
|
|
||||||
更新しました。
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
========================================
|
========================================
|
||||||
Luaスクリプト for YMM4 v1.8.0
|
Luaスクリプト for YMM4 v1.9.2
|
||||||
========================================
|
========================================
|
||||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||||
ピクセルを直接制御できるプラグインです。
|
ピクセルを直接制御できるプラグインです。
|
||||||
@@ -26,7 +26,9 @@ obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動
|
|||||||
|
|
||||||
- スクリプトエラー時の挙動: コンパイルエラーまたは実行時エラーが発生した場合、
|
- スクリプトエラー時の挙動: コンパイルエラーまたは実行時エラーが発生した場合、
|
||||||
そのフレームでの座標・透明度・回転・ピクセルの変更は適用されず、入力された
|
そのフレームでの座標・透明度・回転・ピクセルの変更は適用されず、入力された
|
||||||
元の状態がそのまま出力されます。エラー内容はログへ出力されます。
|
元の状態がそのまま出力されます。エラー内容はログへ出力されるほか、スクリプト
|
||||||
|
エディタの該当箇所へ赤い波線が表示され、ポイントするとエラー内容をツールチップ
|
||||||
|
で確認できます。
|
||||||
|
|
||||||
- ファイルアクセスの制限: スクリプトからのファイル読み込みは許可されておらず、
|
- ファイルアクセスの制限: スクリプトからのファイル読み込みは許可されておらず、
|
||||||
io・os等のモジュールも有効化されていません。
|
io・os等のモジュールも有効化されていません。
|
||||||
|
|||||||
@@ -0,0 +1,172 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using LuaScript.Engine;
|
||||||
|
using LuaScript.Engine.Kernel;
|
||||||
|
using MoonSharp.Interpreter;
|
||||||
|
|
||||||
|
namespace LuaScript.Tests
|
||||||
|
{
|
||||||
|
public sealed class KernelCpuEquivalenceTests
|
||||||
|
{
|
||||||
|
private const int Width = 23;
|
||||||
|
private const int Height = 17;
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,b,g,r,a) end end")]
|
||||||
|
[InlineData("for x=0,obj.w-1 do for y=0,obj.h-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255-r,255-g,255-b,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r*r/255,g*g/255,b*b/255,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255*math.pow(r/255,0.45),255*math.pow(g/255,0.45),255*math.pow(b/255,0.45),a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 obj.setpixel(x,y,v>128 and 255 or 0,v>128 and 255 or 0,v>128 and 255 or 0,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,math.min(255,r+50),math.max(0,g-50),math.floor(b/16)*16,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r%64,math.abs(g-128),math.sqrt(b*255),a) end end")]
|
||||||
|
public void CpuKernelMatchesMoonSharp(string script)
|
||||||
|
{
|
||||||
|
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
|
||||||
|
AssertEquivalent(script, fields, new Dictionary<string, double>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CpuKernelMatchesMoonSharpWithUniforms()
|
||||||
|
{
|
||||||
|
const string script =
|
||||||
|
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
|
||||||
|
"obj.setpixel(x,y,r*obj.track0/100,g*math.sin(time)*0.5+g*0.5,b+x/obj.w*obj.track1,a) end end";
|
||||||
|
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height, ["track0"] = 73d, ["track1"] = 40d };
|
||||||
|
var globals = new Dictionary<string, double> { ["time"] = 1.2345d };
|
||||||
|
AssertEquivalent(script, fields, globals);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("--!cpu\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255-r,255-g,255-b,a) end end")]
|
||||||
|
[InlineData("--!gpu\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end")]
|
||||||
|
[InlineData("--!cpu\r\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/obj.w*255,y/obj.h*255,b,a) end end")]
|
||||||
|
public void DirectivePrefixedKernelsMatchMoonSharp(string script)
|
||||||
|
{
|
||||||
|
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
|
||||||
|
AssertEquivalent(script, fields, new Dictionary<string, double>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("--!cpu", "Cpu")]
|
||||||
|
[InlineData("--!gpu", "Gpu")]
|
||||||
|
public void DirectivePrefixedKernelsRouteToAcceleratedLane(string directive, string expected)
|
||||||
|
{
|
||||||
|
string script = directive + "\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end";
|
||||||
|
|
||||||
|
Assert.True(ScriptDirective.TryResolveExplicit(script, out var kind));
|
||||||
|
Assert.Equal(expected, kind.ToString());
|
||||||
|
Assert.NotNull(KernelExtractor.TryExtract(script));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("obj.setpixel(0,0,0,0,0,0)")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) total=total+r obj.setpixel(x,y,r,g,b,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x+1,y) obj.setpixel(x,y,r,g,b,a) end end")]
|
||||||
|
[InlineData("for i=0,10 do end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,obj.rand(0,255),g,b,a) end end")]
|
||||||
|
public void NonKernelScriptsAreRejected(string script)
|
||||||
|
{
|
||||||
|
Assert.Null(KernelExtractor.TryExtract(script));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AssertEquivalent(string script, Dictionary<string, double> fields, Dictionary<string, double> globals)
|
||||||
|
{
|
||||||
|
var program = KernelExtractor.TryExtract(script);
|
||||||
|
Assert.NotNull(program);
|
||||||
|
|
||||||
|
byte[] source = CreateBuffer(20260629);
|
||||||
|
byte[] oracle = (byte[])source.Clone();
|
||||||
|
byte[] candidate = (byte[])source.Clone();
|
||||||
|
|
||||||
|
RunMoonSharp(script, oracle, fields, globals);
|
||||||
|
|
||||||
|
double[] uniforms = new double[KernelUniforms.Count];
|
||||||
|
foreach (var (name, value) in fields)
|
||||||
|
if (KernelUniforms.TryResolveMember("obj", name, out var uniform))
|
||||||
|
uniforms[(int)uniform] = value;
|
||||||
|
foreach (var (name, value) in globals)
|
||||||
|
if (KernelUniforms.TryResolveGlobal(name, out var uniform))
|
||||||
|
uniforms[(int)uniform] = value;
|
||||||
|
|
||||||
|
CpuKernelCompiler.Compile(program!).Execute(candidate, Width, Height, uniforms);
|
||||||
|
|
||||||
|
Assert.Equal(oracle, candidate);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] CreateBuffer(int seed)
|
||||||
|
{
|
||||||
|
var random = new Random(seed);
|
||||||
|
var buffer = new byte[Width * Height * 4];
|
||||||
|
random.NextBytes(buffer);
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RunMoonSharp(string script, byte[] buffer, Dictionary<string, double> fields, Dictionary<string, double> globals)
|
||||||
|
{
|
||||||
|
var engine = new Script(CoreModules.Basic | CoreModules.Math | CoreModules.Bit32);
|
||||||
|
var obj = new Table(engine);
|
||||||
|
foreach (var (name, value) in fields)
|
||||||
|
obj[name] = value;
|
||||||
|
foreach (var (name, value) in globals)
|
||||||
|
engine.Globals[name] = value;
|
||||||
|
|
||||||
|
obj["getpixel"] = DynValue.NewCallback((_, args) =>
|
||||||
|
{
|
||||||
|
int x = (int)(args[0].CastToNumber() ?? 0d);
|
||||||
|
int y = (int)(args[1].CastToNumber() ?? 0d);
|
||||||
|
var (r, g, b, a) = GetPixel(buffer, x, y);
|
||||||
|
return DynValue.NewTuple(
|
||||||
|
DynValue.NewNumber(r), DynValue.NewNumber(g), DynValue.NewNumber(b), DynValue.NewNumber(a));
|
||||||
|
});
|
||||||
|
|
||||||
|
obj["setpixel"] = DynValue.NewCallback((_, args) =>
|
||||||
|
{
|
||||||
|
int x = (int)(args[0].CastToNumber() ?? 0d);
|
||||||
|
int y = (int)(args[1].CastToNumber() ?? 0d);
|
||||||
|
double r = args[2].CastToNumber() ?? 0d;
|
||||||
|
double g = args[3].CastToNumber() ?? 0d;
|
||||||
|
double b = args[4].CastToNumber() ?? 0d;
|
||||||
|
double a = args.Count > 5 ? args[5].CastToNumber() ?? 255d : 255d;
|
||||||
|
SetPixel(buffer, x, y, r, g, b, a);
|
||||||
|
return DynValue.Void;
|
||||||
|
});
|
||||||
|
|
||||||
|
engine.Globals["obj"] = obj;
|
||||||
|
engine.DoString(script);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (double r, double g, double b, double a) GetPixel(byte[] buffer, int x, int y)
|
||||||
|
{
|
||||||
|
if ((uint)x >= Width || (uint)y >= Height)
|
||||||
|
return (0d, 0d, 0d, 0d);
|
||||||
|
|
||||||
|
int p = (y * Width + x) * 4;
|
||||||
|
double alpha = buffer[p + 3];
|
||||||
|
if (alpha <= 0d)
|
||||||
|
return (0d, 0d, 0d, 0d);
|
||||||
|
|
||||||
|
double scale = 255d / alpha;
|
||||||
|
return (
|
||||||
|
Math.Clamp(buffer[p + 2] * scale, 0d, 255d),
|
||||||
|
Math.Clamp(buffer[p + 1] * scale, 0d, 255d),
|
||||||
|
Math.Clamp(buffer[p] * scale, 0d, 255d),
|
||||||
|
alpha);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void SetPixel(byte[] buffer, int x, int y, double r, double g, double b, double a)
|
||||||
|
{
|
||||||
|
if ((uint)x >= Width || (uint)y >= Height)
|
||||||
|
return;
|
||||||
|
|
||||||
|
int p = (y * Width + x) * 4;
|
||||||
|
double k = Math.Clamp(a, 0d, 255d) / 255d;
|
||||||
|
buffer[p] = (byte)Math.Clamp(b * k, 0d, 255d);
|
||||||
|
buffer[p + 1] = (byte)Math.Clamp(g * k, 0d, 255d);
|
||||||
|
buffer[p + 2] = (byte)Math.Clamp(r * k, 0d, 255d);
|
||||||
|
buffer[p + 3] = (byte)Math.Clamp(a, 0d, 255d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
using LuaScript.Engine.Kernel;
|
||||||
|
|
||||||
|
namespace LuaScript.Tests
|
||||||
|
{
|
||||||
|
public sealed class KernelHlslEmitterTests
|
||||||
|
{
|
||||||
|
private const string Grayscale =
|
||||||
|
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
|
||||||
|
"local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end";
|
||||||
|
|
||||||
|
private const string Threshold =
|
||||||
|
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
|
||||||
|
"obj.setpixel(x,y,r>128 and 255 or 0,g,b,a) end end";
|
||||||
|
|
||||||
|
private const string WithTrack =
|
||||||
|
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
|
||||||
|
"obj.setpixel(x,y,r*obj.track0/100,g,b,a) end end";
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void EmitsValidShaderSkeleton()
|
||||||
|
{
|
||||||
|
string hlsl = HlslKernelEmitter.Emit(Extract(Grayscale));
|
||||||
|
|
||||||
|
Assert.Contains("Texture2D InputTexture : register(t0);", hlsl);
|
||||||
|
Assert.Contains("cbuffer constants : register(b0)", hlsl);
|
||||||
|
Assert.Contains("float4 main(float4 pos : SV_POSITION", hlsl);
|
||||||
|
Assert.Contains("InputTexture.Sample(InputSampler, uv.xy)", hlsl);
|
||||||
|
Assert.Contains("return float4(oR, oG, oB, oA);", hlsl);
|
||||||
|
Assert.Contains("inR", hlsl);
|
||||||
|
Assert.Contains("inG", hlsl);
|
||||||
|
Assert.Contains("inB", hlsl);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ThresholdEmitsTernary()
|
||||||
|
{
|
||||||
|
string hlsl = HlslKernelEmitter.Emit(Extract(Threshold));
|
||||||
|
Assert.Contains(" ? (", hlsl);
|
||||||
|
Assert.Contains(" > ", hlsl);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void UniformReferencesUsePackedConstantBuffer()
|
||||||
|
{
|
||||||
|
string hlsl = HlslKernelEmitter.Emit(Extract(WithTrack));
|
||||||
|
int index = (int)KernelUniform.Track0;
|
||||||
|
Assert.Contains($"uniforms[{index / 4}].{"xyzw"[index % 4]}", hlsl);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void EmissionIsDeterministic()
|
||||||
|
{
|
||||||
|
var program = Extract(Grayscale);
|
||||||
|
Assert.Equal(HlslKernelEmitter.Emit(program), HlslKernelEmitter.Emit(program));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static KernelProgram Extract(string script)
|
||||||
|
{
|
||||||
|
var program = KernelExtractor.TryExtract(script);
|
||||||
|
Assert.NotNull(program);
|
||||||
|
return program!;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -39,8 +39,20 @@
|
|||||||
<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\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\ScriptParameterUsage.cs" Link="Linked\ScriptParameterUsage.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" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\KernelUnsupportedException.cs" Link="Linked\Kernel\KernelUnsupportedException.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\LuaToken.cs" Link="Linked\Kernel\LuaToken.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\LuaLexer.cs" Link="Linked\Kernel\LuaLexer.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\LuaAst.cs" Link="Linked\Kernel\LuaAst.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\LuaParser.cs" Link="Linked\Kernel\LuaParser.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\KernelUniform.cs" Link="Linked\Kernel\KernelUniform.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\KernelModel.cs" Link="Linked\Kernel\KernelModel.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\KernelExtractor.cs" Link="Linked\Kernel\KernelExtractor.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\CpuKernel.cs" Link="Linked\Kernel\CpuKernel.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\CpuKernelCompiler.cs" Link="Linked\Kernel\CpuKernelCompiler.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\HlslKernelEmitter.cs" Link="Linked\Kernel\HlslKernelEmitter.cs" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
using LuaScript.Compat;
|
||||||
|
|
||||||
|
namespace LuaScript.Tests
|
||||||
|
{
|
||||||
|
public sealed class ScriptParameterUsageTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("if obj.check0 then obj.alpha = 0 end", 0)]
|
||||||
|
[InlineData("local v = obj.check3 and 255 or 0", 3)]
|
||||||
|
[InlineData("obj . check1 = true", 1)]
|
||||||
|
public void DetectsReferencedCheck(string script, int index)
|
||||||
|
{
|
||||||
|
var usage = ScriptParameterUsage.Detect(script);
|
||||||
|
for (int i = 0; i < 4; i++)
|
||||||
|
Assert.Equal(i == index, usage.Check(i));
|
||||||
|
Assert.False(usage.Color);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DetectsReferencedColor()
|
||||||
|
{
|
||||||
|
var usage = ScriptParameterUsage.Detect("obj.rz = color / 1000");
|
||||||
|
Assert.True(usage.Color);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DetectsMultipleChecks()
|
||||||
|
{
|
||||||
|
var usage = ScriptParameterUsage.Detect("local a = obj.check0\nlocal b = obj.check2");
|
||||||
|
Assert.True(usage.Check0);
|
||||||
|
Assert.False(usage.Check1);
|
||||||
|
Assert.True(usage.Check2);
|
||||||
|
Assert.False(usage.Check3);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("obj.setoption(\"color\", 1)")]
|
||||||
|
[InlineData("-- color and obj.check0 in a comment")]
|
||||||
|
[InlineData("local colorful = 1")]
|
||||||
|
[InlineData("scene.color = 0")]
|
||||||
|
public void IgnoresStringsCommentsAndUnrelatedNames(string script)
|
||||||
|
{
|
||||||
|
var usage = ScriptParameterUsage.Detect(script);
|
||||||
|
Assert.False(usage.Color);
|
||||||
|
for (int i = 0; i < 4; i++)
|
||||||
|
Assert.False(usage.Check(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(null)]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData("local s = \"unterminated")]
|
||||||
|
public void ReturnsNoneForEmptyOrInvalid(string? script)
|
||||||
|
{
|
||||||
|
var usage = ScriptParameterUsage.Detect(script);
|
||||||
|
Assert.False(usage.Color);
|
||||||
|
Assert.False(usage.Check0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DoesNotDetectOutOfRangeCheck()
|
||||||
|
{
|
||||||
|
var usage = ScriptParameterUsage.Detect("local a = obj.check4");
|
||||||
|
for (int i = 0; i < 4; i++)
|
||||||
|
Assert.False(usage.Check(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,10 +13,12 @@ namespace LuaScript.Compat
|
|||||||
Param,
|
Param,
|
||||||
}
|
}
|
||||||
|
|
||||||
public static string Transform(string source)
|
public static string Transform(string source) => TransformWithMap(source).Code;
|
||||||
|
|
||||||
|
public static (string Code, int[] LineMap) TransformWithMap(string source)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(source))
|
if (string.IsNullOrEmpty(source))
|
||||||
return source;
|
return (source, []);
|
||||||
|
|
||||||
var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
|
var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
|
||||||
|
|
||||||
@@ -48,15 +50,24 @@ namespace LuaScript.Compat
|
|||||||
AppendDeclarations(lines[i], prelude);
|
AppendDeclarations(lines[i], prelude);
|
||||||
|
|
||||||
if (!hasSection && prelude.Count == 0)
|
if (!hasSection && prelude.Count == 0)
|
||||||
return source;
|
return (source, []);
|
||||||
|
|
||||||
var builder = new StringBuilder(source.Length + 64);
|
var builder = new StringBuilder(source.Length + 64);
|
||||||
foreach (var declaration in prelude)
|
var lineMap = new int[prelude.Count + (sectionEnd - sectionStart)];
|
||||||
builder.Append(declaration).Append('\n');
|
int row = 0;
|
||||||
for (int i = sectionStart; i < sectionEnd; i++)
|
|
||||||
builder.Append(lines[i]).Append('\n');
|
|
||||||
|
|
||||||
return builder.ToString();
|
foreach (var declaration in prelude)
|
||||||
|
{
|
||||||
|
builder.Append(declaration).Append('\n');
|
||||||
|
lineMap[row++] = -1;
|
||||||
|
}
|
||||||
|
for (int i = sectionStart; i < sectionEnd; i++)
|
||||||
|
{
|
||||||
|
builder.Append(lines[i]).Append('\n');
|
||||||
|
lineMap[row++] = i;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (builder.ToString(), lineMap);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void AppendDeclarations(string line, List<string> prelude)
|
private static void AppendDeclarations(string line, List<string> prelude)
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using LuaScript.Engine.Kernel;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal readonly struct ScriptParameterUsage
|
||||||
|
{
|
||||||
|
public bool Check0 { get; }
|
||||||
|
public bool Check1 { get; }
|
||||||
|
public bool Check2 { get; }
|
||||||
|
public bool Check3 { get; }
|
||||||
|
public bool Color { get; }
|
||||||
|
|
||||||
|
private ScriptParameterUsage(bool check0, bool check1, bool check2, bool check3, bool color)
|
||||||
|
{
|
||||||
|
Check0 = check0;
|
||||||
|
Check1 = check1;
|
||||||
|
Check2 = check2;
|
||||||
|
Check3 = check3;
|
||||||
|
Color = color;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly ScriptParameterUsage None = default;
|
||||||
|
|
||||||
|
public bool Check(int index) => index switch
|
||||||
|
{
|
||||||
|
0 => Check0,
|
||||||
|
1 => Check1,
|
||||||
|
2 => Check2,
|
||||||
|
3 => Check3,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
|
||||||
|
public static ScriptParameterUsage Detect(string? script)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(script))
|
||||||
|
return None;
|
||||||
|
|
||||||
|
List<LuaToken> tokens;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
tokens = LuaLexer.Tokenize(script);
|
||||||
|
}
|
||||||
|
catch (KernelUnsupportedException)
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
var checks = new bool[4];
|
||||||
|
bool color = false;
|
||||||
|
|
||||||
|
for (int i = 0; i < tokens.Count; i++)
|
||||||
|
{
|
||||||
|
var token = tokens[i];
|
||||||
|
if (token.Kind != LuaTokenKind.Name)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if (token.Text == "color")
|
||||||
|
{
|
||||||
|
if (i == 0 || !tokens[i - 1].IsSymbol("."))
|
||||||
|
color = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (token.Text == "obj" &&
|
||||||
|
i + 2 < tokens.Count &&
|
||||||
|
tokens[i + 1].IsSymbol(".") &&
|
||||||
|
tokens[i + 2].Kind == LuaTokenKind.Name)
|
||||||
|
{
|
||||||
|
string member = tokens[i + 2].Text;
|
||||||
|
if (member.Length == 6 && member.StartsWith("check", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
char digit = member[5];
|
||||||
|
if (digit is >= '0' and <= '3')
|
||||||
|
checks[digit - '0'] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ScriptParameterUsage(checks[0], checks[1], checks[2], checks[3], color);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
using System;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace LuaScript.Diagnostics
|
||||||
|
{
|
||||||
|
internal enum LuaScriptDiagnosticKind
|
||||||
|
{
|
||||||
|
Compile,
|
||||||
|
Runtime,
|
||||||
|
Timeout,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal readonly record struct LuaScriptDiagnostic(
|
||||||
|
LuaScriptDiagnosticKind Kind,
|
||||||
|
int Line,
|
||||||
|
int Column,
|
||||||
|
int Length,
|
||||||
|
string Message);
|
||||||
|
|
||||||
|
internal static partial class LuaScriptDiagnosticParser
|
||||||
|
{
|
||||||
|
[GeneratedRegex(@"^LuaScript:\((\d+),(\d+)(?:-(\d+)(?:,(\d+))?)?\):\s*", RegexOptions.None)]
|
||||||
|
private static partial Regex LocationPattern();
|
||||||
|
|
||||||
|
public static LuaScriptDiagnostic Parse(LuaScriptDiagnosticKind kind, string? message)
|
||||||
|
{
|
||||||
|
var text = message ?? string.Empty;
|
||||||
|
var match = LocationPattern().Match(text);
|
||||||
|
if (!match.Success)
|
||||||
|
return new LuaScriptDiagnostic(kind, 0, 0, 0, text.Trim());
|
||||||
|
|
||||||
|
int line = int.Parse(match.Groups[1].Value);
|
||||||
|
int columnStart = int.Parse(match.Groups[2].Value);
|
||||||
|
|
||||||
|
int length = 0;
|
||||||
|
if (match.Groups[3].Success && !match.Groups[4].Success)
|
||||||
|
length = Math.Max(0, int.Parse(match.Groups[3].Value) - columnStart);
|
||||||
|
|
||||||
|
return new LuaScriptDiagnostic(kind, line, columnStart + 1, length, text[match.Length..].Trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Controls;
|
||||||
|
using System.Windows.Controls.Primitives;
|
||||||
|
using System.Windows.Input;
|
||||||
|
using System.Windows.Media;
|
||||||
|
using ICSharpCode.AvalonEdit.Document;
|
||||||
|
using ICSharpCode.AvalonEdit.Folding;
|
||||||
|
using ICSharpCode.AvalonEdit.Rendering;
|
||||||
|
|
||||||
|
namespace LuaScript.Diagnostics
|
||||||
|
{
|
||||||
|
internal sealed class LuaScriptDiagnosticOverlay : IBackgroundRenderer, ILuaScriptDiagnosticsListener
|
||||||
|
{
|
||||||
|
private static readonly FieldInfo? s_textViewsField = ResolveTextViewsField();
|
||||||
|
|
||||||
|
private static readonly Pen s_squigglePen = CreateSquigglePen();
|
||||||
|
|
||||||
|
private sealed class Marker : ISegment
|
||||||
|
{
|
||||||
|
public required int Offset { get; init; }
|
||||||
|
public required int Length { get; init; }
|
||||||
|
public int EndOffset => Offset + Length;
|
||||||
|
public required LuaScriptDiagnostic Diagnostic { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly TextView _textView;
|
||||||
|
private readonly ToolTip _toolTip = new() { Placement = PlacementMode.Mouse };
|
||||||
|
private readonly List<Marker> _markers = [];
|
||||||
|
private object? _renderedText;
|
||||||
|
private bool _isDirty = true;
|
||||||
|
|
||||||
|
public static void Attach(FoldingManager manager)
|
||||||
|
{
|
||||||
|
var textView = ResolveTextView(manager);
|
||||||
|
if (textView is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
foreach (var renderer in textView.BackgroundRenderers)
|
||||||
|
{
|
||||||
|
if (renderer is LuaScriptDiagnosticOverlay)
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = new LuaScriptDiagnosticOverlay(textView);
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaScriptDiagnosticOverlay(TextView textView)
|
||||||
|
{
|
||||||
|
_textView = textView;
|
||||||
|
textView.BackgroundRenderers.Add(this);
|
||||||
|
textView.MouseHover += OnMouseHover;
|
||||||
|
textView.MouseHoverStopped += OnMouseHoverStopped;
|
||||||
|
LuaScriptDiagnostics.Instance.Subscribe(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public KnownLayer Layer => KnownLayer.Selection;
|
||||||
|
|
||||||
|
public void OnDiagnosticsChanged()
|
||||||
|
{
|
||||||
|
_textView.Dispatcher.BeginInvoke(() =>
|
||||||
|
{
|
||||||
|
_isDirty = true;
|
||||||
|
_textView.InvalidateLayer(KnownLayer.Selection);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Draw(TextView textView, DrawingContext drawingContext)
|
||||||
|
{
|
||||||
|
var document = textView.Document;
|
||||||
|
if (document is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
if (_isDirty || !ReferenceEquals(document.Text, _renderedText))
|
||||||
|
Rebuild(document);
|
||||||
|
|
||||||
|
if (_markers.Count == 0 || !textView.VisualLinesValid)
|
||||||
|
return;
|
||||||
|
|
||||||
|
foreach (var marker in _markers)
|
||||||
|
{
|
||||||
|
foreach (var rect in BackgroundGeometryBuilder.GetRectsForSegment(textView, marker, false))
|
||||||
|
DrawSquiggle(drawingContext, rect);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Rebuild(TextDocument document)
|
||||||
|
{
|
||||||
|
_isDirty = false;
|
||||||
|
_renderedText = document.Text;
|
||||||
|
_markers.Clear();
|
||||||
|
|
||||||
|
foreach (var diagnostic in LuaScriptDiagnostics.Instance.Get(document.Text))
|
||||||
|
{
|
||||||
|
if (TryCreateMarker(document, diagnostic, out var marker))
|
||||||
|
_markers.Add(marker);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryCreateMarker(TextDocument document, LuaScriptDiagnostic diagnostic, out Marker marker)
|
||||||
|
{
|
||||||
|
marker = null!;
|
||||||
|
|
||||||
|
int lineNumber = diagnostic.Line > 0 ? diagnostic.Line : 1;
|
||||||
|
if (lineNumber > document.LineCount)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
var line = document.GetLineByNumber(lineNumber);
|
||||||
|
|
||||||
|
int offset;
|
||||||
|
int length;
|
||||||
|
if (diagnostic.Line > 0 && diagnostic.Column > 0 && diagnostic.Length > 0)
|
||||||
|
{
|
||||||
|
offset = Math.Min(line.Offset + diagnostic.Column - 1, line.EndOffset);
|
||||||
|
length = Math.Min(diagnostic.Length, line.EndOffset - offset);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
offset = SkipLeadingWhitespace(document, line);
|
||||||
|
length = line.EndOffset - offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (length <= 0)
|
||||||
|
{
|
||||||
|
if (line.Length == 0)
|
||||||
|
return false;
|
||||||
|
offset = line.Offset;
|
||||||
|
length = line.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
marker = new Marker { Offset = offset, Length = length, Diagnostic = diagnostic };
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipLeadingWhitespace(TextDocument document, DocumentLine line)
|
||||||
|
{
|
||||||
|
int offset = line.Offset;
|
||||||
|
while (offset < line.EndOffset)
|
||||||
|
{
|
||||||
|
char c = document.GetCharAt(offset);
|
||||||
|
if (c != ' ' && c != '\t')
|
||||||
|
break;
|
||||||
|
offset++;
|
||||||
|
}
|
||||||
|
return offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnMouseHover(object? sender, MouseEventArgs e)
|
||||||
|
{
|
||||||
|
var document = _textView.Document;
|
||||||
|
if (document is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var position = _textView.GetPositionFloor(e.GetPosition(_textView) + _textView.ScrollOffset);
|
||||||
|
if (position is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
int offset = document.GetOffset(position.Value.Location);
|
||||||
|
foreach (var marker in _markers)
|
||||||
|
{
|
||||||
|
if (offset < marker.Offset || offset > marker.EndOffset)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
_toolTip.Content = BuildToolTipContent(marker.Diagnostic);
|
||||||
|
_toolTip.IsOpen = true;
|
||||||
|
e.Handled = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnMouseHoverStopped(object? sender, MouseEventArgs e)
|
||||||
|
{
|
||||||
|
_toolTip.IsOpen = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static object BuildToolTipContent(LuaScriptDiagnostic diagnostic)
|
||||||
|
{
|
||||||
|
var panel = new StackPanel { MaxWidth = 480 };
|
||||||
|
panel.Children.Add(new TextBlock { Text = KindLabel(diagnostic.Kind), FontWeight = FontWeights.Bold });
|
||||||
|
if (!string.IsNullOrEmpty(diagnostic.Message))
|
||||||
|
panel.Children.Add(new TextBlock { Text = diagnostic.Message, TextWrapping = TextWrapping.Wrap });
|
||||||
|
return panel;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string KindLabel(LuaScriptDiagnosticKind kind) => kind switch
|
||||||
|
{
|
||||||
|
LuaScriptDiagnosticKind.Compile => Texts.DiagnosticCompile,
|
||||||
|
LuaScriptDiagnosticKind.Timeout => Texts.DiagnosticTimeout,
|
||||||
|
_ => Texts.DiagnosticRuntime,
|
||||||
|
};
|
||||||
|
|
||||||
|
private static void DrawSquiggle(DrawingContext drawingContext, Rect rect)
|
||||||
|
{
|
||||||
|
if (rect.Width <= 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
const double step = 3.0;
|
||||||
|
double baseline = rect.Bottom - 0.5;
|
||||||
|
|
||||||
|
var geometry = new StreamGeometry();
|
||||||
|
using (var context = geometry.Open())
|
||||||
|
{
|
||||||
|
context.BeginFigure(new Point(rect.Left, baseline), false, false);
|
||||||
|
|
||||||
|
var points = new List<Point>();
|
||||||
|
int index = 0;
|
||||||
|
for (double x = rect.Left; x <= rect.Right; x += step)
|
||||||
|
{
|
||||||
|
points.Add(new Point(x, baseline - (index % 2 == 0 ? 0.0 : step)));
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
context.PolyLineTo(points, true, false);
|
||||||
|
}
|
||||||
|
geometry.Freeze();
|
||||||
|
|
||||||
|
drawingContext.DrawGeometry(null, s_squigglePen, geometry);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Pen CreateSquigglePen()
|
||||||
|
{
|
||||||
|
var pen = new Pen(new SolidColorBrush(Color.FromRgb(0xE5, 0x1A, 0x1A)), 1.0);
|
||||||
|
pen.Brush.Freeze();
|
||||||
|
pen.Freeze();
|
||||||
|
return pen;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static FieldInfo? ResolveTextViewsField()
|
||||||
|
{
|
||||||
|
foreach (var field in typeof(FoldingManager).GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
|
||||||
|
{
|
||||||
|
if (typeof(IEnumerable<TextView>).IsAssignableFrom(field.FieldType))
|
||||||
|
return field;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static TextView? ResolveTextView(FoldingManager? manager)
|
||||||
|
{
|
||||||
|
if (manager is null || s_textViewsField is null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (s_textViewsField.GetValue(manager) is IEnumerable<TextView> views)
|
||||||
|
{
|
||||||
|
foreach (var view in views)
|
||||||
|
{
|
||||||
|
if (view is not null)
|
||||||
|
return view;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Diagnostics
|
||||||
|
{
|
||||||
|
internal interface ILuaScriptDiagnosticsListener
|
||||||
|
{
|
||||||
|
void OnDiagnosticsChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class LuaScriptDiagnostics
|
||||||
|
{
|
||||||
|
public static LuaScriptDiagnostics Instance { get; } = new();
|
||||||
|
|
||||||
|
private const int MaxTrackedScripts = 64;
|
||||||
|
|
||||||
|
private readonly object _gate = new();
|
||||||
|
private readonly Dictionary<string, IReadOnlyList<LuaScriptDiagnostic>> _entries = new(StringComparer.Ordinal);
|
||||||
|
private readonly Queue<string> _insertionOrder = new();
|
||||||
|
private readonly List<WeakReference<ILuaScriptDiagnosticsListener>> _listeners = [];
|
||||||
|
|
||||||
|
private LuaScriptDiagnostics()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Subscribe(ILuaScriptDiagnosticsListener listener)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
PruneDeadListeners();
|
||||||
|
_listeners.Add(new WeakReference<ILuaScriptDiagnosticsListener>(listener));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public IReadOnlyList<LuaScriptDiagnostic> Get(string? script)
|
||||||
|
{
|
||||||
|
if (script is null)
|
||||||
|
return [];
|
||||||
|
|
||||||
|
lock (_gate)
|
||||||
|
return _entries.TryGetValue(script, out var diagnostics) ? diagnostics : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Report(string? script, IReadOnlyList<LuaScriptDiagnostic> diagnostics)
|
||||||
|
{
|
||||||
|
if (script is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
diagnostics ??= [];
|
||||||
|
|
||||||
|
ILuaScriptDiagnosticsListener[] targets;
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (_entries.TryGetValue(script, out var existing) && AreEqual(existing, diagnostics))
|
||||||
|
return;
|
||||||
|
|
||||||
|
if (!_entries.ContainsKey(script))
|
||||||
|
_insertionOrder.Enqueue(script);
|
||||||
|
|
||||||
|
_entries[script] = diagnostics;
|
||||||
|
|
||||||
|
while (_entries.Count > MaxTrackedScripts && _insertionOrder.Count > 0)
|
||||||
|
{
|
||||||
|
var oldest = _insertionOrder.Dequeue();
|
||||||
|
if (!string.Equals(oldest, script, StringComparison.Ordinal))
|
||||||
|
_entries.Remove(oldest);
|
||||||
|
}
|
||||||
|
|
||||||
|
targets = CollectLiveListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var target in targets)
|
||||||
|
target.OnDiagnosticsChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ILuaScriptDiagnosticsListener[] CollectLiveListeners()
|
||||||
|
{
|
||||||
|
var live = new List<ILuaScriptDiagnosticsListener>(_listeners.Count);
|
||||||
|
for (int i = _listeners.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
if (_listeners[i].TryGetTarget(out var listener))
|
||||||
|
live.Add(listener);
|
||||||
|
else
|
||||||
|
_listeners.RemoveAt(i);
|
||||||
|
}
|
||||||
|
return [.. live];
|
||||||
|
}
|
||||||
|
|
||||||
|
private void PruneDeadListeners()
|
||||||
|
{
|
||||||
|
for (int i = _listeners.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
if (!_listeners[i].TryGetTarget(out _))
|
||||||
|
_listeners.RemoveAt(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool AreEqual(IReadOnlyList<LuaScriptDiagnostic> a, IReadOnlyList<LuaScriptDiagnostic> b)
|
||||||
|
{
|
||||||
|
if (a.Count != b.Count)
|
||||||
|
return false;
|
||||||
|
for (int i = 0; i < a.Count; i++)
|
||||||
|
{
|
||||||
|
if (!a[i].Equals(b[i]))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed class CpuKernel(CpuKernel.RowDelegate row)
|
||||||
|
{
|
||||||
|
public delegate void RowDelegate(byte[] buffer, int width, int rowBase, double y, double[] uniforms);
|
||||||
|
|
||||||
|
private const int ParallelThreshold = 64;
|
||||||
|
|
||||||
|
private readonly RowDelegate _row = row;
|
||||||
|
|
||||||
|
public void Execute(byte[] buffer, int width, int height, double[] uniforms)
|
||||||
|
{
|
||||||
|
var row = _row;
|
||||||
|
int stride = width * 4;
|
||||||
|
|
||||||
|
if (height < ParallelThreshold)
|
||||||
|
{
|
||||||
|
for (int y = 0; y < height; y++)
|
||||||
|
row(buffer, width, y * stride, y, uniforms);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Parallel.For(0, height, y => row(buffer, width, y * stride, y, uniforms));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq.Expressions;
|
||||||
|
using System.Reflection;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal static class CpuKernelCompiler
|
||||||
|
{
|
||||||
|
private static readonly MethodInfo Clamp = typeof(Math).GetMethod(nameof(Math.Clamp), [typeof(double), typeof(double), typeof(double)])!;
|
||||||
|
private static readonly MethodInfo Floor = Unary(nameof(Math.Floor));
|
||||||
|
private static readonly MethodInfo Pow = Binary(nameof(Math.Pow));
|
||||||
|
|
||||||
|
private static readonly Dictionary<KFunc, MethodInfo> Functions = new()
|
||||||
|
{
|
||||||
|
[KFunc.Abs] = Unary(nameof(Math.Abs)),
|
||||||
|
[KFunc.Floor] = Floor,
|
||||||
|
[KFunc.Ceil] = Unary(nameof(Math.Ceiling)),
|
||||||
|
[KFunc.Sqrt] = Unary(nameof(Math.Sqrt)),
|
||||||
|
[KFunc.Sin] = Unary(nameof(Math.Sin)),
|
||||||
|
[KFunc.Cos] = Unary(nameof(Math.Cos)),
|
||||||
|
[KFunc.Tan] = Unary(nameof(Math.Tan)),
|
||||||
|
[KFunc.Asin] = Unary(nameof(Math.Asin)),
|
||||||
|
[KFunc.Acos] = Unary(nameof(Math.Acos)),
|
||||||
|
[KFunc.Atan] = Unary(nameof(Math.Atan)),
|
||||||
|
[KFunc.Atan2] = Binary(nameof(Math.Atan2)),
|
||||||
|
[KFunc.Exp] = Unary(nameof(Math.Exp)),
|
||||||
|
[KFunc.Log] = Unary(nameof(Math.Log)),
|
||||||
|
[KFunc.Pow] = Pow,
|
||||||
|
[KFunc.Min] = Binary(nameof(Math.Min)),
|
||||||
|
[KFunc.Max] = Binary(nameof(Math.Max)),
|
||||||
|
};
|
||||||
|
|
||||||
|
public static CpuKernel Compile(KernelProgram program)
|
||||||
|
{
|
||||||
|
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
|
||||||
|
var width = Expression.Parameter(typeof(int), "width");
|
||||||
|
var rowBase = Expression.Parameter(typeof(int), "rowBase");
|
||||||
|
var y = Expression.Parameter(typeof(double), "y");
|
||||||
|
var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
|
||||||
|
|
||||||
|
var x = Expression.Variable(typeof(int), "x");
|
||||||
|
var index = Expression.Variable(typeof(int), "index");
|
||||||
|
var alphaRaw = Expression.Variable(typeof(double), "alphaRaw");
|
||||||
|
var transparent = Expression.Variable(typeof(bool), "transparent");
|
||||||
|
var scale = Expression.Variable(typeof(double), "scale");
|
||||||
|
var inputs = new[]
|
||||||
|
{
|
||||||
|
Expression.Variable(typeof(double), "inR"),
|
||||||
|
Expression.Variable(typeof(double), "inG"),
|
||||||
|
Expression.Variable(typeof(double), "inB"),
|
||||||
|
Expression.Variable(typeof(double), "inA"),
|
||||||
|
};
|
||||||
|
var slots = new ParameterExpression[program.Bindings.Count];
|
||||||
|
for (int i = 0; i < slots.Length; i++)
|
||||||
|
slots[i] = Expression.Variable(typeof(double), "slot" + i);
|
||||||
|
|
||||||
|
var context = new Context(x, y, uniforms, inputs, slots);
|
||||||
|
|
||||||
|
var statements = new List<Expression>
|
||||||
|
{
|
||||||
|
Expression.Assign(index, Expression.Add(rowBase, Expression.Multiply(x, Constant(4)))),
|
||||||
|
Expression.Assign(alphaRaw, ToDouble(ReadByte(buffer, index, 3))),
|
||||||
|
Expression.Assign(transparent, Expression.LessThanOrEqual(alphaRaw, Constant(0d))),
|
||||||
|
Expression.Assign(scale, Select(transparent, Constant(0d), Expression.Divide(Constant(255d), alphaRaw))),
|
||||||
|
Expression.Assign(inputs[3], Select(transparent, Constant(0d), alphaRaw)),
|
||||||
|
Expression.Assign(inputs[0], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 2)), scale)))),
|
||||||
|
Expression.Assign(inputs[1], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 1)), scale)))),
|
||||||
|
Expression.Assign(inputs[2], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 0)), scale)))),
|
||||||
|
};
|
||||||
|
|
||||||
|
for (int i = 0; i < slots.Length; i++)
|
||||||
|
statements.Add(Expression.Assign(slots[i], Build(program.Bindings[i], context)));
|
||||||
|
|
||||||
|
var outA = Expression.Variable(typeof(double), "outA");
|
||||||
|
var alphaScale = Expression.Variable(typeof(double), "alphaScale");
|
||||||
|
statements.Add(Expression.Assign(outA, Build(program.OutputA, context)));
|
||||||
|
statements.Add(Expression.Assign(alphaScale, Expression.Divide(ClampByte(outA), Constant(255d))));
|
||||||
|
statements.Add(WriteByte(buffer, index, 0, ClampByte(Expression.Multiply(Build(program.OutputB, context), alphaScale))));
|
||||||
|
statements.Add(WriteByte(buffer, index, 1, ClampByte(Expression.Multiply(Build(program.OutputG, context), alphaScale))));
|
||||||
|
statements.Add(WriteByte(buffer, index, 2, ClampByte(Expression.Multiply(Build(program.OutputR, context), alphaScale))));
|
||||||
|
statements.Add(WriteByte(buffer, index, 3, ClampByte(outA)));
|
||||||
|
statements.Add(Expression.PostIncrementAssign(x));
|
||||||
|
|
||||||
|
var breakLabel = Expression.Label("break");
|
||||||
|
var loop = Expression.Loop(
|
||||||
|
Expression.IfThenElse(
|
||||||
|
Expression.LessThan(x, width),
|
||||||
|
Expression.Block(statements),
|
||||||
|
Expression.Break(breakLabel)),
|
||||||
|
breakLabel);
|
||||||
|
|
||||||
|
var locals = new List<ParameterExpression> { x, index, alphaRaw, transparent, scale, outA, alphaScale };
|
||||||
|
locals.AddRange(inputs);
|
||||||
|
locals.AddRange(slots);
|
||||||
|
|
||||||
|
var body = Expression.Block(locals, Expression.Assign(x, Constant(0)), loop);
|
||||||
|
|
||||||
|
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, width, rowBase, y, uniforms);
|
||||||
|
return new CpuKernel(lambda.Compile());
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record Context(
|
||||||
|
ParameterExpression X,
|
||||||
|
ParameterExpression Y,
|
||||||
|
ParameterExpression Uniforms,
|
||||||
|
ParameterExpression[] Inputs,
|
||||||
|
ParameterExpression[] Slots);
|
||||||
|
|
||||||
|
private static Expression Build(KExpr expression, Context context)
|
||||||
|
{
|
||||||
|
switch (expression)
|
||||||
|
{
|
||||||
|
case KConst value:
|
||||||
|
return Constant(value.Value);
|
||||||
|
case KInput input:
|
||||||
|
return context.Inputs[(int)input.Channel];
|
||||||
|
case KCoord coord:
|
||||||
|
return coord.Axis == KAxis.X ? ToDouble(context.X) : context.Y;
|
||||||
|
case KUniformRef uniform:
|
||||||
|
return Expression.ArrayIndex(context.Uniforms, Constant((int)uniform.Uniform));
|
||||||
|
case KLocalRef local:
|
||||||
|
return context.Slots[local.Slot];
|
||||||
|
case KNegate negate:
|
||||||
|
return Expression.Negate(Build(negate.Operand, context));
|
||||||
|
case KArith arithmetic:
|
||||||
|
return BuildArithmetic(arithmetic, context);
|
||||||
|
case KCall call:
|
||||||
|
return BuildCall(call, context);
|
||||||
|
case KSelect select:
|
||||||
|
return Select(BuildBool(select.Condition, context), Build(select.WhenTrue, context), Build(select.WhenFalse, context));
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported CPU expression.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression BuildArithmetic(KArith arithmetic, Context context)
|
||||||
|
{
|
||||||
|
var left = Build(arithmetic.Left, context);
|
||||||
|
var right = Build(arithmetic.Right, context);
|
||||||
|
return arithmetic.Op switch
|
||||||
|
{
|
||||||
|
KArithOp.Add => Expression.Add(left, right),
|
||||||
|
KArithOp.Subtract => Expression.Subtract(left, right),
|
||||||
|
KArithOp.Multiply => Expression.Multiply(left, right),
|
||||||
|
KArithOp.Divide => Expression.Divide(left, right),
|
||||||
|
KArithOp.Modulo => FlooredModulo(left, right),
|
||||||
|
KArithOp.Power => Expression.Call(Pow, left, right),
|
||||||
|
_ => throw new KernelUnsupportedException("Unsupported arithmetic operator."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression BuildCall(KCall call, Context context)
|
||||||
|
{
|
||||||
|
var method = Functions[call.Func];
|
||||||
|
if (call.Arguments.Count == 1)
|
||||||
|
return Expression.Call(method, Build(call.Arguments[0], context));
|
||||||
|
return Expression.Call(method, Build(call.Arguments[0], context), Build(call.Arguments[1], context));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression BuildBool(KBool condition, Context context)
|
||||||
|
{
|
||||||
|
switch (condition)
|
||||||
|
{
|
||||||
|
case KBoolConst value:
|
||||||
|
return Expression.Constant(value.Value);
|
||||||
|
case KNot not:
|
||||||
|
return Expression.Not(BuildBool(not.Operand, context));
|
||||||
|
case KLogical logical:
|
||||||
|
return logical.IsAnd
|
||||||
|
? Expression.AndAlso(BuildBool(logical.Left, context), BuildBool(logical.Right, context))
|
||||||
|
: Expression.OrElse(BuildBool(logical.Left, context), BuildBool(logical.Right, context));
|
||||||
|
case KCompare compare:
|
||||||
|
var left = Build(compare.Left, context);
|
||||||
|
var right = Build(compare.Right, context);
|
||||||
|
return compare.Op switch
|
||||||
|
{
|
||||||
|
KCompareOp.Less => Expression.LessThan(left, right),
|
||||||
|
KCompareOp.Greater => Expression.GreaterThan(left, right),
|
||||||
|
KCompareOp.LessEqual => Expression.LessThanOrEqual(left, right),
|
||||||
|
KCompareOp.GreaterEqual => Expression.GreaterThanOrEqual(left, right),
|
||||||
|
KCompareOp.Equal => Expression.Equal(left, right),
|
||||||
|
KCompareOp.NotEqual => Expression.NotEqual(left, right),
|
||||||
|
_ => throw new KernelUnsupportedException("Unsupported comparison."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported CPU condition.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression FlooredModulo(Expression left, Expression right) =>
|
||||||
|
Expression.Subtract(left, Expression.Multiply(Expression.Call(Floor, Expression.Divide(left, right)), right));
|
||||||
|
|
||||||
|
private static Expression Select(Expression condition, Expression whenTrue, Expression whenFalse) =>
|
||||||
|
Expression.Condition(condition, whenTrue, whenFalse);
|
||||||
|
|
||||||
|
private static Expression ClampByte(Expression value) =>
|
||||||
|
Expression.Call(Clamp, value, Constant(0d), Constant(255d));
|
||||||
|
|
||||||
|
private static Expression ReadByte(ParameterExpression buffer, ParameterExpression index, int offset) =>
|
||||||
|
Expression.ArrayIndex(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset)));
|
||||||
|
|
||||||
|
private static Expression WriteByte(ParameterExpression buffer, ParameterExpression index, int offset, Expression value) =>
|
||||||
|
Expression.Assign(
|
||||||
|
Expression.ArrayAccess(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset))),
|
||||||
|
Expression.Convert(value, typeof(byte)));
|
||||||
|
|
||||||
|
private static Expression ToDouble(Expression value) => Expression.Convert(value, typeof(double));
|
||||||
|
|
||||||
|
private static ConstantExpression Constant(double value) => Expression.Constant(value, typeof(double));
|
||||||
|
|
||||||
|
private static ConstantExpression Constant(int value) => Expression.Constant(value, typeof(int));
|
||||||
|
|
||||||
|
private static MethodInfo Unary(string name) => typeof(Math).GetMethod(name, [typeof(double)])!;
|
||||||
|
|
||||||
|
private static MethodInfo Binary(string name) => typeof(Math).GetMethod(name, [typeof(double), typeof(double)])!;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
using System;
|
||||||
|
using Vortice.Direct2D1;
|
||||||
|
using YukkuriMovieMaker.Commons;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed class GpuKernel : IDisposable
|
||||||
|
{
|
||||||
|
private readonly GpuKernelEffect _effect;
|
||||||
|
private readonly float[] _packed = new float[HlslKernelEmitter.ConstantFloatCount];
|
||||||
|
private readonly byte[] _bytes = new byte[HlslKernelEmitter.ConstantFloatCount * sizeof(float)];
|
||||||
|
|
||||||
|
public GpuKernel(IGraphicsDevicesAndContext devices, KernelProgram program)
|
||||||
|
=> _effect = new GpuKernelEffect(devices, HlslKernelEmitter.Emit(program));
|
||||||
|
|
||||||
|
public bool IsReady => _effect.IsReady;
|
||||||
|
|
||||||
|
public ID2D1Image Apply(ID2D1Image input, double[] uniforms)
|
||||||
|
{
|
||||||
|
KernelUniformBinding.Pack(uniforms, _packed);
|
||||||
|
Buffer.BlockCopy(_packed, 0, _bytes, 0, _bytes.Length);
|
||||||
|
_effect.SetConstants(_bytes);
|
||||||
|
_effect.SetInput(0, input, true);
|
||||||
|
return _effect.Output;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() => _effect.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading;
|
||||||
|
using Vortice;
|
||||||
|
using Vortice.D3DCompiler;
|
||||||
|
using Vortice.Direct2D1;
|
||||||
|
using Vortice.Direct3D;
|
||||||
|
using Vortice.Mathematics;
|
||||||
|
using YukkuriMovieMaker.Commons;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed class GpuKernelEffect : ID2D1Effect
|
||||||
|
{
|
||||||
|
private const int ConstantsIndex = 0;
|
||||||
|
private const int InitializedIndex = 1;
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
private unsafe struct ConstantBuffer
|
||||||
|
{
|
||||||
|
public fixed float Values[HlslKernelEmitter.ConstantFloatCount];
|
||||||
|
}
|
||||||
|
|
||||||
|
[CustomEffect(1, null, null, null, null)]
|
||||||
|
private sealed class Impl(Guid guid, string hlsl) : CustomEffectBase, ID2D1DrawTransform
|
||||||
|
{
|
||||||
|
private ConstantBuffer _constants;
|
||||||
|
private ID2D1DrawInfo? _drawInfo;
|
||||||
|
|
||||||
|
[CustomEffectProperty(PropertyType.Blob, ConstantsIndex)]
|
||||||
|
public byte[] Constants
|
||||||
|
{
|
||||||
|
get => ToBytes(_constants);
|
||||||
|
set
|
||||||
|
{
|
||||||
|
FromBytes(value, ref _constants);
|
||||||
|
_drawInfo?.SetPixelShaderConstantBuffer(in _constants);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[CustomEffectProperty(PropertyType.Bool, InitializedIndex)]
|
||||||
|
public bool Initialized { get; private set; }
|
||||||
|
|
||||||
|
public override void Initialize(ID2D1EffectContext effectContext, ID2D1TransformGraph transformGraph)
|
||||||
|
{
|
||||||
|
byte[] source = Encoding.ASCII.GetBytes(hlsl);
|
||||||
|
var result = Compiler.Compile(source, "main", string.Empty, "ps_4_1", out var bytecode, out var errors);
|
||||||
|
if (result.Failure || bytecode is null)
|
||||||
|
{
|
||||||
|
Initialized = false;
|
||||||
|
Log.Default.Write("LuaScript: GPU kernel shader compilation failed.\n" + (errors?.AsString() ?? string.Empty));
|
||||||
|
errors?.Dispose();
|
||||||
|
bytecode?.Dispose();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
byte[] shader = bytecode.AsBytes();
|
||||||
|
effectContext.LoadPixelShader(guid, shader, shader.Length);
|
||||||
|
transformGraph.SetSingleTransformNode(this);
|
||||||
|
Initialized = true;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
errors?.Dispose();
|
||||||
|
bytecode.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SetDrawInfo(ID2D1DrawInfo drawInfo)
|
||||||
|
{
|
||||||
|
_drawInfo = drawInfo;
|
||||||
|
drawInfo.SetPixelShader(guid, PixelOptions.None);
|
||||||
|
drawInfo.SetInputDescription(0, new InputDescription { Filter = (Filter)21, LevelOfDetailCount = 1 });
|
||||||
|
drawInfo.SetPixelShaderConstantBuffer(in _constants);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int GetInputCount() => 1;
|
||||||
|
|
||||||
|
public void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects) =>
|
||||||
|
inputRects[0] = outputRect;
|
||||||
|
|
||||||
|
public void MapInputRectsToOutputRect(RawRect[] inputRects, RawRect[] inputOpaqueSubRects, out RawRect outputRect, out RawRect outputOpaqueSubRect)
|
||||||
|
{
|
||||||
|
outputRect = inputRects[0];
|
||||||
|
outputOpaqueSubRect = default;
|
||||||
|
}
|
||||||
|
|
||||||
|
public RawRect MapInvalidRect(int inputIndex, RawRect invalidInputRect) => invalidInputRect;
|
||||||
|
|
||||||
|
private static unsafe byte[] ToBytes(ConstantBuffer constants)
|
||||||
|
{
|
||||||
|
byte[] bytes = new byte[sizeof(ConstantBuffer)];
|
||||||
|
fixed (byte* destination = bytes)
|
||||||
|
*(ConstantBuffer*)destination = constants;
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static unsafe void FromBytes(byte[] bytes, ref ConstantBuffer constants)
|
||||||
|
{
|
||||||
|
int length = Math.Min(bytes.Length, sizeof(ConstantBuffer));
|
||||||
|
fixed (byte* source = bytes)
|
||||||
|
fixed (ConstantBuffer* destination = &constants)
|
||||||
|
Buffer.MemoryCopy(source, destination, sizeof(ConstantBuffer), length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class Manager
|
||||||
|
{
|
||||||
|
private readonly Lock _locker = new();
|
||||||
|
private readonly Dictionary<int, Dictionary<string, (Guid Guid, int Count)>> _registered = [];
|
||||||
|
|
||||||
|
public Guid Acquire(IGraphicsDevicesAndContext devices, string hlsl)
|
||||||
|
{
|
||||||
|
lock (_locker)
|
||||||
|
{
|
||||||
|
int device = devices.GetHashCode();
|
||||||
|
if (!_registered.TryGetValue(device, out var byHlsl))
|
||||||
|
{
|
||||||
|
byHlsl = [];
|
||||||
|
_registered[device] = byHlsl;
|
||||||
|
}
|
||||||
|
if (byHlsl.TryGetValue(hlsl, out var entry))
|
||||||
|
{
|
||||||
|
byHlsl[hlsl] = (entry.Guid, entry.Count + 1);
|
||||||
|
return entry.Guid;
|
||||||
|
}
|
||||||
|
|
||||||
|
var guid = Guid.NewGuid();
|
||||||
|
byHlsl[hlsl] = (guid, 1);
|
||||||
|
((ID2D1Factory1)devices.D2D.Factory).RegisterEffect<Impl>(() => new Impl(guid, hlsl), guid);
|
||||||
|
return guid;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Release(IGraphicsDevicesAndContext devices, string hlsl)
|
||||||
|
{
|
||||||
|
lock (_locker)
|
||||||
|
{
|
||||||
|
int device = devices.GetHashCode();
|
||||||
|
if (!_registered.TryGetValue(device, out var byHlsl) || !byHlsl.TryGetValue(hlsl, out var entry))
|
||||||
|
return;
|
||||||
|
if (entry.Count > 1)
|
||||||
|
{
|
||||||
|
byHlsl[hlsl] = (entry.Guid, entry.Count - 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
byHlsl.Remove(hlsl);
|
||||||
|
((ID2D1Factory1)devices.D2D.Factory).UnregisterEffect(entry.Guid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly Manager Effects = new();
|
||||||
|
|
||||||
|
private readonly IGraphicsDevicesAndContext _devices;
|
||||||
|
private readonly string _hlsl;
|
||||||
|
|
||||||
|
public GpuKernelEffect(IGraphicsDevicesAndContext devices, string hlsl)
|
||||||
|
: base(Create(devices, hlsl))
|
||||||
|
{
|
||||||
|
_devices = devices;
|
||||||
|
_hlsl = hlsl;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsReady => NativePointer != nint.Zero && ((ID2D1Properties)this).GetBoolValue(InitializedIndex);
|
||||||
|
|
||||||
|
public void SetConstants(byte[] bytes) => ((ID2D1Properties)this).SetValue(ConstantsIndex, bytes);
|
||||||
|
|
||||||
|
private static nint Create(IGraphicsDevicesAndContext devices, string hlsl)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var guid = Effects.Acquire(devices, hlsl);
|
||||||
|
return ((ID2D1DeviceContext)devices.DeviceContext).CreateEffect(guid);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log.Default.Write("LuaScript: failed to create GPU kernel effect.", ex);
|
||||||
|
return nint.Zero;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void DisposeCore(nint nativePointer, bool disposing)
|
||||||
|
{
|
||||||
|
base.DisposeCore(nativePointer, disposing);
|
||||||
|
Effects.Release(_devices, _hlsl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal static class HlslKernelEmitter
|
||||||
|
{
|
||||||
|
public const int ConstantVectorCount = 16;
|
||||||
|
|
||||||
|
public const int ConstantFloatCount = ConstantVectorCount * 4;
|
||||||
|
|
||||||
|
private static readonly string[] Intrinsics =
|
||||||
|
[
|
||||||
|
"abs", "floor", "ceil", "sqrt", "sin", "cos", "tan", "asin", "acos",
|
||||||
|
"atan", "atan2", "exp", "log", "pow", "min", "max", "fmod",
|
||||||
|
];
|
||||||
|
|
||||||
|
public static string Emit(KernelProgram program)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder(1024);
|
||||||
|
|
||||||
|
builder.Append("Texture2D InputTexture : register(t0);\n");
|
||||||
|
builder.Append("SamplerState InputSampler : register(s0);\n");
|
||||||
|
builder.Append("cbuffer constants : register(b0)\n{\n");
|
||||||
|
builder.Append(" float4 uniforms[").Append(ConstantVectorCount).Append("];\n");
|
||||||
|
builder.Append("};\n\n");
|
||||||
|
builder.Append("float4 main(float4 pos : SV_POSITION, float4 posScene : SCENE_POSITION, float4 uv : TEXCOORD0) : SV_Target\n{\n");
|
||||||
|
builder.Append(" float4 src = InputTexture.Sample(InputSampler, uv.xy);\n");
|
||||||
|
builder.Append(" float srcA = src.a;\n");
|
||||||
|
builder.Append(" float invA = srcA <= 0.0 ? 0.0 : 1.0 / srcA;\n");
|
||||||
|
builder.Append(" float inR = clamp(src.r * invA * 255.0, 0.0, 255.0);\n");
|
||||||
|
builder.Append(" float inG = clamp(src.g * invA * 255.0, 0.0, 255.0);\n");
|
||||||
|
builder.Append(" float inB = clamp(src.b * invA * 255.0, 0.0, 255.0);\n");
|
||||||
|
builder.Append(" float inA = srcA * 255.0;\n");
|
||||||
|
builder.Append(" float px = uv.x * ").Append(Uniform(KernelUniform.Width)).Append(";\n");
|
||||||
|
builder.Append(" float py = uv.y * ").Append(Uniform(KernelUniform.Height)).Append(";\n");
|
||||||
|
|
||||||
|
for (int i = 0; i < program.Bindings.Count; i++)
|
||||||
|
{
|
||||||
|
builder.Append(" float slot").Append(i).Append(" = ");
|
||||||
|
EmitExpression(builder, program.Bindings[i]);
|
||||||
|
builder.Append(";\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.Append(" float outA = ");
|
||||||
|
EmitExpression(builder, program.OutputA);
|
||||||
|
builder.Append(";\n");
|
||||||
|
builder.Append(" float alphaK = clamp(outA, 0.0, 255.0) / 255.0;\n");
|
||||||
|
|
||||||
|
builder.Append(" float oR = clamp((");
|
||||||
|
EmitExpression(builder, program.OutputR);
|
||||||
|
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
|
||||||
|
builder.Append(" float oG = clamp((");
|
||||||
|
EmitExpression(builder, program.OutputG);
|
||||||
|
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
|
||||||
|
builder.Append(" float oB = clamp((");
|
||||||
|
EmitExpression(builder, program.OutputB);
|
||||||
|
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
|
||||||
|
builder.Append(" float oA = clamp(outA, 0.0, 255.0) / 255.0;\n");
|
||||||
|
builder.Append(" return float4(oR, oG, oB, oA);\n}\n");
|
||||||
|
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EmitExpression(StringBuilder builder, KExpr expression)
|
||||||
|
{
|
||||||
|
switch (expression)
|
||||||
|
{
|
||||||
|
case KConst value:
|
||||||
|
builder.Append(Number(value.Value));
|
||||||
|
return;
|
||||||
|
case KInput input:
|
||||||
|
builder.Append(input.Channel switch
|
||||||
|
{
|
||||||
|
KChannel.R => "inR",
|
||||||
|
KChannel.G => "inG",
|
||||||
|
KChannel.B => "inB",
|
||||||
|
_ => "inA",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
case KCoord coord:
|
||||||
|
builder.Append(coord.Axis == KAxis.X ? "px" : "py");
|
||||||
|
return;
|
||||||
|
case KUniformRef uniform:
|
||||||
|
builder.Append(Uniform(uniform.Uniform));
|
||||||
|
return;
|
||||||
|
case KLocalRef local:
|
||||||
|
builder.Append("slot").Append(local.Slot);
|
||||||
|
return;
|
||||||
|
case KNegate negate:
|
||||||
|
builder.Append("(-(");
|
||||||
|
EmitExpression(builder, negate.Operand);
|
||||||
|
builder.Append("))");
|
||||||
|
return;
|
||||||
|
case KArith arithmetic:
|
||||||
|
EmitArithmetic(builder, arithmetic);
|
||||||
|
return;
|
||||||
|
case KCall call:
|
||||||
|
EmitCall(builder, call);
|
||||||
|
return;
|
||||||
|
case KSelect select:
|
||||||
|
builder.Append('(');
|
||||||
|
EmitCondition(builder, select.Condition);
|
||||||
|
builder.Append(" ? (");
|
||||||
|
EmitExpression(builder, select.WhenTrue);
|
||||||
|
builder.Append(") : (");
|
||||||
|
EmitExpression(builder, select.WhenFalse);
|
||||||
|
builder.Append("))");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported HLSL expression.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EmitArithmetic(StringBuilder builder, KArith arithmetic)
|
||||||
|
{
|
||||||
|
if (arithmetic.Op == KArithOp.Power)
|
||||||
|
{
|
||||||
|
builder.Append("pow(");
|
||||||
|
EmitExpression(builder, arithmetic.Left);
|
||||||
|
builder.Append(", ");
|
||||||
|
EmitExpression(builder, arithmetic.Right);
|
||||||
|
builder.Append(')');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (arithmetic.Op == KArithOp.Modulo)
|
||||||
|
{
|
||||||
|
builder.Append('(');
|
||||||
|
EmitExpression(builder, arithmetic.Left);
|
||||||
|
builder.Append(" - floor((");
|
||||||
|
EmitExpression(builder, arithmetic.Left);
|
||||||
|
builder.Append(") / (");
|
||||||
|
EmitExpression(builder, arithmetic.Right);
|
||||||
|
builder.Append(")) * (");
|
||||||
|
EmitExpression(builder, arithmetic.Right);
|
||||||
|
builder.Append("))");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.Append('(');
|
||||||
|
EmitExpression(builder, arithmetic.Left);
|
||||||
|
builder.Append(arithmetic.Op switch
|
||||||
|
{
|
||||||
|
KArithOp.Add => " + ",
|
||||||
|
KArithOp.Subtract => " - ",
|
||||||
|
KArithOp.Multiply => " * ",
|
||||||
|
KArithOp.Divide => " / ",
|
||||||
|
_ => throw new KernelUnsupportedException("Unsupported arithmetic operator."),
|
||||||
|
});
|
||||||
|
EmitExpression(builder, arithmetic.Right);
|
||||||
|
builder.Append(')');
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EmitCall(StringBuilder builder, KCall call)
|
||||||
|
{
|
||||||
|
builder.Append(Intrinsics[(int)call.Func]).Append('(');
|
||||||
|
for (int i = 0; i < call.Arguments.Count; i++)
|
||||||
|
{
|
||||||
|
if (i > 0)
|
||||||
|
builder.Append(", ");
|
||||||
|
EmitExpression(builder, call.Arguments[i]);
|
||||||
|
}
|
||||||
|
builder.Append(')');
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EmitCondition(StringBuilder builder, KBool condition)
|
||||||
|
{
|
||||||
|
switch (condition)
|
||||||
|
{
|
||||||
|
case KBoolConst value:
|
||||||
|
builder.Append(value.Value ? "true" : "false");
|
||||||
|
return;
|
||||||
|
case KNot not:
|
||||||
|
builder.Append("(!(");
|
||||||
|
EmitCondition(builder, not.Operand);
|
||||||
|
builder.Append("))");
|
||||||
|
return;
|
||||||
|
case KLogical logical:
|
||||||
|
builder.Append('(');
|
||||||
|
EmitCondition(builder, logical.Left);
|
||||||
|
builder.Append(logical.IsAnd ? " && " : " || ");
|
||||||
|
EmitCondition(builder, logical.Right);
|
||||||
|
builder.Append(')');
|
||||||
|
return;
|
||||||
|
case KCompare compare:
|
||||||
|
builder.Append('(');
|
||||||
|
EmitExpression(builder, compare.Left);
|
||||||
|
builder.Append(compare.Op switch
|
||||||
|
{
|
||||||
|
KCompareOp.Less => " < ",
|
||||||
|
KCompareOp.Greater => " > ",
|
||||||
|
KCompareOp.LessEqual => " <= ",
|
||||||
|
KCompareOp.GreaterEqual => " >= ",
|
||||||
|
KCompareOp.Equal => " == ",
|
||||||
|
_ => " != ",
|
||||||
|
});
|
||||||
|
EmitExpression(builder, compare.Right);
|
||||||
|
builder.Append(')');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported HLSL condition.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Uniform(KernelUniform uniform)
|
||||||
|
{
|
||||||
|
int index = (int)uniform;
|
||||||
|
return $"uniforms[{index / 4}].{"xyzw"[index % 4]}";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Number(double value)
|
||||||
|
{
|
||||||
|
if (double.IsPositiveInfinity(value))
|
||||||
|
return "3.4028235e38";
|
||||||
|
if (double.IsNegativeInfinity(value))
|
||||||
|
return "-3.4028235e38";
|
||||||
|
if (double.IsNaN(value))
|
||||||
|
return "(0.0 / 0.0)";
|
||||||
|
|
||||||
|
string text = value.ToString("R", CultureInfo.InvariantCulture);
|
||||||
|
if (!text.Contains('.') && !text.Contains('e') && !text.Contains('E'))
|
||||||
|
text += ".0";
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,357 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed class KernelExtractor
|
||||||
|
{
|
||||||
|
private readonly record struct FuncSpec(KFunc Func, int MinArgs, int MaxArgs);
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, FuncSpec> MathFunctions = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
["abs"] = new(KFunc.Abs, 1, 1),
|
||||||
|
["floor"] = new(KFunc.Floor, 1, 1),
|
||||||
|
["ceil"] = new(KFunc.Ceil, 1, 1),
|
||||||
|
["sqrt"] = new(KFunc.Sqrt, 1, 1),
|
||||||
|
["sin"] = new(KFunc.Sin, 1, 1),
|
||||||
|
["cos"] = new(KFunc.Cos, 1, 1),
|
||||||
|
["tan"] = new(KFunc.Tan, 1, 1),
|
||||||
|
["asin"] = new(KFunc.Asin, 1, 1),
|
||||||
|
["acos"] = new(KFunc.Acos, 1, 1),
|
||||||
|
["atan"] = new(KFunc.Atan, 1, 1),
|
||||||
|
["atan2"] = new(KFunc.Atan2, 2, 2),
|
||||||
|
["exp"] = new(KFunc.Exp, 1, 1),
|
||||||
|
["log"] = new(KFunc.Log, 1, 1),
|
||||||
|
["pow"] = new(KFunc.Pow, 2, 2),
|
||||||
|
["fmod"] = new(KFunc.Fmod, 2, 2),
|
||||||
|
["min"] = new(KFunc.Min, 2, int.MaxValue),
|
||||||
|
["max"] = new(KFunc.Max, 2, int.MaxValue),
|
||||||
|
};
|
||||||
|
|
||||||
|
private readonly List<KExpr> _bindings = [];
|
||||||
|
private readonly Dictionary<string, int> _scope = new(StringComparer.Ordinal);
|
||||||
|
private readonly SortedSet<KernelUniform> _uniforms = [];
|
||||||
|
|
||||||
|
private string _widthVariable = string.Empty;
|
||||||
|
private string _heightVariable = string.Empty;
|
||||||
|
private bool _coordsEnabled;
|
||||||
|
|
||||||
|
public static KernelProgram? TryExtract(string runnableScript)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return new KernelExtractor().Extract(runnableScript);
|
||||||
|
}
|
||||||
|
catch (KernelUnsupportedException)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private KernelProgram? Extract(string runnableScript)
|
||||||
|
{
|
||||||
|
var block = LuaParser.Parse(runnableScript);
|
||||||
|
|
||||||
|
int index = 0;
|
||||||
|
while (index < block.Count && block[index] is LocalStmt prelude)
|
||||||
|
{
|
||||||
|
BindLocal(prelude);
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (index >= block.Count || block[index] is not NumericForStmt outer)
|
||||||
|
return null;
|
||||||
|
if (index + 1 != block.Count)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
if (!TryAxis(outer, out string outerVar, out KAxis outerAxis))
|
||||||
|
return null;
|
||||||
|
if (outer.Body.Count != 1 || outer.Body[0] is not NumericForStmt inner)
|
||||||
|
return null;
|
||||||
|
if (!TryAxis(inner, out string innerVar, out KAxis innerAxis))
|
||||||
|
return null;
|
||||||
|
if (outerAxis == innerAxis)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
_widthVariable = outerAxis == KAxis.X ? outerVar : innerVar;
|
||||||
|
_heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar;
|
||||||
|
|
||||||
|
return BuildKernel(inner.Body);
|
||||||
|
}
|
||||||
|
|
||||||
|
private KernelProgram? BuildKernel(IReadOnlyList<LuaStmt> body)
|
||||||
|
{
|
||||||
|
if (body.Count < 2)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
if (body[0] is not LocalStmt sample || sample.Values.Count != 1 ||
|
||||||
|
!IsGetPixel(sample.Values[0]))
|
||||||
|
return null;
|
||||||
|
if (sample.Names.Count is < 1 or > 4)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
_coordsEnabled = true;
|
||||||
|
for (int i = 0; i < sample.Names.Count; i++)
|
||||||
|
{
|
||||||
|
EnsureNotCoordinateName(sample.Names[i]);
|
||||||
|
_scope[sample.Names[i]] = AddBinding(new KInput((KChannel)i));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 1; i < body.Count - 1; i++)
|
||||||
|
{
|
||||||
|
switch (body[i])
|
||||||
|
{
|
||||||
|
case LocalStmt local:
|
||||||
|
BindLocal(local);
|
||||||
|
break;
|
||||||
|
case AssignStmt assign:
|
||||||
|
BindAssign(assign);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (body[^1] is not CallStmt { Call: var call } || !IsObjectMethod(call, "setpixel"))
|
||||||
|
return null;
|
||||||
|
if (call.Arguments.Count is < 5 or > 6)
|
||||||
|
return null;
|
||||||
|
if (!IsCoordinate(call.Arguments[0], KAxis.X) || !IsCoordinate(call.Arguments[1], KAxis.Y))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var outR = Lower(call.Arguments[2]);
|
||||||
|
var outG = Lower(call.Arguments[3]);
|
||||||
|
var outB = Lower(call.Arguments[4]);
|
||||||
|
var outA = call.Arguments.Count == 6 ? Lower(call.Arguments[5]) : new KConst(255d);
|
||||||
|
|
||||||
|
return new KernelProgram(_bindings, outR, outG, outB, outA, [.. _uniforms]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void BindLocal(LocalStmt local)
|
||||||
|
{
|
||||||
|
if (local.Values.Count == 1 && IsGetPixel(local.Values[0]))
|
||||||
|
throw new KernelUnsupportedException("Unexpected pixel sample.");
|
||||||
|
if (local.Names.Count != local.Values.Count)
|
||||||
|
throw new KernelUnsupportedException("Multiple-value assignment is not supported.");
|
||||||
|
|
||||||
|
var lowered = new KExpr[local.Values.Count];
|
||||||
|
for (int i = 0; i < local.Values.Count; i++)
|
||||||
|
lowered[i] = Lower(local.Values[i]);
|
||||||
|
for (int i = 0; i < local.Names.Count; i++)
|
||||||
|
{
|
||||||
|
EnsureNotCoordinateName(local.Names[i]);
|
||||||
|
_scope[local.Names[i]] = AddBinding(lowered[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void BindAssign(AssignStmt assign)
|
||||||
|
{
|
||||||
|
if (assign.Targets.Count != assign.Values.Count)
|
||||||
|
throw new KernelUnsupportedException("Unbalanced assignment is not supported.");
|
||||||
|
|
||||||
|
foreach (var target in assign.Targets)
|
||||||
|
{
|
||||||
|
if (target is not NameExpr name || !_scope.ContainsKey(name.Name))
|
||||||
|
throw new KernelUnsupportedException("Assignment target must be a local variable.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var lowered = new KExpr[assign.Values.Count];
|
||||||
|
for (int i = 0; i < assign.Values.Count; i++)
|
||||||
|
lowered[i] = Lower(assign.Values[i]);
|
||||||
|
for (int i = 0; i < assign.Targets.Count; i++)
|
||||||
|
_scope[((NameExpr)assign.Targets[i]).Name] = AddBinding(lowered[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EnsureNotCoordinateName(string name)
|
||||||
|
{
|
||||||
|
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
|
||||||
|
string.Equals(name, _heightVariable, StringComparison.Ordinal))
|
||||||
|
throw new KernelUnsupportedException("Local variable shadows a loop coordinate.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private int AddBinding(KExpr expression)
|
||||||
|
{
|
||||||
|
_bindings.Add(expression);
|
||||||
|
return _bindings.Count - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr Lower(LuaExpr expression)
|
||||||
|
{
|
||||||
|
switch (expression)
|
||||||
|
{
|
||||||
|
case NumberExpr number:
|
||||||
|
return new KConst(number.Value);
|
||||||
|
case NameExpr name:
|
||||||
|
return LowerName(name.Name);
|
||||||
|
case MemberExpr member:
|
||||||
|
return LowerMember(member);
|
||||||
|
case CallExpr call:
|
||||||
|
return LowerCall(call);
|
||||||
|
case UnaryExpr { Operator: "-" } unary:
|
||||||
|
return new KNegate(Lower(unary.Operand));
|
||||||
|
case BinaryExpr binary:
|
||||||
|
return LowerBinary(binary);
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported expression in pixel kernel.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr LowerName(string name)
|
||||||
|
{
|
||||||
|
if (_scope.TryGetValue(name, out int slot))
|
||||||
|
return new KLocalRef(slot);
|
||||||
|
if (_coordsEnabled && string.Equals(name, _widthVariable, StringComparison.Ordinal))
|
||||||
|
return new KCoord(KAxis.X);
|
||||||
|
if (_coordsEnabled && string.Equals(name, _heightVariable, StringComparison.Ordinal))
|
||||||
|
return new KCoord(KAxis.Y);
|
||||||
|
if (KernelUniforms.TryResolveGlobal(name, out var uniform))
|
||||||
|
return UseUniform(uniform);
|
||||||
|
throw new KernelUnsupportedException($"Unknown identifier '{name}'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr LowerMember(MemberExpr member)
|
||||||
|
{
|
||||||
|
if (member.Target is NameExpr { Name: "math" })
|
||||||
|
{
|
||||||
|
return member.Name switch
|
||||||
|
{
|
||||||
|
"pi" => new KConst(Math.PI),
|
||||||
|
"huge" => new KConst(double.PositiveInfinity),
|
||||||
|
_ => throw new KernelUnsupportedException($"Unsupported math field '{member.Name}'."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (member.Target is NameExpr target && KernelUniforms.TryResolveMember(target.Name, member.Name, out var uniform))
|
||||||
|
return UseUniform(uniform);
|
||||||
|
|
||||||
|
throw new KernelUnsupportedException("Unsupported member access in pixel kernel.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr LowerCall(CallExpr call)
|
||||||
|
{
|
||||||
|
if (call.Target is not MemberExpr { Target: NameExpr { Name: "math" }, Name: var function } ||
|
||||||
|
!MathFunctions.TryGetValue(function, out var spec))
|
||||||
|
throw new KernelUnsupportedException("Unsupported function call in pixel kernel.");
|
||||||
|
|
||||||
|
int count = call.Arguments.Count;
|
||||||
|
if (count < spec.MinArgs || count > spec.MaxArgs)
|
||||||
|
throw new KernelUnsupportedException($"Wrong argument count for 'math.{function}'.");
|
||||||
|
|
||||||
|
var arguments = new KExpr[count];
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
arguments[i] = Lower(call.Arguments[i]);
|
||||||
|
|
||||||
|
if (spec.Func is KFunc.Min or KFunc.Max)
|
||||||
|
{
|
||||||
|
var folded = arguments[0];
|
||||||
|
for (int i = 1; i < count; i++)
|
||||||
|
folded = new KCall(spec.Func, [folded, arguments[i]]);
|
||||||
|
return folded;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new KCall(spec.Func, arguments);
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr LowerBinary(BinaryExpr binary)
|
||||||
|
{
|
||||||
|
switch (binary.Operator)
|
||||||
|
{
|
||||||
|
case "+": return new KArith(KArithOp.Add, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "-": return new KArith(KArithOp.Subtract, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "*": return new KArith(KArithOp.Multiply, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "/": return new KArith(KArithOp.Divide, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "%": return new KArith(KArithOp.Modulo, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "^": return new KArith(KArithOp.Power, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "or" when binary.Left is BinaryExpr { Operator: "and" } conditional:
|
||||||
|
return new KSelect(LowerBool(conditional.Left), Lower(conditional.Right), Lower(binary.Right));
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException($"Unsupported operator '{binary.Operator}' in value position.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private KBool LowerBool(LuaExpr expression)
|
||||||
|
{
|
||||||
|
switch (expression)
|
||||||
|
{
|
||||||
|
case BoolExpr boolean:
|
||||||
|
return new KBoolConst(boolean.Value);
|
||||||
|
case UnaryExpr { Operator: "not" } unary:
|
||||||
|
return new KNot(LowerBool(unary.Operand));
|
||||||
|
case BinaryExpr { Operator: "and" } conjunction:
|
||||||
|
return new KLogical(true, LowerBool(conjunction.Left), LowerBool(conjunction.Right));
|
||||||
|
case BinaryExpr { Operator: "or" } disjunction:
|
||||||
|
return new KLogical(false, LowerBool(disjunction.Left), LowerBool(disjunction.Right));
|
||||||
|
case BinaryExpr binary when TryCompareOp(binary.Operator, out var op):
|
||||||
|
return new KCompare(op, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case NameExpr name when IsCheck(LowerName(name.Name)):
|
||||||
|
return new KCompare(KCompareOp.NotEqual, LowerName(name.Name), new KConst(0d));
|
||||||
|
case MemberExpr member when IsCheck(LowerMember(member)):
|
||||||
|
return new KCompare(KCompareOp.NotEqual, LowerMember(member), new KConst(0d));
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported condition in pixel kernel.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsCheck(KExpr expression) =>
|
||||||
|
expression is KUniformRef { Uniform: KernelUniform.Check0 or KernelUniform.Check1 or KernelUniform.Check2 or KernelUniform.Check3 };
|
||||||
|
|
||||||
|
private static bool TryCompareOp(string symbol, out KCompareOp op)
|
||||||
|
{
|
||||||
|
switch (symbol)
|
||||||
|
{
|
||||||
|
case "<": op = KCompareOp.Less; return true;
|
||||||
|
case ">": op = KCompareOp.Greater; return true;
|
||||||
|
case "<=": op = KCompareOp.LessEqual; return true;
|
||||||
|
case ">=": op = KCompareOp.GreaterEqual; return true;
|
||||||
|
case "==": op = KCompareOp.Equal; return true;
|
||||||
|
case "~=": op = KCompareOp.NotEqual; return true;
|
||||||
|
default: op = default; return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr UseUniform(KernelUniform uniform)
|
||||||
|
{
|
||||||
|
_uniforms.Add(uniform);
|
||||||
|
return new KUniformRef(uniform);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryAxis(NumericForStmt loop, out string variable, out KAxis axis)
|
||||||
|
{
|
||||||
|
variable = loop.Variable;
|
||||||
|
axis = default;
|
||||||
|
|
||||||
|
if (loop.Start is not NumberExpr { Value: 0d })
|
||||||
|
return false;
|
||||||
|
if (loop.Step is not null && loop.Step is not NumberExpr { Value: 1d })
|
||||||
|
return false;
|
||||||
|
if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound)
|
||||||
|
return false;
|
||||||
|
if (bound.Left is not MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field })
|
||||||
|
return false;
|
||||||
|
if (!KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (uniform == KernelUniform.Width)
|
||||||
|
{
|
||||||
|
axis = KAxis.X;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (uniform == KernelUniform.Height)
|
||||||
|
{
|
||||||
|
axis = KAxis.Y;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsGetPixel(LuaExpr expression) =>
|
||||||
|
expression is CallExpr call && IsObjectMethod(call, "getpixel") &&
|
||||||
|
call.Arguments.Count == 2 &&
|
||||||
|
IsCoordinate(call.Arguments[0], KAxis.X) && IsCoordinate(call.Arguments[1], KAxis.Y);
|
||||||
|
|
||||||
|
private bool IsCoordinate(LuaExpr expression, KAxis axis) =>
|
||||||
|
expression is NameExpr name &&
|
||||||
|
string.Equals(name.Name, axis == KAxis.X ? _widthVariable : _heightVariable, StringComparison.Ordinal);
|
||||||
|
|
||||||
|
private static bool IsObjectMethod(CallExpr call, string method) =>
|
||||||
|
call.Target is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var name } &&
|
||||||
|
string.Equals(name, method, StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal enum KChannel
|
||||||
|
{
|
||||||
|
R,
|
||||||
|
G,
|
||||||
|
B,
|
||||||
|
A,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal enum KAxis
|
||||||
|
{
|
||||||
|
X,
|
||||||
|
Y,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal enum KArithOp
|
||||||
|
{
|
||||||
|
Add,
|
||||||
|
Subtract,
|
||||||
|
Multiply,
|
||||||
|
Divide,
|
||||||
|
Modulo,
|
||||||
|
Power,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal enum KCompareOp
|
||||||
|
{
|
||||||
|
Less,
|
||||||
|
Greater,
|
||||||
|
LessEqual,
|
||||||
|
GreaterEqual,
|
||||||
|
Equal,
|
||||||
|
NotEqual,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal enum KFunc
|
||||||
|
{
|
||||||
|
Abs,
|
||||||
|
Floor,
|
||||||
|
Ceil,
|
||||||
|
Sqrt,
|
||||||
|
Sin,
|
||||||
|
Cos,
|
||||||
|
Tan,
|
||||||
|
Asin,
|
||||||
|
Acos,
|
||||||
|
Atan,
|
||||||
|
Atan2,
|
||||||
|
Exp,
|
||||||
|
Log,
|
||||||
|
Pow,
|
||||||
|
Min,
|
||||||
|
Max,
|
||||||
|
Fmod,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal abstract record KExpr;
|
||||||
|
|
||||||
|
internal sealed record KConst(double Value) : KExpr;
|
||||||
|
|
||||||
|
internal sealed record KInput(KChannel Channel) : KExpr;
|
||||||
|
|
||||||
|
internal sealed record KCoord(KAxis Axis) : KExpr;
|
||||||
|
|
||||||
|
internal sealed record KUniformRef(KernelUniform Uniform) : KExpr;
|
||||||
|
|
||||||
|
internal sealed record KLocalRef(int Slot) : KExpr;
|
||||||
|
|
||||||
|
internal sealed record KArith(KArithOp Op, KExpr Left, KExpr Right) : KExpr;
|
||||||
|
|
||||||
|
internal sealed record KNegate(KExpr Operand) : KExpr;
|
||||||
|
|
||||||
|
internal sealed record KCall(KFunc Func, IReadOnlyList<KExpr> Arguments) : KExpr;
|
||||||
|
|
||||||
|
internal sealed record KSelect(KBool Condition, KExpr WhenTrue, KExpr WhenFalse) : KExpr;
|
||||||
|
|
||||||
|
internal abstract record KBool;
|
||||||
|
|
||||||
|
internal sealed record KCompare(KCompareOp Op, KExpr Left, KExpr Right) : KBool;
|
||||||
|
|
||||||
|
internal sealed record KLogical(bool IsAnd, KBool Left, KBool Right) : KBool;
|
||||||
|
|
||||||
|
internal sealed record KNot(KBool Operand) : KBool;
|
||||||
|
|
||||||
|
internal sealed record KBoolConst(bool Value) : KBool;
|
||||||
|
|
||||||
|
internal sealed record KernelProgram(
|
||||||
|
IReadOnlyList<KExpr> Bindings,
|
||||||
|
KExpr OutputR,
|
||||||
|
KExpr OutputG,
|
||||||
|
KExpr OutputB,
|
||||||
|
KExpr OutputA,
|
||||||
|
IReadOnlyList<KernelUniform> Uniforms);
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal enum KernelUniform
|
||||||
|
{
|
||||||
|
Width,
|
||||||
|
Height,
|
||||||
|
HalfWidth,
|
||||||
|
HalfHeight,
|
||||||
|
CenterX,
|
||||||
|
CenterY,
|
||||||
|
CenterZ,
|
||||||
|
Diagonal,
|
||||||
|
X,
|
||||||
|
Y,
|
||||||
|
Z,
|
||||||
|
Ox,
|
||||||
|
Oy,
|
||||||
|
Oz,
|
||||||
|
Sx,
|
||||||
|
Sy,
|
||||||
|
Sz,
|
||||||
|
Zoom,
|
||||||
|
Aspect,
|
||||||
|
Alpha,
|
||||||
|
Rx,
|
||||||
|
Ry,
|
||||||
|
Rz,
|
||||||
|
Rxr,
|
||||||
|
Ryr,
|
||||||
|
Rzr,
|
||||||
|
Track0,
|
||||||
|
Track1,
|
||||||
|
Track2,
|
||||||
|
Track3,
|
||||||
|
Check0,
|
||||||
|
Check1,
|
||||||
|
Check2,
|
||||||
|
Check3,
|
||||||
|
Color,
|
||||||
|
Time,
|
||||||
|
Frame,
|
||||||
|
TotalFrame,
|
||||||
|
TotalTime,
|
||||||
|
T,
|
||||||
|
Framerate,
|
||||||
|
Layer,
|
||||||
|
Index,
|
||||||
|
Num,
|
||||||
|
SceneWidth,
|
||||||
|
SceneHeight,
|
||||||
|
SceneCenterX,
|
||||||
|
SceneCenterY,
|
||||||
|
TimelineFrame,
|
||||||
|
TimelineTime,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static class KernelUniforms
|
||||||
|
{
|
||||||
|
public static int Count { get; } = Enum.GetValues<KernelUniform>().Length;
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, KernelUniform> Globals = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
["time"] = KernelUniform.Time,
|
||||||
|
["frame"] = KernelUniform.Frame,
|
||||||
|
["totalframe"] = KernelUniform.TotalFrame,
|
||||||
|
["framerate"] = KernelUniform.Framerate,
|
||||||
|
["timelineframe"] = KernelUniform.TimelineFrame,
|
||||||
|
["timelinetime"] = KernelUniform.TimelineTime,
|
||||||
|
["layer"] = KernelUniform.Layer,
|
||||||
|
["color"] = KernelUniform.Color,
|
||||||
|
};
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, KernelUniform> ObjectFields = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
["w"] = KernelUniform.Width,
|
||||||
|
["h"] = KernelUniform.Height,
|
||||||
|
["hw"] = KernelUniform.HalfWidth,
|
||||||
|
["hh"] = KernelUniform.HalfHeight,
|
||||||
|
["cx"] = KernelUniform.CenterX,
|
||||||
|
["cy"] = KernelUniform.CenterY,
|
||||||
|
["cz"] = KernelUniform.CenterZ,
|
||||||
|
["diagonal"] = KernelUniform.Diagonal,
|
||||||
|
["x"] = KernelUniform.X,
|
||||||
|
["y"] = KernelUniform.Y,
|
||||||
|
["z"] = KernelUniform.Z,
|
||||||
|
["ox"] = KernelUniform.Ox,
|
||||||
|
["oy"] = KernelUniform.Oy,
|
||||||
|
["oz"] = KernelUniform.Oz,
|
||||||
|
["sx"] = KernelUniform.Sx,
|
||||||
|
["sy"] = KernelUniform.Sy,
|
||||||
|
["sz"] = KernelUniform.Sz,
|
||||||
|
["zoom"] = KernelUniform.Zoom,
|
||||||
|
["aspect"] = KernelUniform.Aspect,
|
||||||
|
["alpha"] = KernelUniform.Alpha,
|
||||||
|
["rx"] = KernelUniform.Rx,
|
||||||
|
["ry"] = KernelUniform.Ry,
|
||||||
|
["rz"] = KernelUniform.Rz,
|
||||||
|
["rxr"] = KernelUniform.Rxr,
|
||||||
|
["ryr"] = KernelUniform.Ryr,
|
||||||
|
["rzr"] = KernelUniform.Rzr,
|
||||||
|
["track0"] = KernelUniform.Track0,
|
||||||
|
["track1"] = KernelUniform.Track1,
|
||||||
|
["track2"] = KernelUniform.Track2,
|
||||||
|
["track3"] = KernelUniform.Track3,
|
||||||
|
["check0"] = KernelUniform.Check0,
|
||||||
|
["check1"] = KernelUniform.Check1,
|
||||||
|
["check2"] = KernelUniform.Check2,
|
||||||
|
["check3"] = KernelUniform.Check3,
|
||||||
|
["time"] = KernelUniform.Time,
|
||||||
|
["frame"] = KernelUniform.Frame,
|
||||||
|
["totalframe"] = KernelUniform.TotalFrame,
|
||||||
|
["totaltime"] = KernelUniform.TotalTime,
|
||||||
|
["t"] = KernelUniform.T,
|
||||||
|
["framerate"] = KernelUniform.Framerate,
|
||||||
|
["layer"] = KernelUniform.Layer,
|
||||||
|
["index"] = KernelUniform.Index,
|
||||||
|
["num"] = KernelUniform.Num,
|
||||||
|
};
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, KernelUniform> SceneFields = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
["width"] = KernelUniform.SceneWidth,
|
||||||
|
["height"] = KernelUniform.SceneHeight,
|
||||||
|
["cx"] = KernelUniform.SceneCenterX,
|
||||||
|
["cy"] = KernelUniform.SceneCenterY,
|
||||||
|
};
|
||||||
|
|
||||||
|
public static bool TryResolveGlobal(string name, out KernelUniform uniform) =>
|
||||||
|
Globals.TryGetValue(name, out uniform);
|
||||||
|
|
||||||
|
public static bool TryResolveMember(string target, string field, out KernelUniform uniform)
|
||||||
|
{
|
||||||
|
uniform = default;
|
||||||
|
return target switch
|
||||||
|
{
|
||||||
|
"obj" => ObjectFields.TryGetValue(field, out uniform),
|
||||||
|
"scene" => SceneFields.TryGetValue(field, out uniform),
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string Field(KernelUniform uniform) => "u_" + uniform;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal static class KernelUniformBinding
|
||||||
|
{
|
||||||
|
public static double[] Create() => new double[KernelUniforms.Count];
|
||||||
|
|
||||||
|
public static void Fill(AviUtlScriptContext ctx, double[] values)
|
||||||
|
{
|
||||||
|
values[(int)KernelUniform.Width] = ctx.ImageWidth;
|
||||||
|
values[(int)KernelUniform.Height] = ctx.ImageHeight;
|
||||||
|
values[(int)KernelUniform.HalfWidth] = ctx.ImageWidth / 2d;
|
||||||
|
values[(int)KernelUniform.HalfHeight] = ctx.ImageHeight / 2d;
|
||||||
|
values[(int)KernelUniform.CenterX] = ctx.ImageWidth / 2d;
|
||||||
|
values[(int)KernelUniform.CenterY] = ctx.ImageHeight / 2d;
|
||||||
|
values[(int)KernelUniform.CenterZ] = 0d;
|
||||||
|
values[(int)KernelUniform.Diagonal] = Math.Sqrt((double)ctx.ImageWidth * ctx.ImageWidth + (double)ctx.ImageHeight * ctx.ImageHeight);
|
||||||
|
values[(int)KernelUniform.X] = ctx.X;
|
||||||
|
values[(int)KernelUniform.Y] = ctx.Y;
|
||||||
|
values[(int)KernelUniform.Z] = ctx.Z;
|
||||||
|
values[(int)KernelUniform.Ox] = ctx.Ox;
|
||||||
|
values[(int)KernelUniform.Oy] = ctx.Oy;
|
||||||
|
values[(int)KernelUniform.Oz] = ctx.Oz;
|
||||||
|
values[(int)KernelUniform.Sx] = ctx.Sx;
|
||||||
|
values[(int)KernelUniform.Sy] = ctx.Sy;
|
||||||
|
values[(int)KernelUniform.Sz] = 1d;
|
||||||
|
values[(int)KernelUniform.Zoom] = ctx.Zoom;
|
||||||
|
values[(int)KernelUniform.Aspect] = ctx.Aspect;
|
||||||
|
values[(int)KernelUniform.Alpha] = ctx.Alpha;
|
||||||
|
values[(int)KernelUniform.Rx] = ctx.Rx;
|
||||||
|
values[(int)KernelUniform.Ry] = ctx.Ry;
|
||||||
|
values[(int)KernelUniform.Rz] = ctx.Rz;
|
||||||
|
values[(int)KernelUniform.Rxr] = ctx.RxRad;
|
||||||
|
values[(int)KernelUniform.Ryr] = ctx.RyRad;
|
||||||
|
values[(int)KernelUniform.Rzr] = ctx.RzRad;
|
||||||
|
values[(int)KernelUniform.Track0] = ctx.Track0;
|
||||||
|
values[(int)KernelUniform.Track1] = ctx.Track1;
|
||||||
|
values[(int)KernelUniform.Track2] = ctx.Track2;
|
||||||
|
values[(int)KernelUniform.Track3] = ctx.Track3;
|
||||||
|
values[(int)KernelUniform.Check0] = ctx.Check0 ? 1d : 0d;
|
||||||
|
values[(int)KernelUniform.Check1] = ctx.Check1 ? 1d : 0d;
|
||||||
|
values[(int)KernelUniform.Check2] = ctx.Check2 ? 1d : 0d;
|
||||||
|
values[(int)KernelUniform.Check3] = ctx.Check3 ? 1d : 0d;
|
||||||
|
values[(int)KernelUniform.Color] = ctx.HasColor ? ctx.ColorValue : -1d;
|
||||||
|
values[(int)KernelUniform.Time] = ctx.Time;
|
||||||
|
values[(int)KernelUniform.Frame] = ctx.Frame;
|
||||||
|
values[(int)KernelUniform.TotalFrame] = ctx.TotalFrame;
|
||||||
|
values[(int)KernelUniform.TotalTime] = ctx.TotalTime;
|
||||||
|
values[(int)KernelUniform.T] = ctx.TotalFrame > 0 ? ctx.Frame / (double)ctx.TotalFrame : 0d;
|
||||||
|
values[(int)KernelUniform.Framerate] = ctx.Framerate;
|
||||||
|
values[(int)KernelUniform.Layer] = ctx.Layer;
|
||||||
|
values[(int)KernelUniform.Index] = ctx.Index;
|
||||||
|
values[(int)KernelUniform.Num] = ctx.Num;
|
||||||
|
values[(int)KernelUniform.SceneWidth] = ctx.SceneWidth;
|
||||||
|
values[(int)KernelUniform.SceneHeight] = ctx.SceneHeight;
|
||||||
|
values[(int)KernelUniform.SceneCenterX] = ctx.SceneWidth / 2d;
|
||||||
|
values[(int)KernelUniform.SceneCenterY] = ctx.SceneHeight / 2d;
|
||||||
|
values[(int)KernelUniform.TimelineFrame] = ctx.TimelineFrame;
|
||||||
|
values[(int)KernelUniform.TimelineTime] = ctx.TimelineTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Pack(double[] values, float[] packed)
|
||||||
|
{
|
||||||
|
int count = Math.Min(values.Length, packed.Length);
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
packed[i] = (float)values[i];
|
||||||
|
for (int i = count; i < packed.Length; i++)
|
||||||
|
packed[i] = 0f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed class KernelUnsupportedException(string reason) : Exception(reason);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal abstract record LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record NumberExpr(double Value) : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record BoolExpr(bool Value) : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record NilExpr : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record StringExpr(string Value) : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record NameExpr(string Name) : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record MemberExpr(LuaExpr Target, string Name) : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record IndexExpr(LuaExpr Target, LuaExpr Key) : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record CallExpr(LuaExpr Target, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record UnaryExpr(string Operator, LuaExpr Operand) : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record BinaryExpr(string Operator, LuaExpr Left, LuaExpr Right) : LuaExpr;
|
||||||
|
|
||||||
|
internal abstract record LuaStmt;
|
||||||
|
|
||||||
|
internal sealed record LocalStmt(IReadOnlyList<string> Names, IReadOnlyList<LuaExpr> Values) : LuaStmt;
|
||||||
|
|
||||||
|
internal sealed record AssignStmt(IReadOnlyList<LuaExpr> Targets, IReadOnlyList<LuaExpr> Values) : LuaStmt;
|
||||||
|
|
||||||
|
internal sealed record CallStmt(CallExpr Call) : LuaStmt;
|
||||||
|
|
||||||
|
internal sealed record IfClause(LuaExpr Condition, IReadOnlyList<LuaStmt> Body);
|
||||||
|
|
||||||
|
internal sealed record IfStmt(IReadOnlyList<IfClause> Clauses, IReadOnlyList<LuaStmt>? ElseBody) : LuaStmt;
|
||||||
|
|
||||||
|
internal sealed record NumericForStmt(
|
||||||
|
string Variable,
|
||||||
|
LuaExpr Start,
|
||||||
|
LuaExpr Stop,
|
||||||
|
LuaExpr? Step,
|
||||||
|
IReadOnlyList<LuaStmt> Body) : LuaStmt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal static class LuaLexer
|
||||||
|
{
|
||||||
|
private static readonly HashSet<string> Keywords = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
"and", "break", "do", "else", "elseif", "end", "false", "for", "function",
|
||||||
|
"if", "in", "local", "nil", "not", "or", "repeat", "return", "then",
|
||||||
|
"true", "until", "while",
|
||||||
|
};
|
||||||
|
|
||||||
|
public static List<LuaToken> Tokenize(string source)
|
||||||
|
{
|
||||||
|
var tokens = new List<LuaToken>();
|
||||||
|
int i = 0;
|
||||||
|
int length = source.Length;
|
||||||
|
|
||||||
|
while (i < length)
|
||||||
|
{
|
||||||
|
char c = source[i];
|
||||||
|
|
||||||
|
if (c is ' ' or '\t' or '\r' or '\n' or '\f' or '\v')
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '-' && i + 1 < length && source[i + 1] == '-')
|
||||||
|
{
|
||||||
|
i = SkipComment(source, i + 2);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '"' || c == '\'')
|
||||||
|
{
|
||||||
|
i = ReadShortString(source, i, tokens);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '[' && i + 1 < length && (source[i + 1] == '[' || source[i + 1] == '='))
|
||||||
|
{
|
||||||
|
int level = LongBracketLevel(source, i);
|
||||||
|
if (level >= 0)
|
||||||
|
{
|
||||||
|
i = ReadLongString(source, i, level, tokens);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (char.IsDigit(c) || (c == '.' && i + 1 < length && char.IsDigit(source[i + 1])))
|
||||||
|
{
|
||||||
|
i = ReadNumber(source, i, tokens);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IsNameStart(c))
|
||||||
|
{
|
||||||
|
i = ReadName(source, i, tokens);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
i = ReadSymbol(source, i, tokens);
|
||||||
|
}
|
||||||
|
|
||||||
|
tokens.Add(new LuaToken(LuaTokenKind.Eof, string.Empty, 0d));
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipComment(string source, int i)
|
||||||
|
{
|
||||||
|
int level = LongBracketLevel(source, i);
|
||||||
|
if (level >= 0)
|
||||||
|
return SkipLongBracket(source, i, level);
|
||||||
|
|
||||||
|
int length = source.Length;
|
||||||
|
while (i < length && source[i] != '\n')
|
||||||
|
i++;
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int LongBracketLevel(string source, int i)
|
||||||
|
{
|
||||||
|
if (i >= source.Length || source[i] != '[')
|
||||||
|
return -1;
|
||||||
|
int j = i + 1;
|
||||||
|
int level = 0;
|
||||||
|
while (j < source.Length && source[j] == '=')
|
||||||
|
{
|
||||||
|
level++;
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
return j < source.Length && source[j] == '[' ? level : -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipLongBracket(string source, int i, int level)
|
||||||
|
{
|
||||||
|
int length = source.Length;
|
||||||
|
i += level + 2;
|
||||||
|
while (i < length)
|
||||||
|
{
|
||||||
|
if (source[i] == ']')
|
||||||
|
{
|
||||||
|
int j = i + 1;
|
||||||
|
int count = 0;
|
||||||
|
while (j < length && source[j] == '=')
|
||||||
|
{
|
||||||
|
count++;
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
if (count == level && j < length && source[j] == ']')
|
||||||
|
return j + 1;
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unterminated long bracket.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ReadLongString(string source, int start, int level, List<LuaToken> tokens)
|
||||||
|
{
|
||||||
|
int end = SkipLongBracket(source, start, level);
|
||||||
|
int contentStart = start + level + 2;
|
||||||
|
int contentEnd = end - level - 2;
|
||||||
|
string text = source.Substring(contentStart, Math.Max(0, contentEnd - contentStart));
|
||||||
|
tokens.Add(new LuaToken(LuaTokenKind.String, text, 0d));
|
||||||
|
return end;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ReadShortString(string source, int start, List<LuaToken> tokens)
|
||||||
|
{
|
||||||
|
char quote = source[start];
|
||||||
|
int i = start + 1;
|
||||||
|
int length = source.Length;
|
||||||
|
var value = new System.Text.StringBuilder();
|
||||||
|
|
||||||
|
while (i < length)
|
||||||
|
{
|
||||||
|
char c = source[i];
|
||||||
|
if (c == quote)
|
||||||
|
{
|
||||||
|
tokens.Add(new LuaToken(LuaTokenKind.String, value.ToString(), 0d));
|
||||||
|
return i + 1;
|
||||||
|
}
|
||||||
|
if (c == '\n')
|
||||||
|
throw new KernelUnsupportedException("Unterminated string.");
|
||||||
|
if (c == '\\')
|
||||||
|
{
|
||||||
|
i = ReadEscape(source, i + 1, value);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
value.Append(c);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unterminated string.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ReadEscape(string source, int i, System.Text.StringBuilder value)
|
||||||
|
{
|
||||||
|
if (i >= source.Length)
|
||||||
|
throw new KernelUnsupportedException("Unterminated string escape.");
|
||||||
|
|
||||||
|
char c = source[i];
|
||||||
|
switch (c)
|
||||||
|
{
|
||||||
|
case 'n': value.Append('\n'); return i + 1;
|
||||||
|
case 't': value.Append('\t'); return i + 1;
|
||||||
|
case 'r': value.Append('\r'); return i + 1;
|
||||||
|
case 'a': value.Append('\a'); return i + 1;
|
||||||
|
case 'b': value.Append('\b'); return i + 1;
|
||||||
|
case 'f': value.Append('\f'); return i + 1;
|
||||||
|
case 'v': value.Append('\v'); return i + 1;
|
||||||
|
case '\\': value.Append('\\'); return i + 1;
|
||||||
|
case '"': value.Append('"'); return i + 1;
|
||||||
|
case '\'': value.Append('\''); return i + 1;
|
||||||
|
case '\n': value.Append('\n'); return i + 1;
|
||||||
|
default:
|
||||||
|
if (char.IsDigit(c))
|
||||||
|
{
|
||||||
|
int n = 0;
|
||||||
|
int count = 0;
|
||||||
|
while (i < source.Length && count < 3 && char.IsDigit(source[i]))
|
||||||
|
{
|
||||||
|
n = n * 10 + (source[i] - '0');
|
||||||
|
i++;
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
value.Append((char)n);
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
value.Append(c);
|
||||||
|
return i + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ReadNumber(string source, int start, List<LuaToken> tokens)
|
||||||
|
{
|
||||||
|
int length = source.Length;
|
||||||
|
int i = start;
|
||||||
|
|
||||||
|
if (source[i] == '0' && i + 1 < length && (source[i + 1] == 'x' || source[i + 1] == 'X'))
|
||||||
|
{
|
||||||
|
i += 2;
|
||||||
|
int digitsStart = i;
|
||||||
|
while (i < length && Uri.IsHexDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
if (i == digitsStart)
|
||||||
|
throw new KernelUnsupportedException("Malformed hexadecimal literal.");
|
||||||
|
string hex = source.Substring(digitsStart, i - digitsStart);
|
||||||
|
double hexValue = (double)ulong.Parse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
|
||||||
|
tokens.Add(new LuaToken(LuaTokenKind.Number, source.Substring(start, i - start), hexValue));
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (i < length && char.IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
if (i < length && source[i] == '.')
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
while (i < length && char.IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
if (i < length && (source[i] == 'e' || source[i] == 'E'))
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
if (i < length && (source[i] == '+' || source[i] == '-'))
|
||||||
|
i++;
|
||||||
|
while (i < length && char.IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
string text = source.Substring(start, i - start);
|
||||||
|
double value = double.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture);
|
||||||
|
tokens.Add(new LuaToken(LuaTokenKind.Number, text, value));
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ReadName(string source, int start, List<LuaToken> tokens)
|
||||||
|
{
|
||||||
|
int i = start;
|
||||||
|
int length = source.Length;
|
||||||
|
while (i < length && IsNamePart(source[i]))
|
||||||
|
i++;
|
||||||
|
string text = source.Substring(start, i - start);
|
||||||
|
tokens.Add(new LuaToken(Keywords.Contains(text) ? LuaTokenKind.Keyword : LuaTokenKind.Name, text, 0d));
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ReadSymbol(string source, int start, List<LuaToken> tokens)
|
||||||
|
{
|
||||||
|
int length = source.Length;
|
||||||
|
char c = source[start];
|
||||||
|
|
||||||
|
if (c == '.' && start + 2 < length && source[start + 1] == '.' && source[start + 2] == '.')
|
||||||
|
{
|
||||||
|
tokens.Add(new LuaToken(LuaTokenKind.Symbol, "...", 0d));
|
||||||
|
return start + 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (start + 1 < length)
|
||||||
|
{
|
||||||
|
string two = source.Substring(start, 2);
|
||||||
|
switch (two)
|
||||||
|
{
|
||||||
|
case "==":
|
||||||
|
case "~=":
|
||||||
|
case "<=":
|
||||||
|
case ">=":
|
||||||
|
case "..":
|
||||||
|
tokens.Add(new LuaToken(LuaTokenKind.Symbol, two, 0d));
|
||||||
|
return start + 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (c)
|
||||||
|
{
|
||||||
|
case '+':
|
||||||
|
case '-':
|
||||||
|
case '*':
|
||||||
|
case '/':
|
||||||
|
case '%':
|
||||||
|
case '^':
|
||||||
|
case '#':
|
||||||
|
case '<':
|
||||||
|
case '>':
|
||||||
|
case '=':
|
||||||
|
case '(':
|
||||||
|
case ')':
|
||||||
|
case '{':
|
||||||
|
case '}':
|
||||||
|
case '[':
|
||||||
|
case ']':
|
||||||
|
case ';':
|
||||||
|
case ':':
|
||||||
|
case ',':
|
||||||
|
case '.':
|
||||||
|
tokens.Add(new LuaToken(LuaTokenKind.Symbol, c.ToString(), 0d));
|
||||||
|
return start + 1;
|
||||||
|
default:
|
||||||
|
throw new KernelUnsupportedException($"Unexpected character '{c}'.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsNameStart(char c) => c == '_' || char.IsLetter(c);
|
||||||
|
|
||||||
|
private static bool IsNamePart(char c) => c == '_' || char.IsLetterOrDigit(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,349 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed class LuaParser
|
||||||
|
{
|
||||||
|
private readonly List<LuaToken> _tokens;
|
||||||
|
private int _pos;
|
||||||
|
|
||||||
|
private LuaParser(List<LuaToken> tokens) => _tokens = tokens;
|
||||||
|
|
||||||
|
public static IReadOnlyList<LuaStmt> Parse(string source)
|
||||||
|
{
|
||||||
|
var parser = new LuaParser(LuaLexer.Tokenize(source));
|
||||||
|
var block = parser.ParseBlock();
|
||||||
|
parser.Expect(LuaTokenKind.Eof);
|
||||||
|
return block;
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaToken Current => _tokens[_pos];
|
||||||
|
|
||||||
|
private LuaToken Advance() => _tokens[_pos++];
|
||||||
|
|
||||||
|
private bool IsBlockEnd()
|
||||||
|
{
|
||||||
|
var t = Current;
|
||||||
|
return t.Kind == LuaTokenKind.Eof ||
|
||||||
|
t.IsKeyword("end") || t.IsKeyword("else") || t.IsKeyword("elseif") || t.IsKeyword("until");
|
||||||
|
}
|
||||||
|
|
||||||
|
private IReadOnlyList<LuaStmt> ParseBlock()
|
||||||
|
{
|
||||||
|
var statements = new List<LuaStmt>();
|
||||||
|
while (!IsBlockEnd())
|
||||||
|
{
|
||||||
|
if (Current.IsSymbol(";"))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
statements.Add(ParseStatement());
|
||||||
|
}
|
||||||
|
return statements;
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaStmt ParseStatement()
|
||||||
|
{
|
||||||
|
var t = Current;
|
||||||
|
if (t.IsKeyword("local"))
|
||||||
|
return ParseLocal();
|
||||||
|
if (t.IsKeyword("if"))
|
||||||
|
return ParseIf();
|
||||||
|
if (t.IsKeyword("for"))
|
||||||
|
return ParseFor();
|
||||||
|
if (t.Kind == LuaTokenKind.Keyword)
|
||||||
|
throw new KernelUnsupportedException($"Unsupported statement '{t.Text}'.");
|
||||||
|
return ParseExpressionStatement();
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaStmt ParseLocal()
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
if (Current.IsKeyword("function"))
|
||||||
|
throw new KernelUnsupportedException("Local functions are not supported.");
|
||||||
|
|
||||||
|
var names = new List<string> { ExpectName() };
|
||||||
|
while (Current.IsSymbol(","))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
names.Add(ExpectName());
|
||||||
|
}
|
||||||
|
|
||||||
|
IReadOnlyList<LuaExpr> values = [];
|
||||||
|
if (Current.IsSymbol("="))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
values = ParseExpressionList();
|
||||||
|
}
|
||||||
|
return new LocalStmt(names, values);
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaStmt ParseIf()
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
var clauses = new List<IfClause>();
|
||||||
|
|
||||||
|
var condition = ParseExpression();
|
||||||
|
ExpectKeyword("then");
|
||||||
|
clauses.Add(new IfClause(condition, ParseBlock()));
|
||||||
|
|
||||||
|
while (Current.IsKeyword("elseif"))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
var elseifCondition = ParseExpression();
|
||||||
|
ExpectKeyword("then");
|
||||||
|
clauses.Add(new IfClause(elseifCondition, ParseBlock()));
|
||||||
|
}
|
||||||
|
|
||||||
|
IReadOnlyList<LuaStmt>? elseBody = null;
|
||||||
|
if (Current.IsKeyword("else"))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
elseBody = ParseBlock();
|
||||||
|
}
|
||||||
|
|
||||||
|
ExpectKeyword("end");
|
||||||
|
return new IfStmt(clauses, elseBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaStmt ParseFor()
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
string variable = ExpectName();
|
||||||
|
if (!Current.IsSymbol("="))
|
||||||
|
throw new KernelUnsupportedException("Generic for loops are not supported.");
|
||||||
|
|
||||||
|
Advance();
|
||||||
|
var start = ParseExpression();
|
||||||
|
ExpectSymbol(",");
|
||||||
|
var stop = ParseExpression();
|
||||||
|
|
||||||
|
LuaExpr? step = null;
|
||||||
|
if (Current.IsSymbol(","))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
step = ParseExpression();
|
||||||
|
}
|
||||||
|
|
||||||
|
ExpectKeyword("do");
|
||||||
|
var body = ParseBlock();
|
||||||
|
ExpectKeyword("end");
|
||||||
|
return new NumericForStmt(variable, start, stop, step, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaStmt ParseExpressionStatement()
|
||||||
|
{
|
||||||
|
var first = ParseSuffixedExpression();
|
||||||
|
|
||||||
|
if (Current.IsSymbol("=") || Current.IsSymbol(","))
|
||||||
|
{
|
||||||
|
var targets = new List<LuaExpr> { first };
|
||||||
|
while (Current.IsSymbol(","))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
targets.Add(ParseSuffixedExpression());
|
||||||
|
}
|
||||||
|
ExpectSymbol("=");
|
||||||
|
var values = ParseExpressionList();
|
||||||
|
return new AssignStmt(targets, values);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (first is CallExpr call)
|
||||||
|
return new CallStmt(call);
|
||||||
|
|
||||||
|
throw new KernelUnsupportedException("Expression is not a valid statement.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<LuaExpr> ParseExpressionList()
|
||||||
|
{
|
||||||
|
var values = new List<LuaExpr> { ParseExpression() };
|
||||||
|
while (Current.IsSymbol(","))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
values.Add(ParseExpression());
|
||||||
|
}
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaExpr ParseExpression(int minPrecedence = 0)
|
||||||
|
{
|
||||||
|
var left = ParseUnary();
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var (op, precedence, rightAssociative) = PeekBinaryOperator();
|
||||||
|
if (op is null || precedence < minPrecedence)
|
||||||
|
break;
|
||||||
|
Advance();
|
||||||
|
int nextMinimum = rightAssociative ? precedence : precedence + 1;
|
||||||
|
var right = ParseExpression(nextMinimum);
|
||||||
|
left = new BinaryExpr(op, left, right);
|
||||||
|
}
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaExpr ParseUnary()
|
||||||
|
{
|
||||||
|
var t = Current;
|
||||||
|
if (t.IsKeyword("not") || t.IsSymbol("-") || t.IsSymbol("#"))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
return new UnaryExpr(t.Text, ParseExpression(7));
|
||||||
|
}
|
||||||
|
return ParseValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
private (string? Operator, int Precedence, bool RightAssociative) PeekBinaryOperator()
|
||||||
|
{
|
||||||
|
var t = Current;
|
||||||
|
if (t.IsKeyword("or")) return ("or", 1, false);
|
||||||
|
if (t.IsKeyword("and")) return ("and", 2, false);
|
||||||
|
if (t.Kind == LuaTokenKind.Symbol)
|
||||||
|
{
|
||||||
|
switch (t.Text)
|
||||||
|
{
|
||||||
|
case "<":
|
||||||
|
case ">":
|
||||||
|
case "<=":
|
||||||
|
case ">=":
|
||||||
|
case "~=":
|
||||||
|
case "==":
|
||||||
|
return (t.Text, 3, false);
|
||||||
|
case "..":
|
||||||
|
return ("..", 4, true);
|
||||||
|
case "+":
|
||||||
|
case "-":
|
||||||
|
return (t.Text, 5, false);
|
||||||
|
case "*":
|
||||||
|
case "/":
|
||||||
|
case "%":
|
||||||
|
return (t.Text, 6, false);
|
||||||
|
case "^":
|
||||||
|
return ("^", 8, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (null, 0, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaExpr ParseValue()
|
||||||
|
{
|
||||||
|
var t = Current;
|
||||||
|
switch (t.Kind)
|
||||||
|
{
|
||||||
|
case LuaTokenKind.Number:
|
||||||
|
Advance();
|
||||||
|
return new NumberExpr(t.Number);
|
||||||
|
case LuaTokenKind.String:
|
||||||
|
Advance();
|
||||||
|
return new StringExpr(t.Text);
|
||||||
|
case LuaTokenKind.Keyword when t.Text == "true":
|
||||||
|
Advance();
|
||||||
|
return new BoolExpr(true);
|
||||||
|
case LuaTokenKind.Keyword when t.Text == "false":
|
||||||
|
Advance();
|
||||||
|
return new BoolExpr(false);
|
||||||
|
case LuaTokenKind.Keyword when t.Text == "nil":
|
||||||
|
Advance();
|
||||||
|
return new NilExpr();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (t.IsKeyword("function") || t.IsSymbol("{") || t.IsSymbol("..."))
|
||||||
|
throw new KernelUnsupportedException($"Unsupported expression near '{t.Text}'.");
|
||||||
|
|
||||||
|
return ParseSuffixedExpression();
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaExpr ParseSuffixedExpression()
|
||||||
|
{
|
||||||
|
var expression = ParsePrimaryExpression();
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var t = Current;
|
||||||
|
if (t.IsSymbol("."))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
expression = new MemberExpr(expression, ExpectName());
|
||||||
|
}
|
||||||
|
else if (t.IsSymbol("["))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
var key = ParseExpression();
|
||||||
|
ExpectSymbol("]");
|
||||||
|
expression = new IndexExpr(expression, key);
|
||||||
|
}
|
||||||
|
else if (t.IsSymbol("("))
|
||||||
|
{
|
||||||
|
expression = new CallExpr(expression, ParseArguments());
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return expression;
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaExpr ParsePrimaryExpression()
|
||||||
|
{
|
||||||
|
var t = Current;
|
||||||
|
if (t.IsSymbol("("))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
var inner = ParseExpression();
|
||||||
|
ExpectSymbol(")");
|
||||||
|
return inner;
|
||||||
|
}
|
||||||
|
if (t.Kind == LuaTokenKind.Name)
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
return new NameExpr(t.Text);
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException($"Unexpected token '{t.Text}'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<LuaExpr> ParseArguments()
|
||||||
|
{
|
||||||
|
ExpectSymbol("(");
|
||||||
|
var arguments = new List<LuaExpr>();
|
||||||
|
if (!Current.IsSymbol(")"))
|
||||||
|
{
|
||||||
|
arguments.Add(ParseExpression());
|
||||||
|
while (Current.IsSymbol(","))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
arguments.Add(ParseExpression());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ExpectSymbol(")");
|
||||||
|
return arguments;
|
||||||
|
}
|
||||||
|
|
||||||
|
private string ExpectName()
|
||||||
|
{
|
||||||
|
if (Current.Kind != LuaTokenKind.Name)
|
||||||
|
throw new KernelUnsupportedException($"Expected a name but found '{Current.Text}'.");
|
||||||
|
return Advance().Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Expect(LuaTokenKind kind)
|
||||||
|
{
|
||||||
|
if (Current.Kind != kind)
|
||||||
|
throw new KernelUnsupportedException($"Expected {kind} but found '{Current.Text}'.");
|
||||||
|
Advance();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ExpectSymbol(string symbol)
|
||||||
|
{
|
||||||
|
if (!Current.IsSymbol(symbol))
|
||||||
|
throw new KernelUnsupportedException($"Expected '{symbol}' but found '{Current.Text}'.");
|
||||||
|
Advance();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ExpectKeyword(string keyword)
|
||||||
|
{
|
||||||
|
if (!Current.IsKeyword(keyword))
|
||||||
|
throw new KernelUnsupportedException($"Expected '{keyword}' but found '{Current.Text}'.");
|
||||||
|
Advance();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal enum LuaTokenKind
|
||||||
|
{
|
||||||
|
Name,
|
||||||
|
Number,
|
||||||
|
String,
|
||||||
|
Keyword,
|
||||||
|
Symbol,
|
||||||
|
Eof,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal readonly struct LuaToken(LuaTokenKind kind, string text, double number)
|
||||||
|
{
|
||||||
|
public LuaTokenKind Kind { get; } = kind;
|
||||||
|
public string Text { get; } = text;
|
||||||
|
public double Number { get; } = number;
|
||||||
|
|
||||||
|
public bool Is(LuaTokenKind kind, string text) =>
|
||||||
|
Kind == kind && string.Equals(Text, text, StringComparison.Ordinal);
|
||||||
|
|
||||||
|
public bool IsSymbol(string text) => Is(LuaTokenKind.Symbol, text);
|
||||||
|
|
||||||
|
public bool IsKeyword(string text) => Is(LuaTokenKind.Keyword, text);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,6 +16,9 @@ namespace LuaScript.Engine
|
|||||||
return UsesPixelApi(script) ? ScriptEngineKind.Native : ScriptEngineKind.MoonSharp;
|
return UsesPixelApi(script) ? ScriptEngineKind.Native : ScriptEngineKind.MoonSharp;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static bool TryResolveExplicit(string? script, out ScriptEngineKind kind) =>
|
||||||
|
TryGetDirective(script, out kind);
|
||||||
|
|
||||||
public static bool UsesPixelApi(string? script) =>
|
public static bool UsesPixelApi(string? script) =>
|
||||||
script is not null && (script.Contains("getpixel", StringComparison.Ordinal) || script.Contains("setpixel", StringComparison.Ordinal));
|
script is not null && (script.Contains("getpixel", StringComparison.Ordinal) || script.Contains("setpixel", StringComparison.Ordinal));
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ namespace LuaScript
|
|||||||
private static readonly string[] s_globals =
|
private static readonly string[] s_globals =
|
||||||
[
|
[
|
||||||
"time", "frame", "totalframe", "framerate",
|
"time", "frame", "totalframe", "framerate",
|
||||||
"timelineframe", "timelinetime", "layer",
|
"timelineframe", "timelinetime", "layer", "color",
|
||||||
"obj", "scene", "anim", "ymm4",
|
"obj", "scene", "anim", "ymm4",
|
||||||
"math", "string", "table", "bit32",
|
"math", "string", "table", "bit32",
|
||||||
"type", "tostring", "tonumber", "select", "error", "assert", "print",
|
"type", "tostring", "tonumber", "select", "error", "assert", "print",
|
||||||
@@ -39,6 +39,7 @@ namespace LuaScript
|
|||||||
"obj.rx", "obj.ry", "obj.rz",
|
"obj.rx", "obj.ry", "obj.rz",
|
||||||
"obj.rxr", "obj.ryr", "obj.rzr",
|
"obj.rxr", "obj.ryr", "obj.rzr",
|
||||||
"obj.track0", "obj.track1", "obj.track2", "obj.track3",
|
"obj.track0", "obj.track1", "obj.track2", "obj.track3",
|
||||||
|
"obj.check0", "obj.check1", "obj.check2", "obj.check3",
|
||||||
"obj.time", "obj.totaltime", "obj.t", "obj.frame", "obj.totalframe",
|
"obj.time", "obj.totaltime", "obj.t", "obj.frame", "obj.totalframe",
|
||||||
"obj.framerate", "obj.layer", "obj.index", "obj.num",
|
"obj.framerate", "obj.layer", "obj.index", "obj.num",
|
||||||
"obj.getpixel", "obj.setpixel",
|
"obj.getpixel", "obj.setpixel",
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ using System.Collections.Generic;
|
|||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using ICSharpCode.AvalonEdit.Document;
|
using ICSharpCode.AvalonEdit.Document;
|
||||||
using ICSharpCode.AvalonEdit.Folding;
|
using ICSharpCode.AvalonEdit.Folding;
|
||||||
|
using LuaScript.Diagnostics;
|
||||||
using YukkuriMovieMaker.Controls.AvalonEdit.FoldingStrategy;
|
using YukkuriMovieMaker.Controls.AvalonEdit.FoldingStrategy;
|
||||||
|
|
||||||
namespace LuaScript
|
namespace LuaScript
|
||||||
@@ -25,6 +26,7 @@ namespace LuaScript
|
|||||||
public void UpdateFoldings(FoldingManager manager, TextDocument document)
|
public void UpdateFoldings(FoldingManager manager, TextDocument document)
|
||||||
{
|
{
|
||||||
manager.UpdateFoldings(CreateNewFoldings(document, out int firstErrorOffset), firstErrorOffset);
|
manager.UpdateFoldings(CreateNewFoldings(document, out int firstErrorOffset), firstErrorOffset);
|
||||||
|
LuaScriptDiagnosticOverlay.Attach(manager);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
|
private static IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
|
||||||
|
|||||||
@@ -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.8.0</Version>
|
<Version>1.9.2</Version>
|
||||||
<Platforms>AnyCPU;x64</Platforms>
|
<Platforms>AnyCPU;x64</Platforms>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||||
|
|||||||
@@ -118,16 +118,17 @@ namespace LuaScript
|
|||||||
Layout = layout;
|
Layout = layout;
|
||||||
|
|
||||||
bool hasAny = layout.HasAny;
|
bool hasAny = layout.HasAny;
|
||||||
|
var usage = ScriptParameterUsage.Detect(_script);
|
||||||
|
|
||||||
IsTrack0Visible = !hasAny || layout.HasTrack(0);
|
IsTrack0Visible = !hasAny || layout.HasTrack(0);
|
||||||
IsTrack1Visible = !hasAny || layout.HasTrack(1);
|
IsTrack1Visible = !hasAny || layout.HasTrack(1);
|
||||||
IsTrack2Visible = !hasAny || layout.HasTrack(2);
|
IsTrack2Visible = !hasAny || layout.HasTrack(2);
|
||||||
IsTrack3Visible = !hasAny || layout.HasTrack(3);
|
IsTrack3Visible = !hasAny || layout.HasTrack(3);
|
||||||
IsCheck0Visible = layout.HasCheck(0);
|
IsCheck0Visible = layout.HasCheck(0) || (!hasAny && usage.Check0);
|
||||||
IsCheck1Visible = layout.HasCheck(1);
|
IsCheck1Visible = layout.HasCheck(1) || (!hasAny && usage.Check1);
|
||||||
IsCheck2Visible = layout.HasCheck(2);
|
IsCheck2Visible = layout.HasCheck(2) || (!hasAny && usage.Check2);
|
||||||
IsCheck3Visible = layout.HasCheck(3);
|
IsCheck3Visible = layout.HasCheck(3) || (!hasAny && usage.Check3);
|
||||||
IsColorVisible = layout.HasColor;
|
IsColorVisible = layout.HasColor || (!hasAny && usage.Color);
|
||||||
|
|
||||||
SeedDefaults(layout);
|
SeedDefaults(layout);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ using System.IO;
|
|||||||
using System.Numerics;
|
using System.Numerics;
|
||||||
using System.Runtime.InteropServices;
|
using System.Runtime.InteropServices;
|
||||||
using LuaScript.Compat;
|
using LuaScript.Compat;
|
||||||
|
using LuaScript.Diagnostics;
|
||||||
using LuaScript.Engine;
|
using LuaScript.Engine;
|
||||||
|
using LuaScript.Engine.Kernel;
|
||||||
using Vortice;
|
using Vortice;
|
||||||
using Vortice.DCommon;
|
using Vortice.DCommon;
|
||||||
using Vortice.Direct2D1;
|
using Vortice.Direct2D1;
|
||||||
@@ -64,6 +66,15 @@ namespace LuaScript
|
|||||||
private double[]? _nativeFields;
|
private double[]? _nativeFields;
|
||||||
private bool _nativeWarned;
|
private bool _nativeWarned;
|
||||||
private bool _effectChainWarned;
|
private bool _effectChainWarned;
|
||||||
|
private bool _gpuWarned;
|
||||||
|
|
||||||
|
private string _kernelSource = string.Empty;
|
||||||
|
private bool _kernelResolved;
|
||||||
|
private KernelProgram? _kernelProgram;
|
||||||
|
private CpuKernel? _cpuKernel;
|
||||||
|
private GpuKernel? _gpuKernel;
|
||||||
|
private bool _gpuKernelChecked;
|
||||||
|
private double[]? _kernelUniforms;
|
||||||
|
|
||||||
private EffectDescription? _frameDesc;
|
private EffectDescription? _frameDesc;
|
||||||
private SceneObjectResolver? _frameResolver;
|
private SceneObjectResolver? _frameResolver;
|
||||||
@@ -80,6 +91,7 @@ namespace LuaScript
|
|||||||
private bool _isFirst = true;
|
private bool _isFirst = true;
|
||||||
private string _sourceScript = string.Empty;
|
private string _sourceScript = string.Empty;
|
||||||
private string _runnableScript = string.Empty;
|
private string _runnableScript = string.Empty;
|
||||||
|
private int[] _runnableLineMap = [];
|
||||||
private bool _runnableCached;
|
private bool _runnableCached;
|
||||||
private ID2D1Image? _cachedInput;
|
private ID2D1Image? _cachedInput;
|
||||||
private RenderKey _cachedKey;
|
private RenderKey _cachedKey;
|
||||||
@@ -128,12 +140,39 @@ namespace LuaScript
|
|||||||
if (_runnableCached && string.Equals(source, _sourceScript, StringComparison.Ordinal))
|
if (_runnableCached && string.Equals(source, _sourceScript, StringComparison.Ordinal))
|
||||||
return _runnableScript;
|
return _runnableScript;
|
||||||
|
|
||||||
_runnableScript = AviUtlScript.Transform(source);
|
var (code, lineMap) = AviUtlScript.TransformWithMap(source);
|
||||||
|
_runnableScript = code;
|
||||||
|
_runnableLineMap = lineMap;
|
||||||
_sourceScript = source;
|
_sourceScript = source;
|
||||||
_runnableCached = true;
|
_runnableCached = true;
|
||||||
return _runnableScript;
|
return _runnableScript;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static LuaScriptDiagnosticKind ClassifyDiagnostic(LuaScriptException exception) => exception switch
|
||||||
|
{
|
||||||
|
LuaScriptCompilationException => LuaScriptDiagnosticKind.Compile,
|
||||||
|
LuaScriptTimeoutException => LuaScriptDiagnosticKind.Timeout,
|
||||||
|
_ => LuaScriptDiagnosticKind.Runtime,
|
||||||
|
};
|
||||||
|
|
||||||
|
private LuaScriptDiagnostic CreateDiagnostic(LuaScriptDiagnosticKind kind, string message)
|
||||||
|
{
|
||||||
|
var diagnostic = LuaScriptDiagnosticParser.Parse(kind, message);
|
||||||
|
return diagnostic.Line > 0
|
||||||
|
? diagnostic with { Line = MapRunnableLine(diagnostic.Line) }
|
||||||
|
: diagnostic;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int MapRunnableLine(int runnableLine)
|
||||||
|
{
|
||||||
|
int index = runnableLine - 1;
|
||||||
|
if (index < 0 || index >= _runnableLineMap.Length)
|
||||||
|
return runnableLine;
|
||||||
|
|
||||||
|
int sourceLine = _runnableLineMap[index];
|
||||||
|
return sourceLine >= 0 ? sourceLine + 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
protected override void setInput(ID2D1Image? input)
|
protected override void setInput(ID2D1Image? input)
|
||||||
{
|
{
|
||||||
if (!ReferenceEquals(_cachedInput, input))
|
if (!ReferenceEquals(_cachedInput, input))
|
||||||
@@ -164,7 +203,7 @@ namespace LuaScript
|
|||||||
var t3 = ClampTrack(item.Track3.GetValue(frame, length, fps), layout, 3);
|
var t3 = ClampTrack(item.Track3.GetValue(frame, length, fps), layout, 3);
|
||||||
|
|
||||||
bool c0 = item.Check0, c1 = item.Check1, c2 = item.Check2, c3 = item.Check3;
|
bool c0 = item.Check0, c1 = item.Check1, c2 = item.Check2, c3 = item.Check3;
|
||||||
bool hasColor = layout.HasColor;
|
bool hasColor = item.IsColorVisible;
|
||||||
int colorRgb = hasColor ? (item.Color.R << 16) | (item.Color.G << 8) | item.Color.B : 0;
|
int colorRgb = hasColor ? (item.Color.R << 16) | (item.Color.G << 8) | item.Color.B : 0;
|
||||||
|
|
||||||
var inDesc = desc.DrawDescription;
|
var inDesc = desc.DrawDescription;
|
||||||
@@ -203,63 +242,73 @@ namespace LuaScript
|
|||||||
ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH));
|
ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH));
|
||||||
|
|
||||||
DrawDescription outDesc = inDesc;
|
DrawDescription outDesc = inDesc;
|
||||||
|
IReadOnlyList<LuaScriptDiagnostic> diagnostics = [];
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
string runnable = GetRunnableScript(script);
|
string runnable = GetRunnableScript(script);
|
||||||
bool wantNative = ScriptDirective.ResolveAuto(runnable) == ScriptEngineKind.Native;
|
EnsureKernel(runnable);
|
||||||
bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory);
|
|
||||||
if (wantNative && !nativeReady)
|
|
||||||
WarnNativeUnavailableOnce();
|
|
||||||
|
|
||||||
if (nativeReady)
|
if (ExecuteKernelLane(runnable, ctx, bounds, imgW, imgH))
|
||||||
{
|
{
|
||||||
ExecuteNative(runnable, ctx, bounds, imgW, imgH);
|
outDesc = inDesc;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
_engine.Execute(runnable, ctx);
|
bool wantNative = ScriptDirective.ResolveAuto(runnable) == ScriptEngineKind.Native;
|
||||||
|
bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory);
|
||||||
|
if (wantNative && !nativeReady)
|
||||||
|
WarnNativeUnavailableOnce();
|
||||||
|
|
||||||
if (ctx.IsPixelsDirty)
|
if (nativeReady)
|
||||||
{
|
{
|
||||||
int bufW = ctx.ImageWidth;
|
ExecuteNative(runnable, ctx, bounds, imgW, imgH);
|
||||||
int bufH = ctx.ImageHeight;
|
|
||||||
_pixelManager!.WritePixelsToOutput(ctx.GetPixelBuffer()!, bufW, bufH);
|
|
||||||
if (ctx.BufferReplaced)
|
|
||||||
effectOutput = _pixelManager.GetTransformOutput(-bufW / 2f, -bufH / 2f);
|
|
||||||
else
|
|
||||||
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
effectOutput = null;
|
_engine.Execute(runnable, ctx);
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ctx.DrawCommands.Count > 0)
|
if (ctx.IsPixelsDirty)
|
||||||
{
|
{
|
||||||
ctx.EnsurePixelBuffer();
|
int bufW = ctx.ImageWidth;
|
||||||
var drawBuffer = ctx.GetPixelBuffer();
|
int bufH = ctx.ImageHeight;
|
||||||
if (drawBuffer is not null)
|
_pixelManager!.WritePixelsToOutput(ctx.GetPixelBuffer()!, bufW, bufH);
|
||||||
{
|
if (ctx.BufferReplaced)
|
||||||
_drawCompositor ??= new DrawCompositor(_ownCtx);
|
effectOutput = _pixelManager.GetTransformOutput(-bufW / 2f, -bufH / 2f);
|
||||||
effectOutput = _drawCompositor.Compose(drawBuffer, ctx.ImageWidth, ctx.ImageHeight, ctx.DrawCommands);
|
else
|
||||||
|
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
effectOutput = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
outDesc = BuildOutputDesc(inDesc, ctx);
|
if (ctx.DrawCommands.Count > 0)
|
||||||
|
|
||||||
if (ctx.EffectRequests.Count > 0)
|
|
||||||
{
|
|
||||||
var source = effectOutput ?? input;
|
|
||||||
try
|
|
||||||
{
|
{
|
||||||
effectOutput = ApplyEffectChain(source, ctx.EffectRequests, desc, ref outDesc);
|
ctx.EnsurePixelBuffer();
|
||||||
|
var drawBuffer = ctx.GetPixelBuffer();
|
||||||
|
if (drawBuffer is not null)
|
||||||
|
{
|
||||||
|
_drawCompositor ??= new DrawCompositor(_ownCtx);
|
||||||
|
effectOutput = _drawCompositor.Compose(drawBuffer, ctx.ImageWidth, ctx.ImageHeight, ctx.DrawCommands);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
|
||||||
|
outDesc = BuildOutputDesc(inDesc, ctx);
|
||||||
|
|
||||||
|
if (ctx.EffectRequests.Count > 0)
|
||||||
{
|
{
|
||||||
effectOutput = source;
|
var source = effectOutput ?? input;
|
||||||
WarnEffectChainFailureOnce(ex);
|
try
|
||||||
|
{
|
||||||
|
effectOutput = ApplyEffectChain(source, ctx.EffectRequests, desc, ref outDesc);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
effectOutput = source;
|
||||||
|
WarnEffectChainFailureOnce(ex);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -269,6 +318,7 @@ namespace LuaScript
|
|||||||
_context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
|
_context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
|
||||||
_isFirst = true;
|
_isFirst = true;
|
||||||
Log.Default.Write(ex.Message, ex);
|
Log.Default.Write(ex.Message, ex);
|
||||||
|
LuaScriptDiagnostics.Instance.Report(script, [CreateDiagnostic(LuaScriptDiagnosticKind.Timeout, ex.Message)]);
|
||||||
return inDesc;
|
return inDesc;
|
||||||
}
|
}
|
||||||
catch (LuaScriptException ex)
|
catch (LuaScriptException ex)
|
||||||
@@ -276,6 +326,7 @@ namespace LuaScript
|
|||||||
effectOutput = null;
|
effectOutput = null;
|
||||||
outDesc = inDesc;
|
outDesc = inDesc;
|
||||||
Log.Default.Write(ex.Message, ex);
|
Log.Default.Write(ex.Message, ex);
|
||||||
|
diagnostics = [CreateDiagnostic(ClassifyDiagnostic(ex), ex.Message)];
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -283,6 +334,8 @@ namespace LuaScript
|
|||||||
_pixelLoaderSemaphore.Release();
|
_pixelLoaderSemaphore.Release();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
LuaScriptDiagnostics.Instance.Report(script, diagnostics);
|
||||||
|
|
||||||
_isFirst = false;
|
_isFirst = false;
|
||||||
_cachedKey = key;
|
_cachedKey = key;
|
||||||
_cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries];
|
_cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries];
|
||||||
@@ -423,6 +476,81 @@ namespace LuaScript
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void EnsureKernel(string runnable)
|
||||||
|
{
|
||||||
|
if (_kernelResolved && string.Equals(runnable, _kernelSource, StringComparison.Ordinal))
|
||||||
|
return;
|
||||||
|
|
||||||
|
_kernelSource = runnable;
|
||||||
|
_kernelResolved = true;
|
||||||
|
_kernelProgram = KernelExtractor.TryExtract(runnable);
|
||||||
|
_cpuKernel = _kernelProgram is null ? null : CpuKernelCompiler.Compile(_kernelProgram);
|
||||||
|
_gpuKernel?.Dispose();
|
||||||
|
_gpuKernel = null;
|
||||||
|
_gpuKernelChecked = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool ExecuteKernelLane(string runnable, AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
|
||||||
|
{
|
||||||
|
if (_kernelProgram is null || _cpuKernel is null)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
bool explicitDirective = ScriptDirective.TryResolveExplicit(runnable, out var kind);
|
||||||
|
if (explicitDirective && kind is not (ScriptEngineKind.Gpu or ScriptEngineKind.Cpu))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
_kernelUniforms ??= KernelUniformBinding.Create();
|
||||||
|
KernelUniformBinding.Fill(ctx, _kernelUniforms);
|
||||||
|
|
||||||
|
if (explicitDirective && kind == ScriptEngineKind.Gpu)
|
||||||
|
{
|
||||||
|
var gpu = GetGpuKernel();
|
||||||
|
if (gpu is not null)
|
||||||
|
{
|
||||||
|
effectOutput = gpu.Apply(input!, _kernelUniforms);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
WarnGpuUnavailableOnce();
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] buffer = LoadInputPixels(bounds, imgW, imgH);
|
||||||
|
_cpuKernel.Execute(buffer, imgW, imgH, _kernelUniforms);
|
||||||
|
_pixelManager!.WritePixelsToOutput(buffer, imgW, imgH);
|
||||||
|
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private GpuKernel? GetGpuKernel()
|
||||||
|
{
|
||||||
|
if (_gpuKernelChecked)
|
||||||
|
return _gpuKernel;
|
||||||
|
|
||||||
|
_gpuKernelChecked = true;
|
||||||
|
if (_kernelProgram is null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var kernel = new GpuKernel(_ownCtx!, _kernelProgram);
|
||||||
|
if (kernel.IsReady)
|
||||||
|
_gpuKernel = kernel;
|
||||||
|
else
|
||||||
|
kernel.Dispose();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log.Default.Write("LuaScript: GPU kernel initialization failed; falling back to CPU.", ex);
|
||||||
|
}
|
||||||
|
return _gpuKernel;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WarnGpuUnavailableOnce()
|
||||||
|
{
|
||||||
|
if (_gpuWarned) return;
|
||||||
|
_gpuWarned = true;
|
||||||
|
Log.Default.Write("LuaScript: GPU kernel unavailable; using the CPU kernel lane instead.");
|
||||||
|
}
|
||||||
|
|
||||||
private void WarnNativeUnavailableOnce()
|
private void WarnNativeUnavailableOnce()
|
||||||
{
|
{
|
||||||
if (_nativeWarned) return;
|
if (_nativeWarned) return;
|
||||||
@@ -555,6 +683,7 @@ namespace LuaScript
|
|||||||
if (disposing)
|
if (disposing)
|
||||||
{
|
{
|
||||||
_engine.Dispose();
|
_engine.Dispose();
|
||||||
|
_gpuKernel?.Dispose();
|
||||||
_nativeWorker?.Dispose();
|
_nativeWorker?.Dispose();
|
||||||
_effectChain?.Dispose();
|
_effectChain?.Dispose();
|
||||||
_drawCompositor?.Dispose();
|
_drawCompositor?.Dispose();
|
||||||
|
|||||||
@@ -84,4 +84,7 @@
|
|||||||
<data name="ToolBarImportErrorTitle" 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="ToolBarExportErrorTitle" xml:space="preserve"><value>خطأ في التصدير</value></data>
|
||||||
<data name="LuaFileFilter" xml:space="preserve"><value>نص Lua (*.lua)|*.lua|جميع الملفات (*.*)|*.*</value></data>
|
<data name="LuaFileFilter" xml:space="preserve"><value>نص Lua (*.lua)|*.lua|جميع الملفات (*.*)|*.*</value></data>
|
||||||
|
<data name="DiagnosticCompile" xml:space="preserve"><value>خطأ في بناء الجملة</value></data>
|
||||||
|
<data name="DiagnosticRuntime" xml:space="preserve"><value>خطأ وقت التشغيل</value></data>
|
||||||
|
<data name="DiagnosticTimeout" xml:space="preserve"><value>انتهت المهلة</value></data>
|
||||||
</root>
|
</root>
|
||||||
@@ -24,3 +24,6 @@ ToolBarClearTitle,,確認,Confirm,确认,確認,확인,Confirmar,تأكيد,Konf
|
|||||||
ToolBarImportErrorTitle,,インポートエラー,Import Error,导入错误,導入錯誤,가져오기 오류,Error de importación,خطأ في الاستيراد,Kesalahan impor
|
ToolBarImportErrorTitle,,インポートエラー,Import Error,导入错误,導入錯誤,가져오기 오류,Error de importación,خطأ في الاستيراد,Kesalahan impor
|
||||||
ToolBarExportErrorTitle,,エクスポートエラー,Export Error,导出错误,導出錯誤,내보내기 오류,Error de exportación,خطأ في التصدير,Kesalahan ekspor
|
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 (*.*)|*.*
|
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 (*.*)|*.*
|
||||||
|
DiagnosticCompile,,構文エラー,Syntax error,语法错误,語法錯誤,구문 오류,Error de sintaxis,خطأ في بناء الجملة,Kesalahan sintaksis
|
||||||
|
DiagnosticRuntime,,実行時エラー,Runtime error,运行时错误,執行時錯誤,런타임 오류,Error de ejecución,خطأ وقت التشغيل,Kesalahan runtime
|
||||||
|
DiagnosticTimeout,,タイムアウト,Timed out,执行超时,執行逾時,시간 초과,Tiempo de espera agotado,انتهت المهلة,Waktu habis
|
||||||
|
@@ -84,4 +84,7 @@
|
|||||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Import Error</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="ToolBarExportErrorTitle" xml:space="preserve"><value>Export Error</value></data>
|
||||||
<data name="LuaFileFilter" xml:space="preserve"><value>Lua Script (*.lua)|*.lua|All Files (*.*)|*.*</value></data>
|
<data name="LuaFileFilter" xml:space="preserve"><value>Lua Script (*.lua)|*.lua|All Files (*.*)|*.*</value></data>
|
||||||
|
<data name="DiagnosticCompile" xml:space="preserve"><value>Syntax error</value></data>
|
||||||
|
<data name="DiagnosticRuntime" xml:space="preserve"><value>Runtime error</value></data>
|
||||||
|
<data name="DiagnosticTimeout" xml:space="preserve"><value>Timed out</value></data>
|
||||||
</root>
|
</root>
|
||||||
@@ -84,4 +84,7 @@
|
|||||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Error de importación</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="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>
|
<data name="LuaFileFilter" xml:space="preserve"><value>Script Lua (*.lua)|*.lua|Todos los archivos (*.*)|*.*</value></data>
|
||||||
|
<data name="DiagnosticCompile" xml:space="preserve"><value>Error de sintaxis</value></data>
|
||||||
|
<data name="DiagnosticRuntime" xml:space="preserve"><value>Error de ejecución</value></data>
|
||||||
|
<data name="DiagnosticTimeout" xml:space="preserve"><value>Tiempo de espera agotado</value></data>
|
||||||
</root>
|
</root>
|
||||||
@@ -84,4 +84,7 @@
|
|||||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Kesalahan impor</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="ToolBarExportErrorTitle" xml:space="preserve"><value>Kesalahan ekspor</value></data>
|
||||||
<data name="LuaFileFilter" xml:space="preserve"><value>Skrip Lua (*.lua)|*.lua|Semua File (*.*)|*.*</value></data>
|
<data name="LuaFileFilter" xml:space="preserve"><value>Skrip Lua (*.lua)|*.lua|Semua File (*.*)|*.*</value></data>
|
||||||
|
<data name="DiagnosticCompile" xml:space="preserve"><value>Kesalahan sintaksis</value></data>
|
||||||
|
<data name="DiagnosticRuntime" xml:space="preserve"><value>Kesalahan runtime</value></data>
|
||||||
|
<data name="DiagnosticTimeout" xml:space="preserve"><value>Waktu habis</value></data>
|
||||||
</root>
|
</root>
|
||||||
@@ -84,4 +84,7 @@
|
|||||||
<data name="ToolBarImportErrorTitle" 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="ToolBarExportErrorTitle" xml:space="preserve"><value>내보내기 오류</value></data>
|
||||||
<data name="LuaFileFilter" xml:space="preserve"><value>Lua 스크립트 (*.lua)|*.lua|모든 파일 (*.*)|*.*</value></data>
|
<data name="LuaFileFilter" xml:space="preserve"><value>Lua 스크립트 (*.lua)|*.lua|모든 파일 (*.*)|*.*</value></data>
|
||||||
|
<data name="DiagnosticCompile" xml:space="preserve"><value>구문 오류</value></data>
|
||||||
|
<data name="DiagnosticRuntime" xml:space="preserve"><value>런타임 오류</value></data>
|
||||||
|
<data name="DiagnosticTimeout" xml:space="preserve"><value>시간 초과</value></data>
|
||||||
</root>
|
</root>
|
||||||
@@ -84,4 +84,7 @@
|
|||||||
<data name="ToolBarImportErrorTitle" 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="ToolBarExportErrorTitle" xml:space="preserve"><value>エクスポートエラー</value></data>
|
||||||
<data name="LuaFileFilter" xml:space="preserve"><value>Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*.*</value></data>
|
<data name="LuaFileFilter" xml:space="preserve"><value>Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*.*</value></data>
|
||||||
|
<data name="DiagnosticCompile" xml:space="preserve"><value>構文エラー</value></data>
|
||||||
|
<data name="DiagnosticRuntime" xml:space="preserve"><value>実行時エラー</value></data>
|
||||||
|
<data name="DiagnosticTimeout" xml:space="preserve"><value>タイムアウト</value></data>
|
||||||
</root>
|
</root>
|
||||||
@@ -84,4 +84,7 @@
|
|||||||
<data name="ToolBarImportErrorTitle" 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="ToolBarExportErrorTitle" xml:space="preserve"><value>导出错误</value></data>
|
||||||
<data name="LuaFileFilter" xml:space="preserve"><value>Lua脚本 (*.lua)|*.lua|所有文件 (*.*)|*.*</value></data>
|
<data name="LuaFileFilter" xml:space="preserve"><value>Lua脚本 (*.lua)|*.lua|所有文件 (*.*)|*.*</value></data>
|
||||||
|
<data name="DiagnosticCompile" xml:space="preserve"><value>语法错误</value></data>
|
||||||
|
<data name="DiagnosticRuntime" xml:space="preserve"><value>运行时错误</value></data>
|
||||||
|
<data name="DiagnosticTimeout" xml:space="preserve"><value>执行超时</value></data>
|
||||||
</root>
|
</root>
|
||||||
@@ -84,4 +84,7 @@
|
|||||||
<data name="ToolBarImportErrorTitle" 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="ToolBarExportErrorTitle" xml:space="preserve"><value>導出錯誤</value></data>
|
||||||
<data name="LuaFileFilter" xml:space="preserve"><value>Lua腳本 (*.lua)|*.lua|所有檔案 (*.*)|*.*</value></data>
|
<data name="LuaFileFilter" xml:space="preserve"><value>Lua腳本 (*.lua)|*.lua|所有檔案 (*.*)|*.*</value></data>
|
||||||
|
<data name="DiagnosticCompile" xml:space="preserve"><value>語法錯誤</value></data>
|
||||||
|
<data name="DiagnosticRuntime" xml:space="preserve"><value>執行時錯誤</value></data>
|
||||||
|
<data name="DiagnosticTimeout" xml:space="preserve"><value>執行逾時</value></data>
|
||||||
</root>
|
</root>
|
||||||
@@ -24,6 +24,58 @@
|
|||||||
حذف هذه الاستدعاءات عند عدم الحاجة يسرّع المعالجة.
|
حذف هذه الاستدعاءات عند عدم الحاجة يسرّع المعالجة.
|
||||||
|
|
||||||
|
|
||||||
|
- محركات التنفيذ والتسريع التلقائي -
|
||||||
|
|
||||||
|
النصوص التي تحتوي على معالجة بكسل (حلقة getpixel/setpixel متداخلة)
|
||||||
|
يُحلَّل تركيبها وتُوجَّه تلقائياً إلى محرك أسرع.
|
||||||
|
أما النصوص العادية (الإحداثيات، الدوران، الشفافية، إلخ) فتظل تعمل على
|
||||||
|
MoonSharp كما في السابق دون أي تغيير في السلوك.
|
||||||
|
|
||||||
|
○ التوجيه التلقائي (عند عدم وجود توجيه)
|
||||||
|
· تخطيط بكسل مكتفٍ بنفسه (انظر الشروط أدناه)
|
||||||
|
→ نواة CPU (سريعة ودقيقة)
|
||||||
|
· عمليات البكسل الأخرى → Native (LuaJIT، فقط عند نشره)
|
||||||
|
· بلا عمليات بكسل → MoonSharp
|
||||||
|
|
||||||
|
○ توجيهات المحرك (تعليق في السطر الأول من النص)
|
||||||
|
--!cpu : نواة CPU. تُترجَم وقت التشغيل إلى شجرة تعابير
|
||||||
|
وتُنفَّذ بالتوازي على كل أنوية CPU (مطابقة تماماً لـ MoonSharp).
|
||||||
|
--!gpu : نواة GPU. تُنفَّذ كمظلِّل بكسل Direct2D،
|
||||||
|
وتلغي نقل GPU→CPU لأقصى سرعة.
|
||||||
|
قد تختلف النتائج اختلافاً طفيفاً بسبب دقة float32 (اختياري).
|
||||||
|
--!native : LuaJIT (عملية منفصلة). سريع ومطابق لـ MoonSharp.
|
||||||
|
يتطلب نشر مجلد native.
|
||||||
|
--!moonsharp : يفرض محرك MoonSharp التقليدي.
|
||||||
|
※ إذا كان التوجيه غير متاح/غير مدعوم، يرجع تلقائياً إلى محرك أدنى
|
||||||
|
(لا يتلف الإخراج أبداً).
|
||||||
|
|
||||||
|
○ التركيب المؤهَّل للنواة السريعة (تخطيط بكسل خالص)
|
||||||
|
فقط الحلقة المتداخلة بالشكل التالي تتحول إلى نواة.
|
||||||
|
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, r2, g2, b2 [, a2])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
· يجوز في الجسم استخدام العمليات الحسابية و math.* والمقارنات
|
||||||
|
وصيغة العتبة "cond and value1 or value2" ومتغيرات local فقط.
|
||||||
|
· يجوز الإشارة فقط إلى البكسل الجاري معالجته (getpixel(x, y))
|
||||||
|
وقيم مثل obj/scene/time.
|
||||||
|
· أي استخدام لأخذ عينات الجوار (التمويه، إلخ) أو الكتابة إلى
|
||||||
|
إحداثيات أخرى أو getpixeldata أو getobject أو عمليات
|
||||||
|
الجداول/السلاسل أو جُمَل if لا يتحول إلى نواة ويُنفَّذ تلقائياً
|
||||||
|
على المحرك التقليدي.
|
||||||
|
|
||||||
|
مثال (يجعل شكلاً أبيض أحمر):
|
||||||
|
--!gpu
|
||||||
|
for y = 0, obj.h - 1 do
|
||||||
|
for x = 0, obj.w - 1 do
|
||||||
|
local r, g, b, a = obj.getpixel(x, y)
|
||||||
|
obj.setpixel(x, y, r, g / 2, b / 2, a)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
- المعاملات -
|
- المعاملات -
|
||||||
|
|
||||||
يحتوي لوح التأثيرات على 4 أشرطة تتبع (تدعم الرسوم المتحركة) على النحو التالي.
|
يحتوي لوح التأثيرات على 4 أشرطة تتبع (تدعم الرسوم المتحركة) على النحو التالي.
|
||||||
@@ -36,6 +88,10 @@
|
|||||||
|
|
||||||
* كل شريط تتبع يدعم شرائح الرسوم المتحركة (مع الاستيفاء).
|
* كل شريط تتبع يدعم شرائح الرسوم المتحركة (مع الاستيفاء).
|
||||||
* يمكن استيراد/تصدير ملفات .lua من شريط أدوات محرر النصوص.
|
* يمكن استيراد/تصدير ملفات .lua من شريط أدوات محرر النصوص.
|
||||||
|
* تظهر مربعات الاختيار (obj.check0 إلى obj.check3) واللون (color) في لوح التأثيرات
|
||||||
|
تلقائياً عندما يشير إليها النص البرمجي (تظهر أشرطة التتبع دائماً). هذا الاستخدام
|
||||||
|
العام لا يصاحبه إعلان نطاق/قيمة افتراضية، لذا تعامل مع نطاقات القيم داخل النص.
|
||||||
|
وتبقى رؤوس AviUtl --track / --check / --color تعمل كما كانت.
|
||||||
|
|
||||||
|
|
||||||
- المتغيرات العامة -
|
- المتغيرات العامة -
|
||||||
|
|||||||
@@ -24,6 +24,61 @@
|
|||||||
Omitting these calls when unnecessary will speed up processing.
|
Omitting these calls when unnecessary will speed up processing.
|
||||||
|
|
||||||
|
|
||||||
|
- Execution Engines and Automatic Acceleration -
|
||||||
|
|
||||||
|
Scripts that contain pixel processing (a nested getpixel/setpixel loop)
|
||||||
|
are analyzed and automatically routed to a faster engine.
|
||||||
|
Ordinary scripts (coordinate, rotation, opacity changes, etc.) keep
|
||||||
|
running on MoonSharp as before, with no change in behavior.
|
||||||
|
|
||||||
|
o Automatic routing (when no directive is present)
|
||||||
|
- A self-contained per-pixel map (see conditions below)
|
||||||
|
-> CPU kernel (fast, exact)
|
||||||
|
- Other pixel operations -> Native (LuaJIT, only when deployed)
|
||||||
|
- No pixel operations -> MoonSharp
|
||||||
|
|
||||||
|
o Engine directives (a comment on the first line of the script)
|
||||||
|
--!cpu : CPU kernel. Compiled at runtime to an expression
|
||||||
|
tree and run in parallel on all CPU cores
|
||||||
|
(bit-identical to MoonSharp).
|
||||||
|
--!gpu : GPU kernel. Run as a Direct2D pixel shader,
|
||||||
|
eliminating the GPU->CPU transfer for top speed.
|
||||||
|
Results may differ slightly due to float32
|
||||||
|
precision (opt-in).
|
||||||
|
--!native : LuaJIT (separate process). Fast and identical to
|
||||||
|
MoonSharp. Requires the native folder deployed.
|
||||||
|
--!moonsharp : Forces the classic MoonSharp engine.
|
||||||
|
* If a directive is unavailable or unsupported, it automatically
|
||||||
|
falls back to a lower engine (the output is never broken).
|
||||||
|
|
||||||
|
o Syntax eligible for the fast kernel (a pure per-pixel map)
|
||||||
|
Only a nested loop of the following form becomes a kernel.
|
||||||
|
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, r2, g2, b2 [, a2])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
- The body may use only arithmetic, math.*, comparisons, the
|
||||||
|
threshold idiom "cond and value1 or value2", and local
|
||||||
|
variables.
|
||||||
|
- It may reference only the current pixel being processed
|
||||||
|
(getpixel(x, y)) and values such as obj/scene/time.
|
||||||
|
- Anything using neighbor sampling (blur, etc.), writes to other
|
||||||
|
coordinates, getpixeldata, getobject, table/string operations,
|
||||||
|
or if statements is not turned into a kernel and automatically
|
||||||
|
runs on the classic engine.
|
||||||
|
|
||||||
|
Example (turns a white figure red):
|
||||||
|
--!gpu
|
||||||
|
for y = 0, obj.h - 1 do
|
||||||
|
for x = 0, obj.w - 1 do
|
||||||
|
local r, g, b, a = obj.getpixel(x, y)
|
||||||
|
obj.setpixel(x, y, r, g / 2, b / 2, a)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
- Parameters -
|
- Parameters -
|
||||||
|
|
||||||
The effect panel has 4 trackbars (animation-enabled) as follows.
|
The effect panel has 4 trackbars (animation-enabled) as follows.
|
||||||
@@ -36,6 +91,11 @@
|
|||||||
|
|
||||||
* Each trackbar supports animation sliders (with interpolation).
|
* Each trackbar supports animation sliders (with interpolation).
|
||||||
* .lua files can be imported/exported from the script editor toolbar.
|
* .lua files can be imported/exported from the script editor toolbar.
|
||||||
|
* The checkboxes (obj.check0 - obj.check3) and the color (color) appear in the
|
||||||
|
effect panel automatically when the script references them (the trackbars are
|
||||||
|
always shown). This general use carries no range/default declaration, so handle
|
||||||
|
value ranges within the script. The AviUtl --track / --check / --color headers
|
||||||
|
still work as before.
|
||||||
|
|
||||||
|
|
||||||
- Global Variables -
|
- Global Variables -
|
||||||
|
|||||||
@@ -24,6 +24,61 @@
|
|||||||
primer acceso. Omitir estas llamadas cuando no sean necesarias acelera el procesamiento.
|
primer acceso. Omitir estas llamadas cuando no sean necesarias acelera el procesamiento.
|
||||||
|
|
||||||
|
|
||||||
|
- Motores de ejecución y aceleración automática -
|
||||||
|
|
||||||
|
Los scripts que contienen procesamiento de píxeles (un bucle anidado
|
||||||
|
getpixel/setpixel) se analizan y se enrutan automáticamente a un motor
|
||||||
|
más rápido. Los scripts normales (coordenadas, rotación, opacidad, etc.)
|
||||||
|
siguen ejecutándose en MoonSharp como antes, sin cambios de comportamiento.
|
||||||
|
|
||||||
|
o Enrutamiento automático (cuando no hay directiva)
|
||||||
|
- Un mapeo por píxel autocontenido (ver condiciones abajo)
|
||||||
|
-> núcleo CPU (rápido, exacto)
|
||||||
|
- Otras operaciones de píxeles -> Nativo (LuaJIT, solo si está
|
||||||
|
desplegado)
|
||||||
|
- Sin operaciones de píxeles -> MoonSharp
|
||||||
|
|
||||||
|
o Directivas de motor (un comentario en la primera línea del script)
|
||||||
|
--!cpu : Núcleo CPU. Compilado en tiempo de ejecución a un
|
||||||
|
árbol de expresiones y ejecutado en paralelo en
|
||||||
|
todos los núcleos de la CPU (idéntico a MoonSharp).
|
||||||
|
--!gpu : Núcleo GPU. Ejecutado como un sombreador de píxeles
|
||||||
|
de Direct2D, eliminando la transferencia GPU->CPU
|
||||||
|
para máxima velocidad. Los resultados pueden diferir
|
||||||
|
levemente por la precisión float32 (opcional).
|
||||||
|
--!native : LuaJIT (proceso aparte). Rápido e idéntico a
|
||||||
|
MoonSharp. Requiere la carpeta native desplegada.
|
||||||
|
--!moonsharp : Fuerza el motor clásico MoonSharp.
|
||||||
|
* Si una directiva no está disponible o no es compatible, recurre
|
||||||
|
automáticamente a un motor inferior (la salida nunca se rompe).
|
||||||
|
|
||||||
|
o Sintaxis apta para el núcleo rápido (un mapeo por píxel puro)
|
||||||
|
Solo un bucle anidado con la forma siguiente se convierte en núcleo.
|
||||||
|
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, r2, g2, b2 [, a2])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
- El cuerpo solo puede usar aritmética, math.*, comparaciones, el
|
||||||
|
modismo de umbral "cond and valor1 or valor2" y variables local.
|
||||||
|
- Solo puede referenciar el píxel actual en proceso
|
||||||
|
(getpixel(x, y)) y valores como obj/scene/time.
|
||||||
|
- Todo lo que use muestreo de vecinos (desenfoque, etc.),
|
||||||
|
escrituras en otras coordenadas, getpixeldata, getobject,
|
||||||
|
operaciones de tabla/cadena o sentencias if no se convierte en
|
||||||
|
núcleo y se ejecuta automáticamente en el motor clásico.
|
||||||
|
|
||||||
|
Ejemplo (vuelve roja una figura blanca):
|
||||||
|
--!gpu
|
||||||
|
for y = 0, obj.h - 1 do
|
||||||
|
for x = 0, obj.w - 1 do
|
||||||
|
local r, g, b, a = obj.getpixel(x, y)
|
||||||
|
obj.setpixel(x, y, r, g / 2, b / 2, a)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
- Parámetros -
|
- Parámetros -
|
||||||
|
|
||||||
El panel de efectos tiene los siguientes 4 controles deslizantes (con soporte de animación).
|
El panel de efectos tiene los siguientes 4 controles deslizantes (con soporte de animación).
|
||||||
@@ -36,6 +91,11 @@
|
|||||||
|
|
||||||
* Cada control deslizante es compatible con los deslizadores de animación (con interpolación).
|
* 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.
|
* Los archivos .lua pueden importarse/exportarse desde la barra de herramientas del editor de scripts.
|
||||||
|
* Las casillas (obj.check0 - obj.check3) y el color (color) aparecen en el panel de
|
||||||
|
efectos automáticamente cuando el script los referencia (las barras siempre se
|
||||||
|
muestran). Este uso general no conlleva declaración de rango/valor predeterminado,
|
||||||
|
así que gestione los rangos dentro del script. Las cabeceras --track / --check /
|
||||||
|
--color de AviUtl siguen funcionando como antes.
|
||||||
|
|
||||||
|
|
||||||
- Variables globales -
|
- Variables globales -
|
||||||
|
|||||||
@@ -24,6 +24,60 @@
|
|||||||
Menghilangkan panggilan ini saat tidak diperlukan akan mempercepat pemrosesan.
|
Menghilangkan panggilan ini saat tidak diperlukan akan mempercepat pemrosesan.
|
||||||
|
|
||||||
|
|
||||||
|
- Mesin Eksekusi dan Akselerasi Otomatis -
|
||||||
|
|
||||||
|
Skrip yang berisi pemrosesan piksel (loop bersarang getpixel/setpixel)
|
||||||
|
dianalisis sintaksnya dan secara otomatis dialihkan ke mesin yang lebih
|
||||||
|
cepat. Skrip biasa (koordinat, rotasi, opasitas, dll.) tetap berjalan di
|
||||||
|
MoonSharp seperti sebelumnya, tanpa perubahan perilaku.
|
||||||
|
|
||||||
|
o Pengalihan otomatis (saat tidak ada direktif)
|
||||||
|
- Pemetaan per-piksel mandiri (lihat syarat di bawah)
|
||||||
|
-> kernel CPU (cepat, tepat)
|
||||||
|
- Operasi piksel lainnya -> Native (LuaJIT, hanya jika di-deploy)
|
||||||
|
- Tanpa operasi piksel -> MoonSharp
|
||||||
|
|
||||||
|
o Direktif mesin (komentar pada baris pertama skrip)
|
||||||
|
--!cpu : Kernel CPU. Dikompilasi saat runtime menjadi pohon
|
||||||
|
ekspresi dan dijalankan paralel di semua inti CPU
|
||||||
|
(identik dengan MoonSharp).
|
||||||
|
--!gpu : Kernel GPU. Dijalankan sebagai pixel shader Direct2D,
|
||||||
|
menghilangkan transfer GPU->CPU untuk kecepatan
|
||||||
|
tertinggi. Hasil dapat sedikit berbeda karena
|
||||||
|
presisi float32 (opsional/opt-in).
|
||||||
|
--!native : LuaJIT (proses terpisah). Cepat dan identik dengan
|
||||||
|
MoonSharp. Memerlukan folder native yang di-deploy.
|
||||||
|
--!moonsharp : Memaksa mesin MoonSharp klasik.
|
||||||
|
* Jika direktif tidak tersedia/tidak didukung, secara otomatis
|
||||||
|
jatuh ke mesin yang lebih rendah (output tidak pernah rusak).
|
||||||
|
|
||||||
|
o Sintaks yang memenuhi syarat kernel cepat (pemetaan per-piksel murni)
|
||||||
|
Hanya loop bersarang dengan bentuk berikut yang menjadi kernel.
|
||||||
|
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, r2, g2, b2 [, a2])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
- Badan hanya boleh memakai aritmetika, math.*, perbandingan,
|
||||||
|
idiom ambang "cond and nilai1 or nilai2", dan variabel local.
|
||||||
|
- Hanya boleh mereferensikan piksel yang sedang diproses
|
||||||
|
(getpixel(x, y)) dan nilai seperti obj/scene/time.
|
||||||
|
- Apa pun yang memakai sampling tetangga (blur, dll.), penulisan
|
||||||
|
ke koordinat lain, getpixeldata, getobject, operasi
|
||||||
|
tabel/string, atau pernyataan if tidak diubah menjadi kernel dan
|
||||||
|
otomatis berjalan di mesin klasik.
|
||||||
|
|
||||||
|
Contoh (membuat figur putih menjadi merah):
|
||||||
|
--!gpu
|
||||||
|
for y = 0, obj.h - 1 do
|
||||||
|
for x = 0, obj.w - 1 do
|
||||||
|
local r, g, b, a = obj.getpixel(x, y)
|
||||||
|
obj.setpixel(x, y, r, g / 2, b / 2, a)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
- Parameter -
|
- Parameter -
|
||||||
|
|
||||||
Panel efek memiliki 4 trackbar berikut (mendukung animasi).
|
Panel efek memiliki 4 trackbar berikut (mendukung animasi).
|
||||||
@@ -36,6 +90,11 @@
|
|||||||
|
|
||||||
* Setiap trackbar mendukung slider animasi (dengan interpolasi).
|
* Setiap trackbar mendukung slider animasi (dengan interpolasi).
|
||||||
* File .lua dapat diimpor/diekspor dari toolbar editor skrip.
|
* File .lua dapat diimpor/diekspor dari toolbar editor skrip.
|
||||||
|
* Kotak centang (obj.check0 - obj.check3) dan warna (color) muncul di panel efek
|
||||||
|
secara otomatis saat skrip mereferensikannya (trackbar selalu ditampilkan).
|
||||||
|
Penggunaan umum ini tidak disertai deklarasi rentang/nilai default, jadi tangani
|
||||||
|
rentang nilai di dalam skrip. Header --track / --check / --color AviUtl tetap
|
||||||
|
berfungsi seperti sebelumnya.
|
||||||
|
|
||||||
|
|
||||||
- Variabel Global -
|
- Variabel Global -
|
||||||
|
|||||||
@@ -24,6 +24,56 @@
|
|||||||
発生します。不要な場合は呼び出しを省略することで処理を高速化できます。
|
発生します。不要な場合は呼び出しを省略することで処理を高速化できます。
|
||||||
|
|
||||||
|
|
||||||
|
- 実行エンジンと自動高速化 -
|
||||||
|
|
||||||
|
ピクセル処理(getpixel/setpixel の二重ループ)を含むスクリプトは、
|
||||||
|
構文を解析して自動的に高速なエンジンへ振り分けられます。
|
||||||
|
座標・回転・不透明度などの通常スクリプトは従来どおり MoonSharp で
|
||||||
|
実行され、挙動は一切変わりません。
|
||||||
|
|
||||||
|
○自動振り分け(ディレクティブ無しのとき)
|
||||||
|
・自ピクセル完結のピクセル写像(下記条件) → CPU カーネル(高速・厳密)
|
||||||
|
・上記以外のピクセル操作 → ネイティブ(LuaJIT, 配備時のみ)
|
||||||
|
・ピクセル操作なし → MoonSharp
|
||||||
|
|
||||||
|
○エンジン指定ディレクティブ(スクリプト先頭行のコメント)
|
||||||
|
--!cpu : CPU カーネル。式ツリーへ実行時コンパイルして
|
||||||
|
全 CPU コアで並列実行します(MoonSharp と完全一致)。
|
||||||
|
--!gpu : GPU カーネル。Direct2D ピクセルシェーダとして実行し、
|
||||||
|
GPU→CPU 転送を排して最速です。float32 精度のため
|
||||||
|
結果はごく僅かに異なり得ます(オプトイン)。
|
||||||
|
--!native : LuaJIT(別プロセス)。高速かつ MoonSharp と一致。
|
||||||
|
native フォルダの配備が必要です。
|
||||||
|
--!moonsharp : 従来の MoonSharp を強制します。
|
||||||
|
※ 指定が利用不可/非対応の場合は、自動的に下位エンジンへ
|
||||||
|
フォールバックします(出力が壊れることはありません)。
|
||||||
|
|
||||||
|
○高速カーネルが成立する構文(純粋ピクセル写像)
|
||||||
|
次の形の二重ループのみがカーネル化されます。
|
||||||
|
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, r2, g2, b2 [, a2])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
・本体で使えるのは四則演算・math.*・比較・しきい値の
|
||||||
|
「条件 and 値1 or 値2」・local 変数のみです。
|
||||||
|
・参照できるのは処理中の自ピクセル(getpixel(x, y))と
|
||||||
|
obj/scene/time 等の値だけです。
|
||||||
|
・近傍参照(ぼかし等)、別座標への書き込み、getpixeldata、
|
||||||
|
getobject、テーブル/文字列操作、if 文などを含む場合は
|
||||||
|
カーネル化されず、自動的に従来エンジンで実行されます。
|
||||||
|
|
||||||
|
例(白い図形が赤くなる):
|
||||||
|
--!gpu
|
||||||
|
for y = 0, obj.h - 1 do
|
||||||
|
for x = 0, obj.w - 1 do
|
||||||
|
local r, g, b, a = obj.getpixel(x, y)
|
||||||
|
obj.setpixel(x, y, r, g / 2, b / 2, a)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
- パラメータ -
|
- パラメータ -
|
||||||
|
|
||||||
エフェクトパネルには以下の 4 つのトラックバー(アニメーション対応)があります。
|
エフェクトパネルには以下の 4 つのトラックバー(アニメーション対応)があります。
|
||||||
@@ -36,6 +86,10 @@
|
|||||||
|
|
||||||
※各トラックバーはアニメーションスライダーに対応しています(補間あり)。
|
※各トラックバーはアニメーションスライダーに対応しています(補間あり)。
|
||||||
※スクリプトエディタのツールバーから .lua ファイルのインポート/エクスポートが可能です。
|
※スクリプトエディタのツールバーから .lua ファイルのインポート/エクスポートが可能です。
|
||||||
|
※チェック(obj.check0〜obj.check3)とカラー(color)は、スクリプト本体でそれらを
|
||||||
|
参照すると自動的にエフェクトパネルへ表示されます(トラックバーは常に表示)。
|
||||||
|
この一般利用では範囲・既定値の宣言を伴わないため、値はスクリプト内で扱います。
|
||||||
|
--track / --check / --color ヘッダによる宣言表示も従来どおり利用できます。
|
||||||
|
|
||||||
|
|
||||||
- グローバル変数 -
|
- グローバル変数 -
|
||||||
|
|||||||
@@ -24,6 +24,56 @@
|
|||||||
발생합니다. 필요 없는 경우 호출을 생략하면 처리를 빠르게 할 수 있습니다.
|
발생합니다. 필요 없는 경우 호출을 생략하면 처리를 빠르게 할 수 있습니다.
|
||||||
|
|
||||||
|
|
||||||
|
- 실행 엔진과 자동 가속 -
|
||||||
|
|
||||||
|
픽셀 처리(getpixel/setpixel 이중 루프)를 포함하는 스크립트는
|
||||||
|
구문을 분석하여 자동으로 더 빠른 엔진으로 분배됩니다.
|
||||||
|
좌표・회전・불투명도 등 일반 스크립트는 기존과 동일하게 MoonSharp으로
|
||||||
|
실행되며 동작은 전혀 바뀌지 않습니다.
|
||||||
|
|
||||||
|
○ 자동 분배(디렉티브가 없을 때)
|
||||||
|
· 자기 픽셀로 완결되는 픽셀 매핑(아래 조건) → CPU 커널(고속・엄밀)
|
||||||
|
· 위 이외의 픽셀 조작 → 네이티브(LuaJIT, 배치된 경우에만)
|
||||||
|
· 픽셀 조작 없음 → MoonSharp
|
||||||
|
|
||||||
|
○ 엔진 지정 디렉티브(스크립트 첫 줄의 주석)
|
||||||
|
--!cpu : CPU 커널. 식 트리로 런타임 컴파일하여
|
||||||
|
모든 CPU 코어에서 병렬 실행합니다(MoonSharp과 완전 일치).
|
||||||
|
--!gpu : GPU 커널. Direct2D 픽셀 셰이더로 실행하여
|
||||||
|
GPU→CPU 전송을 없애 가장 빠릅니다.
|
||||||
|
float32 정밀도이므로 결과가 아주 약간 다를 수 있습니다(옵트인).
|
||||||
|
--!native : LuaJIT(별도 프로세스). 고속이며 MoonSharp과 일치.
|
||||||
|
native 폴더의 배치가 필요합니다.
|
||||||
|
--!moonsharp : 기존의 MoonSharp을 강제합니다.
|
||||||
|
※ 지정이 사용 불가/미지원인 경우 자동으로 하위 엔진으로
|
||||||
|
폴백합니다(출력이 깨지지 않습니다).
|
||||||
|
|
||||||
|
○ 고속 커널이 성립하는 구문(순수 픽셀 매핑)
|
||||||
|
다음 형태의 이중 루프만 커널화됩니다.
|
||||||
|
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, r2, g2, b2 [, a2])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
· 본문에서 사용할 수 있는 것은 사칙연산・math.*・비교・임계값
|
||||||
|
「조건 and 값1 or 값2」・local 변수뿐입니다.
|
||||||
|
· 참조할 수 있는 것은 처리 중인 자기 픽셀(getpixel(x, y))과
|
||||||
|
obj/scene/time 등의 값뿐입니다.
|
||||||
|
· 이웃 참조(블러 등), 다른 좌표로의 쓰기, getpixeldata,
|
||||||
|
getobject, 테이블/문자열 조작, if 문 등을 포함하는 경우에는
|
||||||
|
커널화되지 않고 자동으로 기존 엔진에서 실행됩니다.
|
||||||
|
|
||||||
|
예(흰색 도형이 빨갛게 됨):
|
||||||
|
--!gpu
|
||||||
|
for y = 0, obj.h - 1 do
|
||||||
|
for x = 0, obj.w - 1 do
|
||||||
|
local r, g, b, a = obj.getpixel(x, y)
|
||||||
|
obj.setpixel(x, y, r, g / 2, b / 2, a)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
- 파라미터 -
|
- 파라미터 -
|
||||||
|
|
||||||
이펙트 패널에는 다음 4개의 트랙바(애니메이션 지원)가 있습니다.
|
이펙트 패널에는 다음 4개의 트랙바(애니메이션 지원)가 있습니다.
|
||||||
@@ -36,6 +86,10 @@
|
|||||||
|
|
||||||
※ 각 트랙바는 애니메이션 슬라이더를 지원합니다(보간 있음).
|
※ 각 트랙바는 애니메이션 슬라이더를 지원합니다(보간 있음).
|
||||||
※ 스크립트 편집기의 툴바에서 .lua 파일을 가져오기/내보내기할 수 있습니다.
|
※ 스크립트 편집기의 툴바에서 .lua 파일을 가져오기/내보내기할 수 있습니다.
|
||||||
|
※ 체크박스(obj.check0〜obj.check3)와 색상(color)은 스크립트 본문에서 참조하면
|
||||||
|
이펙트 패널에 자동으로 표시됩니다(트랙바는 항상 표시). 이 일반 사용은 범위・기본값
|
||||||
|
선언을 동반하지 않으므로 값의 범위는 스크립트 내에서 처리하세요. AviUtl의
|
||||||
|
--track / --check / --color 헤더 선언 표시도 기존과 동일하게 사용할 수 있습니다.
|
||||||
|
|
||||||
|
|
||||||
- 전역 변수 -
|
- 전역 변수 -
|
||||||
|
|||||||
@@ -24,6 +24,55 @@
|
|||||||
不需要时省略调用可加快处理速度。
|
不需要时省略调用可加快处理速度。
|
||||||
|
|
||||||
|
|
||||||
|
- 执行引擎与自动加速 -
|
||||||
|
|
||||||
|
包含像素处理(getpixel/setpixel 双重循环)的脚本会被解析语法,
|
||||||
|
并自动分配到更快的引擎。
|
||||||
|
坐标、旋转、不透明度等普通脚本仍照旧由 MoonSharp 执行,行为不变。
|
||||||
|
|
||||||
|
○ 自动分配(未指定指令时)
|
||||||
|
· 自像素完结的像素映射(见下方条件)→ CPU 内核(高速、精确)
|
||||||
|
· 上述以外的像素操作 → 原生(LuaJIT,仅在已部署时)
|
||||||
|
· 无像素操作 → MoonSharp
|
||||||
|
|
||||||
|
○ 引擎指定指令(脚本首行的注释)
|
||||||
|
--!cpu :CPU 内核。运行时编译为表达式树,
|
||||||
|
在所有 CPU 核心上并行执行(与 MoonSharp 完全一致)。
|
||||||
|
--!gpu :GPU 内核。作为 Direct2D 像素着色器执行,
|
||||||
|
消除 GPU→CPU 传输,速度最快。
|
||||||
|
因 float32 精度,结果可能有极小差异(需主动选用)。
|
||||||
|
--!native :LuaJIT(独立进程)。高速且与 MoonSharp 一致。
|
||||||
|
需要部署 native 文件夹。
|
||||||
|
--!moonsharp :强制使用传统的 MoonSharp。
|
||||||
|
※ 指令不可用/不支持时,会自动回退到较低的引擎
|
||||||
|
(输出不会损坏)。
|
||||||
|
|
||||||
|
○ 可成为高速内核的语法(纯像素映射)
|
||||||
|
只有以下形式的双重循环才会被内核化。
|
||||||
|
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, r2, g2, b2 [, a2])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
· 主体中仅可使用四则运算、math.*、比较、阈值写法
|
||||||
|
“条件 and 值1 or 值2”以及 local 变量。
|
||||||
|
· 仅可引用正在处理的自像素(getpixel(x, y))
|
||||||
|
以及 obj/scene/time 等值。
|
||||||
|
· 含有邻域参照(模糊等)、写入其他坐标、getpixeldata、
|
||||||
|
getobject、表/字符串操作、if 语句等的脚本不会被内核化,
|
||||||
|
会自动由传统引擎执行。
|
||||||
|
|
||||||
|
示例(让白色图形变红):
|
||||||
|
--!gpu
|
||||||
|
for y = 0, obj.h - 1 do
|
||||||
|
for x = 0, obj.w - 1 do
|
||||||
|
local r, g, b, a = obj.getpixel(x, y)
|
||||||
|
obj.setpixel(x, y, r, g / 2, b / 2, a)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
- 参数 -
|
- 参数 -
|
||||||
|
|
||||||
特效面板包含以下 4 个轨道条(支持动画)。
|
特效面板包含以下 4 个轨道条(支持动画)。
|
||||||
@@ -36,6 +85,9 @@
|
|||||||
|
|
||||||
* 每个轨道条均支持动画滑块(含插值)。
|
* 每个轨道条均支持动画滑块(含插值)。
|
||||||
* 可通过脚本编辑器工具栏导入/导出 .lua 文件。
|
* 可通过脚本编辑器工具栏导入/导出 .lua 文件。
|
||||||
|
* 复选框(obj.check0~obj.check3)与颜色(color)会在脚本本体引用它们时
|
||||||
|
自动显示在特效面板中(轨道条始终显示)。该通用用法不带范围・默认值声明,
|
||||||
|
因此请在脚本内处理取值范围。AviUtl 的 --track / --check / --color 头声明显示仍可照常使用。
|
||||||
|
|
||||||
|
|
||||||
- 全局变量 -
|
- 全局变量 -
|
||||||
|
|||||||
@@ -24,6 +24,55 @@
|
|||||||
不需要時省略呼叫可加快處理速度。
|
不需要時省略呼叫可加快處理速度。
|
||||||
|
|
||||||
|
|
||||||
|
- 執行引擎與自動加速 -
|
||||||
|
|
||||||
|
包含像素處理(getpixel/setpixel 雙重迴圈)的腳本會被解析語法,
|
||||||
|
並自動分配到更快的引擎。
|
||||||
|
座標、旋轉、不透明度等一般腳本仍照舊由 MoonSharp 執行,行為不變。
|
||||||
|
|
||||||
|
○ 自動分配(未指定指令時)
|
||||||
|
· 自像素完結的像素映射(見下方條件)→ CPU 核心(高速、精確)
|
||||||
|
· 上述以外的像素操作 → 原生(LuaJIT,僅在已部署時)
|
||||||
|
· 無像素操作 → MoonSharp
|
||||||
|
|
||||||
|
○ 引擎指定指令(腳本首行的註解)
|
||||||
|
--!cpu :CPU 核心。執行時編譯為運算式樹,
|
||||||
|
在所有 CPU 核心上並行執行(與 MoonSharp 完全一致)。
|
||||||
|
--!gpu :GPU 核心。作為 Direct2D 像素著色器執行,
|
||||||
|
排除 GPU→CPU 傳輸,速度最快。
|
||||||
|
因 float32 精度,結果可能有極小差異(需主動選用)。
|
||||||
|
--!native :LuaJIT(獨立程序)。高速且與 MoonSharp 一致。
|
||||||
|
需要部署 native 資料夾。
|
||||||
|
--!moonsharp :強制使用傳統的 MoonSharp。
|
||||||
|
※ 指令不可用/不支援時,會自動回退到較低的引擎
|
||||||
|
(輸出不會損壞)。
|
||||||
|
|
||||||
|
○ 可成為高速核心的語法(純像素映射)
|
||||||
|
只有以下形式的雙重迴圈才會被核心化。
|
||||||
|
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, r2, g2, b2 [, a2])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
· 主體中僅可使用四則運算、math.*、比較、閾值寫法
|
||||||
|
「條件 and 值1 or 值2」以及 local 變數。
|
||||||
|
· 僅可參照正在處理的自像素(getpixel(x, y))
|
||||||
|
以及 obj/scene/time 等值。
|
||||||
|
· 含有鄰域參照(模糊等)、寫入其他座標、getpixeldata、
|
||||||
|
getobject、表/字串操作、if 陳述式等的腳本不會被核心化,
|
||||||
|
會自動由傳統引擎執行。
|
||||||
|
|
||||||
|
範例(讓白色圖形變紅):
|
||||||
|
--!gpu
|
||||||
|
for y = 0, obj.h - 1 do
|
||||||
|
for x = 0, obj.w - 1 do
|
||||||
|
local r, g, b, a = obj.getpixel(x, y)
|
||||||
|
obj.setpixel(x, y, r, g / 2, b / 2, a)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
- 參數 -
|
- 參數 -
|
||||||
|
|
||||||
特效面板包含以下 4 個軌道條(支援動畫)。
|
特效面板包含以下 4 個軌道條(支援動畫)。
|
||||||
@@ -36,6 +85,9 @@
|
|||||||
|
|
||||||
* 每個軌道條均支援動畫滑桿(含插值)。
|
* 每個軌道條均支援動畫滑桿(含插值)。
|
||||||
* 可透過腳本編輯器工具列匯入/匯出 .lua 檔案。
|
* 可透過腳本編輯器工具列匯入/匯出 .lua 檔案。
|
||||||
|
* 核取方塊(obj.check0~obj.check3)與顏色(color)會在腳本本體參照它們時
|
||||||
|
自動顯示於特效面板中(軌道條始終顯示)。此通用用法不帶範圍・預設值宣告,
|
||||||
|
因此請在腳本內處理取值範圍。AviUtl 的 --track / --check / --color 標頭宣告顯示仍可照常使用。
|
||||||
|
|
||||||
|
|
||||||
- 全域變數 -
|
- 全域變數 -
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
|||||||
|
|
||||||
### 1. スクリプトエンジン
|
### 1. スクリプトエンジン
|
||||||
|
|
||||||
スクリプトの実行エンジンには MoonSharp(Lua 5.2 互換)を使用しています。加えて、ピクセル操作(`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata`)を含むスクリプトは、同梱した高速ランタイム(LuaJIT)で自動的に実行され、大幅に高速化されます(詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照)。どちらのエンジンでも利用可能な標準ライブラリは以下に限定されています。
|
スクリプトの実行エンジンには MoonSharp(Lua 5.2 互換)を使用しています。加えて、自ピクセル完結のピクセル写像(`obj.getpixel` で読み取り `obj.setpixel` で書き戻す二重ループ)は構文解析で検出して **CPU カーネル(式ツリー)** または **GPU カーネル(Direct2D ピクセルシェーダ)** へ実行時コンパイルして高速化し、それ以外のピクセル操作を含むスクリプトは同梱の高速ランタイム(**LuaJIT**)で自動実行されます(詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照)。いずれのエンジンでも利用可能な標準ライブラリは以下に限定されています。
|
||||||
|
|
||||||
- `table`、`string`、`math`、`bit32`
|
- `table`、`string`、`math`、`bit32`
|
||||||
- 基本関数: `type`、`tostring`、`tonumber`、`select`、`error`、`assert`、`print`、`ipairs`、`pairs`、`next`、`unpack`、`setmetatable`、`getmetatable`、`rawget`、`rawset`、`rawequal`、`rawlen`、`pcall`、`xpcall`
|
- 基本関数: `type`、`tostring`、`tonumber`、`select`、`error`、`assert`、`print`、`ipairs`、`pairs`、`next`、`unpack`、`setmetatable`、`getmetatable`、`rawget`、`rawset`、`rawequal`、`rawlen`、`pcall`、`xpcall`
|
||||||
@@ -110,7 +110,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
|||||||
- **`obj.putpixeldata()`**: 互換性のために定義された空実装関数です。`setpixel` / `PixelDataProxy:set` による変更は自動的に反映されるため、呼び出す必要はありません。
|
- **`obj.putpixeldata()`**: 互換性のために定義された空実装関数です。`setpixel` / `PixelDataProxy:set` による変更は自動的に反映されるため、呼び出す必要はありません。
|
||||||
`getpixel` / `setpixel` / `getpixeldata` のいずれかを最初に呼び出した時点で、GPU 上の画像データを CPU 側へ転送する処理が一度だけ発生します。ピクセル操作を行わないスクリプトではこの転送は発生しません。
|
`getpixel` / `setpixel` / `getpixeldata` のいずれかを最初に呼び出した時点で、GPU 上の画像データを CPU 側へ転送する処理が一度だけ発生します。ピクセル操作を行わないスクリプトではこの転送は発生しません。
|
||||||
|
|
||||||
これらのピクセル操作を含むスクリプトは、同梱の高速ランタイム(LuaJIT)で自動的に実行され、従来エンジンに比べて大幅(内部計測で数十倍)に高速化されます。出力結果は従来エンジンと一致します。詳細・制約は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照してください。
|
これらのピクセル操作を含むスクリプトは自動的に高速化されます。自ピクセル完結のピクセル写像は CPU カーネル(式ツリー)または GPU カーネル(Direct2D ピクセルシェーダ)へ、それ以外は高速ランタイム(LuaJIT)へ自動で振り分けられ、いずれも従来エンジンに比べて大幅(内部計測で数十倍)に高速化されます。CPU カーネルと LuaJIT の出力結果は従来エンジンと一致します(GPU カーネルのみ float32 精度のためごく僅かに異なり得ます)。詳細・制約は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照してください。
|
||||||
|
|
||||||
### 4. scene テーブルと ymm4 テーブル
|
### 4. scene テーブルと ymm4 テーブル
|
||||||
|
|
||||||
@@ -174,7 +174,9 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
|||||||
|
|
||||||
### 6. トラックバー(Track0〜Track3)
|
### 6. トラックバー(Track0〜Track3)
|
||||||
|
|
||||||
エフェクトパネルには 4 本のトラックバー(アニメーション対応)があり、各値はスクリプト内で `obj.track0`〜`obj.track3` として参照できます。スライダー表示範囲はいずれも -100〜100、デフォルト値は 0、表示形式は小数点以下2桁です。
|
エフェクトパネルには 4 本のトラックバー(アニメーション対応)があり、各値はスクリプト内で `obj.track0`〜`obj.track3` として参照できます。スライダー表示範囲はいずれも -100〜100、デフォルト値は 0、表示形式は小数点以下2桁です。トラックバーは常に表示されます。
|
||||||
|
|
||||||
|
チェックボックス(`obj.check0`〜`obj.check3`)とカラーピッカー(`color`)は、スクリプト本体でそれらを参照すると自動的にエフェクトパネルへ表示されます(参照を消すと非表示に戻ります)。これにより、`--` ヘッダを書かなくても必要な入力欄だけを出せます。なお、この一般利用ではスライダーのようなラベル・範囲・既定値の宣言は伴わないため、値の範囲はスクリプト内で扱ってください。AviUtl 互換の `--track`/`--check`/`--color` ヘッダによる宣言表示は従来どおり利用できます([AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。
|
||||||
|
|
||||||
### 7. スクリプトエディタの支援機能
|
### 7. スクリプトエディタの支援機能
|
||||||
|
|
||||||
@@ -203,13 +205,13 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
|||||||
- `--track0:`〜`--track3:` … トラックバーの値は従来どおり `obj.track0`〜`obj.track3` から参照します(ラベル・範囲・既定値の UI 反映は行いません)。
|
- `--track0:`〜`--track3:` … トラックバーの値は従来どおり `obj.track0`〜`obj.track3` から参照します(ラベル・範囲・既定値の UI 反映は行いません)。
|
||||||
- **`@` による複数セクション**: 1 つのスクリプトに `@名前` で複数の効果が定義されている場合、先頭のセクションのみを実行します。
|
- **`@` による複数セクション**: 1 つのスクリプトに `@名前` で複数の効果が定義されている場合、先頭のセクションのみを実行します。
|
||||||
- **`obj.rand(st, ed [, seed [, frame]])`**: 指定範囲(`st`〜`ed`)の整数を返す決定論的な乱数です。`seed` と `frame` が同じであれば常に同じ値を返し、`frame` を省略すると現在のフレームを用います。従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)で同じ値を返します。
|
- **`obj.rand(st, ed [, seed [, frame]])`**: 指定範囲(`st`〜`ed`)の整数を返す決定論的な乱数です。`seed` と `frame` が同じであれば常に同じ値を返し、`frame` を省略すると現在のフレームを用います。従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)で同じ値を返します。
|
||||||
- **`obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])`**: 円・四角形・三角形・五角形・六角形・星形を生成し、オブジェクトのバッファを置き換えて描画します(出力は図形サイズに合わせて生成され、中心に配置されます)。`ライン` を省略するか `0` で塗りつぶし、サイズ以上の値でも塗りつぶしになります。`アスペクト`(-1.0〜1.0)で幅・高さを歪曲できます。`figure` 以外の対象は本バージョンでは対象外です。描画系 API を含むスクリプトは従来エンジン(MoonSharp)で実行されます。
|
- **`obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])`**: 円・四角形・三角形・五角形・六角形・星形を生成し、オブジェクトのバッファを置き換えて描画します(出力は図形サイズに合わせて生成され、中心に配置されます)。`ライン` を省略するか `0` で塗りつぶし、サイズ以上の値でも塗りつぶしになります。`アスペクト`(-1.0〜1.0)で幅・高さを歪曲できます。
|
||||||
|
- **描画・メディア・バッファ・オプション API**: `obj.draw` / `obj.drawpoly` による描画合成、`obj.load` の `"text"` / `"image"` / `"movie"`、`obj.setfont`、`obj.copybuffer`、`obj.effect`、`obj.getvalue`、`obj.setoption` / `obj.getoption` / `obj.pixeloption` に対応しています。これらは従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。
|
||||||
|
|
||||||
次のような機能は、本体の描画パイプラインへの統合を要するため、この互換層では対象外です(呼び出しを含むスクリプトは意図どおりには動作しません)。
|
次のような機能は、この互換層では対象外です(呼び出しを含むスクリプトは意図どおりには動作しません)。
|
||||||
|
|
||||||
- 描画・合成(`obj.draw` / `obj.drawpoly`)、`obj.load` の `"figure"` 以外の対象(画像ファイル・`"text"`・`"movie"` など)、および `obj.setfont`
|
- `obj.setanchor`、`scene.set` / `scene.get` などの未実装関数
|
||||||
- フィルタ効果やバッファ操作(`obj.effect` / `obj.copybuffer` / `obj.setoption` など)
|
- `require` によるモジュール読み込み、`io` / `dofile` などの任意ファイルアクセス(`obj.load("image"/"movie")` のみ、先頭ヘッダー検証付きで対応)
|
||||||
- `require` によるモジュール読み込み、`io` などのファイルアクセス
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -217,16 +219,23 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
|||||||
|
|
||||||
### 実行エンジンの自動振り分け
|
### 実行エンジンの自動振り分け
|
||||||
|
|
||||||
スクリプトは内容に応じて 2 つのエンジンへ自動的に振り分けられます。
|
スクリプトは内容に応じて 4 つのエンジンへ自動的に振り分けられます。
|
||||||
|
|
||||||
- **ピクセル操作を含むスクリプト**(`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` を含む)→ 同梱の高速ランタイム **LuaJIT** で実行(ネイティブ実行)。
|
- **自ピクセル完結のピクセル写像**(`for y … for x … obj.getpixel … obj.setpixel … end end` の形)→ **CPU カーネル(式ツリー)** へ実行時コンパイルして実行。
|
||||||
|
- **上記以外のピクセル操作を含むスクリプト**(`obj.getpixeldata` や近傍参照・別座標書き込みなど)→ 同梱の高速ランタイム **LuaJIT** で実行(ネイティブ実行)。
|
||||||
- **変形のみのスクリプト** → 従来の **MoonSharp** で実行。
|
- **変形のみのスクリプト** → 従来の **MoonSharp** で実行。
|
||||||
|
|
||||||
スクリプトの先頭行に次のディレクティブを書くと、エンジンを明示指定できます。
|
スクリプトの先頭行に次のディレクティブを書くと、エンジンを明示指定できます。
|
||||||
|
|
||||||
|
- `--!cpu` … CPU カーネル(式ツリー)で実行。全 CPU コアで並列実行し、出力は MoonSharp とビット単位で一致します。
|
||||||
|
- `--!gpu` … GPU カーネル(Direct2D ピクセルシェーダ)で実行。GPU→CPU 転送を排して最速ですが、float32 精度のため結果はごく僅かに異なり得ます(オプトイン)。
|
||||||
- `--!native` … 高速ランタイム(LuaJIT)で実行
|
- `--!native` … 高速ランタイム(LuaJIT)で実行
|
||||||
- `--!moonsharp` … 従来エンジン(MoonSharp)で実行
|
- `--!moonsharp` … 従来エンジン(MoonSharp)で実行
|
||||||
|
|
||||||
|
いずれのディレクティブも、利用不可・非対応の場合は出力を壊さずに下位のエンジンへ自動的にフォールバックします(例:`--!gpu` の初期化に失敗した場合は CPU カーネル、さらに MoonSharp へ縮退します)。
|
||||||
|
|
||||||
|
CPU / GPU カーネルが成立するのは、四則演算・`math.*`・比較・しきい値の「条件 and 値1 or 値2」・`local` 変数のみを使い、処理中の自ピクセル(`obj.getpixel(x, y)`)と `obj` / `scene` / `time` 等の値だけを参照する純粋な写像(色変換・グレースケール・ガンマ・しきい値・チャンネル混合など)の場合です。近傍参照(ぼかし等)・別座標への書き込み・`getpixeldata`・`getobject`・テーブル/文字列操作・`if` 文などを含む場合はカーネル化されず、自動的に LuaJIT または MoonSharp で実行されます。コンパイル済みのカーネルはスクリプト本文をキーにキャッシュされ、初回フレームのみコンパイルコストを払います。
|
||||||
|
|
||||||
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で受け渡されます。スクリプトが無限ループに陥った場合でも **5 秒のタイムアウトでプロセスを強制終了**するため本体は固まらず、終了後は自動的に復帰します。出力結果は従来エンジンと一致します。
|
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で受け渡されます。スクリプトが無限ループに陥った場合でも **5 秒のタイムアウトでプロセスを強制終了**するため本体は固まらず、終了後は自動的に復帰します。出力結果は従来エンジンと一致します。
|
||||||
|
|
||||||
`obj.getobject` はネイティブ実行でも利用できます。呼び出し時に本体プロセスへ同期的に問い合わせてシーンオブジェクトを解決するため、従来エンジンと同じ結果を返します。同じタグ・同じフレームへの連続した問い合わせはフレーム内でキャッシュされ、2 回目以降は往復を行いません。
|
`obj.getobject` はネイティブ実行でも利用できます。呼び出し時に本体プロセスへ同期的に問い合わせてシーンオブジェクトを解決するため、従来エンジンと同じ結果を返します。同じタグ・同じフレームへの連続した問い合わせはフレーム内でキャッシュされ、2 回目以降は往復を行いません。
|
||||||
@@ -348,7 +357,7 @@ obj.alpha = anim.ease_out(t) * 255
|
|||||||
- **AviUtl 互換は部分的**: AviUtl のアニメーション効果スクリプトのうち、変形・不透明度・乱数の範囲のみ実行できます([AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。描画・フィルタ・ファイルアクセス系の関数、および AviUtl 向けの EXO 出力(`.exo`)には対応していません。
|
- **AviUtl 互換は部分的**: AviUtl のアニメーション効果スクリプトのうち、変形・不透明度・乱数の範囲のみ実行できます([AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。描画・フィルタ・ファイルアクセス系の関数、および AviUtl 向けの EXO 出力(`.exo`)には対応していません。
|
||||||
- **実行タイムアウト**: スクリプトの実行は 5000ms(5秒)でタイムアウトし、超過した場合は強制終了されエラーとして扱われます。無限ループが発生しないよう注意してください。
|
- **実行タイムアウト**: スクリプトの実行は 5000ms(5秒)でタイムアウトし、超過した場合は強制終了されエラーとして扱われます。無限ループが発生しないよう注意してください。
|
||||||
- **利用可能な標準ライブラリの制限**: `table`、`string`、`math`、`bit32` および基本関数のみ利用できます。`io`、`os`、`debug`、`ffi`、`require` は利用できません。
|
- **利用可能な標準ライブラリの制限**: `table`、`string`、`math`、`bit32` および基本関数のみ利用できます。`io`、`os`、`debug`、`ffi`、`require` は利用できません。
|
||||||
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは高速ランタイム(LuaJIT)で自動実行され大幅に高速化されます。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
|
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します(GPU カーネルはこの転送を行いません)。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは内容に応じて CPU カーネル・GPU カーネル・高速ランタイム(LuaJIT)のいずれかで自動実行され大幅に高速化されます。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
|
||||||
- **`math.random` はフレームごとの決定論的な乱数**: 毎フレーム `frame` の値でシードし直されるため、同一フレームでは常に同じ値になります。フレームをまたいで変化する乱数的な値が必要な場合は `anim.rand` の利用を検討してください。
|
- **`math.random` はフレームごとの決定論的な乱数**: 毎フレーム `frame` の値でシードし直されるため、同一フレームでは常に同じ値になります。フレームをまたいで変化する乱数的な値が必要な場合は `anim.rand` の利用を検討してください。
|
||||||
- **`obj.oz` は出力に反映されません**: スクリプト実行後にコンテキストへ読み戻されますが、現在の実装では中心点オフセットの出力計算に使用されていません。
|
- **`obj.oz` は出力に反映されません**: スクリプト実行後にコンテキストへ読み戻されますが、現在の実装では中心点オフセットの出力計算に使用されていません。
|
||||||
- **エクスポートは先頭の1件のみ**: 複数アイテムを選択した状態でも、エクスポートされるスクリプトは先頭のアイテムのもののみです(インポート・クリアは選択中のすべてのアイテムに適用されます)。
|
- **エクスポートは先頭の1件のみ**: 複数アイテムを選択した状態でも、エクスポートされるスクリプトは先頭のアイテムのもののみです(インポート・クリアは選択中のすべてのアイテムに適用されます)。
|
||||||
|
|||||||
新しいイシューから参照
ユーザーをブロックする