コミットを比較

...
63 コミット
作成者 SHA1 メッセージ 日付
routersys 42e0b2b0f7 バージョンをv1.3.3へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.3.3 のコミットから作成しました
2026-06-27 17:56:46 +09:00
routersys 954b1bfc49 READMEからgetobjectのネイティブ制約の記載を削除 2026-06-27 17:56:40 +09:00
routersys 41defa1059 getobjectをネイティブ実行でも利用可能にした 2026-06-27 17:55:47 +09:00
routersys 876f05d277 バージョンをv1.3.2へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.3.2 のコミットから作成しました
2026-06-27 17:31:39 +09:00
routersys 227af2c75c READMEにLuaJIT等のサードパーティ表記を追記 2026-06-27 17:26:53 +09:00
routersys 5cbd5ae8ff 同梱ライブラリのライセンスを追加しリリースに同梱 2026-06-27 17:26:50 +09:00
routersys bb97610454 luajitの残留プロセスをジョブで道連れ終了 2026-06-27 17:26:37 +09:00
routersys 968180c459 バージョンをv1.3.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.3.1 のコミットから作成しました
2026-06-27 13:10:59 +09:00
routersys d9ad3692f2 プラグイン情報を追加 2026-06-27 13:06:29 +09:00
routersys 573234d727 nativeをリリースに同梱
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.3.0 のコミットから作成しました
2026-06-27 12:59:28 +09:00
routersys 69a5f26260 テスト専用luaを配布から除外し必要な4ファイルのみ同梱 2026-06-27 12:40:33 +09:00
routersys ed4601a03a 実行エンジンの自動振り分け・高速化・制約をREADMEに追記 2026-06-27 12:34:49 +09:00
routersys 960569177c v1.3.0のリリースノートを記載 2026-06-27 12:34:48 +09:00
routersys 2831ea25ee バージョンを1.3.0へ更新 2026-06-27 12:34:48 +09:00
routersys a2caa2e910 ネイティブ実行でmath.randomseed(frame)を毎フレーム適用し決定論を維持 2026-06-27 12:34:47 +09:00
routersys 26bc21681f オートルーティングのテストを追加 2026-06-27 12:23:09 +09:00
routersys 7edbe189a2 getpixeldata往復テストを追加 2026-06-27 12:23:08 +09:00
routersys e8ae7d1189 自動振り分けを採用しネイティブ未配備時は一度だけ警告(サイレントフォールバック解消) 2026-06-27 12:23:08 +09:00
routersys ce7007c42e ピクセルAPI使用スクリプトをネイティブへ自動振り分け(ResolveAuto) 2026-06-27 12:23:07 +09:00
routersys f10f31ef2b ワーカーにgetpixeldata(PixelDataProxy相当)を実装 2026-06-27 12:23:07 +09:00
routersys 4a5043eb3a テストプロジェクトの参照を追加 2026-06-27 10:07:47 +09:00
routersys 640c9f5347 ネイティブワーカー往復テスト(変形/ピクセル/タイムアウト/エラー)を追加 2026-06-27 09:57:19 +09:00
routersys b339d60bd7 vendored nativeをリポジトリ直下へ集約し両プロジェクトから参照 2026-06-27 09:57:18 +09:00
routersys f94e0ea849 nativeランタイムをプラグイン出力へ同梱・配備(csproj) 2026-06-27 09:56:57 +09:00
routersys 729ba355d9 --!nativeをLuaJITワーカーへ振り分けるよう配線 2026-06-27 09:56:56 +09:00
routersys 67697930b7 常駐ワーカースクリプト(obj/scene/ymm4/pixel,サンドボックス)を追加 2026-06-27 09:56:56 +09:00
routersys f929c1a83a コンテキスト⇄ネイティブフィールド配列の写像を追加 2026-06-27 09:56:56 +09:00
routersys 6ee2784d6a 常駐LuaJITワーカー管理(別プロセス/共有メモリ/ハードキル)を追加 2026-06-27 09:56:55 +09:00
routersys 03db2d4faf ネイティブ実行の共有メモリプロトコルを定義 2026-06-27 09:56:55 +09:00
routersys fda89f726b 共有メモリでのBGRA授受の検証を追加 2026-06-27 09:33:34 +09:00
routersys d22035111a 共有メモリBGRA処理ワーカー(PoC)を追加 2026-06-27 09:33:34 +09:00
routersys 28bc23cd49 JIT無限ループのハードキル・タイムアウト検証を追加 2026-06-27 09:33:33 +09:00
routersys 796051015c animのMoonSharp×LuaJIT実機等価テストを追加 2026-06-27 09:33:33 +09:00
routersys 7184a89330 bit32のC#×LuaJIT実機等価テストを追加 2026-06-27 09:33:33 +09:00
routersys add78d673a クロスエンジン評価ランナーを追加 2026-06-27 09:33:33 +09:00
routersys f8522ad816 LuaJIT用 bit32/rawlen/anim シムを追加 2026-06-27 09:33:32 +09:00
routersys 45bee472e4 LuaJIT 2.1 x64バイナリを同梱(テストfixture) 2026-06-27 09:33:32 +09:00
routersys be411b596d animユーティリティの契約テストを追加 2026-06-27 09:33:14 +09:00
routersys 21741fc620 rawlen等の基本関数の挙動固定テストを追加 2026-06-27 09:33:14 +09:00
routersys 05ffdcc9d3 Bit32の正しさと安全域でのMoonSharp一致テストを追加 2026-06-27 09:33:13 +09:00
routersys 1f32ec59ce MoonSharpBit32のMoonSharp等価テストを追加 2026-06-27 09:33:13 +09:00
routersys 6af9153f50 ルータのテストを追加 2026-06-27 09:33:13 +09:00
routersys 4528748493 テスト用LuaJITレーン(別プロセス駆動)ヘルパを追加 2026-06-27 09:33:13 +09:00
routersys 3c0e13c85d テスト用MoonSharpレーンヘルパを追加 2026-06-27 09:33:13 +09:00
routersys 66786bfc98 テストプロジェクトLuaScript.Testsを追加 2026-06-27 09:33:12 +09:00
routersys 10dbb022bc 正しいLua5.2準拠のbit32実装を追加 2026-06-27 09:32:53 +09:00
routersys b0e47b82f5 MoonSharp挙動を完全再現するbit32実装(互換層)を追加 2026-06-27 09:32:53 +09:00
routersys 9e3381f0d0 エンジン振り分けディレクティブ(--!native等)を解析するルータを追加 2026-06-27 09:32:53 +09:00
routersys 6e29bf08b0 毎フレーム処理のアロケーションを削減し動画出力を高速化 2026-06-26 20:25:58 +09:00
routersys 21615a5461 マージ 2026-06-25 15:17:11 +09:00
routersys 3dc06dbeb3 v1.2.0向けにバージョンとリリースノートを更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.2.0 のコミットから作成しました
2026-06-25 15:16:28 +09:00
routersys 5c4e1de447 サンプル集に発射時座標の固定例を追加 2026-06-25 15:09:20 +09:00
routersys 488a70ece1 obj.getobjectのフレーム引数を各言語ドキュメントに追記 2026-06-25 15:09:15 +09:00
routersys 41906f81e9 obj.getobjectにフレーム指定引数を追加 2026-06-25 15:09:06 +09:00
routersys bc3bd511df Create CNAME 2026-06-25 07:46:55 +09:00
routersys 6ab90f3584 v1.1.1向けにバージョンとリリースノートを更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.1.1 のコミットから作成しました
2026-06-24 21:51:21 +09:00
routersys 81775e0441 全テーマのシンタックス定義を追加し、エディタ表示時の例外を修正 2026-06-24 21:49:58 +09:00
routersys c51b24cfba Luaスクリプトのサンプル集ページを追加 2026-06-24 21:46:57 +09:00
routersys 3a9be71e95 v1.1.0向けにバージョンとリリースノート、Readme.txtを更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.1.0 のコミットから作成しました
2026-06-24 20:11:42 +09:00
routersys 1255324495 マージ 2026-06-24 20:02:24 +09:00
routersys b95d66f335 Luaスクリプトから他オブジェクトの座標等を取得するobj.getobjectを追加 2026-06-24 20:01:20 +09:00
routersys c4e3bc0692 §サードパーティライセンスの追加 2026-06-21 16:49:12 +09:00
routersys e3c672b5bb サムネイル画像の追加 2026-06-21 14:23:44 +09:00
55個のファイルの変更、4701行の追加、640行の削除

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

+26 -487
ファイルの表示
@@ -1,500 +1,39 @@
# v1.0.0 - Lua スクリプト for YMM4
# v1.3.3 - Lua スクリプト for YMM4
YukkuriMovieMaker4 向けの Lua スクリプトエフェクトプラグインの初回リリースです。
AviUtl アニメーション効果互換の変数・関数体系を YMM4 映像エフェクトとして提供し、
MoonSharp による Lua 実行エンジン・専用コードエディター・シンタックスハイライト・
折り畳み・オートコンプリート・ファイルインポート/エクスポート・ピクセル直接操作・
独自アニメーションユーティリティライブラリ・8 言語対応 UI を備えた映像エフェクトプラグインです。
これまでネイティブ実行では使用できなかった **`obj.getobject` がネイティブ実行でも
利用可能**になったリリースです。ピクセル操作と他オブジェクトの参照を 1 つの
スクリプトで併用できるようになりました。
---
## 新機能
## 新機能・改善
### 1. エフェクト定義(LuaScriptEffect)
### 1. `obj.getobject` をネイティブ実行でも利用可能に
`LuaScriptEffect` は `VideoEffectBase` を継承し、`IScriptProvider` を実装します。
`[VideoEffect]` 属性は以下のパラメーターで宣言されます。
- 表示名:`Texts.LuaScript`(ローカライズキー)
- カテゴリー:`VideoEffectCategories.Filtering`
- 検索タグ:`"lua"`・`"script"`・`"スクリプト"`・`"lua script"`・`"アニメーション効果"`・`"animation"`
- `IsAviUtlSupported = false` により AviUtl 向け EXO 出力は非対応です。
- `ResourceType = typeof(Texts)` でローカライズリソースを指定します。
`Label` プロパティは `Texts.LuaScript` の固定値を返却します。
デフォルトスクリプトは以下のとおりです。
```lua
obj.alpha = math.min(time * 255, 255)
```
公開プロパティは以下のとおりです。
- `ToolBar`(`object?`、常に `null`):
`[LuaScriptToolBar]` でインポート・エクスポート・クリアのツールバーを表示します。
`Texts.ScriptGroup` グループに属します。
- `Script`(`string`、デフォルト `DefaultScript`):
`[CodeEditor]` でシンタックスハイライト付きコードエディターとして表示されます。
シンタックス定義は `pack://application:,,,/LuaScript;component/Resources/SyntaxDefinitions/Lua-{theme}.xshd`
をテーマ別に読み込みます。折り畳みに `LuaFoldingStrategy`、オートコンプリートに
`LuaAutoCompletionStrategy` を使用します。`PropertyEditorSize.FullWidth` で全幅表示されます。
`Set` による変更通知を伴うフィールドプロパティとして実装されます。
`Texts.ScriptGroup` グループに属します。
- `Track0`〜`Track3`(`Animation`、デフォルト `0`、内部範囲:`YMM4Constants.VerySmallValue`〜`YMM4Constants.VeryLargeValue`):
`[AnimationSlider("F2", "", -100, 100)]` でスライダー操作範囲 -100〜100 として表示されます。
スクリプト内では `obj.track0`〜`obj.track3` でアクセスします。
AviUtl の `track0`〜`track3` に対応するスライダー値です。
`Texts.ParametersGroup` グループに属します。
`CreateExoVideoFilters` は空の `IEnumerable<string>` を返却し、EXO 向けフィルター出力は実装されていません。
`CreateVideoEffect(IGraphicsDevicesAndContext devices)` は
`new LuaScriptEffectProcessor(devices, this)` を返却します。
`GetAnimatables` は `Track0`・`Track1`・`Track2`・`Track3` を列挙します。
ピクセル操作を含むスクリプトはネイティブ実行へ振り分けられますが、これまでは
ネイティブ実行中の `obj.getobject` が常に `nil` を返していました。本リリースでは、
ネイティブ実行中に `obj.getobject` を呼び出すと**本体プロセスへ同期的に問い合わせて
シーンオブジェクトを解決**するようにしました。従来エンジンと同じ描画情報を返すため、
ピクセル操作と他オブジェクトの参照を 1 つのスクリプトで併用できます。
`--!moonsharp` を明示してエンジンを切り替える必要はなくなりました。
---
### 2. スクリプト実行コンテキスト(AviUtlScriptContext)
## 注意事項
`AviUtlScriptContext` はスクリプト実行時の状態を保持する内部クラスです。
#### 読み取り専用プロパティ
| プロパティ | 型 | 説明 |
|---|---|---|
| `ImageWidth` | `int` | 画像幅(ピクセル) |
| `ImageHeight` | `int` | 画像高さ(ピクセル) |
| `Track0`〜`Track3` | `double` | スライダー値 |
| `Time` | `double` | アイテム内の経過時間(秒) |
| `Frame` | `int` | アイテム内の経過フレーム数 |
| `TotalFrame` | `int` | アイテムの総フレーム数 |
| `TotalTime` | `double` | アイテムの総時間(秒) |
| `Framerate` | `int` | フレームレート |
| `TimelineFrame` | `int` | タイムライン上の経過フレーム数 |
| `TimelineTime` | `double` | タイムライン上の経過時間(秒) |
| `SceneWidth` | `int` | シーン幅 |
| `SceneHeight` | `int` | シーン高さ |
| `Layer` | `int` | レイヤー番号 |
| `Index` | `int` | グループ内のインデックス |
| `Num` | `int` | グループ内の総数 |
| `GroupIndex` | `int` | グループインデックス |
| `GroupCount` | `int` | グループ総数 |
| `TimelineTotalFrame` | `int` | タイムライン総フレーム数 |
| `TimelineTotalTime` | `double` | タイムライン総時間(秒) |
| `IsSaving` | `bool` | エクスポート中かどうか |
| `IsPlaying` | `bool` | 再生中かどうか |
| `IsPaused` | `bool` | 一時停止中かどうか |
| `TimeRatio` | `double` | アイテム内の時間比率(Frame / TotalFrame) |
| `SceneId` | `string` | シーン ID |
#### 書き換え可能プロパティ
| プロパティ | 型 | 説明 |
|---|---|---|
| `X`・`Y`・`Z` | `double` | 描画位置 |
| `Ox`・`Oy`・`Oz` | `double` | 回転中心のオフセット |
| `Sx`・`Sy` | `double` | X・Y 方向の拡大率 |
| `Zoom` | `double` | 拡大率((Sx + Sy) / 2) |
| `Aspect` | `double` | アスペクト比((Sx - Sy) / (Sx + Sy)) |
| `Alpha` | `double` | 不透明度(0〜255) |
| `Rx`・`Ry`・`Rz` | `double` | X・Y・Z 軸回転角(度) |
`RxRad`・`RyRad`・`RzRad` は各 `Rx`・`Ry`・`Rz` をラジアンに換算した計算プロパティです。
#### ピクセル操作
- `GetPixel(int x, int y)` は `(r, g, b, a)` のタプルを返却します。各成分は 0〜255 の `double` で、
プリマルチプライ済み BGRA からストレートアルファの RGB へ復元して返却します。
アルファが 0 以下の場合はすべて 0 を返却します。
- `SetPixel(int x, int y, double r, double g, double b, double a)` は
ストレートアルファの RGB をプリマルチプライ済み BGRA に変換してバッファーへ書き込みます。
`a` のデフォルトは 255 です。書き込み後は `IsPixelsDirty` が true になります。
- `EnsurePixelBuffer` はピクセルローダーを遅延呼び出しして入力画像をバッファーへ読み込みます。
- `GetPixelBuffer` は内部の `byte[]` バッファーを返却します。
- ネイティブ実行中の `obj.getobject` は、呼び出しごとに本体プロセスへの往復が
発生します。1 フレーム内で多数のオブジェクトを参照する場合は、結果を変数へ
保持して呼び出し回数を抑えることを推奨します。
- `obj.getobject` を含むスクリプトの実行時間も、従来どおり 5 秒のタイムアウトの
対象です。問い合わせを含めた総実行時間が 5 秒を超えると強制終了されます。
---
### 3. エフェクトプロセッサー(LuaScriptEffectProcessor)
`LuaScriptEffectProcessor` は `VideoEffectProcessorBase` を継承し、
コンストラクターで `IGraphicsDevicesAndContext devices` と `LuaScriptEffect item` を受け取ります。
#### CreateEffect メソッド
`GraphicsDevicesAndContext` のプライベートコンテキスト `_ownCtx` を生成して `disposer` に登録し、
`null` を返却します。出力画像の生成はスクリプト実行後に動的に決定します。
#### setInput / ClearEffectChain メソッド
`setInput` は入力が前回と異なる場合に `_isFirst = true` としてキャッシュを無効化します。
`ClearEffectChain` は `effectOutput` を null に設定します。
#### Update メソッド
`Update(EffectDescription desc)` は毎フレーム呼び出されます。
`input` または `_ownCtx` が null の場合は `desc.DrawDescription` をそのまま返却します。
`RenderKey` レコードでフレーム・時間・長さ・FPS・スライダー値 4 本・スクリプト文字列・
利用用途・シーン ID・タイムライン情報・シーンサイズ・レイヤー・インデックス・グループ情報・
タイムライン総フレーム数・`DrawDescription` を一括保持し、
前回と同一の場合はキャッシュした結果をそのまま返却します。
スクリプト実行時は `BuildContext` で `AviUtlScriptContext` を生成し、
`SetPixelLoader` でピクセル遅延ローダーを登録してから `LuaScriptEngine.Execute` を呼び出します。
実行後に `ctx.IsPixelsDirty` が true の場合のみ出力ビットマップへ書き込み、
`AffineTransform2D` で入力境界の原点へ平行移動して `effectOutput` に設定します。
ピクセルが変更されていない場合は `effectOutput = null` としてパススルーします。
`BuildOutputDesc` が書き換え後の `ctx.X/Y/Z/Ox/Oy/Sx/Sy/Zoom/Aspect/Alpha/Rx/Ry/Rz` から
新しい `DrawDescription` を構築して返却します。`Alpha` は `ctx.Alpha / 255d` を
0〜1 にクランプします。
例外は `LuaScriptException` を捕捉してログに書き込み、エラー時は入力の `DrawDescription` を
そのまま返却します。タイムアウトは `LuaScriptRuntimeException` として処理されます。
#### ビットマップ管理
`EnsureBitmaps(int width, int height)` でサイズ変化時にビットマップ 3 枚と変換エフェクトを再生成します。
- `_renderTarget`:`BitmapOptions.Target`、入力を描画する作業バッファー
- `_stagingBitmap`:`B8G8R8A8_UNorm`・`Premultiplied`・`CpuRead | CannotDraw`、CPU 読み出し用
- `_outputBitmap`:`BitmapOptions.Target`、ピクセル操作後の書き出し先
`LoadInputPixels` は `_ownCtx` の独立デバイスコンテキストで入力を `_renderTarget` へ描画し、
`_stagingBitmap` へコピーして `Map(MapOptions.Read)` で `_pixelBuffer` へ読み出します。
ピッチが行ストライドと一致する場合は一括コピー、そうでない場合は行ごとにコピーします。
---
### 4. Lua 実行エンジン(LuaScriptEngine)
`LuaScriptEngine` は `IDisposable` を実装します。
タイムアウトは `ExecutionTimeoutMilliseconds = 5000`(5 秒)です。
タイムアウト時は実行スレッドを非同期で破棄して新しいスレッドを生成し、
`LuaScriptRuntimeException` をスローします。
#### ExecutionThread 内部クラス
Lua スクリプトを専用ワーカースレッドで逐次実行する仕組みです。
キューのバウンド容量は 1 で、実行要求が溢れた場合は即座にエラーを返却します。
`CancellationDebugger` により、キャンセルトークンを MoonSharp デバッガーフックへ橋渡しし、
タイムアウト時に `OperationCanceledException` を発生させます。
コンパイル済みチャンクはスクリプト文字列が変化した場合のみ `LoadString` で再コンパイルします。
再コンパイル時の構文エラーは `LuaScriptCompilationException` としてラップします。
実行時エラーは `LuaScriptRuntimeException` としてラップします。
`EnsureScriptIntegrity` は `math` グローバルが消失していた場合に Lua VM を完全リセットします。
有効な Lua モジュールは以下のとおりです。
`Basic` / `Math` / `String` / `Table` / `Bit32` / `TableIterators` / `Metatables` / `ErrorHandling`
ファイルアクセスは `DisabledFileScriptLoader` により無効化されています。
フレームシードによる `math.randomseed` 呼び出しにより、同一フレームでは `math.random` が
再現性のある値を返します。
#### SetupGlobals メソッド
スクリプト実行前にグローバル変数と各テーブルを初期化します。
ユーザーがフレーム間でグローバルに書き込んだキーは次フレームの実行前に除去されます
(`_builtinGlobalSnapshot` との差分を削除)。
各テーブル(`obj`・`scene`・`anim`・`ymm4`)も同様にフレーム間でリセットします。
スクリプトから利用可能なグローバル変数は以下のとおりです。
| 変数名 | 型 | 説明 |
|---|---|---|
| `time` | `double` | アイテム内の経過時間(秒) |
| `frame` | `int` | アイテム内の経過フレーム数 |
| `totalframe` | `int` | アイテムの総フレーム数 |
| `framerate` | `int` | フレームレート |
| `timelineframe` | `int` | タイムライン上の経過フレーム数 |
| `timelinetime` | `double` | タイムライン上の経過時間(秒) |
| `layer` | `int` | レイヤー番号 |
#### ReadBackGlobals メソッド
スクリプト実行後に `obj` テーブルの変数を `AviUtlScriptContext` へ書き戻します。
書き戻し対象は `x`・`y`・`z`・`ox`・`oy`・`oz`・`alpha`・`sx`・`sy`・`zoom`・`aspect`・
`rx`・`ry`・`rz`・`rxr`・`ryr`・`rzr` です。
`zoom`・`aspect` が変化し、かつ `sx`・`sy` が変化していない場合は
`sx = zoom * (1 + aspect)`・`sy = zoom * (1 - aspect)` で `sx`・`sy` を再計算します。
`rxr`・`ryr`・`rzr` が前回値から変化していた場合は、それをラジアンから度に変換して
`rx`・`ry`・`rz` を上書きします。それ以外の場合は `rx`・`ry`・`rz` を直接読み返します。
---
### 5. スクリプト API(obj テーブル)
スクリプトから参照・書き換えできる `obj` テーブルのメンバーは以下のとおりです。
#### 読み取り専用メンバー
| メンバー | 説明 |
|---|---|
| `obj.w` | 画像幅(ピクセル) |
| `obj.h` | 画像高さ(ピクセル) |
| `obj.hw` | 画像幅の半分 |
| `obj.hh` | 画像高さの半分 |
| `obj.cx` | 画像幅の半分(`hw` の別名) |
| `obj.cy` | 画像高さの半分(`hh` の別名) |
| `obj.cz` | 常に 0 |
| `obj.sz` | 常に 1 |
| `obj.diagonal` | 画像の対角線長(`sqrt(w^2 + h^2)`) |
| `obj.track0`〜`obj.track3` | スライダー値 |
| `obj.time` | アイテム内の経過時間(秒) |
| `obj.frame` | アイテム内の経過フレーム数 |
| `obj.totalframe` | アイテムの総フレーム数 |
| `obj.totaltime` | アイテムの総時間(秒) |
| `obj.t` | `frame / totalframe`(0 除算時は 0) |
| `obj.framerate` | フレームレート |
| `obj.layer` | レイヤー番号 |
| `obj.index` | グループ内のインデックス |
| `obj.num` | グループ内の総数 |
#### 読み書き可能メンバー
| メンバー | 説明 |
|---|---|
| `obj.x`・`obj.y`・`obj.z` | 描画位置(ピクセル) |
| `obj.ox`・`obj.oy`・`obj.oz` | 回転中心のオフセット(ピクセル) |
| `obj.sx`・`obj.sy` | X・Y 方向の拡大率 |
| `obj.zoom` | 拡大率(sx と sy の平均) |
| `obj.aspect` | アスペクト比 |
| `obj.alpha` | 不透明度(0〜255) |
| `obj.rx`・`obj.ry`・`obj.rz` | X・Y・Z 軸回転角(度) |
| `obj.rxr`・`obj.ryr`・`obj.rzr` | X・Y・Z 軸回転角(ラジアン)。変更すると対応する `rx`・`ry`・`rz` を上書きします。 |
#### ピクセル操作関数
| 関数 | 戻り値 | 説明 |
|---|---|---|
| `obj.getpixel(x, y)` | `r, g, b, a` | 指定座標のピクセルを取得します。各成分は 0〜255 の浮動小数点数です。 |
| `obj.setpixel(x, y, r, g, b [, a])` | なし | 指定座標へピクセルを書き込みます。`a` のデフォルトは 255 です。 |
| `obj.getpixeldata()` | `PixelDataProxy` | ピクセルデータへの直接アクセスオブジェクトを返却します。 |
| `obj.putpixeldata()` | なし | 互換性のために存在しますが、何もしません。 |
---
### 6. スクリプト API(scene テーブル)
| メンバー | 説明 |
|---|---|
| `scene.width` | シーン幅(ピクセル) |
| `scene.height` | シーン高さ(ピクセル) |
| `scene.cx` | シーン幅の半分 |
| `scene.cy` | シーン高さの半分 |
---
### 7. スクリプト API(anim テーブル)
`anim` テーブルはアニメーション補助関数と数学ユーティリティを提供します。
#### 定数
| 定数名 | 値 | 説明 |
|---|---|---|
| `anim.tau` | `2π` | 円周率の 2 倍 |
| `anim.e` | `e` | 自然対数の底 |
| `anim.phi` | `(1 + √5) / 2` | 黄金比 |
| `anim.sqrt2` | `√2` | 2 の平方根 |
#### 補間・マッピング関数
| 関数 | 説明 |
|---|---|
| `anim.lerp(a, b, t)` | `a` から `b` への線形補間 |
| `anim.smoothstep(edge0, edge1, x)` | Hermite 補間(0〜1 にクランプ) |
| `anim.smootherstep(edge0, edge1, x)` | 5 次 Hermite 補間(0〜1 にクランプ) |
| `anim.clamp(v, lo, hi)` | `v` を `lo`〜`hi` にクランプ |
| `anim.map(v, a1, b1, a2, b2)` | `a1`〜`b1` の範囲を `a2`〜`b2` へ線形写像 |
| `anim.norm(v, lo, hi)` | `lo`〜`hi` を 0〜1 に正規化 |
| `anim.wrap(v, lo, hi)` | `lo`〜`hi` の範囲でラップアラウンド |
| `anim.pingpong(t, length)` | `0`〜`length` を往復 |
#### ウェーブ・信号関数
| 関数 | 説明 |
|---|---|
| `anim.oscillate(t, lo, hi, freq)` | サイン波で `lo`〜`hi` を周期 `1/freq` 秒で往復 |
| `anim.triangle(t, freq)` | 三角波(0〜1) |
| `anim.square(t, freq)` | 矩形波(0 または 1) |
| `anim.sign(v)` | 符号(−1・0・+1) |
| `anim.step(edge, x)` | `x >= edge` なら 1、それ以外は 0 |
| `anim.fract(v)` | 小数部(`v - floor(v)`) |
| `anim.delay(t, d)` | `max(0, t - d)` |
| `anim.duration(t, dur)` | `clamp(t / dur, 0, 1)` |
#### イージング関数
| 関数 | 説明 |
|---|---|
| `anim.ease_in(t)` | 2 次イーズイン(`t^2`) |
| `anim.ease_out(t)` | 2 次イーズアウト(`1 - (1-t)^2`) |
| `anim.ease_in_out(t)` | 2 次イーズインアウト |
| `anim.elastic(t)` | 弾性イーズアウト(`t` は 0〜1 にクランプ) |
| `anim.back(t)` | バックイーズアウト(定数 c1 = 1.70158) |
| `anim.bounce(t)` | バウンスイーズアウト(`t` は 0〜1 にクランプ) |
| `anim.bezier(t, p0, p1, p2, p3)` | 3 次ベジェ補間(`t` は 0〜1 にクランプ) |
#### 色変換関数
| 関数 | 戻り値 | 説明 |
|---|---|---|
| `anim.hsv_to_rgb(h, s, v)` | `r, g, b` | HSV を RGB(0〜255)に変換。色相 `h` は 0〜360。 |
| `anim.rgb_to_hsv(r, g, b)` | `h, s, v` | RGB(0〜255)を HSV に変換。色相 `h` は 0〜360。 |
#### 2D ベクトル演算関数
| 関数 | 戻り値 | 説明 |
|---|---|---|
| `anim.len(x, y)` | `double` | ベクトルの長さ |
| `anim.dist(x1, y1, x2, y2)` | `double` | 2 点間の距離 |
| `anim.dot(x1, y1, x2, y2)` | `double` | 内積 |
| `anim.normalize(x, y)` | `x, y` | 正規化。長さが 0 の場合は `(0, 0)` を返却します。 |
| `anim.polar(r, a)` | `x, y` | 極座標(半径 `r`・角度 `a` 度)を直交座標へ変換 |
| `anim.rotate(x, y, a)` | `x, y` | ベクトルを `a` 度回転 |
#### ノイズ・乱数関数
| 関数 | 戻り値 | 説明 |
|---|---|---|
| `anim.noise(x [, y [, z]])` | `double` | 値域 0〜1 の 1〜3 次元スムースノイズ(格子点ハッシュによる補間) |
| `anim.rand([max, ] seed)` | `double` | シードベースの決定論的乱数。引数 1 個でシードのみ、2 個で `[0, max]`、3 個で `[min, max]` |
---
### 8. スクリプト API(ymm4 テーブル)
`ymm4` テーブルは YMM4 固有の情報を提供します。
| メンバー | 型 | 説明 |
|---|---|---|
| `ymm4.group_index` | `int` | エフェクトグループ内のインデックス |
| `ymm4.group_count` | `int` | エフェクトグループの総数 |
| `ymm4.group_ratio` | `double` | `group_index / group_count`(0 除算時は 0) |
| `ymm4.timeline_totalframe` | `int` | タイムライン全体の総フレーム数 |
| `ymm4.timeline_totaltime` | `double` | タイムライン全体の総時間(秒) |
| `ymm4.is_saving` | `bool` | エクスポート中かどうか |
| `ymm4.time_ratio` | `double` | アイテム内の時間比率(Frame / TotalFrame) |
| `ymm4.is_playing` | `bool` | 再生中かどうか |
| `ymm4.is_paused` | `bool` | 一時停止中かどうか |
| `ymm4.scene_id` | `string` | シーン ID(GUID 文字列) |
---
### 9. ピクセルデータプロキシ(PixelDataProxy)
`PixelDataProxy` は `[MoonSharpUserData]` 属性を持つ内部クラスで、
`obj.getpixeldata()` の戻り値として Lua から直接操作できます。
- `width`・`height`:画像の幅と高さを返却する読み取り専用メンバーです。
- `get(index)`:1 始まりのフラットインデックスでチャンネルデータを取得します。
チャンネル順は `R, G, B, A` の 4 チャンネルで 1 ピクセルを構成し、
`R`・`G`・`B` はプリマルチプライ済みからストレートアルファに復元した 0〜255 の値、
`A` は 0〜255 のアルファ値を返却します。
- `set(index, value)`:1 始まりのフラットインデックスでチャンネルデータを書き込みます。
`R`・`G`・`B` チャンネルはストレートアルファの値をプリマルチプライ済みに変換して格納します。
`A` チャンネルを変更すると、既存の RGB 成分を新旧アルファ比でスケーリングして整合させます。
---
### 10. コードエディター拡張
#### LuaFoldingStrategy
AvalonEdit 向けの折り畳み戦略を実装します。
`function`・`do`・`if` / `end` ブロックと `repeat` / `until` ブロックを対象に
複数行にまたがるブロックの折り畳み領域を生成します。
複数行コメント(`--[[ ... ]]`)・文字列リテラル・単行コメントを正規表現でトークン化し、
ブロック開閉を誤認しないよう除外します。
#### LuaAutoCompletionStrategy
AvalonEdit 向けのオートコンプリート戦略を実装します。
提供する補完候補は以下のとおりです。
- Lua キーワード(`and`・`break`・`do`・`else`・`elseif`・`end`・`false`・`for`・
`function`・`goto`・`if`・`in`・`local`・`nil`・`not`・`or`・`repeat`・`return`・
`then`・`true`・`until`・`while`)
- グローバル変数(`time`・`frame`・`totalframe`・`framerate`・`timelineframe`・
`timelinetime`・`layer`・`obj`・`scene`・`anim`・`ymm4`・`math`・`string`・`table`・
`bit32`・`type`・`tostring`・`tonumber`・`select`・`error`・`assert`・`print`・
`ipairs`・`pairs`・`next`・`unpack`・`setmetatable`・`getmetatable`・`rawget`・
`rawset`・`rawequal`・`rawlen`・`pcall`・`xpcall`)
- 各名前空間のメンバー(ドット入力後に絞り込み)
- ソースコード内のユーザー定義関数(`function foo()`・`local function foo()` のパターンを抽出)
---
### 11. ツールバー(LuaScriptToolBar)
コードエディター上部に表示される WPF `UserControl` です。
- インポートボタン:ファイルダイアログで `.lua` ファイルを選択し、
UTF-8 として読み込んでスクリプトに設定します。
- エクスポートボタン:現在のスクリプトを UTF-8 BOM なしで `.lua` ファイルに保存します。
複数選択時は最初のアイテムのスクリプトを保存します。
- クリアボタン:確認ダイアログ後にスクリプトを `DefaultScript` へリセットします。
ファイルアクセスエラーは `IOException`・`UnauthorizedAccessException` を捕捉して
メッセージボックスで通知します。
---
### 12. 例外定義
| クラス | 基底 | 説明 |
|---|---|---|
| `LuaScriptException` | `Exception` | Lua スクリプト例外の基底クラス(内部抽象クラス) |
| `LuaScriptCompilationException` | `LuaScriptException` | 構文エラー時にスローされます。 |
| `LuaScriptRuntimeException` | `LuaScriptException` | 実行時エラーまたはタイムアウト時にスローされます。 |
---
### 13. ローカライズ(Texts)
`Texts` クラスは `[AutoGenLocalizer]` 属性を持つ `partial` クラスとして宣言されます。
`YukkuriMovieMaker.Generator` のソースジェネレーターが `Texts.csv` を処理し、
各ロケールのリソースファイルを自動生成します。
対応言語:日本語 (`ja-jp`)・英語 (`en-us`)・中国語簡体字 (`zh-cn`)・中国語繁体字 (`zh-tw`)・
韓国語 (`ko-kr`)・スペイン語 (`es-es`)・アラビア語 (`ar-sa`)・インドネシア語 (`id-id`)
ローカライズキーの一覧は以下のとおりです。
| キー | ja-jp |
|---|---|
| `LuaScript` | Lua スクリプト |
| `ScriptGroup` | スクリプト |
| `ScriptCode` | スクリプトコード |
| `ScriptCodeDesc` | Lua スクリプトを記述します。obj.x/y/zoom/alpha 等でエフェクトを制御できます。 |
| `ParametersGroup` | パラメータ |
| `Track0` | トラック 0 |
| `Track1` | トラック 1 |
| `Track2` | トラック 2 |
| `Track3` | トラック 3 |
| `TrackDesc` | スライダー値(AviUtl 準拠 track0〜3 に対応) |
| `ToolBarImport` | インポート |
| `ToolBarExport` | エクスポート |
| `ToolBarClear` | クリア |
| `ToolBarClearConfirm` | スクリプトをデフォルトに戻しますか? |
| `ToolBarClearTitle` | 確認 |
| `ToolBarImportErrorTitle` | インポートエラー |
| `ToolBarExportErrorTitle` | エクスポートエラー |
| `LuaFileFilter` | Lua スクリプト (*.lua) \| *.lua \| すべてのファイル (*.*) \| *.* |
## 内部実装
- ネイティブ実行の共有メモリプロトコルに同期コールバックを追加しました。ワーカーは
`obj.getobject` の呼び出し時にタグとフレームを共有メモリへ書き込み、本体側が
シーンオブジェクトを解決して結果を書き戻します。解決したオブジェクトは
描画キャッシュの検証対象に含めるため、フレーム間のキャッシュ整合性は保たれます。
- コールバックを含む実行全体に対して単一の実行期限を適用し、`obj.getobject` を
繰り返し呼び出すスクリプトでもタイムアウトが必ず機能するようにしました。
+32
ファイルの表示
@@ -0,0 +1,32 @@
Lua License
-----------
Lua is licensed under the terms of the MIT license reproduced below. This means
that Lua is free software and can be used for both academic and commercial
purposes at absolutely no cost.
For details and rationale, see https://www.lua.org/license.html .
===============================================================================
Copyright (C) 1994-2025 Lua.org, PUC-Rio.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================================================
+56
ファイルの表示
@@ -0,0 +1,56 @@
===============================================================================
LuaJIT -- a Just-In-Time Compiler for Lua. https://luajit.org/
Copyright (C) 2005-2026 Mike Pall. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
[ MIT license: https://www.opensource.org/licenses/mit-license.php ]
===============================================================================
[ LuaJIT includes code from Lua 5.1/5.2, which has this license statement: ]
Copyright (C) 1994-2012 Lua.org, PUC-Rio.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================================================
[ LuaJIT includes code from dlmalloc, which has this license statement: ]
This is a version (aka dlmalloc) of malloc/free/realloc written by
Doug Lea and released to the public domain, as explained at
https://creativecommons.org/licenses/publicdomain
===============================================================================
+38
ファイルの表示
@@ -0,0 +1,38 @@
Copyright (c) 2014-2016, Marco Mastropaolo
All rights reserved.
Parts of the string library are based on the KopiLua project (https://github.com/NLua/KopiLua)
Copyright (c) 2012 LoDC
Visual Studio Code debugger code is based on code from Microsoft vscode-mono-debug project (https://github.com/Microsoft/vscode-mono-debug).
Copyright (c) Microsoft Corporation - released under MIT license.
Remote Debugger icons are from the Eclipse project (https://www.eclipse.org/).
Copyright of The Eclipse Foundation
The MoonSharp icon is (c) Isaac, 2014-2015
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+1 -1
ファイルの表示
@@ -1,5 +1,5 @@
========================================
Luaスクリプト for YMM4 v1.0.0
Luaスクリプト for YMM4 v1.3.3
========================================
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
ピクセルを直接制御できるプラグインです。
+7
ファイルの表示
@@ -69,9 +69,15 @@ jobs:
$pkgName = "LuaScript_$version.ymme"
New-Item -ItemType Directory -Path "$stageRoot/docs" -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/native" -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
Copy-Item "$outDir/LuaScript.dll" "$stageRoot/"
Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/"
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
Copy-Item "$outDir/native/worker.lua" "$stageRoot/native/"
Copy-Item "$outDir/native/shim.lua" "$stageRoot/native/"
foreach ($lang in @("ar-sa", "en-us", "es-es", "id-id", "ko-kr", "zh-cn", "zh-tw")) {
$src = "$outDir/$lang"
@@ -82,6 +88,7 @@ jobs:
}
Copy-Item "LuaScript/docs/LuaScript.*.txt" "$stageRoot/docs/"
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
+146
ファイルの表示
@@ -0,0 +1,146 @@
namespace LuaScript.Tests
{
public class AnimContractTests
{
private const int Precision = 9;
private readonly MoonSharpLane _lane = new();
private void Eq(double expected, string expression) =>
Assert.Equal(expected, _lane.Number(expression), Precision);
[Fact]
public void Constants()
{
Eq(Math.PI * 2d, "anim.tau");
Eq(Math.E, "anim.e");
Eq((1d + Math.Sqrt(5d)) / 2d, "anim.phi");
Eq(Math.Sqrt(2d), "anim.sqrt2");
}
[Fact]
public void LerpMapNormClamp()
{
Eq(5d, "anim.lerp(0,10,0.5)");
Eq(12.5d, "anim.lerp(10,20,0.25)");
Eq(50d, "anim.map(5,0,10,0,100)");
Eq(0.5d, "anim.norm(5,0,10)");
Eq(1d, "anim.clamp(5,0,1)");
Eq(0d, "anim.clamp(-1,0,1)");
Eq(0.5d, "anim.clamp(0.5,0,1)");
}
[Fact]
public void SmoothSteps()
{
Eq(0.5d, "anim.smoothstep(0,1,0.5)");
Eq(0d, "anim.smoothstep(0,1,0)");
Eq(1d, "anim.smoothstep(0,1,1)");
Eq(0.5d, "anim.smootherstep(0,1,0.5)");
}
[Fact]
public void WrapPingpong()
{
Eq(2d, "anim.wrap(7,0,5)");
Eq(4d, "anim.wrap(-1,0,5)");
Eq(3d, "anim.pingpong(7,5)");
Eq(3d, "anim.pingpong(3,5)");
}
[Fact]
public void Waves()
{
Eq(0.5d, "anim.oscillate(0,0,1,1)");
Eq(0d, "anim.triangle(0,1)");
Eq(0.5d, "anim.triangle(0.25,1)");
Eq(1d, "anim.triangle(0.5,1)");
Eq(0d, "anim.square(0.25,1)");
Eq(1d, "anim.square(0.5,1)");
}
[Fact]
public void Easings()
{
Eq(0.25d, "anim.ease_in(0.5)");
Eq(0.75d, "anim.ease_out(0.5)");
Eq(0.125d, "anim.ease_in_out(0.25)");
Eq(0.875d, "anim.ease_in_out(0.75)");
Eq(0d, "anim.back(0)");
Eq(1d, "anim.back(1)");
Eq(0d, "anim.elastic(0)");
Eq(1d, "anim.elastic(1)");
Eq(0d, "anim.bounce(0)");
}
[Fact]
public void Misc()
{
Eq(-1d, "anim.sign(-5)");
Eq(0d, "anim.sign(0)");
Eq(1d, "anim.sign(3)");
Eq(0.5d, "anim.duration(0.5,1)");
Eq(1d, "anim.duration(2,1)");
Eq(1d, "anim.delay(2,1)");
Eq(0d, "anim.delay(0.5,1)");
Eq(1d, "anim.step(0.5,0.6)");
Eq(0d, "anim.step(0.5,0.4)");
Eq(0.25d, "anim.fract(3.25)");
Eq(0.75d, "anim.fract(-0.25)");
}
[Fact]
public void Vectors()
{
Eq(5d, "anim.len(3,4)");
Eq(5d, "anim.dist(0,0,3,4)");
Eq(11d, "anim.dot(1,2,3,4)");
Eq(0d, "anim.bezier(0,0,1,2,3)");
Eq(3d, "anim.bezier(1,0,1,2,3)");
}
[Fact]
public void TupleFunctions()
{
var rgb = _lane.Tuple("anim.hsv_to_rgb(0,1,1)", 3);
Assert.Equal(255d, rgb[0], Precision);
Assert.Equal(0d, rgb[1], Precision);
Assert.Equal(0d, rgb[2], Precision);
var hsv = _lane.Tuple("anim.rgb_to_hsv(255,0,0)", 3);
Assert.Equal(0d, hsv[0], Precision);
Assert.Equal(1d, hsv[1], Precision);
Assert.Equal(1d, hsv[2], Precision);
var n = _lane.Tuple("anim.normalize(3,4)", 2);
Assert.Equal(0.6d, n[0], Precision);
Assert.Equal(0.8d, n[1], Precision);
var rot = _lane.Tuple("anim.rotate(1,0,90)", 2);
Assert.Equal(0d, rot[0], Precision);
Assert.Equal(1d, rot[1], Precision);
}
[Fact]
public void RandIsDeterministicAndBounded()
{
Assert.Equal(_lane.Number("anim.rand(5)"), _lane.Number("anim.rand(5)"));
Assert.NotEqual(_lane.Number("anim.rand(5)"), _lane.Number("anim.rand(6)"));
for (int seed = 0; seed < 50; seed++)
{
double r = _lane.Number($"anim.rand(10,20,{seed})");
Assert.InRange(r, 10d, 20d);
}
}
[Fact]
public void NoiseIsDeterministicAndBounded()
{
Assert.Equal(_lane.Number("anim.noise(1.5,2.5,0.5)"), _lane.Number("anim.noise(1.5,2.5,0.5)"));
for (double x = 0d; x < 5d; x += 0.37d)
{
double v = _lane.Number($"anim.noise({x.ToString(System.Globalization.CultureInfo.InvariantCulture)})");
Assert.InRange(v, 0d, 1d);
}
}
}
}
+113
ファイルの表示
@@ -0,0 +1,113 @@
using System.Collections.Generic;
using LuaScript.Compat;
namespace LuaScript.Tests
{
public class Bit32CleanTests
{
[Fact]
public void Correct_Lua52_Semantics()
{
Assert.Equal(0xFFFFFFFFu, Bit32.Band(4294967295d, 4294967295d));
Assert.Equal(0xFFFFFFFFu, Bit32.Bnot(0d));
Assert.Equal(2147483648u, Bit32.Lshift(1d, 31d));
Assert.Equal(0u, Bit32.Lshift(1d, 32d));
Assert.Equal(0u, Bit32.Lshift(1d, -1d));
Assert.Equal(1u, Bit32.Rshift(2147483648d, 31d));
Assert.Equal(3221225472u, Bit32.Arshift(2147483648d, 1d));
Assert.Equal(0xFFFFFFFFu, Bit32.Arshift(4294967295d, 40d));
Assert.Equal(2147483648u, Bit32.Lrotate(1d, -1d));
Assert.Equal(1u, Bit32.Lrotate(2147483648d, 1d));
}
[Fact]
public void Correct_Extract_Replace_AllowsFullRange()
{
Assert.Equal(1u, Bit32.Extract(4294967295d, 31, 1));
Assert.Equal(0xFFFFFFFFu, Bit32.Extract(4294967295d, 0, 32));
Assert.Equal(255u, Bit32.Extract(255d, 0, 8));
Assert.Equal(2147483648u, Bit32.Replace(0d, 1d, 31, 1));
}
[Theory]
[InlineData(32, 1)]
[InlineData(0, 33)]
[InlineData(-1, 1)]
[InlineData(0, 0)]
public void Extract_OutOfRange_Throws(int field, int width) =>
Assert.Throws<System.ArgumentException>(() => Bit32.Extract(1d, field, width));
public static readonly double[] SafeValues =
[
0d, 1d, 2d, 255d, 256d, 65535d, 65536d, 16777215d,
1073741824d, 2147483647d,
];
public static readonly int[] SafeShifts = [0, 1, 4, 8, 15, 16, 24, 31];
public static IEnumerable<object[]> SafeBinary()
{
foreach (var a in SafeValues)
foreach (var b in SafeValues)
yield return [a, b];
}
public static IEnumerable<object[]> SafeValueAndShift()
{
foreach (var a in SafeValues)
foreach (var n in SafeShifts)
yield return [a, n];
}
[Theory]
[MemberData(nameof(SafeBinary))]
public void Bitwise_MatchesMoonSharp_OnSafeDomain(double a, double b)
{
Assert.Equal(MoonSharpBit32.Band(a, b), Bit32.Band(a, b));
Assert.Equal(MoonSharpBit32.Bor(a, b), Bit32.Bor(a, b));
Assert.Equal(MoonSharpBit32.Bxor(a, b), Bit32.Bxor(a, b));
Assert.Equal(MoonSharpBit32.Btest(a, b), Bit32.Btest(a, b));
}
[Theory]
[MemberData(nameof(SafeValueAndShift))]
public void Shifts_MatchMoonSharp_OnSafeDomain(double a, int n)
{
Assert.Equal(MoonSharpBit32.Lshift(a, n), Bit32.Lshift(a, n));
Assert.Equal(MoonSharpBit32.Rshift(a, n), Bit32.Rshift(a, n));
Assert.Equal((double)MoonSharpBit32.Arshift(a, n), (double)Bit32.Arshift(a, n));
Assert.Equal(MoonSharpBit32.Lrotate(a, n), Bit32.Lrotate(a, n));
Assert.Equal(MoonSharpBit32.Rrotate(a, n), Bit32.Rrotate(a, n));
}
[Theory]
[InlineData(0, 1)]
[InlineData(0, 8)]
[InlineData(4, 4)]
[InlineData(8, 8)]
[InlineData(0, 16)]
[InlineData(15, 16)]
[InlineData(30, 1)]
public void Extract_MatchesMoonSharp_OnSafeDomain(int field, int width)
{
foreach (var a in SafeValues)
Assert.Equal(MoonSharpBit32.Extract(a, field, width), Bit32.Extract(a, field, width));
}
[Fact]
public void Replace_IsCorrectLua52_ShiftsReplacementIntoField()
{
Assert.Equal(0xF0u, Bit32.Replace(0d, 15d, 4, 4));
Assert.Equal(0x80000000u, Bit32.Replace(0d, 1d, 31, 1));
Assert.Equal(0xABCD0000u, Bit32.Replace(0d, 43981d, 16, 16));
}
[Fact]
public void Replace_DivergesFromMoonSharpBug_ForNonZeroField()
{
Assert.NotEqual((double)MoonSharpBit32.Replace(0d, 15d, 4, 4), (double)Bit32.Replace(0d, 15d, 4, 4));
Assert.Equal(0u, MoonSharpBit32.Replace(0d, 15d, 4, 4));
Assert.Equal(0xF0u, Bit32.Replace(0d, 15d, 4, 4));
}
}
}
+161
ファイルの表示
@@ -0,0 +1,161 @@
using System.Collections.Generic;
using System.Globalization;
using LuaScript.Compat;
using MoonSharp.Interpreter;
namespace LuaScript.Tests
{
public class Bit32EquivalenceTests
{
private static readonly Script Oracle = new(CoreModules.Basic | CoreModules.Math | CoreModules.Bit32);
private static double Eval(string expression) => Oracle.DoString("return " + expression).Number;
private static bool EvalBool(string expression) => Oracle.DoString("return " + expression).Boolean;
private static string Lit(double value) => value.ToString("R", CultureInfo.InvariantCulture);
public static readonly double[] RawInputs =
[
0d, 1d, 2d, 255d, 256d, 65535d, 65536d,
2147483647d, 2147483648d, 4294967295d,
4294967296d, 4294967301d,
-1d, -2d, -256d, -2147483648d,
];
public static readonly int[] Shifts =
[
0, 1, 4, 7, 8, 15, 16, 24, 31, 32, 33, 64,
-1, -4, -8, -16, -31, -32, -33,
];
public static IEnumerable<object[]> Unary()
{
foreach (var a in RawInputs)
yield return [a];
}
public static IEnumerable<object[]> Binary()
{
foreach (var a in RawInputs)
foreach (var b in RawInputs)
yield return [a, b];
}
public static IEnumerable<object[]> ValueAndShift()
{
foreach (var a in RawInputs)
foreach (var n in Shifts)
yield return [a, n];
}
[Theory]
[MemberData(nameof(Binary))]
public void Band(double a, double b) =>
Assert.Equal((double)MoonSharpBit32.Band(a, b), Eval($"bit32.band({Lit(a)},{Lit(b)})"));
[Theory]
[MemberData(nameof(Binary))]
public void Bor(double a, double b) =>
Assert.Equal((double)MoonSharpBit32.Bor(a, b), Eval($"bit32.bor({Lit(a)},{Lit(b)})"));
[Theory]
[MemberData(nameof(Binary))]
public void Bxor(double a, double b) =>
Assert.Equal((double)MoonSharpBit32.Bxor(a, b), Eval($"bit32.bxor({Lit(a)},{Lit(b)})"));
[Theory]
[MemberData(nameof(Binary))]
public void Btest(double a, double b) =>
Assert.Equal(MoonSharpBit32.Btest(a, b), EvalBool($"bit32.btest({Lit(a)},{Lit(b)})"));
[Theory]
[MemberData(nameof(Unary))]
public void Bnot(double a) =>
Assert.Equal((double)MoonSharpBit32.Bnot(a), Eval($"bit32.bnot({Lit(a)})"));
[Theory]
[MemberData(nameof(ValueAndShift))]
public void Lshift(double a, int n) =>
Assert.Equal((double)MoonSharpBit32.Lshift(a, n), Eval($"bit32.lshift({Lit(a)},{n})"));
[Theory]
[MemberData(nameof(ValueAndShift))]
public void Rshift(double a, int n) =>
Assert.Equal((double)MoonSharpBit32.Rshift(a, n), Eval($"bit32.rshift({Lit(a)},{n})"));
[Theory]
[MemberData(nameof(ValueAndShift))]
public void Arshift(double a, int n) =>
Assert.Equal((double)MoonSharpBit32.Arshift(a, n), Eval($"bit32.arshift({Lit(a)},{n})"));
[Theory]
[MemberData(nameof(ValueAndShift))]
public void Lrotate(double a, int n) =>
Assert.Equal((double)MoonSharpBit32.Lrotate(a, n), Eval($"bit32.lrotate({Lit(a)},{n})"));
[Theory]
[MemberData(nameof(ValueAndShift))]
public void Rrotate(double a, int n) =>
Assert.Equal((double)MoonSharpBit32.Rrotate(a, n), Eval($"bit32.rrotate({Lit(a)},{n})"));
[Theory]
[InlineData(0, 1)]
[InlineData(0, 8)]
[InlineData(4, 4)]
[InlineData(8, 8)]
[InlineData(0, 16)]
[InlineData(8, 16)]
[InlineData(0, 31)]
[InlineData(30, 1)]
[InlineData(15, 16)]
public void Extract(int field, int width)
{
foreach (var a in RawInputs)
Assert.Equal(
(double)MoonSharpBit32.Extract(a, field, width),
Eval($"bit32.extract({Lit(a)},{field},{width})"));
}
[Theory]
[InlineData(0, 1)]
[InlineData(0, 8)]
[InlineData(4, 4)]
[InlineData(8, 8)]
[InlineData(0, 16)]
[InlineData(8, 16)]
[InlineData(0, 31)]
[InlineData(30, 1)]
[InlineData(15, 16)]
public void Replace(int field, int width)
{
foreach (var a in RawInputs)
foreach (var v in RawInputs)
Assert.Equal(
(double)MoonSharpBit32.Replace(a, v, field, width),
Eval($"bit32.replace({Lit(a)},{Lit(v)},{field},{width})"));
}
[Theory]
[InlineData(31, 1)]
[InlineData(16, 16)]
[InlineData(0, 32)]
[InlineData(32, 0)]
public void Extract_OutOfRange_BothReject(int field, int width)
{
Assert.ThrowsAny<Exception>(() => MoonSharpBit32.Extract(1d, field, width));
Assert.ThrowsAny<ScriptRuntimeException>(() => Eval($"bit32.extract(1,{field},{width})"));
}
[Theory]
[InlineData(31, 1)]
[InlineData(16, 16)]
[InlineData(0, 32)]
[InlineData(32, 0)]
public void Replace_OutOfRange_BothReject(int field, int width)
{
Assert.ThrowsAny<Exception>(() => MoonSharpBit32.Replace(1d, 1d, field, width));
Assert.ThrowsAny<ScriptRuntimeException>(() => Eval($"bit32.replace(1,1,{field},{width})"));
}
}
}
+48
ファイルの表示
@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace LuaScript.Tests
{
internal sealed class LuaJitLane
{
private readonly string _nativeDir = Path.Combine(AppContext.BaseDirectory, "native");
public bool Available => File.Exists(Path.Combine(_nativeDir, "luajit.exe"));
public string[] Eval(IReadOnlyList<string> expressions)
{
string vectors = Path.GetTempFileName();
File.WriteAllLines(vectors, expressions);
try
{
var psi = new ProcessStartInfo
{
FileName = Path.Combine(_nativeDir, "luajit.exe"),
WorkingDirectory = _nativeDir,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
psi.ArgumentList.Add("runner.lua");
psi.ArgumentList.Add(Path.Combine(_nativeDir, "shim.lua"));
psi.ArgumentList.Add(vectors);
using var process = Process.Start(psi)
?? throw new InvalidOperationException("Failed to start luajit.exe");
string stdout = process.StandardOutput.ReadToEnd();
string stderr = process.StandardError.ReadToEnd();
process.WaitForExit();
if (process.ExitCode != 0)
throw new InvalidOperationException("luajit exited " + process.ExitCode + ": " + stderr);
return stdout.Replace("\r\n", "\n").Split('\n');
}
finally
{
File.Delete(vectors);
}
}
}
}
+37
ファイルの表示
@@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="MoonSharp" Version="2.0.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<None Include="..\native\**" CopyToOutputDirectory="PreserveNewest" LinkBase="native" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\LuaScript\Compat\MoonSharpBit32.cs" Link="Linked\MoonSharpBit32.cs" />
<Compile Include="..\LuaScript\Compat\Bit32.cs" Link="Linked\Bit32.cs" />
<Compile Include="..\LuaScript\Engine\ScriptEngineKind.cs" Link="Linked\ScriptEngineKind.cs" />
<Compile Include="..\LuaScript\Engine\NativeProtocol.cs" Link="Linked\NativeProtocol.cs" />
<Compile Include="..\LuaScript\Engine\ProcessJobObject.cs" Link="Linked\ProcessJobObject.cs" />
<Compile Include="..\LuaScript\Engine\LuaJitWorker.cs" Link="Linked\LuaJitWorker.cs" />
<Compile Include="..\LuaScript\SceneObjectInfo.cs" Link="Linked\SceneObjectInfo.cs" />
<Compile Include="..\LuaScript\AnimTableRegistrar.cs" Link="Linked\AnimTableRegistrar.cs" />
</ItemGroup>
</Project>
+46
ファイルの表示
@@ -0,0 +1,46 @@
using LuaScript;
using MoonSharp.Interpreter;
namespace LuaScript.Tests
{
internal sealed class MoonSharpLane
{
private readonly Script _script;
public MoonSharpLane()
{
_script = new Script(
CoreModules.Basic |
CoreModules.Math |
CoreModules.String |
CoreModules.Table |
CoreModules.Bit32 |
CoreModules.TableIterators |
CoreModules.Metatables |
CoreModules.ErrorHandling);
var anim = new Table(_script);
AnimTableRegistrar.RegisterFunctions(anim);
_script.Globals["anim"] = anim;
}
public DynValue Run(string code) => _script.DoString(code);
public double Number(string expression) => Run("return " + expression).Number;
public bool Boolean(string expression) => Run("return " + expression).Boolean;
public string? Text(string expression) => Run("return " + expression).CastToString();
public DataType Type(string expression) => Run("return " + expression).Type;
public double[] Tuple(string expression, int count)
{
var table = Run("return {" + expression + "}").Table;
var result = new double[count];
for (int i = 0; i < count; i++)
result[i] = table.Get(i + 1).Number;
return result;
}
}
}
+133
ファイルの表示
@@ -0,0 +1,133 @@
using System;
using System.Collections.Generic;
using System.Globalization;
namespace LuaScript.Tests
{
public class NativeAnimEquivalenceTests
{
private readonly MoonSharpLane _oracle = new();
[Fact]
public void Anim_MatchesBetweenMoonSharpAndLuaJit()
{
var lane = new LuaJitLane();
Assert.True(lane.Available, "native/luajit.exe must be present");
var exprs = new List<string>();
void Add(string e) => exprs.Add(e);
void Tuple(string call, int n)
{
for (int k = 1; k <= n; k++)
exprs.Add($"({{{call}}})[{k}]");
}
Add("anim.tau"); Add("anim.e"); Add("anim.phi"); Add("anim.sqrt2");
foreach (var (a, b, t) in new[] { (0d, 10d, 0.5d), (10d, 20d, 0.25d), (-5d, 5d, 0.75d), (100d, -100d, 0.1d) })
Add($"anim.lerp({L(a)},{L(b)},{L(t)})");
foreach (var (e0, e1, x) in new[] { (0d, 1d, 0.5d), (0d, 1d, 0.3d), (2d, 4d, 3d), (0d, 1d, -1d), (0d, 1d, 2d) })
{
Add($"anim.smoothstep({L(e0)},{L(e1)},{L(x)})");
Add($"anim.smootherstep({L(e0)},{L(e1)},{L(x)})");
}
foreach (var (v, lo, hi) in new[] { (5d, 0d, 1d), (-1d, 0d, 1d), (0.5d, 0d, 1d), (7d, 2d, 9d) })
{
Add($"anim.clamp({L(v)},{L(lo)},{L(hi)})");
Add($"anim.norm({L(v)},{L(lo)},{L(hi)})");
}
Add("anim.map(5,0,10,0,100)"); Add("anim.map(0.5,0,1,-1,1)");
foreach (var (v, lo, hi) in new[] { (7d, 0d, 5d), (-1d, 0d, 5d), (12d, 2d, 8d), (-7d, -3d, 3d) })
Add($"anim.wrap({L(v)},{L(lo)},{L(hi)})");
foreach (var (t, len) in new[] { (7d, 5d), (3d, 5d), (0d, 5d), (13d, 5d), (-2d, 5d) })
Add($"anim.pingpong({L(t)},{L(len)})");
foreach (var v in new[] { -5d, 0d, 3d, 0.1d, -0.1d })
Add($"anim.sign({L(v)})");
Add("anim.oscillate(0,0,1,1)"); Add("anim.oscillate(0.25,0,1,1)"); Add("anim.oscillate(1,0,10,2)");
foreach (var (t, f) in new[] { (0d, 1d), (0.25d, 1d), (0.5d, 1d), (0.75d, 1d), (1.3d, 2d) })
{
Add($"anim.triangle({L(t)},{L(f)})");
Add($"anim.square({L(t)},{L(f)})");
}
foreach (var (t, d) in new[] { (0.5d, 1d), (2d, 1d), (0d, 1d), (0.3d, 2d) })
Add($"anim.duration({L(t)},{L(d)})");
foreach (var (t, d) in new[] { (2d, 1d), (0.5d, 1d), (3d, 0.5d) })
Add($"anim.delay({L(t)},{L(d)})");
foreach (var t in new[] { 0d, 0.25d, 0.5d, 0.75d, 1d, 0.1d })
{
Add($"anim.ease_in({L(t)})");
Add($"anim.ease_out({L(t)})");
Add($"anim.ease_in_out({L(t)})");
Add($"anim.elastic({L(t)})");
Add($"anim.back({L(t)})");
Add($"anim.bounce({L(t)})");
Add($"anim.fract({L(t + 3d)})");
}
Add("anim.step(0.5,0.6)"); Add("anim.step(0.5,0.4)"); Add("anim.step(0.5,0.5)");
Add("anim.bezier(0,0,1,2,3)"); Add("anim.bezier(1,0,1,2,3)"); Add("anim.bezier(0.5,0,0.3,0.7,1)");
Add("anim.len(3,4)"); Add("anim.len(1,1)");
Add("anim.dist(0,0,3,4)"); Add("anim.dist(1,1,4,5)");
Add("anim.dot(1,2,3,4)"); Add("anim.dot(0,0,1,1)");
foreach (var (h, s, v) in new[] { (0d, 1d, 1d), (120d, 1d, 1d), (240d, 0.5d, 0.8d), (60d, 1d, 1d), (300d, 0.7d, 0.9d) })
Tuple($"anim.hsv_to_rgb({L(h)},{L(s)},{L(v)})", 3);
foreach (var (r, g, b) in new[] { (255d, 0d, 0d), (0d, 255d, 0d), (0d, 0d, 255d), (128d, 128d, 128d), (200d, 100d, 50d) })
Tuple($"anim.rgb_to_hsv({L(r)},{L(g)},{L(b)})", 3);
foreach (var (x, y) in new[] { (3d, 4d), (-1d, 1d), (5d, 0d) })
Tuple($"anim.normalize({L(x)},{L(y)})", 2);
foreach (var (r, a) in new[] { (1d, 0d), (1d, 90d), (2d, 45d) })
Tuple($"anim.polar({L(r)},{L(a)})", 2);
foreach (var (x, y, a) in new[] { (1d, 0d, 90d), (1d, 0d, 45d), (0d, 1d, 180d) })
Tuple($"anim.rotate({L(x)},{L(y)},{L(a)})", 2);
for (int seed = 0; seed < 12; seed++)
{
Add($"anim.rand({seed})");
Add($"anim.rand(10,20,{seed})");
Add($"anim.rand(-3,3,{seed * 7 + 1})");
}
foreach (var x in new[] { 0.3d, 1.5d, 2.7d, 5.1d, -1.2d })
{
Add($"anim.noise({L(x)})");
Add($"anim.noise({L(x)},{L(x + 0.5d)})");
Add($"anim.noise({L(x)},{L(x + 0.5d)},{L(x - 0.3d)})");
}
var expected = new double[exprs.Count];
for (int i = 0; i < exprs.Count; i++)
expected[i] = _oracle.Number(exprs[i]);
string[] lines = lane.Eval(exprs);
Assert.Equal(exprs.Count, lines.Length);
var failures = new List<string>();
for (int i = 0; i < exprs.Count; i++)
{
if (!double.TryParse(lines[i], NumberStyles.Float, CultureInfo.InvariantCulture, out var got))
{
failures.Add($"{exprs[i]} => luajit '{lines[i]}' (not a number), expected {expected[i]}");
continue;
}
double tol = 1e-9 * Math.Max(1d, Math.Abs(expected[i]));
if (Math.Abs(got - expected[i]) > tol)
failures.Add($"{exprs[i]} => luajit {got}, moonsharp {expected[i]}");
}
Assert.True(failures.Count == 0,
$"{failures.Count}/{exprs.Count} mismatches:\n" + string.Join("\n", failures.GetRange(0, Math.Min(25, failures.Count))));
}
private static string L(double value) => value.ToString("R", CultureInfo.InvariantCulture);
}
}
+108
ファイルの表示
@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using LuaScript.Compat;
namespace LuaScript.Tests
{
public class NativeBit32EquivalenceTests
{
private static readonly double[] Values =
[
0d, 1d, 2d, 255d, 256d, 65535d, 65536d,
2147483647d, 2147483648d, 4294967295d,
4294967296d, 4294967301d,
-1d, -2d, -256d, -2147483648d,
];
private static readonly int[] Shifts =
[
0, 1, 4, 7, 8, 15, 16, 24, 31, 32, 33, 64,
-1, -4, -8, -16, -31, -32, -33,
];
private static readonly (int Field, int Width)[] ValidFields =
[
(0, 1), (0, 8), (4, 4), (8, 8), (0, 16), (15, 16), (30, 1), (0, 31), (0, 32),
];
private static readonly (int Field, int Width)[] InvalidFields =
[
(32, 1), (0, 33), (-1, 1), (0, 0),
];
private static string Lit(double value) => value.ToString("R", CultureInfo.InvariantCulture);
[Fact]
public void CorrectBit32_MatchesAcrossMoonSharpAndLuaJit()
{
var lane = new LuaJitLane();
Assert.True(lane.Available, "native/luajit.exe must be present");
var exprs = new List<string>();
var expects = new List<object>();
void Num(string e, double v) { exprs.Add(e); expects.Add(v); }
void Bool(string e, bool v) { exprs.Add(e); expects.Add(v); }
void Err(string e) { exprs.Add(e); expects.Add("ERROR"); }
foreach (var a in Values)
{
Num($"bit32.bnot({Lit(a)})", Bit32.Bnot(a));
foreach (var b in Values)
{
Num($"bit32.band({Lit(a)},{Lit(b)})", Bit32.Band(a, b));
Num($"bit32.bor({Lit(a)},{Lit(b)})", Bit32.Bor(a, b));
Num($"bit32.bxor({Lit(a)},{Lit(b)})", Bit32.Bxor(a, b));
Bool($"bit32.btest({Lit(a)},{Lit(b)})", Bit32.Btest(a, b));
}
foreach (var n in Shifts)
{
Num($"bit32.lshift({Lit(a)},{n})", Bit32.Lshift(a, n));
Num($"bit32.rshift({Lit(a)},{n})", Bit32.Rshift(a, n));
Num($"bit32.arshift({Lit(a)},{n})", Bit32.Arshift(a, n));
Num($"bit32.lrotate({Lit(a)},{n})", Bit32.Lrotate(a, n));
Num($"bit32.rrotate({Lit(a)},{n})", Bit32.Rrotate(a, n));
}
foreach (var (field, width) in ValidFields)
{
Num($"bit32.extract({Lit(a)},{field},{width})", Bit32.Extract(a, field, width));
foreach (var v in Values)
Num($"bit32.replace({Lit(a)},{Lit(v)},{field},{width})", Bit32.Replace(a, v, field, width));
}
foreach (var (field, width) in InvalidFields)
{
Err($"bit32.extract({Lit(a)},{field},{width})");
Err($"bit32.replace({Lit(a)},1,{field},{width})");
}
}
string[] lines = lane.Eval(exprs);
Assert.Equal(exprs.Count, lines.Length);
var failures = new List<string>();
for (int i = 0; i < exprs.Count; i++)
{
string actual = lines[i];
switch (expects[i])
{
case double d:
if (!double.TryParse(actual, NumberStyles.Float, CultureInfo.InvariantCulture, out var got) || got != d)
failures.Add($"{exprs[i]} => luajit '{actual}', expected {d}");
break;
case bool b:
if (actual != (b ? "true" : "false"))
failures.Add($"{exprs[i]} => luajit '{actual}', expected {b}");
break;
case string s:
if (actual != s)
failures.Add($"{exprs[i]} => luajit '{actual}', expected {s}");
break;
}
}
Assert.True(failures.Count == 0,
$"{failures.Count}/{exprs.Count} mismatches:\n" + string.Join("\n", failures.GetRange(0, Math.Min(20, failures.Count))));
}
}
}
+78
ファイルの表示
@@ -0,0 +1,78 @@
using System;
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
namespace LuaScript.Tests
{
public class NativeSharedMemoryTests
{
private static string NativeDir => Path.Combine(AppContext.BaseDirectory, "native");
[Fact]
public void Worker_ProcessesSharedBgraBuffer_ViaFfi()
{
string luajit = Path.Combine(NativeDir, "luajit.exe");
Assert.True(File.Exists(luajit), "native/luajit.exe must be present");
const int width = 8;
const int height = 8;
const int pixels = width * height;
long size = pixels * 4L;
string mapName = "LuaScriptShmPoC_" + Guid.NewGuid().ToString("N");
using var mmf = MemoryMappedFile.CreateNew(mapName, size);
var expectedGray = new byte[pixels];
using (var acc = mmf.CreateViewAccessor())
{
for (int i = 0; i < pixels; i++)
{
byte b = (byte)(i * 3 % 256);
byte g = (byte)(i * 5 % 256);
byte r = (byte)(i * 7 % 256);
acc.Write(i * 4 + 0, b);
acc.Write(i * 4 + 1, g);
acc.Write(i * 4 + 2, r);
acc.Write(i * 4 + 3, (byte)255);
expectedGray[i] = (byte)Math.Min(255, (int)Math.Floor(r * 0.299 + g * 0.587 + b * 0.114 + 0.5));
}
}
var psi = new ProcessStartInfo
{
FileName = luajit,
WorkingDirectory = NativeDir,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
psi.ArgumentList.Add("worker_grayscale.lua");
psi.ArgumentList.Add(mapName);
psi.ArgumentList.Add(size.ToString());
using var process = Process.Start(psi)!;
string stdout = process.StandardOutput.ReadToEnd();
string stderr = process.StandardError.ReadToEnd();
Assert.True(process.WaitForExit(5000), "worker should finish quickly");
Assert.Equal(0, process.ExitCode);
Assert.Equal("done", stdout);
Assert.Equal("", stderr);
using (var acc = mmf.CreateViewAccessor())
{
for (int i = 0; i < pixels; i++)
{
byte b = acc.ReadByte(i * 4 + 0);
byte g = acc.ReadByte(i * 4 + 1);
byte r = acc.ReadByte(i * 4 + 2);
byte a = acc.ReadByte(i * 4 + 3);
Assert.Equal(expectedGray[i], b);
Assert.Equal(expectedGray[i], g);
Assert.Equal(expectedGray[i], r);
Assert.Equal(255, a);
}
}
}
}
}
+233
ファイルの表示
@@ -0,0 +1,233 @@
using System;
using System.IO;
using LuaScript.Engine;
namespace LuaScript.Tests
{
public class NativeWorkerRoundTripTests : IDisposable
{
private static string NativeDir => Path.Combine(AppContext.BaseDirectory, "native");
private static readonly Func<string, int, SceneObjectInfo?> NoResolver = (_, _) => null;
private readonly LuaJitWorker _worker = new(NativeDir);
public void Dispose() => _worker.Dispose();
private static double[] Fields(int w, int h, double time)
{
var f = new double[NativeProtocol.FieldCount];
f[NativeProtocol.W] = w;
f[NativeProtocol.H] = h;
f[NativeProtocol.Time] = time;
f[NativeProtocol.Alpha] = 255d;
return f;
}
[Fact]
public void TransformScript_WritesBackObjFields()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var fields = Fields(4, 4, 2d);
var pixels = new byte[4 * 4 * 4];
bool ok = _worker.Execute(
"obj.rz = obj.time * 90\nobj.alpha = 128",
fields, pixels, 4, 4, 5000, NoResolver, out bool dirty, out string? error);
Assert.True(ok, error);
Assert.False(dirty);
Assert.Equal(180d, fields[NativeProtocol.Rz]);
Assert.Equal(128d, fields[NativeProtocol.Alpha]);
}
[Fact]
public void PixelScript_MatchesExpectedGrayscale()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
void SetBgra(int i, byte b, byte g, byte r, byte a)
{
pixels[i * 4 + 0] = b; pixels[i * 4 + 1] = g; pixels[i * 4 + 2] = r; pixels[i * 4 + 3] = a;
}
SetBgra(0, 10, 20, 30, 255);
SetBgra(1, 0, 0, 0, 0);
SetBgra(2, 50, 100, 200, 128);
SetBgra(3, 255, 255, 255, 255);
var expected = (byte[])pixels.Clone();
for (int i = 0; i < w * h; i++)
Grayscale(expected, i);
var fields = Fields(w, h, 0d);
const string script =
"for y=0,obj.h-1 do for x=0,obj.w-1 do " +
"local r,g,b,a = obj.getpixel(x,y) " +
"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, pixels, w, h, 5000, NoResolver, out bool dirty, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(expected, pixels);
}
[Fact]
public void PixelDataProxy_MatchesExpectedGrayscale()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
void SetBgra(int i, byte b, byte g, byte r, byte a)
{
pixels[i * 4 + 0] = b; pixels[i * 4 + 1] = g; pixels[i * 4 + 2] = r; pixels[i * 4 + 3] = a;
}
SetBgra(0, 10, 20, 30, 255);
SetBgra(1, 0, 0, 0, 0);
SetBgra(2, 50, 100, 200, 128);
SetBgra(3, 255, 255, 255, 255);
var expected = (byte[])pixels.Clone();
for (int i = 0; i < w * h; i++)
Grayscale(expected, i);
var fields = Fields(w, h, 0d);
const string script =
"local pd = obj.getpixeldata() local w,h = pd.width, pd.height " +
"for y=0,h-1 do for x=0,w-1 do local base=(y*w+x)*4 " +
"local r=pd:get(base+1) local g=pd:get(base+2) local b=pd:get(base+3) " +
"local 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, pixels, w, h, 5000, NoResolver, out bool dirty, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(expected, pixels);
}
private static void Grayscale(byte[] px, int i)
{
double b = px[i * 4 + 0], g = px[i * 4 + 1], r = px[i * 4 + 2], a = px[i * 4 + 3];
double sr, sg, sb;
if (a <= 0d) { sr = sg = sb = 0d; }
else
{
double s = 255d / a;
sr = Math.Clamp(r * s, 0d, 255d);
sg = Math.Clamp(g * s, 0d, 255d);
sb = Math.Clamp(b * s, 0d, 255d);
}
double gray = sr * 0.299 + sg * 0.587 + sb * 0.114;
double aK = Math.Clamp(a, 0d, 255d) / 255d;
px[i * 4 + 0] = (byte)Math.Floor(Math.Clamp(gray * aK, 0d, 255d));
px[i * 4 + 1] = (byte)Math.Floor(Math.Clamp(gray * aK, 0d, 255d));
px[i * 4 + 2] = (byte)Math.Floor(Math.Clamp(gray * aK, 0d, 255d));
px[i * 4 + 3] = (byte)Math.Floor(Math.Clamp(a, 0d, 255d));
}
[Fact]
public void PersistentWorker_HandlesMultipleCalls()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
for (int k = 1; k <= 5; k++)
{
var fields = Fields(2, 2, k);
bool ok = _worker.Execute("obj.x = obj.time * 10", fields, pixels, 2, 2, 5000, NoResolver, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(k * 10d, fields[NativeProtocol.X]);
}
}
[Fact]
public void Timeout_KillsWorker_AndRecovers()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
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, pixels, 2, 2, 1500, NoResolver, 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, pixels, 2, 2, 5000, NoResolver, out _, out error);
Assert.True(ok, error);
Assert.Equal(3d, fields2[NativeProtocol.X]);
}
[Fact]
public void GetObject_ResolvesThroughCallback()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
var resolved = new SceneObjectInfo("a", true, 12d, 34d, 56d, 2d, 90d, 200d, 7);
Func<string, int, SceneObjectInfo?> resolver = (tag, frame) =>
tag == "a" && frame == 5 ? resolved : null;
const string script =
"local o = obj.getobject(\"a\", 5) " +
"obj.x = o.x obj.y = o.y obj.z = o.z " +
"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, pixels, 2, 2, 5000, resolver, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(12d, fields[NativeProtocol.X]);
Assert.Equal(34d, fields[NativeProtocol.Y]);
Assert.Equal(56d, fields[NativeProtocol.Z]);
Assert.Equal(2d, fields[NativeProtocol.Zoom]);
Assert.Equal(90d, fields[NativeProtocol.Rz]);
Assert.Equal(200d, fields[NativeProtocol.Alpha]);
Assert.Equal(2d, fields[NativeProtocol.Sx]);
Assert.Equal(90d * Math.PI / 180d, fields[NativeProtocol.Rzr]);
}
[Fact]
public void GetObject_ReturnsNil_WhenUnresolved()
{
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 =
"local o = obj.getobject(\"missing\") obj.x = o == nil and 1 or 0";
bool ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, NoResolver, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(1d, fields[NativeProtocol.X]);
}
[Fact]
public void RuntimeError_IsReported_AndWorkerSurvives()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
bool ok = _worker.Execute("obj.x = missing.value", fields, pixels, 2, 2, 5000, NoResolver, 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, pixels, 2, 2, 5000, NoResolver, out _, out error);
Assert.True(ok2, error);
Assert.Equal(7d, fields2[NativeProtocol.X]);
}
}
}
+52
ファイルの表示
@@ -0,0 +1,52 @@
using System;
using System.Diagnostics;
using System.IO;
namespace LuaScript.Tests
{
public class NativeWorkerTimeoutTests
{
private static string LuaJit => Path.Combine(AppContext.BaseDirectory, "native", "luajit.exe");
private static Process Launch(string inlineScript)
{
var psi = new ProcessStartInfo
{
FileName = LuaJit,
WorkingDirectory = Path.GetDirectoryName(LuaJit)!,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
psi.ArgumentList.Add("-e");
psi.ArgumentList.Add(inlineScript);
return Process.Start(psi) ?? throw new InvalidOperationException("failed to start luajit");
}
[Fact]
public void JitCompiledInfiniteLoop_IsHardKilledWithinTimeout_AndHostRecovers()
{
Assert.True(File.Exists(LuaJit), "native/luajit.exe must be present");
const int timeoutMs = 1500;
using (var hung = Launch("local x=0 for i=1,1e9 do for j=1,1e9 do x=x+1 end end"))
{
bool exitedOnItsOwn = hung.WaitForExit(timeoutMs);
Assert.False(exitedOnItsOwn, "the hot loop should still be running at the timeout");
var sw = Stopwatch.StartNew();
hung.Kill(entireProcessTree: true);
Assert.True(hung.WaitForExit(2000), "the process must terminate promptly after Kill");
sw.Stop();
Assert.True(sw.ElapsedMilliseconds < 2000, "kill should take effect quickly");
}
using var ok = Launch("io.write('recovered')");
string output = ok.StandardOutput.ReadToEnd();
Assert.True(ok.WaitForExit(5000), "a fresh worker must run after the previous was killed");
Assert.Equal(0, ok.ExitCode);
Assert.Equal("recovered", output);
}
}
}
+85
ファイルの表示
@@ -0,0 +1,85 @@
using MoonSharp.Interpreter;
namespace LuaScript.Tests
{
public class RawAndBasicTests
{
private readonly MoonSharpLane _lane = new();
[Fact]
public void RawLen_Table() => Assert.Equal(3d, _lane.Number("rawlen({10,20,30})"));
[Fact]
public void RawLen_String() => Assert.Equal(5d, _lane.Number("rawlen('hello')"));
[Fact]
public void RawEqual_SameReference()
{
Assert.True(_lane.Boolean("(function() local t={} return rawequal(t,t) end)()"));
Assert.False(_lane.Boolean("rawequal({},{})"));
}
[Fact]
public void RawGetSet_BypassMetatable()
{
Assert.Equal(7d, _lane.Number(
"(function() local t=setmetatable({},{__index=function() return 99 end}) rawset(t,'k',7) return rawget(t,'k') end)()"));
Assert.Equal(99d, _lane.Number(
"(function() local t=setmetatable({},{__index=function() return 99 end}) return t.missing end)()"));
}
[Fact]
public void Select_Count() => Assert.Equal(3d, _lane.Number("select('#', 'a', 'b', 'c')"));
[Fact]
public void Select_Index() => Assert.Equal(20d, _lane.Number("(select(2, 10, 20, 30))"));
[Theory]
[InlineData("type(1)", "number")]
[InlineData("type('x')", "string")]
[InlineData("type({})", "table")]
[InlineData("type(nil)", "nil")]
[InlineData("type(true)", "boolean")]
[InlineData("type(print)", "function")]
public void Type_Names(string expression, string expected) =>
Assert.Equal(expected, _lane.Text(expression));
[Theory]
[InlineData("tonumber('42')", 42d)]
[InlineData("tonumber('10', 2)", 2d)]
[InlineData("tonumber('ff', 16)", 255d)]
public void ToNumber_Parsing(string expression, double expected) =>
Assert.Equal(expected, _lane.Number(expression));
[Fact]
public void ToNumber_InvalidIsNil() =>
Assert.Equal(DataType.Nil, _lane.Type("tonumber('not a number')"));
[Fact]
public void ToNumber_HexStringPrefix_IsNil_MoonSharpDivergence() =>
Assert.Equal(DataType.Nil, _lane.Type("tonumber('0x1F')"));
[Fact]
public void Unpack_Global() =>
Assert.Equal(6d, _lane.Number("(function() local a,b,c = unpack({1,2,3}) return a+b+c end)()"));
[Fact]
public void Pcall_CapturesError() =>
Assert.False(_lane.Boolean("(function() local ok = pcall(function() error('boom') end) return ok end)()"));
[Fact]
public void Pcall_SuccessReturnsTrue() =>
Assert.True(_lane.Boolean("(function() local ok = pcall(function() return 1 end) return ok end)()"));
[Fact]
public void StringFormat_Basic() =>
Assert.Equal("a=5 b=2.50", _lane.Text("string.format('a=%d b=%.2f', 5, 2.5)"));
[Fact]
public void MathFloorCeil()
{
Assert.Equal(3d, _lane.Number("math.floor(3.7)"));
Assert.Equal(4d, _lane.Number("math.ceil(3.2)"));
}
}
}
+45
ファイルの表示
@@ -0,0 +1,45 @@
using LuaScript.Engine;
namespace LuaScript.Tests
{
public class ScriptDirectiveTests
{
[Theory]
[InlineData(null, "MoonSharp")]
[InlineData("", "MoonSharp")]
[InlineData("obj.rz = time * 90", "MoonSharp")]
[InlineData("--!native", "Native")]
[InlineData("--!gpu", "Gpu")]
[InlineData("--!cpu", "Cpu")]
[InlineData("--!moonsharp", "MoonSharp")]
[InlineData("--! native ", "Native")]
[InlineData("--!NATIVE", "Native")]
[InlineData("\r\n --!gpu\r\nfunction pixel() end", "Gpu")]
[InlineData("-- normal comment\n--!native\nobj.x = 0", "Native")]
[InlineData("--!unknown", "MoonSharp")]
[InlineData("--!native extra", "MoonSharp")]
[InlineData("obj.x=0 --!native", "MoonSharp")]
public void Resolve_ReturnsExpectedEngine(string? script, string expected)
{
Assert.Equal(expected, ScriptDirective.Resolve(script).ToString());
}
[Fact]
public void Resolve_FirstDirectiveWins()
{
Assert.Equal("Native", ScriptDirective.Resolve("--!native\n--!gpu").ToString());
}
[Theory]
[InlineData("obj.rz = time * 90", "MoonSharp")]
[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")]
public void ResolveAuto_RoutesPixelScriptsToNative(string script, string expected)
{
Assert.Equal(expected, ScriptDirective.ResolveAuto(script).ToString());
}
}
}
+1
ファイルの表示
@@ -3,6 +3,7 @@
<Platform Name="Any CPU" />
<Platform Name="x64" />
</Configurations>
<Project Path="LuaScript.Tests/LuaScript.Tests.csproj" />
<Project Path="LuaScript/LuaScript.csproj">
<Platform Solution="*|x64" Project="x64" />
</Project>
+50 -27
ファイルの表示
@@ -2,12 +2,12 @@ namespace LuaScript
{
internal sealed class AviUtlScriptContext
{
public bool IsPlaying { get; init; }
public bool IsPaused { get; init; }
public string SceneId { get; init; } = string.Empty;
public bool IsPlaying { get; set; }
public bool IsPaused { get; set; }
public string SceneId { get; set; } = string.Empty;
public int ImageWidth { get; init; }
public int ImageHeight { get; init; }
public int ImageWidth { get; set; }
public int ImageHeight { get; set; }
public double X { get; set; }
public double Y { get; set; }
@@ -24,34 +24,40 @@ namespace LuaScript
public double Ry { get; set; }
public double Rz { get; set; }
public double Track0 { get; init; }
public double Track1 { get; init; }
public double Track2 { get; init; }
public double Track3 { get; init; }
public double Track0 { get; set; }
public double Track1 { get; set; }
public double Track2 { get; set; }
public double Track3 { get; set; }
public double Time { get; init; }
public int Frame { get; init; }
public int TotalFrame { get; init; }
public double TotalTime { get; init; }
public int Framerate { get; init; }
public int TimelineFrame { get; init; }
public double TimelineTime { get; init; }
public int SceneWidth { get; init; }
public int SceneHeight { get; init; }
public int Layer { get; init; }
public int Index { get; init; }
public int Num { get; init; }
public double Time { get; set; }
public int Frame { get; set; }
public int TotalFrame { get; set; }
public double TotalTime { get; set; }
public int Framerate { get; set; }
public int TimelineFrame { get; set; }
public double TimelineTime { get; set; }
public int SceneWidth { get; set; }
public int SceneHeight { get; set; }
public int Layer { get; set; }
public int Index { get; set; }
public int Num { get; set; }
public Func<SceneObjectResolver>? ResolverProvider { get; set; }
private readonly List<SceneObjectQuery> _objectQueries = [];
public IReadOnlyList<SceneObjectQuery> ObjectQueries => _objectQueries;
public double RxRad => Rx * Math.PI / 180d;
public double RyRad => Ry * Math.PI / 180d;
public double RzRad => Rz * Math.PI / 180d;
public int GroupIndex { get; init; }
public int GroupCount { get; init; }
public int TimelineTotalFrame { get; init; }
public double TimelineTotalTime { get; init; }
public bool IsSaving { get; init; }
public double TimeRatio { get; init; }
public int GroupIndex { get; set; }
public int GroupCount { get; set; }
public int TimelineTotalFrame { get; set; }
public double TimelineTotalTime { get; set; }
public bool IsSaving { get; set; }
public double TimeRatio { get; set; }
private Func<byte[]>? _pixelLoader;
private byte[]? _pixelBuffer;
@@ -62,6 +68,8 @@ namespace LuaScript
internal int TotalChannels => ImageWidth * ImageHeight * 4;
internal void ClearQueries() => _objectQueries.Clear();
internal void SetPixelLoader(Func<byte[]> loader)
{
_pixelLoader = loader;
@@ -81,6 +89,21 @@ namespace LuaScript
internal void MarkPixelsDirty() => _isPixelsDirty = true;
public bool ResolveObject(string tag, int frame, out SceneObjectInfo info)
{
var resolver = ResolverProvider?.Invoke();
if (resolver is not null && resolver.TryResolve(tag, frame, out var resolved))
{
_objectQueries.Add(new SceneObjectQuery(tag, frame, resolved));
info = resolved;
return true;
}
_objectQueries.Add(new SceneObjectQuery(tag, frame, null));
info = default;
return false;
}
public unsafe (double r, double g, double b, double a) GetPixel(int x, int y)
{
EnsurePixelBuffer();
+109
ファイルの表示
@@ -0,0 +1,109 @@
using System;
namespace LuaScript.Compat
{
internal static class Bit32
{
public static uint ToUInt32(double value) => unchecked((uint)(long)value);
public static uint Band(params double[] values)
{
uint accum = 0xFFFFFFFFu;
foreach (var value in values)
accum &= ToUInt32(value);
return accum;
}
public static uint Bor(params double[] values)
{
uint accum = 0u;
foreach (var value in values)
accum |= ToUInt32(value);
return accum;
}
public static uint Bxor(params double[] values)
{
uint accum = 0u;
foreach (var value in values)
accum ^= ToUInt32(value);
return accum;
}
public static bool Btest(params double[] values) => Band(values) != 0u;
public static uint Bnot(double value) => ~ToUInt32(value);
public static uint Lshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
if (a <= -32 || a >= 32)
return 0u;
return a >= 0 ? v << a : v >> -a;
}
public static uint Rshift(double value, double shift) => Lshift(value, -shift);
public static uint Arshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
if (a < 0)
return Lshift(value, -shift);
bool negative = (v & 0x80000000u) != 0u;
if (a >= 32)
return negative ? 0xFFFFFFFFu : 0u;
if (a == 0)
return v;
uint result = v >> a;
if (negative)
result |= ~0u << (32 - a);
return result;
}
public static uint Lrotate(double value, double shift)
{
uint v = ToUInt32(value);
int a = ((int)shift % 32 + 32) % 32;
return a == 0 ? v : (v << a) | (v >> (32 - a));
}
public static uint Rrotate(double value, double shift) => Lrotate(value, -shift);
public static uint Extract(double value, double pos, double? width)
{
uint v = ToUInt32(value);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
return (v >> p) & NBitMask(w);
}
public static uint Replace(double value, double replacement, double pos, double? width)
{
uint v = ToUInt32(value);
uint u = ToUInt32(replacement);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
uint mask = NBitMask(w) << p;
return (v & ~mask) | ((u & NBitMask(w)) << p);
}
private static void ValidatePosWidth(int pos, int width)
{
if (pos < 0 || width < 1 || pos + width > 32)
throw new ArgumentException("trying to access non-existent bits");
}
private static uint NBitMask(int bits)
{
if (bits <= 0)
return 0u;
if (bits >= 32)
return 0xFFFFFFFFu;
return (1u << bits) - 1u;
}
}
}
+111
ファイルの表示
@@ -0,0 +1,111 @@
using System;
namespace LuaScript.Compat
{
internal static class MoonSharpBit32
{
private const double Modulo = 4294967296.0;
public static uint ToUInt32(double value) => unchecked((uint)Math.IEEERemainder(value, Modulo));
public static int ToInt32(double value) => unchecked((int)Math.IEEERemainder(value, Modulo));
public static uint Band(params double[] values)
{
uint accum = ToUInt32(values[0]);
for (int i = 1; i < values.Length; i++)
accum &= ToUInt32(values[i]);
return accum;
}
public static uint Bor(params double[] values)
{
uint accum = ToUInt32(values[0]);
for (int i = 1; i < values.Length; i++)
accum |= ToUInt32(values[i]);
return accum;
}
public static uint Bxor(params double[] values)
{
uint accum = ToUInt32(values[0]);
for (int i = 1; i < values.Length; i++)
accum ^= ToUInt32(values[i]);
return accum;
}
public static bool Btest(params double[] values) => Band(values) != 0u;
public static uint Bnot(double value) => ~ToUInt32(value);
public static uint Lshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
return a < 0 ? v >> -a : v << a;
}
public static uint Rshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
return a < 0 ? v << -a : v >> a;
}
public static int Arshift(double value, double shift)
{
int v = ToInt32(value);
int a = (int)shift;
return a < 0 ? v << -a : v >> a;
}
public static uint Lrotate(double value, double shift)
{
uint v = ToUInt32(value);
int a = ((int)shift) % 32;
return a < 0 ? (v >> -a) | (v << (32 + a)) : (v << a) | (v >> (32 - a));
}
public static uint Rrotate(double value, double shift)
{
uint v = ToUInt32(value);
int a = ((int)shift) % 32;
return a < 0 ? (v << -a) | (v >> (32 + a)) : (v >> a) | (v << (32 - a));
}
public static uint Extract(double value, double pos, double? width)
{
uint v = ToUInt32(value);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
return (v >> p) & NBitMask(w);
}
public static uint Replace(double value, double replacement, double pos, double? width)
{
uint v = ToUInt32(value);
uint u = ToUInt32(replacement);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
uint mask = NBitMask(w) << p;
return (v & ~mask) | (u & mask);
}
private static void ValidatePosWidth(int pos, int width)
{
if (pos > 31 || pos + width > 31)
throw new ArgumentException("trying to access non-existent bits");
}
private static uint NBitMask(int bits)
{
if (bits <= 0)
return 0u;
if (bits >= 32)
return 0xFFFFFFFFu;
return (1u << bits) - 1u;
}
}
}
+226
ファイルの表示
@@ -0,0 +1,226 @@
using System;
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Text;
using System.Threading;
namespace LuaScript.Engine
{
internal sealed class LuaJitWorker : IDisposable
{
private readonly string _luajitPath;
private readonly string _workerScript;
private readonly string _shimScript;
private readonly string _nativeDir;
private MemoryMappedFile? _mmf;
private MemoryMappedViewAccessor? _view;
private EventWaitHandle? _workEvent;
private EventWaitHandle? _doneEvent;
private Process? _process;
private int _width;
private int _height;
private bool _alive;
public LuaJitWorker(string nativeDir)
{
_nativeDir = nativeDir;
_luajitPath = Path.Combine(nativeDir, "luajit.exe");
_workerScript = Path.Combine(nativeDir, "worker.lua");
_shimScript = Path.Combine(nativeDir, "shim.lua");
}
public static bool IsAvailable(string nativeDir) =>
File.Exists(Path.Combine(nativeDir, "luajit.exe"));
public bool Execute(
string script,
double[] fields,
byte[] pixels,
int width,
int height,
int timeoutMs,
Func<string, int, SceneObjectInfo?> resolveObject,
out bool pixelsDirty,
out string? error)
{
pixelsDirty = false;
error = null;
byte[] scriptBytes = Encoding.UTF8.GetBytes(script);
if (scriptBytes.Length > NativeProtocol.ScriptMax)
{
error = "script too large for native lane";
return false;
}
EnsureWorker(width, height);
var view = _view!;
view.WriteArray(NativeProtocol.FieldsOffset, fields, 0, NativeProtocol.FieldCount);
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(NativeProtocol.PixelOffset, pixels, 0, pixels.Length);
view.Write(NativeProtocol.OffPixelsDirty, 0);
view.Write(NativeProtocol.OffErrorLen, 0);
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdRun);
_workEvent!.Set();
var stopwatch = Stopwatch.StartNew();
int status;
while (true)
{
long remaining = timeoutMs - stopwatch.ElapsedMilliseconds;
if (remaining <= 0 || !_doneEvent!.WaitOne((int)remaining))
{
KillWorker();
error = "native script execution timed out";
return false;
}
status = view.ReadInt32(NativeProtocol.OffStatus);
if (status != NativeProtocol.StatusCallback)
break;
ResolveCallback(view, resolveObject);
_workEvent.Set();
}
if (status == NativeProtocol.StatusError)
{
int len = view.ReadInt32(NativeProtocol.OffErrorLen);
var buffer = new byte[Math.Clamp(len, 0, NativeProtocol.ErrorMax)];
view.ReadArray(NativeProtocol.ErrorOffset, buffer, 0, buffer.Length);
error = Encoding.UTF8.GetString(buffer);
return false;
}
for (int i = NativeProtocol.FirstWritableField; i <= NativeProtocol.LastWritableField; i++)
fields[i] = view.ReadDouble(NativeProtocol.FieldsOffset + i * 8);
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
if (pixelsDirty)
view.ReadArray(NativeProtocol.PixelOffset, pixels, 0, pixels.Length);
return true;
}
private void ResolveCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject)
{
int frame = view.ReadInt32(NativeProtocol.OffCallbackFrame);
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
var tagBytes = new byte[tagLen];
view.ReadArray(NativeProtocol.CallbackTagOffset, tagBytes, 0, tagLen);
string tag = Encoding.UTF8.GetString(tagBytes);
SceneObjectInfo? info;
try { info = resolveObject(tag, frame); }
catch { info = null; }
if (info is { } value)
{
long result = NativeProtocol.CallbackResultOffset;
view.Write(result + NativeProtocol.CbExist * 8, value.Exist ? 1d : 0d);
view.Write(result + NativeProtocol.CbX * 8, value.X);
view.Write(result + NativeProtocol.CbY * 8, value.Y);
view.Write(result + NativeProtocol.CbZ * 8, value.Z);
view.Write(result + NativeProtocol.CbZoom * 8, value.Zoom);
view.Write(result + NativeProtocol.CbRz * 8, value.Rz);
view.Write(result + NativeProtocol.CbAlpha * 8, value.Alpha);
view.Write(result + NativeProtocol.CbLayer * 8, (double)value.Layer);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
else
{
view.Write(NativeProtocol.OffCallbackFound, 0);
}
}
private void EnsureWorker(int width, int height)
{
if (_alive && _process is { HasExited: false } && _width == width && _height == height)
return;
KillWorker();
StartWorker(width, height);
}
private void StartWorker(int width, int height)
{
_width = width;
_height = height;
long size = NativeProtocol.BufferSize(width, height);
string suffix = Guid.NewGuid().ToString("N");
string mapName = "LuaScriptMap_" + suffix;
string workName = "LuaScriptWork_" + suffix;
string doneName = "LuaScriptDone_" + suffix;
_mmf = MemoryMappedFile.CreateNew(mapName, size);
_view = _mmf.CreateViewAccessor();
_view.Write(NativeProtocol.OffMagic, NativeProtocol.Magic);
_workEvent = new EventWaitHandle(false, EventResetMode.AutoReset, workName);
_doneEvent = new EventWaitHandle(false, EventResetMode.AutoReset, doneName);
var psi = new ProcessStartInfo
{
FileName = _luajitPath,
WorkingDirectory = _nativeDir,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
};
psi.ArgumentList.Add(_workerScript);
psi.ArgumentList.Add(mapName);
psi.ArgumentList.Add(size.ToString());
psi.ArgumentList.Add(workName);
psi.ArgumentList.Add(doneName);
psi.ArgumentList.Add(_shimScript);
_process = Process.Start(psi);
if (_process is not null)
ProcessJobObject.Assign(_process.Handle);
_alive = _process is not null;
}
private void KillWorker()
{
if (_process is { HasExited: false })
{
try { _process.Kill(entireProcessTree: true); }
catch { }
}
_process?.Dispose();
_process = null;
_view?.Dispose();
_view = null;
_mmf?.Dispose();
_mmf = null;
_workEvent?.Dispose();
_workEvent = null;
_doneEvent?.Dispose();
_doneEvent = null;
_alive = false;
}
public void Dispose()
{
if (_alive && _process is { HasExited: false } && _view is not null && _workEvent is not null)
{
try
{
_view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdShutdown);
_workEvent.Set();
_process.WaitForExit(500);
}
catch { }
}
KillWorker();
}
}
}
+114
ファイルの表示
@@ -0,0 +1,114 @@
using System;
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;
f[NativeProtocol.H] = ctx.ImageHeight;
f[NativeProtocol.Hw] = ctx.ImageWidth / 2d;
f[NativeProtocol.Hh] = ctx.ImageHeight / 2d;
f[NativeProtocol.Cx] = ctx.ImageWidth / 2d;
f[NativeProtocol.Cy] = ctx.ImageHeight / 2d;
f[NativeProtocol.Cz] = 0d;
f[NativeProtocol.Diagonal] = Math.Sqrt((double)ctx.ImageWidth * ctx.ImageWidth + (double)ctx.ImageHeight * ctx.ImageHeight);
f[NativeProtocol.X] = ctx.X;
f[NativeProtocol.Y] = ctx.Y;
f[NativeProtocol.Z] = ctx.Z;
f[NativeProtocol.Ox] = ctx.Ox;
f[NativeProtocol.Oy] = ctx.Oy;
f[NativeProtocol.Oz] = ctx.Oz;
f[NativeProtocol.Sx] = ctx.Sx;
f[NativeProtocol.Sy] = ctx.Sy;
f[NativeProtocol.Sz] = 1d;
f[NativeProtocol.Zoom] = ctx.Zoom;
f[NativeProtocol.Aspect] = ctx.Aspect;
f[NativeProtocol.Alpha] = ctx.Alpha;
f[NativeProtocol.Rx] = ctx.Rx;
f[NativeProtocol.Ry] = ctx.Ry;
f[NativeProtocol.Rz] = ctx.Rz;
f[NativeProtocol.Rxr] = ctx.RxRad;
f[NativeProtocol.Ryr] = ctx.RyRad;
f[NativeProtocol.Rzr] = ctx.RzRad;
f[NativeProtocol.Track0] = ctx.Track0;
f[NativeProtocol.Track1] = ctx.Track1;
f[NativeProtocol.Track2] = ctx.Track2;
f[NativeProtocol.Track3] = ctx.Track3;
f[NativeProtocol.Time] = ctx.Time;
f[NativeProtocol.Frame] = ctx.Frame;
f[NativeProtocol.TotalFrame] = ctx.TotalFrame;
f[NativeProtocol.TotalTime] = ctx.TotalTime;
f[NativeProtocol.T] = ctx.TotalFrame > 0 ? ctx.Frame / (double)ctx.TotalFrame : 0d;
f[NativeProtocol.Framerate] = ctx.Framerate;
f[NativeProtocol.Layer] = ctx.Layer;
f[NativeProtocol.Index] = ctx.Index;
f[NativeProtocol.Num] = ctx.Num;
f[NativeProtocol.SceneWidth] = ctx.SceneWidth;
f[NativeProtocol.SceneHeight] = ctx.SceneHeight;
f[NativeProtocol.SceneCx] = ctx.SceneWidth / 2d;
f[NativeProtocol.SceneCy] = ctx.SceneHeight / 2d;
f[NativeProtocol.GroupIndex] = ctx.GroupIndex;
f[NativeProtocol.GroupCount] = ctx.GroupCount;
f[NativeProtocol.TimelineTotalFrame] = ctx.TimelineTotalFrame;
f[NativeProtocol.TimelineTotalTime] = ctx.TimelineTotalTime;
f[NativeProtocol.TimeRatio] = ctx.TimeRatio;
f[NativeProtocol.IsSaving] = ctx.IsSaving ? 1d : 0d;
f[NativeProtocol.IsPlaying] = ctx.IsPlaying ? 1d : 0d;
f[NativeProtocol.IsPaused] = ctx.IsPaused ? 1d : 0d;
f[NativeProtocol.TimelineFrame] = ctx.TimelineFrame;
f[NativeProtocol.TimelineTime] = ctx.TimelineTime;
}
public static void FromFields(double[] f, AviUtlScriptContext ctx)
{
ctx.X = f[NativeProtocol.X];
ctx.Y = f[NativeProtocol.Y];
ctx.Z = f[NativeProtocol.Z];
ctx.Ox = f[NativeProtocol.Ox];
ctx.Oy = f[NativeProtocol.Oy];
ctx.Oz = f[NativeProtocol.Oz];
ctx.Alpha = f[NativeProtocol.Alpha];
double initialSx = ctx.Sx;
double initialSy = ctx.Sy;
double initialZoom = ctx.Zoom;
double initialAspect = ctx.Aspect;
ctx.Sx = f[NativeProtocol.Sx];
ctx.Sy = f[NativeProtocol.Sy];
ctx.Zoom = f[NativeProtocol.Zoom];
ctx.Aspect = f[NativeProtocol.Aspect];
bool sxsyChanged = Math.Abs(ctx.Sx - initialSx) > Epsilon || Math.Abs(ctx.Sy - initialSy) > Epsilon;
bool zoomAspectChanged = Math.Abs(ctx.Zoom - initialZoom) > Epsilon || Math.Abs(ctx.Aspect - initialAspect) > Epsilon;
if (zoomAspectChanged && !sxsyChanged)
{
ctx.Sx = ctx.Zoom * (1.0 + ctx.Aspect);
ctx.Sy = ctx.Zoom * (1.0 - ctx.Aspect);
}
double initialRxr = ctx.RxRad;
double rxrNew = f[NativeProtocol.Rxr];
ctx.Rx = Math.Abs(rxrNew - initialRxr) > Epsilon
? rxrNew * (180d / Math.PI)
: f[NativeProtocol.Rx];
double initialRyr = ctx.RyRad;
double ryrNew = f[NativeProtocol.Ryr];
ctx.Ry = Math.Abs(ryrNew - initialRyr) > Epsilon
? ryrNew * (180d / Math.PI)
: f[NativeProtocol.Ry];
double initialRzr = ctx.RzRad;
double rzrNew = f[NativeProtocol.Rzr];
ctx.Rz = Math.Abs(rzrNew - initialRzr) > Epsilon
? rzrNew * (180d / Math.PI)
: f[NativeProtocol.Rz];
}
}
}
+114
ファイルの表示
@@ -0,0 +1,114 @@
namespace LuaScript.Engine
{
internal static class NativeProtocol
{
public const int Magic = 0x4C4A4954;
public const int CmdRun = 0;
public const int CmdShutdown = 1;
public const int StatusIdle = 0;
public const int StatusOk = 1;
public const int StatusError = 2;
public const int StatusCallback = 3;
public const int OffMagic = 0;
public const int OffCommand = 4;
public const int OffStatus = 8;
public const int OffWidth = 12;
public const int OffHeight = 16;
public const int OffScriptLen = 20;
public const int OffPixelsDirty = 24;
public const int OffErrorLen = 28;
public const int OffCallbackFrame = 32;
public const int OffCallbackTagLen = 36;
public const int OffCallbackFound = 40;
public const int HeaderSize = 64;
public const int FieldCount = 64;
public const int FieldsOffset = HeaderSize;
public const int ScriptOffset = FieldsOffset + FieldCount * 8;
public const int ScriptMax = 128 * 1024;
public const int ErrorOffset = ScriptOffset + ScriptMax;
public const int ErrorMax = 4 * 1024;
public const int CallbackTagOffset = ErrorOffset + ErrorMax;
public const int CallbackTagMax = 256;
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
public const int CallbackResultCount = 8;
public const int CbExist = 0;
public const int CbX = 1;
public const int CbY = 2;
public const int CbZ = 3;
public const int CbZoom = 4;
public const int CbRz = 5;
public const int CbAlpha = 6;
public const int CbLayer = 7;
public const int PixelOffset = CallbackResultOffset + CallbackResultCount * 8;
public const int W = 0;
public const int H = 1;
public const int Hw = 2;
public const int Hh = 3;
public const int Cx = 4;
public const int Cy = 5;
public const int Cz = 6;
public const int Diagonal = 7;
public const int X = 8;
public const int Y = 9;
public const int Z = 10;
public const int Ox = 11;
public const int Oy = 12;
public const int Oz = 13;
public const int Sx = 14;
public const int Sy = 15;
public const int Sz = 16;
public const int Zoom = 17;
public const int Aspect = 18;
public const int Alpha = 19;
public const int Rx = 20;
public const int Ry = 21;
public const int Rz = 22;
public const int Rxr = 23;
public const int Ryr = 24;
public const int Rzr = 25;
public const int Track0 = 26;
public const int Track1 = 27;
public const int Track2 = 28;
public const int Track3 = 29;
public const int Time = 30;
public const int Frame = 31;
public const int TotalFrame = 32;
public const int TotalTime = 33;
public const int T = 34;
public const int Framerate = 35;
public const int Layer = 36;
public const int Index = 37;
public const int Num = 38;
public const int SceneWidth = 39;
public const int SceneHeight = 40;
public const int SceneCx = 41;
public const int SceneCy = 42;
public const int GroupIndex = 43;
public const int GroupCount = 44;
public const int TimelineTotalFrame = 45;
public const int TimelineTotalTime = 46;
public const int TimeRatio = 47;
public const int IsSaving = 48;
public const int IsPlaying = 49;
public const int IsPaused = 50;
public const int TimelineFrame = 51;
public const int TimelineTime = 52;
public const int FirstWritableField = X;
public const int LastWritableField = Rzr;
public static long BufferSize(int width, int height) =>
PixelOffset + (long)width * height * 4;
}
}
+103
ファイルの表示
@@ -0,0 +1,103 @@
using System;
using System.Runtime.InteropServices;
namespace LuaScript.Engine
{
internal static class ProcessJobObject
{
private const uint JobObjectExtendedLimitInformation = 9;
private const uint JobObjectLimitKillOnJobClose = 0x2000;
private static readonly nint Handle = Create();
public static void Assign(nint processHandle)
{
if (Handle != nint.Zero && processHandle != nint.Zero)
AssignProcessToJobObject(Handle, processHandle);
}
private static nint Create()
{
nint job = CreateJobObject(nint.Zero, null);
if (job == nint.Zero)
return nint.Zero;
var information = new JobObjectExtendedLimitInformationData
{
BasicLimitInformation = new JobObjectBasicLimitInformationData
{
LimitFlags = JobObjectLimitKillOnJobClose
}
};
int length = Marshal.SizeOf<JobObjectExtendedLimitInformationData>();
nint buffer = Marshal.AllocHGlobal(length);
try
{
Marshal.StructureToPtr(information, buffer, false);
if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, buffer, (uint)length))
{
CloseHandle(job);
return nint.Zero;
}
}
finally
{
Marshal.FreeHGlobal(buffer);
}
return job;
}
[StructLayout(LayoutKind.Sequential)]
private struct JobObjectBasicLimitInformationData
{
public long PerProcessUserTimeLimit;
public long PerJobUserTimeLimit;
public uint LimitFlags;
public nuint MinimumWorkingSetSize;
public nuint MaximumWorkingSetSize;
public uint ActiveProcessLimit;
public nuint Affinity;
public uint PriorityClass;
public uint SchedulingClass;
}
[StructLayout(LayoutKind.Sequential)]
private struct IoCountersData
{
public ulong ReadOperationCount;
public ulong WriteOperationCount;
public ulong OtherOperationCount;
public ulong ReadTransferCount;
public ulong WriteTransferCount;
public ulong OtherTransferCount;
}
[StructLayout(LayoutKind.Sequential)]
private struct JobObjectExtendedLimitInformationData
{
public JobObjectBasicLimitInformationData BasicLimitInformation;
public IoCountersData IoInfo;
public nuint ProcessMemoryLimit;
public nuint JobMemoryLimit;
public nuint PeakProcessMemoryUsed;
public nuint PeakJobMemoryUsed;
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern nint CreateJobObject(nint lpJobAttributes, string? lpName);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetInformationJobObject(nint hJob, uint jobObjectInformationClass, nint lpJobObjectInformation, uint cbJobObjectInformationLength);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AssignProcessToJobObject(nint hJob, nint hProcess);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(nint hObject);
}
}
+106
ファイルの表示
@@ -0,0 +1,106 @@
using System;
namespace LuaScript.Engine
{
internal enum ScriptEngineKind
{
MoonSharp,
Native,
Gpu,
Cpu,
}
internal static class ScriptDirective
{
public static ScriptEngineKind Resolve(string? script) =>
TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.MoonSharp;
public static ScriptEngineKind ResolveAuto(string? script)
{
if (TryGetDirective(script, out var kind))
return kind;
return UsesPixelApi(script) ? ScriptEngineKind.Native : ScriptEngineKind.MoonSharp;
}
public static bool UsesPixelApi(string? script) =>
script is not null && (script.Contains("getpixel", StringComparison.Ordinal) || script.Contains("setpixel", StringComparison.Ordinal));
private static bool TryGetDirective(string? script, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
if (string.IsNullOrEmpty(script))
return false;
int index = 0;
int length = script.Length;
while (index < length)
{
int lineStart = index;
while (index < length && script[index] != '\n')
index++;
int lineEnd = index;
if (lineEnd > lineStart && script[lineEnd - 1] == '\r')
lineEnd--;
if (TryParseDirectiveLine(script, lineStart, lineEnd, out kind))
return true;
index++;
}
return false;
}
private static bool TryParseDirectiveLine(string script, int start, int end, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
int i = start;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
if (i + 3 > end || script[i] != '-' || script[i + 1] != '-' || script[i + 2] != '!')
return false;
i += 3;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
int tokenStart = i;
while (i < end && IsTokenChar(script[i]))
i++;
int tokenEnd = i;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
if (i != end)
return false;
var token = script.AsSpan(tokenStart, tokenEnd - tokenStart);
if (token.Equals("native", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Native;
return true;
}
if (token.Equals("gpu", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Gpu;
return true;
}
if (token.Equals("cpu", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Cpu;
return true;
}
if (token.Equals("moonsharp", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.MoonSharp;
return true;
}
return false;
}
private static bool IsTokenChar(char c) =>
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
}
+9 -3
ファイルの表示
@@ -1,10 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.0.0</Version>
<Version>1.3.3</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
@@ -100,10 +100,16 @@
</Content>
<Resource Include="Resources\SyntaxDefinitions\Lua-Dark.xshd" />
<Resource Include="Resources\SyntaxDefinitions\Lua-Light.xshd" />
<Resource Include="Resources\SyntaxDefinitions\Lua-Black.xshd" />
<Resource Include="Resources\SyntaxDefinitions\Lua-Windows.xshd" />
<None Include="..\native\luajit.exe" Link="native\luajit.exe" CopyToOutputDirectory="PreserveNewest" />
<None Include="..\native\lua51.dll" Link="native\lua51.dll" CopyToOutputDirectory="PreserveNewest" />
<None Include="..\native\worker.lua" Link="native\worker.lua" CopyToOutputDirectory="PreserveNewest" />
<None Include="..\native\shim.lua" Link="native\shim.lua" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(CI)' != 'true'">
<Exec Command="mkdir &quot;$(YMM4DirPath)user\plugin\$(ProjectName)&quot; &gt; NUL 2&gt;&amp;1&#xD;&#xA;copy &quot;$(TargetPath)&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;" />
<Exec Command="mkdir &quot;$(YMM4DirPath)user\plugin\$(ProjectName)&quot; &gt; NUL 2&gt;&amp;1&#xD;&#xA;copy &quot;$(TargetPath)&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;&#xD;&#xA;xcopy /E /I /Y &quot;$(TargetDir)native&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\native&quot;" />
</Target>
</Project>
+3
ファイルの表示
@@ -4,10 +4,13 @@ using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Controls;
using YukkuriMovieMaker.Exo;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Plugin;
using YukkuriMovieMaker.Plugin.Effects;
namespace LuaScript
{
[PluginDetails(AuthorName = "routersys", ContentId = "nc487743")]
[VideoEffect(nameof(Texts.LuaScript), [VideoEffectCategories.Filtering], ["lua", "script", "スクリプト", "lua script", "アニメーション効果", "animation"], IsAviUtlSupported = false, ResourceType = typeof(Texts))]
internal class LuaScriptEffect : VideoEffectBase, IScriptProvider
{
+216 -55
ファイルの表示
@@ -1,5 +1,7 @@
using System.IO;
using System.Numerics;
using System.Runtime.InteropServices;
using LuaScript.Engine;
using Vortice;
using Vortice.DCommon;
using Vortice.Direct2D1;
@@ -9,6 +11,8 @@ using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Player.Video.Effects;
using YukkuriMovieMaker.Project;
using YukkuriMovieMaker.Project.Items;
namespace LuaScript
{
@@ -40,8 +44,26 @@ namespace LuaScript
DrawDescription InputDesc
);
private const int NativeTimeoutMilliseconds = 5000;
private static string NativeDirectory =>
Path.Combine(Path.GetDirectoryName(typeof(LuaScriptEffectProcessor).Assembly.Location) ?? AppContext.BaseDirectory, "native");
private readonly LuaScriptEngine _engine = new();
private readonly SemaphoreSlim _pixelLoaderSemaphore = new(1, 1);
private AviUtlScriptContext _context = new();
private LuaJitWorker? _nativeWorker;
private double[]? _nativeFields;
private bool _nativeWarned;
private EffectDescription? _frameDesc;
private SceneObjectResolver? _frameResolver;
private bool _frameResolverBuilt;
private Guid _lastSceneGuid;
private string _lastSceneId = string.Empty;
private bool _sceneIdCached;
private GraphicsDevicesAndContext? _ownCtx;
@@ -57,6 +79,7 @@ namespace LuaScript
private bool _isFirst = true;
private ID2D1Image? _cachedInput;
private RenderKey _cachedKey;
private SceneObjectQuery[] _cachedQueries = [];
private DrawDescription? _cachedOutputDesc;
private bool _cachedPixelsModified;
@@ -64,9 +87,31 @@ namespace LuaScript
{
_ownCtx = new GraphicsDevicesAndContext(devices);
disposer.Collect(_ownCtx);
_context.ResolverProvider = GetFrameResolver;
return null;
}
private SceneObjectResolver GetFrameResolver()
{
if (!_frameResolverBuilt)
{
_frameResolver = BuildSceneObjectResolver(_frameDesc!);
_frameResolverBuilt = true;
}
return _frameResolver!;
}
private string ResolveSceneId(Guid sceneId)
{
if (!_sceneIdCached || sceneId != _lastSceneGuid)
{
_lastSceneId = sceneId.ToString();
_lastSceneGuid = sceneId;
_sceneIdCached = true;
}
return _lastSceneId;
}
protected override void setInput(ID2D1Image? input)
{
if (!ReferenceEquals(_cachedInput, input))
@@ -110,7 +155,12 @@ namespace LuaScript
desc.TimelineDuration.Time.TotalSeconds,
inDesc);
if (!_isFirst && key == _cachedKey)
_frameDesc = desc;
_frameResolver = null;
_frameResolverBuilt = false;
if (!_isFirst && key == _cachedKey &&
(_cachedQueries.Length == 0 || QueriesMatch(_cachedQueries, GetFrameResolver())))
{
effectOutput = _cachedPixelsModified ? _transformEffect?.Output : null;
return _cachedOutputDesc ?? inDesc;
@@ -120,7 +170,8 @@ namespace LuaScript
int imgW = Math.Max(1, (int)Math.Ceiling(bounds.Right - bounds.Left));
int imgH = Math.Max(1, (int)Math.Ceiling(bounds.Bottom - bounds.Top));
var ctx = BuildContext(in key, imgW, imgH);
var ctx = _context;
PopulateContext(ctx, in key, imgW, imgH);
ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH));
DrawDescription outDesc = inDesc;
@@ -128,23 +179,43 @@ namespace LuaScript
try
{
_engine.Execute(script, ctx);
bool wantNative = ScriptDirective.ResolveAuto(script) == ScriptEngineKind.Native;
bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory);
if (wantNative && !nativeReady)
WarnNativeUnavailableOnce();
if (ctx.IsPixelsDirty)
if (nativeReady)
{
EnsureBitmaps(imgW, imgH);
WritePixelsToOutput(ctx.GetPixelBuffer()!, imgW);
UpdateTransformEffect(bounds);
effectOutput = _transformEffect!.Output;
pixelsModified = true;
pixelsModified = ExecuteNative(script, ctx, bounds, imgW, imgH);
}
else
{
effectOutput = null;
_engine.Execute(script, ctx);
if (ctx.IsPixelsDirty)
{
EnsureBitmaps(imgW, imgH);
WritePixelsToOutput(ctx.GetPixelBuffer()!, imgW);
UpdateTransformEffect(bounds);
effectOutput = _transformEffect!.Output;
pixelsModified = true;
}
else
{
effectOutput = null;
}
}
outDesc = BuildOutputDesc(inDesc, ctx);
}
catch (LuaScriptTimeoutException ex)
{
effectOutput = null;
_context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
_isFirst = true;
Log.Default.Write(ex.Message, ex);
return inDesc;
}
catch (LuaScriptException ex)
{
effectOutput = null;
@@ -159,13 +230,61 @@ namespace LuaScript
_isFirst = false;
_cachedKey = key;
_cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries];
_cachedOutputDesc = outDesc;
_cachedPixelsModified = pixelsModified;
return outDesc;
}
private static AviUtlScriptContext BuildContext(in RenderKey key, int imgW, int imgH)
private static SceneObjectResolver BuildSceneObjectResolver(EffectDescription desc)
{
var scenes = desc.Scenes;
if (scenes is null)
return new SceneObjectResolver([], desc.FPS);
Scene? scene = null;
foreach (var info in scenes)
{
if (info is Scene candidate && candidate.ID == desc.SceneId)
{
scene = candidate;
break;
}
}
if (scene is null)
return new SceneObjectResolver([], desc.FPS);
var items = scene.Timeline.Items;
var entries = new List<SceneObjectResolver.Entry>(items.Count);
foreach (var item in items)
{
if (item is not VisualItem visual)
continue;
var tag = item.Remark;
if (string.IsNullOrEmpty(tag))
continue;
entries.Add(new SceneObjectResolver.Entry(tag, item.Frame, item.Length, item.Layer, visual));
}
return new SceneObjectResolver([.. entries], desc.FPS);
}
private static bool QueriesMatch(SceneObjectQuery[] queries, SceneObjectResolver resolver)
{
for (int i = 0; i < queries.Length; i++)
{
var query = queries[i];
SceneObjectInfo? current = resolver.TryResolve(query.Tag, query.Frame, out var info) ? info : null;
if (!Nullable.Equals(current, query.Result))
return false;
}
return true;
}
private void PopulateContext(AviUtlScriptContext ctx, in RenderKey key, int imgW, int imgH)
{
var zoom = key.InputDesc.Zoom;
double zoomAvg = (zoom.X + zoom.Y) / 2d;
@@ -173,50 +292,49 @@ namespace LuaScript
? (zoom.X - zoom.Y) / (zoom.X + zoom.Y)
: 0d;
return new AviUtlScriptContext
{
ImageWidth = imgW,
ImageHeight = imgH,
X = key.InputDesc.Draw.X,
Y = key.InputDesc.Draw.Y,
Z = key.InputDesc.Draw.Z,
Ox = key.InputDesc.CenterPoint.X,
Oy = key.InputDesc.CenterPoint.Y,
Oz = 0d,
Sx = zoom.X,
Sy = zoom.Y,
Zoom = zoomAvg,
Aspect = aspect,
Alpha = key.InputDesc.Opacity * 255d,
Rx = key.InputDesc.Rotation.X,
Ry = key.InputDesc.Rotation.Y,
Rz = key.InputDesc.Rotation.Z,
Track0 = key.Track0,
Track1 = key.Track1,
Track2 = key.Track2,
Track3 = key.Track3,
Time = key.Time,
Frame = key.Frame,
TotalFrame = key.Length,
TotalTime = key.Fps > 0 ? key.Length / (double)key.Fps : 0d,
Framerate = key.Fps,
TimelineFrame = key.TimelineFrame,
TimelineTime = key.TimelineTime,
SceneWidth = key.SceneWidth,
SceneHeight = key.SceneHeight,
Layer = key.Layer,
Index = key.InputIndex,
Num = key.InputCount,
GroupIndex = key.GroupIndex,
GroupCount = key.GroupCount,
TimelineTotalFrame = key.TimelineTotalFrame,
TimelineTotalTime = key.TimelineTotalTime,
IsSaving = key.Usage == TimelineSourceUsage.Exporting,
IsPlaying = key.Usage == TimelineSourceUsage.Playing,
IsPaused = key.Usage == TimelineSourceUsage.Paused,
SceneId = key.SceneId.ToString(),
TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d,
};
ctx.ClearQueries();
ctx.ImageWidth = imgW;
ctx.ImageHeight = imgH;
ctx.X = key.InputDesc.Draw.X;
ctx.Y = key.InputDesc.Draw.Y;
ctx.Z = key.InputDesc.Draw.Z;
ctx.Ox = key.InputDesc.CenterPoint.X;
ctx.Oy = key.InputDesc.CenterPoint.Y;
ctx.Oz = 0d;
ctx.Sx = zoom.X;
ctx.Sy = zoom.Y;
ctx.Zoom = zoomAvg;
ctx.Aspect = aspect;
ctx.Alpha = key.InputDesc.Opacity * 255d;
ctx.Rx = key.InputDesc.Rotation.X;
ctx.Ry = key.InputDesc.Rotation.Y;
ctx.Rz = key.InputDesc.Rotation.Z;
ctx.Track0 = key.Track0;
ctx.Track1 = key.Track1;
ctx.Track2 = key.Track2;
ctx.Track3 = key.Track3;
ctx.Time = key.Time;
ctx.Frame = key.Frame;
ctx.TotalFrame = key.Length;
ctx.TotalTime = key.Fps > 0 ? key.Length / (double)key.Fps : 0d;
ctx.Framerate = key.Fps;
ctx.TimelineFrame = key.TimelineFrame;
ctx.TimelineTime = key.TimelineTime;
ctx.SceneWidth = key.SceneWidth;
ctx.SceneHeight = key.SceneHeight;
ctx.Layer = key.Layer;
ctx.Index = key.InputIndex;
ctx.Num = key.InputCount;
ctx.GroupIndex = key.GroupIndex;
ctx.GroupCount = key.GroupCount;
ctx.TimelineTotalFrame = key.TimelineTotalFrame;
ctx.TimelineTotalTime = key.TimelineTotalTime;
ctx.IsSaving = key.Usage == TimelineSourceUsage.Exporting;
ctx.IsPlaying = key.Usage == TimelineSourceUsage.Playing;
ctx.IsPaused = key.Usage == TimelineSourceUsage.Paused;
ctx.SceneId = ResolveSceneId(key.SceneId);
ctx.TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d;
}
private static DrawDescription BuildOutputDesc(DrawDescription inDesc, AviUtlScriptContext ctx)
@@ -231,6 +349,48 @@ namespace LuaScript
};
}
private void WarnNativeUnavailableOnce()
{
if (_nativeWarned) return;
_nativeWarned = true;
Log.Default.Write($"LuaScript: native runtime not found at '{NativeDirectory}'. Falling back to MoonSharp (slow). Deploy the 'native' folder next to the plugin.");
}
private bool ExecuteNative(string script, AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
{
_nativeWorker ??= new LuaJitWorker(NativeDirectory);
_nativeFields ??= new double[NativeProtocol.FieldCount];
NativeFieldMap.ToFields(ctx, _nativeFields);
byte[] buffer = LoadInputPixels(bounds, imgW, imgH);
bool ok = _nativeWorker.Execute(
script, _nativeFields, buffer, imgW, imgH, NativeTimeoutMilliseconds,
(tag, frame) => ctx.ResolveObject(tag, frame, out var info) ? info : null,
out bool dirty, out string? error);
if (!ok)
{
if (error is not null && error.Contains("timed out", StringComparison.Ordinal))
throw new LuaScriptTimeoutException(error);
throw new LuaScriptRuntimeException(error ?? "Native script execution failed.");
}
NativeFieldMap.FromFields(_nativeFields, ctx);
if (dirty)
{
EnsureBitmaps(imgW, imgH);
WritePixelsToOutput(buffer, imgW);
UpdateTransformEffect(bounds);
effectOutput = _transformEffect!.Output;
return true;
}
effectOutput = null;
return false;
}
private byte[] LoadInputPixels(RawRectF bounds, int width, int height)
{
_pixelLoaderSemaphore.Wait();
@@ -343,6 +503,7 @@ namespace LuaScript
if (disposing)
{
_engine.Dispose();
_nativeWorker?.Dispose();
_pixelLoaderSemaphore.Dispose();
_renderTarget?.Dispose();
_stagingBitmap?.Dispose();
+110 -65
ファイルの表示
@@ -1,4 +1,3 @@
using System.Collections.Concurrent;
using MoonSharp.Interpreter;
using MoonSharp.Interpreter.Debugging;
using MoonSharp.Interpreter.Loaders;
@@ -11,12 +10,6 @@ namespace LuaScript
LuaScriptException? Exception,
bool TimedOut);
private sealed record ExecutionJob(
string Code,
AviUtlScriptContext Context,
CancellationToken Cancellation,
TaskCompletionSource<ExecutionResult> Completion);
private sealed class ExecutionThread : IDisposable
{
private sealed class CancellationDebugger : IDebugger
@@ -46,10 +39,19 @@ namespace LuaScript
}
}
private readonly BlockingCollection<ExecutionJob> _queue = new(boundedCapacity: 1);
private readonly SemaphoreSlim _workSignal = new(0);
private readonly ManualResetEventSlim _doneSignal = new(false);
private readonly CancellationTokenSource _cts = new();
private readonly Thread _thread;
private readonly CancellationDebugger _debugger = new();
private string _jobCode = string.Empty;
private AviUtlScriptContext? _jobContext;
private LuaScriptException? _jobException;
private volatile bool _disposeRequested;
private readonly List<string> _removalBuffer = [];
private Script? _script;
private DynValue? _compiledChunk;
private string _lastCompiledCode = string.Empty;
@@ -67,6 +69,8 @@ namespace LuaScript
internal ExecutionThread()
{
_activeCancellation = _cts.Token;
_debugger.UpdateToken(_cts.Token);
_thread = new Thread(WorkerLoop)
{
IsBackground = true,
@@ -77,77 +81,65 @@ namespace LuaScript
internal ExecutionResult TryExecute(string code, AviUtlScriptContext ctx, int timeoutMs)
{
using var cts = new CancellationTokenSource();
var tcs = new TaskCompletionSource<ExecutionResult>(
TaskCreationOptions.RunContinuationsAsynchronously);
_jobCode = code;
_jobContext = ctx;
_jobException = null;
_doneSignal.Reset();
_workSignal.Release();
if (!_queue.TryAdd(new ExecutionJob(code, ctx, cts.Token, tcs)))
return new ExecutionResult(
new LuaScriptRuntimeException("Script execution queue is full."), false);
if (_doneSignal.Wait(timeoutMs))
return new ExecutionResult(_jobException, false);
if (tcs.Task.Wait(timeoutMs))
return tcs.Task.Result;
cts.Cancel();
_cts.Cancel();
return new ExecutionResult(null, TimedOut: true);
}
private void WorkerLoop()
{
try
while (true)
{
foreach (var job in _queue.GetConsumingEnumerable())
ProcessJob(job);
_workSignal.Wait();
if (_disposeRequested)
return;
ProcessJob();
_doneSignal.Set();
}
catch (OperationCanceledException) { }
catch (InvalidOperationException) { }
}
private void ProcessJob(ExecutionJob job)
private void ProcessJob()
{
if (job.Cancellation.IsCancellationRequested)
{
job.Completion.TrySetResult(new ExecutionResult(null, TimedOut: true));
return;
}
_activeCancellation = job.Cancellation;
_activeContext = job.Context;
_debugger.UpdateToken(job.Cancellation);
var context = _jobContext!;
_activeContext = context;
try
{
EnsureScript();
EnsureScriptIntegrity();
EnsureCompiled(job.Code);
SetupGlobals(job.Context);
EnsureCompiled(_jobCode);
SetupGlobals(context);
_script!.Call(_compiledChunk!);
ReadBackGlobals(job.Context);
job.Completion.TrySetResult(new ExecutionResult(null, false));
ReadBackGlobals(context);
_jobException = null;
}
catch (OperationCanceledException) when (job.Cancellation.IsCancellationRequested)
catch (OperationCanceledException) when (_cts.IsCancellationRequested)
{
job.Completion.TrySetResult(new ExecutionResult(null, TimedOut: true));
_jobException = null;
}
catch (LuaScriptException ex)
{
job.Completion.TrySetResult(new ExecutionResult(ex, false));
_jobException = ex;
}
catch (ScriptRuntimeException ex)
{
job.Completion.TrySetResult(new ExecutionResult(
new LuaScriptRuntimeException(ex.DecoratedMessage ?? ex.Message, ex), false));
_jobException = new LuaScriptRuntimeException(ex.DecoratedMessage ?? ex.Message, ex);
}
catch (Exception ex)
{
job.Completion.TrySetResult(new ExecutionResult(
new LuaScriptRuntimeException(ex.Message, ex), false));
_jobException = new LuaScriptRuntimeException(ex.Message, ex);
}
finally
{
_debugger.UpdateToken(default);
_activeContext = null;
_activeCancellation = default;
}
}
@@ -216,7 +208,7 @@ namespace LuaScript
script.Globals["scene"] = sceneTable;
var objTable = new Table(script);
RegisterPixelCallbacks(objTable);
RegisterObjectCallbacks(objTable);
script.Globals["obj"] = objTable;
var animTable = new Table(script);
@@ -246,7 +238,7 @@ namespace LuaScript
if (!ReferenceEquals(script.Globals.Get("obj").Table, _objTable))
{
var objTable = new Table(script);
RegisterPixelCallbacks(objTable);
RegisterObjectCallbacks(objTable);
script.Globals["obj"] = objTable;
_objTable = objTable;
_objTableSnapshot = null;
@@ -269,10 +261,10 @@ namespace LuaScript
_ymm4TableSnapshot = null;
}
ResetUserTableKeys(_objTable!, ref _objTableSnapshot);
ResetUserTableKeys(_sceneTable!, ref _sceneTableSnapshot);
ResetUserTableKeys(_animTable!, ref _animTableSnapshot);
ResetUserTableKeys(_ymm4Table!, ref _ymm4TableSnapshot);
ResetUserTableKeys(_objTable!, _objTableSnapshot);
ResetUserTableKeys(_sceneTable!, _sceneTableSnapshot);
ResetUserTableKeys(_animTable!, _animTableSnapshot);
ResetUserTableKeys(_ymm4Table!, _ymm4TableSnapshot);
}
script.Globals["time"] = ctx.Time;
@@ -366,39 +358,62 @@ namespace LuaScript
return keys;
}
private static void ResetUserTableKeys(Table table, ref HashSet<string>? snapshot)
private void ResetUserTableKeys(Table table, HashSet<string>? snapshot)
{
if (snapshot is null) return;
var keysToRemove = new List<string>();
var buffer = _removalBuffer;
buffer.Clear();
foreach (var key in table.Keys)
{
if (key.Type == DataType.String &&
!snapshot.Contains(key.String))
{
keysToRemove.Add(key.String);
buffer.Add(key.String);
}
}
foreach (var key in keysToRemove)
foreach (var key in buffer)
table[key] = DynValue.Nil;
}
private void ResetUserGlobals(Script script)
{
var keysToRemove = new List<string>();
var buffer = _removalBuffer;
buffer.Clear();
foreach (var key in script.Globals.Keys)
{
if (key.Type == DataType.String &&
!_builtinGlobalSnapshot!.Contains(key.String))
{
keysToRemove.Add(key.String);
buffer.Add(key.String);
}
}
foreach (var key in keysToRemove)
foreach (var key in buffer)
script.Globals[key] = DynValue.Nil;
}
private void RegisterPixelCallbacks(Table obj)
private void RegisterObjectCallbacks(Table obj)
{
obj["getobject"] = DynValue.NewCallback((execCtx, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count == 0)
return DynValue.Nil;
var tag = args[0];
if (tag.Type != DataType.String)
return DynValue.Nil;
int frame = _activeContext.TimelineFrame;
if (args.Count >= 2)
{
var frameArg = args[1];
if (frameArg.Type != DataType.Number)
return DynValue.Nil;
frame = (int)frameArg.Number;
}
if (!_activeContext.ResolveObject(tag.String, frame, out var info))
return DynValue.Nil;
return BuildObjectTable(execCtx.GetScript(), info);
});
obj["getpixel"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
@@ -438,6 +453,29 @@ namespace LuaScript
obj["putpixeldata"] = DynValue.NewCallback((_, _) => DynValue.Void);
}
private static DynValue BuildObjectTable(Script script, SceneObjectInfo info)
{
var table = new Table(script)
{
["exist"] = info.Exist,
["x"] = info.X,
["y"] = info.Y,
["z"] = info.Z,
["zoom"] = info.Zoom,
["sx"] = info.Zoom,
["sy"] = info.Zoom,
["rx"] = 0d,
["ry"] = 0d,
["rz"] = info.Rz,
["rxr"] = 0d,
["ryr"] = 0d,
["rzr"] = info.Rz * Math.PI / 180d,
["alpha"] = info.Alpha,
["layer"] = info.Layer,
};
return DynValue.NewTable(table);
}
private void ReadBackGlobals(AviUtlScriptContext ctx)
{
if (_objTable is null) return;
@@ -487,18 +525,25 @@ namespace LuaScript
public void Dispose()
{
_queue.CompleteAdding();
_disposeRequested = true;
_workSignal.Release();
_thread.Join();
_queue.Dispose();
_cts.Cancel();
_cts.Dispose();
_workSignal.Dispose();
_doneSignal.Dispose();
}
internal void AbandonAsync()
{
_queue.CompleteAdding();
_disposeRequested = true;
_workSignal.Release();
ThreadPool.QueueUserWorkItem(_ =>
{
_thread.Join();
_queue.Dispose();
_cts.Dispose();
_workSignal.Dispose();
_doneSignal.Dispose();
});
}
@@ -533,7 +578,7 @@ namespace LuaScript
var stale = _executionThread;
_executionThread = new ExecutionThread();
stale.AbandonAsync();
throw new LuaScriptRuntimeException(
throw new LuaScriptTimeoutException(
$"Script execution timed out after {ExecutionTimeoutMilliseconds} ms.");
}
+2
ファイルの表示
@@ -5,4 +5,6 @@ namespace LuaScript
internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner);
internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner);
internal sealed class LuaScriptTimeoutException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+62
ファイルの表示
@@ -0,0 +1,62 @@
<?xml version="1.0"?>
<SyntaxDefinition name="Lua" extensions=".lua" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<Color name="Comment" foreground="#FF57A64A" />
<Color name="String" foreground="#FFD69D85" />
<Color name="NumberLiteral" foreground="#FFB5CEA8"/>
<Color name="NilKeyword" foreground="#FF569CD6"/>
<Color name="Keywords" foreground="#FF569CD6" />
<Color name="TrueFalse" foreground="#FF569CD6" />
<RuleSet>
<Span color="Comment" multiline="true">
<Begin>--\[\[</Begin>
<End>\]\]</End>
</Span>
<Span color="Comment">
<Begin>--</Begin>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<Span begin="\\" end="." />
</RuleSet>
</Span>
<Span color="String">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<Span begin="\\" end="." />
</RuleSet>
</Span>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>and</Word>
<Word>break</Word>
<Word>do</Word>
<Word>else</Word>
<Word>elseif</Word>
<Word>end</Word>
<Word>for</Word>
<Word>function</Word>
<Word>goto</Word>
<Word>if</Word>
<Word>in</Word>
<Word>local</Word>
<Word>not</Word>
<Word>or</Word>
<Word>repeat</Word>
<Word>return</Word>
<Word>then</Word>
<Word>until</Word>
<Word>while</Word>
</Keywords>
<Keywords color="NilKeyword">
<Word>nil</Word>
</Keywords>
<Rule color="NumberLiteral">\b0[xX][0-9a-fA-F]+|\b(\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
</RuleSet>
</SyntaxDefinition>
+62
ファイルの表示
@@ -0,0 +1,62 @@
<?xml version="1.0"?>
<SyntaxDefinition name="Lua" extensions=".lua" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<Color name="Comment" foreground="#FF008000" />
<Color name="String" foreground="#FFA31515" />
<Color name="NumberLiteral" foreground="#FF000000"/>
<Color name="NilKeyword" foreground="#FF0000FF"/>
<Color name="Keywords" foreground="#FF0000FF" />
<Color name="TrueFalse" foreground="#FF0000FF" />
<RuleSet>
<Span color="Comment" multiline="true">
<Begin>--\[\[</Begin>
<End>\]\]</End>
</Span>
<Span color="Comment">
<Begin>--</Begin>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<Span begin="\\" end="." />
</RuleSet>
</Span>
<Span color="String">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<Span begin="\\" end="." />
</RuleSet>
</Span>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>and</Word>
<Word>break</Word>
<Word>do</Word>
<Word>else</Word>
<Word>elseif</Word>
<Word>end</Word>
<Word>for</Word>
<Word>function</Word>
<Word>goto</Word>
<Word>if</Word>
<Word>in</Word>
<Word>local</Word>
<Word>not</Word>
<Word>or</Word>
<Word>repeat</Word>
<Word>return</Word>
<Word>then</Word>
<Word>until</Word>
<Word>while</Word>
</Keywords>
<Keywords color="NilKeyword">
<Word>nil</Word>
</Keywords>
<Rule color="NumberLiteral">\b0[xX][0-9a-fA-F]+|\b(\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
</RuleSet>
</SyntaxDefinition>
+18
ファイルの表示
@@ -0,0 +1,18 @@
namespace LuaScript
{
internal readonly record struct SceneObjectInfo(
string Tag,
bool Exist,
double X,
double Y,
double Z,
double Zoom,
double Rz,
double Alpha,
int Layer);
internal readonly record struct SceneObjectQuery(
string Tag,
int Frame,
SceneObjectInfo? Result);
}
+69
ファイルの表示
@@ -0,0 +1,69 @@
using YukkuriMovieMaker.Project.Items;
namespace LuaScript
{
internal sealed class SceneObjectResolver
{
internal readonly record struct Entry(string Tag, int Frame, int Length, int Layer, VisualItem Item);
private readonly Entry[] _entries;
private readonly int _fps;
internal SceneObjectResolver(Entry[] entries, int fps)
{
_entries = entries;
_fps = fps;
}
internal bool TryResolve(string tag, int timelineFrame, out SceneObjectInfo info)
{
int fallback = -1;
for (int i = 0; i < _entries.Length; i++)
{
if (!string.Equals(_entries[i].Tag, tag, StringComparison.Ordinal))
continue;
if (IsExist(_entries[i], timelineFrame))
{
info = Evaluate(_entries[i], timelineFrame);
return true;
}
if (fallback < 0)
fallback = i;
}
if (fallback >= 0)
{
info = Evaluate(_entries[fallback], timelineFrame);
return true;
}
info = default;
return false;
}
private static bool IsExist(in Entry entry, int timelineFrame)
=> entry.Frame <= timelineFrame && timelineFrame < entry.Frame + entry.Length;
private SceneObjectInfo Evaluate(in Entry entry, int timelineFrame)
{
var visual = entry.Item;
int length = entry.Length;
int local = Math.Clamp(timelineFrame - entry.Frame, 0, length);
double x = visual.X.GetValue(local, length, _fps);
double y = visual.Y.GetValue(local, length, _fps);
double z = visual.Z.GetValue(local, length, _fps);
double zoom = visual.Zoom.GetValue(local, length, _fps) / 100d;
double rz = visual.Rotation.GetValue(local, length, _fps);
double opacity = visual.Opacity.GetValue(local, length, _fps) / 100d;
double timeSec = _fps > 0 ? local / (double)_fps : 0d;
double durationSec = _fps > 0 ? length / (double)_fps : 0d;
double fadeIn = visual.FadeIn <= 0d ? 1d : Math.Min(1d, timeSec / visual.FadeIn);
double fadeOut = visual.FadeOut <= 0d ? 1d : Math.Min(1d, (durationSec - timeSec) / visual.FadeOut);
double alpha = opacity * Math.Min(fadeIn, fadeOut) * 255d;
return new SceneObjectInfo(entry.Tag, IsExist(entry, timelineFrame), x, y, z, zoom, rz, alpha, entry.Layer);
}
}
}
+45
ファイルの表示
@@ -189,6 +189,51 @@
- جدول obj - الدوال -
○ obj.getobject(tag [, frame])
يحصل على معلومات الرسم لكائن آخر يحمل الوسم المحدد.
※ يطابق الوسم النص المُدخل في حقل "ملاحظة" للعنصر الهدف.
※ عند تمرير الوسيط الثاني frame تُؤخذ القيم عند ذلك الإطار من
المخطط الزمني. وعند حذفه يُستخدم الإطار الحالي.
※ عند وجود عدة عناصر تحمل الوسم نفسه، يُعاد العنصر الظاهر في
الإطار الهدف بأولوية. وإن لم يكن أي منها ظاهرًا، يُعاد أول
عنصر مطابق.
※ القيم المُعادة هي إحداثيات العنصر ودورانه ومقياسه الخاصة به.
ولا تتضمن التحويلات الناتجة عن التحكم بالمجموعة أو التحكم
بالكاميرا أو التأثيرات الأعلى.
※ تستخدم كل قيمة نظام الوحدات نفسه المستخدم في جدول obj.
tag : النص المضبوط في ملاحظة العنصر الهدف
frame : الإطار المطلق على المخطط الزمني المراد أخذه (اختياري)
القيمة المُعادة : جدول معلومات الكائن. يُعيد nil عند عدم وجود
عنصر مطابق.
.exist : هل هو ظاهر في الإطار الهدف (boolean)
.x : إحداثي العرض الأساسي X
.y : إحداثي العرض الأساسي Y
.z : إحداثي العرض الأساسي Z
.zoom : المقياس (1.0 يعني الحجم الأصلي)
.sx : المقياس في اتجاه X (= zoom)
.sy : المقياس في اتجاه Y (= zoom)
.rx : زاوية الدوران حول المحور X (بالدرجات، دائمًا 0)
.ry : زاوية الدوران حول المحور Y (بالدرجات، دائمًا 0)
.rz : زاوية الدوران حول المحور Z (بالدرجات)
.rxr : زاوية الدوران حول المحور X (بالراديان، دائمًا 0)
.ryr : زاوية الدوران حول المحور Y (بالراديان، دائمًا 0)
.rzr : زاوية الدوران حول المحور Z (بالراديان)
.alpha : الشفافية (0.0 - 255.0، مع تطبيق التلاشي)
.layer : رقم الطبقة التي وُضع فيها
مثال:
local funnel = obj.getobject("funnel")
if funnel then
obj.x = funnel.x
obj.y = funnel.y
end
التثبيت على موضع الإطلاق (ملاحظة المُطلِق هي "funnel"):
local fire = timelineframe - frame
local src = obj.getobject("funnel", fire)
if src then
obj.x = src.x
obj.y = src.y
end
○ obj.getpixel(x, y)
يسترد معلومات البكسل عند الإحداثيات المحددة.
* تحدث نقل بيانات الصورة من GPU إلى CPU عند الاستدعاء الأول (مع عبء معالجة).
+48
ファイルの表示
@@ -192,6 +192,54 @@
- obj Table - Functions -
o obj.getobject(tag [, frame])
Gets the drawing information of another object that has the
specified tag.
* The tag matches the string entered in the target item's
"Remark" field.
* When the second argument frame is given, the values at that
timeline frame are returned. When omitted, the current frame
is used.
* If multiple items share the same tag, the item visible at the
target frame is returned with priority. If none is visible,
the first matching item is returned.
* The returned values are the item's own coordinates, rotation
and scale. Transforms from group control, camera control or
upper effects are NOT included.
* Each value uses the same unit system as the obj table.
tag : The string set in the target item's remark
frame : The absolute timeline frame to sample (optional)
Return : An object information table. Returns nil when no
matching item exists.
.exist : Whether it is visible at the target frame (boolean)
.x : Display base coordinate X
.y : Display base coordinate Y
.z : Display base coordinate Z
.zoom : Scale (1.0 = original size)
.sx : Scale along X (= zoom)
.sy : Scale along Y (= zoom)
.rx : Rotation angle around X axis (degrees, always 0)
.ry : Rotation angle around Y axis (degrees, always 0)
.rz : Rotation angle around Z axis (degrees)
.rxr : Rotation angle around X axis (radians, always 0)
.ryr : Rotation angle around Y axis (radians, always 0)
.rzr : Rotation angle around Z axis (radians)
.alpha : Opacity (0.0 - 255.0, fade applied)
.layer : Layer number where it is placed
Example:
local funnel = obj.getobject("funnel")
if funnel then
obj.x = funnel.x
obj.y = funnel.y
end
Locking to the firing position (emitter remark is "funnel"):
local fire = timelineframe - frame
local src = obj.getobject("funnel", fire)
if src then
obj.x = src.x
obj.y = src.y
end
o obj.getpixel(x, y)
Retrieves pixel information at the specified coordinates.
* A GPU->CPU image data transfer occurs on the first call (involves processing overhead).
+49
ファイルの表示
@@ -189,6 +189,55 @@
- Tabla obj - Funciones -
o obj.getobject(tag [, frame])
Obtiene la información de dibujo de otro objeto que tiene la
etiqueta especificada.
* La etiqueta coincide con el texto introducido en el campo
"Observación" del elemento de destino.
* Si se indica el segundo argumento frame, se obtienen los
valores en ese fotograma de la línea de tiempo. Si se omite,
se usa el fotograma actual.
* Si varios elementos comparten la misma etiqueta, se devuelve
con prioridad el elemento visible en el fotograma de destino.
Si ninguno es visible, se devuelve el primer elemento que
coincida.
* Los valores devueltos son las coordenadas, rotación y escala
propias del elemento. NO se incluyen las transformaciones por
control de grupo, control de cámara o efectos superiores.
* Cada valor usa el mismo sistema de unidades que la tabla obj.
tag : El texto definido en la observación del elemento de destino
frame : El fotograma absoluto de la línea de tiempo (opcional)
Retorno : Una tabla de información del objeto. Devuelve nil cuando
no existe ningún elemento coincidente.
.exist : Si es visible en el fotograma de destino (boolean)
.x : Coordenada base de visualización X
.y : Coordenada base de visualización Y
.z : Coordenada base de visualización Z
.zoom : Escala (1.0 = tamaño original)
.sx : Escala en X (= zoom)
.sy : Escala en Y (= zoom)
.rx : Ángulo de rotación en el eje X (grados, siempre 0)
.ry : Ángulo de rotación en el eje Y (grados, siempre 0)
.rz : Ángulo de rotación en el eje Z (grados)
.rxr : Ángulo de rotación en el eje X (radianes, siempre 0)
.ryr : Ángulo de rotación en el eje Y (radianes, siempre 0)
.rzr : Ángulo de rotación en el eje Z (radianes)
.alpha : Opacidad (0.0 - 255.0, fundido aplicado)
.layer : Número de capa donde está colocado
Ejemplo:
local funnel = obj.getobject("funnel")
if funnel then
obj.x = funnel.x
obj.y = funnel.y
end
Fijar a la posición de disparo (la observación del emisor es "funnel"):
local fire = timelineframe - frame
local src = obj.getobject("funnel", fire)
if src then
obj.x = src.x
obj.y = src.y
end
o obj.getpixel(x, y)
Obtiene información del píxel en las coordenadas especificadas.
* Se produce una transferencia de datos de imagen GPU→CPU en la primera llamada (con sobrecarga de procesamiento).
+47
ファイルの表示
@@ -189,6 +189,53 @@
- Tabel obj - Fungsi -
o obj.getobject(tag [, frame])
Mengambil informasi gambar dari objek lain yang memiliki tag
yang ditentukan.
* Tag cocok dengan teks yang dimasukkan pada kolom
"Catatan" item target.
* Jika argumen kedua frame diberikan, nilai pada frame tersebut
di lini masa diambil. Jika dihilangkan, frame saat ini dipakai.
* Jika beberapa item berbagi tag yang sama, item yang tampil
pada frame target dikembalikan dengan prioritas. Jika tidak
ada yang tampil, item pertama yang cocok dikembalikan.
* Nilai yang dikembalikan adalah koordinat, rotasi, dan skala
milik item itu sendiri. Transformasi dari kontrol grup,
kontrol kamera, atau efek di atasnya TIDAK disertakan.
* Setiap nilai menggunakan sistem satuan yang sama dengan tabel obj.
tag : Teks yang diatur pada catatan item target
frame : Frame absolut pada lini masa yang diambil (opsional)
Kembali : Tabel informasi objek. Mengembalikan nil jika tidak ada
item yang cocok.
.exist : Apakah tampil pada frame target (boolean)
.x : Koordinat dasar tampilan X
.y : Koordinat dasar tampilan Y
.z : Koordinat dasar tampilan Z
.zoom : Skala (1.0 = ukuran asli)
.sx : Skala arah X (= zoom)
.sy : Skala arah Y (= zoom)
.rx : Sudut rotasi sumbu X (derajat, selalu 0)
.ry : Sudut rotasi sumbu Y (derajat, selalu 0)
.rz : Sudut rotasi sumbu Z (derajat)
.rxr : Sudut rotasi sumbu X (radian, selalu 0)
.ryr : Sudut rotasi sumbu Y (radian, selalu 0)
.rzr : Sudut rotasi sumbu Z (radian)
.alpha : Opasitas (0.0 - 255.0, fade diterapkan)
.layer : Nomor layer tempat ditempatkan
Contoh:
local funnel = obj.getobject("funnel")
if funnel then
obj.x = funnel.x
obj.y = funnel.y
end
Mengunci ke posisi penembakan (catatan emitor adalah "funnel"):
local fire = timelineframe - frame
local src = obj.getobject("funnel", fire)
if src then
obj.x = src.x
obj.y = src.y
end
o obj.getpixel(x, y)
Mengambil informasi piksel pada koordinat yang ditentukan.
* Transfer data gambar GPU→CPU terjadi pada panggilan pertama (dengan overhead pemrosesan).
+44
ファイルの表示
@@ -192,6 +192,50 @@
- obj テーブル - 関数 -
○obj.getobject(tag [, frame])
指定したタグを持つ他のオブジェクトの描画情報を取得します。
※ タグは対象アイテムの「備考」に入力した文字列と一致します。
※ 第2引数 frame を指定すると、そのタイムラインフレーム時点の値を
取得します。省略時は現在フレームの値を取得します。
※ 同じタグを持つアイテムが複数ある場合、対象フレームで表示中の
アイテムを優先して返します。表示中のものが無い場合は最初に
一致したアイテムを返します。
※ 取得できる値はアイテム自身の座標・回転・拡大率です。
グループ制御・カメラ制御・上位エフェクトによる変形は含まれません。
※ 各値は obj テーブルと同一の単位系です。
tag : 対象アイテムの備考に設定した文字列
frame : 取得するタイムライン上の絶対フレーム (省略可)
戻り値 : オブジェクト情報テーブル。一致するアイテムが存在しない場合は
nil を返します。
.exist : 対象フレームで表示中かどうか (boolean)
.x : 表示基準座標 X
.y : 表示基準座標 Y
.z : 表示基準座標 Z
.zoom : 拡大率 (1.0 で等倍)
.sx : X 方向の拡大率 (= zoom)
.sy : Y 方向の拡大率 (= zoom)
.rx : X 軸回転角度 (度, 常に 0)
.ry : Y 軸回転角度 (度, 常に 0)
.rz : Z 軸回転角度 (度)
.rxr : X 軸回転角度 (ラジアン, 常に 0)
.ryr : Y 軸回転角度 (ラジアン, 常に 0)
.rzr : Z 軸回転角度 (ラジアン)
.alpha : 不透明度 (0.0 ~ 255.0, フェード反映済み)
.layer : 配置レイヤー番号
例:
local funnel = obj.getobject("funnel")
if funnel then
obj.x = funnel.x
obj.y = funnel.y
end
発射時の座標に固定する例 (発射元の備考が "funnel" の場合):
local fire = timelineframe - frame
local src = obj.getobject("funnel", fire)
if src then
obj.x = src.x
obj.y = src.y
end
○obj.getpixel(x, y)
指定座標のピクセル情報を取得します。
※ 初回呼び出し時に GPU→CPU への画像データ転送が発生します(処理負荷を伴います)。
+43
ファイルの表示
@@ -189,6 +189,49 @@
- obj 테이블 - 함수 -
○ obj.getobject(tag [, frame])
지정한 태그를 가진 다른 오브젝트의 그리기 정보를 취득합니다.
※ 태그는 대상 아이템의 "비고"에 입력한 문자열과 일치합니다.
※ 두 번째 인수 frame을 지정하면 해당 타임라인 프레임 시점의 값을
취득합니다. 생략하면 현재 프레임의 값을 취득합니다.
※ 같은 태그를 가진 아이템이 여러 개인 경우, 대상 프레임에서
표시 중인 아이템을 우선하여 반환합니다. 표시 중인 것이 없으면
처음으로 일치한 아이템을 반환합니다.
※ 취득되는 값은 아이템 자신의 좌표·회전·확대율입니다.
그룹 제어·카메라 제어·상위 이펙트에 의한 변형은 포함되지 않습니다.
※ 각 값은 obj 테이블과 동일한 단위 체계입니다.
tag : 대상 아이템의 비고에 설정한 문자열
frame : 취득할 타임라인의 절대 프레임 (생략 가능)
반환값 : 오브젝트 정보 테이블. 일치하는 아이템이 없으면 nil을 반환합니다.
.exist : 대상 프레임에서 표시 중인지 여부 (boolean)
.x : 표시 기준 좌표 X
.y : 표시 기준 좌표 Y
.z : 표시 기준 좌표 Z
.zoom : 확대율 (1.0이 등배)
.sx : X 방향 확대율 (= zoom)
.sy : Y 방향 확대율 (= zoom)
.rx : X축 회전 각도 (도, 항상 0)
.ry : Y축 회전 각도 (도, 항상 0)
.rz : Z축 회전 각도 (도)
.rxr : X축 회전 각도 (라디안, 항상 0)
.ryr : Y축 회전 각도 (라디안, 항상 0)
.rzr : Z축 회전 각도 (라디안)
.alpha : 불투명도 (0.0 ~ 255.0, 페이드 반영됨)
.layer : 배치 레이어 번호
예:
local funnel = obj.getobject("funnel")
if funnel then
obj.x = funnel.x
obj.y = funnel.y
end
발사 시 좌표로 고정하는 예 (발사원의 비고가 "funnel"인 경우):
local fire = timelineframe - frame
local src = obj.getobject("funnel", fire)
if src then
obj.x = src.x
obj.y = src.y
end
○ obj.getpixel(x, y)
지정 좌표의 픽셀 정보를 취득합니다.
※ 최초 호출 시 GPU→CPU로의 이미지 데이터 전송이 발생합니다(처리 부하 수반).
+41
ファイルの表示
@@ -189,6 +189,47 @@
- obj 表 - 函数 -
○ obj.getobject(tag [, frame])
获取具有指定标签的其他对象的绘制信息。
※ 标签与目标项目“备注”中输入的字符串相匹配。
※ 指定第二个参数 frame 时,获取该时间轴帧的数值。省略时获取当前帧。
※ 当多个项目拥有相同标签时,优先返回在目标帧显示中的项目。
若没有显示中的项目,则返回第一个匹配的项目。
※ 获取的值是项目自身的坐标、旋转和缩放。
不包含组控制、摄像机控制以及上层特效造成的变换。
※ 各数值使用与 obj 表相同的单位体系。
tag : 设置在目标项目备注中的字符串
frame : 要获取的时间轴绝对帧 (可省略)
返回值 : 对象信息表。当不存在匹配项目时返回 nil。
.exist : 是否在目标帧显示中 (boolean)
.x : 显示基准坐标 X
.y : 显示基准坐标 Y
.z : 显示基准坐标 Z
.zoom : 缩放率 (1.0 为原始大小)
.sx : X 方向缩放率 (= zoom)
.sy : Y 方向缩放率 (= zoom)
.rx : X 轴旋转角度 (度, 恒为 0)
.ry : Y 轴旋转角度 (度, 恒为 0)
.rz : Z 轴旋转角度 (度)
.rxr : X 轴旋转角度 (弧度, 恒为 0)
.ryr : Y 轴旋转角度 (弧度, 恒为 0)
.rzr : Z 轴旋转角度 (弧度)
.alpha : 不透明度 (0.0 ~ 255.0, 已应用淡入淡出)
.layer : 所在图层编号
示例:
local funnel = obj.getobject("funnel")
if funnel then
obj.x = funnel.x
obj.y = funnel.y
end
固定为发射时坐标的示例 (发射源备注为 "funnel"):
local fire = timelineframe - frame
local src = obj.getobject("funnel", fire)
if src then
obj.x = src.x
obj.y = src.y
end
○ obj.getpixel(x, y)
获取指定坐标的像素信息。
* 首次调用时发生 GPU→CPU 的图像数据传输(存在处理开销)。
+41
ファイルの表示
@@ -189,6 +189,47 @@
- obj 表 - 函式 -
○ obj.getobject(tag [, frame])
取得具有指定標籤的其他物件的繪製資訊。
※ 標籤與目標項目「備註」中輸入的字串相符。
※ 指定第二個參數 frame 時,取得該時間軸影格的數值。省略時取得目前影格。
※ 當多個項目擁有相同標籤時,優先回傳在目標影格顯示中的項目。
若沒有顯示中的項目,則回傳第一個相符的項目。
※ 取得的值是項目自身的座標、旋轉與縮放。
不包含群組控制、攝影機控制以及上層特效造成的變換。
※ 各數值使用與 obj 表相同的單位體系。
tag : 設定於目標項目備註中的字串
frame : 要取得的時間軸絕對影格 (可省略)
回傳值 : 物件資訊表。當不存在相符項目時回傳 nil。
.exist : 是否在目標影格顯示中 (boolean)
.x : 顯示基準座標 X
.y : 顯示基準座標 Y
.z : 顯示基準座標 Z
.zoom : 縮放率 (1.0 為原始大小)
.sx : X 方向縮放率 (= zoom)
.sy : Y 方向縮放率 (= zoom)
.rx : X 軸旋轉角度 (度, 恆為 0)
.ry : Y 軸旋轉角度 (度, 恆為 0)
.rz : Z 軸旋轉角度 (度)
.rxr : X 軸旋轉角度 (弧度, 恆為 0)
.ryr : Y 軸旋轉角度 (弧度, 恆為 0)
.rzr : Z 軸旋轉角度 (弧度)
.alpha : 不透明度 (0.0 ~ 255.0, 已套用淡入淡出)
.layer : 所在圖層編號
範例:
local funnel = obj.getobject("funnel")
if funnel then
obj.x = funnel.x
obj.y = funnel.y
end
固定為發射時座標的範例 (發射來源備註為 "funnel"):
local fire = timelineframe - frame
local src = obj.getobject("funnel", fire)
if src then
obj.x = src.x
obj.y = src.y
end
○ obj.getpixel(x, y)
取得指定座標的像素資訊。
* 首次呼叫時發生 GPU→CPU 的影像資料傳輸(存在處理負擔)。
+102 -2
ファイルの表示
@@ -11,6 +11,8 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
座標・拡縮・回転・不透明度の制御に加えて、`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` によるピクセル単位の画像加工、アニメーション制作向けの数学ユーティリティ群(`anim` テーブル)、4 系統のトラックバー(Track0〜Track3)によるスクリプトへのパラメータ受け渡しに対応しています。
![Image](https://github.com/routersys/YMM4-LuaScript/blob/main/docs/LuaScript.png)
---
## 目次
@@ -28,6 +30,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
- [7. スクリプトエディタの支援機能](#7-スクリプトエディタの支援機能)
- [8. インポート・エクスポート・クリア](#8-インポートエクスポートクリア)
5. [実行モデル](#実行モデル)
- [実行エンジンの自動振り分け](#実行エンジンの自動振り分け)
- [実行スレッドとタイムアウト](#実行スレッドとタイムアウト)
- [実行結果のキャッシュ](#実行結果のキャッシュ)
- [グローバル変数のリセットと整合性チェック](#グローバル変数のリセットと整合性チェック)
@@ -72,7 +75,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
### 1. スクリプトエンジン
スクリプトの実行エンジンには MoonSharp(Lua 5.2 互換)を使用しています。利用可能な標準ライブラリは以下に限定されています。
スクリプトの実行エンジンには MoonSharp(Lua 5.2 互換)を使用しています。加えて、ピクセル操作(`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata`)を含むスクリプトは、同梱した高速ランタイム(LuaJIT)で自動的に実行され、大幅に高速化されます(詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照)。どちらのエンジンでも利用可能な標準ライブラリは以下に限定されています。
- `table`、`string`、`math`、`bit32`
- 基本関数: `type`、`tostring`、`tonumber`、`select`、`error`、`assert`、`print`、`ipairs`、`pairs`、`next`、`unpack`、`setmetatable`、`getmetatable`、`rawget`、`rawset`、`rawequal`、`rawlen`、`pcall`、`xpcall`
@@ -106,6 +109,8 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
- **`obj.putpixeldata()`**: 互換性のために定義された空実装関数です。`setpixel` / `PixelDataProxy:set` による変更は自動的に反映されるため、呼び出す必要はありません。
`getpixel` / `setpixel` / `getpixeldata` のいずれかを最初に呼び出した時点で、GPU 上の画像データを CPU 側へ転送する処理が一度だけ発生します。ピクセル操作を行わないスクリプトではこの転送は発生しません。
これらのピクセル操作を含むスクリプトは、同梱の高速ランタイム(LuaJIT)で自動的に実行され、従来エンジンに比べて大幅(内部計測で数十倍)に高速化されます。出力結果は従来エンジンと一致します。詳細・制約は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照してください。
### 4. scene テーブルと ymm4 テーブル
`scene` テーブルにはシーン(プロジェクト)の解像度情報が格納されています。いずれも読み取り専用です。
@@ -186,6 +191,29 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
## 実行モデル
### 実行エンジンの自動振り分け
スクリプトは内容に応じて 2 つのエンジンへ自動的に振り分けられます。
- **ピクセル操作を含むスクリプト**(`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` を含む)→ 同梱の高速ランタイム **LuaJIT** で実行(ネイティブ実行)。
- **変形のみのスクリプト** → 従来の **MoonSharp** で実行。
スクリプトの先頭行に次のディレクティブを書くと、エンジンを明示指定できます。
- `--!native` … 高速ランタイム(LuaJIT)で実行
- `--!moonsharp` … 従来エンジン(MoonSharp)で実行
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で受け渡されます。スクリプトが無限ループに陥った場合でも **5 秒のタイムアウトでプロセスを強制終了**するため本体は固まらず、終了後は自動的に復帰します。出力結果は従来エンジンと一致します。
`obj.getobject` はネイティブ実行でも利用できます。呼び出し時に本体プロセスへ同期的に問い合わせてシーンオブジェクトを解決するため、従来エンジンと同じ結果を返します。
ネイティブ実行には次の制約があります。
- `bit32` は正しい Lua 5.2 の挙動になります。実用域(0〜2³¹未満の値・0〜31 のシフト量)では従来と一致しますが、`bit32.lshift(1, 32)` のような範囲外の特殊ケースのみ結果が変わります(ネイティブ=0、従来=1)。
- `math.random` は両エンジンとも毎フレーム `frame` でシードし直す決定論的乱数ですが、乱数列の実装が異なるためエンジンをまたぐと同じシードでも値が変わります。エンジン非依存の乱数が必要な場合は `anim.rand(min, max, seed)` を使用してください。
> 高速ランタイム(`luajit.exe` / `lua51.dll` 等)はプラグインに同梱され、本体と同じ場所の `native` フォルダーへ自動配置されます。手動インストールは不要です。
### 実行スレッドとタイムアウト
スクリプトはエフェクトインスタンスごとに確保された専用のバックグラウンドスレッド上で実行されます。実行要求は容量 1 のキューを介してこのスレッドへ渡され、メイン側は実行完了またはタイムアウトまで待機します。
@@ -296,7 +324,7 @@ obj.alpha = anim.ease_out(t) * 255
- **AviUtl 非対応**: 本プラグインは独自のスクリプト実行系であり、AviUtl 向けの EXO 出力(`.exo`)には対応していません。
- **実行タイムアウト**: スクリプトの実行は 5000ms(5秒)でタイムアウトし、超過した場合は強制終了されエラーとして扱われます。無限ループが発生しないよう注意してください。
- **利用可能な標準ライブラリの制限**: `table`、`string`、`math`、`bit32` および基本関数のみ利用できます。`io`、`os`、`debug`、`ffi`、`require` は利用できません。
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します。不要な場合は呼び出しを省略することで処理を高速化できます。
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは高速ランタイム(LuaJIT)で自動実行され大幅に高速化されます。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
- **`math.random` はフレームごとの決定論的な乱数**: 毎フレーム `frame` の値でシードし直されるため、同一フレームでは常に同じ値になります。フレームをまたいで変化する乱数的な値が必要な場合は `anim.rand` の利用を検討してください。
- **`obj.oz` は出力に反映されません**: スクリプト実行後にコンテキストへ読み戻されますが、現在の実装では中心点オフセットの出力計算に使用されていません。
- **エクスポートは先頭の1件のみ**: 複数アイテムを選択した状態でも、エクスポートされるスクリプトは先頭のアイテムのもののみです(インポート・クリアは選択中のすべてのアイテムに適用されます)。
@@ -312,6 +340,78 @@ obj.alpha = anim.ease_out(t) * 255
作者は、本プラグインの使用または使用不能に起因するいかなる損害についても、一切の責任を負いません。
ご利用は自己責任でお願いします。
---
## サードパーティライセンス
本プラグインは以下のサードパーティソフトウェアを同梱・使用しています。各ライセンスの全文は、配布パッケージ(`.ymme`)内の `LICENSE` フォルダーおよびリポジトリの [`.github/LICENSE`](.github/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)
```
Copyright (c) 2014-2016, Marco Mastropaolo
All rights reserved.
Parts of the string library are based on the KopiLua project (https://github.com/NLua/KopiLua)
Copyright (c) 2012 LoDC
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
```
### LuaJIT(MIT License)
同梱の高速ランタイム(`native/luajit.exe`・`native/lua51.dll`)は LuaJIT v2.1 です。LuaJIT 本体は MIT License で配布されており、その中に Lua 5.1/5.2(Copyright © 1994-2012 Lua.org, PUC-Rio、MIT License)および dlmalloc(パブリックドメイン)のコードを含みます。以下は LuaJIT 本体の著作権表示です(Lua・dlmalloc を含む全文は `LICENSE/LuaJIT.txt` を参照)。
```
LuaJIT -- a Just-In-Time Compiler for Lua. https://luajit.org/
Copyright (C) 2005-2026 Mike Pall. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
```
---
+1
ファイルの表示
@@ -0,0 +1 @@
luascript.routersys.com
バイナリ
ファイルの表示
バイナリファイルは表示されません。

変更後

幅:  |  高さ:  |  サイズ: 231 KiB

+630
ファイルの表示
@@ -0,0 +1,630 @@
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Luaスクリプト for YMM4 サンプル集</title>
</head>
<body>
<img src="LuaScript.png" alt="Luaスクリプト for YMM4" width="640">
<h1>Luaスクリプト for YMM4 サンプル集</h1>
<p>
YukkuriMovieMaker4 の「Luaスクリプト」映像エフェクトで使えるサンプルと、
利用可能な変数・関数・定数の一覧をまとめたページです。
各サンプルはエフェクトのスクリプト欄にそのまま貼り付けて利用できます。
スクリプトエンジンは MoonSharp (Lua 5.2 互換) です。
</p>
<p>
変数・関数の詳細な仕様は、スクリプトエディタのヘルプ、または
<code>docs/LuaScript.ja-jp.txt</code> を参照してください。
</p>
<hr>
<h2>目次</h2>
<nav>
<ul>
<li><a href="#about">サンプルの読み方</a></li>
<li><a href="#basic">1. 基本</a></li>
<li><a href="#motion">2. 座標と動き</a></li>
<li><a href="#rotation">3. 回転</a></li>
<li><a href="#scale">4. 拡大・変形</a></li>
<li><a href="#alpha">5. 不透明度・フェード</a></li>
<li><a href="#ease">6. anim 補間・イージング</a></li>
<li><a href="#range">7. anim 範囲・周期</a></li>
<li><a href="#vector">8. anim ベクトル・幾何</a></li>
<li><a href="#noise">9. anim ノイズ・乱数</a></li>
<li><a href="#animcolor">10. anim 色</a></li>
<li><a href="#const">11. anim 定数</a></li>
<li><a href="#getobject">12. 他オブジェクトの参照 (obj.getobject)</a></li>
<li><a href="#pixel">13. ピクセル操作</a></li>
<li><a href="#scene">14. シーン情報 (scene)</a></li>
<li><a href="#ymm4">15. 環境・メタ情報 (ymm4)</a></li>
<li><a href="#globals">16. グローバル変数</a></li>
<li><a href="#stdlib">17. 標準ライブラリ</a></li>
<li><a href="#reference">クイックリファレンス</a></li>
</ul>
</nav>
<hr>
<h2 id="about">サンプルの読み方</h2>
<p>
スクリプト内では、変更可能な <code>obj</code> の値(座標・拡大率・回転・不透明度など)を
書き換えると描画に反映されます。読み戻されるのは
<code>x, y, z, ox, oy, zoom, aspect, alpha, rx, ry, rz</code>
(およびラジアン版 <code>rxr, ryr, rzr</code>、独立スケール <code>sx, sy</code>)です。
</p>
<p>
<code>time</code> はアイテム基準の経過秒数、<code>obj.t</code> はアイテム内の進行割合
(0.0 ~ 1.0) です。グローバル変数の状態はフレーム間で保持されません。
<code>math.random</code> は毎フレーム同じシードで初期化されるため、同一フレームでは
同じ値を返します。安定した乱数が必要な場合は <code>anim.rand</code> を使います。
</p>
<hr>
<h2 id="basic">1. 基本</h2>
<h3>1-1. フェードイン (デフォルトスクリプト)</h3>
<pre><code>obj.alpha = math.min(time * 255, 255)</code></pre>
<h3>1-2. フェードアウト</h3>
<pre><code>obj.alpha = math.max((obj.totalframe - obj.frame) / obj.framerate * 255, 0)</code></pre>
<h3>1-3. Track0 で不透明度を制御</h3>
<pre><code>obj.alpha = obj.track0</code></pre>
<h3>1-4. 時間に応じて回転</h3>
<pre><code>obj.rz = time * 90</code></pre>
<h3>1-5. Track0 でズームを制御</h3>
<pre><code>obj.zoom = obj.zoom * (1 + obj.track0 / 100)</code></pre>
<hr>
<h2 id="motion">2. 座標と動き</h2>
<h3>2-1. 左右の揺れ</h3>
<p>Track0 を振幅(px)、Track1 を周波数(回/秒)として使います。</p>
<pre><code>local amp = obj.track0
local freq = obj.track1
obj.x = obj.x + math.sin(time * anim.tau * freq) * amp</code></pre>
<h3>2-2. 円運動</h3>
<pre><code>local r = obj.track0
local dx, dy = anim.polar(r, time * 90)
obj.x = obj.x + dx
obj.y = obj.y + dy</code></pre>
<h3>2-3. バウンド (跳ねる)</h3>
<pre><code>local h = obj.track0
obj.y = obj.y - anim.bounce(anim.pingpong(time, 1)) * h</code></pre>
<h3>2-4. ゆらぎ (ノイズによる手ぶれ風)</h3>
<pre><code>obj.x = obj.x + (anim.noise(time * 2, 0, 0) - 0.5) * 20
obj.y = obj.y + (anim.noise(0, time * 2, 0) - 0.5) * 20
obj.rz = (anim.noise(0, 0, time * 2) - 0.5) * 10</code></pre>
<h3>2-5. 中心オフセットを基準に振り子運動</h3>
<p>回転中心 <code>ox, oy</code> をずらして振り子のように揺らします。</p>
<pre><code>obj.oy = -obj.hh
obj.rz = math.sin(time * anim.tau) * 30</code></pre>
<hr>
<h2 id="rotation">3. 回転</h2>
<h3>3-1. 度とラジアン</h3>
<p>
<code>rx, ry, rz</code> は度、<code>rxr, ryr, rzr</code> はラジアンです。
ラジアン版を変更するとそちらが優先して反映されます。
</p>
<pre><code>obj.rzr = time * anim.tau</code></pre>
<h3>3-2. Y軸回転で立体的に回す</h3>
<pre><code>obj.ry = time * 180</code></pre>
<h3>3-3. 加速しながら回転 (イージング)</h3>
<pre><code>obj.rz = anim.ease_in(obj.t) * 360</code></pre>
<hr>
<h2 id="scale">4. 拡大・変形</h2>
<h3>4-1. 弾むように登場 (スケールイン)</h3>
<pre><code>local p = anim.duration(time, 0.3)
obj.zoom = obj.zoom * anim.elastic(p)</code></pre>
<h3>4-2. アスペクト比で横伸び・縦伸び</h3>
<p>
<code>aspect</code> は正で横方向に縮小、負で縦方向に縮小します。
</p>
<pre><code>obj.aspect = math.sin(time * anim.tau) * 0.5</code></pre>
<h3>4-3. X・Y を独立して拡大 (sx, sy)</h3>
<p>ぷにぷにと潰れる動きを <code>sx, sy</code> で表現します。</p>
<pre><code>local s = math.sin(time * anim.tau * 2) * 0.2
obj.sx = 1 + s
obj.sy = 1 - s</code></pre>
<hr>
<h2 id="alpha">5. 不透明度・フェード</h2>
<h3>5-1. 遅延フェードイン</h3>
<pre><code>local p = anim.duration(anim.delay(time, 0.5), 1)
obj.alpha = p * 255</code></pre>
<h3>5-2. 点滅 (矩形波)</h3>
<pre><code>obj.alpha = anim.square(time, 4) * 255</code></pre>
<h3>5-3. 滑らかな明滅 (正弦波)</h3>
<pre><code>obj.alpha = anim.oscillate(time, 64, 255, 1)</code></pre>
<hr>
<h2 id="ease">6. anim 補間・イージング</h2>
<h3>6-1. 2点間をイージングで移動</h3>
<pre><code>local tx, ty = 200, -100
local p = anim.ease_in_out(obj.t)
obj.x = anim.lerp(obj.x, tx, p)
obj.y = anim.lerp(obj.y, ty, p)</code></pre>
<h3>6-2. 行き過ぎてから戻る (back)</h3>
<pre><code>obj.x = obj.x + anim.back(obj.t) * 200</code></pre>
<h3>6-3. しきい値で切り替え (step / smoothstep)</h3>
<pre><code>obj.alpha = anim.smoothstep(0, 0.5, obj.t) * 255</code></pre>
<p>補間・イージング系関数の一覧です。</p>
<table border="1">
<tr><th>関数</th><th>説明</th></tr>
<tr><td>anim.lerp(a, b, t)</td><td>a と b を t (0.0~1.0) で線形補間</td></tr>
<tr><td>anim.smoothstep(e0, e1, x)</td><td>e0~e1 をエルミート補間で滑らかに遷移</td></tr>
<tr><td>anim.smootherstep(e0, e1, x)</td><td>2次導関数まで連続な、より滑らかな遷移</td></tr>
<tr><td>anim.ease_in(t)</td><td>2次イーズイン (加速)</td></tr>
<tr><td>anim.ease_out(t)</td><td>2次イーズアウト (減速)</td></tr>
<tr><td>anim.ease_in_out(t)</td><td>2次イーズイン・アウト (加速後減速)</td></tr>
<tr><td>anim.elastic(t)</td><td>弾むようなスプリングイージング</td></tr>
<tr><td>anim.back(t)</td><td>行き過ぎてから戻るイージング</td></tr>
<tr><td>anim.bounce(t)</td><td>バウンドするイージング</td></tr>
<tr><td>anim.step(edge, x)</td><td>x が edge 以上なら 1.0、未満なら 0.0</td></tr>
<tr><td>anim.bezier(t, p0, p1, p2, p3)</td><td>t における3次ベジェ曲線の値</td></tr>
</table>
<hr>
<h2 id="range">7. anim 範囲・周期</h2>
<h3>7-1. 値の範囲変換 (map)</h3>
<pre><code>obj.rz = anim.map(obj.track0, 0, 100, -180, 180)</code></pre>
<h3>7-2. 三角波で往復</h3>
<pre><code>obj.x = obj.x + (anim.triangle(time, 1) - 0.5) * 200</code></pre>
<p>範囲・周期系関数の一覧です。</p>
<table border="1">
<tr><th>関数</th><th>説明</th></tr>
<tr><td>anim.clamp(v, lo, hi)</td><td>v を lo ~ hi の範囲に収める</td></tr>
<tr><td>anim.map(v, a1, b1, a2, b2)</td><td>範囲 a1~b1 の v を a2~b2 に変換</td></tr>
<tr><td>anim.norm(v, lo, hi)</td><td>v が lo~hi のどの割合 (0.0~1.0) かを取得</td></tr>
<tr><td>anim.wrap(v, lo, hi)</td><td>v を lo ~ hi でループさせる</td></tr>
<tr><td>anim.pingpong(t, len)</td><td>0 ~ len を往復する値</td></tr>
<tr><td>anim.sign(v)</td><td>符号 (正=1, 負=-1, ゼロ=0)</td></tr>
<tr><td>anim.fract(v)</td><td>小数部分のみを取得</td></tr>
<tr><td>anim.oscillate(t, lo, hi, freq)</td><td>freq の周波数で lo~hi を正弦波で往復</td></tr>
<tr><td>anim.triangle(t, freq)</td><td>freq の周波数で 0.0~1.0 を往復する三角波</td></tr>
<tr><td>anim.square(t, freq)</td><td>freq の周波数で 1.0 と 0.0 を切り替える矩形波</td></tr>
<tr><td>anim.duration(t, dur)</td><td>時間 dur に対する割合 (0.0~1.0, clamp あり)</td></tr>
<tr><td>anim.delay(t, d)</td><td>時間 d 経過後から開始する時間 (0以下は0)</td></tr>
</table>
<hr>
<h2 id="vector">8. anim ベクトル・幾何</h2>
<h3>8-1. 座標を回転させる</h3>
<pre><code>local rx, ry = anim.rotate(obj.track0, 0, time * 90)
obj.x = obj.x + rx
obj.y = obj.y + ry</code></pre>
<h3>8-2. 2点間の距離で挙動を変える</h3>
<pre><code>local d = anim.dist(obj.x, obj.y, 0, 0)
obj.alpha = anim.clamp(255 - d, 0, 255)</code></pre>
<p>ベクトル・幾何系関数の一覧です。</p>
<table border="1">
<tr><th>関数</th><th>説明</th></tr>
<tr><td>anim.len(x, y)</td><td>ベクトル (x, y) の長さ</td></tr>
<tr><td>anim.dist(x1, y1, x2, y2)</td><td>2点間の距離</td></tr>
<tr><td>anim.dot(x1, y1, x2, y2)</td><td>2ベクトルの内積</td></tr>
<tr><td>anim.normalize(x, y)</td><td>正規化した方向ベクトル (Tuple で返却)</td></tr>
<tr><td>anim.polar(r, a)</td><td>半径 r・角度 a(度) から移動量 (x, y)</td></tr>
<tr><td>anim.rotate(x, y, a)</td><td>(x, y) を a(度) 回転させた座標</td></tr>
</table>
<hr>
<h2 id="noise">9. anim ノイズ・乱数</h2>
<h3>9-1. 安定した乱数で個体差をつける</h3>
<p>
<code>anim.rand</code> はシード引数に基づく決定的な乱数です。レイヤー番号をシードにすると
オブジェクトごとに異なる固定値が得られます。
</p>
<pre><code>local offset = anim.rand(-50, 50, obj.layer)
obj.x = obj.x + offset</code></pre>
<h3>9-2. ノイズで揺らぐ不透明度</h3>
<pre><code>obj.alpha = anim.noise(time, obj.layer, 0) * 255</code></pre>
<table border="1">
<tr><th>関数</th><th>説明</th></tr>
<tr><td>anim.noise(x, y, z)</td><td>1~3次元の滑らかなノイズ (0.0~1.0)</td></tr>
<tr><td>anim.rand(min, max, s)</td><td>シード s に基づく安定した乱数</td></tr>
</table>
<hr>
<h2 id="animcolor">10. anim 色</h2>
<h3>10-1. 時間で色相を回す (虹色)</h3>
<pre><code>local hue = anim.wrap(time * 60, 0, 360)
local cr, cg, cb = anim.hsv_to_rgb(hue, 1, 1)
local pd = obj.getpixeldata()
local n = pd.width * pd.height
for i = 0, n - 1 do
local base = i * 4
pd:set(base + 1, pd:get(base + 1) * cr / 255)
pd:set(base + 2, pd:get(base + 2) * cg / 255)
pd:set(base + 3, pd:get(base + 3) * cb / 255)
end</code></pre>
<table border="1">
<tr><th>関数</th><th>説明</th></tr>
<tr><td>anim.hsv_to_rgb(h, s, v)</td><td>HSV (色相0~360, 彩度0~1, 明度0~1) を RGB に変換</td></tr>
<tr><td>anim.rgb_to_hsv(r, g, b)</td><td>RGB (0~255) を HSV に変換</td></tr>
</table>
<hr>
<h2 id="const">11. anim 定数</h2>
<table border="1">
<tr><th>定数</th><th>説明</th></tr>
<tr><td>anim.tau</td><td>円周率の2倍 (math.pi * 2)</td></tr>
<tr><td>anim.e</td><td>ネイピア数 (math.exp(1))</td></tr>
<tr><td>anim.phi</td><td>黄金比 ((1 + math.sqrt(5)) / 2)</td></tr>
<tr><td>anim.sqrt2</td><td>2の平方根 (math.sqrt(2))</td></tr>
</table>
<hr>
<h2 id="getobject">12. 他オブジェクトの参照 (obj.getobject)</h2>
<p>
<code>obj.getobject(tag [, frame])</code> は、対象アイテムの「備考」欄に入力した文字列を
タグとして、そのアイテムの描画情報を取得します。備考欄はプロパティエリアの上側にあります。
第2引数 <code>frame</code> を指定すると、そのタイムラインフレーム時点の値を取得します
(省略時は現在フレーム)。返り値は対象アイテム自身の座標・回転・拡大率であり、
グループ制御・カメラ制御による変形は含みません。一致するアイテムが無い場合は
<code>nil</code> を返します。同じタグのアイテムが複数あるときは、対象フレームで
表示中のものを優先します。
</p>
<h3>12-1. 発射元の座標に合わせる</h3>
<pre><code>local src = obj.getobject("routersys")
if src then
obj.x = src.x
obj.y = src.y
end</code></pre>
<h3>12-2. 発射元へ向かって移動する</h3>
<pre><code>local target = obj.getobject("routersys")
if target then
local p = anim.ease_in_out(obj.t)
obj.x = anim.lerp(obj.x, target.x, p)
obj.y = anim.lerp(obj.y, target.y, p)
end</code></pre>
<h3>12-3. 発射元へ向きながら移動する (ファンネル風)</h3>
<pre><code>local target = obj.getobject("routersys")
if target then
local p = anim.ease_in_out(obj.t)
local nx = anim.lerp(obj.x, target.x, p)
local ny = anim.lerp(obj.y, target.y, p)
obj.rz = math.deg(math.atan2(target.y - obj.y, target.x - obj.x))
obj.x = nx
obj.y = ny
end</code></pre>
<h3>12-4. 一定速度で接近し、到達したら停止</h3>
<pre><code>local target = obj.getobject("routersys")
if target then
local dx = target.x - obj.x
local dy = target.y - obj.y
local dist = anim.len(dx, dy)
if dist > 0 then
local step = math.min(dist, obj.track0 * obj.time)
obj.x = obj.x + dx / dist * step
obj.y = obj.y + dy / dist * step
end
end</code></pre>
<h3>12-5. 表示中のときだけ追従する</h3>
<pre><code>local target = obj.getobject("routersys")
if target and target.exist then
obj.x = target.x
obj.y = target.y
end</code></pre>
<h3>12-6. 発射元の拡大率・回転・不透明度も引き継ぐ</h3>
<pre><code>local src = obj.getobject("routersys")
if src then
obj.x = src.x
obj.y = src.y
obj.zoom = src.zoom
obj.rz = src.rz
obj.alpha = src.alpha
end</code></pre>
<h3>12-7. 発射時の座標に固定する</h3>
<p>
弾の発射フレーム (弾アイテムの開始フレーム) は <code>timelineframe - frame</code> で
求まります。そのフレーム時点の発射元座標を取得すれば、発射元が動いても弾の原点は
発射位置に固定されます。
</p>
<pre><code>local fire = timelineframe - frame
local src = obj.getobject("routersys", fire)
if src then
obj.x = src.x
obj.y = src.y
end</code></pre>
<p>返り値テーブルのメンバーは以下のとおりです。</p>
<table border="1">
<tr><th>メンバー</th><th>説明</th></tr>
<tr><td>exist</td><td>対象フレームが表示期間内か (boolean)</td></tr>
<tr><td>x / y / z</td><td>描画位置 (ピクセル)</td></tr>
<tr><td>zoom / sx / sy</td><td>拡大率 (1.0 で等倍)</td></tr>
<tr><td>rx / ry / rz</td><td>X / Y / Z 軸回転角 (度)</td></tr>
<tr><td>rxr / ryr / rzr</td><td>X / Y / Z 軸回転角 (ラジアン)</td></tr>
<tr><td>alpha</td><td>不透明度 (0.0 ~ 255.0)</td></tr>
<tr><td>layer</td><td>レイヤー番号</td></tr>
</table>
<hr>
<h2 id="pixel">13. ピクセル操作</h2>
<p>
ピクセル操作は実際の入力画像へアクセスするため、初回アクセス時に画像データの
転送が発生します。座標は画像の左上を (0, 0) とし、右・下方向が正です。
取得値はストレートアルファ相当です。
</p>
<h3>13-1. getpixel / setpixel で赤成分を反転</h3>
<pre><code>for y = 0, obj.h - 1 do
for x = 0, obj.w - 1 do
local r, g, b, a = obj.getpixel(x, y)
obj.setpixel(x, y, 255 - r, g, b, a)
end
end</code></pre>
<h3>13-2. getpixeldata でグレースケール (高速)</h3>
<p>
<code>obj.getpixeldata()</code> はピクセルへ直接アクセスできるプロキシを返します。
インデックスは 1 始まりで、チャンネルは R, G, B, A の繰り返しです。
<code>pixel(x, y)</code> の R チャンネルのインデックスは <code>(y * obj.w + x) * 4 + 1</code> です。
</p>
<pre><code>local pd = obj.getpixeldata()
local w = pd.width
local h = pd.height
for y = 0, h - 1 do
for x = 0, w - 1 do
local base = (y * w + x) * 4
local r = pd:get(base + 1)
local g = pd:get(base + 2)
local b = pd:get(base + 3)
local 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</code></pre>
<h3>13-3. 中心からの距離でフェード (円形ビネット)</h3>
<pre><code>local pd = obj.getpixeldata()
local w = pd.width
local h = pd.height
local cx = w / 2
local cy = h / 2
local maxd = anim.len(cx, cy)
for y = 0, h - 1 do
for x = 0, w - 1 do
local base = (y * w + x) * 4
local d = anim.len(x - cx, y - cy)
local k = anim.clamp(1 - d / maxd, 0, 1)
pd:set(base + 4, pd:get(base + 4) * k)
end
end</code></pre>
<p>
<code>obj.putpixeldata()</code> は AviUtl との互換性のために存在しますが、
このプラグインでは変更が自動的に反映されるため呼び出す必要はありません (no-op)。
</p>
<table border="1">
<tr><th>関数</th><th>戻り値</th><th>説明</th></tr>
<tr><td>obj.getpixel(x, y)</td><td>r, g, b, a</td><td>指定座標のピクセルを取得 (各成分 0~255)</td></tr>
<tr><td>obj.setpixel(x, y, r, g, b [, a])</td><td>なし</td><td>指定座標へ書き込み (a 既定 255)</td></tr>
<tr><td>obj.getpixeldata()</td><td>PixelDataProxy</td><td>全ピクセルへの直接アクセスプロキシ</td></tr>
<tr><td>obj.putpixeldata()</td><td>なし</td><td>互換用の空実装</td></tr>
</table>
<hr>
<h2 id="scene">14. シーン情報 (scene)</h2>
<h3>14-1. シーンサイズに対する相対配置</h3>
<pre><code>obj.x = scene.cx * obj.track0 / 100</code></pre>
<table border="1">
<tr><th>メンバー</th><th>説明</th></tr>
<tr><td>scene.width</td><td>シーンの横解像度 (ピクセル)</td></tr>
<tr><td>scene.height</td><td>シーンの縦解像度 (ピクセル)</td></tr>
<tr><td>scene.cx</td><td>横解像度の半分 (= scene.width / 2)</td></tr>
<tr><td>scene.cy</td><td>縦解像度の半分 (= scene.height / 2)</td></tr>
</table>
<hr>
<h2 id="ymm4">15. 環境・メタ情報 (ymm4)</h2>
<h3>15-1. グループ内のインデックスで時間差をつける</h3>
<pre><code>local d = ymm4.group_index * 0.1
local p = anim.duration(anim.delay(time, d), 0.5)
obj.alpha = p * 255</code></pre>
<h3>15-2. グループ内の進行割合で配置をずらす</h3>
<pre><code>obj.x = obj.x + ymm4.group_ratio * 400</code></pre>
<h3>15-3. 出力時のみ挙動を変える</h3>
<pre><code>if ymm4.is_saving then
obj.alpha = 255
else
obj.alpha = 128
end</code></pre>
<table border="1">
<tr><th>メンバー</th><th>説明</th></tr>
<tr><td>ymm4.group_index</td><td>グループ制御内の現在のインデックス (0始まり)</td></tr>
<tr><td>ymm4.group_count</td><td>グループ制御内の総アイテム数</td></tr>
<tr><td>ymm4.group_ratio</td><td>グループ内の進行割合 (group_index / group_count)</td></tr>
<tr><td>ymm4.timeline_totalframe</td><td>タイムライン全体の総フレーム数</td></tr>
<tr><td>ymm4.timeline_totaltime</td><td>タイムライン全体の総時間 (秒)</td></tr>
<tr><td>ymm4.time_ratio</td><td>現在の再生位置の割合 (0.0 ~ 1.0)</td></tr>
<tr><td>ymm4.is_saving</td><td>動画出力中のみ true</td></tr>
<tr><td>ymm4.is_playing</td><td>再生中のみ true</td></tr>
<tr><td>ymm4.is_paused</td><td>一時停止中のみ true</td></tr>
<tr><td>ymm4.scene_id</td><td>現在のシーンを識別する文字列 (Guid)</td></tr>
</table>
<hr>
<h2 id="globals">16. グローバル変数</h2>
<p>以下の変数はスクリプトのグローバルスコープで直接参照できます (すべて読み取り専用)。</p>
<table border="1">
<tr><th>変数</th><th>説明</th></tr>
<tr><td>time</td><td>オブジェクト基準の現在時間 (秒)。obj.time と同じ</td></tr>
<tr><td>frame</td><td>オブジェクト基準の現在フレーム番号。obj.frame と同じ</td></tr>
<tr><td>totalframe</td><td>オブジェクトの総フレーム数。obj.totalframe と同じ</td></tr>
<tr><td>framerate</td><td>フレームレート (fps)。obj.framerate と同じ</td></tr>
<tr><td>timelineframe</td><td>タイムライン先頭からの絶対フレーム番号</td></tr>
<tr><td>timelinetime</td><td>タイムライン基準の現在時間 (秒)</td></tr>
<tr><td>layer</td><td>配置されているレイヤー番号。obj.layer と同じ</td></tr>
<tr><td>obj / scene / ymm4 / anim</td><td>各テーブル (本ページ参照)</td></tr>
</table>
<hr>
<h2 id="stdlib">17. 標準ライブラリ</h2>
<p>利用できる標準ライブラリは以下に限定されます。io, os, debug, ffi, require 等は使用できません。</p>
<h3>math</h3>
<p>
abs, ceil, cos, exp, floor, fmod, huge, log, max, min, modf, pi, random, randomseed,
sin, sqrt, tan, atan, atan2, deg, rad, ldexp, frexp, sinh, cosh, tanh, type,
tointeger, maxinteger, mininteger
</p>
<h3>string</h3>
<p>
format, len, sub, upper, lower, rep, reverse, find, match, gmatch, gsub, byte, char,
dump, pack, unpack, packsize
</p>
<h3>table</h3>
<p>insert, remove, sort, concat, unpack, move</p>
<h3>bit32</h3>
<p>
band, bor, bxor, bnot, lshift, rshift, arshift, extract, replace, btest, countlz, countrz
</p>
<h3>基本関数</h3>
<p>
type, tostring, tonumber, select, error, assert, print, ipairs, pairs, next, unpack,
setmetatable, getmetatable, rawget, rawset, rawequal, rawlen, pcall, xpcall
</p>
<hr>
<h2 id="reference">クイックリファレンス</h2>
<h3>obj (変更可能メンバー)</h3>
<table border="1">
<tr><th>メンバー</th><th>説明</th></tr>
<tr><td>obj.x / obj.y / obj.z</td><td>描画位置 (ピクセル)</td></tr>
<tr><td>obj.ox / obj.oy / obj.oz</td><td>回転中心のオフセット (ピクセル)</td></tr>
<tr><td>obj.zoom</td><td>拡大率 (sx と sy の平均、1.0 で等倍)</td></tr>
<tr><td>obj.aspect</td><td>アスペクト比 (-1.0 ~ 1.0)</td></tr>
<tr><td>obj.sx / obj.sy</td><td>X / Y 方向の独立拡大率</td></tr>
<tr><td>obj.alpha</td><td>不透明度 (0.0 ~ 255.0)</td></tr>
<tr><td>obj.rx / obj.ry / obj.rz</td><td>X / Y / Z 軸回転角 (度)</td></tr>
<tr><td>obj.rxr / obj.ryr / obj.rzr</td><td>X / Y / Z 軸回転角 (ラジアン)</td></tr>
</table>
<h3>obj (読み取り専用メンバー)</h3>
<table border="1">
<tr><th>メンバー</th><th>説明</th></tr>
<tr><td>obj.w / obj.h</td><td>入力画像の幅 / 高さ (ピクセル)</td></tr>
<tr><td>obj.hw / obj.hh</td><td>幅 / 高さの半分</td></tr>
<tr><td>obj.cx / obj.cy</td><td>画像中心 (= hw / hh)</td></tr>
<tr><td>obj.cz / obj.sz</td><td>常に 0 / 常に 1</td></tr>
<tr><td>obj.diagonal</td><td>対角線長 (sqrt(w^2 + h^2))</td></tr>
<tr><td>obj.time / obj.frame</td><td>アイテム基準の経過時間 (秒) / フレーム</td></tr>
<tr><td>obj.totalframe / obj.totaltime</td><td>アイテムの総フレーム数 / 総時間 (秒)</td></tr>
<tr><td>obj.t</td><td>アイテム内の進行割合 (0.0 ~ 1.0)</td></tr>
<tr><td>obj.framerate</td><td>フレームレート (fps)</td></tr>
<tr><td>obj.layer</td><td>レイヤー番号</td></tr>
<tr><td>obj.index / obj.num</td><td>グループ内のインデックス / 総数</td></tr>
<tr><td>obj.track0 ~ obj.track3</td><td>エフェクトパネルの各トラックバーの値</td></tr>
</table>
<h3>obj 関数</h3>
<table border="1">
<tr><th>関数</th><th>説明</th></tr>
<tr><td>obj.getobject(tag [, frame])</td><td>他アイテムの描画情報を取得 (本ページ 12 章)</td></tr>
<tr><td>obj.getpixel(x, y)</td><td>ピクセル取得</td></tr>
<tr><td>obj.setpixel(x, y, r, g, b [, a])</td><td>ピクセル書き込み</td></tr>
<tr><td>obj.getpixeldata()</td><td>ピクセル直接アクセスプロキシ</td></tr>
<tr><td>obj.putpixeldata()</td><td>互換用の空実装</td></tr>
</table>
<hr>
<h2>非対応・制限事項</h2>
<ul>
<li>AviUtl2 の obj.effect(), obj.draw(), obj.drawpoly(), obj.load() 等は非対応です。</li>
<li>obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor() 等は非対応です。</li>
<li>scene.set(), scene.get() 等は非対応です (scene.width / scene.height の読み取りのみ)。</li>
<li>ファイルアクセス (require, dofile, io 等) は非対応です。</li>
<li>スクリプトのタイムアウトは 5 秒です。無限ループに注意してください。</li>
<li>--track@, --check@ 等のヘッダーディレクティブは非対応です (Track0 ~ Track3 のみ)。</li>
</ul>
<hr>
<p>
Luaスクリプト for YMM4 / MIT License /
<a href="https://github.com/routersys/YMM4-LuaScript">https://github.com/routersys/YMM4-LuaScript</a>
</p>
</body>
</html>
バイナリ
ファイルの表示
バイナリファイルは表示されません。
バイナリ
ファイルの表示
バイナリファイルは表示されません。
+25
ファイルの表示
@@ -0,0 +1,25 @@
local shimPath = arg[1]
local vectorsPath = arg[2]
assert(loadfile(shimPath))()
local f = assert(io.open(vectorsPath, "r"))
local out = {}
for line in f:lines() do
local chunk = loadstring("return " .. line)
if not chunk then
out[#out + 1] = "ERROR"
else
local ok, res = pcall(chunk)
if not ok then
out[#out + 1] = "ERROR"
elseif type(res) == "boolean" then
out[#out + 1] = res and "true" or "false"
else
out[#out + 1] = string.format("%.17g", res)
end
end
end
f:close()
io.write(table.concat(out, "\n"))
+347
ファイルの表示
@@ -0,0 +1,347 @@
local ffi = require("ffi")
local bit = require("bit")
local i64 = ffi.typeof("int64_t")
local u32 = ffi.typeof("uint32_t")
local u64 = ffi.typeof("uint64_t")
local function tou(d)
return tonumber(u32(i64(d)))
end
local function umul32(a, b)
return tonumber(u32(u64(a) * u64(b)))
end
local function mask(width)
if width <= 0 then return 0 end
if width >= 32 then return tou(0xFFFFFFFF) end
return bit.lshift(1, width) - 1
end
local function validate(pos, width)
if pos < 0 or width < 1 or pos + width > 32 then
error("trying to access non-existent bits")
end
end
bit32 = {}
function bit32.band(...) return tou(bit.band(...)) end
function bit32.bor(...) return tou(bit.bor(...)) end
function bit32.bxor(...) return tou(bit.bxor(...)) end
function bit32.btest(...) return tou(bit.band(...)) ~= 0 end
function bit32.bnot(x) return tou(bit.bnot(x)) end
function bit32.lshift(x, n)
if n <= -32 or n >= 32 then return 0 end
if n >= 0 then return tou(bit.lshift(x, n)) end
return tou(bit.rshift(x, -n))
end
function bit32.rshift(x, n) return bit32.lshift(x, -n) end
function bit32.arshift(x, n)
if n < 0 then return bit32.lshift(x, -n) end
if n > 31 then n = 31 end
return tou(bit.arshift(x, n))
end
function bit32.lrotate(x, n) return tou(bit.rol(x, n)) end
function bit32.rrotate(x, n) return tou(bit.ror(x, n)) end
function bit32.extract(v, pos, width)
width = width or 1
validate(pos, width)
return tou(bit.band(bit.rshift(v, pos), mask(width)))
end
function bit32.replace(v, u, pos, width)
width = width or 1
validate(pos, width)
local m = bit.lshift(mask(width), pos)
return tou(bit.bor(bit.band(v, bit.bnot(m)), bit.band(bit.lshift(u, pos), m)))
end
if rawlen == nil then
rawlen = function(x)
local t = type(x)
if t == "table" then return #x end
if t == "string" then return string.len(x) end
error("table or string expected")
end
end
local floor = math.floor
local abs = math.abs
local sqrt = math.sqrt
local sin = math.sin
local cos = math.cos
local fmod = math.fmod
local pi = math.pi
local tau = pi * 2
local function clamp(v, lo, hi)
if v < lo then return lo end
if v > hi then return hi end
return v
end
anim = {}
anim.tau = tau
anim.e = math.exp(1)
anim.phi = (1 + sqrt(5)) / 2
anim.sqrt2 = sqrt(2)
function anim.lerp(a, b, t) return a + (b - a) * t end
function anim.smoothstep(e0, e1, x)
local span = e1 - e0
local t = span == 0 and 0 or clamp((x - e0) / span, 0, 1)
return t * t * (3 - 2 * t)
end
function anim.smootherstep(e0, e1, x)
local span = e1 - e0
local t = span == 0 and 0 or clamp((x - e0) / span, 0, 1)
return t * t * t * (t * (6 * t - 15) + 10)
end
function anim.clamp(v, lo, hi) return clamp(v, lo, hi) end
function anim.map(v, a1, b1, a2, b2)
local range = b1 - a1
if range == 0 then return a2 end
return a2 + (b2 - a2) * (v - a1) / range
end
function anim.norm(v, lo, hi)
local span = hi - lo
if span == 0 then return 0 end
return (v - lo) / span
end
function anim.wrap(v, lo, hi)
local range = hi - lo
if range <= 0 then return lo end
local result = fmod(v - lo, range)
if result < 0 then result = result + range end
return lo + result
end
function anim.pingpong(t, length)
if length <= 0 then return 0 end
local v = fmod(t, 2 * length)
if v < 0 then v = v + 2 * length end
if v > length then return 2 * length - v end
return v
end
function anim.sign(v)
if v > 0 then return 1 end
if v < 0 then return -1 end
return 0
end
function anim.oscillate(t, lo, hi, freq)
local wave = (sin(t * freq * tau) + 1) / 2
return lo + (hi - lo) * wave
end
function anim.triangle(t, freq)
local f = t * freq
f = f - floor(f)
return 1 - 2 * abs(f - 0.5)
end
function anim.square(t, freq)
local f = t * freq
f = f - floor(f)
return f >= 0.5 and 1 or 0
end
function anim.duration(t, dur)
if dur <= 0 then return 1 end
return clamp(t / dur, 0, 1)
end
function anim.delay(t, d) return math.max(0, t - d) end
function anim.ease_in(t) return t * t end
function anim.ease_out(t)
local inv = 1 - t
return 1 - inv * inv
end
function anim.ease_in_out(t)
if t < 0.5 then return 2 * t * t end
local inv = -2 * t + 2
return 1 - inv * inv / 2
end
function anim.elastic(t)
t = clamp(t, 0, 1)
if t == 0 then return 0 end
if t == 1 then return 1 end
return 2 ^ (-10 * t) * sin((t * 10 - 0.75) * (tau / 3)) + 1
end
function anim.back(t)
local c1 = 1.70158
local c3 = c1 + 1
local inv = t - 1
return 1 + c3 * inv * inv * inv + c1 * inv * inv
end
function anim.step(edge, x) return x >= edge and 1 or 0 end
function anim.fract(v) return v - floor(v) end
function anim.bounce(t)
local n1 = 7.5625
local d1 = 2.75
t = clamp(t, 0, 1)
if t < 1 / d1 then return n1 * t * t end
if t < 2 / d1 then
t = t - 1.5 / d1
return n1 * t * t + 0.75
end
if t < 2.5 / d1 then
t = t - 2.25 / d1
return n1 * t * t + 0.9375
end
t = t - 2.625 / d1
return n1 * t * t + 0.984375
end
function anim.hsv_to_rgb(h, s, v)
local c = v * s
local x = c * (1 - abs(fmod(h / 60, 2) - 1))
local m = v - c
local sector = floor(h / 60) % 6
local r, g, b
if sector == 0 then r, g, b = c, x, 0
elseif sector == 1 then r, g, b = x, c, 0
elseif sector == 2 then r, g, b = 0, c, x
elseif sector == 3 then r, g, b = 0, x, c
elseif sector == 4 then r, g, b = x, 0, c
else r, g, b = c, 0, x end
return (r + m) * 255, (g + m) * 255, (b + m) * 255
end
function anim.rgb_to_hsv(r, g, b)
r = r / 255; g = g / 255; b = b / 255
local max = math.max(r, g, b)
local min = math.min(r, g, b)
local delta = max - min
local h = 0
if delta > 0 then
if max == r then
h = 60 * fmod(fmod((g - b) / delta, 6) + 6, 6)
elseif max == g then
h = 60 * ((b - r) / delta + 2)
else
h = 60 * ((r - g) / delta + 4)
end
end
return h, max > 0 and delta / max or 0, max
end
function anim.len(x, y) return sqrt(x * x + y * y) end
function anim.dist(x1, y1, x2, y2)
local dx = x2 - x1
local dy = y2 - y1
return sqrt(dx * dx + dy * dy)
end
function anim.dot(x1, y1, x2, y2) return x1 * x2 + y1 * y2 end
function anim.normalize(x, y)
local m = sqrt(x * x + y * y)
if m == 0 then return 0, 0 end
return x / m, y / m
end
function anim.polar(r, a)
local rad = a * pi / 180
return r * cos(rad), r * sin(rad)
end
function anim.rotate(x, y, a)
local rad = a * pi / 180
local c = cos(rad)
local s = sin(rad)
return x * c - y * s, x * s + y * c
end
function anim.bezier(t, p0, p1, p2, p3)
t = clamp(t, 0, 1)
local inv = 1 - t
local b0 = inv * inv * inv
local b1 = 3 * inv * inv * t
local b2 = 3 * inv * t * t
local b3 = t * t * t
return b0 * p0 + b1 * p1 + b2 * p2 + b3 * p3
end
function anim.rand(...)
local a = { ... }
local n = select("#", ...)
if n == 0 then return 0 end
local min, max, seed = 0, 1, 0
if n == 1 then
seed = a[1]
elseif n == 2 then
max, seed = a[1], a[2]
else
min, max, seed = a[1], a[2], a[3]
end
local p = ffi.new("double[1]", seed)
local w = ffi.cast("uint32_t*", p)
local lo, hi = tonumber(w[0]), tonumber(w[1])
local h = umul32(tou(bit.bxor(lo, hi)), 374761393)
h = umul32(tou(bit.bxor(h, bit.rshift(h, 13))), 1274126177)
local r = tou(bit.bxor(h, bit.rshift(h, 16))) / 4294967295.0
return min + r * (max - min)
end
local function noise_hash(x, y, z)
local n = tou(umul32(tou(x), 374761393) + umul32(tou(y), 668265263) + umul32(tou(z), 1013904223))
n = umul32(tou(bit.bxor(n, bit.rshift(n, 13))), 1274126177)
return tou(bit.bxor(n, bit.rshift(n, 16))) / 4294967295.0
end
function anim.noise(x, y, z)
y = y or 0
z = z or 0
local xi = floor(x)
local yi = floor(y)
local zi = floor(z)
local xf = x - xi
local yf = y - yi
local zf = z - zi
local u = xf * xf * (3 - 2 * xf)
local v = yf * yf * (3 - 2 * yf)
local w = zf * zf * (3 - 2 * zf)
local c000 = noise_hash(xi, yi, zi)
local c100 = noise_hash(xi + 1, yi, zi)
local c010 = noise_hash(xi, yi + 1, zi)
local c110 = noise_hash(xi + 1, yi + 1, zi)
local c001 = noise_hash(xi, yi, zi + 1)
local c101 = noise_hash(xi + 1, yi, zi + 1)
local c011 = noise_hash(xi, yi + 1, zi + 1)
local c111 = noise_hash(xi + 1, yi + 1, zi + 1)
local x00 = c000 + u * (c100 - c000)
local x10 = c010 + u * (c110 - c010)
local x01 = c001 + u * (c101 - c001)
local x11 = c011 + u * (c111 - c011)
local y0 = x00 + v * (x10 - x00)
local y1 = x01 + v * (x11 - x01)
return y0 + w * (y1 - y0)
end
+266
ファイルの表示
@@ -0,0 +1,266 @@
local ffi = require("ffi")
ffi.cdef [[
typedef void* HANDLE;
HANDLE OpenFileMappingA(unsigned long, int, const char*);
void* MapViewOfFile(HANDLE, unsigned long, unsigned long, unsigned long, size_t);
int UnmapViewOfFile(const void*);
int CloseHandle(HANDLE);
HANDLE OpenEventA(unsigned long, int, const char*);
unsigned long WaitForSingleObject(HANDLE, unsigned long);
int SetEvent(HANDLE);
unsigned long GetLastError();
]]
local k32 = ffi.load("kernel32")
local FILE_MAP_ALL_ACCESS = 0x000F001F
local EVENT_ALL_ACCESS = 0x1F0003
local INFINITE = 0xFFFFFFFF
local mapName = arg[1]
local mapSize = tonumber(arg[2])
local workEventName = arg[3]
local doneEventName = arg[4]
local shimPath = arg[5]
local hMap = k32.OpenFileMappingA(FILE_MAP_ALL_ACCESS, 0, mapName)
assert(hMap ~= nil, "OpenFileMapping failed")
local view = k32.MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, mapSize)
assert(view ~= nil, "MapViewOfFile failed")
local workEvent = k32.OpenEventA(EVENT_ALL_ACCESS, 0, workEventName)
local doneEvent = k32.OpenEventA(EVENT_ALL_ACCESS, 0, doneEventName)
assert(workEvent ~= nil and doneEvent ~= nil, "OpenEvent failed")
local base = ffi.cast("uint8_t*", view)
local i32 = ffi.cast("int32_t*", base)
local f64 = ffi.cast("double*", base + 64)
local OFF_COMMAND = 1
local OFF_STATUS = 2
local OFF_WIDTH = 3
local OFF_HEIGHT = 4
local OFF_SCRIPTLEN = 5
local OFF_PIXELSDIRTY = 6
local OFF_ERRORLEN = 7
local OFF_CB_FRAME = 8
local OFF_CB_TAGLEN = 9
local OFF_CB_FOUND = 10
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 = 256
local CB_RESULT_OFFSET = CB_TAG_OFFSET + CB_TAG_MAX
local PIXEL_OFFSET = CB_RESULT_OFFSET + 8 * 8
local FIRST_WRITABLE = 8
local LAST_WRITABLE = 25
local STATUS_CALLBACK = 3
assert(loadfile(shimPath))()
local clamp = function(v, lo, hi)
if v < lo then return lo end
if v > hi then return hi end
return v
end
local width, height = 0, 0
local pixels = ffi.cast("uint8_t*", base + PIXEL_OFFSET)
local cbResult = ffi.cast("double*", base + CB_RESULT_OFFSET)
local dirty = false
local obj = {}
local scene = {}
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
local p = pixels + (y * width + x) * 4
local a = p[3]
if a <= 0 then return 0, 0, 0, 0 end
local s = 255 / a
return clamp(p[2] * s, 0, 255), clamp(p[1] * s, 0, 255), clamp(p[0] * s, 0, 255), a
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
a = a or 255
dirty = true
local aK = clamp(a, 0, 255) / 255
local p = pixels + (y * width + x) * 4
p[0] = math.floor(clamp(b * aK, 0, 255))
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))
end
function obj.getpixeldata()
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)
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
end
return pd
end
function obj.putpixeldata() end
function obj.getobject(tag, frame)
if type(tag) ~= "string" then return nil end
if frame then frame = math.floor(frame) else frame = math.floor(obj.timelineframe or 0) end
local len = #tag
if len > CB_TAG_MAX then len = CB_TAG_MAX end
ffi.copy(base + CB_TAG_OFFSET, tag, len)
i32[OFF_CB_TAGLEN] = len
i32[OFF_CB_FRAME] = frame
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
if i32[OFF_CB_FOUND] == 0 then return nil end
local rz = cbResult[5]
local zoom = cbResult[4]
return {
exist = cbResult[0] ~= 0,
x = cbResult[1], y = cbResult[2], z = cbResult[3],
zoom = zoom, sx = zoom, sy = zoom,
rx = 0, ry = 0, rz = rz,
rxr = 0, ryr = 0, rzr = rz * math.pi / 180,
alpha = cbResult[6], layer = cbResult[7],
}
end
local sandbox = {
obj = obj, scene = scene, ymm4 = ymm4,
anim = anim, bit32 = bit32, rawlen = rawlen,
math = math, string = string, table = table,
type = type, tostring = tostring, tonumber = tonumber, select = select,
error = error, assert = assert, ipairs = ipairs, pairs = pairs, next = next,
unpack = unpack, setmetatable = setmetatable, getmetatable = getmetatable,
rawget = rawget, rawset = rawset, rawequal = rawequal, rawlen = rawlen,
pcall = pcall, xpcall = xpcall, print = function() end,
}
sandbox._G = sandbox
local compiledCode, compiledChunk
local function loadFields()
width = i32[OFF_WIDTH]
height = i32[OFF_HEIGHT]
obj.w = f64[0]; obj.h = f64[1]; obj.hw = f64[2]; obj.hh = f64[3]
obj.cx = f64[4]; obj.cy = f64[5]; obj.cz = f64[6]; obj.diagonal = f64[7]
obj.x = f64[8]; obj.y = f64[9]; obj.z = f64[10]
obj.ox = f64[11]; obj.oy = f64[12]; obj.oz = f64[13]
obj.sx = f64[14]; obj.sy = f64[15]; obj.sz = f64[16]
obj.zoom = f64[17]; obj.aspect = f64[18]; obj.alpha = f64[19]
obj.rx = f64[20]; obj.ry = f64[21]; obj.rz = f64[22]
obj.rxr = f64[23]; obj.ryr = f64[24]; obj.rzr = f64[25]
obj.track0 = f64[26]; obj.track1 = f64[27]; obj.track2 = f64[28]; obj.track3 = f64[29]
obj.time = f64[30]; obj.frame = f64[31]; obj.totalframe = f64[32]; obj.totaltime = f64[33]
obj.t = f64[34]; obj.framerate = f64[35]; obj.layer = f64[36]; obj.index = f64[37]; obj.num = f64[38]
scene.width = f64[39]; scene.height = f64[40]; scene.cx = f64[41]; scene.cy = f64[42]
ymm4.group_index = f64[43]; ymm4.group_count = f64[44]
ymm4.timeline_totalframe = f64[45]; ymm4.timeline_totaltime = f64[46]
ymm4.time_ratio = f64[47]
ymm4.is_saving = f64[48] ~= 0; ymm4.is_playing = f64[49] ~= 0; ymm4.is_paused = f64[50] ~= 0
ymm4.group_ratio = (f64[44] ~= 0) and (f64[43] / f64[44]) or 0
obj.timelineframe = f64[51]; obj.timelinetime = f64[52]
end
local function storeFields()
for i = FIRST_WRITABLE, LAST_WRITABLE do
local key
if i == 8 then key = obj.x elseif i == 9 then key = obj.y elseif i == 10 then key = obj.z
elseif i == 11 then key = obj.ox elseif i == 12 then key = obj.oy elseif i == 13 then key = obj.oz
elseif i == 14 then key = obj.sx elseif i == 15 then key = obj.sy elseif i == 16 then key = obj.sz
elseif i == 17 then key = obj.zoom elseif i == 18 then key = obj.aspect elseif i == 19 then key = obj.alpha
elseif i == 20 then key = obj.rx elseif i == 21 then key = obj.ry elseif i == 22 then key = obj.rz
elseif i == 23 then key = obj.rxr elseif i == 24 then key = obj.ryr elseif i == 25 then key = obj.rzr end
f64[i] = tonumber(key) or f64[i]
end
end
while true do
k32.WaitForSingleObject(workEvent, INFINITE)
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)
end
end
if compiledChunk and code == compiledCode then
loadFields()
math.randomseed(f64[31])
setfenv(compiledChunk, sandbox)
local ok, err = pcall(compiledChunk)
if ok then
storeFields()
i32[OFF_PIXELSDIRTY] = dirty and 1 or 0
i32[OFF_STATUS] = 1
else
local msg = tostring(err)
ffi.copy(base + ERROR_OFFSET, msg, math.min(#msg, 4096))
i32[OFF_ERRORLEN] = math.min(#msg, 4096)
i32[OFF_STATUS] = 2
end
k32.SetEvent(doneEvent)
end
end
k32.UnmapViewOfFile(view)
k32.CloseHandle(hMap)
+42
ファイルの表示
@@ -0,0 +1,42 @@
local ffi = require("ffi")
ffi.cdef [[
typedef void* HANDLE;
HANDLE OpenFileMappingA(unsigned long dwDesiredAccess, int bInheritHandle, const char* lpName);
void* MapViewOfFile(HANDLE hFileMappingObject, unsigned long dwDesiredAccess, unsigned long dwFileOffsetHigh, unsigned long dwFileOffsetLow, size_t dwNumberOfBytesToMap);
int UnmapViewOfFile(const void* lpBaseAddress);
int CloseHandle(HANDLE hObject);
unsigned long GetLastError();
]]
local k32 = ffi.load("kernel32")
local FILE_MAP_ALL_ACCESS = 0x000F001F
local name = arg[1]
local size = tonumber(arg[2])
local h = k32.OpenFileMappingA(FILE_MAP_ALL_ACCESS, 0, name)
if h == nil then error("OpenFileMapping failed: " .. tonumber(k32.GetLastError())) end
local p = k32.MapViewOfFile(h, FILE_MAP_ALL_ACCESS, 0, 0, size)
if p == nil then
k32.CloseHandle(h)
error("MapViewOfFile failed: " .. tonumber(k32.GetLastError()))
end
local buf = ffi.cast("uint8_t*", p)
local pixels = size / 4
for i = 0, pixels - 1 do
local b = buf[i * 4]
local g = buf[i * 4 + 1]
local r = buf[i * 4 + 2]
local gray = math.floor(r * 0.299 + g * 0.587 + b * 0.114 + 0.5)
if gray > 255 then gray = 255 end
buf[i * 4] = gray
buf[i * 4 + 1] = gray
buf[i * 4 + 2] = gray
end
k32.UnmapViewOfFile(p)
k32.CloseHandle(h)
io.write("done")