コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
de6472c34b
|
||
|
|
55c8bffb70
|
||
|
|
8ca66bceb8
|
||
|
|
865f5117ea
|
||
|
|
b30f7a818b
|
||
|
|
95786a1f0a
|
||
|
|
cc07e2a83d
|
||
|
|
08e5e432b7
|
||
|
|
1e9b039cef
|
||
|
|
bad39fe0db
|
||
|
|
a5567a804d
|
||
|
|
a9cb4a9cda
|
||
|
|
9e9b5277af
|
||
|
|
1d8705c7ee
|
||
|
|
14683c7909
|
||
|
|
42b123ebc3
|
||
|
|
b0114abdb7
|
||
|
|
c21de5b3eb
|
||
|
|
bd891d9a1e
|
||
|
|
d2bef10085
|
||
|
|
3eafcdc70e
|
||
|
|
6f26fc95fa
|
||
|
|
88ce786d05
|
||
|
|
d69ae5f06e
|
||
|
|
d42d8a6764
|
||
|
|
8f9ace2dc8
|
||
|
|
c416e955a4
|
||
|
|
7362e70ab8
|
||
|
|
c9741836a5
|
||
|
|
afd57d758d
|
||
|
|
c56432dbd6
|
||
|
|
9493aef779
|
||
|
|
5d55f2c083
|
||
|
|
09918c2858
|
||
|
|
a687bba0ff
|
||
|
|
bb591b6fef
|
||
|
|
27d7294290
|
||
|
|
8d1cf91499
|
||
|
|
b2a1900616
|
||
|
|
f786250866
|
||
|
|
20dfba6e7e
|
||
|
|
5e40f45910
|
||
|
|
ea4f096bc4
|
||
|
|
d7812f39dc
|
||
|
|
77fdf60ec9
|
||
|
|
bcb9925953
|
||
|
|
ec7d8a1da4
|
||
|
|
098d6e498b
|
||
|
|
ccf37dd1d3
|
||
|
|
2ce3068d54
|
||
|
|
c2a1990501
|
||
|
|
4ac25584b9
|
||
|
|
5e40f30124
|
||
|
|
9d541e06b9
|
||
|
|
bca7b5707e
|
||
|
|
a17289a2da
|
||
|
|
71e6b71056
|
||
|
|
13a0602adb
|
||
|
|
6a0c993755
|
||
|
|
484a26ec45
|
||
|
|
a121a598b6
|
||
|
|
6dd70413a9
|
||
|
|
ac482b6041
|
||
|
|
c2761c0796
|
||
|
|
3bbd411d86
|
||
|
|
324faabb96
|
||
|
|
32b706cb8b
|
||
|
|
aa97c52b38
|
||
|
|
a2f0231739
|
||
|
|
2905192d3a
|
||
|
|
ee6f6bd9c1
|
||
|
|
8853f5e403
|
||
|
|
867de7aa73
|
||
|
|
e384d7e490
|
||
|
|
87e060d71d
|
||
|
|
9c6167d224
|
||
|
|
a8a91103e1
|
||
|
|
4a2f4b2dbb
|
||
|
|
33fc45639b
|
||
|
|
7af803e46e
|
||
|
|
48e8287704
|
||
|
|
7eff4591f0
|
||
|
|
5b1bb4ad6e
|
||
|
|
7f3e6b0019
|
||
|
|
7519a11851
|
||
|
|
4193c40f41
|
||
|
|
cd68bf86b0
|
||
|
|
9948204265
|
||
|
|
25670bde90
|
||
|
|
ae230c0e10
|
||
|
|
7ee8f1ccf0
|
||
|
|
da88898a67
|
||
|
|
3c63ba0729
|
||
|
|
e7382ac289
|
||
|
|
ee7e4f43bc
|
||
|
|
7dc6e9fb40
|
||
|
|
803534d804
|
||
|
|
a25803fa30
|
||
|
|
e42401670f
|
||
|
|
a139326c39
|
||
|
|
496c237f50
|
||
|
|
dfbcbded98
|
||
|
|
2ebbe3ced0
|
||
|
|
9671cba5a1
|
||
|
|
947532f064
|
||
|
|
6e3594eb01
|
||
|
|
abc7b2cde2
|
||
|
|
68d862ded0
|
||
|
|
d3060fd202
|
検索条件に一致するファイルはありません
+137
-39
@@ -1,61 +1,159 @@
|
||||
# v1.10.0 - Lua スクリプト for YMM4
|
||||
# v1.12.0 - Lua スクリプト for YMM4
|
||||
|
||||
エフェクトパネルへ新しいパラメータ入力欄を追加したリリースです。整数スライダー 4 本と、
|
||||
テキスト・フォント・フォルダ・ファイルの文字列入力をスクリプトから参照できるようにしました。
|
||||
文字列パラメータは MoonSharp とネイティブの両エンジンで同じ名前から参照でき、ネイティブでは
|
||||
共有メモリの文字列領域を必要量に応じて拡張・縮小します。あわせて毎フレームのアロケーションを
|
||||
見直し、補完候補を拡充しました。
|
||||
ネイティブレーンとカーネルの性能をまとめて引き上げたリリースです。プロセス間の
|
||||
画素転送、draw 呼び出しの往復、スクリプト本文の転送と比較、getpixeldata の実装、
|
||||
CPU カーネルの命令並列という経路ごとの無駄を系統的に削りました。あわせて、
|
||||
カーネル抽出の検査漏れや math.fmod の剰余の種類など、結果の正しさに関わる不具合を
|
||||
修正しました。全体の設計は「識別子と版数による変更検知」と「消費される境界での
|
||||
遅延実体化」で統一しています。
|
||||
|
||||
---
|
||||
|
||||
## 新機能・機能改善
|
||||
## 改善
|
||||
|
||||
### 1. 整数スライダー obj.slider0〜3
|
||||
### 1. ネイティブレーンの画素転送を直結化
|
||||
|
||||
数値スライダーを 4 本追加しました。各値は `obj.slider0`〜`obj.slider3` として参照できます。
|
||||
ネイティブレーンでは、Direct2D のステージングビットマップと共有メモリの間に中間の
|
||||
バッファを挟んでいたため、入力の転送で 2 回、結果の読み戻しで 2 回の複製が毎フレーム
|
||||
発生していました。本リリースでは両者をポインタで直結し、入力はステージングの Map から
|
||||
共有メモリへ、結果は共有メモリから出力ビットマップの CopyFromMemory へ、それぞれ
|
||||
1 回の複製で転送します。
|
||||
|
||||
- 値は整数で、小数は扱いません。表示範囲は `obj.slider0` が 1〜10、`obj.slider1` が 0〜100、
|
||||
`obj.slider2` が 0〜1000、`obj.slider3` が -1000〜1000 です。
|
||||
- 状態の切り替えなど、補間を伴わない整数値の受け渡しに使えます。
|
||||
- MoonSharp・ネイティブ・CPU/GPU カーネルのいずれのレーンからも参照できます。
|
||||
1920×1080 の BGRA フレームは約 8.3MB で、複製量は毎フレーム約 33MB から約 17MB へ
|
||||
半減します。開発機の実測ではこの規模の複製 1 回が約 0.4ms なので、画素を書き換える
|
||||
スクリプトで 1 フレームあたり約 0.8ms、4K では単純比例で約 3.2ms を複製から削れる
|
||||
計算です。draw 合成やバッファ置換のように従来形式のバッファが必要な経路に限り、
|
||||
そこでだけ実体化します。
|
||||
|
||||
### 2. 文字列パラメータ obj.text / obj.font / obj.dir / obj.file_*
|
||||
### 2. draw と drawpoly の呼び出しをリングバッファで一括化
|
||||
|
||||
テキスト・フォント・フォルダ・ファイルの入力欄を追加しました。
|
||||
ネイティブレーンの obj.draw と obj.drawpoly は、1 回の呼び出しごとにプロセス間の
|
||||
イベント往復を行っていました。本リリースでは共有メモリ上のリングバッファへ書き溜め、
|
||||
容量の 4096 件に達したときと実行の終わりにまとめて回収します。1 フレームに 1000 回
|
||||
draw するスクリプトなら、往復は 1000 回から 1 回になります。
|
||||
|
||||
- `obj.text` はテキスト入力欄の文字列、`obj.font` はフォント名、`obj.dir` はフォルダのパスです。
|
||||
- ファイル選択は種類ごとに `obj.file_video` / `obj.file_audio` / `obj.file_image` /
|
||||
`obj.file_project` / `obj.file_mp4` / `obj.file_exo` / `obj.file_subtitle` /
|
||||
`obj.file_shader` で参照し、選択したファイルのパスを取得します。
|
||||
- 取得したパスは `obj.load` へ渡して画像・動画の読み込みに使えます。
|
||||
- MoonSharp とネイティブの両エンジンで同じ名前から参照できます。
|
||||
### 3. getpixeldata を平坦な配列の遅延反映へ変更
|
||||
|
||||
### 3. 補完候補の拡充
|
||||
ネイティブレーンの getpixeldata は、添字 1 回の読み書きごとに座標の分解と除算、
|
||||
乗算済み表現との変換を行っていました。本リリースでは取得時に全画素を一度だけ
|
||||
変換して平坦な配列を作り、以後の読み書きは配列参照 1 回になります。書き込みは
|
||||
putpixeldata または次の画素操作の時点でまとめてフレームへ反映します。1920×1080 の
|
||||
全画素を添字で走査すると約 830 万回のアクセスになるため、1 回あたりの費用の削減が
|
||||
そのまま効きます。
|
||||
|
||||
スクリプトエディタの補完候補へ `obj.slider0`〜`obj.slider3` と、追加した文字列パラメータの
|
||||
各名前を加えました。
|
||||
### 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 圧力を取り除きました。
|
||||
|
||||
---
|
||||
|
||||
## 不具合修正
|
||||
|
||||
### getpixeldata の未反映の書き込みをフレーム置換時に破棄
|
||||
|
||||
obj.load や obj.copybuffer でフレームが置き換わった直後に、置換前の getpixeldata へ
|
||||
書き込んだ未反映の内容が新しいフレームへ流し込まれることがありました。フレームの
|
||||
置換時に未反映の書き込みを破棄するように修正しました。
|
||||
|
||||
### getpixeldata の色の復元順序を getpixel と統一
|
||||
|
||||
MoonSharp レーンの getpixeldata が乗算済み表現から色を復元する際の計算順序が
|
||||
getpixel と食い違っており、丸めで 1 階調ずれる可能性がありました。getpixel の順序へ
|
||||
統一し、MoonSharp、ネイティブ、カーネルの三経路が同じ結果を返すようにしました。
|
||||
|
||||
### カーネル抽出の検査漏れを修正
|
||||
|
||||
ループ変数や getpixeldata の参照名を内側のローカル変数が同じ名前で覆い隠す
|
||||
スクリプトを誤って抽出し、結果が変わる可能性がありました。該当する形の抽出を拒否し、
|
||||
従来の経路で実行するように修正しました。あわせて、getpixeldata への書き込み値が
|
||||
0 から 255 へ収められずにカーネル化されていた点を、MoonSharp と同じ挙動へ修正
|
||||
しました。
|
||||
|
||||
### math.fmod の剰余の種類を修正
|
||||
|
||||
カーネル実行の math.fmod が床方式の剰余で計算されており、負の値を渡したときに
|
||||
Lua の math.fmod と符号の異なる結果を返していました。被除数の符号を保つ切り捨て
|
||||
方式へ修正し、MoonSharp およびネイティブレーンと一致させました。
|
||||
|
||||
### draw リングの読み出し件数を容量へ制限
|
||||
|
||||
ホストが共有メモリ上の draw の件数をそのまま信頼していたため、値が壊れた場合に
|
||||
リングの範囲外を読み出す可能性がありました。件数を容量で制限するように修正しました。
|
||||
|
||||
---
|
||||
|
||||
## 互換性・後方互換
|
||||
|
||||
- スライダーと文字列パラメータは、スクリプト本体でそれらを参照したときだけエフェクトパネルへ
|
||||
表示されます。参照しない既存スクリプトの表示と挙動は変わりません。
|
||||
- CPU/GPU カーネルは数値計算に特化するため、文字列パラメータは扱いません。文字列を参照する
|
||||
スクリプトは MoonSharp かネイティブで実行してください。
|
||||
- トラックバー・チェックボックス・カラー・AviUtl 互換ヘッダの既存挙動は変わりません。
|
||||
- スクリプトの書き方と API に変更はありません。
|
||||
- カーネル実行で math.fmod を負の値に使っている場合は結果が変わります。従来の結果が
|
||||
誤りで、修正後は MoonSharp と同じ結果になります。
|
||||
- SIMD 経路の出力はスカラ経路とバイト単位で一致します。対象外の演算を含むカーネルは
|
||||
従来のスカラ経路で実行するため、出力の正しさに妥協はありません。採用の自動判定は
|
||||
実行時間だけを比較するもので、どちらの経路が選ばれても結果は同一です。
|
||||
- getpixeldata の書き込みがフレームへ反映されるのは putpixeldata または次の画素操作の
|
||||
時点になりましたが、読み出しの直前に必ず反映されるため、観測できる結果は変わり
|
||||
ません。
|
||||
- ネイティブ実行環境が無い場合は、従来どおり MoonSharp で実行します。
|
||||
|
||||
---
|
||||
|
||||
## 内部実装
|
||||
|
||||
- ネイティブの共有メモリへ文字列パラメータ領域を追加し、容量をワーカーの起動引数にしました。
|
||||
必要量が容量を超えると 2 倍へ拡張し、容量の半分以下に収まると縮小します。最小は 64KB で、
|
||||
容量の変化はワーカーの再生成のみで完結します。
|
||||
- 文字列パラメータの変更検出をバージョン方式へ変更し、フレームごとの署名文字列の生成を
|
||||
やめました。値の参照が変わったときだけ版数を進めます。
|
||||
- ネイティブの文字列書き込みで、名前のバイト列をキャッシュし、値のエンコード先バッファを
|
||||
再利用します。
|
||||
- スライダーの値は MoonSharp の obj テーブル・ネイティブのフィールド・CPU/GPU カーネルの
|
||||
ユニフォームへ配線しました。スクリプトの使用検出は obj メンバを汎用的に走査する方式へ
|
||||
再設計しました。
|
||||
- 転送の契約を PixelRegionAccess へ統一し、LuaJitWorker と PixelBufferManager を
|
||||
ポインタで直結しました。ワーカーが報告する結果寸法は共有メモリの容量で検査し、
|
||||
アップロード中に例外が起きた場合はワーカーを破棄して次回の実行で再起動します。
|
||||
- NativeProtocol へ draw リング領域とスクリプト版数のヘッダを追加しました。リングは
|
||||
1 件 24 個の倍精度値で 4096 件です。
|
||||
- worker.lua が getpixeldata の平坦な配列と遅延反映、リングへの書き溜めを行います。
|
||||
- SimdKernelCompiler が式木から Vector256 のブロック委譲を生成し、CpuKernel が
|
||||
4 画素単位のブロックと端数のスカラ処理を組み合わせます。ClampByte は Math.Clamp の
|
||||
分岐順序を ConditionalSelect で再現し、byte への変換もスカラと同一です。
|
||||
- CpuKernel の自己校正は、経路ごとに暖機 1 回と計測 3 回を交互に行い、累積時間の
|
||||
短い経路を採用します。判定はカーネルのインスタンスごとに一度だけ行い、以後は
|
||||
分岐しません。
|
||||
- KernelExtractor が getpixeldata の添字ループの定型を認識します。
|
||||
- テストは 3041 件です。v1.11.4 の 2994 件から、リングの順序と容量、遅延反映の整合、
|
||||
SIMD とスカラの一致、採用判定の収束と交互計測、抽出の拒否、転送領域の容量保証
|
||||
などの検証を追加しました。
|
||||
Direct2D の実描画を伴う直結転送の最終確認は、従来の GPU 経路と同様に YMM4 上が
|
||||
対象です。
|
||||
@@ -1,5 +1,5 @@
|
||||
========================================
|
||||
Luaスクリプト for YMM4 v1.10.0
|
||||
Luaスクリプト for YMM4 v1.12.0
|
||||
========================================
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||
ピクセルを直接制御できるプラグインです。
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Collections.Immutable;
|
||||
using LuaScript.Anchor;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class AnchorSupportTests
|
||||
{
|
||||
[Fact]
|
||||
public void ClampCount_LimitsToRange()
|
||||
{
|
||||
Assert.Equal(0, AnchorSupport.ClampCount(-5));
|
||||
Assert.Equal(10, AnchorSupport.ClampCount(10));
|
||||
Assert.Equal(AnchorSupport.MaxAnchors, AnchorSupport.ClampCount(100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyOption_SetsConnectionAndDimension()
|
||||
{
|
||||
var connection = AnchorConnection.None;
|
||||
bool is3D = false;
|
||||
|
||||
AnchorSupport.ApplyOption("loop", ref connection, ref is3D);
|
||||
AnchorSupport.ApplyOption("xyz", ref connection, ref is3D);
|
||||
|
||||
Assert.Equal(AnchorConnection.Loop, connection);
|
||||
Assert.True(is3D);
|
||||
|
||||
AnchorSupport.ApplyOption("star", ref connection, ref is3D);
|
||||
Assert.Equal(AnchorConnection.Star, connection);
|
||||
|
||||
AnchorSupport.ApplyOption("unknown", ref connection, ref is3D);
|
||||
Assert.Equal(AnchorConnection.Star, connection);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DefaultPosition_IsDeterministicGrid()
|
||||
{
|
||||
Assert.Equal(AnchorSupport.DefaultPosition(0), AnchorSupport.DefaultPosition(0));
|
||||
Assert.NotEqual(AnchorSupport.DefaultPosition(0), AnchorSupport.DefaultPosition(1));
|
||||
|
||||
var (x8, y8) = AnchorSupport.DefaultPosition(8);
|
||||
var (x0, y0) = AnchorSupport.DefaultPosition(0);
|
||||
Assert.Equal(x0, x8);
|
||||
Assert.True(y8 > y0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolvePosition_PrefersStoredThenDefault()
|
||||
{
|
||||
var source = ImmutableList.Create(new LuaAnchorPoint { Group = "pos", Index = 1, X = 12, Y = 34, Z = 56 });
|
||||
|
||||
AnchorSupport.ResolvePosition(source, "pos", 1, out double x, out double y, out double z);
|
||||
Assert.Equal(12, x);
|
||||
Assert.Equal(34, y);
|
||||
Assert.Equal(56, z);
|
||||
|
||||
AnchorSupport.ResolvePosition(source, "pos", 0, out double dx, out double dy, out double dz);
|
||||
var (ex, ey) = AnchorSupport.DefaultPosition(0);
|
||||
Assert.Equal(ex, dx);
|
||||
Assert.Equal(ey, dy);
|
||||
Assert.Equal(0, dz);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolvePosition_IsGroupScoped()
|
||||
{
|
||||
var source = ImmutableList.Create(new LuaAnchorPoint { Group = "a", Index = 0, X = 5, Y = 5, Z = 0 });
|
||||
|
||||
AnchorSupport.ResolvePosition(source, "b", 0, out double x, out double y, out _);
|
||||
var (ex, ey) = AnchorSupport.DefaultPosition(0);
|
||||
Assert.Equal(ex, x);
|
||||
Assert.Equal(ey, y);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyDrag_UpdatesExistingPoint()
|
||||
{
|
||||
var source = ImmutableList.Create(new LuaAnchorPoint { Group = "pos", Index = 2, X = 10, Y = 20, Z = 30 });
|
||||
|
||||
var result = AnchorSupport.ApplyDrag(source, "pos", 2, 3, -4, 5);
|
||||
|
||||
Assert.Single(result);
|
||||
Assert.Equal(13, result[0].X);
|
||||
Assert.Equal(16, result[0].Y);
|
||||
Assert.Equal(35, result[0].Z);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyDrag_AddsNewPointFromDefault()
|
||||
{
|
||||
var source = ImmutableList<LuaAnchorPoint>.Empty;
|
||||
|
||||
var result = AnchorSupport.ApplyDrag(source, "pos", 3, 7, 8, 0);
|
||||
|
||||
Assert.Single(result);
|
||||
var (bx, by) = AnchorSupport.DefaultPosition(3);
|
||||
Assert.Equal("pos", result[0].Group);
|
||||
Assert.Equal(3, result[0].Index);
|
||||
Assert.Equal(bx + 7, result[0].X);
|
||||
Assert.Equal(by + 8, result[0].Y);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class DrawTransformTests
|
||||
{
|
||||
[Fact]
|
||||
public void TryResolve_Affine_MapsSourceCenterToOffset()
|
||||
{
|
||||
var command = new DrawCommand(10d, 20d, 0d, 1d, 1d, 0d);
|
||||
|
||||
Assert.True(DrawTransform.TryResolve(command, 4, 6, out var matrix));
|
||||
|
||||
var mapped = Vector2.Transform(new Vector2(2f, 3f), matrix);
|
||||
Assert.Equal(10d, mapped.X, 3);
|
||||
Assert.Equal(20d, mapped.Y, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryResolve_Affine_AppliesZoomAndAspect()
|
||||
{
|
||||
var command = new DrawCommand(0d, 0d, 0d, 2d, 1d, 0.5d);
|
||||
|
||||
Assert.True(DrawTransform.TryResolve(command, 2, 2, out var matrix));
|
||||
|
||||
var mapped = Vector2.Transform(new Vector2(2f, 2f), matrix);
|
||||
Assert.Equal(3d, mapped.X, 3);
|
||||
Assert.Equal(1d, mapped.Y, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryResolve_Affine_ClampsAspect()
|
||||
{
|
||||
var command = new DrawCommand(0d, 0d, 0d, 2d, 1d, -3d);
|
||||
|
||||
Assert.False(DrawTransform.TryResolve(command, 2, 2, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryResolve_ZeroZoom_Fails()
|
||||
{
|
||||
var command = new DrawCommand(0d, 0d, 0d, 0d, 1d, 0d);
|
||||
|
||||
Assert.False(DrawTransform.TryResolve(command, 2, 2, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryResolve_NegativeZoom_Mirrors()
|
||||
{
|
||||
var command = new DrawCommand(0d, 0d, 0d, -1d, 1d, 0d);
|
||||
|
||||
Assert.True(DrawTransform.TryResolve(command, 2, 2, out var matrix));
|
||||
|
||||
var mapped = Vector2.Transform(new Vector2(2f, 2f), matrix);
|
||||
Assert.Equal(-1d, mapped.X, 3);
|
||||
Assert.Equal(-1d, mapped.Y, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryResolve_IdentityPoly_YieldsIdentity()
|
||||
{
|
||||
double[] poly =
|
||||
[
|
||||
0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 2, 0,
|
||||
0, 0, 2, 0, 2, 2, 0, 2,
|
||||
1,
|
||||
];
|
||||
var command = new DrawCommand(0d, 0d, 0d, 1d, 1d, 0d, poly);
|
||||
|
||||
Assert.True(DrawTransform.TryResolve(command, 2, 2, out var matrix));
|
||||
Assert.Equal(Matrix3x2.Identity, matrix);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryResolve_DegeneratePoly_Fails()
|
||||
{
|
||||
var command = new DrawCommand(0d, 0d, 0d, 1d, 1d, 0d, new double[DrawPolyMath.Length]);
|
||||
|
||||
Assert.False(DrawTransform.TryResolve(command, 2, 2, out _));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class FallbackCompositorTests
|
||||
{
|
||||
private sealed class RecordingCompositor : IBufferCompositor
|
||||
{
|
||||
public int Calls;
|
||||
public byte[]? LastDst;
|
||||
public byte[]? LastSrc;
|
||||
public DrawCommand LastCommand;
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
Calls++;
|
||||
LastDst = dst;
|
||||
LastSrc = src;
|
||||
LastCommand = command;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class RejectingCompositor : IBufferCompositor
|
||||
{
|
||||
public int Calls;
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
Calls++;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ThrowingCompositor : IBufferCompositor
|
||||
{
|
||||
public int Calls;
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
Calls++;
|
||||
throw new InvalidOperationException("device lost");
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class DisposableCompositor : IBufferCompositor, IDisposable
|
||||
{
|
||||
public bool Disposed;
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command) => true;
|
||||
|
||||
public void Dispose() => Disposed = true;
|
||||
}
|
||||
|
||||
private static readonly DrawCommand Command = new(1d, 2d, 0d, 1d, 1d, 0d);
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_PrimarySucceeds_FallbackIsNotUsed()
|
||||
{
|
||||
var primary = new RecordingCompositor();
|
||||
var fallback = new RecordingCompositor();
|
||||
var compositor = new FallbackCompositor(primary, fallback);
|
||||
|
||||
Assert.True(compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
|
||||
|
||||
Assert.Equal(1, primary.Calls);
|
||||
Assert.Equal(0, fallback.Calls);
|
||||
Assert.False(compositor.IsDegraded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_PrimaryThrows_FallbackReceivesSameArguments()
|
||||
{
|
||||
var primary = new ThrowingCompositor();
|
||||
var fallback = new RecordingCompositor();
|
||||
Exception? reported = null;
|
||||
var compositor = new FallbackCompositor(primary, fallback, ex => reported = ex);
|
||||
var dst = new byte[4];
|
||||
var src = new byte[4];
|
||||
|
||||
Assert.True(compositor.TryCompose(dst, 1, 1, src, 1, 1, Command));
|
||||
|
||||
Assert.Equal(1, fallback.Calls);
|
||||
Assert.Same(dst, fallback.LastDst);
|
||||
Assert.Same(src, fallback.LastSrc);
|
||||
Assert.Equal(Command, fallback.LastCommand);
|
||||
Assert.IsType<InvalidOperationException>(reported);
|
||||
Assert.True(compositor.IsDegraded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_AfterFailure_PrimaryIsSkippedAndDegradationReportedOnce()
|
||||
{
|
||||
var primary = new ThrowingCompositor();
|
||||
var fallback = new RecordingCompositor();
|
||||
int reports = 0;
|
||||
var compositor = new FallbackCompositor(primary, fallback, _ => reports++);
|
||||
|
||||
compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command);
|
||||
compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command);
|
||||
|
||||
Assert.Equal(1, primary.Calls);
|
||||
Assert.Equal(2, fallback.Calls);
|
||||
Assert.Equal(1, reports);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_PrimaryRejects_FallbackIsUsedWithoutDegradation()
|
||||
{
|
||||
var primary = new RejectingCompositor();
|
||||
var fallback = new RecordingCompositor();
|
||||
int reports = 0;
|
||||
var compositor = new FallbackCompositor(primary, fallback, _ => reports++);
|
||||
|
||||
Assert.True(compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
|
||||
Assert.True(compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
|
||||
|
||||
Assert.Equal(2, primary.Calls);
|
||||
Assert.Equal(2, fallback.Calls);
|
||||
Assert.Equal(0, reports);
|
||||
Assert.False(compositor.IsDegraded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_DisposesDisposableLanes()
|
||||
{
|
||||
var primary = new DisposableCompositor();
|
||||
var fallback = new DisposableCompositor();
|
||||
var compositor = new FallbackCompositor(primary, fallback);
|
||||
|
||||
compositor.Dispose();
|
||||
|
||||
Assert.True(primary.Disposed);
|
||||
Assert.True(fallback.Disposed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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) 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("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)
|
||||
{
|
||||
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
|
||||
@@ -38,6 +40,31 @@ namespace LuaScript.Tests
|
||||
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]
|
||||
[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")]
|
||||
@@ -107,6 +134,8 @@ namespace LuaScript.Tests
|
||||
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);
|
||||
engine.Globals.Get("math").Table["fmod"] = DynValue.NewCallback((_, a) =>
|
||||
DynValue.NewNumber(a[0].Number % a[1].Number));
|
||||
var obj = new Table(engine);
|
||||
foreach (var (name, value) in fields)
|
||||
obj[name] = value;
|
||||
@@ -134,10 +163,60 @@ namespace LuaScript.Tests
|
||||
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.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)
|
||||
{
|
||||
if ((uint)x >= Width || (uint)y >= Height)
|
||||
|
||||
@@ -31,6 +31,21 @@ namespace LuaScript.Tests
|
||||
Assert.Contains("inB", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CoordinatesUsePixelCenterOrigin()
|
||||
{
|
||||
string hlsl = HlslKernelEmitter.Emit(Extract(Grayscale));
|
||||
Assert.Contains(" - 0.5;", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OutputTruncatesToMatchCpuKernel()
|
||||
{
|
||||
string hlsl = HlslKernelEmitter.Emit(Extract(Grayscale));
|
||||
Assert.Contains("float oR = floor(clamp((", hlsl);
|
||||
Assert.Contains("float oA = floor(outA) / 255.0;", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThresholdEmitsTernary()
|
||||
{
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -30,9 +31,17 @@
|
||||
<Compile Include="..\LuaScript\Engine\ScriptDirective.cs" Link="Linked\ScriptDirective.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\PixelRegionAccess.cs" Link="Linked\PixelRegionAccess.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\LuaJitWorker.cs" Link="Linked\LuaJitWorker.cs" />
|
||||
<Compile Include="..\LuaScript\DrawCommand.cs" Link="Linked\DrawCommand.cs" />
|
||||
<Compile Include="..\LuaScript\DrawPolyMath.cs" Link="Linked\DrawPolyMath.cs" />
|
||||
<Compile Include="..\LuaScript\DrawTransform.cs" Link="Linked\DrawTransform.cs" />
|
||||
<Compile Include="..\LuaScript\IBufferCompositor.cs" Link="Linked\IBufferCompositor.cs" />
|
||||
<Compile Include="..\LuaScript\SoftwareCompositor.cs" Link="Linked\SoftwareCompositor.cs" />
|
||||
<Compile Include="..\LuaScript\FallbackCompositor.cs" Link="Linked\FallbackCompositor.cs" />
|
||||
<Compile Include="..\LuaScript\SynchronizedCompositor.cs" Link="Linked\SynchronizedCompositor.cs" />
|
||||
<Compile Include="..\LuaScript\Anchor\LuaAnchorPoint.cs" Link="Linked\LuaAnchorPoint.cs" />
|
||||
<Compile Include="..\LuaScript\Anchor\AnchorSupport.cs" Link="Linked\AnchorSupport.cs" />
|
||||
<Compile Include="..\LuaScript\SceneObjectInfo.cs" Link="Linked\SceneObjectInfo.cs" />
|
||||
<Compile Include="..\LuaScript\SceneObjectQuery.cs" Link="Linked\SceneObjectQuery.cs" />
|
||||
<Compile Include="..\LuaScript\AnimTableRegistrar.cs" Link="Linked\AnimTableRegistrar.cs" />
|
||||
@@ -56,6 +65,7 @@
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\KernelExtractor.cs" Link="Linked\Kernel\KernelExtractor.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\CpuKernel.cs" Link="Linked\Kernel\CpuKernel.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\CpuKernelCompiler.cs" Link="Linked\Kernel\CpuKernelCompiler.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\SimdKernelCompiler.cs" Link="Linked\Kernel\SimdKernelCompiler.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\HlslKernelEmitter.cs" Link="Linked\Kernel\HlslKernelEmitter.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ namespace LuaScript.Tests
|
||||
private static readonly Func<string, double, (byte[] buffer, int w, int h)> NoLoadMovie = (_, _) => ([], 1, 1);
|
||||
private static readonly Action<string, System.Collections.Generic.IReadOnlyList<System.Collections.Generic.KeyValuePair<string, object>>> NoAddEffect = (_, _) => { };
|
||||
private static readonly Action<DrawCommand> NoAddDraw = _ => { };
|
||||
private static readonly Action<string, int, bool, int, double[]> NoSetAnchor = (_, _, _, _, _) => { };
|
||||
private static readonly System.Collections.Generic.IReadOnlyDictionary<string, string> NoStringParams = new System.Collections.Generic.Dictionary<string, string>();
|
||||
|
||||
private readonly LuaJitWorker _worker = new(NativeDir);
|
||||
@@ -31,6 +32,79 @@ namespace LuaScript.Tests
|
||||
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]
|
||||
public void TransformScript_WritesBackObjFields()
|
||||
{
|
||||
@@ -39,9 +113,9 @@ namespace LuaScript.Tests
|
||||
var fields = Fields(4, 4, 2d);
|
||||
var pixels = new byte[4 * 4 * 4];
|
||||
|
||||
bool ok = _worker.Execute(
|
||||
bool ok = RunWorker(
|
||||
"obj.rz = obj.time * 90\nobj.alpha = 128",
|
||||
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, 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);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.False(dirty);
|
||||
@@ -62,9 +136,9 @@ namespace LuaScript.Tests
|
||||
["file_image"] = "C:/サンプル/画像.png",
|
||||
};
|
||||
|
||||
bool ok = _worker.Execute(
|
||||
bool ok = RunWorker(
|
||||
"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, 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);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(5d, fields[NativeProtocol.X]);
|
||||
@@ -81,17 +155,17 @@ namespace LuaScript.Tests
|
||||
|
||||
var large = new System.Collections.Generic.Dictionary<string, string> { ["text"] = big };
|
||||
var fieldsLarge = Fields(2, 2, 0d);
|
||||
bool ok = _worker.Execute(
|
||||
bool ok = RunWorker(
|
||||
"obj.x = string.len(obj.text)",
|
||||
fieldsLarge, large, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, 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.Equal(big.Length, fieldsLarge[NativeProtocol.X]);
|
||||
|
||||
var small = new System.Collections.Generic.Dictionary<string, string> { ["text"] = "ok" };
|
||||
var fieldsSmall = Fields(2, 2, 0d);
|
||||
ok = _worker.Execute(
|
||||
ok = RunWorker(
|
||||
"obj.x = string.len(obj.text)",
|
||||
fieldsSmall, small, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, 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.Equal(2d, fieldsSmall[NativeProtocol.X]);
|
||||
}
|
||||
@@ -123,7 +197,7 @@ namespace LuaScript.Tests
|
||||
"local gray = r*0.299 + g*0.587 + b*0.114 " +
|
||||
"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, 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(dirty);
|
||||
@@ -158,7 +232,7 @@ namespace LuaScript.Tests
|
||||
"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";
|
||||
|
||||
bool ok = _worker.Execute(script, fields, NoStringParams, pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, 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(dirty);
|
||||
@@ -185,6 +259,109 @@ namespace LuaScript.Tests
|
||||
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]
|
||||
public void PersistentWorker_HandlesMultipleCalls()
|
||||
{
|
||||
@@ -194,12 +371,57 @@ namespace LuaScript.Tests
|
||||
for (int k = 1; k <= 5; 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, 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.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]
|
||||
public void Timeout_KillsWorker_AndRecovers()
|
||||
{
|
||||
@@ -208,13 +430,13 @@ namespace LuaScript.Tests
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
|
||||
bool timedOut = _worker.Execute(
|
||||
"local x=0 while true do x=x+1 end", fields, NoStringParams, pixels, 2, 2, 1500, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
|
||||
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);
|
||||
Assert.False(timedOut);
|
||||
Assert.Contains("timed out", error);
|
||||
|
||||
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, 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.Equal(3d, fields2[NativeProtocol.X]);
|
||||
}
|
||||
@@ -236,7 +458,7 @@ namespace LuaScript.Tests
|
||||
"obj.zoom = o.zoom obj.rz = o.rz obj.alpha = o.alpha " +
|
||||
"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, 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.Equal(12d, fields[NativeProtocol.X]);
|
||||
@@ -268,13 +490,13 @@ namespace LuaScript.Tests
|
||||
"local b = obj.getobject(\"a\") " +
|
||||
"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, 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.Equal(1, calls);
|
||||
var fields = Fields(2, 2, 0d);
|
||||
|
||||
x = 20d;
|
||||
ok = _worker.Execute(script, fields, NoStringParams, pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, 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.Equal(2, calls);
|
||||
Assert.Equal(40d, fields[NativeProtocol.X]);
|
||||
@@ -291,7 +513,7 @@ namespace LuaScript.Tests
|
||||
const string script =
|
||||
"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, 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.Equal(1d, fields[NativeProtocol.X]);
|
||||
@@ -307,9 +529,9 @@ namespace LuaScript.Tests
|
||||
var commands = new System.Collections.Generic.List<DrawCommand>();
|
||||
Action<DrawCommand> addDraw = commands.Add;
|
||||
|
||||
bool ok = _worker.Execute(
|
||||
bool ok = RunWorker(
|
||||
"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,
|
||||
fields, 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);
|
||||
@@ -318,6 +540,28 @@ namespace LuaScript.Tests
|
||||
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]
|
||||
public void DrawPoly_RecordsDefaultUvAndAlpha()
|
||||
{
|
||||
@@ -328,9 +572,9 @@ namespace LuaScript.Tests
|
||||
var commands = new System.Collections.Generic.List<DrawCommand>();
|
||||
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)",
|
||||
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw,
|
||||
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
@@ -350,9 +594,9 @@ namespace LuaScript.Tests
|
||||
var commands = new System.Collections.Generic.List<DrawCommand>();
|
||||
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)",
|
||||
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw,
|
||||
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
@@ -371,9 +615,9 @@ namespace LuaScript.Tests
|
||||
var pixels = new byte[16];
|
||||
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')",
|
||||
fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw,
|
||||
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);
|
||||
@@ -390,9 +634,9 @@ namespace LuaScript.Tests
|
||||
var commands = new System.Collections.Generic.List<DrawCommand>();
|
||||
Action<DrawCommand> addDraw = commands.Add;
|
||||
|
||||
bool ok = _worker.Execute(
|
||||
bool ok = RunWorker(
|
||||
"obj.draw() obj.setoption('antialias', 0) obj.draw()",
|
||||
Fields(2, 2, 0d), NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw,
|
||||
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);
|
||||
@@ -401,6 +645,157 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(0d, commands[1].Antialias);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Draw_CarriesBlendFromOption()
|
||||
{
|
||||
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;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"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,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(2, commands.Count);
|
||||
Assert.Equal(0d, commands[0].Blend);
|
||||
Assert.Equal(3d, commands[1].Blend);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DrawPoly_CarriesBlendFromOption()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[4 * 4 * 4];
|
||||
var commands = new System.Collections.Generic.List<DrawCommand>();
|
||||
Action<DrawCommand> addDraw = commands.Add;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"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,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Single(commands);
|
||||
Assert.Equal(11d, commands[0].Blend);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetOption_DrawState_WritesBackFlag()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[16];
|
||||
|
||||
var fTrue = Fields(2, 2, 0d);
|
||||
bool okTrue = RunWorker(
|
||||
"obj.setoption('draw_state', true)",
|
||||
fTrue, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? errorTrue);
|
||||
Assert.True(okTrue, errorTrue);
|
||||
Assert.Equal(1d, fTrue[NativeProtocol.DrawState]);
|
||||
|
||||
var fFalse = Fields(2, 2, 0d);
|
||||
bool okFalse = RunWorker(
|
||||
"obj.setoption('draw_state', false)",
|
||||
fFalse, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? errorFalse);
|
||||
Assert.True(okFalse, errorFalse);
|
||||
Assert.Equal(2d, fFalse[NativeProtocol.DrawState]);
|
||||
|
||||
var fUnset = Fields(2, 2, 0d);
|
||||
bool okUnset = RunWorker(
|
||||
"obj.x = 1",
|
||||
fUnset, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? errorUnset);
|
||||
Assert.True(okUnset, errorUnset);
|
||||
Assert.Equal(0d, fUnset[NativeProtocol.DrawState]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetAnchor_FillsLuaVariableFromResolver()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
|
||||
string? capturedGroup = null;
|
||||
int capturedCount = -1;
|
||||
Action<string, int, bool, int, double[]> setAnchor = (group, count, is3D, connection, positions) =>
|
||||
{
|
||||
capturedGroup = group;
|
||||
capturedCount = count;
|
||||
int stride = is3D ? 3 : 2;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
positions[i * stride + 0] = i * 10;
|
||||
positions[i * stride + 1] = i * 10 + 5;
|
||||
if (is3D)
|
||||
positions[i * stride + 2] = 0;
|
||||
}
|
||||
};
|
||||
|
||||
string script =
|
||||
"local n = obj.setanchor('pos', 2, 'loop')\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = pos[1]\n" +
|
||||
"obj.z = pos[3]";
|
||||
|
||||
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000,
|
||||
NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, setAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal("pos", capturedGroup);
|
||||
Assert.Equal(2, capturedCount);
|
||||
Assert.Equal(2d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(0d, fields[NativeProtocol.Y]);
|
||||
Assert.Equal(10d, fields[NativeProtocol.Z]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DrawTarget_TempBuffer_CompositesAndCopiesBack()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[2 * 2 * 4];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
|
||||
string script =
|
||||
"obj.setpixel(0,0,255,0,0,255)\n" +
|
||||
"obj.setpixel(1,0,0,255,0,255)\n" +
|
||||
"obj.setpixel(0,1,0,0,255,255)\n" +
|
||||
"obj.setpixel(1,1,255,255,0,255)\n" +
|
||||
"obj.setoption('drawtarget','tempbuffer',2,2)\n" +
|
||||
"obj.draw(1,1,0,1,1,0)\n" +
|
||||
"obj.setoption('drawtarget','framebuffer')\n" +
|
||||
"obj.copybuffer('obj','tmp')";
|
||||
|
||||
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(0, pixels[0]);
|
||||
Assert.Equal(0, pixels[1]);
|
||||
Assert.Equal(255, pixels[2]);
|
||||
Assert.Equal(255, pixels[3]);
|
||||
|
||||
int i11 = (1 * 2 + 1) * 4;
|
||||
Assert.Equal(0, pixels[i11]);
|
||||
Assert.Equal(255, pixels[i11 + 1]);
|
||||
Assert.Equal(255, pixels[i11 + 2]);
|
||||
Assert.Equal(255, pixels[i11 + 3]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadText_RoundTripsThroughCallback()
|
||||
{
|
||||
@@ -427,9 +822,9 @@ namespace LuaScript.Tests
|
||||
var pixels = new byte[4 * 4 * 4];
|
||||
var fields = Fields(4, 4, 0d);
|
||||
|
||||
bool ok = _worker.Execute(
|
||||
bool ok = RunWorker(
|
||||
"obj.setfont('Meiryo', 40, 3, 0x112233) obj.load('text', 'Hi')",
|
||||
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, loadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw,
|
||||
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);
|
||||
|
||||
Assert.True(ok, error);
|
||||
@@ -467,9 +862,9 @@ namespace LuaScript.Tests
|
||||
var pixels = new byte[4 * 4 * 4];
|
||||
var fields = Fields(4, 4, 0d);
|
||||
|
||||
bool ok = _worker.Execute(
|
||||
bool ok = RunWorker(
|
||||
"obj.load('image', 'C:/sample.png')",
|
||||
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, loadImage, NoLoadMovie, NoAddEffect, NoAddDraw,
|
||||
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);
|
||||
|
||||
Assert.True(ok, error);
|
||||
@@ -504,9 +899,9 @@ namespace LuaScript.Tests
|
||||
var pixels = new byte[4 * 4 * 4];
|
||||
var fields = Fields(4, 4, 0d);
|
||||
|
||||
bool ok = _worker.Execute(
|
||||
bool ok = RunWorker(
|
||||
"obj.load('movie', 'C:/clip.mp4', 1.5)",
|
||||
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, loadMovie, NoAddEffect, NoAddDraw,
|
||||
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);
|
||||
|
||||
Assert.True(ok, error);
|
||||
@@ -529,9 +924,9 @@ namespace LuaScript.Tests
|
||||
var fields = Fields(2, 2, 0d);
|
||||
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')",
|
||||
fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw,
|
||||
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);
|
||||
@@ -558,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 " +
|
||||
"obj.copybuffer('obj','tmp')";
|
||||
|
||||
bool ok = _worker.Execute(script, fields, NoStringParams, pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, 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(dirty);
|
||||
@@ -577,14 +972,127 @@ namespace LuaScript.Tests
|
||||
stored[3] = 255; stored[7] = 255; stored[11] = 255; stored[15] = 255;
|
||||
|
||||
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, 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);
|
||||
|
||||
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, out bool dirty, out _, out _, 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(dirty);
|
||||
Assert.Equal(stored, blank);
|
||||
Assert.NotNull(restored);
|
||||
Assert.Equal(stored, restored!.AsSpan(0, stored.Length).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TransformScript_NeverRequestsPixels()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[16];
|
||||
int loads = 0;
|
||||
Func<byte[]> loadPixels = () => { loads++; return pixels; };
|
||||
|
||||
var fields = Fields(2, 2, 1d);
|
||||
bool ok = RunWorker(
|
||||
"obj.x = obj.time * 10 obj.draw()",
|
||||
fields, NoStringParams, loadPixels, 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.False(dirty);
|
||||
Assert.Equal(0, loads);
|
||||
Assert.Equal(10d, fields[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelScript_RequestsPixelsExactlyOnce()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[16];
|
||||
pixels[3] = 255; pixels[7] = 255; pixels[11] = 255; pixels[15] = 255;
|
||||
int loads = 0;
|
||||
Func<byte[]> loadPixels = () => { loads++; return pixels; };
|
||||
|
||||
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",
|
||||
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);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(1, loads);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Worker_SurvivesSizeChanges_PreservingCache()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var stored = new byte[2 * 2 * 4];
|
||||
for (int i = 0; i < stored.Length; i++)
|
||||
stored[i] = (byte)((i * 41 + 13) & 0xFF);
|
||||
stored[3] = 255; stored[7] = 255; stored[11] = 255; stored[15] = 255;
|
||||
|
||||
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);
|
||||
|
||||
var bigger = new byte[4 * 4 * 4];
|
||||
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(dirty);
|
||||
Assert.True(bufferReplaced);
|
||||
Assert.Equal(2, rw);
|
||||
Assert.Equal(2, rh);
|
||||
Assert.NotNull(restored);
|
||||
Assert.Equal(stored, restored!.AsSpan(0, stored.Length).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BareGlobals_MirrorObjFields()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 2d);
|
||||
fields[NativeProtocol.Frame] = 10d;
|
||||
fields[NativeProtocol.TotalFrame] = 20d;
|
||||
fields[NativeProtocol.Framerate] = 30d;
|
||||
fields[NativeProtocol.Layer] = 3d;
|
||||
fields[NativeProtocol.TimelineFrame] = 100d;
|
||||
fields[NativeProtocol.TimelineTime] = 4d;
|
||||
|
||||
const string script =
|
||||
"obj.x = time * 10 + frame " +
|
||||
"obj.y = totalframe + framerate + layer " +
|
||||
"obj.z = timelineframe + timelinetime";
|
||||
|
||||
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(30d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(53d, fields[NativeProtocol.Y]);
|
||||
Assert.Equal(104d, fields[NativeProtocol.Z]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UserGlobals_AreResetBetweenRuns()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[16];
|
||||
|
||||
bool ok = RunWorker(
|
||||
"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);
|
||||
Assert.True(ok, error);
|
||||
|
||||
var fields = Fields(2, 2, 0d);
|
||||
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)",
|
||||
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.Equal(1111d, fields[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -595,12 +1103,12 @@ namespace LuaScript.Tests
|
||||
var pixels = new byte[16];
|
||||
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, 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(string.IsNullOrEmpty(error));
|
||||
|
||||
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, 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.Equal(7d, fields2[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
@@ -31,18 +31,21 @@ namespace LuaScript.Tests
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("obj.rz = time * 90", "MoonSharp")]
|
||||
[InlineData(null, "MoonSharp")]
|
||||
[InlineData("", "MoonSharp")]
|
||||
[InlineData("obj.rz = time * 90", "Native")]
|
||||
[InlineData("local r,g,b,a = obj.getpixel(0,0)", "Native")]
|
||||
[InlineData("obj.setpixel(0,0,255,0,0)", "Native")]
|
||||
[InlineData("local pd = obj.getpixeldata()", "Native")]
|
||||
[InlineData("--!moonsharp\nobj.setpixel(0,0,1,1,1)", "MoonSharp")]
|
||||
[InlineData("--!native\nobj.rz = 1", "Native")]
|
||||
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)", "MoonSharp")]
|
||||
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)\nlocal r = obj.getpixel(0,0)", "Native")]
|
||||
[InlineData("obj.draw()", "MoonSharp")]
|
||||
[InlineData("obj.draw()\nlocal r = obj.getpixel(0,0)", "Native")]
|
||||
[InlineData("--!native\nobj.load(\"figure\", \"円\", 0xff0000, 100)", "Native")]
|
||||
public void ResolveAuto_RoutesPixelScriptsToNative(string script, string expected)
|
||||
[InlineData("--!gpu\nfunction pixel() end", "Gpu")]
|
||||
[InlineData("--!cpu\nfunction pixel() end", "Cpu")]
|
||||
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)", "Native")]
|
||||
[InlineData("obj.draw()", "Native")]
|
||||
[InlineData("obj.setoption('blend', 1)", "Native")]
|
||||
[InlineData("obj.setanchor('pos', 2)", "Native")]
|
||||
public void ResolveAuto_DefaultsToNative(string? script, string expected)
|
||||
{
|
||||
Assert.Equal(expected, ScriptDirective.ResolveAuto(script).ToString());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
using LuaScript;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class SoftwareCompositorTests
|
||||
{
|
||||
private static byte[] Solid(int w, int h, byte b, byte g, byte r, byte a)
|
||||
{
|
||||
var buffer = new byte[w * h * 4];
|
||||
for (int i = 0; i < w * h; i++)
|
||||
{
|
||||
buffer[i * 4] = b;
|
||||
buffer[i * 4 + 1] = g;
|
||||
buffer[i * 4 + 2] = r;
|
||||
buffer[i * 4 + 3] = a;
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DrawInto_NearestOpaque_BlitsSinglePixel()
|
||||
{
|
||||
var dst = new byte[3 * 3 * 4];
|
||||
var src = Solid(1, 1, 255, 255, 255, 255);
|
||||
|
||||
SoftwareCompositor.DrawInto(dst, 3, 3, src, 1, 1, 1.5, 1.5, 1d, 0d, 1d, linear: false);
|
||||
|
||||
int center = (1 * 3 + 1) * 4;
|
||||
Assert.Equal(255, dst[center]);
|
||||
Assert.Equal(255, dst[center + 1]);
|
||||
Assert.Equal(255, dst[center + 2]);
|
||||
Assert.Equal(255, dst[center + 3]);
|
||||
|
||||
Assert.Equal(0, dst[0]);
|
||||
Assert.Equal(0, dst[(0 * 3 + 0) * 4 + 3]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DrawInto_HalfAlphaOverOpaque_BlendsPremultiplied()
|
||||
{
|
||||
var dst = Solid(1, 1, 0, 0, 0, 255);
|
||||
var src = Solid(1, 1, 255, 255, 255, 255);
|
||||
|
||||
SoftwareCompositor.DrawInto(dst, 1, 1, src, 1, 1, 0.5, 0.5, 1d, 0d, 0.5, linear: false);
|
||||
|
||||
Assert.Equal(127, dst[0]);
|
||||
Assert.Equal(127, dst[1]);
|
||||
Assert.Equal(127, dst[2]);
|
||||
Assert.Equal(255, dst[3]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DrawInto_OutOfBounds_LeavesDestinationUnchanged()
|
||||
{
|
||||
var dst = new byte[2 * 2 * 4];
|
||||
var src = Solid(1, 1, 255, 255, 255, 255);
|
||||
|
||||
SoftwareCompositor.DrawInto(dst, 2, 2, src, 1, 1, 100d, 100d, 1d, 0d, 1d, linear: false);
|
||||
|
||||
foreach (var value in dst)
|
||||
Assert.Equal(0, value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_AffineCommand_MatchesDrawInto()
|
||||
{
|
||||
var src = Solid(1, 1, 10, 20, 30, 255);
|
||||
var actual = new byte[3 * 3 * 4];
|
||||
var expected = new byte[3 * 3 * 4];
|
||||
var command = new DrawCommand(1.5, 1.5, 0d, 1d, 1d, 0d, Antialias: 0d);
|
||||
|
||||
Assert.True(SoftwareCompositor.Instance.TryCompose(actual, 3, 3, src, 1, 1, command));
|
||||
SoftwareCompositor.DrawInto(expected, 3, 3, src, 1, 1, 1.5, 1.5, 1d, 0d, 1d, linear: false);
|
||||
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_PolyCommand_MatchesDrawPolyInto()
|
||||
{
|
||||
var src = Solid(2, 2, 40, 50, 60, 255);
|
||||
var actual = new byte[2 * 2 * 4];
|
||||
var expected = new byte[2 * 2 * 4];
|
||||
double[] poly =
|
||||
[
|
||||
0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 2, 0,
|
||||
0, 0, 2, 0, 2, 2, 0, 2,
|
||||
1,
|
||||
];
|
||||
var command = new DrawCommand(0d, 0d, 0d, 1d, 1d, 0d, poly, Antialias: 0d);
|
||||
|
||||
Assert.True(SoftwareCompositor.Instance.TryCompose(actual, 2, 2, src, 2, 2, command));
|
||||
SoftwareCompositor.DrawPolyInto(expected, 2, 2, src, 2, 2, poly, 1d, linear: false);
|
||||
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_AntialiasCommand_UsesLinearSampling()
|
||||
{
|
||||
var src = new byte[2 * 1 * 4];
|
||||
src[3] = 255;
|
||||
src[4] = 255;
|
||||
src[5] = 255;
|
||||
src[6] = 255;
|
||||
src[7] = 255;
|
||||
var actual = new byte[4 * 1 * 4];
|
||||
var expected = new byte[4 * 1 * 4];
|
||||
var command = new DrawCommand(2d, 0.5, 0d, 2d, 1d, 0d, Antialias: 1d);
|
||||
|
||||
Assert.True(SoftwareCompositor.Instance.TryCompose(actual, 4, 1, src, 2, 1, command));
|
||||
SoftwareCompositor.DrawInto(expected, 4, 1, src, 2, 1, 2d, 0.5, 2d, 0d, 1d, linear: true);
|
||||
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DrawPolyInto_IdentityAffine_CopiesSource()
|
||||
{
|
||||
var src = new byte[2 * 2 * 4];
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
src[i * 4] = (byte)(i + 1);
|
||||
src[i * 4 + 1] = (byte)(i + 10);
|
||||
src[i * 4 + 2] = (byte)(i + 20);
|
||||
src[i * 4 + 3] = 255;
|
||||
}
|
||||
var dst = new byte[2 * 2 * 4];
|
||||
|
||||
double[] poly =
|
||||
[
|
||||
0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 2, 0,
|
||||
0, 0, 2, 0, 2, 2, 0, 2,
|
||||
1,
|
||||
];
|
||||
|
||||
SoftwareCompositor.DrawPolyInto(dst, 2, 2, src, 2, 2, poly, 1d, linear: false);
|
||||
|
||||
Assert.Equal(src, dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class SynchronizedCompositorTests
|
||||
{
|
||||
private sealed class GateObservingCompositor(SemaphoreSlim gate, bool result) : IBufferCompositor
|
||||
{
|
||||
public int Calls;
|
||||
public int GateCountDuringCompose = -1;
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
Calls++;
|
||||
GateCountDuringCompose = gate.CurrentCount;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ThrowingCompositor : IBufferCompositor
|
||||
{
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command) =>
|
||||
throw new InvalidOperationException("device lost");
|
||||
}
|
||||
|
||||
private sealed class DisposableCompositor : IBufferCompositor, IDisposable
|
||||
{
|
||||
public bool Disposed;
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command) => true;
|
||||
|
||||
public void Dispose() => Disposed = true;
|
||||
}
|
||||
|
||||
private static readonly DrawCommand Command = new(0d, 0d, 0d, 1d, 1d, 0d);
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_HoldsGateDuringComposeAndReleasesAfter()
|
||||
{
|
||||
using var gate = new SemaphoreSlim(1, 1);
|
||||
var inner = new GateObservingCompositor(gate, result: true);
|
||||
var compositor = new SynchronizedCompositor(inner, gate);
|
||||
|
||||
Assert.True(compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
|
||||
|
||||
Assert.Equal(1, inner.Calls);
|
||||
Assert.Equal(0, inner.GateCountDuringCompose);
|
||||
Assert.Equal(1, gate.CurrentCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_PassesRejectionThrough()
|
||||
{
|
||||
using var gate = new SemaphoreSlim(1, 1);
|
||||
var inner = new GateObservingCompositor(gate, result: false);
|
||||
var compositor = new SynchronizedCompositor(inner, gate);
|
||||
|
||||
Assert.False(compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
|
||||
Assert.Equal(1, gate.CurrentCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_ReleasesGateWhenInnerThrows()
|
||||
{
|
||||
using var gate = new SemaphoreSlim(1, 1);
|
||||
var compositor = new SynchronizedCompositor(new ThrowingCompositor(), gate);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
|
||||
Assert.Equal(1, gate.CurrentCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_DisposesInnerButNotGate()
|
||||
{
|
||||
using var gate = new SemaphoreSlim(1, 1);
|
||||
var inner = new DisposableCompositor();
|
||||
var compositor = new SynchronizedCompositor(inner, gate);
|
||||
|
||||
compositor.Dispose();
|
||||
|
||||
Assert.True(inner.Disposed);
|
||||
gate.Wait();
|
||||
gate.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace LuaScript.Anchor
|
||||
{
|
||||
internal enum AnchorConnection
|
||||
{
|
||||
None,
|
||||
Line,
|
||||
Loop,
|
||||
Star,
|
||||
Arm,
|
||||
}
|
||||
|
||||
internal readonly record struct AnchorOptions(AnchorConnection Connection, bool Is3D);
|
||||
|
||||
internal readonly record struct AnchorRequestData(string Group, int Count, AnchorConnection Connection, bool Is3D);
|
||||
|
||||
internal static class AnchorSupport
|
||||
{
|
||||
public const int MaxAnchors = 32;
|
||||
public const string TrackGroup = "track";
|
||||
|
||||
public static int ClampCount(int count) => Math.Clamp(count, 0, MaxAnchors);
|
||||
|
||||
public static void ApplyOption(string option, ref AnchorConnection connection, ref bool is3D)
|
||||
{
|
||||
switch (option)
|
||||
{
|
||||
case "line": connection = AnchorConnection.Line; break;
|
||||
case "loop": connection = AnchorConnection.Loop; break;
|
||||
case "star": connection = AnchorConnection.Star; break;
|
||||
case "arm": connection = AnchorConnection.Arm; break;
|
||||
case "xyz": is3D = true; break;
|
||||
}
|
||||
}
|
||||
|
||||
public static (double X, double Y) DefaultPosition(int index)
|
||||
{
|
||||
int col = index % 8;
|
||||
int row = index / 8;
|
||||
return ((col - 3.5) * 60d, (row - 1.5) * 60d);
|
||||
}
|
||||
|
||||
public static void ResolvePosition(IReadOnlyList<LuaAnchorPoint>? source, string group, int index,
|
||||
out double x, out double y, out double z)
|
||||
{
|
||||
if (source is not null)
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var a = source[i];
|
||||
if (a.Index == index && string.Equals(a.Group, group, StringComparison.Ordinal))
|
||||
{
|
||||
x = a.X;
|
||||
y = a.Y;
|
||||
z = a.Z;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var (dx, dy) = DefaultPosition(index);
|
||||
x = dx;
|
||||
y = dy;
|
||||
z = 0d;
|
||||
}
|
||||
|
||||
public static ImmutableList<LuaAnchorPoint> ApplyDrag(
|
||||
ImmutableList<LuaAnchorPoint> source, string group, int index, double dx, double dy, double dz)
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var a = source[i];
|
||||
if (a.Index == index && string.Equals(a.Group, group, StringComparison.Ordinal))
|
||||
{
|
||||
return source.SetItem(i, new LuaAnchorPoint
|
||||
{
|
||||
Group = group,
|
||||
Index = index,
|
||||
X = a.X + dx,
|
||||
Y = a.Y + dy,
|
||||
Z = a.Z + dz,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
var (bx, by) = DefaultPosition(index);
|
||||
return source.Add(new LuaAnchorPoint
|
||||
{
|
||||
Group = group,
|
||||
Index = index,
|
||||
X = bx + dx,
|
||||
Y = by + dy,
|
||||
Z = dz,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace LuaScript.Anchor
|
||||
{
|
||||
public sealed class LuaAnchorPoint
|
||||
{
|
||||
public string Group { get; set; } = string.Empty;
|
||||
public int Index { get; set; }
|
||||
public double X { get; set; }
|
||||
public double Y { get; set; }
|
||||
public double Z { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,19 @@
|
||||
using LuaScript.Anchor;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class AviUtlScriptContext
|
||||
{
|
||||
public IReadOnlyList<LuaAnchorPoint>? AnchorSource { get; set; }
|
||||
|
||||
private readonly List<AnchorRequestData> _anchorRequests = [];
|
||||
|
||||
public IReadOnlyList<AnchorRequestData> AnchorRequests => _anchorRequests;
|
||||
|
||||
internal void AddAnchorRequest(in AnchorRequestData request) => _anchorRequests.Add(request);
|
||||
|
||||
internal void ClearAnchorRequests() => _anchorRequests.Clear();
|
||||
|
||||
public bool IsPlaying { get; set; }
|
||||
public bool IsPaused { get; set; }
|
||||
public string SceneId { get; set; } = string.Empty;
|
||||
@@ -42,6 +54,8 @@ namespace LuaScript
|
||||
public bool HasColor { get; set; }
|
||||
public double ColorValue { get; set; }
|
||||
|
||||
public bool? DrawStateOverride { get; set; }
|
||||
|
||||
public double Time { get; set; }
|
||||
public int Frame { get; set; }
|
||||
public int TotalFrame { get; set; }
|
||||
@@ -77,6 +91,8 @@ namespace LuaScript
|
||||
|
||||
internal void ClearEffects() => _effectRequests.Clear();
|
||||
|
||||
internal IBufferCompositor Compositor { get; set; } = SoftwareCompositor.Instance;
|
||||
|
||||
private readonly List<DrawCommand> _drawCommands = [];
|
||||
|
||||
public IReadOnlyList<DrawCommand> DrawCommands => _drawCommands;
|
||||
@@ -85,6 +101,49 @@ namespace LuaScript
|
||||
|
||||
internal void ClearDraws() => _drawCommands.Clear();
|
||||
|
||||
private bool _drawTargetTemp;
|
||||
|
||||
internal void ResetDrawTarget() => _drawTargetTemp = false;
|
||||
|
||||
internal void SetDrawTarget(bool temp, int width, int height, bool hasSize)
|
||||
{
|
||||
_drawTargetTemp = temp;
|
||||
if (temp && hasSize)
|
||||
{
|
||||
int w = Math.Max(1, width);
|
||||
int h = Math.Max(1, height);
|
||||
_buffers["t"] = (new byte[w * h * 4], w, h);
|
||||
}
|
||||
}
|
||||
|
||||
internal void SubmitDraw(DrawCommand command)
|
||||
{
|
||||
if (!_drawTargetTemp)
|
||||
{
|
||||
_drawCommands.Add(command);
|
||||
return;
|
||||
}
|
||||
CompositeToTemp(command);
|
||||
}
|
||||
|
||||
private void CompositeToTemp(DrawCommand command)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
var src = _pixelBuffer;
|
||||
if (src is null)
|
||||
return;
|
||||
|
||||
if (!_buffers.TryGetValue("t", out var temp))
|
||||
{
|
||||
int w = Math.Max(1, ImageWidth);
|
||||
int h = Math.Max(1, ImageHeight);
|
||||
temp = (new byte[w * h * 4], w, h);
|
||||
_buffers["t"] = temp;
|
||||
}
|
||||
|
||||
Compositor.TryCompose(temp.Data, temp.Width, temp.Height, src, ImageWidth, ImageHeight, command);
|
||||
}
|
||||
|
||||
private readonly Dictionary<string, (byte[] Data, int Width, int Height)> _buffers = new(StringComparer.Ordinal);
|
||||
|
||||
internal bool CopyBuffer(string dst, string src)
|
||||
@@ -126,20 +185,29 @@ namespace LuaScript
|
||||
|
||||
private bool TryWriteBuffer(string id, byte[] data, int width, int height)
|
||||
{
|
||||
int n = width * height * 4;
|
||||
switch (BufferKind(id, out string key))
|
||||
{
|
||||
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;
|
||||
case 't':
|
||||
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;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private byte[]? _copyOutputBuffer;
|
||||
|
||||
private static char BufferKind(string id, out string key)
|
||||
{
|
||||
key = string.Empty;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
using YukkuriMovieMaker.Project;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal static class BlendModeMap
|
||||
{
|
||||
private static readonly Blend[] Order =
|
||||
[
|
||||
Blend.Normal,
|
||||
Blend.Dissolve,
|
||||
Blend.Darker,
|
||||
Blend.Multiply,
|
||||
Blend.ColorBurn,
|
||||
Blend.LinearBurn,
|
||||
Blend.Lighter,
|
||||
Blend.Screen,
|
||||
Blend.ColorDodge,
|
||||
Blend.LinearDodge,
|
||||
Blend.Add,
|
||||
Blend.Overlay,
|
||||
Blend.SoftLight,
|
||||
Blend.HardLight,
|
||||
Blend.VividLight,
|
||||
Blend.LinearLight,
|
||||
Blend.PinLight,
|
||||
Blend.HardMix,
|
||||
Blend.Difference,
|
||||
Blend.Exclusion,
|
||||
Blend.Subtract,
|
||||
Blend.Division,
|
||||
Blend.Hue,
|
||||
Blend.Saturation,
|
||||
Blend.Color,
|
||||
Blend.Luminosity,
|
||||
Blend.LighterColor,
|
||||
Blend.DestinationOver,
|
||||
Blend.DarkerColor,
|
||||
Blend.DestinationOut,
|
||||
Blend.SourceAtop,
|
||||
Blend.XOR,
|
||||
Blend.MaskInvert,
|
||||
];
|
||||
|
||||
public static Blend Resolve(double value)
|
||||
{
|
||||
if (double.IsNaN(value))
|
||||
return Blend.Normal;
|
||||
|
||||
int index = (int)value;
|
||||
return (uint)index < (uint)Order.Length ? Order[index] : Blend.Normal;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,5 +8,6 @@ namespace LuaScript
|
||||
double Alpha,
|
||||
double Aspect,
|
||||
double[]? Poly = null,
|
||||
double Antialias = 1d);
|
||||
double Antialias = 1d,
|
||||
double Blend = 0d);
|
||||
}
|
||||
+49
-23
@@ -1,9 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using LuaScript.Compat;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player;
|
||||
using Blend = YukkuriMovieMaker.Project.Blend;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
@@ -15,6 +18,9 @@ namespace LuaScript
|
||||
private ID2D1Bitmap1? _source;
|
||||
private ID2D1Bitmap1? _target;
|
||||
private AffineTransform2D? _placement;
|
||||
private ID2D1Image? _placementOutput;
|
||||
private Opacity? _opacityEffect;
|
||||
private ID2D1Image? _opacityOutput;
|
||||
private int _sourceWidth;
|
||||
private int _sourceHeight;
|
||||
private int _targetWidth;
|
||||
@@ -65,7 +71,7 @@ namespace LuaScript
|
||||
|
||||
var dc = _ctx.DeviceContext;
|
||||
var rt = (ID2D1RenderTarget)dc;
|
||||
var savedTarget = dc.Target;
|
||||
using var savedTarget = dc.Target;
|
||||
|
||||
dc.Target = _target;
|
||||
dc.BeginDraw();
|
||||
@@ -74,40 +80,44 @@ namespace LuaScript
|
||||
for (int i = 0; i < commands.Count; i++)
|
||||
{
|
||||
var cmd = commands[i];
|
||||
if (!DrawTransform.TryResolve(cmd, width, height, out var transform))
|
||||
continue;
|
||||
|
||||
var interpolation = cmd.Antialias != 0d
|
||||
? BitmapInterpolationMode.Linear
|
||||
: BitmapInterpolationMode.NearestNeighbor;
|
||||
var blend = BlendModeMap.Resolve(cmd.Blend);
|
||||
|
||||
if (cmd.Poly is { } poly)
|
||||
{
|
||||
if (!DrawPolyMath.TrySolveAffine(poly, out var affine))
|
||||
continue;
|
||||
rt.Transform = affine * toTarget;
|
||||
rt.DrawBitmap(_source, (float)Math.Clamp(poly[20], 0d, 1d), interpolation);
|
||||
continue;
|
||||
}
|
||||
|
||||
double aspect = Math.Clamp(cmd.Aspect, -1d, 1d);
|
||||
float zx = (float)(cmd.Zoom * (1d + aspect));
|
||||
float zy = (float)(cmd.Zoom * (1d - aspect));
|
||||
float opacity = (float)Math.Clamp(cmd.Alpha, 0d, 1d);
|
||||
|
||||
var matrix =
|
||||
Matrix3x2.CreateTranslation(-width * 0.5f, -height * 0.5f) *
|
||||
Matrix3x2.CreateScale(zx, zy) *
|
||||
Matrix3x2.CreateTranslation((float)(cmd.Ox - originX), (float)(cmd.Oy - originY));
|
||||
|
||||
rt.Transform = matrix;
|
||||
rt.DrawBitmap(_source, opacity, interpolation);
|
||||
rt.Transform = transform * toTarget;
|
||||
DrawSource(rt, (float)Math.Clamp(cmd.Alpha, 0d, 1d), interpolation, blend);
|
||||
}
|
||||
rt.Transform = Matrix3x2.Identity;
|
||||
dc.EndDraw();
|
||||
dc.Target = savedTarget;
|
||||
|
||||
_placement!.TransformMatrix = Matrix3x2.CreateTranslation(originX, originY);
|
||||
return _placement.Output;
|
||||
return _placementOutput!;
|
||||
}
|
||||
|
||||
private void DrawSource(ID2D1RenderTarget rt, float opacity, BitmapInterpolationMode interpolation, Blend blend)
|
||||
{
|
||||
if (blend == Blend.Normal)
|
||||
{
|
||||
rt.DrawBitmap(_source!, opacity, interpolation);
|
||||
return;
|
||||
}
|
||||
|
||||
var interp = ToImageInterpolation(interpolation);
|
||||
_opacityEffect!.Value = opacity;
|
||||
if (blend.IsCompositionEffect())
|
||||
_ctx.DeviceContext.DrawImage(_opacityOutput!, interpolationMode: interp, compositeMode: blend.ToD2DCompositionMode());
|
||||
else
|
||||
_ctx.DeviceContext.BlendImage(_opacityOutput!, blend.ToD2DBlendMode(), null, null, interp);
|
||||
}
|
||||
|
||||
private static InterpolationMode ToImageInterpolation(BitmapInterpolationMode mode) =>
|
||||
mode == BitmapInterpolationMode.Linear ? InterpolationMode.Linear : InterpolationMode.NearestNeighbor;
|
||||
|
||||
private void EnsureSource(int width, int height)
|
||||
{
|
||||
if (_source is not null && _sourceWidth == width && _sourceHeight == height)
|
||||
@@ -117,6 +127,13 @@ namespace LuaScript
|
||||
_source = _ctx.DeviceContext.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
||||
_sourceWidth = width;
|
||||
_sourceHeight = height;
|
||||
|
||||
if (_opacityEffect is null)
|
||||
{
|
||||
_opacityEffect = new Opacity(_ctx.DeviceContext);
|
||||
_opacityOutput = _opacityEffect.Output;
|
||||
}
|
||||
_opacityEffect.SetInput(0, _source, true);
|
||||
}
|
||||
|
||||
private void EnsureTarget(int width, int height)
|
||||
@@ -124,8 +141,10 @@ namespace LuaScript
|
||||
if (_target is not null && _targetWidth == width && _targetHeight == height)
|
||||
return;
|
||||
|
||||
_placementOutput?.Dispose();
|
||||
_placement?.Dispose();
|
||||
_target?.Dispose();
|
||||
_placementOutput = null;
|
||||
_placement = null;
|
||||
|
||||
_target = _ctx.DeviceContext.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
||||
@@ -134,14 +153,21 @@ namespace LuaScript
|
||||
|
||||
_placement = new AffineTransform2D(_ctx.DeviceContext);
|
||||
_placement.SetInput(0, _target, true);
|
||||
_placementOutput = _placement.Output;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_placementOutput?.Dispose();
|
||||
_placement?.Dispose();
|
||||
_opacityOutput?.Dispose();
|
||||
_opacityEffect?.Dispose();
|
||||
_source?.Dispose();
|
||||
_target?.Dispose();
|
||||
_placementOutput = null;
|
||||
_placement = null;
|
||||
_opacityOutput = null;
|
||||
_opacityEffect = null;
|
||||
_source = null;
|
||||
_target = null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal static class DrawTransform
|
||||
{
|
||||
public static bool TryResolve(in DrawCommand command, int srcW, int srcH, out Matrix3x2 matrix)
|
||||
{
|
||||
if (command.Poly is { } poly)
|
||||
return DrawPolyMath.TrySolveAffine(poly, out matrix);
|
||||
|
||||
double aspect = Math.Clamp(command.Aspect, -1d, 1d);
|
||||
double zx = command.Zoom * (1d + aspect);
|
||||
double zy = command.Zoom * (1d - aspect);
|
||||
if (zx == 0d || zy == 0d)
|
||||
{
|
||||
matrix = Matrix3x2.Identity;
|
||||
return false;
|
||||
}
|
||||
|
||||
matrix =
|
||||
Matrix3x2.CreateTranslation(-srcW * 0.5f, -srcH * 0.5f) *
|
||||
Matrix3x2.CreateScale((float)zx, (float)zy) *
|
||||
Matrix3x2.CreateTranslation((float)command.Ox, (float)command.Oy);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,28 +1,95 @@
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.Intrinsics;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
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 WarmupRunsPerPath = 1;
|
||||
private const int TimedRunsPerPath = 3;
|
||||
|
||||
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)
|
||||
{
|
||||
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 block = useBlock ? _block : null;
|
||||
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)
|
||||
{
|
||||
for (int y = 0; y < height; y++)
|
||||
row(buffer, width, y * stride, y, uniforms);
|
||||
RunRow(y);
|
||||
return;
|
||||
}
|
||||
|
||||
Parallel.For(0, height, y => row(buffer, width, y * stride, y, uniforms));
|
||||
Parallel.For(0, height, RunRow);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,11 +31,15 @@ namespace LuaScript.Engine.Kernel
|
||||
[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 width = Expression.Parameter(typeof(int), "width");
|
||||
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 uniforms = Expression.Parameter(typeof(double[]), "uniforms");
|
||||
|
||||
@@ -85,7 +89,7 @@ namespace LuaScript.Engine.Kernel
|
||||
var breakLabel = Expression.Label("break");
|
||||
var loop = Expression.Loop(
|
||||
Expression.IfThenElse(
|
||||
Expression.LessThan(x, width),
|
||||
Expression.LessThan(x, xEnd),
|
||||
Expression.Block(statements),
|
||||
Expression.Break(breakLabel)),
|
||||
breakLabel);
|
||||
@@ -94,10 +98,10 @@ namespace LuaScript.Engine.Kernel
|
||||
locals.AddRange(inputs);
|
||||
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);
|
||||
return new CpuKernel(lambda.Compile());
|
||||
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, y, uniforms);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
private sealed record Context(
|
||||
@@ -151,6 +155,8 @@ namespace LuaScript.Engine.Kernel
|
||||
|
||||
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];
|
||||
if (call.Arguments.Count == 1)
|
||||
return Expression.Call(method, Build(call.Arguments[0], context));
|
||||
|
||||
@@ -1,17 +1,30 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed class GpuKernel : IDisposable
|
||||
{
|
||||
private const int VerifySize = 64;
|
||||
private const int VerifyTolerance = 2;
|
||||
|
||||
private readonly IGraphicsDevicesAndContext _devices;
|
||||
private readonly GpuKernelEffect _effect;
|
||||
private readonly float[] _packed = new float[HlslKernelEmitter.ConstantFloatCount];
|
||||
private readonly byte[] _bytes = new byte[HlslKernelEmitter.ConstantFloatCount * sizeof(float)];
|
||||
private ID2D1Image? _output;
|
||||
|
||||
public GpuKernel(IGraphicsDevicesAndContext devices, KernelProgram program)
|
||||
=> _effect = new GpuKernelEffect(devices, HlslKernelEmitter.Emit(program));
|
||||
{
|
||||
_devices = devices;
|
||||
_effect = new GpuKernelEffect(devices, HlslKernelEmitter.Emit(program));
|
||||
}
|
||||
|
||||
public bool IsReady => _effect.IsReady;
|
||||
|
||||
@@ -21,9 +34,130 @@ namespace LuaScript.Engine.Kernel
|
||||
Buffer.BlockCopy(_packed, 0, _bytes, 0, _bytes.Length);
|
||||
_effect.SetConstants(_bytes);
|
||||
_effect.SetInput(0, input, true);
|
||||
return _effect.Output;
|
||||
return _output ??= _effect.Output;
|
||||
}
|
||||
|
||||
public void Dispose() => _effect.Dispose();
|
||||
public unsafe bool Verify(CpuKernel reference)
|
||||
{
|
||||
if (!IsReady)
|
||||
return false;
|
||||
|
||||
var uniforms = KernelUniformBinding.Create();
|
||||
for (int i = 0; i < uniforms.Length; i++)
|
||||
uniforms[i] = (i % 7) + 1;
|
||||
uniforms[(int)KernelUniform.Width] = VerifySize;
|
||||
uniforms[(int)KernelUniform.Height] = VerifySize;
|
||||
|
||||
byte[] probe = BuildProbe(VerifySize);
|
||||
byte[] expected = (byte[])probe.Clone();
|
||||
reference.Execute(expected, VerifySize, VerifySize, uniforms);
|
||||
|
||||
var dc = (ID2D1DeviceContext)_devices.DeviceContext;
|
||||
ID2D1Bitmap1? source = null;
|
||||
ID2D1Bitmap1? target = null;
|
||||
ID2D1Bitmap1? staging = null;
|
||||
try
|
||||
{
|
||||
source = dc.CreateEmptyBitmap(VerifySize, VerifySize, BitmapOptions.Target);
|
||||
fixed (byte* ptr = probe)
|
||||
source.CopyFromMemory(new nint(ptr), VerifySize * 4);
|
||||
|
||||
target = dc.CreateEmptyBitmap(VerifySize, VerifySize, BitmapOptions.Target);
|
||||
|
||||
var stagingProps = new BitmapProperties1(
|
||||
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
|
||||
96f, 96f,
|
||||
BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
|
||||
staging = dc.CreateBitmap(new SizeI(VerifySize, VerifySize), nint.Zero, VerifySize * 4, stagingProps);
|
||||
|
||||
var output = Apply(source, uniforms);
|
||||
|
||||
using var savedTarget = dc.Target;
|
||||
dc.Target = target;
|
||||
try
|
||||
{
|
||||
dc.BeginDraw();
|
||||
dc.Clear(null);
|
||||
dc.DrawImage(output, new Vector2(0f, 0f));
|
||||
dc.EndDraw();
|
||||
}
|
||||
finally
|
||||
{
|
||||
dc.Target = savedTarget;
|
||||
}
|
||||
|
||||
staging.CopyFromBitmap(target);
|
||||
byte[] actual = new byte[VerifySize * VerifySize * 4];
|
||||
var mapped = staging.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
if (mapped.Pitch == VerifySize * 4)
|
||||
{
|
||||
Marshal.Copy(mapped.Bits, actual, 0, actual.Length);
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int row = 0; row < VerifySize; row++)
|
||||
Marshal.Copy(mapped.Bits + mapped.Pitch * row, actual, row * VerifySize * 4, VerifySize * 4);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
staging.Unmap();
|
||||
}
|
||||
|
||||
return WithinTolerance(expected, actual, VerifyTolerance);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Default.Write("LuaScript: GPU kernel verification could not run; using the CPU kernel.", ex);
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
source?.Dispose();
|
||||
target?.Dispose();
|
||||
staging?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] BuildProbe(int size)
|
||||
{
|
||||
var buffer = new byte[size * size * 4];
|
||||
ReadOnlySpan<int> alphas = [0, 64, 128, 200, 255];
|
||||
for (int y = 0; y < size; y++)
|
||||
{
|
||||
for (int x = 0; x < size; x++)
|
||||
{
|
||||
int alpha = alphas[(x + y) % alphas.Length];
|
||||
int r = x * 255 / (size - 1);
|
||||
int g = y * 255 / (size - 1);
|
||||
int b = (x + y) * 255 / (2 * (size - 1));
|
||||
int p = (y * size + x) * 4;
|
||||
buffer[p] = (byte)(b * alpha / 255);
|
||||
buffer[p + 1] = (byte)(g * alpha / 255);
|
||||
buffer[p + 2] = (byte)(r * alpha / 255);
|
||||
buffer[p + 3] = (byte)alpha;
|
||||
}
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
private static bool WithinTolerance(byte[] expected, byte[] actual, int tolerance)
|
||||
{
|
||||
if (expected.Length != actual.Length)
|
||||
return false;
|
||||
for (int i = 0; i < expected.Length; i++)
|
||||
if (Math.Abs(expected[i] - actual[i]) > tolerance)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_output?.Dispose();
|
||||
_output = null;
|
||||
_effect.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,8 +32,8 @@ namespace LuaScript.Engine.Kernel
|
||||
builder.Append(" float inG = clamp(src.g * invA * 255.0, 0.0, 255.0);\n");
|
||||
builder.Append(" float inB = clamp(src.b * invA * 255.0, 0.0, 255.0);\n");
|
||||
builder.Append(" float inA = srcA * 255.0;\n");
|
||||
builder.Append(" float px = uv.x * ").Append(Uniform(KernelUniform.Width)).Append(";\n");
|
||||
builder.Append(" float py = uv.y * ").Append(Uniform(KernelUniform.Height)).Append(";\n");
|
||||
builder.Append(" float px = uv.x * ").Append(Uniform(KernelUniform.Width)).Append(" - 0.5;\n");
|
||||
builder.Append(" float py = uv.y * ").Append(Uniform(KernelUniform.Height)).Append(" - 0.5;\n");
|
||||
|
||||
for (int i = 0; i < program.Bindings.Count; i++)
|
||||
{
|
||||
@@ -42,21 +42,21 @@ namespace LuaScript.Engine.Kernel
|
||||
builder.Append(";\n");
|
||||
}
|
||||
|
||||
builder.Append(" float outA = ");
|
||||
builder.Append(" float outA = clamp(");
|
||||
EmitExpression(builder, program.OutputA);
|
||||
builder.Append(";\n");
|
||||
builder.Append(" float alphaK = clamp(outA, 0.0, 255.0) / 255.0;\n");
|
||||
builder.Append(", 0.0, 255.0);\n");
|
||||
builder.Append(" float alphaK = outA / 255.0;\n");
|
||||
|
||||
builder.Append(" float oR = clamp((");
|
||||
builder.Append(" float oR = floor(clamp((");
|
||||
EmitExpression(builder, program.OutputR);
|
||||
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
|
||||
builder.Append(" float oG = clamp((");
|
||||
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
|
||||
builder.Append(" float oG = floor(clamp((");
|
||||
EmitExpression(builder, program.OutputG);
|
||||
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
|
||||
builder.Append(" float oB = clamp((");
|
||||
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
|
||||
builder.Append(" float oB = floor(clamp((");
|
||||
EmitExpression(builder, program.OutputB);
|
||||
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
|
||||
builder.Append(" float oA = clamp(outA, 0.0, 255.0) / 255.0;\n");
|
||||
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
|
||||
builder.Append(" float oA = floor(outA) / 255.0;\n");
|
||||
builder.Append(" return float4(oR, oG, oB, oA);\n}\n");
|
||||
|
||||
return builder.ToString();
|
||||
|
||||
@@ -35,6 +35,9 @@ namespace LuaScript.Engine.Kernel
|
||||
private string _widthVariable = string.Empty;
|
||||
private string _heightVariable = string.Empty;
|
||||
private bool _coordsEnabled;
|
||||
private string? _pixelDataVariable;
|
||||
private string _baseIndexVariable = string.Empty;
|
||||
private readonly bool[] _writtenChannels = new bool[4];
|
||||
|
||||
public static KernelProgram? TryExtract(string runnableScript)
|
||||
{
|
||||
@@ -55,6 +58,11 @@ namespace LuaScript.Engine.Kernel
|
||||
int index = 0;
|
||||
while (index < block.Count && block[index] is LocalStmt prelude)
|
||||
{
|
||||
if (TryBindPixelData(prelude))
|
||||
{
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
BindLocal(prelude);
|
||||
index++;
|
||||
}
|
||||
@@ -72,11 +80,140 @@ namespace LuaScript.Engine.Kernel
|
||||
return null;
|
||||
if (outerAxis == innerAxis)
|
||||
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;
|
||||
_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)
|
||||
@@ -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;
|
||||
if (call.Arguments.Count is < 5 or > 6)
|
||||
return null;
|
||||
@@ -167,6 +304,10 @@ namespace LuaScript.Engine.Kernel
|
||||
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
|
||||
string.Equals(name, _heightVariable, StringComparison.Ordinal))
|
||||
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)
|
||||
@@ -187,6 +328,8 @@ namespace LuaScript.Engine.Kernel
|
||||
return LowerMember(member);
|
||||
case CallExpr call:
|
||||
return LowerCall(call);
|
||||
case MethodCallExpr method when TryPixelDataChannel(method, out int channel):
|
||||
return new KInput((KChannel)channel);
|
||||
case UnaryExpr { Operator: "-" } unary:
|
||||
return new KNegate(Lower(unary.Operand));
|
||||
case BinaryExpr binary:
|
||||
@@ -323,20 +466,36 @@ namespace LuaScript.Engine.Kernel
|
||||
return false;
|
||||
if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound)
|
||||
return false;
|
||||
if (bound.Left is not MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field })
|
||||
return false;
|
||||
if (!KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||
return false;
|
||||
|
||||
if (uniform == KernelUniform.Width)
|
||||
if (bound.Left is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
||||
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||
{
|
||||
axis = KAxis.X;
|
||||
return true;
|
||||
if (uniform == KernelUniform.Width)
|
||||
{
|
||||
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;
|
||||
return true;
|
||||
if (pixelField == "width")
|
||||
{
|
||||
axis = KAxis.X;
|
||||
return true;
|
||||
}
|
||||
if (pixelField == "height")
|
||||
{
|
||||
axis = KAxis.Y;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,8 @@ namespace LuaScript.Engine.Kernel
|
||||
|
||||
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 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 CallStmt(CallExpr Call) : LuaStmt;
|
||||
internal sealed record CallStmt(LuaExpr Call) : LuaStmt;
|
||||
|
||||
internal sealed record IfClause(LuaExpr Condition, IReadOnlyList<LuaStmt> Body);
|
||||
|
||||
|
||||
@@ -149,8 +149,8 @@ namespace LuaScript.Engine.Kernel
|
||||
return new AssignStmt(targets, values);
|
||||
}
|
||||
|
||||
if (first is CallExpr call)
|
||||
return new CallStmt(call);
|
||||
if (first is CallExpr or MethodCallExpr)
|
||||
return new CallStmt(first);
|
||||
|
||||
throw new KernelUnsupportedException("Expression is not a valid statement.");
|
||||
}
|
||||
@@ -275,6 +275,12 @@ namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
expression = new CallExpr(expression, ParseArguments());
|
||||
}
|
||||
else if (t.IsSymbol(":"))
|
||||
{
|
||||
Advance();
|
||||
string method = ExpectName();
|
||||
expression = new MethodCallExpr(expression, method, ParseArguments());
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
|
||||
@@ -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<>);
|
||||
}
|
||||
}
|
||||
+152
-58
@@ -19,17 +19,20 @@ namespace LuaScript.Engine
|
||||
private EventWaitHandle? _workEvent;
|
||||
private EventWaitHandle? _doneEvent;
|
||||
private Process? _process;
|
||||
private int _width;
|
||||
private int _height;
|
||||
private int _stringParamsCapacity = NativeProtocol.MinStringParamsCapacity;
|
||||
private long _pixelOffset = NativeProtocol.PixelOffset(NativeProtocol.MinStringParamsCapacity);
|
||||
private long _allocatedSize;
|
||||
private bool _alive;
|
||||
|
||||
private readonly byte[] _callbackTag = new byte[NativeProtocol.CallbackTagMax];
|
||||
private readonly byte[] _lastCallbackTag = new byte[NativeProtocol.CallbackTagMax];
|
||||
private readonly double[] _anchorBuffer = new double[Anchor.AnchorSupport.MaxAnchors * 3];
|
||||
private int _lastCallbackTagLength = -1;
|
||||
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 byte[] _stringValueBytes = new byte[256];
|
||||
|
||||
@@ -48,7 +51,7 @@ namespace LuaScript.Engine
|
||||
string script,
|
||||
double[] fields,
|
||||
IReadOnlyDictionary<string, string> stringParameters,
|
||||
byte[] pixels,
|
||||
PixelRegionAccess loadPixels,
|
||||
int width,
|
||||
int height,
|
||||
int timeoutMs,
|
||||
@@ -59,25 +62,31 @@ namespace LuaScript.Engine
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
|
||||
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
|
||||
Action<DrawCommand> addDraw,
|
||||
Action<string, int, bool, int, double[]> setAnchor,
|
||||
out bool pixelsDirty,
|
||||
out bool bufferReplaced,
|
||||
out byte[]? newPixels,
|
||||
out int resultWidth,
|
||||
out int resultHeight,
|
||||
out string? error)
|
||||
{
|
||||
pixelsDirty = false;
|
||||
bufferReplaced = false;
|
||||
newPixels = null;
|
||||
resultWidth = width;
|
||||
resultHeight = height;
|
||||
error = null;
|
||||
|
||||
byte[] scriptBytes = Encoding.UTF8.GetBytes(script);
|
||||
if (scriptBytes.Length > NativeProtocol.ScriptMax)
|
||||
bool scriptChanged = !ReferenceEquals(script, _lastScript);
|
||||
if (scriptChanged)
|
||||
{
|
||||
error = "script too large for native lane";
|
||||
return false;
|
||||
byte[] scriptBytes = Encoding.UTF8.GetBytes(script);
|
||||
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));
|
||||
@@ -88,9 +97,13 @@ namespace LuaScript.Engine
|
||||
WriteStringParameters(view, stringParameters);
|
||||
view.Write(NativeProtocol.OffWidth, width);
|
||||
view.Write(NativeProtocol.OffHeight, height);
|
||||
view.Write(NativeProtocol.OffScriptLen, scriptBytes.Length);
|
||||
view.WriteArray(NativeProtocol.ScriptOffset, scriptBytes, 0, scriptBytes.Length);
|
||||
view.WriteArray(_pixelOffset, pixels, 0, pixels.Length);
|
||||
if (scriptChanged || !_scriptWritten)
|
||||
{
|
||||
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.OffErrorLen, 0);
|
||||
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
|
||||
@@ -114,7 +127,27 @@ namespace LuaScript.Engine
|
||||
if (status != NativeProtocol.StatusCallback)
|
||||
break;
|
||||
|
||||
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, addDraw);
|
||||
int callbackKind = view.ReadInt32(NativeProtocol.OffCallbackKind);
|
||||
if (callbackKind == NativeProtocol.CbKindRequestPixels)
|
||||
{
|
||||
try
|
||||
{
|
||||
AccessPixelRegion(loadPixels);
|
||||
}
|
||||
catch
|
||||
{
|
||||
KillWorker();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
else if (callbackKind == NativeProtocol.CbKindFlushDraws)
|
||||
{
|
||||
DrainDrawRing(view, addDraw);
|
||||
}
|
||||
else
|
||||
{
|
||||
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, setAnchor);
|
||||
}
|
||||
_workEvent.Set();
|
||||
}
|
||||
|
||||
@@ -127,33 +160,61 @@ namespace LuaScript.Engine
|
||||
return false;
|
||||
}
|
||||
|
||||
DrainDrawRing(view, addDraw);
|
||||
|
||||
for (int i = NativeProtocol.FirstWritableField; i <= NativeProtocol.LastWritableField; i++)
|
||||
fields[i] = view.ReadDouble(NativeProtocol.FieldsOffset + i * 8);
|
||||
|
||||
fields[NativeProtocol.DrawState] = view.ReadDouble(NativeProtocol.FieldsOffset + NativeProtocol.DrawState * 8);
|
||||
|
||||
resultWidth = view.ReadInt32(NativeProtocol.OffWidth);
|
||||
resultHeight = view.ReadInt32(NativeProtocol.OffHeight);
|
||||
bufferReplaced = resultWidth != width || resultHeight != height;
|
||||
|
||||
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
|
||||
if (pixelsDirty)
|
||||
if (pixelsDirty && (long)resultWidth * resultHeight * 4 > _allocatedSize - _pixelOffset)
|
||||
{
|
||||
if (bufferReplaced)
|
||||
{
|
||||
int pixelSize = resultWidth * resultHeight * 4;
|
||||
if (_resultBuffer == null || _resultBuffer.Length < pixelSize)
|
||||
_resultBuffer = new byte[pixelSize];
|
||||
view.ReadArray(_pixelOffset, _resultBuffer, 0, pixelSize);
|
||||
newPixels = _resultBuffer;
|
||||
}
|
||||
else
|
||||
{
|
||||
view.ReadArray(_pixelOffset, pixels, 0, pixels.Length);
|
||||
}
|
||||
error = "native worker reported a pixel buffer beyond capacity";
|
||||
return false;
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
var handle = _view!.SafeMemoryMappedViewHandle;
|
||||
byte* ptr = null;
|
||||
handle.AcquirePointer(ref ptr);
|
||||
try
|
||||
{
|
||||
fixed (byte* src = source)
|
||||
Buffer.MemoryCopy(src, ptr + _view.PointerOffset + _pixelOffset, handle.ByteLength - (ulong)(_view.PointerOffset + _pixelOffset), (ulong)length);
|
||||
}
|
||||
finally
|
||||
{
|
||||
handle.ReleasePointer();
|
||||
}
|
||||
}
|
||||
|
||||
private static int MeasureStringParameters(IReadOnlyDictionary<string, string> stringParameters)
|
||||
{
|
||||
int total = 4;
|
||||
@@ -174,8 +235,6 @@ namespace LuaScript.Engine
|
||||
}
|
||||
capacity *= 2;
|
||||
}
|
||||
while (capacity > NativeProtocol.MinStringParamsCapacity && required <= capacity / 2)
|
||||
capacity /= 2;
|
||||
return capacity;
|
||||
}
|
||||
|
||||
@@ -217,7 +276,7 @@ namespace LuaScript.Engine
|
||||
Func<string, (byte[] buffer, int w, int h)> loadImage,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
|
||||
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
|
||||
Action<DrawCommand> addDraw)
|
||||
Action<string, int, bool, int, double[]> setAnchor)
|
||||
{
|
||||
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
|
||||
switch (kind)
|
||||
@@ -240,41 +299,75 @@ namespace LuaScript.Engine
|
||||
case NativeProtocol.CbKindEffect:
|
||||
ResolveEffectCallback(view, addEffect);
|
||||
break;
|
||||
case NativeProtocol.CbKindDraw:
|
||||
ResolveDrawCallback(view, addDraw);
|
||||
break;
|
||||
case NativeProtocol.CbKindDrawPoly:
|
||||
ResolveDrawPolyCallback(view, addDraw);
|
||||
case NativeProtocol.CbKindSetAnchor:
|
||||
ResolveSetAnchorCallback(view, setAnchor);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void ResolveDrawCallback(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
|
||||
private void ResolveSetAnchorCallback(MemoryMappedViewAccessor view, Action<string, int, bool, int, double[]> setAnchor)
|
||||
{
|
||||
long rOff = NativeProtocol.CallbackResultOffset;
|
||||
double ox = view.ReadDouble(rOff + 0 * 8);
|
||||
double oy = view.ReadDouble(rOff + 1 * 8);
|
||||
double oz = view.ReadDouble(rOff + 2 * 8);
|
||||
double zoom = view.ReadDouble(rOff + 3 * 8);
|
||||
double alpha = view.ReadDouble(rOff + 4 * 8);
|
||||
double aspect = view.ReadDouble(rOff + 5 * 8);
|
||||
double antialias = view.ReadDouble(rOff + 6 * 8);
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
string group = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||
|
||||
try { addDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, antialias)); }
|
||||
long rOff = NativeProtocol.CallbackResultOffset;
|
||||
int count = Math.Clamp((int)view.ReadDouble(rOff + 0 * 8), 0, Anchor.AnchorSupport.MaxAnchors);
|
||||
bool is3D = view.ReadDouble(rOff + 1 * 8) != 0d;
|
||||
int connection = (int)view.ReadDouble(rOff + 2 * 8);
|
||||
|
||||
Array.Clear(_anchorBuffer, 0, _anchorBuffer.Length);
|
||||
try { setAnchor(group, count, is3D, connection, _anchorBuffer); }
|
||||
catch { }
|
||||
|
||||
int stride = is3D ? 3 : 2;
|
||||
for (int i = 0; i < count * stride; i++)
|
||||
view.Write(NativeProtocol.CallbackTagOffset + i * 8, _anchorBuffer[i]);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private static void ResolveDrawPolyCallback(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
|
||||
private void DrainDrawRing(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
|
||||
{
|
||||
long ringBase = NativeProtocol.DrawRingOffset(_stringParamsCapacity);
|
||||
int count = Math.Clamp((int)view.ReadDouble(ringBase), 0, NativeProtocol.DrawRingCapacity);
|
||||
for (int k = 0; k < count; k++)
|
||||
{
|
||||
long entry = ringBase + (1 + (long)k * NativeProtocol.DrawEntryDoubles) * 8;
|
||||
int kind = (int)view.ReadDouble(entry);
|
||||
long payload = entry + 8;
|
||||
if (kind == NativeProtocol.CbKindDrawPoly)
|
||||
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)); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static void DispatchRingDrawPoly(MemoryMappedViewAccessor view, long payload, Action<DrawCommand> addDraw)
|
||||
{
|
||||
var poly = new double[DrawPolyMath.Length];
|
||||
for (int i = 0; i < DrawPolyMath.Length; i++)
|
||||
poly[i] = view.ReadDouble(NativeProtocol.CallbackTagOffset + i * 8);
|
||||
double antialias = view.ReadDouble(NativeProtocol.CallbackTagOffset + DrawPolyMath.Length * 8);
|
||||
poly[i] = view.ReadDouble(payload + i * 8);
|
||||
double antialias = view.ReadDouble(payload + DrawPolyMath.Length * 8);
|
||||
double blend = view.ReadDouble(payload + (DrawPolyMath.Length + 1) * 8);
|
||||
|
||||
try { addDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, antialias)); }
|
||||
try { addDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, antialias, blend)); }
|
||||
catch { }
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private void ResolveGetObjectCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject)
|
||||
@@ -335,7 +428,7 @@ namespace LuaScript.Engine
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
view.WriteArray(_pixelOffset, result.buffer, 0, pixelSize);
|
||||
WritePixelRegion(result.buffer, pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
@@ -370,7 +463,7 @@ namespace LuaScript.Engine
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
view.WriteArray(_pixelOffset, result.buffer, 0, pixelSize);
|
||||
WritePixelRegion(result.buffer, pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
@@ -396,7 +489,7 @@ namespace LuaScript.Engine
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
view.WriteArray(_pixelOffset, result.buffer, 0, pixelSize);
|
||||
WritePixelRegion(result.buffer, pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
@@ -423,7 +516,7 @@ namespace LuaScript.Engine
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
view.WriteArray(_pixelOffset, result.buffer, 0, pixelSize);
|
||||
WritePixelRegion(result.buffer, pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
@@ -473,7 +566,8 @@ namespace LuaScript.Engine
|
||||
|
||||
private void EnsureWorker(int width, int height, int stringCapacity)
|
||||
{
|
||||
if (_alive && _process is { HasExited: false } && _width == width && _height == height && _stringParamsCapacity == stringCapacity)
|
||||
long required = NativeProtocol.PixelOffset(stringCapacity) + (long)width * height * 4;
|
||||
if (_alive && _process is { HasExited: false } && _stringParamsCapacity == stringCapacity && required <= _allocatedSize)
|
||||
return;
|
||||
|
||||
KillWorker();
|
||||
@@ -482,11 +576,11 @@ namespace LuaScript.Engine
|
||||
|
||||
private void StartWorker(int width, int height, int stringCapacity)
|
||||
{
|
||||
_width = width;
|
||||
_height = height;
|
||||
_stringParamsCapacity = stringCapacity;
|
||||
_scriptWritten = false;
|
||||
_pixelOffset = NativeProtocol.PixelOffset(stringCapacity);
|
||||
long size = NativeProtocol.BufferSize(width, height, stringCapacity);
|
||||
long size = Math.Max(NativeProtocol.BufferSize(width, height, stringCapacity), _allocatedSize);
|
||||
_allocatedSize = size;
|
||||
|
||||
string suffix = Guid.NewGuid().ToString("N");
|
||||
string mapName = "LuaScriptMap_" + suffix;
|
||||
|
||||
@@ -4,8 +4,6 @@ namespace LuaScript.Engine
|
||||
{
|
||||
internal static class NativeFieldMap
|
||||
{
|
||||
private const double Epsilon = 1e-10;
|
||||
|
||||
public static void ToFields(AviUtlScriptContext ctx, double[] f)
|
||||
{
|
||||
f[NativeProtocol.W] = ctx.ImageWidth;
|
||||
@@ -93,6 +91,13 @@ namespace LuaScript.Engine
|
||||
f[NativeProtocol.Rxr],
|
||||
f[NativeProtocol.Ryr],
|
||||
f[NativeProtocol.Rzr]);
|
||||
|
||||
ctx.DrawStateOverride = f[NativeProtocol.DrawState] switch
|
||||
{
|
||||
1d => true,
|
||||
2d => false,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ namespace LuaScript.Engine
|
||||
public const int OffLoadResultWidth = 48;
|
||||
public const int OffLoadResultHeight = 52;
|
||||
public const int OffStringParamsLen = 56;
|
||||
public const int OffScriptVersion = 60;
|
||||
|
||||
public const int HeaderSize = 64;
|
||||
|
||||
@@ -55,6 +56,14 @@ namespace LuaScript.Engine
|
||||
public const int CbKindLoadText = 5;
|
||||
public const int CbKindLoadImage = 6;
|
||||
public const int CbKindLoadMovie = 7;
|
||||
public const int CbKindSetAnchor = 8;
|
||||
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 CbX = 1;
|
||||
@@ -65,7 +74,9 @@ namespace LuaScript.Engine
|
||||
public const int CbAlpha = 6;
|
||||
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 H = 1;
|
||||
@@ -129,6 +140,7 @@ namespace LuaScript.Engine
|
||||
public const int Slider1 = 59;
|
||||
public const int Slider2 = 60;
|
||||
public const int Slider3 = 61;
|
||||
public const int DrawState = 62;
|
||||
|
||||
public const int FirstWritableField = X;
|
||||
public const int LastWritableField = Rzr;
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine
|
||||
{
|
||||
internal delegate void PixelRegionAccess(nint address, long capacity);
|
||||
}
|
||||
@@ -9,23 +9,14 @@ namespace LuaScript.Engine
|
||||
|
||||
public static ScriptEngineKind ResolveAuto(string? script)
|
||||
{
|
||||
if (TryGetDirective(script, out var kind))
|
||||
return kind;
|
||||
if (UsesDrawingApi(script))
|
||||
if (string.IsNullOrEmpty(script))
|
||||
return ScriptEngineKind.MoonSharp;
|
||||
return UsesPixelApi(script) ? ScriptEngineKind.Native : ScriptEngineKind.MoonSharp;
|
||||
return TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.Native;
|
||||
}
|
||||
|
||||
public static bool TryResolveExplicit(string? script, out ScriptEngineKind kind) =>
|
||||
TryGetDirective(script, out kind);
|
||||
|
||||
public static bool UsesPixelApi(string? script) =>
|
||||
script is not null && (script.Contains("getpixel", StringComparison.Ordinal) || script.Contains("setpixel", StringComparison.Ordinal));
|
||||
|
||||
public static bool UsesDrawingApi(string? script) =>
|
||||
script is not null &&
|
||||
script.Contains("obj.setoption", StringComparison.Ordinal);
|
||||
|
||||
private static bool TryGetDirective(string? script, out ScriptEngineKind kind)
|
||||
{
|
||||
kind = ScriptEngineKind.MoonSharp;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class FallbackCompositor(
|
||||
IBufferCompositor primary,
|
||||
IBufferCompositor fallback,
|
||||
Action<Exception>? onDegraded = null) : IBufferCompositor, IDisposable
|
||||
{
|
||||
private bool _degraded;
|
||||
|
||||
public bool IsDegraded => _degraded;
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
if (!_degraded)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (primary.TryCompose(dst, dstW, dstH, src, srcW, srcH, command))
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_degraded = true;
|
||||
onDegraded?.Invoke(ex);
|
||||
}
|
||||
}
|
||||
return fallback.TryCompose(dst, dstW, dstH, src, srcW, srcH, command);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
(primary as IDisposable)?.Dispose();
|
||||
(fallback as IDisposable)?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class HardwareCompositor : IBufferCompositor, IDisposable
|
||||
{
|
||||
private const int MaxDimension = 8192;
|
||||
|
||||
private readonly GraphicsDevicesAndContext _ctx;
|
||||
private ID2D1Bitmap1? _source;
|
||||
private ID2D1Bitmap1? _target;
|
||||
private ID2D1Bitmap1? _staging;
|
||||
private int _sourceWidth;
|
||||
private int _sourceHeight;
|
||||
private int _targetWidth;
|
||||
private int _targetHeight;
|
||||
|
||||
public HardwareCompositor(GraphicsDevicesAndContext ctx)
|
||||
{
|
||||
_ctx = ctx;
|
||||
}
|
||||
|
||||
public unsafe bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
if (srcW <= 0 || srcH <= 0 || dstW <= 0 || dstH <= 0)
|
||||
return true;
|
||||
if (srcW > MaxDimension || srcH > MaxDimension || dstW > MaxDimension || dstH > MaxDimension)
|
||||
return false;
|
||||
if (src.Length < srcW * srcH * 4 || dst.Length < dstW * dstH * 4)
|
||||
return false;
|
||||
if (!DrawTransform.TryResolve(command, srcW, srcH, out var transform))
|
||||
return true;
|
||||
|
||||
float opacity = (float)Math.Clamp(command.Alpha, 0d, 1d);
|
||||
if (opacity <= 0f)
|
||||
return true;
|
||||
|
||||
EnsureSource(srcW, srcH);
|
||||
EnsureTarget(dstW, dstH);
|
||||
|
||||
fixed (byte* ptr = src)
|
||||
_source!.CopyFromMemory(new nint(ptr), srcW * 4);
|
||||
fixed (byte* ptr = dst)
|
||||
_target!.CopyFromMemory(new nint(ptr), dstW * 4);
|
||||
|
||||
var interpolation = command.Antialias != 0d
|
||||
? BitmapInterpolationMode.Linear
|
||||
: BitmapInterpolationMode.NearestNeighbor;
|
||||
|
||||
var dc = _ctx.DeviceContext;
|
||||
var rt = (ID2D1RenderTarget)dc;
|
||||
using var savedTarget = dc.Target;
|
||||
dc.Target = _target;
|
||||
try
|
||||
{
|
||||
dc.BeginDraw();
|
||||
rt.Transform = transform;
|
||||
rt.DrawBitmap(_source!, opacity, interpolation);
|
||||
rt.Transform = Matrix3x2.Identity;
|
||||
dc.EndDraw();
|
||||
}
|
||||
finally
|
||||
{
|
||||
dc.Target = savedTarget;
|
||||
}
|
||||
|
||||
_staging!.CopyFromBitmap(_target!);
|
||||
var mapped = _staging.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
if (mapped.Pitch == dstW * 4)
|
||||
{
|
||||
Marshal.Copy(mapped.Bits, dst, 0, dstW * dstH * 4);
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int row = 0; row < dstH; row++)
|
||||
Marshal.Copy(mapped.Bits + mapped.Pitch * row, dst, row * dstW * 4, dstW * 4);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_staging.Unmap();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void EnsureSource(int width, int height)
|
||||
{
|
||||
if (_source is not null && _sourceWidth == width && _sourceHeight == height)
|
||||
return;
|
||||
|
||||
_source?.Dispose();
|
||||
_source = _ctx.DeviceContext.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
||||
_sourceWidth = width;
|
||||
_sourceHeight = height;
|
||||
}
|
||||
|
||||
private void EnsureTarget(int width, int height)
|
||||
{
|
||||
if (_target is not null && _targetWidth == width && _targetHeight == height)
|
||||
return;
|
||||
|
||||
_target?.Dispose();
|
||||
_staging?.Dispose();
|
||||
_target = null;
|
||||
_staging = null;
|
||||
|
||||
var dc = _ctx.DeviceContext;
|
||||
_target = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
||||
|
||||
var stagingProps = new BitmapProperties1(
|
||||
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
|
||||
96f, 96f,
|
||||
BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
|
||||
_staging = dc.CreateBitmap(new SizeI(width, height), nint.Zero, width * 4, stagingProps);
|
||||
|
||||
_targetWidth = width;
|
||||
_targetHeight = height;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_source?.Dispose();
|
||||
_target?.Dispose();
|
||||
_staging?.Dispose();
|
||||
_source = null;
|
||||
_target = null;
|
||||
_staging = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal interface IBufferCompositor
|
||||
{
|
||||
bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.10.0</Version>
|
||||
<Version>1.12.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Windows.Media;
|
||||
using LuaScript.Anchor;
|
||||
using LuaScript.Compat;
|
||||
using Newtonsoft.Json;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
@@ -293,6 +295,19 @@ namespace LuaScript
|
||||
return Color.FromRgb(r, g, b);
|
||||
}
|
||||
|
||||
public ImmutableList<LuaAnchorPoint> Anchors
|
||||
{
|
||||
get => _anchors;
|
||||
set { if (Set(ref _anchors, value ?? ImmutableList<LuaAnchorPoint>.Empty)) AnchorVersion++; }
|
||||
}
|
||||
ImmutableList<LuaAnchorPoint> _anchors = ImmutableList<LuaAnchorPoint>.Empty;
|
||||
|
||||
[JsonIgnore]
|
||||
internal int AnchorVersion { get; private set; }
|
||||
|
||||
internal void ApplyAnchorDrag(string group, int index, double dx, double dy, double dz)
|
||||
=> Anchors = AnchorSupport.ApplyDrag(Anchors, group, index, dx, dy, dz);
|
||||
|
||||
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
|
||||
|
||||
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.IO;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using LuaScript.Anchor;
|
||||
using LuaScript.Compat;
|
||||
using LuaScript.Diagnostics;
|
||||
using LuaScript.Engine;
|
||||
@@ -40,7 +42,7 @@ namespace LuaScript
|
||||
bool Check3,
|
||||
bool HasColor,
|
||||
int Color,
|
||||
string Script,
|
||||
int ScriptVersion,
|
||||
int StringsVersion,
|
||||
TimelineSourceUsage Usage,
|
||||
Guid SceneId,
|
||||
@@ -55,6 +57,7 @@ namespace LuaScript
|
||||
int GroupCount,
|
||||
int TimelineTotalFrame,
|
||||
double TimelineTotalTime,
|
||||
int AnchorVersion,
|
||||
DrawDescription InputDesc
|
||||
);
|
||||
|
||||
@@ -73,6 +76,9 @@ namespace LuaScript
|
||||
private bool _effectChainWarned;
|
||||
private bool _gpuWarned;
|
||||
|
||||
private string? _scriptKeyRef;
|
||||
private int _scriptKeyVersion;
|
||||
|
||||
private string _kernelSource = string.Empty;
|
||||
private bool _kernelResolved;
|
||||
private KernelProgram? _kernelProgram;
|
||||
@@ -93,6 +99,34 @@ namespace LuaScript
|
||||
|
||||
private PixelBufferManager? _pixelManager;
|
||||
|
||||
private RawRectF _pixelBounds;
|
||||
private int _pixelWidth;
|
||||
private int _pixelHeight;
|
||||
private Func<byte[]>? _pixelLoader;
|
||||
|
||||
private string _directiveSource = string.Empty;
|
||||
private bool _directiveCached;
|
||||
private ScriptEngineKind _autoKind;
|
||||
private bool _hasExplicitDirective;
|
||||
private ScriptEngineKind _explicitDirectiveKind;
|
||||
|
||||
private PixelRegionAccess? _nativeUpload;
|
||||
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, 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, (byte[] buffer, int w, int h)>? _nativeLoadImage;
|
||||
private Func<string, double, (byte[] buffer, int w, int h)>? _nativeLoadMovie;
|
||||
private Action<string, IReadOnlyList<KeyValuePair<string, object>>>? _nativeAddEffect;
|
||||
private Action<DrawCommand>? _nativeAddDraw;
|
||||
private Action<string, int, bool, int, double[]>? _nativeSetAnchor;
|
||||
|
||||
private bool _isFirst = true;
|
||||
private string _sourceScript = string.Empty;
|
||||
private string _runnableScript = string.Empty;
|
||||
@@ -106,6 +140,7 @@ namespace LuaScript
|
||||
|
||||
private VideoEffectChain? _effectChain;
|
||||
private DrawCompositor? _drawCompositor;
|
||||
private FallbackCompositor? _bufferCompositor;
|
||||
private TextRenderer? _nativeTextRenderer;
|
||||
private ImageDecoder? _nativeImageDecoder;
|
||||
private MovieDecoder? _nativeMovieDecoder;
|
||||
@@ -115,10 +150,26 @@ namespace LuaScript
|
||||
_ownCtx = new GraphicsDevicesAndContext(devices);
|
||||
disposer.Collect(_ownCtx);
|
||||
_pixelManager = new PixelBufferManager(_ownCtx);
|
||||
_bufferCompositor = new FallbackCompositor(
|
||||
new SynchronizedCompositor(new HardwareCompositor(_ownCtx), _pixelLoaderSemaphore),
|
||||
SoftwareCompositor.Instance,
|
||||
WarnBufferCompositorDegraded);
|
||||
_context.ResolverProvider = GetFrameResolver;
|
||||
_context.Compositor = _bufferCompositor;
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void WarnBufferCompositorDegraded(Exception ex) =>
|
||||
Log.Default.Write("LuaScript: hardware buffer compositing failed; falling back to the software compositor.", ex);
|
||||
|
||||
private AviUtlScriptContext CreateScriptContext()
|
||||
{
|
||||
var context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
|
||||
if (_bufferCompositor is not null)
|
||||
context.Compositor = _bufferCompositor;
|
||||
return context;
|
||||
}
|
||||
|
||||
private SceneObjectResolver GetFrameResolver()
|
||||
{
|
||||
if (!_frameResolverBuilt)
|
||||
@@ -200,6 +251,11 @@ namespace LuaScript
|
||||
var fps = desc.FPS;
|
||||
var time = desc.ItemPosition.Time.TotalSeconds;
|
||||
var script = item.Script ?? string.Empty;
|
||||
if (!ReferenceEquals(script, _scriptKeyRef))
|
||||
{
|
||||
_scriptKeyRef = script;
|
||||
_scriptKeyVersion++;
|
||||
}
|
||||
|
||||
var layout = item.Layout;
|
||||
var t0 = ClampTrack(item.Track0.GetValue(frame, length, fps), layout, 0);
|
||||
@@ -219,7 +275,7 @@ namespace LuaScript
|
||||
t0, t1, t2, t3,
|
||||
s0, s1, s2, s3,
|
||||
c0, c1, c2, c3, hasColor, colorRgb,
|
||||
script, RefreshStringParameters(),
|
||||
_scriptKeyVersion, RefreshStringParameters(),
|
||||
desc.Usage, desc.SceneId,
|
||||
desc.TimelinePosition.Frame,
|
||||
desc.TimelinePosition.Time.TotalSeconds,
|
||||
@@ -228,6 +284,7 @@ namespace LuaScript
|
||||
desc.GroupIndex, desc.GroupCount,
|
||||
desc.TimelineDuration.Frame,
|
||||
desc.TimelineDuration.Time.TotalSeconds,
|
||||
item.AnchorVersion,
|
||||
inDesc);
|
||||
|
||||
_frameDesc = desc;
|
||||
@@ -247,7 +304,10 @@ namespace LuaScript
|
||||
|
||||
var ctx = _context;
|
||||
PopulateContext(ctx, in key, imgW, imgH);
|
||||
ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH));
|
||||
_pixelBounds = bounds;
|
||||
_pixelWidth = imgW;
|
||||
_pixelHeight = imgH;
|
||||
ctx.SetPixelLoader(_pixelLoader ??= LoadPendingInputPixels);
|
||||
|
||||
DrawDescription outDesc = inDesc;
|
||||
IReadOnlyList<LuaScriptDiagnostic> diagnostics = [];
|
||||
@@ -256,14 +316,15 @@ namespace LuaScript
|
||||
{
|
||||
string runnable = GetRunnableScript(script);
|
||||
EnsureKernel(runnable);
|
||||
EnsureDirective(runnable);
|
||||
|
||||
if (ExecuteKernelLane(runnable, ctx, bounds, imgW, imgH))
|
||||
if (ExecuteKernelLane(ctx, bounds, imgW, imgH))
|
||||
{
|
||||
outDesc = inDesc;
|
||||
}
|
||||
else
|
||||
{
|
||||
bool wantNative = ScriptDirective.ResolveAuto(runnable) == ScriptEngineKind.Native;
|
||||
bool wantNative = _autoKind == ScriptEngineKind.Native;
|
||||
bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory);
|
||||
if (wantNative && !nativeReady)
|
||||
WarnNativeUnavailableOnce();
|
||||
@@ -303,6 +364,8 @@ namespace LuaScript
|
||||
}
|
||||
}
|
||||
|
||||
ApplyDrawState(ctx, bounds);
|
||||
|
||||
outDesc = BuildOutputDesc(inDesc, ctx);
|
||||
|
||||
if (ctx.EffectRequests.Count > 0)
|
||||
@@ -318,12 +381,14 @@ namespace LuaScript
|
||||
WarnEffectChainFailureOnce(ex);
|
||||
}
|
||||
}
|
||||
|
||||
outDesc = AddAnchorControllers(outDesc, ctx);
|
||||
}
|
||||
}
|
||||
catch (LuaScriptTimeoutException ex)
|
||||
{
|
||||
effectOutput = null;
|
||||
_context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
|
||||
_context = CreateScriptContext();
|
||||
_isFirst = true;
|
||||
Log.Default.Write(ex.Message, ex);
|
||||
LuaScriptDiagnostics.Instance.Report(script, [CreateDiagnostic(LuaScriptDiagnosticKind.Timeout, ex.Message)]);
|
||||
@@ -464,6 +529,10 @@ namespace LuaScript
|
||||
ctx.ClearQueries();
|
||||
ctx.ClearEffects();
|
||||
ctx.ClearDraws();
|
||||
ctx.ClearAnchorRequests();
|
||||
ctx.AnchorSource = item.Anchors;
|
||||
ctx.DrawStateOverride = null;
|
||||
ctx.ResetDrawTarget();
|
||||
|
||||
ctx.ImageWidth = imgW;
|
||||
ctx.ImageHeight = imgH;
|
||||
@@ -524,6 +593,143 @@ namespace LuaScript
|
||||
return layout.GetTrack(index) is { } p ? Math.Clamp(value, p.Min, p.Max) : value;
|
||||
}
|
||||
|
||||
private ImmutableList<VideoEffectController> _anchorControllers = ImmutableList<VideoEffectController>.Empty;
|
||||
private AnchorRequestData[] _anchorSignature = [];
|
||||
private IReadOnlyList<LuaAnchorPoint>? _anchorSignatureSource;
|
||||
|
||||
private ImmutableList<VideoEffectController> ResolveAnchorControllers(AviUtlScriptContext ctx)
|
||||
{
|
||||
var requests = ctx.AnchorRequests;
|
||||
if (requests.Count == 0)
|
||||
{
|
||||
_anchorControllers = ImmutableList<VideoEffectController>.Empty;
|
||||
_anchorSignature = [];
|
||||
_anchorSignatureSource = null;
|
||||
return _anchorControllers;
|
||||
}
|
||||
|
||||
if (ReferenceEquals(_anchorSignatureSource, ctx.AnchorSource) && AnchorSignatureMatches(requests))
|
||||
return _anchorControllers;
|
||||
|
||||
_anchorControllers = BuildAnchorControllers(ctx.AnchorSource, requests);
|
||||
_anchorSignature = new AnchorRequestData[requests.Count];
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
_anchorSignature[i] = requests[i];
|
||||
_anchorSignatureSource = ctx.AnchorSource;
|
||||
return _anchorControllers;
|
||||
}
|
||||
|
||||
private bool AnchorSignatureMatches(IReadOnlyList<AnchorRequestData> requests)
|
||||
{
|
||||
if (_anchorSignature.Length != requests.Count)
|
||||
return false;
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
if (!_anchorSignature[i].Equals(requests[i]))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private DrawDescription AddAnchorControllers(DrawDescription desc, AviUtlScriptContext ctx)
|
||||
{
|
||||
var controllers = ResolveAnchorControllers(ctx);
|
||||
return controllers.Count == 0 ? desc : desc with { Controllers = desc.Controllers.AddRange(controllers) };
|
||||
}
|
||||
|
||||
private ImmutableList<VideoEffectController> BuildAnchorControllers(
|
||||
IReadOnlyList<LuaAnchorPoint>? source, IReadOnlyList<AnchorRequestData> requests)
|
||||
{
|
||||
var builder = ImmutableList.CreateBuilder<VideoEffectController>();
|
||||
foreach (var request in requests)
|
||||
{
|
||||
if (request.Count <= 0)
|
||||
continue;
|
||||
|
||||
AddConnectionControllers(builder, source, request);
|
||||
|
||||
var group = request.Group;
|
||||
bool is3D = request.Is3D;
|
||||
for (int i = 0; i < request.Count; i++)
|
||||
{
|
||||
AnchorSupport.ResolvePosition(source, group, i, out double x, out double y, out double z);
|
||||
int index = i;
|
||||
var point = new ControllerPoint(
|
||||
new Vector3((float)x, (float)y, (float)(is3D ? z : 0d)),
|
||||
arg => item.ApplyAnchorDrag(group, index, arg.Delta.X, arg.Delta.Y, is3D ? arg.Delta.Z : 0d))
|
||||
{
|
||||
Shape = VideoControllerPointShape.Circle,
|
||||
};
|
||||
builder.Add(new VideoEffectController(item, [point]));
|
||||
}
|
||||
}
|
||||
return builder.ToImmutable();
|
||||
}
|
||||
|
||||
private void AddConnectionControllers(
|
||||
ImmutableList<VideoEffectController>.Builder builder, IReadOnlyList<LuaAnchorPoint>? source, in AnchorRequestData request)
|
||||
{
|
||||
switch (request.Connection)
|
||||
{
|
||||
case AnchorConnection.Line:
|
||||
for (int i = 0; i + 1 < request.Count; i++)
|
||||
AddEdge(builder, ConnectionPoint(source, request, i), ConnectionPoint(source, request, i + 1));
|
||||
break;
|
||||
case AnchorConnection.Loop:
|
||||
for (int i = 0; i + 1 < request.Count; i++)
|
||||
AddEdge(builder, ConnectionPoint(source, request, i), ConnectionPoint(source, request, i + 1));
|
||||
if (request.Count >= 2)
|
||||
AddEdge(builder, ConnectionPoint(source, request, request.Count - 1), ConnectionPoint(source, request, 0));
|
||||
break;
|
||||
case AnchorConnection.Star:
|
||||
for (int i = 0; i < request.Count; i++)
|
||||
AddEdge(builder, CenterPoint(), ConnectionPoint(source, request, i));
|
||||
break;
|
||||
case AnchorConnection.Arm:
|
||||
if (request.Count >= 1)
|
||||
AddEdge(builder, CenterPoint(), ConnectionPoint(source, request, 0));
|
||||
for (int i = 0; i + 1 < request.Count; i++)
|
||||
AddEdge(builder, ConnectionPoint(source, request, i), ConnectionPoint(source, request, i + 1));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void AddEdge(ImmutableList<VideoEffectController>.Builder builder, ControllerPoint a, ControllerPoint b) =>
|
||||
builder.Add(new VideoEffectController(item, [a, b]) { Connection = VideoControllerPointConnection.Line });
|
||||
|
||||
private static ControllerPoint CenterPoint() =>
|
||||
new(Vector3.Zero) { Shape = VideoControllerPointShape.None };
|
||||
|
||||
private static ControllerPoint ConnectionPoint(IReadOnlyList<LuaAnchorPoint>? source, in AnchorRequestData request, int index)
|
||||
{
|
||||
AnchorSupport.ResolvePosition(source, request.Group, index, out double x, out double y, out double z);
|
||||
return new ControllerPoint(new Vector3((float)x, (float)y, (float)(request.Is3D ? z : 0d)))
|
||||
{
|
||||
Shape = VideoControllerPointShape.None,
|
||||
};
|
||||
}
|
||||
|
||||
private void ApplyDrawState(AviUtlScriptContext ctx, RawRectF bounds)
|
||||
{
|
||||
if (ctx.DrawStateOverride is not { } drawn)
|
||||
return;
|
||||
|
||||
if (!drawn)
|
||||
{
|
||||
effectOutput = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (effectOutput is not null)
|
||||
return;
|
||||
|
||||
ctx.EnsurePixelBuffer();
|
||||
var buffer = ctx.GetPixelBuffer();
|
||||
if (buffer is null)
|
||||
return;
|
||||
|
||||
_pixelManager!.WritePixelsToOutput(buffer, ctx.ImageWidth, ctx.ImageHeight);
|
||||
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
|
||||
}
|
||||
|
||||
private static DrawDescription BuildOutputDesc(DrawDescription inDesc, AviUtlScriptContext ctx)
|
||||
{
|
||||
return inDesc with
|
||||
@@ -550,19 +756,31 @@ namespace LuaScript
|
||||
_gpuKernelChecked = false;
|
||||
}
|
||||
|
||||
private bool ExecuteKernelLane(string runnable, AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
|
||||
private void EnsureDirective(string runnable)
|
||||
{
|
||||
if (_directiveCached && string.Equals(runnable, _directiveSource, StringComparison.Ordinal))
|
||||
return;
|
||||
|
||||
_directiveSource = runnable;
|
||||
_directiveCached = true;
|
||||
_hasExplicitDirective = ScriptDirective.TryResolveExplicit(runnable, out _explicitDirectiveKind);
|
||||
_autoKind = ScriptDirective.ResolveAuto(runnable);
|
||||
}
|
||||
|
||||
private bool ExecuteKernelLane(AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
|
||||
{
|
||||
if (_kernelProgram is null || _cpuKernel is null)
|
||||
return false;
|
||||
|
||||
bool explicitDirective = ScriptDirective.TryResolveExplicit(runnable, out var kind);
|
||||
bool explicitDirective = _hasExplicitDirective;
|
||||
var kind = _explicitDirectiveKind;
|
||||
if (explicitDirective && kind is not (ScriptEngineKind.Gpu or ScriptEngineKind.Cpu))
|
||||
return false;
|
||||
|
||||
_kernelUniforms ??= KernelUniformBinding.Create();
|
||||
KernelUniformBinding.Fill(ctx, _kernelUniforms);
|
||||
|
||||
if (explicitDirective && kind == ScriptEngineKind.Gpu)
|
||||
if (!explicitDirective || kind == ScriptEngineKind.Gpu)
|
||||
{
|
||||
var gpu = GetGpuKernel();
|
||||
if (gpu is not null)
|
||||
@@ -570,7 +788,8 @@ namespace LuaScript
|
||||
effectOutput = gpu.Apply(input!, _kernelUniforms);
|
||||
return true;
|
||||
}
|
||||
WarnGpuUnavailableOnce();
|
||||
if (explicitDirective)
|
||||
WarnGpuUnavailableOnce();
|
||||
}
|
||||
|
||||
byte[] buffer = LoadInputPixels(bounds, imgW, imgH);
|
||||
@@ -586,16 +805,22 @@ namespace LuaScript
|
||||
return _gpuKernel;
|
||||
|
||||
_gpuKernelChecked = true;
|
||||
if (_kernelProgram is null)
|
||||
if (_kernelProgram is null || _cpuKernel is null)
|
||||
return null;
|
||||
|
||||
try
|
||||
{
|
||||
var kernel = new GpuKernel(_ownCtx!, _kernelProgram);
|
||||
if (kernel.IsReady)
|
||||
if (kernel.IsReady && kernel.Verify(_cpuKernel))
|
||||
{
|
||||
_gpuKernel = kernel;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (kernel.IsReady)
|
||||
Log.Default.Write("LuaScript: GPU kernel output diverges from the CPU kernel beyond tolerance; using the CPU kernel.");
|
||||
kernel.Dispose();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -629,20 +854,30 @@ namespace LuaScript
|
||||
{
|
||||
_nativeWorker ??= new LuaJitWorker(NativeDirectory);
|
||||
_nativeFields ??= new double[NativeProtocol.FieldCount];
|
||||
_nativeUpload ??= UploadNativeInputPixels;
|
||||
_nativeResolveObject ??= (tag, frame) => _context.ResolveObject(tag, frame, out var info) ? info : null;
|
||||
_nativeLoadFigure ??= NativeLoadFigure;
|
||||
_nativeLoadText ??= NativeLoadText;
|
||||
_nativeLoadImage ??= NativeLoadImage;
|
||||
_nativeLoadMovie ??= NativeLoadMovie;
|
||||
_nativeAddEffect ??= (name, args) => _context.AddEffect(new AviUtlEffectRequest(name, args));
|
||||
_nativeAddDraw ??= command => _context.AddDraw(command);
|
||||
_nativeSetAnchor ??= ResolveNativeAnchor;
|
||||
|
||||
NativeFieldMap.ToFields(ctx, _nativeFields);
|
||||
byte[] buffer = LoadInputPixels(bounds, imgW, imgH);
|
||||
_nativeUploaded = false;
|
||||
|
||||
bool ok = _nativeWorker.Execute(
|
||||
script, _nativeFields, ctx.StringParameters, buffer, imgW, imgH, NativeTimeoutMilliseconds,
|
||||
(tag, frame) => ctx.ResolveObject(tag, frame, out var info) ? info : null,
|
||||
NativeLoadFigure,
|
||||
NativeLoadText,
|
||||
NativeLoadImage,
|
||||
NativeLoadMovie,
|
||||
(name, args) => ctx.AddEffect(new AviUtlEffectRequest(name, args)),
|
||||
ctx.AddDraw,
|
||||
out bool dirty, out bool bufferReplaced, out byte[]? newPixels,
|
||||
script, _nativeFields, ctx.StringParameters, _nativeUpload, imgW, imgH, NativeTimeoutMilliseconds,
|
||||
_nativeResolveObject,
|
||||
_nativeLoadFigure,
|
||||
_nativeLoadText,
|
||||
_nativeLoadImage,
|
||||
_nativeLoadMovie,
|
||||
_nativeAddEffect,
|
||||
_nativeAddDraw,
|
||||
_nativeSetAnchor,
|
||||
out bool dirty, out bool bufferReplaced,
|
||||
out int resultW, out int resultH, out string? error);
|
||||
|
||||
if (!ok)
|
||||
@@ -660,31 +895,31 @@ namespace LuaScript
|
||||
{
|
||||
int outW = bufferReplaced ? resultW : imgW;
|
||||
int outH = bufferReplaced ? resultH : imgH;
|
||||
byte[] outPixels = buffer;
|
||||
|
||||
if (bufferReplaced && newPixels != null)
|
||||
{
|
||||
outPixels = newPixels;
|
||||
ctx.ReplaceBuffer(outPixels, outW, outH);
|
||||
}
|
||||
|
||||
if (hasDraws)
|
||||
{
|
||||
ctx.SetResolvedBuffer(outPixels, outW, outH);
|
||||
var result = ReadNativeResultPixels(outW, outH);
|
||||
if (bufferReplaced)
|
||||
ctx.ReplaceBuffer(result, outW, outH);
|
||||
else
|
||||
ctx.SetResolvedBuffer(result, outW, outH);
|
||||
return true;
|
||||
}
|
||||
|
||||
_pixelManager!.WritePixelsToOutput(outPixels, outW, outH);
|
||||
_nativeOutputWidth = outW;
|
||||
_nativeOutputHeight = outH;
|
||||
_nativeWorker.ReadPixels(_nativeWriteOutput ??= WriteNativeOutputPixels);
|
||||
if (bufferReplaced)
|
||||
effectOutput = _pixelManager.GetTransformOutput(-outW / 2f, -outH / 2f);
|
||||
effectOutput = _pixelManager!.GetTransformOutput(-outW / 2f, -outH / 2f);
|
||||
else
|
||||
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
|
||||
effectOutput = _pixelManager!.GetTransformOutput(bounds.Left, bounds.Top);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (hasDraws)
|
||||
{
|
||||
ctx.SetResolvedBuffer(buffer, imgW, imgH);
|
||||
if (_nativeUploaded)
|
||||
ctx.SetResolvedBuffer(ReadNativeResultPixels(imgW, imgH), imgW, imgH);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -692,6 +927,57 @@ namespace LuaScript
|
||||
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)
|
||||
{
|
||||
_context.AddAnchorRequest(new AnchorRequestData(group, count, (AnchorConnection)connection, is3D));
|
||||
|
||||
int stride = is3D ? 3 : 2;
|
||||
var source = _context.AnchorSource;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
AnchorSupport.ResolvePosition(source, group, i, out double x, out double y, out double z);
|
||||
positions[i * stride + 0] = x;
|
||||
positions[i * stride + 1] = y;
|
||||
if (is3D)
|
||||
positions[i * stride + 2] = z;
|
||||
}
|
||||
}
|
||||
|
||||
private (byte[] buffer, int w, int h) NativeLoadText(string family, string text, double size, bool bold, bool italic, int color)
|
||||
{
|
||||
_nativeTextRenderer ??= new TextRenderer();
|
||||
@@ -725,6 +1011,8 @@ namespace LuaScript
|
||||
return (buffer, fw, fh);
|
||||
}
|
||||
|
||||
private byte[] LoadPendingInputPixels() => LoadInputPixels(_pixelBounds, _pixelWidth, _pixelHeight);
|
||||
|
||||
private byte[] LoadInputPixels(RawRectF bounds, int width, int height)
|
||||
{
|
||||
_pixelLoaderSemaphore.Wait();
|
||||
@@ -747,6 +1035,7 @@ namespace LuaScript
|
||||
_nativeWorker?.Dispose();
|
||||
_effectChain?.Dispose();
|
||||
_drawCompositor?.Dispose();
|
||||
_bufferCompositor?.Dispose();
|
||||
_nativeTextRenderer?.Dispose();
|
||||
_nativeImageDecoder?.Dispose();
|
||||
_pixelLoaderSemaphore.Dispose();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using LuaScript.Anchor;
|
||||
using LuaScript.Compat;
|
||||
using MoonSharp.Interpreter;
|
||||
using MoonSharp.Interpreter.Debugging;
|
||||
@@ -587,7 +588,7 @@ namespace LuaScript
|
||||
double alpha = args.Count > 4 ? args[4].CastToNumber() ?? 1d : 1d;
|
||||
double aspect = args.Count > 5 ? args[5].CastToNumber() ?? 0d : 0d;
|
||||
|
||||
_activeContext.AddDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, CurrentAntialias()));
|
||||
_activeContext.SubmitDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, CurrentAntialias(), CurrentBlend()));
|
||||
return DynValue.Void;
|
||||
});
|
||||
|
||||
@@ -623,7 +624,7 @@ namespace LuaScript
|
||||
_ => 1d,
|
||||
};
|
||||
|
||||
_activeContext.AddDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, CurrentAntialias()));
|
||||
_activeContext.SubmitDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, CurrentAntialias(), CurrentBlend()));
|
||||
return DynValue.Void;
|
||||
});
|
||||
|
||||
@@ -648,12 +649,68 @@ namespace LuaScript
|
||||
return value.Type == DataType.Number ? value : DynValue.NewNumber(0d);
|
||||
});
|
||||
|
||||
obj["setanchor"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || _script is null || args.Count < 2 || args[0].Type != DataType.String)
|
||||
return DynValue.NewNumber(0d);
|
||||
|
||||
var anchorName = args[0].String;
|
||||
int count = AnchorSupport.ClampCount((int)(args[1].CastToNumber() ?? 0d));
|
||||
if (string.Equals(anchorName, AnchorSupport.TrackGroup, StringComparison.Ordinal))
|
||||
return DynValue.NewNumber(0d);
|
||||
|
||||
var connection = AnchorConnection.None;
|
||||
bool is3D = false;
|
||||
for (int i = 2; i < args.Count; i++)
|
||||
{
|
||||
if (args[i].Type == DataType.String)
|
||||
AnchorSupport.ApplyOption(args[i].String, ref connection, ref is3D);
|
||||
}
|
||||
|
||||
int stride = is3D ? 3 : 2;
|
||||
var table = new Table(_script);
|
||||
var source = _activeContext.AnchorSource;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
AnchorSupport.ResolvePosition(source, anchorName, i, out double x, out double y, out double z);
|
||||
table.Set(i * stride + 1, DynValue.NewNumber(x));
|
||||
table.Set(i * stride + 2, DynValue.NewNumber(y));
|
||||
if (is3D)
|
||||
table.Set(i * stride + 3, DynValue.NewNumber(z));
|
||||
}
|
||||
_script.Globals.Set(anchorName, DynValue.NewTable(table));
|
||||
|
||||
_activeContext.AddAnchorRequest(new AnchorRequestData(anchorName, count, connection, is3D));
|
||||
return DynValue.NewNumber(count);
|
||||
});
|
||||
|
||||
obj["setoption"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
_options[args[0].String] = args.Count > 1 ? args[1] : DynValue.True;
|
||||
var name = args[0].String;
|
||||
var value = args.Count > 1 ? args[1] : DynValue.True;
|
||||
_options[name] = value;
|
||||
if (name == "draw_state" && _activeContext is not null)
|
||||
_activeContext.DrawStateOverride = value.Type == DataType.Boolean
|
||||
? value.Boolean
|
||||
: (value.CastToNumber() ?? 0d) != 0d;
|
||||
if (name == "drawtarget" && _activeContext is not null)
|
||||
{
|
||||
if (value.Type == DataType.String && value.String == "tempbuffer")
|
||||
{
|
||||
bool hasSize = args.Count > 3;
|
||||
int w = hasSize ? (int)(args[2].CastToNumber() ?? 0d) : 0;
|
||||
int h = hasSize ? (int)(args[3].CastToNumber() ?? 0d) : 0;
|
||||
_activeContext.SetDrawTarget(true, w, h, hasSize);
|
||||
}
|
||||
else
|
||||
{
|
||||
_activeContext.SetDrawTarget(false, 0, 0, false);
|
||||
}
|
||||
}
|
||||
return DynValue.Void;
|
||||
});
|
||||
|
||||
@@ -680,6 +737,11 @@ namespace LuaScript
|
||||
? value.Number
|
||||
: 1d;
|
||||
|
||||
private double CurrentBlend() =>
|
||||
_options.TryGetValue("blend", out var value) && value.Type == DataType.Number
|
||||
? value.Number
|
||||
: 0d;
|
||||
|
||||
private void LoadFigure(string name, int color, double size, double line, double aspect)
|
||||
{
|
||||
int boundingSize = Math.Max(1, (int)Math.Round(size));
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using System;
|
||||
using Vortice;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
@@ -18,6 +17,7 @@ namespace LuaScript
|
||||
private ID2D1Bitmap1? _stagingBitmap;
|
||||
private ID2D1Bitmap1? _outputBitmap;
|
||||
private AffineTransform2D? _transformEffect;
|
||||
private ID2D1Image? _transformOutput;
|
||||
private byte[]? _pixelBuffer;
|
||||
private int _bitmapWidth;
|
||||
private int _bitmapHeight;
|
||||
@@ -28,38 +28,16 @@ namespace LuaScript
|
||||
_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);
|
||||
RenderToStaging(input, bounds);
|
||||
|
||||
var dc = _ctx.DeviceContext;
|
||||
var savedTarget = dc.Target;
|
||||
|
||||
dc.Target = _renderTarget;
|
||||
dc.BeginDraw();
|
||||
dc.Clear(null);
|
||||
dc.DrawImage(input, new Vector2(-bounds.Left, -bounds.Top));
|
||||
dc.EndDraw();
|
||||
dc.Target = savedTarget;
|
||||
|
||||
_stagingBitmap!.CopyFromBitmap(_renderTarget!);
|
||||
|
||||
var mapped = _stagingBitmap.Map(MapOptions.Read);
|
||||
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);
|
||||
}
|
||||
fixed (byte* destination = _pixelBuffer)
|
||||
CopyStagingRows(mapped.Bits, mapped.Pitch, destination, _pixelBuffer!.Length, width, height);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -69,6 +47,22 @@ namespace LuaScript
|
||||
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);
|
||||
@@ -76,12 +70,56 @@ namespace LuaScript
|
||||
_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;
|
||||
using var savedTarget = dc.Target;
|
||||
|
||||
dc.Target = _renderTarget;
|
||||
dc.BeginDraw();
|
||||
dc.Clear(null);
|
||||
dc.DrawImage(input, new Vector2(-bounds.Left, -bounds.Top));
|
||||
dc.EndDraw();
|
||||
dc.Target = savedTarget;
|
||||
|
||||
_stagingBitmap!.CopyFromBitmap(_renderTarget!);
|
||||
}
|
||||
|
||||
private static unsafe void CopyStagingRows(nint bits, int pitch, byte* destination, long capacity, int width, int height)
|
||||
{
|
||||
long required = (long)width * height * 4;
|
||||
if (required > capacity)
|
||||
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)
|
||||
{
|
||||
if (_transformEffect is null)
|
||||
{
|
||||
_transformEffect = new AffineTransform2D(_ctx.DeviceContext);
|
||||
_transformEffect.SetInput(0, _outputBitmap, true);
|
||||
_transformOutput = _transformEffect.Output;
|
||||
_cachedBounds = default;
|
||||
}
|
||||
|
||||
@@ -91,7 +129,7 @@ namespace LuaScript
|
||||
_cachedBounds = new RawRectF(left, top, left, top);
|
||||
}
|
||||
|
||||
return _transformEffect.Output;
|
||||
return _transformOutput!;
|
||||
}
|
||||
|
||||
private void EnsureBitmaps(int width, int height)
|
||||
@@ -101,10 +139,12 @@ namespace LuaScript
|
||||
_renderTarget?.Dispose();
|
||||
_stagingBitmap?.Dispose();
|
||||
_outputBitmap?.Dispose();
|
||||
_transformOutput?.Dispose();
|
||||
_transformEffect?.Dispose();
|
||||
_renderTarget = null;
|
||||
_stagingBitmap = null;
|
||||
_outputBitmap = null;
|
||||
_transformOutput = null;
|
||||
_transformEffect = null;
|
||||
_bitmapWidth = 0;
|
||||
_bitmapHeight = 0;
|
||||
@@ -135,10 +175,12 @@ namespace LuaScript
|
||||
_renderTarget?.Dispose();
|
||||
_stagingBitmap?.Dispose();
|
||||
_outputBitmap?.Dispose();
|
||||
_transformOutput?.Dispose();
|
||||
_transformEffect?.Dispose();
|
||||
_renderTarget = null;
|
||||
_stagingBitmap = null;
|
||||
_outputBitmap = null;
|
||||
_transformOutput = null;
|
||||
_transformEffect = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,13 +24,17 @@ namespace LuaScript
|
||||
{
|
||||
byte* pixel = p + pixelIndex * 4;
|
||||
double a = pixel[3];
|
||||
if (channel == 3)
|
||||
return a;
|
||||
if (a <= 0d)
|
||||
return 0d;
|
||||
|
||||
double scale = 255d / a;
|
||||
return channel switch
|
||||
{
|
||||
0 => a > 0d ? Math.Clamp(pixel[2] * 255d / a, 0d, 255d) : 0d,
|
||||
1 => a > 0d ? Math.Clamp(pixel[1] * 255d / a, 0d, 255d) : 0d,
|
||||
2 => a > 0d ? Math.Clamp(pixel[0] * 255d / a, 0d, 255d) : 0d,
|
||||
3 => a,
|
||||
0 => Math.Clamp(pixel[2] * scale, 0d, 255d),
|
||||
1 => Math.Clamp(pixel[1] * scale, 0d, 255d),
|
||||
2 => Math.Clamp(pixel[0] * scale, 0d, 255d),
|
||||
_ => throw new UnreachableException()
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class SoftwareCompositor : IBufferCompositor
|
||||
{
|
||||
public static readonly SoftwareCompositor Instance = new();
|
||||
|
||||
private SoftwareCompositor()
|
||||
{
|
||||
}
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
bool linear = command.Antialias != 0d;
|
||||
if (command.Poly is { } poly)
|
||||
DrawPolyInto(dst, dstW, dstH, src, srcW, srcH, poly, command.Alpha, linear);
|
||||
else
|
||||
DrawInto(dst, dstW, dstH, src, srcW, srcH, command.Ox, command.Oy, command.Zoom, command.Aspect, command.Alpha, linear);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void DrawInto(
|
||||
byte[] dst, int dstW, int dstH,
|
||||
byte[] src, int srcW, int srcH,
|
||||
double ox, double oy, double zoom, double aspect, double alpha, bool linear)
|
||||
{
|
||||
if (srcW <= 0 || srcH <= 0 || dstW <= 0 || dstH <= 0)
|
||||
return;
|
||||
|
||||
double clampedAspect = Math.Clamp(aspect, -1d, 1d);
|
||||
double zx = zoom * (1d + clampedAspect);
|
||||
double zy = zoom * (1d - clampedAspect);
|
||||
if (zx == 0d || zy == 0d)
|
||||
return;
|
||||
|
||||
double ka = Math.Clamp(alpha, 0d, 1d);
|
||||
if (ka <= 0d)
|
||||
return;
|
||||
|
||||
double halfW = srcW * 0.5;
|
||||
double halfH = srcH * 0.5;
|
||||
double spanX = Math.Abs(halfW * zx);
|
||||
double spanY = Math.Abs(halfH * zy);
|
||||
|
||||
int x0 = Math.Max(0, (int)Math.Floor(ox - spanX));
|
||||
int x1 = Math.Min(dstW - 1, (int)Math.Ceiling(ox + spanX));
|
||||
int y0 = Math.Max(0, (int)Math.Floor(oy - spanY));
|
||||
int y1 = Math.Min(dstH - 1, (int)Math.Ceiling(oy + spanY));
|
||||
|
||||
for (int py = y0; py <= y1; py++)
|
||||
{
|
||||
for (int px = x0; px <= x1; px++)
|
||||
{
|
||||
double u = (px + 0.5 - ox) / zx + halfW;
|
||||
double v = (py + 0.5 - oy) / zy + halfH;
|
||||
if (u < 0d || u >= srcW || v < 0d || v >= srcH)
|
||||
continue;
|
||||
|
||||
Sample(src, srcW, srcH, u, v, linear, out double sb, out double sg, out double sr, out double sa);
|
||||
CompositeOver(dst, (py * dstW + px) * 4, sb * ka, sg * ka, sr * ka, sa * ka);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void DrawPolyInto(
|
||||
byte[] dst, int dstW, int dstH,
|
||||
byte[] src, int srcW, int srcH,
|
||||
double[] poly, double alpha, bool linear)
|
||||
{
|
||||
if (srcW <= 0 || srcH <= 0 || dstW <= 0 || dstH <= 0)
|
||||
return;
|
||||
if (!DrawPolyMath.TrySolveAffine(poly, out var forward))
|
||||
return;
|
||||
if (!Matrix3x2.Invert(forward, out var inverse))
|
||||
return;
|
||||
|
||||
double ka = Math.Clamp(alpha, 0d, 1d);
|
||||
if (ka <= 0d)
|
||||
return;
|
||||
|
||||
DrawPolyMath.Bounds(poly, out double minX, out double minY, out double maxX, out double maxY);
|
||||
int x0 = Math.Max(0, (int)Math.Floor(minX));
|
||||
int x1 = Math.Min(dstW - 1, (int)Math.Ceiling(maxX));
|
||||
int y0 = Math.Max(0, (int)Math.Floor(minY));
|
||||
int y1 = Math.Min(dstH - 1, (int)Math.Ceiling(maxY));
|
||||
|
||||
for (int py = y0; py <= y1; py++)
|
||||
{
|
||||
for (int px = x0; px <= x1; px++)
|
||||
{
|
||||
var uv = Vector2.Transform(new Vector2(px + 0.5f, py + 0.5f), inverse);
|
||||
double u = uv.X;
|
||||
double v = uv.Y;
|
||||
if (u < 0d || u >= srcW || v < 0d || v >= srcH)
|
||||
continue;
|
||||
|
||||
Sample(src, srcW, srcH, u, v, linear, out double sb, out double sg, out double sr, out double sa);
|
||||
CompositeOver(dst, (py * dstW + px) * 4, sb * ka, sg * ka, sr * ka, sa * ka);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void Sample(byte[] src, int srcW, int srcH, double u, double v, bool linear,
|
||||
out double b, out double g, out double r, out double a)
|
||||
{
|
||||
if (!linear)
|
||||
{
|
||||
int su = Math.Clamp((int)Math.Floor(u), 0, srcW - 1);
|
||||
int sv = Math.Clamp((int)Math.Floor(v), 0, srcH - 1);
|
||||
int si = (sv * srcW + su) * 4;
|
||||
b = src[si];
|
||||
g = src[si + 1];
|
||||
r = src[si + 2];
|
||||
a = src[si + 3];
|
||||
return;
|
||||
}
|
||||
|
||||
double fx = u - 0.5;
|
||||
double fy = v - 0.5;
|
||||
int x0 = (int)Math.Floor(fx);
|
||||
int y0 = (int)Math.Floor(fy);
|
||||
double tx = fx - x0;
|
||||
double ty = fy - y0;
|
||||
|
||||
b = g = r = a = 0d;
|
||||
for (int j = 0; j < 2; j++)
|
||||
{
|
||||
int sy = Math.Clamp(y0 + j, 0, srcH - 1);
|
||||
double wy = j == 0 ? 1d - ty : ty;
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
int sx = Math.Clamp(x0 + i, 0, srcW - 1);
|
||||
double w = wy * (i == 0 ? 1d - tx : tx);
|
||||
int si = (sy * srcW + sx) * 4;
|
||||
b += src[si] * w;
|
||||
g += src[si + 1] * w;
|
||||
r += src[si + 2] * w;
|
||||
a += src[si + 3] * w;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void CompositeOver(byte[] dst, int di, double sb, double sg, double sr, double sa)
|
||||
{
|
||||
double inv = 1d - sa / 255d;
|
||||
dst[di] = (byte)Math.Clamp(sb + dst[di] * inv, 0d, 255d);
|
||||
dst[di + 1] = (byte)Math.Clamp(sg + dst[di + 1] * inv, 0d, 255d);
|
||||
dst[di + 2] = (byte)Math.Clamp(sr + dst[di + 2] * inv, 0d, 255d);
|
||||
dst[di + 3] = (byte)Math.Clamp(sa + dst[di + 3] * inv, 0d, 255d);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class SynchronizedCompositor(IBufferCompositor inner, SemaphoreSlim gate) : IBufferCompositor, IDisposable
|
||||
{
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
gate.Wait();
|
||||
try
|
||||
{
|
||||
return inner.TryCompose(dst, dstW, dstH, src, srcW, srcH, command);
|
||||
}
|
||||
finally
|
||||
{
|
||||
gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => (inner as IDisposable)?.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
يستخدم تأثير الفيديو "نص Lua" في YukkuriMovieMaker4
|
||||
لغة Lua لكتابة النصوص البرمجية.
|
||||
يعتمد محرك النصوص على MoonSharp (متوافق مع Lua 5.2).
|
||||
تُنفَّذ النصوص على بيئة التشغيل السريعة المرفقة (LuaJIT)،
|
||||
وتعمل على MoonSharp (متوافق مع Lua 5.2) عندما لا تتوفر تلك البيئة.
|
||||
|
||||
* هذا التأثير تطبيق مستقل ويختلف عن مواصفات نصوص AviUtl2.
|
||||
* يختلف في مواصفاته عن ملفات نصوص AviUtl2 (*.anm2 وما شابه).
|
||||
@@ -11,7 +12,7 @@
|
||||
|
||||
- ملاحظات -
|
||||
|
||||
○ محرك تنفيذ النصوص هو MoonSharp (متوافق مع Lua 5.2).
|
||||
○ محركا تنفيذ النصوص هما LuaJIT (الافتراضي) وMoonSharp (متوافق مع Lua 5.2).
|
||||
○ المكتبات القياسية المتاحة محدودة بما يلي:
|
||||
table, string, math, bit32
|
||||
* io, os, debug, ffi, require وغيرها غير متاحة.
|
||||
@@ -26,16 +27,16 @@
|
||||
|
||||
- محركات التنفيذ والتسريع التلقائي -
|
||||
|
||||
النصوص التي تحتوي على معالجة بكسل (حلقة getpixel/setpixel متداخلة)
|
||||
يُحلَّل تركيبها وتُوجَّه تلقائياً إلى محرك أسرع.
|
||||
أما النصوص العادية (الإحداثيات، الدوران، الشفافية، إلخ) فتظل تعمل على
|
||||
MoonSharp كما في السابق دون أي تغيير في السلوك.
|
||||
يُحلَّل تركيب النصوص وتُوجَّه تلقائياً إلى المحرك الأنسب.
|
||||
النصوص التي لا تحمل توجيهاً تُنفَّذ على بيئة التشغيل السريعة المرفقة
|
||||
(LuaJIT)، أما تخطيطات البكسل المكتفية بنفسها فتُترجَم إضافةً إلى ذلك
|
||||
إلى نواة CPU الأسرع. وفي كلتا الحالتين تطابق النتائج MoonSharp.
|
||||
|
||||
○ التوجيه التلقائي (عند عدم وجود توجيه)
|
||||
· تخطيط بكسل مكتفٍ بنفسه (انظر الشروط أدناه)
|
||||
→ نواة CPU (سريعة ودقيقة)
|
||||
· عمليات البكسل الأخرى → Native (LuaJIT، فقط عند نشره)
|
||||
· بلا عمليات بكسل → MoonSharp
|
||||
· كل ما عدا ذلك → Native (LuaJIT، فقط عند نشره)
|
||||
· عند عدم نشر native أو كون النص فارغاً → MoonSharp
|
||||
|
||||
○ توجيهات المحرك (تعليق في السطر الأول من النص)
|
||||
--!cpu : نواة CPU. تُترجَم وقت التشغيل إلى شجرة تعابير
|
||||
@@ -489,10 +490,57 @@
|
||||
الخيارات التي تؤثر على الرسم حالياً:
|
||||
"antialias" : 0 = أقرب جار، وإلا استيفاء خطّي
|
||||
(obj.draw / obj.drawpoly).
|
||||
"blend" : رقم وضع الدمج (obj.draw / obj.drawpoly). بنفس ترتيب
|
||||
القائمة المنسدلة "وضع الدمج" في لوحة الخصائص في YMM4 (يبدأ من 0):
|
||||
0=عادي,1=اكتمل الذوبان,2=أغمق,3=ضرب,4=حرق اللون,
|
||||
5=احتراق خطي,6=معالجة (أخفّ),7=شاشة,8=تراكب اللون,
|
||||
9=المزج الخطي (إضافة),10=إضافة,11=تراكب,12=ضوء ناعم,
|
||||
13=ضوء قوي,14=ضوء حيوي,15=الضوء الخطي,16=ضوء دبوس,
|
||||
17=مزج قوي,18=الفرق,19=استبعاد,20=طرح,21=القسمة,22=تدرج,
|
||||
23=التشبع,24=لون,25=السطوع,26=لون أفتح,27=خلفية,
|
||||
28=لون أغمق,29=مسح,30=القص حسب الخلفية,
|
||||
31=فقط الأجزاء غير المتراكبة,32=قناع عكس الألوان.
|
||||
القيم خارج النطاق أو غير الصالحة تُعامَل كـ 0 (عادي).
|
||||
"draw_state" : قيمة منطقية تحدد ما إذا كان هذا التأثير يُخرج صورة
|
||||
العمل. true تُخرج صورة العمل، وfalse تمرر الدخل كما هو. تُستخدم
|
||||
لإخراج صورة العمل دون obj.draw أو setpixel، أو لإيقاف الإخراج.
|
||||
تعمل في المحركين معاً.
|
||||
"drawtarget" : يبدّل وجهة رسم obj.draw / obj.drawpoly.
|
||||
"framebuffer" (الافتراضي) يركّب في مخزن الإطار. "tempbuffer"
|
||||
يركّب في مخزن العمل tmp مباشرة. في
|
||||
obj.setoption("drawtarget", "tempbuffer", w, h) تُحدد w, h حجم
|
||||
تهيئة مخزن tmp، وحذفهما يُبقيه كما هو. أعِد نتيجة tmp إلى صورة
|
||||
العمل عبر obj.copybuffer("obj", "tmp"). التركيب في tempbuffer
|
||||
عادي (source-over)، وblend يُطبَّق على الرسم في framebuffer.
|
||||
تعمل في المحركين معاً. في MoonSharp يُنفَّذ التركيب في tempbuffer
|
||||
على GPU، ويتحوّل تلقائياً إلى التركيب على CPU عندما تكون GPU
|
||||
غير متاحة. وبسبب اختلاف التقريب قد تختلف نتيجة التركيب
|
||||
اختلافاً طفيفاً جداً بين المحركين.
|
||||
|
||||
○ obj.pixeloption(name, value)
|
||||
يحفظ خياراً لعمليات البكسل كحالة.
|
||||
|
||||
○ obj.setanchor(name, count [, option, ..])
|
||||
يعرض نقاط الإرساء على المعاينة لضبط إحداثياتها بالسحب بالفأرة.
|
||||
تُحفَظ الإحداثيات المعدّلة مع المشروع.
|
||||
name : اسم متغير Lua الذي يستقبل الإحداثيات، كسلسلة نصية. يكون
|
||||
المتغير بالترتيب pos={x0,y0,x1,y1,…}، أو {x0,y0,z0,x1,y1,z1,…}
|
||||
مع "xyz". الإحداثيات بالنسبة إلى مركز الكائن.
|
||||
count : عدد نقاط الإرساء. حتى 32.
|
||||
option : تُذكَر كسلاسل نصية.
|
||||
"line" : يصل نقاط الإرساء بخطوط.
|
||||
"loop" : يصل نقاط الإرساء ويغلق الحلقة.
|
||||
"star" : يصل كل نقطة إرساء بمركز الكائن.
|
||||
"arm" : يصل مركز الكائن بكل نقطة إرساء بالترتيب.
|
||||
"xyz" : يعامل النقاط كإحداثيات ثلاثية الأبعاد. الافتراضي ثنائي.
|
||||
يعيد عدد نقاط الإرساء. يعمل في المحركين معاً.
|
||||
وضع شريط "track" غير مدعوم حالياً ويعيد 0.
|
||||
مثال:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end
|
||||
|
||||
|
||||
- ymm4 Table -
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
The "Lua Script" video effect in YukkuriMovieMaker4 uses
|
||||
the Lua language for scripting.
|
||||
The scripting engine is MoonSharp (Lua 5.2 compatible).
|
||||
Scripts run on the bundled fast runtime (LuaJIT), and fall back to
|
||||
MoonSharp (Lua 5.2 compatible) when the runtime is unavailable.
|
||||
|
||||
* This effect is a custom implementation and differs from the AviUtl2 script specification.
|
||||
* This is a separate specification from AviUtl2 script files (*.anm2, etc.).
|
||||
@@ -11,7 +12,7 @@
|
||||
|
||||
- Notes -
|
||||
|
||||
o The script execution engine is MoonSharp (Lua 5.2 compatible).
|
||||
o The script execution engines are LuaJIT (default) and MoonSharp (Lua 5.2 compatible).
|
||||
o Available standard libraries are limited to the following:
|
||||
table, string, math, bit32
|
||||
* io, os, debug, ffi, require, etc. are not available.
|
||||
@@ -26,16 +27,16 @@
|
||||
|
||||
- Execution Engines and Automatic Acceleration -
|
||||
|
||||
Scripts that contain pixel processing (a nested getpixel/setpixel loop)
|
||||
are analyzed and automatically routed to a faster engine.
|
||||
Ordinary scripts (coordinate, rotation, opacity changes, etc.) keep
|
||||
running on MoonSharp as before, with no change in behavior.
|
||||
Scripts are analyzed and automatically routed to the best engine.
|
||||
Scripts without a directive run on the bundled fast runtime (LuaJIT),
|
||||
and self-contained per-pixel maps are further compiled to the even
|
||||
faster CPU kernel. Either way the results match MoonSharp.
|
||||
|
||||
o Automatic routing (when no directive is present)
|
||||
- A self-contained per-pixel map (see conditions below)
|
||||
-> CPU kernel (fast, exact)
|
||||
- Other pixel operations -> Native (LuaJIT, only when deployed)
|
||||
- No pixel operations -> MoonSharp
|
||||
- Everything else -> Native (LuaJIT, only when deployed)
|
||||
- Native not deployed, or an empty script -> MoonSharp
|
||||
|
||||
o Engine directives (a comment on the first line of the script)
|
||||
--!cpu : CPU kernel. Compiled at runtime to an expression
|
||||
@@ -506,10 +507,61 @@
|
||||
Options that currently affect drawing:
|
||||
"antialias" : 0 = nearest neighbor, otherwise linear interpolation
|
||||
(obj.draw / obj.drawpoly).
|
||||
"blend" : blend mode number (obj.draw / obj.drawpoly). Same order
|
||||
(0-based) as YMM4's own "Blend mode" dropdown in the property
|
||||
panel: 0=Normal,1=Dissolve,2=Darker,3=Multiply,4=Color burn,
|
||||
5=Linear burn,6=Lighter,7=Screen,8=Color dodge,
|
||||
9=Linear dodge (Add),10=Add,11=Overlay,12=Soft light,
|
||||
13=Hard light,14=Vivid light,15=Linear light,16=Pin light,
|
||||
17=Hard mix,18=Difference,19=Exclution,20=Subtract,
|
||||
21=Division,22=Hue,23=Saturation,24=Color,25=Luminance,
|
||||
26=Lighter color,27=Behind,28=Darker color,29=Clear,
|
||||
30=Clipping by background,31=XOR,32=Color inversion mask.
|
||||
Out-of-range or invalid values are treated as 0 (Normal).
|
||||
"draw_state" : a boolean that decides whether this effect emits
|
||||
its working image. true outputs the working image; false passes
|
||||
the input through unchanged. Use it to emit the working image
|
||||
without obj.draw or setpixel, or to suppress the output. It works
|
||||
in both engines.
|
||||
"drawtarget" : switches the destination of obj.draw / obj.drawpoly.
|
||||
"framebuffer" (default) composites into the frame buffer.
|
||||
"tempbuffer" composites into the working tmp buffer in place. In
|
||||
obj.setoption("drawtarget", "tempbuffer", w, h) the w, h give the
|
||||
size to initialize the tmp buffer; omit them to keep it. Bring the
|
||||
tmp result back to the working image with
|
||||
obj.copybuffer("obj", "tmp"). Compositing into tempbuffer is
|
||||
normal (source-over); blend applies to framebuffer drawing. It
|
||||
works in both engines. In MoonSharp the compositing into
|
||||
tempbuffer runs on the GPU and switches to the CPU compositing
|
||||
automatically when the GPU is unavailable. Due to rounding, the
|
||||
composited result may differ very slightly between the engines.
|
||||
|
||||
o obj.pixeloption(name, value)
|
||||
Stores an option for pixel operations as state.
|
||||
|
||||
o obj.setanchor(name, count [, option, ..])
|
||||
Shows anchor points on the preview so their coordinates can be
|
||||
adjusted by mouse dragging. The adjusted coordinates are saved with
|
||||
the project.
|
||||
name : the name of the Lua variable that receives the coordinates,
|
||||
given as a string. The variable is laid out as
|
||||
pos={x0,y0,x1,y1,…}, or {x0,y0,z0,x1,y1,z1,…} with "xyz".
|
||||
Coordinates are relative to the object center.
|
||||
count : the number of anchor points. Up to 32.
|
||||
option : enumerated as strings.
|
||||
"line" : connect the anchor points with lines.
|
||||
"loop" : connect the anchor points and close the loop.
|
||||
"star" : connect each anchor point to the object center.
|
||||
"arm" : connect the object center to each anchor point in order.
|
||||
"xyz" : treat the anchor points as 3D coordinates. 2D by default.
|
||||
Returns the number of anchor points. It works in both engines.
|
||||
The "track" trackbar mode is not supported yet and returns 0.
|
||||
Example:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end
|
||||
|
||||
|
||||
- ymm4 Table -
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
El efecto de video «Script Lua» de YukkuriMovieMaker4 utiliza
|
||||
el lenguaje Lua para los scripts.
|
||||
El motor de scripts empleado es MoonSharp (compatible con Lua 5.2).
|
||||
Los scripts se ejecutan en el runtime rápido incluido (LuaJIT) y,
|
||||
cuando este no está disponible, en MoonSharp (compatible con Lua 5.2).
|
||||
|
||||
* Este efecto es una implementación propia y difiere de la especificación de scripts de AviUtl2.
|
||||
* Tiene una especificación distinta a los archivos de script de AviUtl2 (*.anm2, etc.).
|
||||
@@ -11,7 +12,7 @@
|
||||
|
||||
- Notas -
|
||||
|
||||
o El motor de ejecución de scripts es MoonSharp (compatible con Lua 5.2).
|
||||
o Los motores de ejecución son LuaJIT (predeterminado) y MoonSharp (compatible con Lua 5.2).
|
||||
o Las bibliotecas estándar disponibles se limitan a las siguientes:
|
||||
table, string, math, bit32
|
||||
* io, os, debug, ffi, require, etc. no están disponibles.
|
||||
@@ -26,17 +27,17 @@
|
||||
|
||||
- Motores de ejecución y aceleración automática -
|
||||
|
||||
Los scripts que contienen procesamiento de píxeles (un bucle anidado
|
||||
getpixel/setpixel) se analizan y se enrutan automáticamente a un motor
|
||||
más rápido. Los scripts normales (coordenadas, rotación, opacidad, etc.)
|
||||
siguen ejecutándose en MoonSharp como antes, sin cambios de comportamiento.
|
||||
Los scripts se analizan y se enrutan automáticamente al mejor motor.
|
||||
Los scripts sin directiva se ejecutan en el runtime rápido incluido
|
||||
(LuaJIT), y los mapeos por píxel autocontenidos se compilan además al
|
||||
núcleo CPU, aún más rápido. En ambos casos los resultados coinciden
|
||||
con MoonSharp.
|
||||
|
||||
o Enrutamiento automático (cuando no hay directiva)
|
||||
- Un mapeo por píxel autocontenido (ver condiciones abajo)
|
||||
-> núcleo CPU (rápido, exacto)
|
||||
- Otras operaciones de píxeles -> Nativo (LuaJIT, solo si está
|
||||
desplegado)
|
||||
- Sin operaciones de píxeles -> MoonSharp
|
||||
- Todo lo demás -> Nativo (LuaJIT, solo si está desplegado)
|
||||
- Nativo no desplegado, o script vacío -> MoonSharp
|
||||
|
||||
o Directivas de motor (un comentario en la primera línea del script)
|
||||
--!cpu : Núcleo CPU. Compilado en tiempo de ejecución a un
|
||||
@@ -505,10 +506,66 @@
|
||||
Opciones que afectan al dibujo actualmente:
|
||||
"antialias" : 0 = vecino más cercano, en otro caso interpolación
|
||||
lineal (obj.draw / obj.drawpoly).
|
||||
"blend" : número de modo de fusión (obj.draw / obj.drawpoly). El
|
||||
mismo orden (empezando en 0) que la lista desplegable "Modo de
|
||||
fusión" del panel de propiedades de YMM4:
|
||||
0=Normal,1=Síntesis de interpolación,2=Comparación (oscura),
|
||||
3=Multiplicar,4=Color de relleno,5=Burn-in (lineal),
|
||||
6=Comparación (clara),7=Pantalla,8=Color sin máscara,
|
||||
9=Sin máscara (lineal) - Aditivo,10=Adición,11=Superponer,
|
||||
12=Luz suave,13=Luz dura,14=Luz viva,15=Luz lineal,
|
||||
16=Pin Light,17=Mezcla dura,18=diferencia,19=Excluido,
|
||||
20=Sustracción,21=División,22=Tono,23=Saturación,24=Color,
|
||||
25=Luminosidad,26=Comparación de colores (claro),27=Fondo,
|
||||
28=Comparación de colores (oscuro),29=Supresión,
|
||||
30=Recorte en el fondo,31=Sólo partes no superpuestas,
|
||||
32=Máscara de inversión de color. Los valores fuera de rango
|
||||
o no válidos se tratan como 0 (Normal).
|
||||
"draw_state" : un booleano que decide si este efecto emite su
|
||||
imagen de trabajo. true emite la imagen de trabajo; false deja
|
||||
pasar la entrada sin cambios. Sirve para emitir la imagen de
|
||||
trabajo sin obj.draw ni setpixel, o para suprimir la salida.
|
||||
Funciona en ambos motores.
|
||||
"drawtarget" : cambia el destino de obj.draw / obj.drawpoly.
|
||||
"framebuffer" (por defecto) compone en el búfer de fotograma.
|
||||
"tempbuffer" compone en el búfer de trabajo tmp en el momento. En
|
||||
obj.setoption("drawtarget", "tempbuffer", w, h) los valores w, h
|
||||
dan el tamaño con que se inicializa el búfer tmp; omítelos para
|
||||
conservarlo. Recupera el resultado de tmp a la imagen de trabajo
|
||||
con obj.copybuffer("obj", "tmp"). La composición en tempbuffer es
|
||||
normal (source-over); blend se aplica al dibujo en framebuffer.
|
||||
Funciona en ambos motores. En MoonSharp la composición en
|
||||
tempbuffer se ejecuta en la GPU y cambia automáticamente a la
|
||||
composición por CPU cuando la GPU no está disponible. Por el
|
||||
redondeo, el resultado puede diferir muy ligeramente entre los
|
||||
motores.
|
||||
|
||||
o obj.pixeloption(nombre, valor)
|
||||
Guarda como estado una opción para las operaciones de píxeles.
|
||||
|
||||
o obj.setanchor(nombre, cantidad [, opción, ..])
|
||||
Muestra puntos de anclaje en la vista previa para ajustar sus
|
||||
coordenadas arrastrando con el ratón. Las coordenadas ajustadas se
|
||||
guardan con el proyecto.
|
||||
nombre : el nombre de la variable Lua que recibe las coordenadas,
|
||||
como cadena. La variable se dispone como pos={x0,y0,x1,y1,…}, o
|
||||
{x0,y0,z0,x1,y1,z1,…} con "xyz". Las coordenadas son relativas
|
||||
al centro del objeto.
|
||||
cantidad : el número de puntos de anclaje. Hasta 32.
|
||||
opción : se enumeran como cadenas.
|
||||
"line" : une los puntos de anclaje con líneas.
|
||||
"loop" : une los puntos de anclaje y cierra el bucle.
|
||||
"star" : une cada punto de anclaje con el centro del objeto.
|
||||
"arm" : une el centro del objeto con cada punto en orden.
|
||||
"xyz" : trata los puntos como coordenadas 3D. 2D por defecto.
|
||||
Devuelve el número de puntos de anclaje. Funciona en ambos motores.
|
||||
El modo de barra "track" aún no se admite y devuelve 0.
|
||||
Ejemplo:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end
|
||||
|
||||
|
||||
- ymm4 Table -
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
Efek video "Script Lua" di YukkuriMovieMaker4 menggunakan
|
||||
bahasa Lua untuk penulisan skrip.
|
||||
Mesin skrip yang digunakan adalah MoonSharp (kompatibel dengan Lua 5.2).
|
||||
Skrip dijalankan pada runtime cepat yang disertakan (LuaJIT), dan
|
||||
berjalan pada MoonSharp (kompatibel dengan Lua 5.2) jika runtime
|
||||
tersebut tidak tersedia.
|
||||
|
||||
* Efek ini adalah implementasi mandiri dan berbeda dari spesifikasi skrip AviUtl2.
|
||||
* Memiliki spesifikasi yang berbeda dari file skrip AviUtl2 (*.anm2, dll.).
|
||||
@@ -11,7 +13,7 @@
|
||||
|
||||
- Catatan -
|
||||
|
||||
o Mesin eksekusi skrip adalah MoonSharp (kompatibel dengan Lua 5.2).
|
||||
o Mesin eksekusi skrip adalah LuaJIT (bawaan) dan MoonSharp (kompatibel dengan Lua 5.2).
|
||||
o Pustaka standar yang tersedia terbatas pada berikut ini:
|
||||
table, string, math, bit32
|
||||
* io, os, debug, ffi, require, dll. tidak tersedia.
|
||||
@@ -26,16 +28,17 @@
|
||||
|
||||
- Mesin Eksekusi dan Akselerasi Otomatis -
|
||||
|
||||
Skrip yang berisi pemrosesan piksel (loop bersarang getpixel/setpixel)
|
||||
dianalisis sintaksnya dan secara otomatis dialihkan ke mesin yang lebih
|
||||
cepat. Skrip biasa (koordinat, rotasi, opasitas, dll.) tetap berjalan di
|
||||
MoonSharp seperti sebelumnya, tanpa perubahan perilaku.
|
||||
Skrip dianalisis sintaksnya dan secara otomatis dialihkan ke mesin
|
||||
yang paling sesuai. Skrip tanpa direktif dijalankan pada runtime cepat
|
||||
yang disertakan (LuaJIT), dan pemetaan per-piksel mandiri dikompilasi
|
||||
lebih lanjut ke kernel CPU yang lebih cepat lagi. Hasil keduanya sama
|
||||
dengan MoonSharp.
|
||||
|
||||
o Pengalihan otomatis (saat tidak ada direktif)
|
||||
- Pemetaan per-piksel mandiri (lihat syarat di bawah)
|
||||
-> kernel CPU (cepat, tepat)
|
||||
- Operasi piksel lainnya -> Native (LuaJIT, hanya jika di-deploy)
|
||||
- Tanpa operasi piksel -> MoonSharp
|
||||
- Selain itu -> Native (LuaJIT, hanya jika di-deploy)
|
||||
- Native tidak di-deploy, atau skrip kosong -> MoonSharp
|
||||
|
||||
o Direktif mesin (komentar pada baris pertama skrip)
|
||||
--!cpu : Kernel CPU. Dikompilasi saat runtime menjadi pohon
|
||||
@@ -501,10 +504,64 @@
|
||||
Opsi yang saat ini memengaruhi penggambaran:
|
||||
"antialias" : 0 = tetangga terdekat, selain itu interpolasi linear
|
||||
(obj.draw / obj.drawpoly).
|
||||
"blend" : nomor mode blend (obj.draw / obj.drawpoly). Urutan yang
|
||||
sama (mulai dari 0) dengan dropdown "Mode blend" pada panel
|
||||
properti YMM4:
|
||||
0=Normal,1=Larut,2=Gelap,3=Multiply,4=Bakar warna,
|
||||
5=Bakar linier,6=Terang,7=Layar,8=Peleburan warna,
|
||||
9=Peleburan linier (tambah),10=Tambah,11=Overlay,
|
||||
12=Cahaya lembut,13=Cahaya keras,14=Cahaya hidup,
|
||||
15=Cahaya linier,16=Cahaya pin,17=Campuran keras,
|
||||
18=Perbedaan,19=Ekslklusi,20=Pengurangan,21=Divisi,22=Hue,
|
||||
23=Saturasi,24=Warna,25=Pencahayaan,26=Warna terang,
|
||||
27=Belakang,28=Warna gelap,29=Bersih,
|
||||
30=Potong dengan latar belakang,
|
||||
31=Hanya bagian yang tidak tumpang tindih,32=Mask inversi warna.
|
||||
Nilai di luar jangkauan atau tidak valid dianggap 0 (Normal).
|
||||
"draw_state" : boolean yang menentukan apakah efek ini
|
||||
mengeluarkan citra kerjanya. true mengeluarkan citra kerja;
|
||||
false meneruskan input apa adanya. Berguna untuk mengeluarkan
|
||||
citra kerja tanpa obj.draw atau setpixel, atau untuk menekan
|
||||
keluaran. Bekerja pada kedua mesin.
|
||||
"drawtarget" : mengganti tujuan gambar obj.draw / obj.drawpoly.
|
||||
"framebuffer" (bawaan) mengomposit ke frame buffer. "tempbuffer"
|
||||
mengomposit ke buffer kerja tmp secara langsung. Pada
|
||||
obj.setoption("drawtarget", "tempbuffer", w, h), w, h adalah
|
||||
ukuran untuk menginisialisasi buffer tmp; hilangkan untuk
|
||||
mempertahankannya. Kembalikan hasil tmp ke citra kerja dengan
|
||||
obj.copybuffer("obj", "tmp"). Komposit ke tempbuffer bersifat
|
||||
normal (source-over); blend berlaku untuk gambar ke framebuffer.
|
||||
Bekerja pada kedua mesin. Pada MoonSharp, komposit ke tempbuffer
|
||||
dijalankan di GPU dan beralih secara otomatis ke komposit CPU
|
||||
saat GPU tidak tersedia. Karena pembulatan, hasil komposit dapat
|
||||
sedikit berbeda antara kedua mesin.
|
||||
|
||||
o obj.pixeloption(name, value)
|
||||
Menyimpan opsi untuk operasi piksel sebagai status.
|
||||
|
||||
o obj.setanchor(name, count [, option, ..])
|
||||
Menampilkan titik jangkar pada pratinjau agar koordinatnya dapat
|
||||
disesuaikan dengan menyeret mouse. Koordinat yang disesuaikan
|
||||
disimpan bersama proyek.
|
||||
name : nama variabel Lua yang menerima koordinat, sebagai string.
|
||||
Variabel disusun sebagai pos={x0,y0,x1,y1,…}, atau
|
||||
{x0,y0,z0,x1,y1,z1,…} dengan "xyz". Koordinat relatif terhadap
|
||||
pusat objek.
|
||||
count : jumlah titik jangkar. Hingga 32.
|
||||
option : dicantumkan sebagai string.
|
||||
"line" : menghubungkan titik jangkar dengan garis.
|
||||
"loop" : menghubungkan titik jangkar dan menutup lingkaran.
|
||||
"star" : menghubungkan tiap titik jangkar ke pusat objek.
|
||||
"arm" : menghubungkan pusat objek ke tiap titik secara berurutan.
|
||||
"xyz" : memperlakukan titik sebagai koordinat 3D. Bawaan 2D.
|
||||
Mengembalikan jumlah titik jangkar. Bekerja pada kedua mesin.
|
||||
Mode bilah "track" belum didukung dan mengembalikan 0.
|
||||
Contoh:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end
|
||||
|
||||
|
||||
- ymm4 Table -
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
YukkuriMovieMaker4 の「Luaスクリプト」映像エフェクトで
|
||||
利用可能なスクリプトには Lua 言語を使用します。
|
||||
スクリプトエンジンには MoonSharp (Lua 5.2 互換) が採用されています。
|
||||
スクリプトは同梱の高速ランタイム(LuaJIT)で実行され、
|
||||
利用できない環境では MoonSharp (Lua 5.2 互換) で実行されます。
|
||||
|
||||
※このエフェクトは AviUtl2 のスクリプト仕様とは異なる独自実装です。
|
||||
※AviUtl2 のスクリプトファイル(*.anm2 等)とは別仕様です。
|
||||
@@ -11,7 +12,7 @@
|
||||
|
||||
- 注意点 -
|
||||
|
||||
○スクリプトの実行エンジンは MoonSharp (Lua 5.2 互換) です。
|
||||
○スクリプトの実行エンジンは LuaJIT(標準)と MoonSharp (Lua 5.2 互換) です。
|
||||
○利用可能な標準ライブラリは以下に限定されます。
|
||||
table, string, math, bit32
|
||||
※io, os, debug, ffi, require 等は使用できません。
|
||||
@@ -26,15 +27,15 @@
|
||||
|
||||
- 実行エンジンと自動高速化 -
|
||||
|
||||
ピクセル処理(getpixel/setpixel の二重ループ)を含むスクリプトは、
|
||||
構文を解析して自動的に高速なエンジンへ振り分けられます。
|
||||
座標・回転・不透明度などの通常スクリプトは従来どおり MoonSharp で
|
||||
実行され、挙動は一切変わりません。
|
||||
スクリプトは構文を解析して自動的に最適なエンジンへ振り分けられます。
|
||||
ディレクティブ無しのスクリプトは同梱の高速ランタイム(LuaJIT)で
|
||||
実行され、自ピクセル完結のピクセル写像はさらに高速な CPU カーネルへ
|
||||
変換されます。いずれの結果も MoonSharp と一致します。
|
||||
|
||||
○自動振り分け(ディレクティブ無しのとき)
|
||||
・自ピクセル完結のピクセル写像(下記条件) → CPU カーネル(高速・厳密)
|
||||
・上記以外のピクセル操作 → ネイティブ(LuaJIT, 配備時のみ)
|
||||
・ピクセル操作なし → MoonSharp
|
||||
・上記以外 → ネイティブ(LuaJIT, 配備時のみ)
|
||||
・native 未配備または空のスクリプト → MoonSharp
|
||||
|
||||
○エンジン指定ディレクティブ(スクリプト先頭行のコメント)
|
||||
--!cpu : CPU カーネル。式ツリーへ実行時コンパイルして
|
||||
@@ -490,10 +491,61 @@
|
||||
停止させません(getoption は設定値を返し、未設定は 0)。
|
||||
現在描画へ反映される項目:
|
||||
"antialias" : 0 で最近傍、それ以外で線形補間(obj.draw/drawpoly)。
|
||||
"blend" : obj.draw / obj.drawpoly の合成モードを番号で指定します。
|
||||
YMM4 のプロパティパネルにある「合成モード」のドロップダウンと
|
||||
並び順が同じで、番号は 0 から始まります。
|
||||
0=通常,1=ディザ合成,2=比較(暗),3=乗算,4=焼き込みカラー,
|
||||
5=焼き込み(リニア),6=比較(明),7=スクリーン,8=覆い焼きカラー,
|
||||
9=覆い焼き(リニア) - 加算,10=加算,11=オーバーレイ,
|
||||
12=ソフトライト,13=ハードライト,14=ビビッドライト,15=リニアライト,
|
||||
16=ピンライト,17=ハードミックス,18=差分,19=除外,20=減算,21=除算,
|
||||
22=色相,23=彩度,24=カラー,25=輝度,26=カラー比較(明),27=背景,
|
||||
28=カラー比較(暗),29=削除,30=背景でクリッピング,
|
||||
31=重ならない部分のみ,32=色反転マスク。
|
||||
範囲外の値や数値以外を指定した場合は通常モードになります。
|
||||
"draw_state" : このエフェクトが作業画像を出力するかどうかを
|
||||
真偽値で決めます。true で作業画像を出力し、false で入力を
|
||||
そのまま通します。obj.draw や setpixel を使わずに作業画像を
|
||||
そのまま出力させたいときや、逆に出力を止めたいときに使います。
|
||||
両エンジンで動きます。
|
||||
"drawtarget" : obj.draw / obj.drawpoly の描画先を切り替えます。
|
||||
"framebuffer"(既定)ではフレームバッファへ合成します。
|
||||
"tempbuffer" では作業用の tmp バッファへその場で合成します。
|
||||
obj.setoption("drawtarget", "tempbuffer", w, h) の w, h は
|
||||
tmp バッファを初期化するサイズで、省略すると初期化しません。
|
||||
tmp へ描いた結果は obj.copybuffer("obj", "tmp") で作業画像へ
|
||||
戻せます。tempbuffer への合成は通常(ソースオーバー)で、blend は
|
||||
framebuffer への描画に適用されます。両エンジンで動きます。
|
||||
MoonSharp では tempbuffer への合成を GPU で実行し、GPU を
|
||||
利用できない環境では CPU の合成へ自動的に切り替わります。
|
||||
丸めの違いにより、合成の結果はエンジン間でごく僅かに
|
||||
異なることがあります。
|
||||
|
||||
○obj.pixeloption(名前, 値)
|
||||
ピクセル操作のオプションを状態として保持します。
|
||||
|
||||
○obj.setanchor(名前, 個数 [, オプション, ..])
|
||||
アンカーポイントをプレビュー上に表示し、マウスドラッグで座標を
|
||||
調整できるようにします。調整した座標はプロジェクトへ保存されます。
|
||||
名前 : 座標を格納する Lua 変数の名前を文字列で指定します。
|
||||
変数は pos={x0,y0,x1,y1,…} の並びで、xyz 指定時は
|
||||
{x0,y0,z0,x1,y1,z1,…} になります。座標はオブジェクトの
|
||||
中心が原点です。
|
||||
個数 : アンカーポイントの数を指定します。最大 32 個です。
|
||||
オプション : 文字列で列挙できます。
|
||||
"line" : アンカーポイントを線で結びます。
|
||||
"loop" : アンカーポイントを線で結び一周させます。
|
||||
"star" : 各アンカーポイントとオブジェクトの中心を線で結びます。
|
||||
"arm" : オブジェクトの中心から各アンカーポイントへ順に線で結びます。
|
||||
"xyz" : アンカーポイントを 3D 座標で扱います。既定は 2D です。
|
||||
戻り値は設置したアンカーポイントの数です。両エンジンで動きます。
|
||||
名前に "track" を指定するトラックバー連携は現在未対応で、0 を返します。
|
||||
例:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end
|
||||
|
||||
|
||||
- ymm4 テーブル -
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
YukkuriMovieMaker4의 「Lua 스크립트」 영상 이펙트에서
|
||||
사용 가능한 스크립트에는 Lua 언어를 사용합니다.
|
||||
스크립트 엔진으로는 MoonSharp (Lua 5.2 호환)이 채용되어 있습니다.
|
||||
스크립트는 동봉된 고속 런타임(LuaJIT)으로 실행되며,
|
||||
사용할 수 없는 환경에서는 MoonSharp (Lua 5.2 호환)으로 실행됩니다.
|
||||
|
||||
※ 이 이펙트는 AviUtl2의 스크립트 사양과는 다른 독자적인 구현입니다.
|
||||
※ AviUtl2의 스크립트 파일(*.anm2 등)과는 별도의 사양입니다.
|
||||
@@ -11,7 +12,7 @@
|
||||
|
||||
- 주의 사항 -
|
||||
|
||||
○ 스크립트 실행 엔진은 MoonSharp (Lua 5.2 호환)입니다.
|
||||
○ 스크립트 실행 엔진은 LuaJIT(표준)과 MoonSharp (Lua 5.2 호환)입니다.
|
||||
○ 사용 가능한 표준 라이브러리는 다음으로 제한됩니다.
|
||||
table, string, math, bit32
|
||||
※ io, os, debug, ffi, require 등은 사용할 수 없습니다.
|
||||
@@ -26,15 +27,15 @@
|
||||
|
||||
- 실행 엔진과 자동 가속 -
|
||||
|
||||
픽셀 처리(getpixel/setpixel 이중 루프)를 포함하는 스크립트는
|
||||
구문을 분석하여 자동으로 더 빠른 엔진으로 분배됩니다.
|
||||
좌표・회전・불투명도 등 일반 스크립트는 기존과 동일하게 MoonSharp으로
|
||||
실행되며 동작은 전혀 바뀌지 않습니다.
|
||||
스크립트는 구문을 분석하여 자동으로 가장 적합한 엔진으로 분배됩니다.
|
||||
디렉티브가 없는 스크립트는 동봉된 고속 런타임(LuaJIT)으로 실행되며,
|
||||
자기 픽셀로 완결되는 픽셀 매핑은 더욱 빠른 CPU 커널로 변환됩니다.
|
||||
어느 쪽이든 결과는 MoonSharp과 일치합니다.
|
||||
|
||||
○ 자동 분배(디렉티브가 없을 때)
|
||||
· 자기 픽셀로 완결되는 픽셀 매핑(아래 조건) → CPU 커널(고속・엄밀)
|
||||
· 위 이외의 픽셀 조작 → 네이티브(LuaJIT, 배치된 경우에만)
|
||||
· 픽셀 조작 없음 → MoonSharp
|
||||
· 위 이외 → 네이티브(LuaJIT, 배치된 경우에만)
|
||||
· native 미배치 또는 빈 스크립트 → MoonSharp
|
||||
|
||||
○ 엔진 지정 디렉티브(스크립트 첫 줄의 주석)
|
||||
--!cpu : CPU 커널. 식 트리로 런타임 컴파일하여
|
||||
@@ -484,10 +485,59 @@
|
||||
스크립트를 중단시키지 않습니다(getoption은 설정값을 반환, 미설정은 0).
|
||||
현재 그리기에 반영되는 항목:
|
||||
"antialias" : 0이면 최근접, 그 외는 선형 보간(obj.draw / obj.drawpoly).
|
||||
"blend" : 합성 모드 번호(obj.draw / obj.drawpoly). YMM4 속성
|
||||
패널의 "합성 모드" 드롭다운과 동일한 순서(0부터 시작):
|
||||
0=보통,1=디졸브,2=비교(어두움),3=곱하기,4=색상번,
|
||||
5=구워내기(선형),6=비교(밝음),7=화면,8=색상 닷지,
|
||||
9=선형 닷지 ‐ 가산,10=가산,11=오버레이,12=소프트 라이트,
|
||||
13=하드 라이트,14=선명한 라이트,15=리니어 라이트,16=핀 라이트,
|
||||
17=하드 믹스,18=차분,19=제외,20=감산,21=디비전,22=색조,
|
||||
23=채도,24=컬러,25=밝기,26=색상 비교(밝음),27=배경,
|
||||
28=색상 비교(어두운),29=삭제,30=배경에서 클리핑,
|
||||
31=겹치지 않는 부분만,32=색상 반전 마스크.
|
||||
범위를 벗어나거나 잘못된 값은 0(보통)으로 처리합니다.
|
||||
"draw_state" : 이 이펙트가 작업 이미지를 출력할지를 불리언으로
|
||||
정합니다. true는 작업 이미지를 출력하고, false는 입력을 그대로
|
||||
통과시킵니다. obj.draw나 setpixel을 쓰지 않고 작업 이미지를
|
||||
출력하거나, 반대로 출력을 막을 때 사용합니다. 두 엔진 모두에서
|
||||
동작합니다.
|
||||
"drawtarget" : obj.draw / obj.drawpoly의 그리기 대상을 바꿉니다.
|
||||
"framebuffer"(기본)는 프레임 버퍼에 합성합니다. "tempbuffer"는
|
||||
작업용 tmp 버퍼에 즉시 합성합니다.
|
||||
obj.setoption("drawtarget", "tempbuffer", w, h)의 w, h는 tmp
|
||||
버퍼를 초기화하는 크기이며, 생략하면 초기화하지 않습니다. tmp에
|
||||
그린 결과는 obj.copybuffer("obj", "tmp")로 작업 이미지에 되돌릴
|
||||
수 있습니다. tempbuffer로의 합성은 보통(소스 오버)이며, blend는
|
||||
framebuffer 그리기에 적용됩니다. 두 엔진 모두에서 동작합니다.
|
||||
MoonSharp에서는 tempbuffer로의 합성을 GPU에서 실행하며, GPU를
|
||||
사용할 수 없는 환경에서는 CPU 합성으로 자동 전환됩니다. 반올림
|
||||
차이로 인해 합성 결과가 엔진 간에 아주 조금 다를 수 있습니다.
|
||||
|
||||
○ obj.pixeloption(이름, 값)
|
||||
픽셀 조작 옵션을 상태로 보존합니다.
|
||||
|
||||
○ obj.setanchor(이름, 개수 [, 옵션, ..])
|
||||
프리뷰에 앵커 포인트를 표시하고 마우스 드래그로 좌표를 조정할 수
|
||||
있게 합니다. 조정한 좌표는 프로젝트에 저장됩니다.
|
||||
이름 : 좌표를 받을 Lua 변수 이름을 문자열로 지정합니다. 변수는
|
||||
pos={x0,y0,x1,y1,…} 배열이며, "xyz" 지정 시
|
||||
{x0,y0,z0,x1,y1,z1,…}가 됩니다. 좌표는 오브젝트 중심이
|
||||
원점입니다.
|
||||
개수 : 앵커 포인트 수를 지정합니다. 최대 32개입니다.
|
||||
옵션 : 문자열로 열거할 수 있습니다.
|
||||
"line" : 앵커 포인트를 선으로 잇습니다.
|
||||
"loop" : 앵커 포인트를 선으로 잇고 한 바퀴 닫습니다.
|
||||
"star" : 각 앵커 포인트를 오브젝트 중심과 선으로 잇습니다.
|
||||
"arm" : 오브젝트 중심에서 각 앵커 포인트로 차례로 잇습니다.
|
||||
"xyz" : 앵커 포인트를 3D 좌표로 다룹니다. 기본은 2D입니다.
|
||||
설치한 앵커 포인트 수를 반환합니다. 두 엔진 모두에서 동작합니다.
|
||||
이름에 "track"을 지정하는 트랙바 연동은 현재 미지원이며 0을 반환합니다.
|
||||
예:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end
|
||||
|
||||
|
||||
- ymm4 테이블 -
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
YukkuriMovieMaker4 的"Lua 脚本"视频特效使用
|
||||
Lua 语言编写脚本。
|
||||
脚本引擎采用 MoonSharp(兼容 Lua 5.2)。
|
||||
脚本由随附的高速运行时(LuaJIT)执行,
|
||||
在其不可用的环境下改由 MoonSharp(兼容 Lua 5.2)执行。
|
||||
|
||||
* 本特效为独立实现,与 AviUtl2 的脚本规范不同。
|
||||
* 与 AviUtl2 的脚本文件(*.anm2 等)为不同规范。
|
||||
@@ -11,7 +12,7 @@
|
||||
|
||||
- 注意事项 -
|
||||
|
||||
○ 脚本执行引擎为 MoonSharp(兼容 Lua 5.2)。
|
||||
○ 脚本执行引擎为 LuaJIT(默认)与 MoonSharp(兼容 Lua 5.2)。
|
||||
○ 可用的标准库仅限以下内容:
|
||||
table, string, math, bit32
|
||||
* io、os、debug、ffi、require 等不可使用。
|
||||
@@ -26,14 +27,15 @@
|
||||
|
||||
- 执行引擎与自动加速 -
|
||||
|
||||
包含像素处理(getpixel/setpixel 双重循环)的脚本会被解析语法,
|
||||
并自动分配到更快的引擎。
|
||||
坐标、旋转、不透明度等普通脚本仍照旧由 MoonSharp 执行,行为不变。
|
||||
脚本会被解析语法,并自动分配到最合适的引擎。
|
||||
未指定指令的脚本由随附的高速运行时(LuaJIT)执行,
|
||||
自像素完结的像素映射会进一步转换为更快的 CPU 内核。
|
||||
两者的结果均与 MoonSharp 一致。
|
||||
|
||||
○ 自动分配(未指定指令时)
|
||||
· 自像素完结的像素映射(见下方条件)→ CPU 内核(高速、精确)
|
||||
· 上述以外的像素操作 → 原生(LuaJIT,仅在已部署时)
|
||||
· 无像素操作 → MoonSharp
|
||||
· 上述以外 → 原生(LuaJIT,仅在已部署时)
|
||||
· 未部署 native 或脚本为空 → MoonSharp
|
||||
|
||||
○ 引擎指定指令(脚本首行的注释)
|
||||
--!cpu :CPU 内核。运行时编译为表达式树,
|
||||
@@ -477,10 +479,51 @@
|
||||
(getoption 返回设置值,未设置为 0)。
|
||||
当前会反映到绘制的项目:
|
||||
"antialias" : 0 为最近邻,其它为线性插值(obj.draw / obj.drawpoly)。
|
||||
"blend" : 合成模式编号(obj.draw / obj.drawpoly)。与 YMM4 属性
|
||||
面板中「合成模式」下拉列表相同的顺序(从 0 开始):
|
||||
0=普通,1=溶解,2=对比(暗),3=相乘,4=颜色加深,5=线性加深,
|
||||
6=对比(明),7=画面,8=颜色减淡,9=线性减淡 (相加),10=相加,
|
||||
11=覆盖,12=柔光,13=强光,14=亮光,15=明暗,16=点光,17=实色混合,
|
||||
18=反差,19=排除,20=相减,21=相除,22=色相,23=饱和度,24=颜色,
|
||||
25=亮度,26=颜色对比(明),27=背景,28=颜色对比(暗),29=清除,
|
||||
30=按背景裁剪,31=异或,32=颜色反转遮罩。超出范围或无效的值
|
||||
将按 0(普通)处理。
|
||||
"draw_state" : 用布尔值决定该效果是否输出工作图像。true 输出
|
||||
工作图像,false 则原样传递输入。可用于不使用 obj.draw 或
|
||||
setpixel 也输出工作图像,或反过来抑制输出。两个引擎都可用。
|
||||
"drawtarget" : 切换 obj.draw / obj.drawpoly 的绘制目标。
|
||||
"framebuffer"(默认)合成到帧缓冲。"tempbuffer" 则就地合成到
|
||||
工作用 tmp 缓冲。obj.setoption("drawtarget", "tempbuffer", w, h)
|
||||
中的 w, h 是初始化 tmp 缓冲的尺寸,省略则不初始化。画到 tmp 的
|
||||
结果可用 obj.copybuffer("obj", "tmp") 取回工作图像。合成到
|
||||
tempbuffer 使用普通(源覆盖),blend 应用于 framebuffer 的绘制。
|
||||
两个引擎都可用。在 MoonSharp 中,合成到 tempbuffer 在 GPU 上
|
||||
执行,GPU 不可用时会自动切换到 CPU 合成。由于舍入方式不同,
|
||||
合成结果在引擎之间可能存在极小差异。
|
||||
|
||||
○ obj.pixeloption(名称, 值)
|
||||
将像素操作的选项作为状态保存。
|
||||
|
||||
○ obj.setanchor(名称, 个数 [, 选项, ..])
|
||||
在预览上显示锚点,可用鼠标拖动调整坐标。调整后的坐标会随工程保存。
|
||||
名称 : 以字符串指定接收坐标的 Lua 变量名。变量排列为
|
||||
pos={x0,y0,x1,y1,…},指定 "xyz" 时为 {x0,y0,z0,x1,y1,z1,…}。
|
||||
坐标以对象中心为原点。
|
||||
个数 : 指定锚点数量。最多 32 个。
|
||||
选项 : 可用字符串列举。
|
||||
"line" : 用线连接锚点。
|
||||
"loop" : 用线连接锚点并闭合一圈。
|
||||
"star" : 将每个锚点与对象中心用线连接。
|
||||
"arm" : 从对象中心依次连接到各锚点。
|
||||
"xyz" : 以 3D 坐标处理锚点。默认是 2D。
|
||||
返回设置的锚点数量。两个引擎都可用。
|
||||
名称指定 "track" 的轨道条联动暂不支持,返回 0。
|
||||
示例:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end
|
||||
|
||||
|
||||
- ymm4 表 -
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
YukkuriMovieMaker4 的「Lua 腳本」視訊特效使用
|
||||
Lua 語言編寫腳本。
|
||||
腳本引擎採用 MoonSharp(相容 Lua 5.2)。
|
||||
腳本由隨附的高速執行環境(LuaJIT)執行,
|
||||
在其不可用的環境下改由 MoonSharp(相容 Lua 5.2)執行。
|
||||
|
||||
* 本特效為獨立實作,與 AviUtl2 的腳本規範不同。
|
||||
* 與 AviUtl2 的腳本檔案(*.anm2 等)為不同規範。
|
||||
@@ -11,7 +12,7 @@
|
||||
|
||||
- 注意事項 -
|
||||
|
||||
○ 腳本執行引擎為 MoonSharp(相容 Lua 5.2)。
|
||||
○ 腳本執行引擎為 LuaJIT(預設)與 MoonSharp(相容 Lua 5.2)。
|
||||
○ 可用的標準函式庫僅限以下內容:
|
||||
table, string, math, bit32
|
||||
* io、os、debug、ffi、require 等不可使用。
|
||||
@@ -26,14 +27,15 @@
|
||||
|
||||
- 執行引擎與自動加速 -
|
||||
|
||||
包含像素處理(getpixel/setpixel 雙重迴圈)的腳本會被解析語法,
|
||||
並自動分配到更快的引擎。
|
||||
座標、旋轉、不透明度等一般腳本仍照舊由 MoonSharp 執行,行為不變。
|
||||
腳本會被解析語法,並自動分配到最合適的引擎。
|
||||
未指定指令的腳本由隨附的高速執行環境(LuaJIT)執行,
|
||||
自像素完結的像素映射會進一步轉換為更快的 CPU 核心。
|
||||
兩者的結果均與 MoonSharp 一致。
|
||||
|
||||
○ 自動分配(未指定指令時)
|
||||
· 自像素完結的像素映射(見下方條件)→ CPU 核心(高速、精確)
|
||||
· 上述以外的像素操作 → 原生(LuaJIT,僅在已部署時)
|
||||
· 無像素操作 → MoonSharp
|
||||
· 上述以外 → 原生(LuaJIT,僅在已部署時)
|
||||
· 未部署 native 或腳本為空 → MoonSharp
|
||||
|
||||
○ 引擎指定指令(腳本首行的註解)
|
||||
--!cpu :CPU 核心。執行時編譯為運算式樹,
|
||||
@@ -477,10 +479,52 @@
|
||||
(getoption 回傳設定值,未設定為 0)。
|
||||
目前會反映到繪製的項目:
|
||||
"antialias" : 0 為最近鄰,其它為線性內插(obj.draw / obj.drawpoly)。
|
||||
"blend" : 合成模式編號(obj.draw / obj.drawpoly)。與 YMM4 屬性
|
||||
面板中「合成模式」下拉選單相同的順序(從 0 開始):
|
||||
0=一般,1=Dissolve,2=比較(暗),3=相乘,4=Color burn,5=陰影,
|
||||
6=比較(亮),7=畫面,8=Color dodge,9=Linear dodge (Add),
|
||||
10=相加,11=覆蓋,12=Soft light,13=Hard light,14=Vivid light,
|
||||
15=明暗,16=Pin light,17=Hard mix,18=差異,19=Exclution,
|
||||
20=相減,21=Division,22=Hue,23=Saturation,24=色,25=亮度,
|
||||
26=Lighter color,27=Behind,28=Darker color,29=Clear,
|
||||
30=Clipping by background,31=XOR,32=Color inversion mask。
|
||||
超出範圍或無效的值將視為 0(一般)。
|
||||
"draw_state" : 以布林值決定此效果是否輸出工作影像。true 輸出
|
||||
工作影像,false 則原樣傳遞輸入。可用於不使用 obj.draw 或
|
||||
setpixel 也輸出工作影像,或反過來抑制輸出。兩個引擎都可用。
|
||||
"drawtarget" : 切換 obj.draw / obj.drawpoly 的繪製目標。
|
||||
"framebuffer"(預設)合成到影格緩衝。"tempbuffer" 則就地合成到
|
||||
工作用 tmp 緩衝。obj.setoption("drawtarget", "tempbuffer", w, h)
|
||||
中的 w, h 是初始化 tmp 緩衝的尺寸,省略則不初始化。畫到 tmp 的
|
||||
結果可用 obj.copybuffer("obj", "tmp") 取回工作影像。合成到
|
||||
tempbuffer 使用一般(來源覆蓋),blend 套用於 framebuffer 的繪製。
|
||||
兩個引擎都可用。在 MoonSharp 中,合成到 tempbuffer 在 GPU 上
|
||||
執行,GPU 無法使用時會自動切換到 CPU 合成。由於捨入方式不同,
|
||||
合成結果在引擎之間可能存在極小差異。
|
||||
|
||||
○ obj.pixeloption(名稱, 值)
|
||||
將像素操作的選項作為狀態保存。
|
||||
|
||||
○ obj.setanchor(名稱, 個數 [, 選項, ..])
|
||||
在預覽上顯示錨點,可用滑鼠拖曳調整座標。調整後的座標會隨專案保存。
|
||||
名稱 : 以字串指定接收座標的 Lua 變數名。變數排列為
|
||||
pos={x0,y0,x1,y1,…},指定 "xyz" 時為 {x0,y0,z0,x1,y1,z1,…}。
|
||||
座標以物件中心為原點。
|
||||
個數 : 指定錨點數量。最多 32 個。
|
||||
選項 : 可用字串列舉。
|
||||
"line" : 用線連接錨點。
|
||||
"loop" : 用線連接錨點並閉合一圈。
|
||||
"star" : 將每個錨點與物件中心用線連接。
|
||||
"arm" : 從物件中心依序連接到各錨點。
|
||||
"xyz" : 以 3D 座標處理錨點。預設是 2D。
|
||||
回傳設置的錨點數量。兩個引擎都可用。
|
||||
名稱指定 "track" 的軌道條連動暫不支援,回傳 0。
|
||||
範例:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end
|
||||
|
||||
|
||||
- ymm4 表 -
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
---
|
||||
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブジェクトの座標・拡縮・回転・不透明度・ピクセルを直接制御できる映像エフェクトプラグイン**です。
|
||||
スクリプトエンジンには MoonSharp(Lua 5.2 互換)が採用されており、`obj.x` や `obj.alpha` といった変数をスクリプトから書き換えることで、AviUtl のスクリプト制御に近い感覚でアニメーションを組み立てられます。
|
||||
スクリプトは同梱の高速ランタイム(LuaJIT)で実行され、`obj.x` や `obj.alpha` といった変数をスクリプトから書き換えることで、AviUtl のスクリプト制御に近い感覚でアニメーションを組み立てられます。高速ランタイムを利用できない環境では MoonSharp(Lua 5.2 互換)で実行されます。
|
||||
|
||||
座標・拡縮・回転・不透明度の制御に加えて、`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` によるピクセル単位の画像加工、アニメーション制作向けの数学ユーティリティ群(`anim` テーブル)、4 系統のトラックバー(Track0〜Track3)によるスクリプトへのパラメータ受け渡しに対応しています。
|
||||
|
||||
@@ -46,7 +46,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
|
||||
本プラグインは YMM4 の「映像エフェクト」として動作し、エフェクトの種類一覧では「Luaスクリプト」として表示されます。
|
||||
|
||||
内部的には MoonSharp(Lua 5.2 互換のスクリプトエンジン)を組み込んでおり、ユーザーが記述した Lua スクリプトをフレームごとに実行します。スクリプト内で `obj.x` や `obj.alpha` といったグローバル変数を書き換えると、その値がオブジェクトの座標・拡縮・回転・不透明度として描画に反映されます。
|
||||
内部的には高速ランタイム(LuaJIT)と MoonSharp(Lua 5.2 互換のスクリプトエンジン)を組み込んでおり、ユーザーが記述した Lua スクリプトをフレームごとに実行します。スクリプト内で `obj.x` や `obj.alpha` といったグローバル変数を書き換えると、その値がオブジェクトの座標・拡縮・回転・不透明度として描画に反映されます。
|
||||
|
||||
このエフェクトは独自のスクリプト実行系を基盤としつつ、AviUtl のアニメーション効果スクリプト(`.anm` 系)の一部に対する互換層を備えています(詳細は[AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。AviUtl 向けの EXO 出力(`.exo`)には対応していません。
|
||||
|
||||
@@ -60,7 +60,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
| YukkuriMovieMaker4 | 最新版を推奨 |
|
||||
| ランタイム | .NET 10.0 |
|
||||
|
||||
※ スクリプトエンジン(MoonSharp)はプラグインに同梱されており、別途インストールする必要はありません。
|
||||
※ スクリプトエンジン(LuaJIT・MoonSharp)はプラグインに同梱されており、別途インストールする必要はありません。
|
||||
|
||||
---
|
||||
|
||||
@@ -76,7 +76,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
|
||||
### 1. スクリプトエンジン
|
||||
|
||||
スクリプトの実行エンジンには MoonSharp(Lua 5.2 互換)を使用しています。加えて、自ピクセル完結のピクセル写像(`obj.getpixel` で読み取り `obj.setpixel` で書き戻す二重ループ)は構文解析で検出して **CPU カーネル(式ツリー)** または **GPU カーネル(Direct2D ピクセルシェーダ)** へ実行時コンパイルして高速化し、それ以外のピクセル操作を含むスクリプトは同梱の高速ランタイム(**LuaJIT**)で自動実行されます(詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照)。いずれのエンジンでも利用可能な標準ライブラリは以下に限定されています。
|
||||
スクリプトの実行エンジンには、同梱の高速ランタイム(**LuaJIT**)と MoonSharp(Lua 5.2 互換)を使用しています。ディレクティブを書いていないスクリプトは LuaJIT で実行され、自ピクセル完結のピクセル写像(`obj.getpixel` で読み取り `obj.setpixel` で書き戻す二重ループ)は構文解析で検出して **CPU カーネル(式ツリー)** へ実行時コンパイルしてさらに高速化されます。`native` フォルダが配備されていない環境と空のスクリプトは MoonSharp で実行されます(詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照)。いずれのエンジンでも利用可能な標準ライブラリは以下に限定されています。
|
||||
|
||||
- `table`、`string`、`math`、`bit32`
|
||||
- 基本関数: `type`、`tostring`、`tonumber`、`select`、`error`、`assert`、`print`、`ipairs`、`pairs`、`next`、`unpack`、`setmetatable`、`getmetatable`、`rawget`、`rawset`、`rawequal`、`rawlen`、`pcall`、`xpcall`
|
||||
@@ -113,7 +113,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
- **`obj.putpixeldata()`**: 互換性のために定義された空実装関数です。`setpixel` / `PixelDataProxy:set` による変更は自動的に反映されるため、呼び出す必要はありません。
|
||||
`getpixel` / `setpixel` / `getpixeldata` のいずれかを最初に呼び出した時点で、GPU 上の画像データを CPU 側へ転送する処理が一度だけ発生します。ピクセル操作を行わないスクリプトではこの転送は発生しません。
|
||||
|
||||
これらのピクセル操作を含むスクリプトは自動的に高速化されます。自ピクセル完結のピクセル写像は CPU カーネル(式ツリー)または GPU カーネル(Direct2D ピクセルシェーダ)へ、それ以外は高速ランタイム(LuaJIT)へ自動で振り分けられ、いずれも従来エンジンに比べて大幅(内部計測で数十倍)に高速化されます。CPU カーネルと LuaJIT の出力結果は従来エンジンと一致します(GPU カーネルのみ float32 精度のためごく僅かに異なり得ます)。詳細・制約は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照してください。
|
||||
これらのピクセル操作を含むスクリプトは自動的に高速化されます。自ピクセル完結のピクセル写像は CPU カーネル(式ツリー)へ、それ以外は高速ランタイム(LuaJIT)へ自動で振り分けられ、いずれも MoonSharp に比べて大幅(内部計測で数十倍)に高速化されます。CPU カーネルと LuaJIT の出力結果は MoonSharp と一致します(明示指定のみで使われる GPU カーネルは float32 精度のためごく僅かに異なり得ます)。詳細・制約は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照してください。
|
||||
|
||||
### 4. scene テーブルと ymm4 テーブル
|
||||
|
||||
@@ -213,12 +213,13 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
||||
- **`@` による複数セクション**: 1 つのスクリプトに `@名前` で複数の効果が定義されている場合、先頭のセクションのみを実行します。
|
||||
- **`obj.rand(st, ed [, seed [, frame]])`**: 指定範囲(`st`〜`ed`)の整数を返す決定論的な乱数です。`seed` と `frame` が同じであれば常に同じ値を返し、`frame` を省略すると現在のフレームを用います。従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)で同じ値を返します。
|
||||
- **`obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])`**: 円・四角形・三角形・五角形・六角形・星形を生成し、オブジェクトのバッファを置き換えて描画します(出力は図形サイズに合わせて生成され、中心に配置されます)。`ライン` を省略するか `0` で塗りつぶし、サイズ以上の値でも塗りつぶしになります。`アスペクト`(-1.0〜1.0)で幅・高さを歪曲できます。
|
||||
- **描画・メディア・バッファ・オプション API**: `obj.draw` / `obj.drawpoly` による描画合成、`obj.load` の `"text"` / `"image"` / `"movie"`、`obj.setfont`、`obj.copybuffer`、`obj.effect`、`obj.getvalue`、`obj.setoption` / `obj.getoption` / `obj.pixeloption` に対応しています。これらは従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。
|
||||
- **描画・メディア・バッファ・オプション API**: `obj.draw` / `obj.drawpoly` による描画合成、`obj.load` の `"text"` / `"image"` / `"movie"`、`obj.setfont`、`obj.copybuffer`、`obj.effect`、`obj.getvalue`、`obj.setoption` / `obj.getoption` / `obj.pixeloption` に対応しています。これらは従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。`obj.setoption` では `antialias` に加えて、`obj.draw` / `obj.drawpoly` の合成モードを YMM4 の並びで指定する `blend`、描画先を `"framebuffer"` / `"tempbuffer"` で切り替える `drawtarget`、作業画像の出力可否を切り替える `draw_state` に対応します。MoonSharp では `tempbuffer` への合成を GPU で実行し、GPU を利用できない環境では CPU の合成へ自動的に切り替わります。丸めの違いにより、合成の結果はエンジン間でごく僅かに異なることがあります。
|
||||
- **`obj.setanchor(name, count [, option, ...])`**: プレビュー上にドラッグ可能なアンカーポイントを表示し、その座標を `name` の Lua 変数(`pos={x0,y0,x1,y1,…}`、`"xyz"` 指定時は `{x0,y0,z0,…}`)へ格納します。座標はオブジェクトの中心が原点で、ドラッグで調整した値はプロジェクトへ保存されます。最大 32 個で、`"line"` / `"loop"` / `"star"` / `"arm"` の線結びと `"xyz"` の 3D 指定に対応します。設置数を返し、従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。`name` に `"track"` を指定するトラックバー連携は未対応です。
|
||||
- **`obj.effect` の AviUtl/AviUtl2 互換マップ**: `obj.effect("エフェクト名", "パラメータ名", 値, …)` はまず互換マップを参照し、AviUtl/AviUtl2 の名前として宣言したエフェクトを、対応する YMM4 の映像エフェクトとプロパティへ変換して適用します。値の倍率とオフセットの変換まで宣言できます。互換マップに宣言が無い名前は、従来どおり YMM4 のエフェクト名・キーワードでそのまま解決するため、既存の呼び出しはそのまま動きます。この互換マップは YMM4 自身が AviUtl の `.exo` へ書き出す変換を逆向きにたどって構築しているため、往復しても結果が一致します。対象のエンジンは指定子 `--!aviutl` または `--!aviutl2` で切り替え、指定子を書かないときは `--!aviutl` として扱います。互換マップが対応するエフェクト名の一覧はドキュメントの「obj の関数」を参照してください。
|
||||
|
||||
次のような機能は、この互換層では対象外です(呼び出しを含むスクリプトは意図どおりには動作しません)。
|
||||
|
||||
- `obj.setanchor`、`scene.set` / `scene.get` などの未実装関数
|
||||
- `scene.set` / `scene.get` などの未実装関数
|
||||
- `require` によるモジュール読み込み、`io` / `dofile` などの任意ファイルアクセス(`obj.load("image"/"movie")` のみ、先頭ヘッダー検証付きで対応)
|
||||
|
||||
---
|
||||
@@ -230,8 +231,8 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
||||
スクリプトは内容に応じて 4 つのエンジンへ自動的に振り分けられます。
|
||||
|
||||
- **自ピクセル完結のピクセル写像**(`for y … for x … obj.getpixel … obj.setpixel … end end` の形)→ **CPU カーネル(式ツリー)** へ実行時コンパイルして実行。
|
||||
- **上記以外のピクセル操作を含むスクリプト**(`obj.getpixeldata` や近傍参照・別座標書き込みなど)→ 同梱の高速ランタイム **LuaJIT** で実行(ネイティブ実行)。
|
||||
- **変形のみのスクリプト** → 従来の **MoonSharp** で実行。
|
||||
- **上記以外のスクリプト** → 同梱の高速ランタイム **LuaJIT** で実行(ネイティブ実行)。
|
||||
- **`native` フォルダが配備されていない環境と空のスクリプト** → **MoonSharp** で実行。
|
||||
|
||||
スクリプトの先頭行に次のディレクティブを書くと、エンジンを明示指定できます。
|
||||
|
||||
@@ -244,7 +245,7 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
||||
|
||||
CPU / GPU カーネルが成立するのは、四則演算・`math.*`・比較・しきい値の「条件 and 値1 or 値2」・`local` 変数のみを使い、処理中の自ピクセル(`obj.getpixel(x, y)`)と `obj` / `scene` / `time` 等の値だけを参照する純粋な写像(色変換・グレースケール・ガンマ・しきい値・チャンネル混合など)の場合です。近傍参照(ぼかし等)・別座標への書き込み・`getpixeldata`・`getobject`・テーブル/文字列操作・`if` 文などを含む場合はカーネル化されず、自動的に LuaJIT または MoonSharp で実行されます。コンパイル済みのカーネルはスクリプト本文をキーにキャッシュされ、初回フレームのみコンパイルコストを払います。
|
||||
|
||||
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で受け渡されます。スクリプトが無限ループに陥った場合でも **5 秒のタイムアウトでプロセスを強制終了**するため本体は固まらず、終了後は自動的に復帰します。出力結果は従来エンジンと一致します。
|
||||
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で受け渡されます。ピクセルの転送はスクリプトがピクセルへ初めてアクセスした時点でのみ行われるため、変形や描画だけのスクリプトでは転送が発生しません。ワーカープロセスは入力画像のサイズが変わっても再起動せず、フレームをまたいで再利用されます。スクリプトが無限ループに陥った場合でも **5 秒のタイムアウトでプロセスを強制終了**するため本体は固まらず、終了後は自動的に復帰します。出力結果は MoonSharp と一致します。
|
||||
|
||||
`obj.getobject` はネイティブ実行でも利用できます。呼び出し時に本体プロセスへ同期的に問い合わせてシーンオブジェクトを解決するため、従来エンジンと同じ結果を返します。同じタグ・同じフレームへの連続した問い合わせはフレーム内でキャッシュされ、2 回目以降は往復を行いません。
|
||||
|
||||
@@ -271,7 +272,7 @@ CPU / GPU カーネルが成立するのは、四則演算・`math.*`・比較
|
||||
|
||||
### グローバル変数のリセットと整合性チェック
|
||||
|
||||
内部の Lua 実行環境(Script / Table インスタンス)は性能のためフレームをまたいで再利用されますが、スクリプトが定義したユーザー定義のグローバル変数や、`obj` / `scene` / `anim` / `ymm4` テーブルへスクリプトが追加したキーは、各フレームの実行開始時に初期状態のスナップショットと比較して取り除かれます。これにより、あるフレームでスクリプトが作成した状態が次のフレームへ意図せず持ち越されることを防いでいます。
|
||||
内部の Lua 実行環境は性能のためフレームをまたいで再利用されますが、スクリプトが定義したユーザー定義のグローバル変数や、`obj` / `scene` / `anim` / `ymm4` テーブルへスクリプトが追加したキーは、各フレームの実行開始時に初期状態のスナップショットと比較して取り除かれます。これにより、あるフレームでスクリプトが作成した状態が次のフレームへ意図せず持ち越されることを防いでいます。このリセットは LuaJIT と MoonSharp のどちらのエンジンでも同じように行われます。
|
||||
|
||||
また、実行のたびに組み込みの `math` グローバルがテーブル型のまま残っているかを確認し、スクリプトの誤操作などで破壊されていた場合は Lua 実行環境ごと再構築します。
|
||||
|
||||
@@ -373,7 +374,7 @@ obj.alpha = anim.ease_out(t) * 255
|
||||
- **AviUtl 互換は部分的**: AviUtl のアニメーション効果スクリプトのうち、変形・不透明度・乱数の範囲のみ実行できます([AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。描画・フィルタ・ファイルアクセス系の関数、および AviUtl 向けの EXO 出力(`.exo`)には対応していません。
|
||||
- **実行タイムアウト**: スクリプトの実行は 5000ms(5秒)でタイムアウトし、超過した場合は強制終了されエラーとして扱われます。無限ループが発生しないよう注意してください。
|
||||
- **利用可能な標準ライブラリの制限**: `table`、`string`、`math`、`bit32` および基本関数のみ利用できます。`io`、`os`、`debug`、`ffi`、`require` は利用できません。
|
||||
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します(GPU カーネルはこの転送を行いません)。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは内容に応じて CPU カーネル・GPU カーネル・高速ランタイム(LuaJIT)のいずれかで自動実行され大幅に高速化されます。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
|
||||
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します(GPU カーネルはこの転送を行いません)。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは内容に応じて CPU カーネルまたは高速ランタイム(LuaJIT)で自動実行され大幅に高速化されます。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
|
||||
- **`math.random` はフレームごとの決定論的な乱数**: 毎フレーム `frame` の値でシードし直されるため、同一フレームでは常に同じ値になります。フレームをまたいで変化する乱数的な値が必要な場合は `anim.rand` の利用を検討してください。
|
||||
- **`obj.oz` は出力に反映されません**: スクリプト実行後にコンテキストへ読み戻されますが、現在の実装では中心点オフセットの出力計算に使用されていません。
|
||||
- **エクスポートは先頭の1件のみ**: 複数アイテムを選択した状態でも、エクスポートされるスクリプトは先頭のアイテムのもののみです(インポート・クリアは選択中のすべてのアイテムに適用されます)。
|
||||
@@ -398,8 +399,8 @@ obj.alpha = anim.ease_out(t) * 255
|
||||
|
||||
| ソフトウェア | 用途 | ライセンス |
|
||||
|---|---|---|
|
||||
| [MoonSharp](https://github.com/moonsharp-devs/moonsharp) | 標準のLua実行エンジン(Lua 5.2 互換) | 3-Clause BSD License |
|
||||
| [LuaJIT](https://github.com/LuaJIT/LuaJIT) | ピクセル操作向け高速ランタイム(`native/luajit.exe`・`lua51.dll`) | MIT License |
|
||||
| [MoonSharp](https://github.com/moonsharp-devs/moonsharp) | フォールバック用のLua実行エンジン(Lua 5.2 互換) | 3-Clause BSD License |
|
||||
| [LuaJIT](https://github.com/LuaJIT/LuaJIT) | 標準の高速ランタイム(`native/luajit.exe`・`lua51.dll`) | MIT License |
|
||||
|
||||
### MoonSharp(3-Clause BSD License)
|
||||
|
||||
|
||||
+10
-8
@@ -14,17 +14,17 @@
|
||||
<h1>エンジンと高速化</h1>
|
||||
|
||||
<p>
|
||||
このプラグインには複数の実行エンジンがあります。標準は MoonSharp ですが、重いピクセル処理のために
|
||||
LuaJIT ネイティブレーンや、CPU / GPU カーネルへ変換するレーンを選べます。
|
||||
座標などを動かすだけのスクリプトでは MoonSharp で十分速く、エンジンを意識する必要はありません。
|
||||
このプラグインには複数の実行エンジンがあります。標準は同梱の LuaJIT ネイティブレーンで、
|
||||
決まった形の重いピクセル処理はさらに CPU カーネルへ変換されます。Lua 5.2 互換の MoonSharp は
|
||||
フォールバック用の従来エンジンです。指定子を書かなくても、内容に応じて自動で最適なレーンが選ばれます。
|
||||
</p>
|
||||
|
||||
<h2>エンジンの種類</h2>
|
||||
|
||||
<table>
|
||||
<tr><th>エンジン</th><th>指定子</th><th>特徴</th></tr>
|
||||
<tr><td>MoonSharp</td><td><code>--!moonsharp</code>(既定)</td><td>Lua 5.2 互換。全機能が使える標準エンジン</td></tr>
|
||||
<tr><td>ネイティブ(LuaJIT)</td><td><code>--!native</code></td><td>別プロセスの LuaJIT で実行。ピクセル処理が大幅に高速</td></tr>
|
||||
<tr><td>ネイティブ(LuaJIT)</td><td><code>--!native</code>(既定)</td><td>別プロセスの LuaJIT で実行。ピクセル処理が大幅に高速</td></tr>
|
||||
<tr><td>MoonSharp</td><td><code>--!moonsharp</code></td><td>Lua 5.2 互換。フォールバック用の従来エンジン</td></tr>
|
||||
<tr><td>CPU カーネル</td><td><code>--!cpu</code></td><td>決まった形のピクセルループを並列実行に変換。MoonSharp と一致する結果</td></tr>
|
||||
<tr><td>GPU カーネル</td><td><code>--!gpu</code></td><td>ピクセルループを GPU シェーダーに変換。最速だが float32 精度(明示指定のみ)</td></tr>
|
||||
</table>
|
||||
@@ -57,9 +57,8 @@ end</code></pre>
|
||||
|
||||
<ul>
|
||||
<li>後述のカーネル条件に当てはまるピクセルループは、CPU カーネルで実行します。結果は MoonSharp と一致します。</li>
|
||||
<li><code>obj.setoption</code> を使う描画系のスクリプトは、MoonSharp で実行します。</li>
|
||||
<li>カーネル条件には当てはまらないものの <code>getpixel</code> や <code>setpixel</code> を使うスクリプトは、ネイティブが使えればネイティブで実行します。</li>
|
||||
<li>それ以外は MoonSharp で実行します。</li>
|
||||
<li>それ以外のスクリプトは、同梱の LuaJIT ネイティブで実行します。結果は MoonSharp と一致します。</li>
|
||||
<li><code>native</code> フォルダが配備されていない環境と空のスクリプトは、MoonSharp で実行します。</li>
|
||||
</ul>
|
||||
|
||||
<div class="note">
|
||||
@@ -113,6 +112,9 @@ end</code></pre>
|
||||
<li><code>--!gpu</code> を指定しても、GPU カーネルを初期化できない場合は CPU カーネル、さらに MoonSharp の順で
|
||||
フォールバックします。</li>
|
||||
<li><code>--!cpu</code> を指定してもカーネル条件に合わないスクリプトは、ほかのエンジンで実行されます。</li>
|
||||
<li>MoonSharp では <code>tempbuffer</code> への描画合成を GPU で実行し、GPU を利用できない環境では
|
||||
CPU の合成へ自動的に切り替わります。丸めの違いにより、合成の結果はエンジン間で
|
||||
ごく僅かに異なることがあります。</li>
|
||||
</ul>
|
||||
|
||||
<div class="warn">
|
||||
|
||||
+3
-3
@@ -20,9 +20,9 @@ YukkuriMovieMaker4 の映像エフェクト「Lua スクリプト」の公式ド
|
||||
</p>
|
||||
|
||||
<p>
|
||||
標準のスクリプトエンジンは Lua 5.2 互換の MoonSharp です。
|
||||
重いピクセル処理のためには、LuaJIT で実行する <code>--!native</code> レーンと、
|
||||
CPU・GPU カーネルへ変換する <code>--!cpu</code>・<code>--!gpu</code> レーンも用意しています。
|
||||
標準のスクリプトエンジンは LuaJIT で実行するネイティブレーンで、
|
||||
決まった形のピクセル処理は <code>--!cpu</code> の CPU カーネルへ変換されます。
|
||||
Lua 5.2 互換の MoonSharp はフォールバックとして使われ、明示指定の <code>--!gpu</code> レーンも用意しています。
|
||||
詳しくは<a href="engines.html">エンジンと高速化</a>を参照してください。
|
||||
</p>
|
||||
|
||||
|
||||
+101
-1
@@ -167,12 +167,112 @@ obj.load("text", "サンプル")</code></pre>
|
||||
<tr><td><code>obj.draw([ox, oy, oz, zoom, alpha, aspect])</code></td><td>現在のバッファをオフセット・拡大率・不透明度を指定して描画する</td></tr>
|
||||
<tr><td><code>obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3 [, u0,v0, ... ,u3,v3] [, alpha])</code></td><td>4 頂点のテクスチャ付きポリゴンを描画する。UV を省略すると画像全体を使う</td></tr>
|
||||
<tr><td><code>obj.copybuffer(dst, src)</code></td><td>バッファ間でコピーする。ID は <code>obj</code>(作業画像)・<code>tmp</code>・<code>cache:名前</code>。書き込み先が <code>obj</code> のときのみ作業画像を置き換える</td></tr>
|
||||
<tr><td><code>obj.setoption(name [, value])</code></td><td>オプションを設定する。<code>antialias</code> は <code>obj.draw</code> で参照される</td></tr>
|
||||
<tr><td><code>obj.setoption(name [, value])</code></td><td>オプションを設定する。<code>antialias</code> は <code>obj.draw</code> で参照される。<code>blend</code> は <code>obj.draw</code>/<code>obj.drawpoly</code> の合成モードを番号で指定する。番号は下記の「合成モード」を参照。<code>draw_state</code> は真偽値で、<code>true</code> なら作業画像を出力し、<code>false</code> なら入力をそのまま通す。<code>drawtarget</code> は <code>obj.draw</code>/<code>obj.drawpoly</code> の描画先を <code>"framebuffer"</code> と <code>"tempbuffer"</code> で切り替える。詳細は下記の「描画先」を参照</td></tr>
|
||||
<tr><td><code>obj.getoption(name)</code></td><td>設定したオプションを取得する</td></tr>
|
||||
<tr><td><code>obj.getvalue(name)</code></td><td><code>obj</code> の数値メンバーを名前で取得する</td></tr>
|
||||
<tr><td><code>obj.pixeloption(name [, value])</code></td><td>ピクセル処理向けのオプションを設定する</td></tr>
|
||||
<tr><td><code>obj.setanchor(name, count [, option, ...])</code></td><td>プレビュー上にドラッグ可能なアンカーポイントを表示し、その座標を <code>name</code> の Lua 変数へ格納する。設置数を返す。詳細は下記の「アンカーポイント」を参照</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>合成モード</h3>
|
||||
|
||||
<p>
|
||||
<code>obj.setoption("blend", 番号)</code> は <code>obj.draw</code>/<code>obj.drawpoly</code> の描画に合成モードを設定します。
|
||||
番号は YMM4 のプロパティパネルにある「合成モード」のドロップダウンと並び順が同じで、0 から始まります。
|
||||
範囲外の値や数値以外を指定したときは通常モードになります。
|
||||
</p>
|
||||
|
||||
<pre><code>obj.setoption("blend", 3)
|
||||
obj.draw()</code></pre>
|
||||
|
||||
<table>
|
||||
<tr><th>番号</th><th>合成モード</th></tr>
|
||||
<tr><td><code>0</code></td><td>通常</td></tr>
|
||||
<tr><td><code>1</code></td><td>ディザ合成</td></tr>
|
||||
<tr><td><code>2</code></td><td>比較(暗)</td></tr>
|
||||
<tr><td><code>3</code></td><td>乗算</td></tr>
|
||||
<tr><td><code>4</code></td><td>焼き込みカラー</td></tr>
|
||||
<tr><td><code>5</code></td><td>焼き込み(リニア)</td></tr>
|
||||
<tr><td><code>6</code></td><td>比較(明)</td></tr>
|
||||
<tr><td><code>7</code></td><td>スクリーン</td></tr>
|
||||
<tr><td><code>8</code></td><td>覆い焼きカラー</td></tr>
|
||||
<tr><td><code>9</code></td><td>覆い焼き(リニア) - 加算</td></tr>
|
||||
<tr><td><code>10</code></td><td>加算</td></tr>
|
||||
<tr><td><code>11</code></td><td>オーバーレイ</td></tr>
|
||||
<tr><td><code>12</code></td><td>ソフトライト</td></tr>
|
||||
<tr><td><code>13</code></td><td>ハードライト</td></tr>
|
||||
<tr><td><code>14</code></td><td>ビビッドライト</td></tr>
|
||||
<tr><td><code>15</code></td><td>リニアライト</td></tr>
|
||||
<tr><td><code>16</code></td><td>ピンライト</td></tr>
|
||||
<tr><td><code>17</code></td><td>ハードミックス</td></tr>
|
||||
<tr><td><code>18</code></td><td>差分</td></tr>
|
||||
<tr><td><code>19</code></td><td>除外</td></tr>
|
||||
<tr><td><code>20</code></td><td>減算</td></tr>
|
||||
<tr><td><code>21</code></td><td>除算</td></tr>
|
||||
<tr><td><code>22</code></td><td>色相</td></tr>
|
||||
<tr><td><code>23</code></td><td>彩度</td></tr>
|
||||
<tr><td><code>24</code></td><td>カラー</td></tr>
|
||||
<tr><td><code>25</code></td><td>輝度</td></tr>
|
||||
<tr><td><code>26</code></td><td>カラー比較(明)</td></tr>
|
||||
<tr><td><code>27</code></td><td>背景</td></tr>
|
||||
<tr><td><code>28</code></td><td>カラー比較(暗)</td></tr>
|
||||
<tr><td><code>29</code></td><td>削除</td></tr>
|
||||
<tr><td><code>30</code></td><td>背景でクリッピング</td></tr>
|
||||
<tr><td><code>31</code></td><td>重ならない部分のみ</td></tr>
|
||||
<tr><td><code>32</code></td><td>色反転マスク</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>描画先</h3>
|
||||
|
||||
<p>
|
||||
<code>obj.setoption("drawtarget", 先)</code> は <code>obj.draw</code>/<code>obj.drawpoly</code> の描画先を切り替えます。
|
||||
<code>"framebuffer"</code>(既定)ではフレームバッファへ合成します。
|
||||
<code>"tempbuffer"</code> では作業用の <code>tmp</code> バッファへその場で合成します。
|
||||
<code>obj.setoption("drawtarget", "tempbuffer", w, h)</code> の <code>w, h</code> は <code>tmp</code> バッファを初期化するサイズで、省略すると初期化しません。
|
||||
<code>tmp</code> へ描いた結果は <code>obj.copybuffer("obj", "tmp")</code> で作業画像へ戻せます。
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<code>tempbuffer</code> への合成は通常(ソースオーバー)で、<code>blend</code> は <code>framebuffer</code> への描画に適用されます。
|
||||
描画先の切り替えは両エンジンで動きます。
|
||||
MoonSharp では <code>tempbuffer</code> への合成を GPU で実行し、GPU を利用できない環境では CPU の合成へ自動的に切り替わります。
|
||||
丸めの違いにより、合成の結果はエンジン間でごく僅かに異なることがあります。
|
||||
</p>
|
||||
|
||||
<pre><code>obj.setoption("drawtarget", "tempbuffer", obj.w, obj.h)
|
||||
obj.draw()
|
||||
obj.setoption("drawtarget", "framebuffer")
|
||||
obj.copybuffer("obj", "tmp")</code></pre>
|
||||
|
||||
<h3>アンカーポイント</h3>
|
||||
|
||||
<p>
|
||||
<code>obj.setanchor(name, count [, option, ...])</code> は、プレビュー上にドラッグ可能なアンカーポイントを表示します。
|
||||
ドラッグで調整した座標はプロジェクトへ保存され、<code>name</code> で指定した Lua 変数へ格納されます。
|
||||
変数は <code>pos={x0,y0,x1,y1,…}</code> の並びで、<code>"xyz"</code> を指定すると <code>{x0,y0,z0,x1,y1,z1,…}</code> になります。
|
||||
座標はオブジェクトの中心が原点です。個数は最大 32 個です。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>オプション</th><th>意味</th></tr>
|
||||
<tr><td><code>"line"</code></td><td>アンカーポイントを線で結ぶ</td></tr>
|
||||
<tr><td><code>"loop"</code></td><td>アンカーポイントを線で結び一周させる</td></tr>
|
||||
<tr><td><code>"star"</code></td><td>各アンカーポイントとオブジェクトの中心を線で結ぶ</td></tr>
|
||||
<tr><td><code>"arm"</code></td><td>オブジェクトの中心から各アンカーポイントへ順に線で結ぶ</td></tr>
|
||||
<tr><td><code>"xyz"</code></td><td>アンカーポイントを 3D 座標で扱う。既定は 2D</td></tr>
|
||||
</table>
|
||||
|
||||
<p>
|
||||
戻り値は設置したアンカーポイントの数です。両エンジンで動きます。
|
||||
<code>name</code> に <code>"track"</code> を指定するトラックバー連携は現在未対応で、<code>0</code> を返します。
|
||||
</p>
|
||||
|
||||
<pre><code>num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end</code></pre>
|
||||
|
||||
<h3>互換マップ</h3>
|
||||
|
||||
<p>
|
||||
|
||||
+2
-2
@@ -125,8 +125,8 @@ A チャンネル(インデックス <code>base + 4</code>)を変更する
|
||||
<p>
|
||||
ピクセル処理は重くなりがちです。このプラグインは <code>getpixel</code> / <code>setpixel</code> を含むスクリプトを
|
||||
自動的に高速なネイティブレーンへ振り分けます(利用できる場合)。さらに、二重ループで
|
||||
<code>getpixel</code> → 計算 → <code>setpixel</code> という決まった形のスクリプトは、CPU / GPU カーネルへ
|
||||
変換されてさらに高速に実行できます。詳しくは <a href="engines.html">エンジンと高速化</a> を参照してください。
|
||||
<code>getpixel</code> → 計算 → <code>setpixel</code> という決まった形のスクリプトは、CPU カーネルへ
|
||||
変換されてさらに高速に実行できます。<code>--!gpu</code> を明示すると GPU カーネルも使えます。詳しくは <a href="engines.html">エンジンと高速化</a> を参照してください。
|
||||
</p>
|
||||
|
||||
<div class="pager">
|
||||
|
||||
+379
-80
@@ -51,13 +51,19 @@ local OFF_CB_KIND = 11
|
||||
local OFF_LOAD_RESULT_W = 12
|
||||
local OFF_LOAD_RESULT_H = 13
|
||||
local OFF_STRING_PARAMS_LEN = 14
|
||||
local OFF_SCRIPT_VERSION = 15
|
||||
local SCRIPT_OFFSET = 64 + 64 * 8
|
||||
local ERROR_OFFSET = SCRIPT_OFFSET + 128 * 1024
|
||||
local CB_TAG_OFFSET = ERROR_OFFSET + 4 * 1024
|
||||
local CB_TAG_MAX = 4096
|
||||
local CB_RESULT_OFFSET = CB_TAG_OFFSET + CB_TAG_MAX
|
||||
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 LAST_WRITABLE = 25
|
||||
local STATUS_CALLBACK = 3
|
||||
@@ -69,6 +75,9 @@ local CB_KIND_DRAWPOLY = 4
|
||||
local CB_KIND_LOADTEXT = 5
|
||||
local CB_KIND_LOADIMAGE = 6
|
||||
local CB_KIND_LOADMOVIE = 7
|
||||
local CB_KIND_SETANCHOR = 8
|
||||
local CB_KIND_REQUESTPIXELS = 9
|
||||
local CB_KIND_FLUSHDRAWS = 10
|
||||
|
||||
assert(loadfile(shimPath))()
|
||||
|
||||
@@ -80,6 +89,7 @@ end
|
||||
|
||||
local width, height = 0, 0
|
||||
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 cbTagD = ffi.cast("double*", base + CB_TAG_OFFSET)
|
||||
local pixelCapacity = mapSize - PIXEL_OFFSET
|
||||
@@ -87,6 +97,201 @@ local buffers = {}
|
||||
local options = {}
|
||||
local pixeloptions = {}
|
||||
local dirty = false
|
||||
local pixelsValid = false
|
||||
local drawTarget = "frame"
|
||||
local pdData, pdCapacity, pdValid, pdDirty = nil, 0, false, false
|
||||
|
||||
local function ensurePixels()
|
||||
if pixelsValid then return end
|
||||
i32[OFF_CB_KIND] = CB_KIND_REQUESTPIXELS
|
||||
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||
k32.SetEvent(doneEvent)
|
||||
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||
pixelsValid = true
|
||||
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)
|
||||
if not linear then
|
||||
local su = clamp(math.floor(u), 0, srcW - 1)
|
||||
local sv = clamp(math.floor(v), 0, srcH - 1)
|
||||
local si = (sv * srcW + su) * 4
|
||||
return src[si], src[si + 1], src[si + 2], src[si + 3]
|
||||
end
|
||||
local fx = u - 0.5
|
||||
local fy = v - 0.5
|
||||
local x0 = math.floor(fx)
|
||||
local y0 = math.floor(fy)
|
||||
local tx = fx - x0
|
||||
local ty = fy - y0
|
||||
local b, g, r, a = 0, 0, 0, 0
|
||||
for j = 0, 1 do
|
||||
local sy = clamp(y0 + j, 0, srcH - 1)
|
||||
local wy = (j == 0) and (1 - ty) or ty
|
||||
for i = 0, 1 do
|
||||
local sx = clamp(x0 + i, 0, srcW - 1)
|
||||
local w = wy * ((i == 0) and (1 - tx) or tx)
|
||||
local si = (sy * srcW + sx) * 4
|
||||
b = b + src[si] * w
|
||||
g = g + src[si + 1] * w
|
||||
r = r + src[si + 2] * w
|
||||
a = a + src[si + 3] * w
|
||||
end
|
||||
end
|
||||
return b, g, r, a
|
||||
end
|
||||
|
||||
local function compositeOver(dst, di, sb, sg, sr, sa)
|
||||
local inv = 1 - sa / 255
|
||||
dst[di] = math.floor(clamp(sb + dst[di] * inv, 0, 255))
|
||||
dst[di + 1] = math.floor(clamp(sg + dst[di + 1] * inv, 0, 255))
|
||||
dst[di + 2] = math.floor(clamp(sr + dst[di + 2] * inv, 0, 255))
|
||||
dst[di + 3] = math.floor(clamp(sa + dst[di + 3] * inv, 0, 255))
|
||||
end
|
||||
|
||||
local function compositeDrawInto(dst, dstW, dstH, src, srcW, srcH, ox, oy, zoom, aspect, alpha, linear)
|
||||
if srcW <= 0 or srcH <= 0 or dstW <= 0 or dstH <= 0 then return end
|
||||
local ca = clamp(aspect, -1, 1)
|
||||
local zx = zoom * (1 + ca)
|
||||
local zy = zoom * (1 - ca)
|
||||
if zx == 0 or zy == 0 then return end
|
||||
local ka = clamp(alpha, 0, 1)
|
||||
if ka <= 0 then return end
|
||||
local halfW = srcW * 0.5
|
||||
local halfH = srcH * 0.5
|
||||
local spanX = math.abs(halfW * zx)
|
||||
local spanY = math.abs(halfH * zy)
|
||||
local x0 = math.max(0, math.floor(ox - spanX))
|
||||
local x1 = math.min(dstW - 1, math.ceil(ox + spanX))
|
||||
local y0 = math.max(0, math.floor(oy - spanY))
|
||||
local y1 = math.min(dstH - 1, math.ceil(oy + spanY))
|
||||
for py = y0, y1 do
|
||||
for px = x0, x1 do
|
||||
local u = (px + 0.5 - ox) / zx + halfW
|
||||
local v = (py + 0.5 - oy) / zy + halfH
|
||||
if u >= 0 and u < srcW and v >= 0 and v < srcH then
|
||||
local sb, sg, sr, sa = sampleSource(src, srcW, srcH, u, v, linear)
|
||||
compositeOver(dst, (py * dstW + px) * 4, sb * ka, sg * ka, sr * ka, sa * ka)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function compositeDrawPolyInto(dst, dstW, dstH, src, srcW, srcH, poly, alpha, linear)
|
||||
if srcW <= 0 or srcH <= 0 or dstW <= 0 or dstH <= 0 then return end
|
||||
local x0p, y0p = poly[0], poly[1]
|
||||
local x1p, y1p = poly[3], poly[4]
|
||||
local x3p, y3p = poly[9], poly[10]
|
||||
local u0, v0 = poly[12], poly[13]
|
||||
local u1, v1 = poly[14], poly[15]
|
||||
local u3, v3 = poly[18], poly[19]
|
||||
local det = u0 * (v1 - v3) - v0 * (u1 - u3) + (u1 * v3 - v1 * u3)
|
||||
if math.abs(det) < 1e-9 then return end
|
||||
local inv = 1 / det
|
||||
local a = (x0p * (v1 - v3) - v0 * (x1p - x3p) + (x1p * v3 - v1 * x3p)) * inv
|
||||
local b = (u0 * (x1p - x3p) - x0p * (u1 - u3) + (u1 * x3p - x1p * u3)) * inv
|
||||
local c = (u0 * (v1 * x3p - x1p * v3) - v0 * (u1 * x3p - x1p * u3) + x0p * (u1 * v3 - v1 * u3)) * inv
|
||||
local d = (y0p * (v1 - v3) - v0 * (y1p - y3p) + (y1p * v3 - v1 * y3p)) * inv
|
||||
local e = (u0 * (y1p - y3p) - y0p * (u1 - u3) + (u1 * y3p - y1p * u3)) * inv
|
||||
local f = (u0 * (v1 * y3p - y1p * v3) - v0 * (u1 * y3p - y1p * u3) + y0p * (u1 * v3 - v1 * u3)) * inv
|
||||
local adet = a * e - b * d
|
||||
if math.abs(adet) < 1e-9 then return end
|
||||
local ka = clamp(alpha, 0, 1)
|
||||
if ka <= 0 then return end
|
||||
local minX, minY, maxX, maxY = poly[0], poly[1], poly[0], poly[1]
|
||||
for i = 0, 3 do
|
||||
local xx = poly[i * 3]
|
||||
local yy = poly[i * 3 + 1]
|
||||
if xx < minX then minX = xx end
|
||||
if xx > maxX then maxX = xx end
|
||||
if yy < minY then minY = yy end
|
||||
if yy > maxY then maxY = yy end
|
||||
end
|
||||
local bx0 = math.max(0, math.floor(minX))
|
||||
local bx1 = math.min(dstW - 1, math.ceil(maxX))
|
||||
local by0 = math.max(0, math.floor(minY))
|
||||
local by1 = math.min(dstH - 1, math.ceil(maxY))
|
||||
for py = by0, by1 do
|
||||
for px = bx0, bx1 do
|
||||
local dx = (px + 0.5) - c
|
||||
local dy = (py + 0.5) - f
|
||||
local u = (e * dx - b * dy) / adet
|
||||
local v = (-d * dx + a * dy) / adet
|
||||
if u >= 0 and u < srcW and v >= 0 and v < srcH then
|
||||
local sb, sg, sr, sa = sampleSource(src, srcW, srcH, u, v, linear)
|
||||
compositeOver(dst, (py * dstW + px) * 4, sb * ka, sg * ka, sr * ka, sa * ka)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function ensureTemp()
|
||||
local t = buffers["t"]
|
||||
if not t then
|
||||
local n = width * height * 4
|
||||
t = { data = ffi.new("uint8_t[?]", n), w = width, h = height }
|
||||
buffers["t"] = t
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
local function bufferKind(id)
|
||||
local c = id:match("^%s*(.)")
|
||||
@@ -99,6 +304,7 @@ local function bufferKind(id)
|
||||
return c, c
|
||||
end
|
||||
|
||||
local sandbox
|
||||
local obj = {}
|
||||
local scene = {}
|
||||
local ymm4 = {}
|
||||
@@ -106,6 +312,8 @@ local ymm4 = {}
|
||||
function obj.getpixel(x, 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
|
||||
ensurePixels()
|
||||
flushPixelData()
|
||||
local p = pixels + (y * width + x) * 4
|
||||
local a = p[3]
|
||||
if a <= 0 then return 0, 0, 0, 0 end
|
||||
@@ -116,6 +324,8 @@ end
|
||||
function obj.setpixel(x, y, r, g, b, a)
|
||||
x = math.floor(x); y = math.floor(y)
|
||||
if x < 0 or y < 0 or x >= width or y >= height then return end
|
||||
ensurePixels()
|
||||
flushPixelData()
|
||||
a = a or 255
|
||||
dirty = true
|
||||
local aK = clamp(a, 0, 255) / 255
|
||||
@@ -124,57 +334,30 @@ function obj.setpixel(x, y, r, g, b, a)
|
||||
p[1] = math.floor(clamp(g * aK, 0, 255))
|
||||
p[2] = math.floor(clamp(r * aK, 0, 255))
|
||||
p[3] = math.floor(clamp(a, 0, 255))
|
||||
pdValid = false
|
||||
end
|
||||
|
||||
function obj.getpixeldata()
|
||||
ensurePixels()
|
||||
if not pdValid then rebuildPixelData() end
|
||||
local data = pdData
|
||||
local total = width * height * 4
|
||||
local buf = pixels
|
||||
local pd = { width = width, height = height }
|
||||
function pd:get(index)
|
||||
local zb = index - 1
|
||||
if zb < 0 or zb >= total then return 0 end
|
||||
local pi = math.floor(zb / 4)
|
||||
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)
|
||||
return data[zb]
|
||||
end
|
||||
function pd:set(index, value)
|
||||
local zb = index - 1
|
||||
if zb < 0 or zb >= total then return end
|
||||
dirty = true
|
||||
local pi = math.floor(zb / 4)
|
||||
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
|
||||
data[zb] = clamp(value, 0, 255)
|
||||
pdDirty = true
|
||||
end
|
||||
return pd
|
||||
end
|
||||
|
||||
function obj.putpixeldata() end
|
||||
function obj.putpixeldata() flushPixelData() end
|
||||
|
||||
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)
|
||||
@@ -202,6 +385,9 @@ local function applyLoadResult()
|
||||
i32[OFF_WIDTH] = newW
|
||||
i32[OFF_HEIGHT] = newH
|
||||
dirty = true
|
||||
pixelsValid = true
|
||||
pdValid = false
|
||||
pdDirty = false
|
||||
obj.w = newW; obj.h = newH
|
||||
obj.hw = newW / 2; obj.hh = newH / 2
|
||||
obj.cx = newW / 2; obj.cy = newH / 2
|
||||
@@ -319,31 +505,38 @@ function obj.effect(name, ...)
|
||||
end
|
||||
|
||||
function obj.draw(ox, oy, oz, zoom, alpha, aspect)
|
||||
cbResult[0] = ox or 0
|
||||
cbResult[1] = oy or 0
|
||||
cbResult[2] = oz or 0
|
||||
cbResult[3] = zoom or 1
|
||||
cbResult[4] = alpha or 1
|
||||
cbResult[5] = aspect or 0
|
||||
cbResult[6] = options.antialias or 1
|
||||
i32[OFF_CB_KIND] = CB_KIND_DRAW
|
||||
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||
k32.SetEvent(doneEvent)
|
||||
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||
if drawTarget == "temp" then
|
||||
ensurePixels()
|
||||
flushPixelData()
|
||||
local t = ensureTemp()
|
||||
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)
|
||||
return
|
||||
end
|
||||
local eb = ringSlot(CB_KIND_DRAW)
|
||||
ringD[eb + 1] = ox or 0
|
||||
ringD[eb + 2] = oy or 0
|
||||
ringD[eb + 3] = oz or 0
|
||||
ringD[eb + 4] = zoom or 1
|
||||
ringD[eb + 5] = alpha or 1
|
||||
ringD[eb + 6] = aspect or 0
|
||||
ringD[eb + 7] = options.antialias or 1
|
||||
ringD[eb + 8] = options.blend or 0
|
||||
end
|
||||
|
||||
function obj.drawpoly(...)
|
||||
local n = select("#", ...)
|
||||
if n < 12 then return end
|
||||
local a = { ... }
|
||||
for i = 0, 11 do cbTagD[i] = a[i + 1] or 0 end
|
||||
local p = {}
|
||||
for i = 0, 11 do p[i] = a[i + 1] or 0 end
|
||||
if n >= 20 then
|
||||
for i = 0, 7 do cbTagD[12 + i] = a[13 + i] or 0 end
|
||||
for i = 0, 7 do p[12 + i] = a[13 + i] or 0 end
|
||||
else
|
||||
cbTagD[12] = 0; cbTagD[13] = 0
|
||||
cbTagD[14] = width; cbTagD[15] = 0
|
||||
cbTagD[16] = width; cbTagD[17] = height
|
||||
cbTagD[18] = 0; cbTagD[19] = height
|
||||
p[12] = 0; p[13] = 0
|
||||
p[14] = width; p[15] = 0
|
||||
p[16] = width; p[17] = height
|
||||
p[18] = 0; p[19] = height
|
||||
end
|
||||
local alpha = 1
|
||||
if n == 13 then
|
||||
@@ -351,12 +544,18 @@ function obj.drawpoly(...)
|
||||
elseif n >= 21 then
|
||||
alpha = a[21] or 1
|
||||
end
|
||||
cbTagD[20] = alpha
|
||||
cbTagD[21] = options.antialias or 1
|
||||
i32[OFF_CB_KIND] = CB_KIND_DRAWPOLY
|
||||
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||
k32.SetEvent(doneEvent)
|
||||
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||
p[20] = alpha
|
||||
if drawTarget == "temp" then
|
||||
ensurePixels()
|
||||
flushPixelData()
|
||||
local t = ensureTemp()
|
||||
compositeDrawPolyInto(t.data, t.w, t.h, pixels, width, height, p, alpha, (options.antialias or 1) ~= 0)
|
||||
return
|
||||
end
|
||||
local eb = ringSlot(CB_KIND_DRAWPOLY)
|
||||
for i = 0, 20 do ringD[eb + 1 + i] = p[i] end
|
||||
ringD[eb + 22] = options.antialias or 1
|
||||
ringD[eb + 23] = options.blend or 0
|
||||
end
|
||||
|
||||
function obj.getvalue(target)
|
||||
@@ -366,10 +565,22 @@ function obj.getvalue(target)
|
||||
return 0
|
||||
end
|
||||
|
||||
function obj.setoption(name, value)
|
||||
function obj.setoption(name, value, a, b)
|
||||
if type(name) ~= "string" then return end
|
||||
if value == nil then value = true end
|
||||
options[name] = value
|
||||
if name == "drawtarget" then
|
||||
if value == "tempbuffer" then
|
||||
drawTarget = "temp"
|
||||
if a ~= nil and b ~= nil then
|
||||
local w = math.max(1, math.floor(a))
|
||||
local h = math.max(1, math.floor(b))
|
||||
buffers["t"] = { data = ffi.new("uint8_t[?]", w * h * 4), w = w, h = h }
|
||||
end
|
||||
else
|
||||
drawTarget = "frame"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function obj.getoption(name)
|
||||
@@ -385,12 +596,54 @@ function obj.pixeloption(name, value)
|
||||
pixeloptions[name] = value
|
||||
end
|
||||
|
||||
function obj.setanchor(name, count, ...)
|
||||
if type(name) ~= "string" then return 0 end
|
||||
count = math.floor(count or 0)
|
||||
if count < 0 then count = 0 elseif count > 32 then count = 32 end
|
||||
if name == "track" then return 0 end
|
||||
|
||||
local connection, is3d = 0, false
|
||||
local optCount = select("#", ...)
|
||||
for i = 1, optCount do
|
||||
local o = select(i, ...)
|
||||
if o == "line" then connection = 1
|
||||
elseif o == "loop" then connection = 2
|
||||
elseif o == "star" then connection = 3
|
||||
elseif o == "arm" then connection = 4
|
||||
elseif o == "xyz" then is3d = true end
|
||||
end
|
||||
|
||||
local len = #name
|
||||
if len > CB_TAG_MAX then len = CB_TAG_MAX end
|
||||
ffi.copy(base + CB_TAG_OFFSET, name, len)
|
||||
i32[OFF_CB_TAGLEN] = len
|
||||
cbResult[0] = count
|
||||
cbResult[1] = is3d and 1 or 0
|
||||
cbResult[2] = connection
|
||||
i32[OFF_CB_KIND] = CB_KIND_SETANCHOR
|
||||
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||
k32.SetEvent(doneEvent)
|
||||
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||
|
||||
local stride = is3d and 3 or 2
|
||||
local pos = {}
|
||||
for i = 0, count - 1 do
|
||||
pos[i * stride + 1] = cbTagD[i * stride + 0]
|
||||
pos[i * stride + 2] = cbTagD[i * stride + 1]
|
||||
if is3d then pos[i * stride + 3] = cbTagD[i * stride + 2] end
|
||||
end
|
||||
sandbox[name] = pos
|
||||
return count
|
||||
end
|
||||
|
||||
function obj.copybuffer(dst, src)
|
||||
if type(dst) ~= "string" or type(src) ~= "string" then return end
|
||||
local sk, skey = bufferKind(src)
|
||||
local data, w, h
|
||||
if sk == "o" then
|
||||
data = ffi.string(pixels, width * height * 4)
|
||||
ensurePixels()
|
||||
flushPixelData()
|
||||
data = pixels
|
||||
w = width; h = height
|
||||
elseif sk == "t" or sk == "c" then
|
||||
local b = buffers[skey]
|
||||
@@ -407,13 +660,19 @@ function obj.copybuffer(dst, src)
|
||||
width = w; height = h
|
||||
i32[OFF_WIDTH] = w; i32[OFF_HEIGHT] = h
|
||||
dirty = true
|
||||
pixelsValid = true
|
||||
pdValid = false
|
||||
pdDirty = false
|
||||
obj.w = w; obj.h = h
|
||||
obj.hw = w / 2; obj.hh = h / 2
|
||||
obj.cx = w / 2; obj.cy = h / 2
|
||||
obj.cz = 0
|
||||
obj.diagonal = math.sqrt(w * w + h * h)
|
||||
elseif dk == "t" or dk == "c" then
|
||||
buffers[dkey] = { data = data, w = w, h = h }
|
||||
local n = w * h * 4
|
||||
local arr = ffi.new("uint8_t[?]", n)
|
||||
ffi.copy(arr, data, n)
|
||||
buffers[dkey] = { data = arr, w = w, h = h }
|
||||
end
|
||||
end
|
||||
|
||||
@@ -460,7 +719,7 @@ function obj.getobject(tag, frame)
|
||||
return buildObject()
|
||||
end
|
||||
|
||||
local sandbox = {
|
||||
sandbox = {
|
||||
obj = obj, scene = scene, ymm4 = ymm4,
|
||||
anim = anim, bit32 = bit32, rawlen = rawlen,
|
||||
math = math, string = string, table = table,
|
||||
@@ -472,7 +731,25 @@ local sandbox = {
|
||||
}
|
||||
sandbox._G = sandbox
|
||||
|
||||
local compiledCode, compiledChunk
|
||||
local function captureKeys(t)
|
||||
local keys = {}
|
||||
for k in pairs(t) do keys[k] = true end
|
||||
return keys
|
||||
end
|
||||
|
||||
local function resetExtraKeys(t, keys)
|
||||
for k in pairs(t) do
|
||||
if not keys[k] then t[k] = nil end
|
||||
end
|
||||
end
|
||||
|
||||
local sandboxKeys = captureKeys(sandbox)
|
||||
local objKeys = captureKeys(obj)
|
||||
local sceneKeys = captureKeys(scene)
|
||||
local ymm4Keys = captureKeys(ymm4)
|
||||
|
||||
local compiledCode, compiledChunk, compiledError
|
||||
local lastScriptVersion
|
||||
|
||||
local function loadFields()
|
||||
width = i32[OFF_WIDTH]
|
||||
@@ -498,6 +775,9 @@ local function loadFields()
|
||||
obj.timelineframe = f64[51]; obj.timelinetime = f64[52]
|
||||
obj.check0 = f64[53] ~= 0; obj.check1 = f64[54] ~= 0; obj.check2 = f64[55] ~= 0; obj.check3 = f64[56] ~= 0
|
||||
sandbox.color = (f64[57] >= 0) and f64[57] or nil
|
||||
sandbox.time = f64[30]; sandbox.frame = f64[31]; sandbox.totalframe = f64[32]
|
||||
sandbox.framerate = f64[35]; sandbox.layer = f64[36]
|
||||
sandbox.timelineframe = f64[51]; sandbox.timelinetime = f64[52]
|
||||
end
|
||||
|
||||
local function loadStringParams()
|
||||
@@ -532,36 +812,55 @@ while true do
|
||||
if i32[OFF_COMMAND] == 1 then break end
|
||||
|
||||
dirty = false
|
||||
local scriptLen = i32[OFF_SCRIPTLEN]
|
||||
local code = ffi.string(base + SCRIPT_OFFSET, scriptLen)
|
||||
|
||||
if code ~= compiledCode then
|
||||
local chunk, err = loadstring(code, "LuaScript")
|
||||
if chunk then
|
||||
compiledChunk = chunk
|
||||
compiledCode = code
|
||||
else
|
||||
compiledChunk = nil
|
||||
local msg = err 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)
|
||||
pixelsValid = false
|
||||
pdValid = false
|
||||
pdDirty = false
|
||||
ringD[0] = 0
|
||||
local version = i32[OFF_SCRIPT_VERSION]
|
||||
if version ~= lastScriptVersion then
|
||||
lastScriptVersion = version
|
||||
local scriptLen = i32[OFF_SCRIPTLEN]
|
||||
local code = ffi.string(base + SCRIPT_OFFSET, scriptLen)
|
||||
if code ~= compiledCode then
|
||||
local chunk, err = loadstring(code, "LuaScript")
|
||||
if chunk then
|
||||
compiledChunk = chunk
|
||||
compiledCode = code
|
||||
compiledError = nil
|
||||
else
|
||||
compiledChunk = nil
|
||||
compiledCode = code
|
||||
compiledError = err or "compile error"
|
||||
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(obj, objKeys)
|
||||
resetExtraKeys(scene, sceneKeys)
|
||||
resetExtraKeys(ymm4, ymm4Keys)
|
||||
loadFields()
|
||||
loadStringParams()
|
||||
cacheTag = nil
|
||||
for k in pairs(options) do options[k] = nil end
|
||||
for k in pairs(pixeloptions) do pixeloptions[k] = nil end
|
||||
drawTarget = "frame"
|
||||
font.family = ""; font.size = 34; font.bold = false; font.italic = false; font.color = 0xFFFFFF
|
||||
math.randomseed(f64[31])
|
||||
setfenv(compiledChunk, sandbox)
|
||||
local ok, err = pcall(compiledChunk)
|
||||
if ok then
|
||||
flushPixelData()
|
||||
storeFields()
|
||||
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
|
||||
i32[OFF_PIXELSDIRTY] = dirty and 1 or 0
|
||||
i32[OFF_STATUS] = 1
|
||||
k32.SetEvent(doneEvent)
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする