コミットを比較

..
13 コミット
作成者 SHA1 メッセージ 日付
routersys de6472c34b バージョンをv1.12.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.12.0 のコミットから作成しました
2026-07-02 19:54:36 +09:00
routersys 55c8bffb70 SIMD経路の採用を初回フレームの実測で自動判定 2026-07-02 19:52:59 +09:00
routersys 8ca66bceb8 ネイティブ画素転送をD2DステージングとMMFの直結へ変更 2026-07-02 19:28:01 +09:00
routersys 865f5117ea カーネル抽出の検査漏れとfmodの剰余実装を修正 2026-07-02 19:04:05 +09:00
routersys b30f7a818b drawリングの読み出し件数を容量へクランプ 2026-07-02 19:03:41 +09:00
routersys 95786a1f0a getpixeldataの遅延書き込みをフレーム置換時に破棄 2026-07-02 19:03:23 +09:00
routersys cc07e2a83d CPUカーネルにVector256のSIMD経路を追加 2026-07-02 18:36:43 +09:00
routersys 08e5e432b7 getpixeldata添字ループをカーネル抽出へ対応 2026-07-02 17:48:59 +09:00
routersys 1e9b039cef draw/drawpolyをMMFリングバッファでバッチ化 2026-07-02 17:26:12 +09:00
routersys bad39fe0db getpixeldataをストレートFFI配列の遅延反映へ変更 2026-07-02 14:39:22 +09:00
routersys a5567a804d copybufferの複製をバッファ再利用へ変更 2026-07-02 14:20:01 +09:00
routersys a9cb4a9cda RenderKeyのスクリプト比較を参照バージョンへ変更 2026-07-02 14:17:57 +09:00
routersys 9e9b5277af スクリプト本文をバージョンスタンプで変更時のみ転送 2026-07-02 14:16:09 +09:00
22個のファイルの変更、1641行の追加、310行の削除

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

+131 -47
ファイルの表示
@@ -1,75 +1,159 @@
# v1.11.4 - Lua スクリプト for YMM4 # v1.12.0 - Lua スクリプト for YMM4
毎ピクセル処理のスクリプト(カーネル)の実行先を、GPU と CPU から自動で選べるように ネイティブレーンとカーネルの性能をまとめて引き上げたリリースです。プロセス間の
したリリースです。これまで GPU カーネルは `--!gpu` を明示したときだけ使っていましたが、 画素転送、draw 呼び出しの往復、スクリプト本文の転送と比較、getpixeldata の実装、
指定が無いときも利用できるかを自動で判断し、利用できる場合は GPU で実行します。正確性を CPU カーネルの命令並列という経路ごとの無駄を系統的に削りました。あわせて、
最優先し、初回に実機の GPU で CPU カーネルとの出力一致を検証し、許容差に収まった カーネル抽出の検査漏れや math.fmod の剰余の種類など、結果の正しさに関わる不具合を
プログラムだけ GPU で実行します。あわせて、GPU カーネルと CPU カーネルで食い違って 修正しました。全体の設計は「識別子と版数による変更検知」と「消費される境界での
いた HLSL の座標原点と出力の丸めを、CPU カーネルに合わせて修正しました。 遅延実体化」で統一しています。
--- ---
## 改善 ## 改善
### 1. カーネルの GPU/CPU 自動選択 ### 1. ネイティブレーンの画素転送を直結化
これまで毎ピクセル処理のスクリプトは、`--!gpu` を明示したときだけ GPU カーネルで実行し、 ネイティブレーンでは、Direct2D のステージングビットマップと共有メモリの間に中間の
指定が無いときは CPU カーネルで実行していました。本リリースでは、指定が無いときも バッファを挟んでいたため、入力の転送で 2 回、結果の読み戻しで 2 回の複製が毎フレーム
GPU カーネルを利用できるかを自動で判断し、利用できる場合は GPU で実行します。GPU 発生していました。本リリースでは両者をポインタで直結し、入力はステージングの Map から
カーネルは CPU カーネルが必要とするピクセルの読み戻しとアップロードを伴わないため、 共有メモリへ、結果は共有メモリから出力ビットマップの CopyFromMemory へ、それぞれ
そのぶん高速です。実行先はプログラム単位で一度だけ決まり、フレームや画像サイズによって 1 回の複製で転送します。
切り替わらないため、途中で結果がちらつくことはありません。
### 2. 実行時のセルフ検証で正確性を担保 1920×1080 の BGRA フレームは約 8.3MB で、複製量は毎フレーム約 33MB から約 17MB へ
半減します。開発機の実測ではこの規模の複製 1 回が約 0.4ms なので、画素を書き換える
スクリプトで 1 フレームあたり約 0.8ms、4K では単純比例で約 3.2ms を複製から削れる
計算です。draw 合成やバッファ置換のように従来形式のバッファが必要な経路に限り、
そこでだけ実体化します。
GPU カーネルを初めて構築したとき、固定の 64×64 の検証用画像を実機の GPU で処理し、 ### 2. draw と drawpoly の呼び出しをリングバッファで一括化
その結果を CPU カーネルの結果と比較します。全チャンネルの差が許容範囲に収まった
プログラムだけを GPU で実行し、収まらない場合や検証を実行できない場合は CPU カーネルで ネイティブレーンの obj.draw と obj.drawpoly は、1 回の呼び出しごとにプロセス間の
実行します。GPU の出力が CPU カーネルと食い違うことはありません。検証の結果はログに イベント往復を行っていました。本リリースでは共有メモリ上のリングバッファへ書き溜め、
記録します。 容量の 4096 件に達したときと実行の終わりにまとめて回収します。1 フレームに 1000 回
draw するスクリプトなら、往復は 1000 回から 1 回になります。
### 3. getpixeldata を平坦な配列の遅延反映へ変更
ネイティブレーンの getpixeldata は、添字 1 回の読み書きごとに座標の分解と除算、
乗算済み表現との変換を行っていました。本リリースでは取得時に全画素を一度だけ
変換して平坦な配列を作り、以後の読み書きは配列参照 1 回になります。書き込みは
putpixeldata または次の画素操作の時点でまとめてフレームへ反映します。1920×1080 の
全画素を添字で走査すると約 830 万回のアクセスになるため、1 回あたりの費用の削減が
そのまま効きます。
### 4. getpixeldata の添字ループをカーネルとして実行
getpixeldata で得た画素を添字のループで書き換える定型を、getpixel と setpixel の
定型と同じようにカーネルとして抽出し、CPU カーネルで実行するようにしました。従来
この形はネイティブレーンで実行され、ワーカーへの画素転送を伴っていました。抽出後は
転送そのものが不要になります。出力は MoonSharp とバイト単位で一致します。
### 5. CPU カーネルに SIMD の実行経路を追加し、採用を実測で自動判定
CPU カーネルに Vector256 で 4 画素を同時に評価するブロック経路を追加しました。
倍精度で完全一致を保てる加減乗除、床剰余、符号反転、abs、floor、ceil、sqrt、比較と
選択だけを対象とし、min や max、pow、三角関数を含むカーネルは従来のスカラ経路で
実行します。出力はスカラ経路とバイト単位で一致します。
SIMD が有利かどうかはカーネルの内容と実行環境に依存し、並列実行でメモリ帯域が
飽和する環境では不利になる場合すらあります。そこで GPU カーネルのセルフ検証と同じ
流儀で、採用を実測で自動判定します。最初の数フレームで両経路を交互に実行して時間を
計測し、各経路の初回は JIT の暖機として計測から除いたうえで、速かった経路を
プログラム単位で恒久採用します。両経路の出力はバイト単位で一致するため、判定中の
切り替えが結果に現れることはありません。
開発機の 1920×1080 での実測では、単一スレッドの評価はグレースケール相当のカーネルで
約 1.6 倍から 2 倍、比較選択を多く含む重いカーネルで約 1.2 倍から 1.5 倍になりました。
フレーム全体の処理は行単位の並列実行でメモリ帯域が支配的になるため差は縮まり、
判定前の強制 SIMD では重いカーネルが約 2 割遅くなる場合がありましたが、自動判定に
よって常に速い側の経路で実行されます。
### 6. スクリプト本文の転送と比較を変更検知へ変更
ネイティブレーンはスクリプト本文を毎フレーム UTF-8 へ変換して共有メモリへ書き込んで
いました。本文は最大 128KB あるため、変換と複製と配列の割り当てが毎フレーム発生して
いました。本リリースでは本文へ版数を振り、変更したフレームだけ転送します。ワーカー側の
コンパイル結果も版数で保持し、同じ本文の再コンパイルを行いません。
フレームキャッシュの鍵も同様に、スクリプト本文の文字列比較から参照の版数比較へ
変更しました。長いスクリプトほど毎フレームの比較費用が大きかったため、これも定数時間に
なります。
### 7. copybuffer の複製でバッファを再利用
MoonSharp レーンの obj.copybuffer は、コピーのたびに新しい配列を割り当てていました。
寸法が同じ間は既存の配列へ上書きするように変更し、毎フレーム呼び出すスクリプトの
GC 圧力を取り除きました。
--- ---
## 不具合修正 ## 不具合修正
### GPU カーネルの座標原点のずれを修正 ### getpixeldata の未反映の書き込みをフレーム置換時に破棄
GPU カーネルの HLSL は、ピクセル座標を「テクスチャ座標 × 寸法」で求めていました。 obj.load や obj.copybuffer でフレームが置き換わった直後に、置換前の getpixeldata へ
テクスチャ座標はピクセルの中心を指すため、求まる座標は CPU カーネルが用いる整数の 書き込んだ未反映の内容が新しいフレームへ流し込まれることがありました。フレームの
添字より 0.5 大きく、ループ変数 `x`・`y` を参照するスクリプトで結果がずれていました。 置換時に未反映の書き込みを破棄するように修正しました。
テクスチャ座標から 0.5 を引くように変更し、CPU カーネルの整数座標と一致させました。
### GPU カーネルの出力の丸めを修正 ### getpixeldata の色の復元順序を getpixel と統一
Direct2D は出力を四捨五入で 8 ビットへ量子化する一方、CPU カーネルは切り捨てていた MoonSharp レーンの getpixeldata が乗算済み表現から色を復元する際の計算順序が
ため、両者に系統的な 1 階調のずれがありました。シェーダ側で各チャンネルを切り捨てて getpixel と食い違っており、丸めで 1 階調ずれる可能性がありました。getpixel の順序へ
から量子化するように変更し、丸め方を CPU カーネルへ統一しました。 統一し、MoonSharp、ネイティブ、カーネルの三経路が同じ結果を返すようにしました。
### カーネル抽出の検査漏れを修正
ループ変数や getpixeldata の参照名を内側のローカル変数が同じ名前で覆い隠す
スクリプトを誤って抽出し、結果が変わる可能性がありました。該当する形の抽出を拒否し、
従来の経路で実行するように修正しました。あわせて、getpixeldata への書き込み値が
0 から 255 へ収められずにカーネル化されていた点を、MoonSharp と同じ挙動へ修正
しました。
### math.fmod の剰余の種類を修正
カーネル実行の math.fmod が床方式の剰余で計算されており、負の値を渡したときに
Lua の math.fmod と符号の異なる結果を返していました。被除数の符号を保つ切り捨て
方式へ修正し、MoonSharp およびネイティブレーンと一致させました。
### draw リングの読み出し件数を容量へ制限
ホストが共有メモリ上の draw の件数をそのまま信頼していたため、値が壊れた場合に
リングの範囲外を読み出す可能性がありました。件数を容量で制限するように修正しました。
--- ---
## 互換性・後方互換 ## 互換性・後方互換
- スクリプトの書き方と API に変更はありません。 - スクリプトの書き方と API に変更はありません。
- `--!cpu` は従来どおり CPU カーネルで実行します。`--!gpu` は GPU カーネルで実行しますが、 - カーネル実行で math.fmod を負の値に使っている場合は結果が変わります。従来の結果が
検証に通らない場合は CPU カーネルへ切り替え、一度だけ警告を記録します。 誤りで、修正後は MoonSharp と同じ結果になります。
- 指定の無いカーネルは、検証に通れば GPU、通らなければ CPU で実行します。いずれも - SIMD 経路の出力はスカラ経路とバイト単位で一致します。対象外の演算を含むカーネルは
出力は CPU カーネルと許容差の範囲で一致します。 従来のスカラ経路で実行するため、出力の正しさに妥協はありません。採用の自動判定は
- GPU カーネルは浮動小数点で計算するため、CPU カーネルと 1 階調程度異なることが 実行時間だけを比較するもので、どちらの経路が選ばれても結果は同一です。
あります。この差が許容範囲に収まることを検証で確認したプログラムだけを GPU で - getpixeldata の書き込みがフレームへ反映されるのは putpixeldata または次の画素操作の
実行します。 時点になりましたが、読み出しの直前に必ず反映されるため、観測できる結果は変わり
- GPU を利用できない環境では、従来どおり CPU カーネルで実行します。 ません。
- ネイティブ実行環境が無い場合は、従来どおり MoonSharp で実行します。
--- ---
## 内部実装 ## 内部実装
- `HlslKernelEmitter` の座標を「テクスチャ座標 × 寸法 - 0.5」へ、出力の各チャンネルを - 転送の契約を PixelRegionAccess へ統一し、LuaJitWorker と PixelBufferManager を
`floor(clamp(...))` へ変更し、CPU カーネルの整数座標と切り捨てへ揃えました。 ポインタで直結しました。ワーカーが報告する結果寸法は共有メモリの容量で検査し、
- `GpuKernel` へ `Verify` を追加しました。検証用画像を効果で描画して読み戻し、 アップロード中に例外が起きた場合はワーカーを破棄して次回の実行で再起動します。
`CpuKernel` の結果と比較します。差が許容範囲に収まらない場合は GPU カーネルを - NativeProtocol へ draw リング領域とスクリプト版数のヘッダを追加しました。リングは
採用しません。 1 件 24 個の倍精度値で 4096 件です。
- `LuaScriptEffectProcessor` の `GetGpuKernel` は検証に通った GPU カーネルだけを返し、 - worker.lua が getpixeldata の平坦な配列と遅延反映、リングへの書き溜めを行います。
判定をプログラム単位でキャッシュします。`ExecuteKernelLane` は指定が無いときと - SimdKernelCompiler が式木から Vector256 のブロック委譲を生成し、CpuKernel が
`--!gpu` のときに検証済みの GPU カーネルを優先し、無ければ CPU カーネルで実行します。 4 画素単位のブロックと端数のスカラ処理を組み合わせます。ClampByte は Math.Clamp の
- テストへ HLSL の座標原点と出力の丸めを検証するケースを追加しました(全 2994 件)。 分岐順序を ConditionalSelect で再現し、byte への変換もスカラと同一です。
GPU カーネルの実行と検証は実機の GPU が必要なため、YMM4 上での確認が対象です。 - CpuKernel の自己校正は、経路ごとに暖機 1 回と計測 3 回を交互に行い、累積時間の
短い経路を採用します。判定はカーネルのインスタンスごとに一度だけ行い、以後は
分岐しません。
- KernelExtractor が getpixeldata の添字ループの定型を認識します。
- テストは 3041 件です。v1.11.4 の 2994 件から、リングの順序と容量、遅延反映の整合、
SIMD とスカラの一致、採用判定の収束と交互計測、抽出の拒否、転送領域の容量保証
などの検証を追加しました。
Direct2D の実描画を伴う直結転送の最終確認は、従来の GPU 経路と同様に YMM4 上が
対象です。
+1 -1
ファイルの表示
@@ -1,5 +1,5 @@
======================================== ========================================
Luaスクリプト for YMM4 v1.11.4 Luaスクリプト for YMM4 v1.12.0
======================================== ========================================
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
ピクセルを直接制御できるプラグインです。 ピクセルを直接制御できるプラグインです。
+79
ファイルの表示
@@ -21,6 +21,8 @@ namespace LuaScript.Tests
[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) 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,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")] [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")]
[InlineData("local x=99 local k=3 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,x/obj.w*255+k,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,math.fmod(r,64),math.fmod(g,7)*36,math.fmod(b-128,60)+128,a) end end")]
public void CpuKernelMatchesMoonSharp(string script) public void CpuKernelMatchesMoonSharp(string script)
{ {
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height }; var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
@@ -38,6 +40,31 @@ namespace LuaScript.Tests
AssertEquivalent(script, fields, globals); AssertEquivalent(script, fields, globals);
} }
[Theory]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,255-r) pd:set(i+2,255-g) pd:set(i+3,255-b) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,obj.h-1 do for x=0,obj.w-1 do local i=(y*obj.w+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) local l=0.298912*r+0.586611*g+0.114478*b pd:set(i+1,l) pd:set(i+2,l) pd:set(i+3,l) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,b) pd:set(i+2,g) pd:set(i+3,r) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,obj.h-1 do for x=0,obj.w-1 do local i=(y*obj.w+x)*4 local r=pd:get(i+1) local a=pd:get(i+4) pd:set(i+1,r*a/255) pd:set(i+2,pd:get(i+2)*obj.track0/100) pd:set(i+3,math.min(255,pd:get(i+3)+50)) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,r*3) pd:set(i+2,g-300) pd:set(i+3,b*2-255) end end")]
public void GetPixelDataKernelMatchesMoonSharp(string script)
{
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height, ["track0"] = 73d };
AssertEquivalent(script, fields, new Dictionary<string, double>());
}
[Theory]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 pd:set(i+4,128) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 pd:set(i+1,pd:get(i+5)) pd:set(i+2,0) pd:set(i+3,0) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=((y+1)*pd.width+x)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 pd:set(i+1,pd:get(i+3)) pd:set(i+2,pd:get(i+2)) pd:set(i+3,pd:get(i+1)) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local i=i+4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for pd=0,pd.width-1 do local i=(y*2+pd)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local pd=0 pd:set(i+1,0) end end")]
public void GetPixelDataNonKernelScriptsAreRejected(string script)
{
Assert.Null(KernelExtractor.TryExtract(script));
}
[Theory] [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("--!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("--!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")]
@@ -107,6 +134,8 @@ namespace LuaScript.Tests
private static void RunMoonSharp(string script, byte[] buffer, Dictionary<string, double> fields, Dictionary<string, double> globals) 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 engine = new Script(CoreModules.Basic | CoreModules.Math | CoreModules.Bit32);
engine.Globals.Get("math").Table["fmod"] = DynValue.NewCallback((_, a) =>
DynValue.NewNumber(a[0].Number % a[1].Number));
var obj = new Table(engine); var obj = new Table(engine);
foreach (var (name, value) in fields) foreach (var (name, value) in fields)
obj[name] = value; obj[name] = value;
@@ -134,10 +163,60 @@ namespace LuaScript.Tests
return DynValue.Void; return DynValue.Void;
}); });
obj["getpixeldata"] = DynValue.NewCallback((_, _) =>
{
var pd = new Table(engine);
pd["width"] = Width;
pd["height"] = Height;
pd["get"] = DynValue.NewCallback((_, a) =>
DynValue.NewNumber(PixelDataGet(buffer, (int)(a[1].CastToNumber() ?? 0d))));
pd["set"] = DynValue.NewCallback((_, a) =>
{
PixelDataSet(buffer, (int)(a[1].CastToNumber() ?? 0d), a[2].CastToNumber() ?? 0d);
return DynValue.Void;
});
return DynValue.NewTable(pd);
});
engine.Globals["obj"] = obj; engine.Globals["obj"] = obj;
engine.DoString(script); engine.DoString(script);
} }
private static double PixelDataGet(byte[] buffer, int index)
{
int zeroBased = index - 1;
if ((uint)zeroBased >= (uint)buffer.Length)
return 0d;
int pixel = Math.DivRem(zeroBased, 4, out int channel);
int p = pixel * 4;
double a = buffer[p + 3];
if (channel == 3)
return a;
if (a <= 0d)
return 0d;
double scale = 255d / a;
return channel switch
{
0 => Math.Clamp(buffer[p + 2] * scale, 0d, 255d),
1 => Math.Clamp(buffer[p + 1] * scale, 0d, 255d),
_ => Math.Clamp(buffer[p] * scale, 0d, 255d),
};
}
private static void PixelDataSet(byte[] buffer, int index, double value)
{
int zeroBased = index - 1;
if ((uint)zeroBased >= (uint)buffer.Length)
return;
int pixel = Math.DivRem(zeroBased, 4, out int channel);
int p = pixel * 4;
double clamped = Math.Clamp(value, 0d, 255d);
double a = buffer[p + 3];
double premultiplied = clamped * (a / 255d);
int byteOffset = channel switch { 0 => 2, 1 => 1, _ => 0 };
buffer[p + byteOffset] = (byte)Math.Clamp(premultiplied, 0d, 255d);
}
private static (double r, double g, double b, double a) GetPixel(byte[] buffer, int x, int y) private static (double r, double g, double b, double a) GetPixel(byte[] buffer, int x, int y)
{ {
if ((uint)x >= Width || (uint)y >= Height) if ((uint)x >= Width || (uint)y >= Height)
+122
ファイルの表示
@@ -0,0 +1,122 @@
using System;
using System.Runtime.Intrinsics;
using System.Threading;
using LuaScript.Engine.Kernel;
namespace LuaScript.Tests
{
public class KernelSimdAdoptionTests
{
private const int CalibrationExecutes = 8;
private static CpuKernel.RowDelegate Path(Action onCall, int delayMs) =>
(buffer, rowBase, xStart, xEnd, y, uniforms) =>
{
onCall();
if (delayMs > 0)
Thread.Sleep(delayMs);
};
[Fact]
public void SlowerBlock_SettlesOnScalar()
{
if (!Vector256.IsHardwareAccelerated)
return;
int rowCalls = 0, blockCalls = 0;
var kernel = new CpuKernel(Path(() => rowCalls++, 0), Path(() => blockCalls++, 5));
var buffer = new byte[8 * 4];
var uniforms = new double[1];
for (int i = 0; i < CalibrationExecutes - 1; i++)
kernel.Execute(buffer, 8, 1, uniforms);
Assert.Null(kernel.BlockAdopted);
kernel.Execute(buffer, 8, 1, uniforms);
Assert.True(kernel.BlockAdopted.HasValue);
Assert.False(kernel.BlockAdopted.Value);
int blockCallsAtDecision = blockCalls;
int rowCallsAtDecision = rowCalls;
for (int i = 0; i < 5; i++)
kernel.Execute(buffer, 8, 1, uniforms);
Assert.Equal(blockCallsAtDecision, blockCalls);
Assert.Equal(rowCallsAtDecision + 5, rowCalls);
}
[Fact]
public void FasterBlock_SettlesOnBlock()
{
if (!Vector256.IsHardwareAccelerated)
return;
int rowCalls = 0, blockCalls = 0;
var kernel = new CpuKernel(Path(() => rowCalls++, 5), Path(() => blockCalls++, 0));
var buffer = new byte[8 * 4];
var uniforms = new double[1];
for (int i = 0; i < CalibrationExecutes; i++)
kernel.Execute(buffer, 8, 1, uniforms);
Assert.True(kernel.BlockAdopted.HasValue);
Assert.True(kernel.BlockAdopted.Value);
int rowCallsAtDecision = rowCalls;
int blockCallsAtDecision = blockCalls;
for (int i = 0; i < 5; i++)
kernel.Execute(buffer, 8, 1, uniforms);
Assert.Equal(rowCallsAtDecision, rowCalls);
Assert.Equal(blockCallsAtDecision + 5, blockCalls);
}
[Fact]
public void CalibrationAlternatesBothPaths()
{
if (!Vector256.IsHardwareAccelerated)
return;
int rowCalls = 0, blockCalls = 0;
var kernel = new CpuKernel(Path(() => rowCalls++, 0), Path(() => blockCalls++, 0));
var buffer = new byte[8 * 4];
var uniforms = new double[1];
for (int i = 0; i < CalibrationExecutes; i++)
kernel.Execute(buffer, 8, 1, uniforms);
Assert.Equal(CalibrationExecutes / 2, rowCalls);
Assert.Equal(CalibrationExecutes / 2, blockCalls);
}
[Fact]
public void WithoutBlock_RunsScalarWithoutDecision()
{
int rowCalls = 0;
var kernel = new CpuKernel(Path(() => rowCalls++, 0), null);
var buffer = new byte[8 * 4];
var uniforms = new double[1];
for (int i = 0; i < CalibrationExecutes + 2; i++)
kernel.Execute(buffer, 8, 1, uniforms);
Assert.Null(kernel.BlockAdopted);
Assert.Equal(CalibrationExecutes + 2, rowCalls);
}
[Fact]
public void BlockPath_UsesScalarRowForRemainder()
{
if (!Vector256.IsHardwareAccelerated)
return;
int rowCalls = 0, blockCalls = 0;
var kernel = new CpuKernel(Path(() => rowCalls++, 0), Path(() => blockCalls++, 0));
var buffer = new byte[10 * 4];
var uniforms = new double[1];
kernel.Execute(buffer, 10, 1, uniforms);
Assert.Equal(1, blockCalls);
Assert.Equal(1, rowCalls);
}
}
}
+96
ファイルの表示
@@ -0,0 +1,96 @@
using System;
using System.Collections.Generic;
using LuaScript.Engine.Kernel;
namespace LuaScript.Tests
{
public sealed class KernelSimdEquivalenceTests
{
private const int Width = 24;
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) 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,b,g,r,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,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,x/obj.w*255,y/obj.h*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) 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,r%64,math.abs(g-128),math.sqrt(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,math.floor(r/16)*16,math.ceil(g/16)*16,-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,r*obj.track0/100,g+x/obj.w*obj.track1,b,a) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,255-r) pd:set(i+2,g*g/255) pd:set(i+3,b) 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>128 and g<64) or (not (b>200))) and 255 or 0,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,(r>=200) and 255 or 0,(g<=50) and 255 or 0,(b==0) and 255 or ((b~=0) and 100 or 0),a) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,r*3) pd:set(i+2,g-300) pd:set(i+3,b*2-255) end end")]
public void SimdBlockMatchesScalarRow(string script)
{
var program = KernelExtractor.TryExtract(script);
Assert.NotNull(program);
var block = SimdKernelCompiler.TryCompile(program!);
Assert.NotNull(block);
var scalarRow = CpuKernelCompiler.CompileRow(program!);
double[] uniforms = BuildUniforms();
byte[] source = CreateBuffer();
byte[] scalar = (byte[])source.Clone();
byte[] simd = (byte[])source.Clone();
int stride = Width * 4;
for (int y = 0; y < Height; y++)
{
scalarRow(scalar, y * stride, 0, Width, y, uniforms);
block!(simd, y * stride, 0, Width, y, uniforms);
}
Assert.Equal(scalar, simd);
}
[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,math.min(255,r+50),math.max(0,g-50),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,255*math.pow(r/255,0.45),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,r^2/255,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,255*math.sin(r/255),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,math.atan2(r,g),b,a,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.fmod(r,64),g,b,a) end end")]
public void SimdRejectsNonVectorizableKernels(string script)
{
var program = KernelExtractor.TryExtract(script);
Assert.NotNull(program);
Assert.Null(SimdKernelCompiler.TryCompile(program!));
}
private static double[] BuildUniforms()
{
double[] uniforms = new double[KernelUniforms.Count];
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height, ["track0"] = 73d, ["track1"] = 40d };
foreach (var (name, value) in fields)
if (KernelUniforms.TryResolveMember("obj", name, out var uniform))
uniforms[(int)uniform] = value;
return uniforms;
}
private static byte[] CreateBuffer()
{
var random = new Random(20260702);
var buffer = new byte[Width * Height * 4];
random.NextBytes(buffer);
void SetPixel(int i, byte b, byte g, byte r, byte a)
{
buffer[i * 4 + 0] = b; buffer[i * 4 + 1] = g; buffer[i * 4 + 2] = r; buffer[i * 4 + 3] = a;
}
SetPixel(0, 0, 0, 0, 0);
SetPixel(1, 255, 255, 255, 255);
SetPixel(2, 1, 0, 0, 1);
SetPixel(3, 200, 128, 64, 254);
SetPixel(4, 0, 0, 0, 128);
SetPixel(5, 255, 255, 255, 2);
return buffer;
}
}
}
+2
ファイルの表示
@@ -31,6 +31,7 @@
<Compile Include="..\LuaScript\Engine\ScriptDirective.cs" Link="Linked\ScriptDirective.cs" /> <Compile Include="..\LuaScript\Engine\ScriptDirective.cs" Link="Linked\ScriptDirective.cs" />
<Compile Include="..\LuaScript\Engine\NativeProtocol.cs" Link="Linked\NativeProtocol.cs" /> <Compile Include="..\LuaScript\Engine\NativeProtocol.cs" Link="Linked\NativeProtocol.cs" />
<Compile Include="..\LuaScript\Engine\ProcessJobObject.cs" Link="Linked\ProcessJobObject.cs" /> <Compile Include="..\LuaScript\Engine\ProcessJobObject.cs" Link="Linked\ProcessJobObject.cs" />
<Compile Include="..\LuaScript\Engine\PixelRegionAccess.cs" Link="Linked\PixelRegionAccess.cs" />
<Compile Include="..\LuaScript\Engine\LuaJitWorker.cs" Link="Linked\LuaJitWorker.cs" /> <Compile Include="..\LuaScript\Engine\LuaJitWorker.cs" Link="Linked\LuaJitWorker.cs" />
<Compile Include="..\LuaScript\DrawCommand.cs" Link="Linked\DrawCommand.cs" /> <Compile Include="..\LuaScript\DrawCommand.cs" Link="Linked\DrawCommand.cs" />
<Compile Include="..\LuaScript\DrawPolyMath.cs" Link="Linked\DrawPolyMath.cs" /> <Compile Include="..\LuaScript\DrawPolyMath.cs" Link="Linked\DrawPolyMath.cs" />
@@ -64,6 +65,7 @@
<Compile Include="..\LuaScript\Engine\Kernel\KernelExtractor.cs" Link="Linked\Kernel\KernelExtractor.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\CpuKernel.cs" Link="Linked\Kernel\CpuKernel.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\CpuKernelCompiler.cs" Link="Linked\Kernel\CpuKernelCompiler.cs" /> <Compile Include="..\LuaScript\Engine\Kernel\CpuKernelCompiler.cs" Link="Linked\Kernel\CpuKernelCompiler.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\SimdKernelCompiler.cs" Link="Linked\Kernel\SimdKernelCompiler.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\HlslKernelEmitter.cs" Link="Linked\Kernel\HlslKernelEmitter.cs" /> <Compile Include="..\LuaScript\Engine\Kernel\HlslKernelEmitter.cs" Link="Linked\Kernel\HlslKernelEmitter.cs" />
</ItemGroup> </ItemGroup>
+284 -41
ファイルの表示
@@ -32,6 +32,79 @@ namespace LuaScript.Tests
return f; return f;
} }
private bool RunWorker(
string script,
double[] fields,
System.Collections.Generic.IReadOnlyDictionary<string, string> stringParameters,
Func<byte[]> loadPixels,
int width,
int height,
int timeoutMs,
Func<string, int, SceneObjectInfo?> resolveObject,
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure,
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
Func<string, (byte[] buffer, int w, int h)> loadImage,
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
Action<string, System.Collections.Generic.IReadOnlyList<System.Collections.Generic.KeyValuePair<string, object>>> addEffect,
Action<DrawCommand> addDraw,
Action<string, int, bool, int, double[]> setAnchor,
out bool pixelsDirty,
out bool bufferReplaced,
out byte[]? resultPixels,
out int resultWidth,
out int resultHeight,
out string? error)
{
byte[]? uploaded = null;
bool ok = _worker.Execute(
script, fields, stringParameters,
(address, capacity) =>
{
uploaded = loadPixels();
System.Runtime.InteropServices.Marshal.Copy(uploaded, 0, address, uploaded.Length);
},
width, height, timeoutMs,
resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, addDraw, setAnchor,
out pixelsDirty, out bufferReplaced, out resultWidth, out resultHeight, out error);
resultPixels = null;
if (ok && pixelsDirty)
{
int pixelSize = resultWidth * resultHeight * 4;
byte[] destination = !bufferReplaced && uploaded is not null && uploaded.Length >= pixelSize
? uploaded
: new byte[pixelSize];
_worker.ReadPixels((address, capacity) =>
System.Runtime.InteropServices.Marshal.Copy(address, destination, 0, pixelSize));
resultPixels = destination;
}
return ok;
}
[Fact]
public void PixelUpload_ProvidesRegionCoveringFrame()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 3, h = 2;
var pixels = new byte[w * h * 4];
long observedCapacity = -1;
bool ok = _worker.Execute(
"local r, g, b, a = obj.getpixel(0, 0) obj.x = a",
Fields(w, h, 0d), NoStringParams,
(address, capacity) =>
{
observedCapacity = capacity;
System.Runtime.InteropServices.Marshal.Copy(pixels, 0, address, pixels.Length);
},
w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(observedCapacity >= (long)w * h * 4);
}
[Fact] [Fact]
public void TransformScript_WritesBackObjFields() public void TransformScript_WritesBackObjFields()
{ {
@@ -40,7 +113,7 @@ namespace LuaScript.Tests
var fields = Fields(4, 4, 2d); var fields = Fields(4, 4, 2d);
var pixels = new byte[4 * 4 * 4]; var pixels = new byte[4 * 4 * 4];
bool ok = _worker.Execute( bool ok = RunWorker(
"obj.rz = obj.time * 90\nobj.alpha = 128", "obj.rz = obj.time * 90\nobj.alpha = 128",
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error); fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
@@ -63,7 +136,7 @@ namespace LuaScript.Tests
["file_image"] = "C:/サンプル/画像.png", ["file_image"] = "C:/サンプル/画像.png",
}; };
bool ok = _worker.Execute( bool ok = RunWorker(
"obj.x = string.len(obj.text) obj.alpha = string.len(obj.file_image)", "obj.x = string.len(obj.text) obj.alpha = string.len(obj.file_image)",
fields, stringParameters, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error); fields, stringParameters, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
@@ -82,7 +155,7 @@ namespace LuaScript.Tests
var large = new System.Collections.Generic.Dictionary<string, string> { ["text"] = big }; var large = new System.Collections.Generic.Dictionary<string, string> { ["text"] = big };
var fieldsLarge = Fields(2, 2, 0d); var fieldsLarge = Fields(2, 2, 0d);
bool ok = _worker.Execute( bool ok = RunWorker(
"obj.x = string.len(obj.text)", "obj.x = string.len(obj.text)",
fieldsLarge, large, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error); fieldsLarge, large, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
@@ -90,7 +163,7 @@ namespace LuaScript.Tests
var small = new System.Collections.Generic.Dictionary<string, string> { ["text"] = "ok" }; var small = new System.Collections.Generic.Dictionary<string, string> { ["text"] = "ok" };
var fieldsSmall = Fields(2, 2, 0d); var fieldsSmall = Fields(2, 2, 0d);
ok = _worker.Execute( ok = RunWorker(
"obj.x = string.len(obj.text)", "obj.x = string.len(obj.text)",
fieldsSmall, small, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error); fieldsSmall, small, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error); Assert.True(ok, error);
@@ -124,7 +197,7 @@ namespace LuaScript.Tests
"local gray = r*0.299 + g*0.587 + b*0.114 " + "local gray = r*0.299 + g*0.587 + b*0.114 " +
"obj.setpixel(x,y,gray,gray,gray,a) end end"; "obj.setpixel(x,y,gray,gray,gray,a) end end";
bool ok = _worker.Execute(script, fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error); bool ok = RunWorker(script, fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.True(dirty); Assert.True(dirty);
@@ -159,7 +232,7 @@ namespace LuaScript.Tests
"local gray=r*0.299+g*0.587+b*0.114 " + "local gray=r*0.299+g*0.587+b*0.114 " +
"pd:set(base+1,gray) pd:set(base+2,gray) pd:set(base+3,gray) end end"; "pd:set(base+1,gray) pd:set(base+2,gray) pd:set(base+3,gray) end end";
bool ok = _worker.Execute(script, fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error); bool ok = RunWorker(script, fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.True(dirty); Assert.True(dirty);
@@ -186,6 +259,109 @@ namespace LuaScript.Tests
px[i * 4 + 3] = (byte)Math.Floor(Math.Clamp(a, 0d, 255d)); px[i * 4 + 3] = (byte)Math.Floor(Math.Clamp(a, 0d, 255d));
} }
[Fact]
public void PixelData_RebuildsAfterSetPixel()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
const string script =
"obj.setpixel(0,0,100,150,200,255) " +
"local pd = obj.getpixeldata() " +
"obj.x = pd:get(1) obj.y = pd:get(2) obj.z = pd:get(3) obj.alpha = pd:get(4)";
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(100d, fields[NativeProtocol.X]);
Assert.Equal(150d, fields[NativeProtocol.Y]);
Assert.Equal(200d, fields[NativeProtocol.Z]);
Assert.Equal(255d, fields[NativeProtocol.Alpha]);
}
[Fact]
public void PixelData_WritesAreVisibleToGetPixel()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
pixels[3] = 255;
var fields = Fields(2, 2, 0d);
const string script =
"local pd = obj.getpixeldata() " +
"pd:set(1,120) pd:set(2,130) pd:set(3,140) " +
"local r,g,b,a = obj.getpixel(0,0) " +
"obj.x = r obj.y = g obj.z = b obj.alpha = a";
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(120d, fields[NativeProtocol.X]);
Assert.Equal(130d, fields[NativeProtocol.Y]);
Assert.Equal(140d, fields[NativeProtocol.Z]);
Assert.Equal(255d, fields[NativeProtocol.Alpha]);
}
[Fact]
public void PixelData_StaleWritesDoNotResurrect_AfterLoad()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int iw = 2, ih = 2;
var decoded = new byte[iw * ih * 4];
for (int i = 0; i < decoded.Length; i++)
decoded[i] = (byte)((i * 19 + 7) & 0xFF);
Func<string, (byte[], int, int)> loadImage = _ => (decoded, iw, ih);
var pixels = new byte[4 * 4 * 4];
for (int i = 3; i < pixels.Length; i += 4)
pixels[i] = 255;
const string script =
"local pd = obj.getpixeldata() " +
"pd:set(1, 11) pd:set(2, 22) pd:set(3, 33) " +
"obj.load('image', 'p')";
bool ok = RunWorker(script, Fields(4, 4, 0d), NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, loadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out bool bufferReplaced, out byte[]? result, out int rw, out int rh, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.True(bufferReplaced);
Assert.Equal(iw, rw);
Assert.Equal(ih, rh);
Assert.NotNull(result);
Assert.Equal(decoded, result!.AsSpan(0, decoded.Length).ToArray());
}
[Fact]
public void PixelData_StaleWritesDoNotResurrect_AfterCopyBuffer()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
for (int i = 0; i < pixels.Length; i++)
pixels[i] = (byte)((i * 29 + 3) & 0xFF);
pixels[3] = 255; pixels[7] = 255; pixels[11] = 255; pixels[15] = 255;
var original = (byte[])pixels.Clone();
const string script =
"obj.copybuffer('tmp','obj') " +
"local pd = obj.getpixeldata() " +
"pd:set(1, 99) pd:set(2, 98) pd:set(3, 97) " +
"obj.copybuffer('obj','tmp')";
bool ok = RunWorker(script, Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(original, pixels);
}
[Fact] [Fact]
public void PersistentWorker_HandlesMultipleCalls() public void PersistentWorker_HandlesMultipleCalls()
{ {
@@ -195,12 +371,57 @@ namespace LuaScript.Tests
for (int k = 1; k <= 5; k++) for (int k = 1; k <= 5; k++)
{ {
var fields = Fields(2, 2, k); var fields = Fields(2, 2, k);
bool ok = _worker.Execute("obj.x = obj.time * 10", fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error); bool ok = RunWorker("obj.x = obj.time * 10", fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.Equal(k * 10d, fields[NativeProtocol.X]); Assert.Equal(k * 10d, fields[NativeProtocol.X]);
} }
} }
[Fact]
public void AlternatingScripts_RecompileWhenVersionChanges()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
const string scriptA = "obj.x = obj.time * 2";
const string scriptB = "obj.x = obj.time * 3";
for (int k = 1; k <= 4; k++)
{
var fa = Fields(2, 2, k);
bool okA = RunWorker(scriptA, fa, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? errorA);
Assert.True(okA, errorA);
Assert.Equal(k * 2d, fa[NativeProtocol.X]);
var fb = Fields(2, 2, k);
bool okB = RunWorker(scriptB, fb, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? errorB);
Assert.True(okB, errorB);
Assert.Equal(k * 3d, fb[NativeProtocol.X]);
}
}
[Fact]
public void CompileError_IsReportedEveryFrame_AndRecovers()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
const string broken = "obj.x = (";
for (int k = 0; k < 2; k++)
{
bool ok = RunWorker(broken, Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.False(ok);
Assert.False(string.IsNullOrEmpty(error));
Assert.DoesNotContain("timed out", error);
}
var fields = Fields(2, 2, 9d);
bool recovered = RunWorker("obj.x = obj.time", fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? recoverError);
Assert.True(recovered, recoverError);
Assert.Equal(9d, fields[NativeProtocol.X]);
}
[Fact] [Fact]
public void Timeout_KillsWorker_AndRecovers() public void Timeout_KillsWorker_AndRecovers()
{ {
@@ -209,13 +430,13 @@ namespace LuaScript.Tests
var pixels = new byte[16]; var pixels = new byte[16];
var fields = Fields(2, 2, 0d); var fields = Fields(2, 2, 0d);
bool timedOut = _worker.Execute( bool timedOut = RunWorker(
"local x=0 while true do x=x+1 end", fields, NoStringParams, () => pixels, 2, 2, 1500, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error); "local x=0 while true do x=x+1 end", fields, NoStringParams, () => pixels, 2, 2, 1500, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.False(timedOut); Assert.False(timedOut);
Assert.Contains("timed out", error); Assert.Contains("timed out", error);
var fields2 = Fields(2, 2, 3d); var fields2 = Fields(2, 2, 3d);
bool ok = _worker.Execute("obj.x = obj.time", fields2, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error); bool ok = RunWorker("obj.x = obj.time", fields2, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.Equal(3d, fields2[NativeProtocol.X]); Assert.Equal(3d, fields2[NativeProtocol.X]);
} }
@@ -237,7 +458,7 @@ namespace LuaScript.Tests
"obj.zoom = o.zoom obj.rz = o.rz obj.alpha = o.alpha " + "obj.zoom = o.zoom obj.rz = o.rz obj.alpha = o.alpha " +
"obj.sx = o.sy obj.rzr = o.rzr"; "obj.sx = o.sy obj.rzr = o.rzr";
bool ok = _worker.Execute(script, fields, NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error); bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.Equal(12d, fields[NativeProtocol.X]); Assert.Equal(12d, fields[NativeProtocol.X]);
@@ -269,13 +490,13 @@ namespace LuaScript.Tests
"local b = obj.getobject(\"a\") " + "local b = obj.getobject(\"a\") " +
"obj.x = a.x + b.x"; "obj.x = a.x + b.x";
bool ok = _worker.Execute(script, Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error); bool ok = RunWorker(script, Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.Equal(1, calls); Assert.Equal(1, calls);
var fields = Fields(2, 2, 0d); var fields = Fields(2, 2, 0d);
x = 20d; x = 20d;
ok = _worker.Execute(script, fields, NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error); ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.Equal(2, calls); Assert.Equal(2, calls);
Assert.Equal(40d, fields[NativeProtocol.X]); Assert.Equal(40d, fields[NativeProtocol.X]);
@@ -292,7 +513,7 @@ namespace LuaScript.Tests
const string script = const string script =
"local o = obj.getobject(\"missing\") obj.x = o == nil and 1 or 0"; "local o = obj.getobject(\"missing\") obj.x = o == nil and 1 or 0";
bool ok = _worker.Execute(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error); bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.Equal(1d, fields[NativeProtocol.X]); Assert.Equal(1d, fields[NativeProtocol.X]);
@@ -308,7 +529,7 @@ namespace LuaScript.Tests
var commands = new System.Collections.Generic.List<DrawCommand>(); var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add; Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute( bool ok = RunWorker(
"obj.draw() obj.draw(10, 20, 30, 2, 0.5, 0.25)", "obj.draw() obj.draw(10, 20, 30, 2, 0.5, 0.25)",
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error); out _, out _, out _, out _, out _, out string? error);
@@ -319,6 +540,28 @@ namespace LuaScript.Tests
Assert.Equal(new DrawCommand(10d, 20d, 30d, 2d, 0.5d, 0.25d), commands[1]); Assert.Equal(new DrawCommand(10d, 20d, 30d, 2d, 0.5d, 0.25d), commands[1]);
} }
[Fact]
public void Draw_BatchesInOrderAcrossRingOverflow()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add;
int total = NativeProtocol.DrawRingCapacity + 100;
string script = "for i=1," + total + " do obj.draw(i,0,0,1,1,0) end";
bool ok = RunWorker(
script, Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(total, commands.Count);
for (int i = 0; i < total; i++)
Assert.Equal(i + 1, commands[i].Ox);
}
[Fact] [Fact]
public void DrawPoly_RecordsDefaultUvAndAlpha() public void DrawPoly_RecordsDefaultUvAndAlpha()
{ {
@@ -329,7 +572,7 @@ namespace LuaScript.Tests
var commands = new System.Collections.Generic.List<DrawCommand>(); var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add; Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute( bool ok = RunWorker(
"obj.drawpoly(0,0,0, 10,0,0, 10,10,0, 0,10,0)", "obj.drawpoly(0,0,0, 10,0,0, 10,10,0, 0,10,0)",
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor, fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error); out _, out _, out _, out _, out _, out string? error);
@@ -351,7 +594,7 @@ namespace LuaScript.Tests
var commands = new System.Collections.Generic.List<DrawCommand>(); var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add; Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute( bool ok = RunWorker(
"obj.drawpoly(0,0,0, 8,0,0, 8,8,0, 0,8,0, 1,1, 3,1, 3,3, 1,3, 0.5)", "obj.drawpoly(0,0,0, 8,0,0, 8,8,0, 0,8,0, 1,1, 3,1, 3,3, 1,3, 0.5)",
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor, fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error); out _, out _, out _, out _, out _, out string? error);
@@ -372,7 +615,7 @@ namespace LuaScript.Tests
var pixels = new byte[16]; var pixels = new byte[16];
var fields = Fields(2, 2, 0d); var fields = Fields(2, 2, 0d);
bool ok = _worker.Execute( bool ok = RunWorker(
"obj.setoption('antialias', 0) obj.x = obj.getoption('antialias') obj.y = obj.getoption('unset')", "obj.setoption('antialias', 0) obj.x = obj.getoption('antialias') obj.y = obj.getoption('unset')",
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error); out _, out _, out _, out _, out _, out string? error);
@@ -391,7 +634,7 @@ namespace LuaScript.Tests
var commands = new System.Collections.Generic.List<DrawCommand>(); var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add; Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute( bool ok = RunWorker(
"obj.draw() obj.setoption('antialias', 0) obj.draw()", "obj.draw() obj.setoption('antialias', 0) obj.draw()",
Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor, Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error); out _, out _, out _, out _, out _, out string? error);
@@ -411,7 +654,7 @@ namespace LuaScript.Tests
var commands = new System.Collections.Generic.List<DrawCommand>(); var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add; Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute( bool ok = RunWorker(
"obj.draw() obj.setoption('blend', 3) obj.draw()", "obj.draw() obj.setoption('blend', 3) obj.draw()",
Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor, Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error); out _, out _, out _, out _, out _, out string? error);
@@ -431,7 +674,7 @@ namespace LuaScript.Tests
var commands = new System.Collections.Generic.List<DrawCommand>(); var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add; Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute( bool ok = RunWorker(
"obj.setoption('blend', 11) obj.drawpoly(0,0,0, 10,0,0, 10,10,0, 0,10,0)", "obj.setoption('blend', 11) obj.drawpoly(0,0,0, 10,0,0, 10,10,0, 0,10,0)",
Fields(4, 4, 0d), NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor, Fields(4, 4, 0d), NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error); out _, out _, out _, out _, out _, out string? error);
@@ -449,7 +692,7 @@ namespace LuaScript.Tests
var pixels = new byte[16]; var pixels = new byte[16];
var fTrue = Fields(2, 2, 0d); var fTrue = Fields(2, 2, 0d);
bool okTrue = _worker.Execute( bool okTrue = RunWorker(
"obj.setoption('draw_state', true)", "obj.setoption('draw_state', true)",
fTrue, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, fTrue, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? errorTrue); out _, out _, out _, out _, out _, out string? errorTrue);
@@ -457,7 +700,7 @@ namespace LuaScript.Tests
Assert.Equal(1d, fTrue[NativeProtocol.DrawState]); Assert.Equal(1d, fTrue[NativeProtocol.DrawState]);
var fFalse = Fields(2, 2, 0d); var fFalse = Fields(2, 2, 0d);
bool okFalse = _worker.Execute( bool okFalse = RunWorker(
"obj.setoption('draw_state', false)", "obj.setoption('draw_state', false)",
fFalse, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, fFalse, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? errorFalse); out _, out _, out _, out _, out _, out string? errorFalse);
@@ -465,7 +708,7 @@ namespace LuaScript.Tests
Assert.Equal(2d, fFalse[NativeProtocol.DrawState]); Assert.Equal(2d, fFalse[NativeProtocol.DrawState]);
var fUnset = Fields(2, 2, 0d); var fUnset = Fields(2, 2, 0d);
bool okUnset = _worker.Execute( bool okUnset = RunWorker(
"obj.x = 1", "obj.x = 1",
fUnset, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, fUnset, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? errorUnset); out _, out _, out _, out _, out _, out string? errorUnset);
@@ -503,7 +746,7 @@ namespace LuaScript.Tests
"obj.y = pos[1]\n" + "obj.y = pos[1]\n" +
"obj.z = pos[3]"; "obj.z = pos[3]";
bool ok = _worker.Execute(script, fields, NoStringParams, () => pixels, 2, 2, 5000, bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000,
NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, setAnchor, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, setAnchor,
out _, out _, out _, out _, out _, out string? error); out _, out _, out _, out _, out _, out string? error);
@@ -533,7 +776,7 @@ namespace LuaScript.Tests
"obj.setoption('drawtarget','framebuffer')\n" + "obj.setoption('drawtarget','framebuffer')\n" +
"obj.copybuffer('obj','tmp')"; "obj.copybuffer('obj','tmp')";
bool ok = _worker.Execute( bool ok = RunWorker(
script, fields, NoStringParams, () => pixels, 2, 2, 5000, script, fields, NoStringParams, () => pixels, 2, 2, 5000,
NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error); out bool dirty, out _, out _, out _, out _, out string? error);
@@ -579,7 +822,7 @@ namespace LuaScript.Tests
var pixels = new byte[4 * 4 * 4]; var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d); var fields = Fields(4, 4, 0d);
bool ok = _worker.Execute( bool ok = RunWorker(
"obj.setfont('Meiryo', 40, 3, 0x112233) obj.load('text', 'Hi')", "obj.setfont('Meiryo', 40, 3, 0x112233) obj.load('text', 'Hi')",
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, loadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, loadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error); out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
@@ -619,7 +862,7 @@ namespace LuaScript.Tests
var pixels = new byte[4 * 4 * 4]; var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d); var fields = Fields(4, 4, 0d);
bool ok = _worker.Execute( bool ok = RunWorker(
"obj.load('image', 'C:/sample.png')", "obj.load('image', 'C:/sample.png')",
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, loadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, loadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error); out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
@@ -656,7 +899,7 @@ namespace LuaScript.Tests
var pixels = new byte[4 * 4 * 4]; var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d); var fields = Fields(4, 4, 0d);
bool ok = _worker.Execute( bool ok = RunWorker(
"obj.load('movie', 'C:/clip.mp4', 1.5)", "obj.load('movie', 'C:/clip.mp4', 1.5)",
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, loadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, loadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error); out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
@@ -681,7 +924,7 @@ namespace LuaScript.Tests
var fields = Fields(2, 2, 0d); var fields = Fields(2, 2, 0d);
fields[NativeProtocol.Track0] = 42d; fields[NativeProtocol.Track0] = 42d;
bool ok = _worker.Execute( bool ok = RunWorker(
"obj.x = obj.getvalue('track0') obj.y = obj.getvalue('alpha') obj.z = obj.getvalue('unknown')", "obj.x = obj.getvalue('track0') obj.y = obj.getvalue('alpha') obj.z = obj.getvalue('unknown')",
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error); out _, out _, out _, out _, out _, out string? error);
@@ -710,7 +953,7 @@ namespace LuaScript.Tests
"for y=0,obj.h-1 do for x=0,obj.w-1 do obj.setpixel(x,y,0,0,0,0) end end " + "for y=0,obj.h-1 do for x=0,obj.w-1 do obj.setpixel(x,y,0,0,0,0) end end " +
"obj.copybuffer('obj','tmp')"; "obj.copybuffer('obj','tmp')";
bool ok = _worker.Execute(script, fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error); bool ok = RunWorker(script, fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.True(dirty); Assert.True(dirty);
@@ -729,11 +972,11 @@ namespace LuaScript.Tests
stored[3] = 255; stored[7] = 255; stored[11] = 255; stored[15] = 255; stored[3] = 255; stored[7] = 255; stored[11] = 255; stored[15] = 255;
var save = (byte[])stored.Clone(); var save = (byte[])stored.Clone();
bool ok = _worker.Execute("obj.copybuffer('cache:foo','obj')", Fields(w, h, 0d), NoStringParams, () => save, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error); bool ok = RunWorker("obj.copybuffer('cache:foo','obj')", Fields(w, h, 0d), NoStringParams, () => save, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
var blank = new byte[w * h * 4]; var blank = new byte[w * h * 4];
ok = _worker.Execute("obj.copybuffer('obj','cache:foo')", Fields(w, h, 0d), NoStringParams, () => blank, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out byte[]? restored, out _, out _, out error); ok = RunWorker("obj.copybuffer('obj','cache:foo')", Fields(w, h, 0d), NoStringParams, () => blank, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out byte[]? restored, out _, out _, out error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.True(dirty); Assert.True(dirty);
Assert.NotNull(restored); Assert.NotNull(restored);
@@ -750,7 +993,7 @@ namespace LuaScript.Tests
Func<byte[]> loadPixels = () => { loads++; return pixels; }; Func<byte[]> loadPixels = () => { loads++; return pixels; };
var fields = Fields(2, 2, 1d); var fields = Fields(2, 2, 1d);
bool ok = _worker.Execute( bool ok = RunWorker(
"obj.x = obj.time * 10 obj.draw()", "obj.x = obj.time * 10 obj.draw()",
fields, NoStringParams, loadPixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, fields, NoStringParams, loadPixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error); out bool dirty, out _, out _, out _, out _, out string? error);
@@ -771,7 +1014,7 @@ namespace LuaScript.Tests
int loads = 0; int loads = 0;
Func<byte[]> loadPixels = () => { loads++; return pixels; }; Func<byte[]> loadPixels = () => { loads++; return pixels; };
bool ok = _worker.Execute( bool ok = RunWorker(
"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", "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",
Fields(2, 2, 0d), NoStringParams, loadPixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, Fields(2, 2, 0d), NoStringParams, loadPixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error); out bool dirty, out _, out _, out _, out _, out string? error);
@@ -791,11 +1034,11 @@ namespace LuaScript.Tests
stored[i] = (byte)((i * 41 + 13) & 0xFF); stored[i] = (byte)((i * 41 + 13) & 0xFF);
stored[3] = 255; stored[7] = 255; stored[11] = 255; stored[15] = 255; stored[3] = 255; stored[7] = 255; stored[11] = 255; stored[15] = 255;
bool ok = _worker.Execute("obj.copybuffer('cache:sz','obj')", Fields(2, 2, 0d), NoStringParams, () => stored, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error); bool ok = RunWorker("obj.copybuffer('cache:sz','obj')", Fields(2, 2, 0d), NoStringParams, () => stored, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
var bigger = new byte[4 * 4 * 4]; var bigger = new byte[4 * 4 * 4];
ok = _worker.Execute("obj.copybuffer('obj','cache:sz')", Fields(4, 4, 0d), NoStringParams, () => bigger, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out bool bufferReplaced, out byte[]? restored, out int rw, out int rh, out error); ok = RunWorker("obj.copybuffer('obj','cache:sz')", Fields(4, 4, 0d), NoStringParams, () => bigger, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out bool bufferReplaced, out byte[]? restored, out int rw, out int rh, out error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.True(dirty); Assert.True(dirty);
Assert.True(bufferReplaced); Assert.True(bufferReplaced);
@@ -824,7 +1067,7 @@ namespace LuaScript.Tests
"obj.y = totalframe + framerate + layer " + "obj.y = totalframe + framerate + layer " +
"obj.z = timelineframe + timelinetime"; "obj.z = timelineframe + timelinetime";
bool ok = _worker.Execute(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error); bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.Equal(30d, fields[NativeProtocol.X]); Assert.Equal(30d, fields[NativeProtocol.X]);
@@ -839,13 +1082,13 @@ namespace LuaScript.Tests
var pixels = new byte[16]; var pixels = new byte[16];
bool ok = _worker.Execute( bool ok = RunWorker(
"leak = 42 obj.leaked = 7 scene.custom = 1 ymm4.custom = 2", "leak = 42 obj.leaked = 7 scene.custom = 1 ymm4.custom = 2",
Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error); Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
var fields = Fields(2, 2, 0d); var fields = Fields(2, 2, 0d);
ok = _worker.Execute( ok = RunWorker(
"obj.x = (leak == nil and 1 or 0) + (obj.leaked == nil and 10 or 0) + (scene.custom == nil and 100 or 0) + (ymm4.custom == nil and 1000 or 0)", "obj.x = (leak == nil and 1 or 0) + (obj.leaked == nil and 10 or 0) + (scene.custom == nil and 100 or 0) + (ymm4.custom == nil and 1000 or 0)",
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error); fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error); Assert.True(ok, error);
@@ -860,12 +1103,12 @@ namespace LuaScript.Tests
var pixels = new byte[16]; var pixels = new byte[16];
var fields = Fields(2, 2, 0d); var fields = Fields(2, 2, 0d);
bool ok = _worker.Execute("obj.x = missing.value", fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error); bool ok = RunWorker("obj.x = missing.value", fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.False(ok); Assert.False(ok);
Assert.False(string.IsNullOrEmpty(error)); Assert.False(string.IsNullOrEmpty(error));
var fields2 = Fields(2, 2, 7d); var fields2 = Fields(2, 2, 7d);
bool ok2 = _worker.Execute("obj.x = obj.time", fields2, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error); bool ok2 = RunWorker("obj.x = obj.time", fields2, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
Assert.True(ok2, error); Assert.True(ok2, error);
Assert.Equal(7d, fields2[NativeProtocol.X]); Assert.Equal(7d, fields2[NativeProtocol.X]);
} }
+11 -2
ファイルの表示
@@ -185,20 +185,29 @@ namespace LuaScript
private bool TryWriteBuffer(string id, byte[] data, int width, int height) private bool TryWriteBuffer(string id, byte[] data, int width, int height)
{ {
int n = width * height * 4;
switch (BufferKind(id, out string key)) switch (BufferKind(id, out string key))
{ {
case 'o': case 'o':
ReplaceBuffer((byte[])data.Clone(), width, height); if (_copyOutputBuffer is null || _copyOutputBuffer.Length != n)
_copyOutputBuffer = new byte[n];
Buffer.BlockCopy(data, 0, _copyOutputBuffer, 0, n);
ReplaceBuffer(_copyOutputBuffer, width, height);
return true; return true;
case 't': case 't':
case 'c': case 'c':
_buffers[key] = ((byte[])data.Clone(), width, height); if (!_buffers.TryGetValue(key, out var existing) || existing.Data.Length != n)
existing.Data = new byte[n];
Buffer.BlockCopy(data, 0, existing.Data, 0, n);
_buffers[key] = (existing.Data, width, height);
return false; return false;
default: default:
return false; return false;
} }
} }
private byte[]? _copyOutputBuffer;
private static char BufferKind(string id, out string key) private static char BufferKind(string id, out string key)
{ {
key = string.Empty; key = string.Empty;
+71 -4
ファイルの表示
@@ -1,28 +1,95 @@
using System.Diagnostics;
using System.Runtime.Intrinsics;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace LuaScript.Engine.Kernel namespace LuaScript.Engine.Kernel
{ {
internal sealed class CpuKernel(CpuKernel.RowDelegate row) internal sealed class CpuKernel(CpuKernel.RowDelegate row, CpuKernel.RowDelegate? block)
{ {
public delegate void RowDelegate(byte[] buffer, int width, int rowBase, double y, double[] uniforms); public delegate void RowDelegate(byte[] buffer, int rowBase, int xStart, int xEnd, double y, double[] uniforms);
private const int ParallelThreshold = 64; private const int ParallelThreshold = 64;
private const int WarmupRunsPerPath = 1;
private const int TimedRunsPerPath = 3;
private readonly RowDelegate _row = row; private readonly RowDelegate _row = row;
private readonly RowDelegate? _block = block;
private long _rowTicks;
private long _blockTicks;
private int _rowRuns;
private int _blockRuns;
private bool _nextIsBlock = true;
private bool _decided;
private bool _useBlock;
public bool? BlockAdopted => _decided ? _useBlock : null;
public void Execute(byte[] buffer, int width, int height, double[] uniforms) public void Execute(byte[] buffer, int width, int height, double[] uniforms)
{
if (_block is null || !Vector256.IsHardwareAccelerated)
{
Run(buffer, width, height, uniforms, false);
return;
}
if (_decided)
{
Run(buffer, width, height, uniforms, _useBlock);
return;
}
bool useBlock = _nextIsBlock;
_nextIsBlock = !_nextIsBlock;
long start = Stopwatch.GetTimestamp();
Run(buffer, width, height, uniforms, useBlock);
long elapsed = Stopwatch.GetTimestamp() - start;
if (useBlock)
{
if (_blockRuns >= WarmupRunsPerPath)
_blockTicks += elapsed;
_blockRuns++;
}
else
{
if (_rowRuns >= WarmupRunsPerPath)
_rowTicks += elapsed;
_rowRuns++;
}
if (_rowRuns >= WarmupRunsPerPath + TimedRunsPerPath &&
_blockRuns >= WarmupRunsPerPath + TimedRunsPerPath)
{
_useBlock = _blockTicks < _rowTicks;
_decided = true;
}
}
private void Run(byte[] buffer, int width, int height, double[] uniforms, bool useBlock)
{ {
var row = _row; var row = _row;
var block = useBlock ? _block : null;
int stride = width * 4; int stride = width * 4;
int blockWidth = block is null ? 0 : width & ~3;
void RunRow(int y)
{
int rowBase = y * stride;
if (blockWidth > 0)
block!(buffer, rowBase, 0, blockWidth, y, uniforms);
if (blockWidth < width)
row(buffer, rowBase, blockWidth, width, y, uniforms);
}
if (height < ParallelThreshold) if (height < ParallelThreshold)
{ {
for (int y = 0; y < height; y++) for (int y = 0; y < height; y++)
row(buffer, width, y * stride, y, uniforms); RunRow(y);
return; return;
} }
Parallel.For(0, height, y => row(buffer, width, y * stride, y, uniforms)); Parallel.For(0, height, RunRow);
} }
} }
} }
+12 -6
ファイルの表示
@@ -31,11 +31,15 @@ namespace LuaScript.Engine.Kernel
[KFunc.Max] = Binary(nameof(Math.Max)), [KFunc.Max] = Binary(nameof(Math.Max)),
}; };
public static CpuKernel Compile(KernelProgram program) public static CpuKernel Compile(KernelProgram program) =>
new(CompileRow(program), SimdKernelCompiler.TryCompile(program));
public static CpuKernel.RowDelegate CompileRow(KernelProgram program)
{ {
var buffer = Expression.Parameter(typeof(byte[]), "buffer"); var buffer = Expression.Parameter(typeof(byte[]), "buffer");
var width = Expression.Parameter(typeof(int), "width");
var rowBase = Expression.Parameter(typeof(int), "rowBase"); var rowBase = Expression.Parameter(typeof(int), "rowBase");
var xStart = Expression.Parameter(typeof(int), "xStart");
var xEnd = Expression.Parameter(typeof(int), "xEnd");
var y = Expression.Parameter(typeof(double), "y"); var y = Expression.Parameter(typeof(double), "y");
var uniforms = Expression.Parameter(typeof(double[]), "uniforms"); var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
@@ -85,7 +89,7 @@ namespace LuaScript.Engine.Kernel
var breakLabel = Expression.Label("break"); var breakLabel = Expression.Label("break");
var loop = Expression.Loop( var loop = Expression.Loop(
Expression.IfThenElse( Expression.IfThenElse(
Expression.LessThan(x, width), Expression.LessThan(x, xEnd),
Expression.Block(statements), Expression.Block(statements),
Expression.Break(breakLabel)), Expression.Break(breakLabel)),
breakLabel); breakLabel);
@@ -94,10 +98,10 @@ namespace LuaScript.Engine.Kernel
locals.AddRange(inputs); locals.AddRange(inputs);
locals.AddRange(slots); locals.AddRange(slots);
var body = Expression.Block(locals, Expression.Assign(x, Constant(0)), loop); var body = Expression.Block(locals, Expression.Assign(x, xStart), loop);
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, width, rowBase, y, uniforms); var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, y, uniforms);
return new CpuKernel(lambda.Compile()); return lambda.Compile();
} }
private sealed record Context( private sealed record Context(
@@ -151,6 +155,8 @@ namespace LuaScript.Engine.Kernel
private static Expression BuildCall(KCall call, Context context) private static Expression BuildCall(KCall call, Context context)
{ {
if (call.Func == KFunc.Fmod)
return Expression.Modulo(Build(call.Arguments[0], context), Build(call.Arguments[1], context));
var method = Functions[call.Func]; var method = Functions[call.Func];
if (call.Arguments.Count == 1) if (call.Arguments.Count == 1)
return Expression.Call(method, Build(call.Arguments[0], context)); return Expression.Call(method, Build(call.Arguments[0], context));
+172 -13
ファイルの表示
@@ -35,6 +35,9 @@ namespace LuaScript.Engine.Kernel
private string _widthVariable = string.Empty; private string _widthVariable = string.Empty;
private string _heightVariable = string.Empty; private string _heightVariable = string.Empty;
private bool _coordsEnabled; private bool _coordsEnabled;
private string? _pixelDataVariable;
private string _baseIndexVariable = string.Empty;
private readonly bool[] _writtenChannels = new bool[4];
public static KernelProgram? TryExtract(string runnableScript) public static KernelProgram? TryExtract(string runnableScript)
{ {
@@ -55,6 +58,11 @@ namespace LuaScript.Engine.Kernel
int index = 0; int index = 0;
while (index < block.Count && block[index] is LocalStmt prelude) while (index < block.Count && block[index] is LocalStmt prelude)
{ {
if (TryBindPixelData(prelude))
{
index++;
continue;
}
BindLocal(prelude); BindLocal(prelude);
index++; index++;
} }
@@ -72,11 +80,140 @@ namespace LuaScript.Engine.Kernel
return null; return null;
if (outerAxis == innerAxis) if (outerAxis == innerAxis)
return null; return null;
if (_pixelDataVariable is not null &&
(string.Equals(outerVar, _pixelDataVariable, StringComparison.Ordinal) ||
string.Equals(innerVar, _pixelDataVariable, StringComparison.Ordinal)))
return null;
if (_scope.ContainsKey(outerVar))
_scope.Remove(outerVar);
if (_scope.ContainsKey(innerVar))
_scope.Remove(innerVar);
_widthVariable = outerAxis == KAxis.X ? outerVar : innerVar; _widthVariable = outerAxis == KAxis.X ? outerVar : innerVar;
_heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar; _heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar;
return BuildKernel(inner.Body); return _pixelDataVariable is null ? BuildKernel(inner.Body) : BuildPixelDataKernel(inner.Body);
}
private bool TryBindPixelData(LocalStmt local)
{
if (local.Names.Count != 1 || local.Values.Count != 1 ||
local.Values[0] is not CallExpr { Target: MemberExpr { Target: NameExpr { Name: "obj" }, Name: "getpixeldata" }, Arguments.Count: 0 })
return false;
if (_pixelDataVariable is not null)
throw new KernelUnsupportedException("Multiple pixel-data handles are not supported.");
_pixelDataVariable = local.Names[0];
return true;
}
private KernelProgram? BuildPixelDataKernel(IReadOnlyList<LuaStmt> body)
{
if (body.Count < 5)
return null;
if (body[0] is not LocalStmt { Names.Count: 1, Values.Count: 1 } baseStmt || !IsBaseIndex(baseStmt.Values[0]))
return null;
EnsureNotCoordinateName(baseStmt.Names[0]);
_baseIndexVariable = baseStmt.Names[0];
_coordsEnabled = true;
KExpr? outR = null, outG = null, outB = null;
for (int i = 1; i < body.Count; i++)
{
switch (body[i])
{
case LocalStmt local:
BindLocal(local);
break;
case AssignStmt assign:
BindAssign(assign);
break;
case CallStmt { Call: MethodCallExpr set } when IsPixelDataSet(set, out int writeChannel):
var value = ClampChannel(Lower(set.Arguments[1]));
if (writeChannel == 0) outR = value;
else if (writeChannel == 1) outG = value;
else outB = value;
_writtenChannels[writeChannel] = true;
break;
default:
return null;
}
}
if (outR is null || outG is null || outB is null)
return null;
return new KernelProgram(_bindings, outR, outG, outB, new KInput(KChannel.A), [.. _uniforms]);
}
private bool IsBaseIndex(LuaExpr expression)
{
if (expression is not BinaryExpr { Operator: "*", Right: NumberExpr { Value: 4d } } scaled ||
scaled.Left is not BinaryExpr { Operator: "+" } sum)
return false;
if (!IsCoordinate(sum.Right, KAxis.X))
return false;
if (sum.Left is not BinaryExpr { Operator: "*" } stride)
return false;
return IsCoordinate(stride.Left, KAxis.Y) && IsWidth(stride.Right);
}
private bool IsWidth(LuaExpr expression)
{
if (expression is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
KernelUniforms.TryResolveMember("obj", field, out var uniform))
return uniform == KernelUniform.Width;
return _pixelDataVariable is not null &&
expression is MemberExpr { Target: NameExpr { } target, Name: "width" } &&
string.Equals(target.Name, _pixelDataVariable, StringComparison.Ordinal);
}
private bool TryPixelDataChannel(LuaExpr expression, out int channel)
{
channel = 0;
if (expression is not MethodCallExpr { Method: "get", Arguments.Count: 1 } call ||
call.Target is not NameExpr { } handle ||
!string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
return false;
if (!TryChannelOffset(call.Arguments[0], 1, 4, out channel))
return false;
channel--;
return !_writtenChannels[channel];
}
private bool IsPixelDataSet(MethodCallExpr call, out int channel)
{
channel = 0;
if (call.Method != "set" || call.Arguments.Count != 2 ||
call.Target is not NameExpr { } handle ||
!string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
return false;
if (!TryChannelOffset(call.Arguments[0], 1, 3, out channel))
return false;
channel--;
return true;
}
private KExpr ClampChannel(KExpr value)
{
var bound = new KLocalRef(AddBinding(value));
return new KSelect(
new KCompare(KCompareOp.Less, bound, new KConst(0d)),
new KConst(0d),
new KSelect(
new KCompare(KCompareOp.Greater, bound, new KConst(255d)),
new KConst(255d),
bound));
}
private bool TryChannelOffset(LuaExpr expression, int min, int max, out int offset)
{
offset = 0;
if (expression is not BinaryExpr { Operator: "+", Left: NameExpr baseName, Right: NumberExpr number } ||
!string.Equals(baseName.Name, _baseIndexVariable, StringComparison.Ordinal))
return false;
offset = (int)number.Value;
return offset == number.Value && offset >= min && offset <= max;
} }
private KernelProgram? BuildKernel(IReadOnlyList<LuaStmt> body) private KernelProgram? BuildKernel(IReadOnlyList<LuaStmt> body)
@@ -112,7 +249,7 @@ namespace LuaScript.Engine.Kernel
} }
} }
if (body[^1] is not CallStmt { Call: var call } || !IsObjectMethod(call, "setpixel")) if (body[^1] is not CallStmt { Call: CallExpr call } || !IsObjectMethod(call, "setpixel"))
return null; return null;
if (call.Arguments.Count is < 5 or > 6) if (call.Arguments.Count is < 5 or > 6)
return null; return null;
@@ -167,6 +304,10 @@ namespace LuaScript.Engine.Kernel
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) || if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
string.Equals(name, _heightVariable, StringComparison.Ordinal)) string.Equals(name, _heightVariable, StringComparison.Ordinal))
throw new KernelUnsupportedException("Local variable shadows a loop coordinate."); throw new KernelUnsupportedException("Local variable shadows a loop coordinate.");
if (_pixelDataVariable is not null && string.Equals(name, _pixelDataVariable, StringComparison.Ordinal))
throw new KernelUnsupportedException("Local variable shadows the pixel-data handle.");
if (_baseIndexVariable.Length > 0 && string.Equals(name, _baseIndexVariable, StringComparison.Ordinal))
throw new KernelUnsupportedException("Local variable shadows the base index.");
} }
private int AddBinding(KExpr expression) private int AddBinding(KExpr expression)
@@ -187,6 +328,8 @@ namespace LuaScript.Engine.Kernel
return LowerMember(member); return LowerMember(member);
case CallExpr call: case CallExpr call:
return LowerCall(call); return LowerCall(call);
case MethodCallExpr method when TryPixelDataChannel(method, out int channel):
return new KInput((KChannel)channel);
case UnaryExpr { Operator: "-" } unary: case UnaryExpr { Operator: "-" } unary:
return new KNegate(Lower(unary.Operand)); return new KNegate(Lower(unary.Operand));
case BinaryExpr binary: case BinaryExpr binary:
@@ -323,20 +466,36 @@ namespace LuaScript.Engine.Kernel
return false; return false;
if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound) if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound)
return false; return false;
if (bound.Left is not MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field }) if (bound.Left is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
return false; KernelUniforms.TryResolveMember("obj", field, out var uniform))
if (!KernelUniforms.TryResolveMember("obj", field, out var uniform))
return false;
if (uniform == KernelUniform.Width)
{ {
axis = KAxis.X; if (uniform == KernelUniform.Width)
return true; {
axis = KAxis.X;
return true;
}
if (uniform == KernelUniform.Height)
{
axis = KAxis.Y;
return true;
}
return false;
} }
if (uniform == KernelUniform.Height)
if (_pixelDataVariable is not null &&
bound.Left is MemberExpr { Target: NameExpr { } handle, Name: var pixelField } &&
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
{ {
axis = KAxis.Y; if (pixelField == "width")
return true; {
axis = KAxis.X;
return true;
}
if (pixelField == "height")
{
axis = KAxis.Y;
return true;
}
} }
return false; return false;
} }
+3 -1
ファイルの表示
@@ -20,6 +20,8 @@ namespace LuaScript.Engine.Kernel
internal sealed record CallExpr(LuaExpr Target, IReadOnlyList<LuaExpr> Arguments) : LuaExpr; internal sealed record CallExpr(LuaExpr Target, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
internal sealed record MethodCallExpr(LuaExpr Target, string Method, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
internal sealed record UnaryExpr(string Operator, LuaExpr Operand) : LuaExpr; internal sealed record UnaryExpr(string Operator, LuaExpr Operand) : LuaExpr;
internal sealed record BinaryExpr(string Operator, LuaExpr Left, LuaExpr Right) : LuaExpr; internal sealed record BinaryExpr(string Operator, LuaExpr Left, LuaExpr Right) : LuaExpr;
@@ -30,7 +32,7 @@ namespace LuaScript.Engine.Kernel
internal sealed record AssignStmt(IReadOnlyList<LuaExpr> Targets, 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 CallStmt(LuaExpr Call) : LuaStmt;
internal sealed record IfClause(LuaExpr Condition, IReadOnlyList<LuaStmt> Body); internal sealed record IfClause(LuaExpr Condition, IReadOnlyList<LuaStmt> Body);
+8 -2
ファイルの表示
@@ -149,8 +149,8 @@ namespace LuaScript.Engine.Kernel
return new AssignStmt(targets, values); return new AssignStmt(targets, values);
} }
if (first is CallExpr call) if (first is CallExpr or MethodCallExpr)
return new CallStmt(call); return new CallStmt(first);
throw new KernelUnsupportedException("Expression is not a valid statement."); throw new KernelUnsupportedException("Expression is not a valid statement.");
} }
@@ -275,6 +275,12 @@ namespace LuaScript.Engine.Kernel
{ {
expression = new CallExpr(expression, ParseArguments()); expression = new CallExpr(expression, ParseArguments());
} }
else if (t.IsSymbol(":"))
{
Advance();
string method = ExpectName();
expression = new MethodCallExpr(expression, method, ParseArguments());
}
else else
{ {
break; break;
+270
ファイルの表示
@@ -0,0 +1,270 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Intrinsics;
namespace LuaScript.Engine.Kernel
{
internal static class SimdKernelCompiler
{
private static readonly Type Vec = typeof(Vector256<double>);
private static readonly MethodInfo Broadcast = typeof(Vector256).GetMethod(nameof(Vector256.Create), [typeof(double)])!;
private static readonly MethodInfo Create4 = typeof(Vector256).GetMethod(nameof(Vector256.Create), [typeof(double), typeof(double), typeof(double), typeof(double)])!;
private static readonly MethodInfo GetElement = VecOp(nameof(Vector256.GetElement), 1, 1);
private static readonly MethodInfo Add = VecOp(nameof(Vector256.Add), 2);
private static readonly MethodInfo Subtract = VecOp(nameof(Vector256.Subtract), 2);
private static readonly MethodInfo Multiply = VecOp(nameof(Vector256.Multiply), 2);
private static readonly MethodInfo Divide = VecOp(nameof(Vector256.Divide), 2);
private static readonly MethodInfo Negate = VecOp(nameof(Vector256.Negate), 1);
private static readonly MethodInfo Abs = VecOp(nameof(Vector256.Abs), 1);
private static readonly MethodInfo Sqrt = VecOp(nameof(Vector256.Sqrt), 1);
private static readonly MethodInfo FloorFn = typeof(Vector256).GetMethod(nameof(Vector256.Floor), [Vec])!;
private static readonly MethodInfo CeilingFn = typeof(Vector256).GetMethod(nameof(Vector256.Ceiling), [Vec])!;
private static readonly MethodInfo ConditionalSelect = VecOp(nameof(Vector256.ConditionalSelect), 3);
private static readonly MethodInfo LessThan = VecOp(nameof(Vector256.LessThan), 2);
private static readonly MethodInfo GreaterThan = VecOp(nameof(Vector256.GreaterThan), 2);
private static readonly MethodInfo LessThanOrEqual = VecOp(nameof(Vector256.LessThanOrEqual), 2);
private static readonly MethodInfo GreaterThanOrEqual = VecOp(nameof(Vector256.GreaterThanOrEqual), 2);
private static readonly MethodInfo EqualsFn = VecOp(nameof(Vector256.Equals), 2);
private static readonly MethodInfo BitwiseAnd = VecOp(nameof(Vector256.BitwiseAnd), 2);
private static readonly MethodInfo BitwiseOr = VecOp(nameof(Vector256.BitwiseOr), 2);
private static readonly MethodInfo OnesComplement = VecOp(nameof(Vector256.OnesComplement), 1);
private static readonly Expression Zero = Expression.Constant(Vector256<double>.Zero, Vec);
private static readonly Expression AllBits = Expression.Constant(Vector256<double>.AllBitsSet, Vec);
private static readonly Expression V255 = Expression.Constant(Vector256.Create(255d), Vec);
public static CpuKernel.RowDelegate? TryCompile(KernelProgram program)
{
try
{
return Compile(program);
}
catch (KernelUnsupportedException)
{
return null;
}
}
private static CpuKernel.RowDelegate Compile(KernelProgram program)
{
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
var rowBase = Expression.Parameter(typeof(int), "rowBase");
var xStart = Expression.Parameter(typeof(int), "xStart");
var xEnd = Expression.Parameter(typeof(int), "xEnd");
var yScalar = 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 yVec = Expression.Variable(Vec, "yVec");
var xVec = Expression.Variable(Vec, "xVec");
var alphaRaw = Expression.Variable(Vec, "alphaRaw");
var transparent = Expression.Variable(Vec, "transparent");
var scale = Expression.Variable(Vec, "scale");
var inputs = new[]
{
Expression.Variable(Vec, "inR"),
Expression.Variable(Vec, "inG"),
Expression.Variable(Vec, "inB"),
Expression.Variable(Vec, "inA"),
};
var slots = new ParameterExpression[program.Bindings.Count];
for (int i = 0; i < slots.Length; i++)
slots[i] = Expression.Variable(Vec, "slot" + i);
var context = new Context(xVec, yVec, uniforms, inputs, slots);
var statements = new List<Expression>
{
Expression.Assign(index, Expression.Add(rowBase, Expression.Multiply(x, Constant(4)))),
Expression.Assign(xVec, Expression.Call(Create4,
ToDouble(x),
ToDouble(Expression.Add(x, Constant(1))),
ToDouble(Expression.Add(x, Constant(2))),
ToDouble(Expression.Add(x, Constant(3))))),
Expression.Assign(alphaRaw, LoadChannel(buffer, index, 3)),
Expression.Assign(transparent, Call(LessThanOrEqual, alphaRaw, Zero)),
Expression.Assign(scale, Select(transparent, Zero, Call(Divide, V255, alphaRaw))),
Expression.Assign(inputs[3], Select(transparent, Zero, alphaRaw)),
Expression.Assign(inputs[0], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 2), scale)))),
Expression.Assign(inputs[1], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 1), scale)))),
Expression.Assign(inputs[2], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(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(Vec, "outA");
var alphaScale = Expression.Variable(Vec, "alphaScale");
statements.Add(Expression.Assign(outA, Build(program.OutputA, context)));
statements.Add(Expression.Assign(alphaScale, Call(Divide, ClampByte(outA), V255)));
statements.Add(StoreChannel(buffer, index, 0, ClampByte(Call(Multiply, Build(program.OutputB, context), alphaScale))));
statements.Add(StoreChannel(buffer, index, 1, ClampByte(Call(Multiply, Build(program.OutputG, context), alphaScale))));
statements.Add(StoreChannel(buffer, index, 2, ClampByte(Call(Multiply, Build(program.OutputR, context), alphaScale))));
statements.Add(StoreChannel(buffer, index, 3, ClampByte(outA)));
statements.Add(Expression.AddAssign(x, Constant(4)));
var breakLabel = Expression.Label("break");
var loop = Expression.Loop(
Expression.IfThenElse(
Expression.LessThan(x, xEnd),
Expression.Block(statements),
Expression.Break(breakLabel)),
breakLabel);
var locals = new List<ParameterExpression> { x, index, yVec, xVec, alphaRaw, transparent, scale, outA, alphaScale };
locals.AddRange(inputs);
locals.AddRange(slots);
var body = Expression.Block(
locals,
Expression.Assign(yVec, Expression.Call(Broadcast, yScalar)),
Expression.Assign(x, xStart),
loop);
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, yScalar, uniforms);
return lambda.Compile();
}
private sealed record Context(
Expression X,
Expression Y,
ParameterExpression Uniforms,
Expression[] Inputs,
ParameterExpression[] Slots);
private static Expression Build(KExpr expression, Context context)
{
switch (expression)
{
case KConst value:
return Expression.Constant(Vector256.Create(value.Value), Vec);
case KInput input:
return context.Inputs[(int)input.Channel];
case KCoord coord:
return coord.Axis == KAxis.X ? context.X : context.Y;
case KUniformRef uniform:
return Expression.Call(Broadcast, Expression.ArrayIndex(context.Uniforms, Constant((int)uniform.Uniform)));
case KLocalRef local:
return context.Slots[local.Slot];
case KNegate negate:
return Call(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 SIMD 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 => Call(Add, left, right),
KArithOp.Subtract => Call(Subtract, left, right),
KArithOp.Multiply => Call(Multiply, left, right),
KArithOp.Divide => Call(Divide, left, right),
KArithOp.Modulo => Call(Subtract, left, Call(Multiply, Call(FloorFn, Call(Divide, left, right)), right)),
_ => throw new KernelUnsupportedException("Unsupported SIMD arithmetic operator."),
};
}
private static Expression BuildCall(KCall call, Context context)
{
var argument = Build(call.Arguments[0], context);
return call.Func switch
{
KFunc.Abs => Call(Abs, argument),
KFunc.Floor => Call(FloorFn, argument),
KFunc.Ceil => Call(CeilingFn, argument),
KFunc.Sqrt => Call(Sqrt, argument),
_ => throw new KernelUnsupportedException("Unsupported SIMD function."),
};
}
private static Expression BuildBool(KBool condition, Context context)
{
switch (condition)
{
case KBoolConst value:
return value.Value ? AllBits : Zero;
case KNot not:
return Call(OnesComplement, BuildBool(not.Operand, context));
case KLogical logical:
return logical.IsAnd
? Call(BitwiseAnd, BuildBool(logical.Left, context), BuildBool(logical.Right, context))
: Call(BitwiseOr, 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 => Call(LessThan, left, right),
KCompareOp.Greater => Call(GreaterThan, left, right),
KCompareOp.LessEqual => Call(LessThanOrEqual, left, right),
KCompareOp.GreaterEqual => Call(GreaterThanOrEqual, left, right),
KCompareOp.Equal => Call(EqualsFn, left, right),
KCompareOp.NotEqual => Call(OnesComplement, Call(EqualsFn, left, right)),
_ => throw new KernelUnsupportedException("Unsupported SIMD comparison."),
};
}
throw new KernelUnsupportedException("Unsupported SIMD condition.");
}
private static Expression ClampByte(Expression value)
{
var low = Select(Call(LessThan, value, Zero), Zero, value);
return Select(Call(GreaterThan, low, V255), V255, low);
}
private static Expression Select(Expression condition, Expression whenTrue, Expression whenFalse) =>
Expression.Call(ConditionalSelect, condition, whenTrue, whenFalse);
private static Expression LoadChannel(ParameterExpression buffer, ParameterExpression index, int offset) =>
Expression.Call(Create4,
ToDouble(ReadByte(buffer, index, offset)),
ToDouble(ReadByte(buffer, index, offset + 4)),
ToDouble(ReadByte(buffer, index, offset + 8)),
ToDouble(ReadByte(buffer, index, offset + 12)));
private static Expression StoreChannel(ParameterExpression buffer, ParameterExpression index, int offset, Expression value)
{
var writes = new Expression[4];
for (int lane = 0; lane < 4; lane++)
writes[lane] = Expression.Assign(
Expression.ArrayAccess(buffer, Expression.Add(index, Constant(lane * 4 + offset))),
Expression.Convert(Expression.Call(GetElement, value, Constant(lane)), typeof(byte)));
return Expression.Block(writes);
}
private static Expression ReadByte(ParameterExpression buffer, ParameterExpression index, int offset) =>
Expression.ArrayIndex(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset)));
private static Expression Call(MethodInfo method, params Expression[] arguments) =>
Expression.Call(method, arguments);
private static Expression ToDouble(Expression value) => Expression.Convert(value, typeof(double));
private static ConstantExpression Constant(int value) => Expression.Constant(value, typeof(int));
private static MethodInfo VecOp(string name, int vectorArgs, int intArgs = 0) =>
typeof(Vector256).GetMethods()
.Single(m => m.Name == name && m.IsGenericMethodDefinition &&
m.GetParameters().Length == vectorArgs + intArgs &&
m.GetParameters().Take(vectorArgs).All(p => IsVector(p.ParameterType)) &&
m.GetParameters().Skip(vectorArgs).All(p => p.ParameterType == typeof(int)))
.MakeGenericMethod(typeof(double));
private static bool IsVector(Type type) =>
type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Vector256<>);
}
}
+93 -68
ファイルの表示
@@ -29,7 +29,10 @@ namespace LuaScript.Engine
private readonly double[] _anchorBuffer = new double[Anchor.AnchorSupport.MaxAnchors * 3]; private readonly double[] _anchorBuffer = new double[Anchor.AnchorSupport.MaxAnchors * 3];
private int _lastCallbackTagLength = -1; private int _lastCallbackTagLength = -1;
private string _lastCallbackTagText = string.Empty; private string _lastCallbackTagText = string.Empty;
private byte[]? _resultBuffer; private int _scriptVersion;
private string? _lastScript;
private byte[] _lastScriptBytes = Array.Empty<byte>();
private bool _scriptWritten;
private readonly Dictionary<string, byte[]> _stringNameBytes = new(StringComparer.Ordinal); private readonly Dictionary<string, byte[]> _stringNameBytes = new(StringComparer.Ordinal);
private byte[] _stringValueBytes = new byte[256]; private byte[] _stringValueBytes = new byte[256];
@@ -48,7 +51,7 @@ namespace LuaScript.Engine
string script, string script,
double[] fields, double[] fields,
IReadOnlyDictionary<string, string> stringParameters, IReadOnlyDictionary<string, string> stringParameters,
Func<byte[]> loadPixels, PixelRegionAccess loadPixels,
int width, int width,
int height, int height,
int timeoutMs, int timeoutMs,
@@ -62,23 +65,28 @@ namespace LuaScript.Engine
Action<string, int, bool, int, double[]> setAnchor, Action<string, int, bool, int, double[]> setAnchor,
out bool pixelsDirty, out bool pixelsDirty,
out bool bufferReplaced, out bool bufferReplaced,
out byte[]? resultPixels,
out int resultWidth, out int resultWidth,
out int resultHeight, out int resultHeight,
out string? error) out string? error)
{ {
pixelsDirty = false; pixelsDirty = false;
bufferReplaced = false; bufferReplaced = false;
resultPixels = null;
resultWidth = width; resultWidth = width;
resultHeight = height; resultHeight = height;
error = null; error = null;
byte[] scriptBytes = Encoding.UTF8.GetBytes(script); bool scriptChanged = !ReferenceEquals(script, _lastScript);
if (scriptBytes.Length > NativeProtocol.ScriptMax) if (scriptChanged)
{ {
error = "script too large for native lane"; byte[] scriptBytes = Encoding.UTF8.GetBytes(script);
return false; if (scriptBytes.Length > NativeProtocol.ScriptMax)
{
error = "script too large for native lane";
return false;
}
_lastScript = script;
_lastScriptBytes = scriptBytes;
_scriptVersion++;
} }
int stringCapacity = ResolveStringCapacity(_stringParamsCapacity, MeasureStringParameters(stringParameters)); int stringCapacity = ResolveStringCapacity(_stringParamsCapacity, MeasureStringParameters(stringParameters));
@@ -89,8 +97,13 @@ namespace LuaScript.Engine
WriteStringParameters(view, stringParameters); WriteStringParameters(view, stringParameters);
view.Write(NativeProtocol.OffWidth, width); view.Write(NativeProtocol.OffWidth, width);
view.Write(NativeProtocol.OffHeight, height); view.Write(NativeProtocol.OffHeight, height);
view.Write(NativeProtocol.OffScriptLen, scriptBytes.Length); if (scriptChanged || !_scriptWritten)
view.WriteArray(NativeProtocol.ScriptOffset, scriptBytes, 0, scriptBytes.Length); {
view.Write(NativeProtocol.OffScriptLen, _lastScriptBytes.Length);
view.WriteArray(NativeProtocol.ScriptOffset, _lastScriptBytes, 0, _lastScriptBytes.Length);
_scriptWritten = true;
}
view.Write(NativeProtocol.OffScriptVersion, _scriptVersion);
view.Write(NativeProtocol.OffPixelsDirty, 0); view.Write(NativeProtocol.OffPixelsDirty, 0);
view.Write(NativeProtocol.OffErrorLen, 0); view.Write(NativeProtocol.OffErrorLen, 0);
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle); view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
@@ -98,7 +111,6 @@ namespace LuaScript.Engine
_workEvent!.Set(); _workEvent!.Set();
byte[]? uploadedPixels = null;
var stopwatch = Stopwatch.StartNew(); var stopwatch = Stopwatch.StartNew();
int status; int status;
while (true) while (true)
@@ -115,14 +127,26 @@ namespace LuaScript.Engine
if (status != NativeProtocol.StatusCallback) if (status != NativeProtocol.StatusCallback)
break; break;
if (view.ReadInt32(NativeProtocol.OffCallbackKind) == NativeProtocol.CbKindRequestPixels) int callbackKind = view.ReadInt32(NativeProtocol.OffCallbackKind);
if (callbackKind == NativeProtocol.CbKindRequestPixels)
{ {
uploadedPixels ??= loadPixels(); try
WritePixelRegion(uploadedPixels, uploadedPixels.Length); {
AccessPixelRegion(loadPixels);
}
catch
{
KillWorker();
throw;
}
}
else if (callbackKind == NativeProtocol.CbKindFlushDraws)
{
DrainDrawRing(view, addDraw);
} }
else else
{ {
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, addDraw, setAnchor); DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, setAnchor);
} }
_workEvent.Set(); _workEvent.Set();
} }
@@ -136,6 +160,8 @@ namespace LuaScript.Engine
return false; return false;
} }
DrainDrawRing(view, addDraw);
for (int i = NativeProtocol.FirstWritableField; i <= NativeProtocol.LastWritableField; i++) for (int i = NativeProtocol.FirstWritableField; i <= NativeProtocol.LastWritableField; i++)
fields[i] = view.ReadDouble(NativeProtocol.FieldsOffset + i * 8); fields[i] = view.ReadDouble(NativeProtocol.FieldsOffset + i * 8);
@@ -146,26 +172,33 @@ namespace LuaScript.Engine
bufferReplaced = resultWidth != width || resultHeight != height; bufferReplaced = resultWidth != width || resultHeight != height;
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0; pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
if (pixelsDirty) if (pixelsDirty && (long)resultWidth * resultHeight * 4 > _allocatedSize - _pixelOffset)
{ {
int pixelSize = resultWidth * resultHeight * 4; error = "native worker reported a pixel buffer beyond capacity";
if (!bufferReplaced && uploadedPixels is not null) return false;
{
ReadPixelRegion(uploadedPixels, pixelSize);
resultPixels = uploadedPixels;
}
else
{
if (_resultBuffer == null || _resultBuffer.Length < pixelSize)
_resultBuffer = new byte[pixelSize];
ReadPixelRegion(_resultBuffer, pixelSize);
resultPixels = _resultBuffer;
}
} }
return true; return true;
} }
public void ReadPixels(PixelRegionAccess reader) => AccessPixelRegion(reader);
private unsafe void AccessPixelRegion(PixelRegionAccess access)
{
var handle = _view!.SafeMemoryMappedViewHandle;
byte* ptr = null;
handle.AcquirePointer(ref ptr);
try
{
long offset = _view.PointerOffset + _pixelOffset;
access((nint)(ptr + offset), (long)handle.ByteLength - offset);
}
finally
{
handle.ReleasePointer();
}
}
private unsafe void WritePixelRegion(byte[] source, int length) private unsafe void WritePixelRegion(byte[] source, int length)
{ {
var handle = _view!.SafeMemoryMappedViewHandle; var handle = _view!.SafeMemoryMappedViewHandle;
@@ -182,22 +215,6 @@ namespace LuaScript.Engine
} }
} }
private unsafe void ReadPixelRegion(byte[] destination, int length)
{
var handle = _view!.SafeMemoryMappedViewHandle;
byte* ptr = null;
handle.AcquirePointer(ref ptr);
try
{
fixed (byte* dst = destination)
Buffer.MemoryCopy(ptr + _view.PointerOffset + _pixelOffset, dst, destination.Length, length);
}
finally
{
handle.ReleasePointer();
}
}
private static int MeasureStringParameters(IReadOnlyDictionary<string, string> stringParameters) private static int MeasureStringParameters(IReadOnlyDictionary<string, string> stringParameters)
{ {
int total = 4; int total = 4;
@@ -259,7 +276,6 @@ namespace LuaScript.Engine
Func<string, (byte[] buffer, int w, int h)> loadImage, Func<string, (byte[] buffer, int w, int h)> loadImage,
Func<string, double, (byte[] buffer, int w, int h)> loadMovie, Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect, Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
Action<DrawCommand> addDraw,
Action<string, int, bool, int, double[]> setAnchor) Action<string, int, bool, int, double[]> setAnchor)
{ {
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind); int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
@@ -283,12 +299,6 @@ namespace LuaScript.Engine
case NativeProtocol.CbKindEffect: case NativeProtocol.CbKindEffect:
ResolveEffectCallback(view, addEffect); ResolveEffectCallback(view, addEffect);
break; break;
case NativeProtocol.CbKindDraw:
ResolveDrawCallback(view, addDraw);
break;
case NativeProtocol.CbKindDrawPoly:
ResolveDrawPolyCallback(view, addDraw);
break;
case NativeProtocol.CbKindSetAnchor: case NativeProtocol.CbKindSetAnchor:
ResolveSetAnchorCallback(view, setAnchor); ResolveSetAnchorCallback(view, setAnchor);
break; break;
@@ -316,34 +326,48 @@ namespace LuaScript.Engine
view.Write(NativeProtocol.OffCallbackFound, 1); view.Write(NativeProtocol.OffCallbackFound, 1);
} }
private static void ResolveDrawCallback(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw) private void DrainDrawRing(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
{ {
long rOff = NativeProtocol.CallbackResultOffset; long ringBase = NativeProtocol.DrawRingOffset(_stringParamsCapacity);
double ox = view.ReadDouble(rOff + 0 * 8); int count = Math.Clamp((int)view.ReadDouble(ringBase), 0, NativeProtocol.DrawRingCapacity);
double oy = view.ReadDouble(rOff + 1 * 8); for (int k = 0; k < count; k++)
double oz = view.ReadDouble(rOff + 2 * 8); {
double zoom = view.ReadDouble(rOff + 3 * 8); long entry = ringBase + (1 + (long)k * NativeProtocol.DrawEntryDoubles) * 8;
double alpha = view.ReadDouble(rOff + 4 * 8); int kind = (int)view.ReadDouble(entry);
double aspect = view.ReadDouble(rOff + 5 * 8); long payload = entry + 8;
double antialias = view.ReadDouble(rOff + 6 * 8); if (kind == NativeProtocol.CbKindDrawPoly)
double blend = view.ReadDouble(rOff + 7 * 8); DispatchRingDrawPoly(view, payload, addDraw);
else
DispatchRingDraw(view, payload, addDraw);
}
view.Write(ringBase, 0d);
}
private static void DispatchRingDraw(MemoryMappedViewAccessor view, long payload, Action<DrawCommand> addDraw)
{
double ox = view.ReadDouble(payload + 0 * 8);
double oy = view.ReadDouble(payload + 1 * 8);
double oz = view.ReadDouble(payload + 2 * 8);
double zoom = view.ReadDouble(payload + 3 * 8);
double alpha = view.ReadDouble(payload + 4 * 8);
double aspect = view.ReadDouble(payload + 5 * 8);
double antialias = view.ReadDouble(payload + 6 * 8);
double blend = view.ReadDouble(payload + 7 * 8);
try { addDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, antialias, blend)); } try { addDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, antialias, blend)); }
catch { } catch { }
view.Write(NativeProtocol.OffCallbackFound, 1);
} }
private static void ResolveDrawPolyCallback(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw) private static void DispatchRingDrawPoly(MemoryMappedViewAccessor view, long payload, Action<DrawCommand> addDraw)
{ {
var poly = new double[DrawPolyMath.Length]; var poly = new double[DrawPolyMath.Length];
for (int i = 0; i < DrawPolyMath.Length; i++) for (int i = 0; i < DrawPolyMath.Length; i++)
poly[i] = view.ReadDouble(NativeProtocol.CallbackTagOffset + i * 8); poly[i] = view.ReadDouble(payload + i * 8);
double antialias = view.ReadDouble(NativeProtocol.CallbackTagOffset + DrawPolyMath.Length * 8); double antialias = view.ReadDouble(payload + DrawPolyMath.Length * 8);
double blend = view.ReadDouble(NativeProtocol.CallbackTagOffset + (DrawPolyMath.Length + 1) * 8); double blend = view.ReadDouble(payload + (DrawPolyMath.Length + 1) * 8);
try { addDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, antialias, blend)); } try { addDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, antialias, blend)); }
catch { } catch { }
view.Write(NativeProtocol.OffCallbackFound, 1);
} }
private void ResolveGetObjectCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject) private void ResolveGetObjectCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject)
@@ -553,6 +577,7 @@ namespace LuaScript.Engine
private void StartWorker(int width, int height, int stringCapacity) private void StartWorker(int width, int height, int stringCapacity)
{ {
_stringParamsCapacity = stringCapacity; _stringParamsCapacity = stringCapacity;
_scriptWritten = false;
_pixelOffset = NativeProtocol.PixelOffset(stringCapacity); _pixelOffset = NativeProtocol.PixelOffset(stringCapacity);
long size = Math.Max(NativeProtocol.BufferSize(width, height, stringCapacity), _allocatedSize); long size = Math.Max(NativeProtocol.BufferSize(width, height, stringCapacity), _allocatedSize);
_allocatedSize = size; _allocatedSize = size;
+10 -1
ファイルの表示
@@ -27,6 +27,7 @@ namespace LuaScript.Engine
public const int OffLoadResultWidth = 48; public const int OffLoadResultWidth = 48;
public const int OffLoadResultHeight = 52; public const int OffLoadResultHeight = 52;
public const int OffStringParamsLen = 56; public const int OffStringParamsLen = 56;
public const int OffScriptVersion = 60;
public const int HeaderSize = 64; public const int HeaderSize = 64;
@@ -57,6 +58,12 @@ namespace LuaScript.Engine
public const int CbKindLoadMovie = 7; public const int CbKindLoadMovie = 7;
public const int CbKindSetAnchor = 8; public const int CbKindSetAnchor = 8;
public const int CbKindRequestPixels = 9; public const int CbKindRequestPixels = 9;
public const int CbKindFlushDraws = 10;
public const int DrawRingCapacity = 4096;
public const int DrawEntryDoubles = 24;
public const int DrawRingDoubles = 1 + DrawRingCapacity * DrawEntryDoubles;
public const long DrawRingBytes = (long)DrawRingDoubles * 8;
public const int CbExist = 0; public const int CbExist = 0;
public const int CbX = 1; public const int CbX = 1;
@@ -67,7 +74,9 @@ namespace LuaScript.Engine
public const int CbAlpha = 6; public const int CbAlpha = 6;
public const int CbLayer = 7; public const int CbLayer = 7;
public static int PixelOffset(int stringCapacity) => StringParamsOffset + stringCapacity; public static long DrawRingOffset(int stringCapacity) => StringParamsOffset + stringCapacity;
public static long PixelOffset(int stringCapacity) => DrawRingOffset(stringCapacity) + DrawRingBytes;
public const int W = 0; public const int W = 0;
public const int H = 1; public const int H = 1;
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine
{
internal delegate void PixelRegionAccess(nint address, long capacity);
}
+1 -1
ファイルの表示
@@ -4,7 +4,7 @@
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework> <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF> <UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Version>1.11.4</Version> <Version>1.12.0</Version>
<Platforms>AnyCPU;x64</Platforms> <Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+70 -17
ファイルの表示
@@ -42,7 +42,7 @@ namespace LuaScript
bool Check3, bool Check3,
bool HasColor, bool HasColor,
int Color, int Color,
string Script, int ScriptVersion,
int StringsVersion, int StringsVersion,
TimelineSourceUsage Usage, TimelineSourceUsage Usage,
Guid SceneId, Guid SceneId,
@@ -76,6 +76,9 @@ namespace LuaScript
private bool _effectChainWarned; private bool _effectChainWarned;
private bool _gpuWarned; private bool _gpuWarned;
private string? _scriptKeyRef;
private int _scriptKeyVersion;
private string _kernelSource = string.Empty; private string _kernelSource = string.Empty;
private bool _kernelResolved; private bool _kernelResolved;
private KernelProgram? _kernelProgram; private KernelProgram? _kernelProgram;
@@ -107,8 +110,14 @@ namespace LuaScript
private bool _hasExplicitDirective; private bool _hasExplicitDirective;
private ScriptEngineKind _explicitDirectiveKind; private ScriptEngineKind _explicitDirectiveKind;
private byte[]? _nativeInputPixels; private PixelRegionAccess? _nativeUpload;
private Func<byte[]>? _nativeLoadInput; private PixelRegionAccess? _nativeReadIntoResult;
private PixelRegionAccess? _nativeWriteOutput;
private byte[]? _nativeResultBuffer;
private int _nativeReadLength;
private int _nativeOutputWidth;
private int _nativeOutputHeight;
private bool _nativeUploaded;
private Func<string, int, SceneObjectInfo?>? _nativeResolveObject; private Func<string, int, SceneObjectInfo?>? _nativeResolveObject;
private Func<string, int, double, double, double, (byte[] buffer, int w, int h)>? _nativeLoadFigure; private Func<string, int, double, double, double, (byte[] buffer, int w, int h)>? _nativeLoadFigure;
private Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)>? _nativeLoadText; private Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)>? _nativeLoadText;
@@ -242,6 +251,11 @@ namespace LuaScript
var fps = desc.FPS; var fps = desc.FPS;
var time = desc.ItemPosition.Time.TotalSeconds; var time = desc.ItemPosition.Time.TotalSeconds;
var script = item.Script ?? string.Empty; var script = item.Script ?? string.Empty;
if (!ReferenceEquals(script, _scriptKeyRef))
{
_scriptKeyRef = script;
_scriptKeyVersion++;
}
var layout = item.Layout; var layout = item.Layout;
var t0 = ClampTrack(item.Track0.GetValue(frame, length, fps), layout, 0); var t0 = ClampTrack(item.Track0.GetValue(frame, length, fps), layout, 0);
@@ -261,7 +275,7 @@ namespace LuaScript
t0, t1, t2, t3, t0, t1, t2, t3,
s0, s1, s2, s3, s0, s1, s2, s3,
c0, c1, c2, c3, hasColor, colorRgb, c0, c1, c2, c3, hasColor, colorRgb,
script, RefreshStringParameters(), _scriptKeyVersion, RefreshStringParameters(),
desc.Usage, desc.SceneId, desc.Usage, desc.SceneId,
desc.TimelinePosition.Frame, desc.TimelinePosition.Frame,
desc.TimelinePosition.Time.TotalSeconds, desc.TimelinePosition.Time.TotalSeconds,
@@ -840,7 +854,7 @@ namespace LuaScript
{ {
_nativeWorker ??= new LuaJitWorker(NativeDirectory); _nativeWorker ??= new LuaJitWorker(NativeDirectory);
_nativeFields ??= new double[NativeProtocol.FieldCount]; _nativeFields ??= new double[NativeProtocol.FieldCount];
_nativeLoadInput ??= () => _nativeInputPixels ??= LoadPendingInputPixels(); _nativeUpload ??= UploadNativeInputPixels;
_nativeResolveObject ??= (tag, frame) => _context.ResolveObject(tag, frame, out var info) ? info : null; _nativeResolveObject ??= (tag, frame) => _context.ResolveObject(tag, frame, out var info) ? info : null;
_nativeLoadFigure ??= NativeLoadFigure; _nativeLoadFigure ??= NativeLoadFigure;
_nativeLoadText ??= NativeLoadText; _nativeLoadText ??= NativeLoadText;
@@ -851,10 +865,10 @@ namespace LuaScript
_nativeSetAnchor ??= ResolveNativeAnchor; _nativeSetAnchor ??= ResolveNativeAnchor;
NativeFieldMap.ToFields(ctx, _nativeFields); NativeFieldMap.ToFields(ctx, _nativeFields);
_nativeInputPixels = null; _nativeUploaded = false;
bool ok = _nativeWorker.Execute( bool ok = _nativeWorker.Execute(
script, _nativeFields, ctx.StringParameters, _nativeLoadInput, imgW, imgH, NativeTimeoutMilliseconds, script, _nativeFields, ctx.StringParameters, _nativeUpload, imgW, imgH, NativeTimeoutMilliseconds,
_nativeResolveObject, _nativeResolveObject,
_nativeLoadFigure, _nativeLoadFigure,
_nativeLoadText, _nativeLoadText,
@@ -863,7 +877,7 @@ namespace LuaScript
_nativeAddEffect, _nativeAddEffect,
_nativeAddDraw, _nativeAddDraw,
_nativeSetAnchor, _nativeSetAnchor,
out bool dirty, out bool bufferReplaced, out byte[]? resultPixels, out bool dirty, out bool bufferReplaced,
out int resultW, out int resultH, out string? error); out int resultW, out int resultH, out string? error);
if (!ok) if (!ok)
@@ -877,31 +891,35 @@ namespace LuaScript
bool hasDraws = ctx.DrawCommands.Count > 0; bool hasDraws = ctx.DrawCommands.Count > 0;
if (dirty && resultPixels is not null) if (dirty)
{ {
int outW = bufferReplaced ? resultW : imgW; int outW = bufferReplaced ? resultW : imgW;
int outH = bufferReplaced ? resultH : imgH; int outH = bufferReplaced ? resultH : imgH;
if (bufferReplaced)
ctx.ReplaceBuffer(resultPixels, outW, outH);
if (hasDraws) if (hasDraws)
{ {
ctx.SetResolvedBuffer(resultPixels, outW, outH); var result = ReadNativeResultPixels(outW, outH);
if (bufferReplaced)
ctx.ReplaceBuffer(result, outW, outH);
else
ctx.SetResolvedBuffer(result, outW, outH);
return true; return true;
} }
_pixelManager!.WritePixelsToOutput(resultPixels, outW, outH); _nativeOutputWidth = outW;
_nativeOutputHeight = outH;
_nativeWorker.ReadPixels(_nativeWriteOutput ??= WriteNativeOutputPixels);
if (bufferReplaced) if (bufferReplaced)
effectOutput = _pixelManager.GetTransformOutput(-outW / 2f, -outH / 2f); effectOutput = _pixelManager!.GetTransformOutput(-outW / 2f, -outH / 2f);
else else
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top); effectOutput = _pixelManager!.GetTransformOutput(bounds.Left, bounds.Top);
return true; return true;
} }
if (hasDraws) if (hasDraws)
{ {
ctx.SetResolvedBuffer(_nativeLoadInput(), imgW, imgH); if (_nativeUploaded)
ctx.SetResolvedBuffer(ReadNativeResultPixels(imgW, imgH), imgW, imgH);
return false; return false;
} }
@@ -909,6 +927,41 @@ namespace LuaScript
return false; return false;
} }
private void UploadNativeInputPixels(nint address, long capacity)
{
_nativeUploaded = true;
_pixelLoaderSemaphore.Wait();
try
{
_pixelManager!.LoadInputPixelsInto(input!, _pixelBounds, _pixelWidth, _pixelHeight, address, capacity);
}
finally
{
_pixelLoaderSemaphore.Release();
}
}
private byte[] ReadNativeResultPixels(int width, int height)
{
int length = width * height * 4;
if (_nativeResultBuffer is null || _nativeResultBuffer.Length < length)
_nativeResultBuffer = new byte[length];
_nativeReadLength = length;
_nativeWorker!.ReadPixels(_nativeReadIntoResult ??= ReadNativePixelsIntoResult);
return _nativeResultBuffer;
}
private unsafe void ReadNativePixelsIntoResult(nint address, long capacity)
{
fixed (byte* destination = _nativeResultBuffer)
Buffer.MemoryCopy((void*)address, destination, _nativeResultBuffer!.Length, Math.Min(_nativeReadLength, capacity));
}
private void WriteNativeOutputPixels(nint address, long capacity)
{
_pixelManager!.WritePixelsToOutput(address, _nativeOutputWidth, _nativeOutputHeight);
}
private void ResolveNativeAnchor(string group, int count, bool is3D, int connection, double[] positions) private void ResolveNativeAnchor(string group, int count, bool is3D, int connection, double[] positions)
{ {
_context.AddAnchorRequest(new AnchorRequestData(group, count, (AnchorConnection)connection, is3D)); _context.AddAnchorRequest(new AnchorRequestData(group, count, (AnchorConnection)connection, is3D));
+66 -30
ファイルの表示
@@ -1,7 +1,6 @@
using System; using System;
using Vortice; using Vortice;
using System.Numerics; using System.Numerics;
using System.Runtime.InteropServices;
using Vortice.DCommon; using Vortice.DCommon;
using Vortice.Direct2D1; using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects; using Vortice.Direct2D1.Effects;
@@ -29,10 +28,56 @@ namespace LuaScript
_ctx = ctx; _ctx = ctx;
} }
public byte[] LoadInputPixels(ID2D1Image input, RawRectF bounds, int width, int height) public unsafe byte[] LoadInputPixels(ID2D1Image input, RawRectF bounds, int width, int height)
{ {
EnsureBitmaps(width, height); EnsureBitmaps(width, height);
RenderToStaging(input, bounds);
var mapped = _stagingBitmap!.Map(MapOptions.Read);
try
{
fixed (byte* destination = _pixelBuffer)
CopyStagingRows(mapped.Bits, mapped.Pitch, destination, _pixelBuffer!.Length, width, height);
}
finally
{
_stagingBitmap.Unmap();
}
return _pixelBuffer!;
}
public unsafe void LoadInputPixelsInto(ID2D1Image input, RawRectF bounds, int width, int height, nint destination, long capacity)
{
EnsureBitmaps(width, height);
RenderToStaging(input, bounds);
var mapped = _stagingBitmap!.Map(MapOptions.Read);
try
{
CopyStagingRows(mapped.Bits, mapped.Pitch, (byte*)destination, capacity, width, height);
}
finally
{
_stagingBitmap.Unmap();
}
}
public unsafe void WritePixelsToOutput(byte[] pixels, int width, int height)
{
EnsureBitmaps(width, height);
fixed (byte* ptr = pixels)
_outputBitmap!.CopyFromMemory(new nint(ptr), width * 4);
}
public void WritePixelsToOutput(nint source, int width, int height)
{
EnsureBitmaps(width, height);
_outputBitmap!.CopyFromMemory(source, width * 4);
}
private void RenderToStaging(ID2D1Image input, RawRectF bounds)
{
var dc = _ctx.DeviceContext; var dc = _ctx.DeviceContext;
using var savedTarget = dc.Target; using var savedTarget = dc.Target;
@@ -44,37 +89,28 @@ namespace LuaScript
dc.Target = savedTarget; dc.Target = savedTarget;
_stagingBitmap!.CopyFromBitmap(_renderTarget!); _stagingBitmap!.CopyFromBitmap(_renderTarget!);
var mapped = _stagingBitmap.Map(MapOptions.Read);
try
{
if (mapped.Pitch == width * 4)
{
Marshal.Copy(mapped.Bits, _pixelBuffer!, 0, width * height * 4);
}
else
{
for (int row = 0; row < height; row++)
Marshal.Copy(
mapped.Bits + mapped.Pitch * row,
_pixelBuffer!,
row * width * 4,
width * 4);
}
}
finally
{
_stagingBitmap.Unmap();
}
return _pixelBuffer!;
} }
public unsafe void WritePixelsToOutput(byte[] pixels, int width, int height) private static unsafe void CopyStagingRows(nint bits, int pitch, byte* destination, long capacity, int width, int height)
{ {
EnsureBitmaps(width, height); long required = (long)width * height * 4;
fixed (byte* ptr = pixels) if (required > capacity)
_outputBitmap!.CopyFromMemory(new nint(ptr), width * 4); throw new InvalidOperationException("Pixel destination is smaller than the mapped region.");
byte* source = (byte*)bits;
if (pitch == width * 4)
{
Buffer.MemoryCopy(source, destination, capacity, required);
return;
}
long rowBytes = (long)width * 4;
for (int row = 0; row < height; row++)
Buffer.MemoryCopy(
source + (long)pitch * row,
destination + rowBytes * row,
capacity - rowBytes * row,
rowBytes);
} }
public ID2D1Image GetTransformOutput(float left, float top) public ID2D1Image GetTransformOutput(float left, float top)
+8 -4
ファイルの表示
@@ -24,13 +24,17 @@ namespace LuaScript
{ {
byte* pixel = p + pixelIndex * 4; byte* pixel = p + pixelIndex * 4;
double a = pixel[3]; double a = pixel[3];
if (channel == 3)
return a;
if (a <= 0d)
return 0d;
double scale = 255d / a;
return channel switch return channel switch
{ {
0 => a > 0d ? Math.Clamp(pixel[2] * 255d / a, 0d, 255d) : 0d, 0 => Math.Clamp(pixel[2] * scale, 0d, 255d),
1 => a > 0d ? Math.Clamp(pixel[1] * 255d / a, 0d, 255d) : 0d, 1 => Math.Clamp(pixel[1] * scale, 0d, 255d),
2 => a > 0d ? Math.Clamp(pixel[0] * 255d / a, 0d, 255d) : 0d, 2 => Math.Clamp(pixel[0] * scale, 0d, 255d),
3 => a,
_ => throw new UnreachableException() _ => throw new UnreachableException()
}; };
} }
+127 -72
ファイルの表示
@@ -51,13 +51,19 @@ local OFF_CB_KIND = 11
local OFF_LOAD_RESULT_W = 12 local OFF_LOAD_RESULT_W = 12
local OFF_LOAD_RESULT_H = 13 local OFF_LOAD_RESULT_H = 13
local OFF_STRING_PARAMS_LEN = 14 local OFF_STRING_PARAMS_LEN = 14
local OFF_SCRIPT_VERSION = 15
local SCRIPT_OFFSET = 64 + 64 * 8 local SCRIPT_OFFSET = 64 + 64 * 8
local ERROR_OFFSET = SCRIPT_OFFSET + 128 * 1024 local ERROR_OFFSET = SCRIPT_OFFSET + 128 * 1024
local CB_TAG_OFFSET = ERROR_OFFSET + 4 * 1024 local CB_TAG_OFFSET = ERROR_OFFSET + 4 * 1024
local CB_TAG_MAX = 4096 local CB_TAG_MAX = 4096
local CB_RESULT_OFFSET = CB_TAG_OFFSET + CB_TAG_MAX local CB_RESULT_OFFSET = CB_TAG_OFFSET + CB_TAG_MAX
local STRING_PARAMS_OFFSET = CB_RESULT_OFFSET + 8 * 8 local STRING_PARAMS_OFFSET = CB_RESULT_OFFSET + 8 * 8
local PIXEL_OFFSET = STRING_PARAMS_OFFSET + stringParamsCap local DRAW_RING_CAPACITY = 4096
local DRAW_ENTRY_DOUBLES = 24
local DRAW_RING_DOUBLES = 1 + DRAW_RING_CAPACITY * DRAW_ENTRY_DOUBLES
local DRAW_RING_BYTES = DRAW_RING_DOUBLES * 8
local DRAW_RING_OFFSET = STRING_PARAMS_OFFSET + stringParamsCap
local PIXEL_OFFSET = DRAW_RING_OFFSET + DRAW_RING_BYTES
local FIRST_WRITABLE = 8 local FIRST_WRITABLE = 8
local LAST_WRITABLE = 25 local LAST_WRITABLE = 25
local STATUS_CALLBACK = 3 local STATUS_CALLBACK = 3
@@ -71,6 +77,7 @@ local CB_KIND_LOADIMAGE = 6
local CB_KIND_LOADMOVIE = 7 local CB_KIND_LOADMOVIE = 7
local CB_KIND_SETANCHOR = 8 local CB_KIND_SETANCHOR = 8
local CB_KIND_REQUESTPIXELS = 9 local CB_KIND_REQUESTPIXELS = 9
local CB_KIND_FLUSHDRAWS = 10
assert(loadfile(shimPath))() assert(loadfile(shimPath))()
@@ -82,6 +89,7 @@ end
local width, height = 0, 0 local width, height = 0, 0
local pixels = ffi.cast("uint8_t*", base + PIXEL_OFFSET) local pixels = ffi.cast("uint8_t*", base + PIXEL_OFFSET)
local ringD = ffi.cast("double*", base + DRAW_RING_OFFSET)
local cbResult = ffi.cast("double*", base + CB_RESULT_OFFSET) local cbResult = ffi.cast("double*", base + CB_RESULT_OFFSET)
local cbTagD = ffi.cast("double*", base + CB_TAG_OFFSET) local cbTagD = ffi.cast("double*", base + CB_TAG_OFFSET)
local pixelCapacity = mapSize - PIXEL_OFFSET local pixelCapacity = mapSize - PIXEL_OFFSET
@@ -91,6 +99,7 @@ local pixeloptions = {}
local dirty = false local dirty = false
local pixelsValid = false local pixelsValid = false
local drawTarget = "frame" local drawTarget = "frame"
local pdData, pdCapacity, pdValid, pdDirty = nil, 0, false, false
local function ensurePixels() local function ensurePixels()
if pixelsValid then return end if pixelsValid then return end
@@ -101,6 +110,65 @@ local function ensurePixels()
pixelsValid = true pixelsValid = true
end end
local function flushDraws()
i32[OFF_CB_KIND] = CB_KIND_FLUSHDRAWS
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
end
local function ringSlot(kind)
local n = ringD[0]
if n >= DRAW_RING_CAPACITY then
flushDraws()
n = 0
end
local eb = 1 + n * DRAW_ENTRY_DOUBLES
ringD[eb] = kind
ringD[0] = n + 1
return eb
end
local function rebuildPixelData()
local count = width * height * 4
if not pdData or pdCapacity < count then
pdData = ffi.new("double[?]", count)
pdCapacity = count
end
for pi = 0, width * height - 1 do
local p = pixels + pi * 4
local di = pi * 4
local a = p[3]
pdData[di + 3] = a
if a <= 0 then
pdData[di] = 0; pdData[di + 1] = 0; pdData[di + 2] = 0
else
local s = 255 / a
pdData[di] = clamp(p[2] * s, 0, 255)
pdData[di + 1] = clamp(p[1] * s, 0, 255)
pdData[di + 2] = clamp(p[0] * s, 0, 255)
end
end
pdValid = true
pdDirty = false
end
local function flushPixelData()
if not pdDirty then return end
for pi = 0, width * height - 1 do
local di = pi * 4
local a = math.floor(clamp(pdData[di + 3], 0, 255))
local aK = a / 255
local p = pixels + pi * 4
p[0] = math.floor(clamp(pdData[di + 2] * aK, 0, 255))
p[1] = math.floor(clamp(pdData[di + 1] * aK, 0, 255))
p[2] = math.floor(clamp(pdData[di] * aK, 0, 255))
p[3] = a
end
dirty = true
pdDirty = false
end
local function sampleSource(src, srcW, srcH, u, v, linear) local function sampleSource(src, srcW, srcH, u, v, linear)
if not linear then if not linear then
local su = clamp(math.floor(u), 0, srcW - 1) local su = clamp(math.floor(u), 0, srcW - 1)
@@ -245,6 +313,7 @@ function obj.getpixel(x, y)
x = math.floor(x); y = math.floor(y) x = math.floor(x); y = math.floor(y)
if x < 0 or y < 0 or x >= width or y >= height then return 0, 0, 0, 0 end if x < 0 or y < 0 or x >= width or y >= height then return 0, 0, 0, 0 end
ensurePixels() ensurePixels()
flushPixelData()
local p = pixels + (y * width + x) * 4 local p = pixels + (y * width + x) * 4
local a = p[3] local a = p[3]
if a <= 0 then return 0, 0, 0, 0 end if a <= 0 then return 0, 0, 0, 0 end
@@ -256,6 +325,7 @@ function obj.setpixel(x, y, r, g, b, a)
x = math.floor(x); y = math.floor(y) x = math.floor(x); y = math.floor(y)
if x < 0 or y < 0 or x >= width or y >= height then return end if x < 0 or y < 0 or x >= width or y >= height then return end
ensurePixels() ensurePixels()
flushPixelData()
a = a or 255 a = a or 255
dirty = true dirty = true
local aK = clamp(a, 0, 255) / 255 local aK = clamp(a, 0, 255) / 255
@@ -264,58 +334,30 @@ function obj.setpixel(x, y, r, g, b, a)
p[1] = math.floor(clamp(g * aK, 0, 255)) p[1] = math.floor(clamp(g * aK, 0, 255))
p[2] = math.floor(clamp(r * aK, 0, 255)) p[2] = math.floor(clamp(r * aK, 0, 255))
p[3] = math.floor(clamp(a, 0, 255)) p[3] = math.floor(clamp(a, 0, 255))
pdValid = false
end end
function obj.getpixeldata() function obj.getpixeldata()
ensurePixels() ensurePixels()
if not pdValid then rebuildPixelData() end
local data = pdData
local total = width * height * 4 local total = width * height * 4
local buf = pixels
local pd = { width = width, height = height } local pd = { width = width, height = height }
function pd:get(index) function pd:get(index)
local zb = index - 1 local zb = index - 1
if zb < 0 or zb >= total then return 0 end if zb < 0 or zb >= total then return 0 end
local pi = math.floor(zb / 4) return data[zb]
local ch = zb - pi * 4
local p = buf + pi * 4
local a = p[3]
if ch == 3 then return a end
if a <= 0 then return 0 end
local sc = 255 / a
if ch == 0 then return clamp(p[2] * sc, 0, 255) end
if ch == 1 then return clamp(p[1] * sc, 0, 255) end
return clamp(p[0] * sc, 0, 255)
end end
function pd:set(index, value) function pd:set(index, value)
local zb = index - 1 local zb = index - 1
if zb < 0 or zb >= total then return end if zb < 0 or zb >= total then return end
dirty = true data[zb] = clamp(value, 0, 255)
local pi = math.floor(zb / 4) pdDirty = true
local ch = zb - pi * 4
local p = buf + pi * 4
local clamped = clamp(value, 0, 255)
if ch == 3 then
local oldA = p[3]
local newA = clamped
if oldA > 0 and newA > 0 then
local f = newA / oldA
p[0] = math.floor(clamp(p[0] * f, 0, 255))
p[1] = math.floor(clamp(p[1] * f, 0, 255))
p[2] = math.floor(clamp(p[2] * f, 0, 255))
elseif newA <= 0 then
p[0] = 0; p[1] = 0; p[2] = 0
end
p[3] = math.floor(newA)
else
local a = p[3]
local pm = clamped * (a / 255)
local bo = (ch == 0) and 2 or ((ch == 1) and 1 or 0)
p[bo] = math.floor(clamp(pm, 0, 255))
end
end end
return pd return pd
end end
function obj.putpixeldata() end function obj.putpixeldata() flushPixelData() end
function obj.rand(a, b, seed, frame) function obj.rand(a, b, seed, frame)
return aviutl_rand(a or 0, b or 0, seed or 0, frame or obj.frame or 0) return aviutl_rand(a or 0, b or 0, seed or 0, frame or obj.frame or 0)
@@ -344,6 +386,8 @@ local function applyLoadResult()
i32[OFF_HEIGHT] = newH i32[OFF_HEIGHT] = newH
dirty = true dirty = true
pixelsValid = true pixelsValid = true
pdValid = false
pdDirty = false
obj.w = newW; obj.h = newH obj.w = newW; obj.h = newH
obj.hw = newW / 2; obj.hh = newH / 2 obj.hw = newW / 2; obj.hh = newH / 2
obj.cx = newW / 2; obj.cy = newH / 2 obj.cx = newW / 2; obj.cy = newH / 2
@@ -463,23 +507,21 @@ end
function obj.draw(ox, oy, oz, zoom, alpha, aspect) function obj.draw(ox, oy, oz, zoom, alpha, aspect)
if drawTarget == "temp" then if drawTarget == "temp" then
ensurePixels() ensurePixels()
flushPixelData()
local t = ensureTemp() local t = ensureTemp()
compositeDrawInto(t.data, t.w, t.h, pixels, width, height, compositeDrawInto(t.data, t.w, t.h, pixels, width, height,
ox or 0, oy or 0, zoom or 1, aspect or 0, alpha or 1, (options.antialias or 1) ~= 0) ox or 0, oy or 0, zoom or 1, aspect or 0, alpha or 1, (options.antialias or 1) ~= 0)
return return
end end
cbResult[0] = ox or 0 local eb = ringSlot(CB_KIND_DRAW)
cbResult[1] = oy or 0 ringD[eb + 1] = ox or 0
cbResult[2] = oz or 0 ringD[eb + 2] = oy or 0
cbResult[3] = zoom or 1 ringD[eb + 3] = oz or 0
cbResult[4] = alpha or 1 ringD[eb + 4] = zoom or 1
cbResult[5] = aspect or 0 ringD[eb + 5] = alpha or 1
cbResult[6] = options.antialias or 1 ringD[eb + 6] = aspect or 0
cbResult[7] = options.blend or 0 ringD[eb + 7] = options.antialias or 1
i32[OFF_CB_KIND] = CB_KIND_DRAW ringD[eb + 8] = options.blend or 0
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
end end
function obj.drawpoly(...) function obj.drawpoly(...)
@@ -505,17 +547,15 @@ function obj.drawpoly(...)
p[20] = alpha p[20] = alpha
if drawTarget == "temp" then if drawTarget == "temp" then
ensurePixels() ensurePixels()
flushPixelData()
local t = ensureTemp() local t = ensureTemp()
compositeDrawPolyInto(t.data, t.w, t.h, pixels, width, height, p, alpha, (options.antialias or 1) ~= 0) compositeDrawPolyInto(t.data, t.w, t.h, pixels, width, height, p, alpha, (options.antialias or 1) ~= 0)
return return
end end
for i = 0, 20 do cbTagD[i] = p[i] end local eb = ringSlot(CB_KIND_DRAWPOLY)
cbTagD[21] = options.antialias or 1 for i = 0, 20 do ringD[eb + 1 + i] = p[i] end
cbTagD[22] = options.blend or 0 ringD[eb + 22] = options.antialias or 1
i32[OFF_CB_KIND] = CB_KIND_DRAWPOLY ringD[eb + 23] = options.blend or 0
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
end end
function obj.getvalue(target) function obj.getvalue(target)
@@ -602,6 +642,7 @@ function obj.copybuffer(dst, src)
local data, w, h local data, w, h
if sk == "o" then if sk == "o" then
ensurePixels() ensurePixels()
flushPixelData()
data = pixels data = pixels
w = width; h = height w = width; h = height
elseif sk == "t" or sk == "c" then elseif sk == "t" or sk == "c" then
@@ -620,6 +661,8 @@ function obj.copybuffer(dst, src)
i32[OFF_WIDTH] = w; i32[OFF_HEIGHT] = h i32[OFF_WIDTH] = w; i32[OFF_HEIGHT] = h
dirty = true dirty = true
pixelsValid = true pixelsValid = true
pdValid = false
pdDirty = false
obj.w = w; obj.h = h obj.w = w; obj.h = h
obj.hw = w / 2; obj.hh = h / 2 obj.hw = w / 2; obj.hh = h / 2
obj.cx = w / 2; obj.cy = h / 2 obj.cx = w / 2; obj.cy = h / 2
@@ -705,7 +748,8 @@ local objKeys = captureKeys(obj)
local sceneKeys = captureKeys(scene) local sceneKeys = captureKeys(scene)
local ymm4Keys = captureKeys(ymm4) local ymm4Keys = captureKeys(ymm4)
local compiledCode, compiledChunk local compiledCode, compiledChunk, compiledError
local lastScriptVersion
local function loadFields() local function loadFields()
width = i32[OFF_WIDTH] width = i32[OFF_WIDTH]
@@ -769,25 +813,35 @@ while true do
dirty = false dirty = false
pixelsValid = false pixelsValid = false
local scriptLen = i32[OFF_SCRIPTLEN] pdValid = false
local code = ffi.string(base + SCRIPT_OFFSET, scriptLen) pdDirty = false
ringD[0] = 0
if code ~= compiledCode then local version = i32[OFF_SCRIPT_VERSION]
local chunk, err = loadstring(code, "LuaScript") if version ~= lastScriptVersion then
if chunk then lastScriptVersion = version
compiledChunk = chunk local scriptLen = i32[OFF_SCRIPTLEN]
compiledCode = code local code = ffi.string(base + SCRIPT_OFFSET, scriptLen)
else if code ~= compiledCode then
compiledChunk = nil local chunk, err = loadstring(code, "LuaScript")
local msg = err or "compile error" if chunk then
ffi.copy(base + ERROR_OFFSET, msg, math.min(#msg, 4096)) compiledChunk = chunk
i32[OFF_ERRORLEN] = math.min(#msg, 4096) compiledCode = code
i32[OFF_STATUS] = 2 compiledError = nil
k32.SetEvent(doneEvent) else
compiledChunk = nil
compiledCode = code
compiledError = err or "compile error"
end
end end
end end
if compiledChunk and code == compiledCode then if not compiledChunk then
local msg = compiledError or "compile error"
ffi.copy(base + ERROR_OFFSET, msg, math.min(#msg, 4096))
i32[OFF_ERRORLEN] = math.min(#msg, 4096)
i32[OFF_STATUS] = 2
k32.SetEvent(doneEvent)
else
resetExtraKeys(sandbox, sandboxKeys) resetExtraKeys(sandbox, sandboxKeys)
resetExtraKeys(obj, objKeys) resetExtraKeys(obj, objKeys)
resetExtraKeys(scene, sceneKeys) resetExtraKeys(scene, sceneKeys)
@@ -803,6 +857,7 @@ while true do
setfenv(compiledChunk, sandbox) setfenv(compiledChunk, sandbox)
local ok, err = pcall(compiledChunk) local ok, err = pcall(compiledChunk)
if ok then if ok then
flushPixelData()
storeFields() storeFields()
local ds = options.draw_state local ds = options.draw_state
if ds == nil then f64[62] = 0 elseif ds == false or ds == 0 then f64[62] = 2 else f64[62] = 1 end if ds == nil then f64[62] = 0 elseif ds == false or ds == 0 then f64[62] = 2 else f64[62] = 1 end