コミットを比較

...
229 コミット
作成者 SHA1 メッセージ 日付
routersys 96558947ed Gitea Actions のワークフローを直す 2026-11-08 13:05:42 +09:00
routersys d9fcd6fcfc Gitea Actions のワークフローを直す 2026-11-08 10:15:17 +09:00
routersys b3703e1afc Gitea Actions のワークフローを直す 2026-11-08 09:48:15 +09:00
routersys 20e19a9d9f 過去のタグ用ワークフローを消す 2026-11-08 03:57:47 +09:00
routersys 64e5799493 Gitea Actions のワークフローを直す 2026-11-08 03:55:52 +09:00
routersys 87c861bc16 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 01:34:20 +09:00
routersys 9e8fd2d897 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 01:06:49 +09:00
routersys 50b21ccb01 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-07 22:35:57 +09:00
routersys 8fe4a86246 Gitea Actions のワークフローを直す 2026-11-07 22:07:52 +09:00
routersys cce60990e2 Gitea Actions のワークフローを足す 2026-11-07 19:52:56 +09:00
routersys cf62a6ef5d 画像の参照先をGiteaへ移す 2026-11-07 18:21:33 +09:00
routersys 8d4f771f8d サブモジュールの参照先をGiteaへ移す 2026-11-07 18:17:35 +09:00
routersys dc2e015b1a READMEの数式をLaTeXで書く 2026-10-20 19:06:24 +09:00
routersys b0a0c5cc8f バージョンをv1.20.3へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.20.3 のコミットから作成しました
2026-07-05 19:52:33 +09:00
routersys 40f1322042 [fast]に小処理時の低速化リスクの注意書きを追加 2026-07-05 19:37:27 +09:00
routersys d1b0439611 バージョンをv1.20.2へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.20.2 のコミットから作成しました
2026-07-05 19:19:02 +09:00
routersys 30d6f62d15 READMEを[fast]強制委譲の仕様へ更新 2026-07-05 19:17:52 +09:00
routersys ac3a1e350e サイトを[fast]強制委譲の仕様へ更新 2026-07-05 19:17:45 +09:00
routersys 0a7a2c7d40 全言語ドキュメントを[fast]強制委譲の仕様へ更新 2026-07-05 19:17:39 +09:00
routersys 1a97536bc5 テストへ[fast]の強制委譲を検証する項目を追加 2026-07-05 19:17:29 +09:00
routersys 8f954c7a2e 従来エンジンにもforce引数を復元 2026-07-05 19:17:21 +09:00
routersys 20509b19c9 ワーカーにforce引数を復元し[fast]で強制委譲 2026-07-05 19:17:13 +09:00
routersys e4bdf0df19 GPU処理にforce引数を追加しきい値を無視可能に 2026-07-05 19:17:06 +09:00
routersys 1f421dd158 バージョンをv1.20.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.20.1 のコミットから作成しました
2026-07-05 18:45:22 +09:00
routersys e56a2d85d7 CHANGELOGをv1.20.1の内容へ更新 2026-07-05 18:45:22 +09:00
routersys 969cf52299 READMEを自動GPU委譲の仕様へ更新 2026-07-05 18:24:08 +09:00
routersys 01785267fc サイトを自動GPU委譲の仕様へ更新 2026-07-05 18:24:08 +09:00
routersys 206001888c 全言語ドキュメントを自動GPU委譲の仕様へ更新 2026-07-05 18:24:07 +09:00
routersys 7c8776dd05 MoonSharpの画像加工を自動GPU委譲へ統一 2026-07-05 18:24:07 +09:00
routersys d6756ad3c8 ワーカーの画像加工を自動GPU委譲へ統一 2026-07-05 18:24:07 +09:00
routersys 57c3b346d8 バージョンをv1.20.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.20.0 のコミットから作成しました
2026-07-05 17:44:48 +09:00
routersys 55dde273ae CHANGELOGをv1.20.0の内容へ全置換 2026-07-05 17:43:02 +09:00
routersys a6a9963c85 補完候補へ構文拡張キーワードfastを登録 2026-07-05 17:26:28 +09:00
routersys fb7614d6fb 構文規則属性にIsCatalogとKeywordを追加 2026-07-05 17:26:28 +09:00
routersys a7a8c6b117 ハードウェアデバイス再生成に予算制限を適用 2026-07-05 17:12:16 +09:00
routersys 8b59897992 ホストコールバック時間をネイティブタイムアウトから除外 2026-07-05 17:12:15 +09:00
routersys 0d8f1e5102 [fast]の記載例を単独行形式へ統一 2026-07-05 16:37:10 +09:00
routersys e6165ca5a3 [fast]の診断を英語化し単独行形式をテスト 2026-07-05 16:37:10 +09:00
routersys 2bd54674c1 READMEへ[fast]高速化マーカーを追記 2026-07-05 16:13:11 +09:00
routersys 9a733807e8 [fast]をサイト構文ドキュメントへ追記 2026-07-05 16:13:08 +09:00
routersys f14c689353 [fast]を全言語ドキュメントへ追記 2026-07-05 16:13:05 +09:00
routersys d4443a1eef [fast]と高速化経路のテストを追加 2026-07-05 16:12:51 +09:00
routersys b618a3093b [fast]マーカーの書き換え規則を追加 2026-07-05 16:12:47 +09:00
routersys a03ba45f2a 拡張構文の書き換え診断を全経路へ通す 2026-07-05 16:12:44 +09:00
routersys 56c38b2891 エンジンに__fast_*プリミティブを配線 2026-07-05 16:12:31 +09:00
routersys 68b730e6d2 ワーカーに[fast]高速化プリミティブを追加 2026-07-05 16:12:28 +09:00
routersys ce7b15121c 画像加工にGPU委譲の明示フラグを追加 2026-07-05 16:12:26 +09:00
routersys 50b20e3060 GPU生成器の増分キャッシュをEquatableArray化 2026-07-05 13:52:30 +09:00
routersys c1f4fa2dc5 生成器をLua/Gpuへ整理し型を1ファイル1クラス化 2026-07-05 13:36:03 +09:00
routersys af9c5af173 GPU内部シェーダーをビルド時DXBC化 2026-07-05 13:22:06 +09:00
routersys 406a4c1a1b LuaJIT画像処理をGPU委譲 2026-07-05 11:19:28 +09:00
routersys b732dd1b90 畳み込みHLSLの予約語衝突を修正 2026-07-05 10:49:56 +09:00
routersys 1e93df21ef MoonSharp画像処理をGPU委譲 2026-07-05 10:44:17 +09:00
routersys 3bd6133bef GPUシェーダー管理を属性生成化 2026-07-05 10:40:33 +09:00
routersys 0c05fe2198 GPU画像処理をHW実行へ限定 2026-07-05 10:22:19 +09:00
routersys 775791d1e1 画像処理CPU基準を共有化 2026-07-05 10:16:12 +09:00
routersys a291d66567 画像処理のGPU委譲契約を追加 2026-07-05 10:11:26 +09:00
routersys 31d26c0a70 GPU基盤を専用プロジェクトへ分離 2026-07-05 10:05:41 +09:00
routersys 88b95cc09a 構文規則モデルを専用ファイルへ分離 2026-07-05 09:08:25 +09:00
routersys 9ff328d03a API生成器の型宣言を1ファイル1型へ分離 2026-07-05 09:08:19 +09:00
routersys 481bce261e バージョンをv1.19.2へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.19.2 のコミットから作成しました
2026-07-05 08:57:20 +09:00
routersys 421acf1a6a CHANGELOGへ毎フレーム更新の改善を追記 2026-07-05 08:53:47 +09:00
routersys 1d01e9d275 obj寸法の更新をボックス化しないSetへ置換 2026-07-05 08:53:46 +09:00
routersys 1a3394b8f5 変数更新の発行を型付きDynValueへ変更しボックス化を除去 2026-07-05 08:53:45 +09:00
routersys 52bbff8284 バージョンをv1.19.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.19.1 のコミットから作成しました
2026-07-05 08:39:44 +09:00
routersys b150970f83 getpixelregionの値生成を共有DynValueキャッシュへ置換 2026-07-05 08:39:43 +09:00
routersys 6ce23d486a バージョンをv1.19.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.19.0 のコミットから作成しました
2026-07-05 08:27:35 +09:00
routersys 024723a029 READMEへ画像加工5関数を追加 2026-07-05 08:27:34 +09:00
routersys 4746f01134 サイトへ画像加工5関数の説明を追加 2026-07-05 08:27:32 +09:00
routersys f2ea36ba49 全言語ドキュメントへ画像加工5関数を追加 2026-07-05 08:27:32 +09:00
routersys adf47608d2 画像加工5関数の両エンジンテストと補完カタログを追加 2026-07-05 08:27:13 +09:00
routersys f916c810dc MoonSharpレーンへ画像加工5関数を追加 2026-07-05 08:27:12 +09:00
routersys 9b86a3cb10 ワーカーへfill/pixelregion/convolve/resizeを追加 2026-07-05 08:27:11 +09:00
routersys 0fd1194596 コンテキストへ塗り・領域・畳み込み・拡縮のバッファ演算を追加 2026-07-05 08:27:10 +09:00
routersys 72aa5d7351 バージョンをv1.18.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.18.0 のコミットから作成しました
2026-07-05 07:40:16 +09:00
routersys a68c0fedd6 itembufferのリフレクションを公開クラスの直接生成へ置換 2026-07-05 07:25:06 +09:00
routersys c5ed30bc72 サイトとREADMEのaudiobufferの説明を修正 2026-07-05 07:15:04 +09:00
routersys 6f44e30fa1 全言語ドキュメントのaudiobufferとitembufferを修正 2026-07-05 07:15:03 +09:00
routersys 3db40f07cb audiobufferを公開APIのシーン音声へ変更しitembufferを追加 2026-07-05 07:15:02 +09:00
routersys ff8791d086 READMEへgetaudioの機能を追記 2026-07-05 00:31:48 +09:00
routersys f7f445bd3d サイトへgetaudioのドキュメントを追記 2026-07-05 00:31:47 +09:00
routersys 68af14bbf8 全言語ドキュメントへgetaudioを追記 2026-07-05 00:31:46 +09:00
routersys 7a23318be3 obj.getaudioを両エンジンへ配線しテストを追加 2026-07-05 00:31:45 +09:00
routersys 4072d9b117 音声サンプル取得のホスト部品を追加 2026-07-05 00:31:44 +09:00
routersys bc366a0af2 MoonSharpレーンへobj.getaudioを実装 2026-07-05 00:31:43 +09:00
routersys 0c896d44ee ネイティブワーカーへobj.getaudioを実装 2026-07-05 00:31:42 +09:00
routersys 9a9acc4b85 getaudioの契約をコンテキストとプロトコルへ追加 2026-07-05 00:31:42 +09:00
routersys a7e2285691 音声データ変換のAviUtl互換ロジックを追加 2026-07-05 00:31:41 +09:00
routersys 093e16feec 冗長なカッコ補足の削除と強調記法の削除 2026-07-04 23:29:23 +09:00
routersys 70b1b79fc2 READMEへgetobjectのメタデータを追記 2026-07-04 23:18:50 +09:00
routersys 995e1bc1aa サイトへgetobjectのメタデータを追記 2026-07-04 23:18:50 +09:00
routersys 1120373e67 全言語ドキュメントへgetobjectのメタデータを追記 2026-07-04 23:18:49 +09:00
routersys 43b3ed7077 ネイティブgetobjectメタデータのテストを更新 2026-07-04 23:18:40 +09:00
routersys 04ab6b111b 従来エンジンのgetobjectメタデータのテストを追加 2026-07-04 23:18:39 +09:00
routersys 5d6787e7d6 アイテムのメタデータ抽出をリゾルバーへ配線 2026-07-04 23:18:38 +09:00
routersys 6960406965 リゾルバーをIVideoItem化し音声アイテムとメタデータへ対応 2026-07-04 23:18:38 +09:00
routersys 9454310988 ネイティブホストのgetobjectへメタデータを配線 2026-07-04 23:18:37 +09:00
routersys d3118d20af 従来エンジンのgetobjectへメタデータを配線 2026-07-04 23:18:37 +09:00
routersys 78337c06dd SceneObjectInfoへメタデータのフィールドを追加 2026-07-04 23:18:36 +09:00
routersys 85fc0f8e9f getobjectのネイティブ応答へメタデータ領域を追加 2026-07-04 23:09:56 +09:00
routersys c19ae507cf 共有バインダーをParameterBinderへ改名 2026-07-04 22:21:49 +09:00
routersys 004041b342 バージョンをv1.17.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.17.0 のコミットから作成しました
2026-07-04 22:05:45 +09:00
routersys 08f69cf76d READMEへobj.brushの説明を追記 2026-07-04 22:03:27 +09:00
routersys e10bfbe406 サイトへobj.brushの説明を追記 2026-07-04 22:02:52 +09:00
routersys 1a46a76b59 全言語ドキュメントへobj.brushを追記 2026-07-04 22:01:55 +09:00
routersys e2f32a6722 obj.brushのテストを追加 2026-07-04 22:00:12 +09:00
routersys 5a23f4329e obj.brushを両エンジンへ追加 2026-07-04 22:00:10 +09:00
routersys f5fd6cebdb パラメータ適用を共有バインダーへ抽出 2026-07-04 22:00:08 +09:00
routersys 48f6711f1a ネイティブ手順へ模様パラメータ呼出種別を追加 2026-07-04 22:00:08 +09:00
routersys 859046f5aa ワーカーへobj.brushの呼出を追加 2026-07-04 22:00:07 +09:00
routersys 7c7a60807f READMEへシーンと模様の読込説明を追記 2026-07-04 20:54:48 +09:00
routersys 1b23b2937e サイトへシーンと模様の読込説明を追記 2026-07-04 20:54:16 +09:00
routersys 4135f52499 全言語ドキュメントへシーンと模様の読込を追記 2026-07-04 20:53:00 +09:00
routersys 8fda0bfec5 シーンと模様の読込テストを追加 2026-07-04 20:44:39 +09:00
routersys 7e353053c7 シーンと模様の読込を両エンジンへ配線 2026-07-04 20:44:37 +09:00
routersys d744d218fb 模様ブラシの読み戻しレンダラーを追加 2026-07-04 20:41:03 +09:00
routersys 772fa6b678 シーン描画の読み戻しレンダラーを追加 2026-07-04 20:41:01 +09:00
routersys 154bc6a5c0 ピクセル管理へブラシ塗り読み戻しを追加 2026-07-04 20:37:02 +09:00
routersys 593939c2d4 ワーカーへシーンと模様の読込呼出を追加 2026-07-04 20:34:30 +09:00
routersys 6730c8ce70 ネイティブ手順へシーンと模様の読込種別を追加 2026-07-04 20:32:37 +09:00
routersys b6a1e6e43c obj.loadへsceneとbrushの読込種別を追加 2026-07-04 20:32:07 +09:00
routersys fd06fdafe7 シーンと模様の画像読込委譲をコンテキストへ追加 2026-07-04 20:30:58 +09:00
routersys 20a119c6c8 バージョンをv1.16.3へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.16.3 のコミットから作成しました
2026-07-04 18:28:03 +09:00
routersys cfa8141424 再生中の毎フレームのシーン照会スナップショット割り当てを排除 2026-07-04 18:25:50 +09:00
routersys 7a2a7e5593 バージョンをv1.16.2へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.16.2 のコミットから作成しました
2026-07-04 17:41:12 +09:00
routersys 1a61091ec2 READMEのカーネル対象構文を改定 2026-07-04 17:28:21 +09:00
routersys bbb1bd3562 サイトのカーネル対象構文を改定 2026-07-04 17:28:14 +09:00
routersys db8017a8ce 全言語ドキュメントのカーネル対象構文を改定 2026-07-04 17:28:13 +09:00
routersys bc69ec5681 スクリプト依存キャッシュを参照同一性へ統一 2026-07-04 17:28:05 +09:00
routersys 8f6c3105ef 条件分岐カーネルのSIMD一致テストを追加 2026-07-04 17:27:58 +09:00
routersys de6c1b8b44 条件分岐カーネルのHLSL発行テストを追加 2026-07-04 17:27:51 +09:00
routersys ffd57fabd0 カーネル等価性テストへ新形状を追加 2026-07-04 17:27:46 +09:00
routersys a80d5dec88 カーネル抽出をAviUtl定型構文へ拡大 2026-07-04 17:27:45 +09:00
routersys 8bccf5ed01 バージョンをv1.16.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.16.1 のコミットから作成しました
2026-07-04 16:47:41 +09:00
routersys 7c831441fc READMEのsetanchor記述をtrack対応へ改定 2026-07-04 16:40:22 +09:00
routersys 7cd54ff3e8 サイトのsetanchor記述をtrack対応へ改定 2026-07-04 16:40:13 +09:00
routersys 3c3f5aed69 全言語ドキュメントのsetanchor記述をtrack対応へ改定 2026-07-04 16:40:05 +09:00
routersys 913e1a8643 アンカー座標スライダーを専用グループへ分離 2026-07-04 16:39:51 +09:00
routersys f6c7dac970 アンカー座標用グループを多言語資源へ追加 2026-07-04 16:39:39 +09:00
routersys 95db23f253 NormalizeCountとSetPositionのテスト追加 2026-07-04 16:26:07 +09:00
routersys 62044a3351 アンカー座標名を多言語資源へ追加 2026-07-04 16:25:59 +09:00
routersys 694b50d375 アンカー選択でX/Y/Z編集を開始 2026-07-04 16:25:49 +09:00
routersys 122d85068d 選択アンカーのX/Y/Z座標スライダーを追加 2026-07-04 16:25:44 +09:00
routersys 620670915f setanchorのtrack拒否を解除し個数正規化を適用 2026-07-04 16:25:25 +09:00
routersys 10974242aa ネイティブsetanchorのtrack拒否を解除 2026-07-04 16:25:13 +09:00
routersys 36b2ada16a アンカー座標の絶対設定とtrack個数正規化を追加 2026-07-04 16:25:06 +09:00
routersys 8428057eb4 バージョンをv1.16.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.16.0 のコミットから作成しました
2026-07-04 15:21:03 +09:00
routersys 1133daf764 READMEの構文名称をnil条件演算子と範囲判定へ改称 2026-07-04 15:01:49 +09:00
routersys b09070e8df サイトの構文名称をnil条件演算子と範囲判定へ改称 2026-07-04 15:01:46 +09:00
routersys cde0b8f498 全言語ドキュメントの構文名称をnil条件演算子と範囲判定へ改称 2026-07-04 15:01:45 +09:00
routersys 916dd278b2 READMEの構文拡張に新構文を追加 2026-07-04 14:53:00 +09:00
routersys d6d0792207 サイトの構文拡張ページに新構文を追加 2026-07-04 14:52:56 +09:00
routersys a7bae506a7 全言語ドキュメントに新構文の説明を追加 2026-07-04 14:52:55 +09:00
routersys d05906de7b 構文糖衣の単体テストを追加 2026-07-04 14:42:59 +09:00
routersys a8300041e3 範囲メンバーシップの構文糖衣を追加 2026-07-04 14:42:53 +09:00
routersys 8bd0d2bc0e 安全ナビゲーションの構文糖衣を追加 2026-07-04 14:42:47 +09:00
routersys cf5f4acf72 三項演算子の構文糖衣を追加 2026-07-04 14:42:41 +09:00
routersys 0d6709d518 パイプ演算子の構文糖衣を追加 2026-07-04 14:42:34 +09:00
routersys 12bd10164b ラムダ式の構文糖衣を追加 2026-07-04 14:42:28 +09:00
routersys 6287e74fe5 補間文字列の構文糖衣を追加 2026-07-04 14:42:27 +09:00
routersys 8956b7c8d5 範囲構文の解析を共通ヘルパーへ抽出 2026-07-04 14:42:13 +09:00
routersys 60c6a37f89 字句解析器に補間文字列とラムダ・パイプ演算子を追加 2026-07-04 14:42:05 +09:00
routersys 9a9c2ec405 バージョンをv1.15.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.15.0 のコミットから作成しました
2026-07-04 12:29:04 +09:00
routersys 103b612082 シェーダー領域の整列と容量判定を補正 2026-07-04 12:08:09 +09:00
routersys 9e1da1839e READMEのピクセルシェーダー記述を更新 2026-07-04 12:06:27 +09:00
routersys c19e12aa87 サイトのピクセルシェーダー節を更新 2026-07-04 12:05:45 +09:00
routersys ed4c38772f 各言語ドキュメントのpixelshader節を更新 2026-07-04 12:04:44 +09:00
routersys d31fd77aee pixelshaderの自動振分けをnativeへ変更 2026-07-04 11:59:12 +09:00
routersys eb0199131d workerへobj.pixelshaderと仮想フレームバッファを実装 2026-07-04 11:58:07 +09:00
routersys 36935bdf1d ネイティブワーカーへシェーダー実行呼出を実装 2026-07-04 11:52:59 +09:00
routersys 7d9a9f1cb8 ピクセルシェーダー呼出デリゲートを追加 2026-07-04 11:49:48 +09:00
routersys 3ce2483062 ネイティブ手順へシェーダー交換領域を追加 2026-07-04 11:49:12 +09:00
routersys fc8a07f935 プロセッサへ合成器配線とフレームバッファ初期化を追加 2026-07-04 11:48:25 +09:00
routersys d1279c25fa フレームバッファ出力後にobj寸法を更新 2026-07-04 11:47:37 +09:00
routersys 048c6d6707 コンテキストへ仮想フレームバッファを追加 2026-07-04 11:46:49 +09:00
routersys 3a29862423 数値合成指定のテストを追加 2026-07-04 11:44:32 +09:00
routersys 8c69864456 pixelshaderの合成指定を構造体化し数値合成へ対応 2026-07-04 11:43:43 +09:00
routersys 8a7b328db4 ピクセルシェーダー合成モード列挙を追加 2026-07-04 11:43:41 +09:00
routersys 8517bf5f50 ハードウェア合成へ合成モード適用を追加 2026-07-04 11:40:40 +09:00
routersys b928101e3e tempbuffer合成の合成モードを通常へ固定 2026-07-04 11:39:13 +09:00
routersys 7fb671e8c6 変換がシェーダー定義を保持するテストを追加 2026-07-04 11:16:01 +09:00
routersys 20ff47edce READMEへピクセルシェーダー対応を追記 2026-07-04 11:14:38 +09:00
routersys 8f9b7c725f サイトへピクセルシェーダーの節を追加 2026-07-04 11:14:36 +09:00
routersys 499f8ba078 各言語ドキュメントへobj.pixelshaderを追加 2026-07-04 11:12:51 +09:00
routersys 66f2d398b7 nativeでのpixelshaderエラーのテストを追加 2026-07-04 11:07:19 +09:00
routersys 935bca6fbb native実行時のpixelshaderへ明示エラーを追加 2026-07-04 11:07:17 +09:00
routersys 4c7ef12361 プロセッサへシェーダー実行器を配線 2026-07-04 11:02:04 +09:00
routersys 65e7864221 D3D11ピクセルシェーダー実行器を追加 2026-07-04 11:02:02 +09:00
routersys 25430c4dcf obj.pixelshaderのテストを追加 2026-07-04 11:01:59 +09:00
routersys f0234d21e4 pixelshader使用時はMoonSharpへ自動転送 2026-07-04 11:01:57 +09:00
routersys bfe23707f0 obj.pixelshaderをobjテーブルへ追加 2026-07-04 11:01:54 +09:00
routersys e74af227d8 コンテキストへシェーダーバッファ操作を追加 2026-07-04 11:01:51 +09:00
routersys 2b5901379f ピクセルシェーダー実行契約を追加 2026-07-04 11:01:50 +09:00
routersys deb94b3f29 シェーダー定義解析のテストを追加 2026-07-04 11:01:46 +09:00
routersys 74a65b7a8b シェーダー定義の解析器を追加 2026-07-04 11:01:44 +09:00
routersys a4cc0f3220 バージョンをv1.14.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.14.0 のコミットから作成しました
2026-07-03 23:20:02 +09:00
routersys 86f889cbd2 変更行マップのテストを追加 2026-07-03 23:07:25 +09:00
routersys c2f48230f3 拡張構文でのパラメータ検出テストを追加 2026-07-03 23:07:21 +09:00
routersys 4153956b37 変更行の診断を行単位へ補正 2026-07-03 23:07:18 +09:00
routersys 3763db1cfc 変換に変更行情報を伝播 2026-07-03 23:07:15 +09:00
routersys 9bcab1ae28 変更行を返す書き換えAPIを追加 2026-07-03 23:07:11 +09:00
routersys 6e13a4d1c2 書き換えた行番号を記録 2026-07-03 23:07:09 +09:00
routersys 8dc87d63be パラメータ検出を汎用字句解析器へ移行 2026-07-03 23:07:08 +09:00
routersys 0afb7afc21 READMEに構文拡張の節を新設 2026-07-03 21:50:22 +09:00
routersys 2769a29808 サイトに構文拡張ページを追加 2026-07-03 21:48:25 +09:00
routersys 1f21b4c49c 各言語ドキュメントの構文拡張を拡充 2026-07-03 21:45:59 +09:00
routersys cafc6d6e48 構文拡張の攻撃的テストを追加 2026-07-03 21:32:57 +09:00
routersys 49a2ce29b2 変換をトークン規則方式へ刷新 2026-07-03 21:32:46 +09:00
routersys d728c8d056 生成器をアナライザ参照に追加 2026-07-03 21:32:38 +09:00
routersys b6eac20941 構文規則レジストリ生成器を追加 2026-07-03 21:32:27 +09:00
routersys d8589007b3 範囲for<a..b>規則を実装 2026-07-03 21:32:20 +09:00
routersys 85596f76f7 nil合体演算子??規則を実装 2026-07-03 21:32:10 +09:00
routersys 018999ff5e 複合代入/nil合体代入/++規則を実装 2026-07-03 21:32:00 +09:00
routersys c5da497bb3 論理演算子!/&&/||規則を実装 2026-07-03 21:31:52 +09:00
routersys f46cb08f85 is/is not/!=規則を実装 2026-07-03 21:31:46 +09:00
routersys b0a5293b89 書き換え文脈とオペランド抽出を実装 2026-07-03 21:31:24 +09:00
routersys 67a1b4fa31 構文規則インターフェースを定義 2026-07-03 21:31:14 +09:00
routersys 2d0fb2c47a 構文規則属性を定義 2026-07-03 21:31:03 +09:00
routersys 45d5164afa 式境界判定ヘルパを追加 2026-07-03 21:30:55 +09:00
routersys ba20fc8187 Lua予約語判定を追加 2026-07-03 21:30:44 +09:00
routersys 669b24c2b3 可逆字句解析器を実装 2026-07-03 21:30:35 +09:00
routersys 91a3e3f762 構文トークン型を定義 2026-07-03 21:30:26 +09:00
routersys 722ae62326 構文トークン種別を定義 2026-07-03 21:30:19 +09:00
routersys fee1f293c7 READMEにis not構文を追記 2026-07-03 19:44:03 +09:00
routersys b6764fe637 サイトにis not構文の説明を追加 2026-07-03 19:43:11 +09:00
routersys 01e368207d 各言語ドキュメントにis not構文を追記 2026-07-03 19:42:35 +09:00
routersys 29ea2ea45c is not 構文のテストを追加 2026-07-03 19:40:28 +09:00
routersys 1d60d8b245 変換パイプラインへ構文拡張を組み込む 2026-07-03 19:40:23 +09:00
routersys 8f2aafdffd is not 構文の書き換えを実装 2026-07-03 19:40:19 +09:00
149個のファイルの変更、13744行の追加、458行の削除

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

+228
ファイルの表示
@@ -0,0 +1,228 @@
name: リリース
on:
push:
tags:
- 'v*'
workflow_dispatch:
inputs:
tag:
description: リリースするタグ
required: true
permissions:
contents: write
jobs:
build-and-release:
runs-on: windows-latest
steps:
- name: ソースコードのチェックアウト
uses: actions/checkout@v4
env:
GIT_CONFIG_COUNT: "2"
GIT_CONFIG_KEY_0: url.https://git.routersys.com/routersys/.insteadOf
GIT_CONFIG_VALUE_0: https://github.com/routersys/
GIT_CONFIG_KEY_1: url.https://git.routersys.com/manju-summoner/YukkuriMovieMaker.Generator.insteadOf
GIT_CONFIG_VALUE_1: https://github.com/manju-summoner/YukkuriMovieMaker.Generator
with:
ref: ${{ inputs.tag || github.ref_name }}
submodules: recursive
- name: YMM4 最新リリースの取得と解凍
id: ymm4
shell: pwsh
run: |
$list = 'C:\runner\cache\ymm4\releases.json'
New-Item -ItemType Directory -Force -Path (Split-Path $list) | Out-Null
if (-not (Test-Path $list) -or (Get-Item $list).Length -lt 1000 -or ((Get-Date) - (Get-Item $list).LastWriteTime).TotalHours -gt 6) {
$fetched = $null
for ($attempt = 1; $attempt -le 6 -and -not $fetched; $attempt++) {
try {
$fetched = Invoke-RestMethod -Uri "https://api.github.com/repos/manju-summoner/YukkuriMovieMaker4/releases?per_page=100" `
-Headers @{ "User-Agent" = "LuaScript-CI" } -ErrorAction Stop
}
catch {
$message = $_.Exception.Message
Write-Host "リリース一覧の取得に失敗しました($attempt 回目): $($message.Substring(0, [Math]::Min(80, $message.Length)))"
Start-Sleep -Seconds (5 * $attempt)
}
}
if (@($fetched).Count -gt 0) {
$fetched | Select-Object tag_name, published_at, prerelease, draft, assets |
ConvertTo-Json -Depth 6 | Set-Content -Path $list -Encoding UTF8
}
elseif (-not (Test-Path $list)) { throw 'the list of releases could not be fetched' }
else { Write-Host '保存済みのリリース一覧を使います' }
}
$when = [DateTimeOffset](git log -1 --format=%cI)
$releases = @(Get-Content -Raw -Path $list | ConvertFrom-Json | Where-Object { -not $_.draft -and -not $_.prerelease })
$release = $releases | Where-Object { [DateTimeOffset]$_.published_at -le $when } | Select-Object -First 1
if (-not $release) { $release = $releases | Select-Object -Last 1 }
Write-Host "最後のコミット $when に合わせた YMM4: $($release.tag_name)"
$asset = $release.assets | Where-Object { $_.name -like "*_Lite.zip" } | Select-Object -First 1
if (-not $asset) {
$asset = $release.assets | Where-Object { $_.name -like "*.zip" } | Select-Object -First 1
}
Write-Host "ダウンロード対象: $($asset.name)"
$cache = Join-Path 'C:\runner\cache\ymm4' $asset.name
$extracted = "$cache.extracted"
$lock = New-Object System.Threading.Mutex($false, 'Global\ci-ymm4-cache')
[void]$lock.WaitOne()
try {
if (-not (Test-Path "$extracted\.complete")) {
New-Item -ItemType Directory -Force -Path (Split-Path $cache) | Out-Null
Invoke-WebRequest -Uri $asset.browser_download_url -OutFile $cache
Remove-Item -Recurse -Force $extracted -ErrorAction SilentlyContinue
Expand-Archive -Path $cache -DestinationPath $extracted -Force
New-Item -ItemType File -Path "$extracted\.complete" | Out-Null
}
else {
Write-Host "保存済みの YMM4 を使います: $extracted"
}
}
finally {
$lock.ReleaseMutex()
}
$ymm4Dir = (Get-ChildItem -Path $extracted -Recurse -Filter "YukkuriMovieMaker.dll" |
Select-Object -First 1).DirectoryName
Write-Host "YMM4 DLL ディレクトリ: $ymm4Dir"
echo "YMM4_DIR=$ymm4Dir\" >> $env:GITHUB_OUTPUT
- name: タグ名からバージョンを取得
id: version
shell: pwsh
run: |
$tag = "${{ inputs.tag || github.ref_name }}"
echo "TAG=$tag" >> $env:GITHUB_OUTPUT
echo "VERSION=$($tag.TrimStart('v'))" >> $env:GITHUB_OUTPUT
- name: プロジェクトのビルド
shell: pwsh
env:
CI: 'true'
run: |
dotnet build LuaScript/LuaScript.csproj `
-c Release `
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
-p:Platform=x64
- name: パッケージの作成
id: package
shell: pwsh
run: |
$version = "${{ steps.version.outputs.TAG }}"
$outDir = "LuaScript/bin/x64/Release/net10.0-windows10.0.19041.0"
$stageRoot = "stage/LuaScript"
$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/LuaScript.Kernel.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Compat.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Media.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Runtime.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Gpu.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"
if (Test-Path $src) {
New-Item -ItemType Directory -Path "$stageRoot/$lang" -Force | Out-Null
Copy-Item "$src/*.dll" "$stageRoot/$lang/"
}
}
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
echo "PKG_NAME=$pkgName" >> $env:GITHUB_OUTPUT
- name: Gitea リリースの作成
shell: pwsh
env:
GITEA_TOKEN: ${{ github.token }}
REPOSITORY: ${{ github.repository }}
SERVER_URL: ${{ github.server_url }}
EVENT_NAME: ${{ github.event_name }}
WORKFLOW_NAME: ${{ github.workflow }}
JOB_NAME: ${{ github.job }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}
RELEASE_TAG: ${{ inputs.tag || github.ref_name }}
RELEASE_NAME: ${{ steps.version.outputs.TAG }}
RELEASE_BODY: ''
RELEASE_BODY_PATH: .github/CHANGELOG.md
RELEASE_DRAFT: false
RELEASE_PRERELEASE: false
RELEASE_FILES: |
${{ steps.package.outputs.PKG_NAME }}
run: |
$headers = @{ Authorization = "token $env:GITEA_TOKEN" }
$api = "$env:SERVER_URL/api/v1/repos/$env:REPOSITORY"
$tag = $env:RELEASE_TAG
$body = $env:RELEASE_BODY
if ($env:RELEASE_BODY_PATH -and (Test-Path $env:RELEASE_BODY_PATH)) {
$body = Get-Content $env:RELEASE_BODY_PATH -Raw -Encoding utf8
}
$files = @()
foreach ($pattern in ($env:RELEASE_FILES -split "[`r`n,]+" | Where-Object { $_.Trim() })) {
$found = @(Get-ChildItem -Path $pattern.Trim() -File -ErrorAction SilentlyContinue)
if ($found.Count -eq 0) { throw "リリースに付けるファイルが見つかりません: $pattern" }
$files += $found
}
$payload = @{
tag_name = $tag
name = $env:RELEASE_NAME
body = [string]$body
draft = ($env:RELEASE_DRAFT -eq 'true')
prerelease = ($env:RELEASE_PRERELEASE -eq 'true')
} | ConvertTo-Json
$bytes = [System.Text.Encoding]::UTF8.GetBytes($payload)
$existing = $null
try { $existing = Invoke-RestMethod -Uri "$api/releases/tags/$([System.Uri]::EscapeDataString($tag))" -Headers $headers } catch { }
if ($existing) {
$release = Invoke-RestMethod -Method Patch -Uri "$api/releases/$($existing.id)" -Headers $headers -ContentType "application/json; charset=utf-8" -Body $bytes
foreach ($asset in @($existing.assets)) {
Invoke-RestMethod -Method Delete -Uri "$api/releases/$($existing.id)/assets/$($asset.id)" -Headers $headers | Out-Null
}
} else {
$release = Invoke-RestMethod -Method Post -Uri "$api/releases" -Headers $headers -ContentType "application/json; charset=utf-8" -Body $bytes
}
foreach ($file in $files) {
$name = [System.Uri]::EscapeDataString($file.Name)
Invoke-RestMethod -Method Post -Uri "$api/releases/$($release.id)/assets?name=$name" -Headers $headers -Form @{ attachment = Get-Item $file.FullName } | Out-Null
Write-Host "添付しました: $($file.Name)"
}
Write-Host "リリースを作成しました: $($release.html_url)"
if ($env:EVENT_NAME -eq 'workflow_dispatch') {
try {
$sha = (git rev-parse HEAD).Trim()
$status = @{
state = 'success'
context = "$env:WORKFLOW_NAME / $env:JOB_NAME (workflow_dispatch)"
description = "Actions がタグ $tag のコミットから作成しました"
target_url = $env:RUN_URL
} | ConvertTo-Json
Invoke-RestMethod -Method Post -Uri "$api/statuses/$sha" -Headers $headers -ContentType "application/json; charset=utf-8" -Body ([System.Text.Encoding]::UTF8.GetBytes($status)) | Out-Null
Write-Host "タグのコミット $sha に成功の状態を付けました"
}
catch {
Write-Warning "タグのコミットに状態を付けられませんでした: $($_.Exception.Message)"
}
}
+11 -26
ファイルの表示
@@ -1,43 +1,28 @@
# v1.13.4 - Lua スクリプト for YMM4
# v1.20.3 - Lua スクリプト for YMM4
環境情報を取得する obj.getinfo を追加したリリースです。
スクリプトの設置フォルダのパスや動画の出力状態に加えて、最大画像サイズ、BPMグリッドの情報、経過時間、本体のバージョンを名前で取得できます。MoonSharp とネイティブの両エンジンで同一の関数として動作します。
あわせて、プラグインの内部構成を依存関係の層ごとの複数アセンブリへ分割し、Lua API の登録と入力補完をソースジェネレータによる宣言的な生成へ移行しました。既存のスクリプトの書き方と実行結果に変更はありません。
[fast] マーカーの注意書きを補うドキュメント更新リリースです。v1.20.2 で [fast] は obj.fill / obj.convolve / obj.resize の処理量のしきい値を無視して GPU へ委譲する仕様になりましたが、処理量が小さいときは GPU への委譲自体の往復コストが CPU 実行を上回り、かえって遅くなる場合があることを明記しました。動作に関わる実装、API、実行結果、エラーの扱いに変更はありません。
---
## 新機能
## 変更
### obj.getinfo による環境情報の取得
### [fast] は小さな処理で遅くなる場合があることを明記
obj.getinfo(名前) は、名前で指定した環境情報を返します。対応していない名前を指定した場合は nil を返します。取得できる情報は次のとおりです。
[fast] は obj.fill / obj.convolve / obj.resize のしきい値を無視しますが、GPU への委譲には往復コストがあります。処理量が小さいときは CPU 実行のほうが速い場合があるため、README、サイト、付属ドキュメントに注意書きを追加しました。
- "script_path" は、プラグインの設置フォルダのパスを返します。末尾には区切り文字が付きます。
- "filter" は、フィルタ効果として処理中かどうかを返します。本プラグインでは常に true を返します。
- "saving" は、動画を出力中のときだけ true を返します。
- "image_max" は、最大画像サイズを横幅と高さの2つの値で返します。
- "bpm" は、BPMグリッドのテンポと拍子と基準時間の3つの値を返します。基準時間の単位は秒です。BPMグリッドを設定していない場合はテンポが 0 になります。
- "clock" は、YMM4 の起動からの経過時間を秒で返します。
- "script_time" は、スクリプトの実行開始からの経過時間をミリ秒で返します。
- "version" は、本体のバージョンを major×10000+minor×100+build の数値で返します。
編集中のみプレビューへ枠を描き、出力時には描かないといった分岐へ利用できます。
- 付属の 8 言語ドキュメントの [fast] の節へ、同じ注意書きを追加しました。
---
## 互換性・後方互換
- 既存のスクリプトの書き方と実行結果に変更はありません。obj.getinfo は新規の関数であり、従来の呼び出しへは影響しません。
- obj.getinfo は MoonSharp とネイティブの両エンジンで動作します。script_path、filter、saving、image_max、bpm、version は両エンジンで同一の値を返します。clock と script_time は経過時間の計測であり、値そのものは実行のたびに変わります。
- v1.13.3 までの仕様に変更はありません。
- 動作に関わる実装の変更はありません。
- API、構文、エンジンの自動振り分け、GPU 検証、CPU への自動フォールバックに変更はありません。
- v1.20.2 の [fast] の強制委譲仕様に変更はありません。
---
## 内部実装
- プラグインを依存関係の層ごとに LuaScript.Kernel、LuaScript.Compat、LuaScript.Media、LuaScript.Runtime、および本体の 5 つのアセンブリへ分割しました。名前空間は据え置き、参照の向きを一方向へ整理しています。
- Lua API の登録と毎フレームの変数投影を、属性から生成するソースジェネレータへ移行しました。入力補完の候補もこの宣言から生成し、手書きの一覧を廃止しました。関数を 1 つ追加すると、登録と補完へ自動的に反映されます。
- Kernel、Compat、Runtime の各プロジェクトを 1 ファイル 1 クラスへ整理し、ドメインごとのフォルダへ再配置しました。エンジンのテーブル管理は LuaScope へ汎用化しています。
- 映像デコーダを LuaScript.Media プロジェクトへ分離し、ツールバーを View と ViewModel へ分離しました。ViewModel はフレームワークに依存しない構成へ整理しています。
- obj.getinfo の実装では、BPMグリッドの情報を YMM4 のシーンから取得し、script_path と version は本体からエンジンへ渡します。経過時間は両エンジンがそれぞれ高精度タイマーで計測します。
- テストは 3113 件です。v1.13.3 の 3092 件から、obj.getinfo の両エンジンでの実行結果の検証と、補完カタログの回帰検証、およびエンジンのテーブルライフサイクルの特性化検証を追加しました。
- 動作に関わるコード変更はありません。
- リリース対象のバージョン表記を v1.20.3 へ更新しました。
+3 -3
ファイルの表示
@@ -1,11 +1,11 @@
========================================
Luaスクリプト for YMM4 v1.13.4
Luaスクリプト for YMM4 v1.20.3
========================================
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
ピクセルを直接制御できるプラグインです。
スクリプトの実行にはMoonSharpによるLuaインタプリタを使用しており、座標・拡大率・
透明度・回転といった描画パラメータの変更に加えて、ピクセル単位での読み書きにも
対応しています。
透明度・回転といった描画パラメータの変更に加えて、ピクセル単位での読み書きや、
塗りつぶし・領域の一括読み書き・畳み込み・拡大縮小による画像加工にも対応しています。
obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動するTrack0~3パラメータ
からも参照でき、anim.*関数群によるイージングやノイズ等の演出も組み合わせられます。
--------------------------------------------------------------------------------
+1
ファイルの表示
@@ -77,6 +77,7 @@ jobs:
Copy-Item "$outDir/LuaScript.Compat.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Media.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Runtime.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Gpu.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/"
+1 -1
ファイルの表示
@@ -1,3 +1,3 @@
[submodule "YukkuriMovieMaker.Generator"]
path = YukkuriMovieMaker.Generator
url = https://github.com/manju-summoner/YukkuriMovieMaker.Generator.git
url = https://git.routersys.com/manju-summoner/YukkuriMovieMaker.Generator.git
+195
ファイルの表示
@@ -0,0 +1,195 @@
using System;
namespace LuaScript.Compat
{
internal sealed class AviUtlAudioConverter
{
public const int MaxSamples = 1024;
public const int SpectrumWindow = 1024;
public const int FourierWindow = 2048;
public const int SpectrumBins = SpectrumWindow / 2;
private const double PcmScale = 32768d;
private readonly double[] _mono = new double[FourierWindow];
private readonly double[] _real = new double[FourierWindow];
private readonly double[] _imag = new double[FourierWindow];
private enum DataKind
{
Unknown,
Pcm,
Spectrum,
Fourier,
}
public static int RequiredFrames(string type, int size)
{
var (kind, _) = Parse(type);
return kind switch
{
DataKind.Pcm => ResolveCount(kind, size),
DataKind.Spectrum => SpectrumWindow,
DataKind.Fourier => FourierWindow,
_ => 0,
};
}
public int Convert(string type, ReadOnlySpan<float> interleaved, int frames, int size, Span<double> destination)
{
var (kind, channel) = Parse(type);
if (kind == DataKind.Unknown || frames <= 0)
return 0;
int window = kind switch
{
DataKind.Pcm => Math.Min(frames, ResolveCount(kind, size)),
DataKind.Spectrum => SpectrumWindow,
_ => FourierWindow,
};
FillMono(interleaved, frames, channel, window);
switch (kind)
{
case DataKind.Pcm:
{
int count = Math.Min(ResolveCount(kind, size), frames);
for (int i = 0; i < count; i++)
destination[i] = Math.Clamp(_mono[i] * PcmScale, -32768d, 32767d);
return count;
}
case DataKind.Spectrum:
{
int bands = ResolveCount(kind, size);
Fft(SpectrumWindow);
double scale = 2d / SpectrumWindow * PcmScale;
for (int b = 0; b < bands; b++)
{
int start = b * SpectrumBins / bands;
int end = (b + 1) * SpectrumBins / bands;
if (end <= start)
end = start + 1;
double sum = 0d;
for (int bin = start; bin < end; bin++)
sum += Magnitude(bin);
destination[b] = sum / (end - start) * scale;
}
return bands;
}
case DataKind.Fourier:
{
int count = ResolveCount(kind, size);
Fft(FourierWindow);
double scale = 2d / FourierWindow;
for (int i = 0; i < count; i++)
destination[i] = Magnitude(i + 1) * scale;
return count;
}
default:
return 0;
}
}
private static int ResolveCount(DataKind kind, int size)
{
int fallback = kind == DataKind.Spectrum ? 32 : MaxSamples;
int max = kind == DataKind.Spectrum ? SpectrumBins : MaxSamples;
return size <= 0 ? Math.Min(fallback, max) : Math.Clamp(size, 1, max);
}
private static (DataKind Kind, int Channel) Parse(string type)
{
int channel = 0;
int length = type.Length;
if (length >= 2 && type[length - 2] == '.')
{
char suffix = type[length - 1];
if (suffix == 'l')
channel = 1;
else if (suffix == 'r')
channel = 2;
if (channel != 0)
length -= 2;
}
var name = type.AsSpan(0, length);
DataKind kind = DataKind.Unknown;
if (name.SequenceEqual("pcm"))
kind = DataKind.Pcm;
else if (name.SequenceEqual("spectrum"))
kind = DataKind.Spectrum;
else if (name.SequenceEqual("fourier"))
kind = DataKind.Fourier;
return (kind, channel);
}
private void FillMono(ReadOnlySpan<float> interleaved, int frames, int channel, int window)
{
int available = Math.Min(frames, window);
for (int i = 0; i < available; i++)
{
float left = interleaved[i * 2];
float right = interleaved[i * 2 + 1];
_mono[i] = channel switch
{
1 => left,
2 => right,
_ => (left + right) * 0.5d,
};
}
for (int i = available; i < window; i++)
_mono[i] = 0d;
}
private double Magnitude(int bin) =>
Math.Sqrt(_real[bin] * _real[bin] + _imag[bin] * _imag[bin]);
private void Fft(int n)
{
for (int i = 0; i < n; i++)
{
_real[i] = _mono[i];
_imag[i] = 0d;
}
for (int i = 1, j = 0; i < n; i++)
{
int bit = n >> 1;
for (; (j & bit) != 0; bit >>= 1)
j ^= bit;
j |= bit;
if (i < j)
{
(_real[i], _real[j]) = (_real[j], _real[i]);
(_imag[i], _imag[j]) = (_imag[j], _imag[i]);
}
}
for (int len = 2; len <= n; len <<= 1)
{
double angle = -2d * Math.PI / len;
double wRe = Math.Cos(angle);
double wIm = Math.Sin(angle);
for (int i = 0; i < n; i += len)
{
double curRe = 1d;
double curIm = 0d;
for (int k = 0; k < len / 2; k++)
{
int a = i + k;
int b = i + k + len / 2;
double tRe = _real[b] * curRe - _imag[b] * curIm;
double tIm = _real[b] * curIm + _imag[b] * curRe;
_real[b] = _real[a] - tRe;
_imag[b] = _imag[a] - tIm;
_real[a] += tRe;
_imag[a] += tIm;
double nextRe = curRe * wRe - curIm * wIm;
curIm = curRe * wIm + curIm * wRe;
curRe = nextRe;
}
}
}
}
}
}
+3 -2
ファイルの表示
@@ -1,9 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.13.4</Version>
<Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
</PropertyGroup>
@@ -16,6 +16,7 @@
<ItemGroup>
<ProjectReference Include="..\LuaScript.Kernel\LuaScript.Kernel.csproj" />
<ProjectReference Include="..\LuaScript.Generator\LuaScript.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
<ItemGroup>
+85
ファイルの表示
@@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
namespace LuaScript.Compat
{
internal sealed class AviUtlPixelShaderLibrary
{
private const string SectionMarker = "--[[pixelshader@";
public static AviUtlPixelShaderLibrary Empty { get; } = new(null);
private readonly Dictionary<string, string>? _shaders;
private AviUtlPixelShaderLibrary(Dictionary<string, string>? shaders) => _shaders = shaders;
public int Count => _shaders?.Count ?? 0;
public static AviUtlPixelShaderLibrary Parse(string? source)
{
if (string.IsNullOrEmpty(source))
return Empty;
Dictionary<string, string>? shaders = null;
int index = 0;
while (index < source.Length)
{
int lineStart = index;
int lineBreak = source.IndexOf('\n', index);
index = lineBreak < 0 ? source.Length : lineBreak + 1;
int i = ScriptParserHelper.SkipSpaces(source, lineStart);
if (!MatchesMarker(source, i))
continue;
i += SectionMarker.Length;
int nameStart = i;
while (i < source.Length && IsEntryPointChar(source[i]))
i++;
if (i == nameStart || i >= source.Length || source[i] != ':')
continue;
string name = source[nameStart..i];
int bodyStart = i + 1;
int bodyEnd = source.IndexOf("]]", bodyStart, StringComparison.Ordinal);
if (bodyEnd < 0)
continue;
shaders ??= new Dictionary<string, string>(StringComparer.Ordinal);
shaders.TryAdd(name, source[bodyStart..bodyEnd]);
index = bodyEnd + 2;
}
return shaders is null ? Empty : new AviUtlPixelShaderLibrary(shaders);
}
public bool TryGet(string name, out string hlsl)
{
hlsl = string.Empty;
if (_shaders is null || string.IsNullOrEmpty(name))
return false;
int at = name.IndexOf('@');
string local = at < 0 ? name : name[..at];
if (_shaders.TryGetValue(local, out var found))
{
hlsl = found;
return true;
}
return false;
}
public static string EntryPointOf(string name)
{
int at = name.IndexOf('@');
return at < 0 ? name : name[..at];
}
private static bool MatchesMarker(string text, int index) =>
index + SectionMarker.Length <= text.Length &&
string.CompareOrdinal(text, index, SectionMarker, 0, SectionMarker.Length) == 0;
private static bool IsEntryPointChar(char c) =>
ScriptParserHelper.IsNameChar(c) || c == '_';
}
}
+9 -4
ファイルの表示
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Text;
using LuaScript.Compat.Syntax;
namespace LuaScript.Compat
{
@@ -15,10 +16,10 @@ namespace LuaScript.Compat
public static string Transform(string source) => TransformWithMap(source).Code;
public static (string Code, int[] LineMap) TransformWithMap(string source)
public static (string Code, int[] LineMap, int[] ChangedLines, LuaRewriteDiagnostic[] Diagnostics) TransformWithMap(string source)
{
if (string.IsNullOrEmpty(source))
return (source, []);
return (source, [], [], []);
var lines = ScriptParserHelper.SplitLines(source);
bool hasSection = ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
@@ -28,7 +29,10 @@ namespace LuaScript.Compat
AppendDeclarations(lines[i], prelude);
if (!hasSection && prelude.Count == 0)
return (source, []);
{
var (code, changed, preludeless) = LuaSyntaxExtensions.RewriteWithMap(source);
return (code, [], changed, preludeless);
}
var builder = new StringBuilder(source.Length + 64);
var lineMap = new int[prelude.Count + (sectionEnd - sectionStart)];
@@ -45,7 +49,8 @@ namespace LuaScript.Compat
lineMap[row++] = i;
}
return (builder.ToString(), lineMap);
var (rewritten, changedLines, diagnostics) = LuaSyntaxExtensions.RewriteWithMap(builder.ToString());
return (rewritten, lineMap, changedLines, diagnostics);
}
private static void AppendDeclarations(string line, List<string> prelude)
+49
ファイルの表示
@@ -0,0 +1,49 @@
using LuaScript.Compat.Syntax;
namespace LuaScript.Compat
{
internal static class LuaSyntaxExtensions
{
public static string Rewrite(string source) => RewriteWithMap(source).Code;
public static (string Code, int[] ChangedLines, LuaRewriteDiagnostic[] Diagnostics) RewriteWithMap(string source)
{
if (string.IsNullOrEmpty(source))
return (source, [], []);
var tokens = LuaSyntaxLexer.Tokenize(source);
var context = new LuaRewriteContext(tokens);
var rules = LuaSyntaxRuleRegistry.Rules;
while (!context.AtEnd)
{
var current = context.Current;
if (current.IsTrivia || current.Kind == LuaSyntaxTokenKind.String)
{
context.Emit(current);
context.Advance();
continue;
}
bool matched = false;
foreach (var rule in rules)
{
if (rule.TryApply(context))
{
matched = true;
break;
}
}
if (!matched)
{
context.Emit(current);
context.Advance();
}
}
var diagnostics = context.Diagnostics;
return context.Changed ? (context.Serialize(), context.ChangedLines, diagnostics) : (source, [], diagnostics);
}
}
}
+35 -17
ファイルの表示
@@ -1,6 +1,6 @@
using System;
using System.Collections.Generic;
using LuaScript.Engine.Kernel;
using LuaScript.Compat.Syntax;
namespace LuaScript.Compat
{
@@ -35,15 +35,7 @@ namespace LuaScript.Compat
if (string.IsNullOrEmpty(script))
return None;
List<LuaToken> tokens;
try
{
tokens = LuaLexer.Tokenize(script);
}
catch (KernelUnsupportedException)
{
return None;
}
var tokens = LuaSyntaxLexer.Tokenize(script);
HashSet<string>? members = null;
bool color = false;
@@ -51,26 +43,52 @@ namespace LuaScript.Compat
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
if (token.Kind != LuaTokenKind.Name)
if (token.Kind != LuaSyntaxTokenKind.Name)
continue;
if (token.Text == "color")
{
if (i == 0 || !tokens[i - 1].IsSymbol("."))
int previous = PreviousSignificant(tokens, i);
if (previous < 0 || !tokens[previous].IsOperator("."))
color = true;
continue;
}
if (token.Text == "obj" &&
i + 2 < tokens.Count &&
tokens[i + 1].IsSymbol(".") &&
tokens[i + 2].Kind == LuaTokenKind.Name)
if (token.Text == "obj")
{
(members ??= new HashSet<string>(StringComparer.Ordinal)).Add(tokens[i + 2].Text);
int dot = NextSignificant(tokens, i + 1);
if (dot < 0 || !tokens[dot].IsOperator("."))
continue;
int member = NextSignificant(tokens, dot + 1);
if (member < 0 || tokens[member].Kind != LuaSyntaxTokenKind.Name)
continue;
(members ??= new HashSet<string>(StringComparer.Ordinal)).Add(tokens[member].Text);
}
}
return new ScriptParameterUsage(members, color);
}
private static int PreviousSignificant(List<LuaSyntaxToken> tokens, int from)
{
for (int i = from - 1; i >= 0; i--)
{
if (!tokens[i].IsTrivia)
return i;
}
return -1;
}
private static int NextSignificant(List<LuaSyntaxToken> tokens, int from)
{
for (int i = from; i < tokens.Count; i++)
{
if (!tokens[i].IsTrivia)
return i;
}
return -1;
}
}
}
+7
ファイルの表示
@@ -0,0 +1,7 @@
namespace LuaScript.Compat.Syntax
{
internal interface ILuaSyntaxRule
{
bool TryApply(LuaRewriteContext context);
}
}
+23
ファイルの表示
@@ -0,0 +1,23 @@
using System.Collections.Generic;
namespace LuaScript.Compat.Syntax
{
internal static class LuaKeywords
{
private static readonly HashSet<string> Reserved = new()
{
"and", "break", "do", "else", "elseif", "end", "false", "for", "function",
"goto", "if", "in", "local", "nil", "not", "or", "repeat", "return",
"then", "true", "until", "while",
};
private static readonly HashSet<string> ExpressionSafe = new()
{
"and", "or", "not", "nil", "true", "false",
};
public static bool IsReserved(string name) => Reserved.Contains(name);
public static bool IsExpressionBoundary(string name) => Reserved.Contains(name) && !ExpressionSafe.Contains(name);
}
}
+130
ファイルの表示
@@ -0,0 +1,130 @@
using System.Collections.Generic;
using System.Text;
namespace LuaScript.Compat.Syntax
{
internal readonly struct LuaRangeParts
{
public LuaRangeParts(string start, string stop, string? step, bool exclusive)
{
Start = start;
Stop = stop;
Step = step;
Exclusive = exclusive;
}
public string Start { get; }
public string Stop { get; }
public string? Step { get; }
public bool Exclusive { get; }
}
internal static class LuaRangeSyntax
{
public static bool TryParse(IReadOnlyList<LuaSyntaxToken> input, int open, out LuaRangeParts parts, out int end)
{
parts = default;
end = open;
if (open < 0 || open >= input.Count || !input[open].IsOperator("<"))
return false;
int position = open + 1;
if (!TryReadSegment(input, ref position, "..", ">", out string start, out string startTerminator) || startTerminator != "..")
return false;
bool exclusive = false;
int caret = NextSignificant(input, position);
if (caret >= 0 && input[caret].IsOperator("<"))
{
exclusive = true;
position = caret + 1;
}
if (!TryReadSegment(input, ref position, ",", ">", out string stop, out string stopTerminator))
return false;
string? step = null;
if (stopTerminator == ",")
{
if (!TryReadSegment(input, ref position, ">", ">", out string stepText, out string stepTerminator) || stepTerminator != ">")
return false;
step = stepText;
}
else if (stopTerminator != ">")
{
return false;
}
if (start.Length == 0 || stop.Length == 0 || (step is not null && step.Length == 0))
return false;
parts = new LuaRangeParts(start, stop, step, exclusive);
end = position;
return true;
}
private static bool TryReadSegment(IReadOnlyList<LuaSyntaxToken> input, ref int position, string primaryStop, string secondaryStop, out string text, out string terminator)
{
text = string.Empty;
terminator = string.Empty;
int start = position;
int depth = 0;
int count = input.Count;
while (position < count)
{
var token = input[position];
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
return false;
if (token.Kind == LuaSyntaxTokenKind.Operator)
{
if (token.Text is "(" or "[" or "{")
{
depth++;
}
else if (token.Text is ")" or "]" or "}")
{
if (depth == 0)
return false;
depth--;
}
else if (depth == 0 && (token.Text == primaryStop || token.Text == secondaryStop))
{
terminator = token.Text;
text = Trim(input, start, position);
position++;
return true;
}
}
position++;
}
return false;
}
private static int NextSignificant(IReadOnlyList<LuaSyntaxToken> input, int from)
{
for (int i = from; i < input.Count; i++)
{
if (!input[i].IsTrivia)
return i;
}
return -1;
}
private static string Trim(IReadOnlyList<LuaSyntaxToken> input, int begin, int end)
{
while (begin < end && input[begin].IsTrivia)
begin++;
while (end > begin && input[end - 1].IsTrivia)
end--;
var builder = new StringBuilder();
for (int i = begin; i < end; i++)
builder.Append(input[i].Text);
return builder.ToString();
}
}
}
+327
ファイルの表示
@@ -0,0 +1,327 @@
using System.Collections.Generic;
using System.Text;
namespace LuaScript.Compat.Syntax
{
internal sealed class LuaRewriteContext
{
private readonly List<LuaSyntaxToken> _input;
private readonly List<LuaSyntaxToken> _output;
private List<int>? _changedLines;
private List<LuaRewriteDiagnostic>? _diagnostics;
private int _line = 1;
private int _lastChangedLine;
private int _temporaries;
public LuaRewriteContext(List<LuaSyntaxToken> input)
{
_input = input;
_output = new List<LuaSyntaxToken>(input.Count);
}
public IReadOnlyList<LuaSyntaxToken> Input => _input;
public List<LuaSyntaxToken> Output => _output;
public int Index { get; set; }
public bool Changed { get; private set; }
public int[] ChangedLines => _changedLines is null ? [] : _changedLines.ToArray();
public LuaRewriteDiagnostic[] Diagnostics => _diagnostics is null ? [] : _diagnostics.ToArray();
public void AddDiagnostic(string message)
{
(_diagnostics ??= new List<LuaRewriteDiagnostic>()).Add(new LuaRewriteDiagnostic(_line, message));
MarkChanged();
}
public bool AtEnd => Index >= _input.Count;
public LuaSyntaxToken Current => _input[Index];
public void Advance() => Index++;
public void Emit(LuaSyntaxToken token)
{
_output.Add(token);
if (token.Kind == LuaSyntaxTokenKind.Newline)
_line++;
}
public void EmitRaw(string text)
{
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, text));
MarkChanged();
}
public void EmitOperator(string text)
{
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, text));
MarkChanged();
}
public string NextTemporary() => "__lc" + _temporaries++;
public int NextSignificant(int from)
{
for (int i = from; i < _input.Count; i++)
{
if (!_input[i].IsTrivia)
return i;
}
return -1;
}
public bool TryPreviousOutputSignificantSameLine(out LuaSyntaxToken token)
{
for (int i = _output.Count - 1; i >= 0; i--)
{
if (_output[i].Kind == LuaSyntaxTokenKind.Newline)
break;
if (_output[i].IsTrivia)
continue;
token = _output[i];
return true;
}
token = default;
return false;
}
public int NextSignificantSameLine(int from)
{
for (int i = from; i < _input.Count; i++)
{
if (_input[i].Kind == LuaSyntaxTokenKind.Newline)
return -1;
if (_input[i].IsTrivia)
continue;
return i;
}
return -1;
}
public void EmitWord(string word)
{
if (_output.Count > 0 && !_output[_output.Count - 1].IsTrivia)
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, " "));
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, word));
if (Index < _input.Count && !_input[Index].IsTrivia)
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, " "));
MarkChanged();
}
private void MarkChanged()
{
Changed = true;
if (_line == _lastChangedLine)
return;
(_changedLines ??= new List<int>()).Add(_line);
_lastChangedLine = _line;
}
public bool TryReadTrailingLvalue(out int start, out string text)
{
start = _output.Count;
text = string.Empty;
int end = _output.Count;
while (end > 0 && _output[end - 1].IsTrivia)
end--;
if (end == 0)
return false;
int depth = 0;
int begin = end;
for (int i = end - 1; i >= 0; i--)
{
var token = _output[i];
if (token.Kind == LuaSyntaxTokenKind.Operator)
{
if (token.Text is ")" or "]" or "}")
{
depth++;
begin = i;
continue;
}
if (token.Text is "(" or "[" or "{")
{
if (depth == 0)
break;
depth--;
begin = i;
continue;
}
if (depth > 0 || token.Text == ".")
{
begin = i;
continue;
}
break;
}
if (token.Kind == LuaSyntaxTokenKind.Name)
{
if (depth == 0 && LuaKeywords.IsReserved(token.Text))
break;
begin = i;
continue;
}
if (depth > 0)
{
begin = i;
continue;
}
break;
}
while (begin < end && _output[begin].IsTrivia)
begin++;
if (begin >= end)
return false;
start = begin;
text = Concat(begin, end);
return true;
}
public bool TryPopOrOperand(out string text)
{
text = string.Empty;
int end = _output.Count;
while (end > 0 && _output[end - 1].IsTrivia)
end--;
if (end == 0)
return false;
int depth = 0;
int begin = end;
for (int i = end - 1; i >= 0; i--)
{
var token = _output[i];
if (token.Kind == LuaSyntaxTokenKind.Operator)
{
if (token.Text is ")" or "]" or "}")
{
depth++;
begin = i;
continue;
}
if (token.Text is "(" or "[" or "{")
{
if (depth == 0)
break;
depth--;
begin = i;
continue;
}
if (depth == 0 && token.Text is "=" or "," or ";")
break;
begin = i;
continue;
}
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
break;
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
break;
begin = i;
}
while (begin < end && _output[begin].IsTrivia)
begin++;
if (begin >= end)
return false;
text = Concat(begin, end);
_output.RemoveRange(begin, _output.Count - begin);
return true;
}
public void RemoveOutputFrom(int start) => _output.RemoveRange(start, _output.Count - start);
public bool LastOutputIsTrivia() => _output.Count == 0 || _output[_output.Count - 1].IsTrivia;
public string ReadLineExpression()
{
int start = Index;
int depth = 0;
while (Index < _input.Count)
{
var token = _input[Index];
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
break;
if (token.Kind == LuaSyntaxTokenKind.Operator)
{
if (token.Text is "(" or "[" or "{")
depth++;
else if (token.Text is ")" or "]" or "}")
{
if (depth == 0)
break;
depth--;
}
else if (depth == 0 && token.Text == ";")
break;
}
Index++;
}
return TrimmedRange(start, Index);
}
public string ReadForwardOrOperand()
{
int start = Index;
int depth = 0;
while (Index < _input.Count)
{
var token = _input[Index];
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
break;
if (token.Kind == LuaSyntaxTokenKind.Operator)
{
if (token.Text is "(" or "[" or "{")
depth++;
else if (token.Text is ")" or "]" or "}")
{
if (depth == 0)
break;
depth--;
}
else if (depth == 0 && token.Text is "," or ";")
break;
}
else if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
break;
Index++;
}
return TrimmedRange(start, Index);
}
public string Serialize()
{
var builder = new StringBuilder();
foreach (var token in _output)
builder.Append(token.Text);
return builder.ToString();
}
private string Concat(int begin, int end)
{
var builder = new StringBuilder();
for (int i = begin; i < end; i++)
builder.Append(_output[i].Text);
return builder.ToString();
}
private string TrimmedRange(int begin, int end)
{
while (begin < end && _input[begin].IsTrivia)
begin++;
while (end > begin && _input[end - 1].IsTrivia)
end--;
var builder = new StringBuilder();
for (int i = begin; i < end; i++)
builder.Append(_input[i].Text);
return builder.ToString();
}
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Compat.Syntax
{
internal readonly record struct LuaRewriteDiagnostic(int Line, string Message);
}
+21
ファイルの表示
@@ -0,0 +1,21 @@
namespace LuaScript.Compat.Syntax
{
internal static class LuaSyntaxFacts
{
public static bool IsValueEnd(LuaSyntaxToken token) => token.Kind switch
{
LuaSyntaxTokenKind.Number or LuaSyntaxTokenKind.String => true,
LuaSyntaxTokenKind.Name => !LuaKeywords.IsReserved(token.Text) || token.Text is "nil" or "true" or "false",
LuaSyntaxTokenKind.Operator => token.Text is ")" or "]" or "}",
_ => false,
};
public static bool IsValueStart(LuaSyntaxToken token) => token.Kind switch
{
LuaSyntaxTokenKind.Number or LuaSyntaxTokenKind.String => true,
LuaSyntaxTokenKind.Name => !LuaKeywords.IsReserved(token.Text) || token.Text is "nil" or "true" or "false" or "not" or "function",
LuaSyntaxTokenKind.Operator => token.Text is "(" or "{" or "-" or "#" or "~",
_ => false,
};
}
}
+246
ファイルの表示
@@ -0,0 +1,246 @@
using System.Collections.Generic;
namespace LuaScript.Compat.Syntax
{
internal static class LuaSyntaxLexer
{
private static readonly string[] Operators =
{
"...", "..=", "??=", "||=", "&&=",
"==", "~=", "<=", ">=", "..", "::", "??", "||", "&&", "!=", "++",
"=>", "|>",
"+=", "-=", "*=", "/=", "%=", "^=",
"+", "-", "*", "/", "%", "^", "#", "<", ">", "=",
"(", ")", "{", "}", "[", "]", ";", ":", ",", ".",
"!", "&", "|", "?", "~",
};
public static List<LuaSyntaxToken> Tokenize(string source)
{
var tokens = new List<LuaSyntaxToken>();
int i = 0;
int length = source.Length;
while (i < length)
{
char c = source[i];
if (c == '\r' || c == '\n')
{
int start = i;
if (c == '\r' && i + 1 < length && source[i + 1] == '\n')
i += 2;
else
i++;
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Newline, source.Substring(start, i - start)));
continue;
}
if (c == ' ' || c == '\t' || c == '\f' || c == '\v')
{
int start = i;
while (i < length && (source[i] == ' ' || source[i] == '\t' || source[i] == '\f' || source[i] == '\v'))
i++;
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, source.Substring(start, i - start)));
continue;
}
if (c == '-' && i + 1 < length && source[i + 1] == '-')
{
int start = i;
i = SkipComment(source, i + 2);
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Comment, source.Substring(start, i - start)));
continue;
}
if (c == '[')
{
int level = LongBracketLevel(source, i);
if (level >= 0)
{
int start = i;
i = SkipLongBracket(source, i, level);
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.String, source.Substring(start, i - start)));
continue;
}
}
if (c == '"' || c == '\'')
{
int start = i;
i = SkipShortString(source, i);
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.String, source.Substring(start, i - start)));
continue;
}
if (c == '`')
{
int start = i;
i = SkipShortString(source, i);
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.InterpolatedString, source.Substring(start, i - start)));
continue;
}
if (IsDigit(c) || (c == '.' && i + 1 < length && IsDigit(source[i + 1])))
{
int start = i;
i = SkipNumber(source, i);
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Number, source.Substring(start, i - start)));
continue;
}
if (IsNameStart(c))
{
int start = i;
while (i < length && IsNamePart(source[i]))
i++;
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, source.Substring(start, i - start)));
continue;
}
string? op = MatchOperator(source, i);
if (op is not null)
{
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, op));
i += op.Length;
continue;
}
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, source.Substring(i, 1)));
i++;
}
return tokens;
}
private static string? MatchOperator(string source, int index)
{
int remaining = source.Length - index;
foreach (var op in Operators)
{
if (op.Length > remaining)
continue;
if (string.CompareOrdinal(source, index, op, 0, op.Length) == 0)
return op;
}
return null;
}
private static int SkipNumber(string source, int i)
{
int length = source.Length;
if (source[i] == '0' && i + 1 < length && (source[i + 1] == 'x' || source[i + 1] == 'X'))
{
i += 2;
while (i < length && (IsHexDigit(source[i]) || source[i] == '.'))
i++;
if (i < length && (source[i] == 'p' || source[i] == 'P'))
{
i++;
if (i < length && (source[i] == '+' || source[i] == '-'))
i++;
while (i < length && IsDigit(source[i]))
i++;
}
return i;
}
while (i < length && IsDigit(source[i]))
i++;
if (i < length && source[i] == '.' && !(i + 1 < length && source[i + 1] == '.'))
{
i++;
while (i < length && IsDigit(source[i]))
i++;
}
if (i < length && (source[i] == 'e' || source[i] == 'E'))
{
i++;
if (i < length && (source[i] == '+' || source[i] == '-'))
i++;
while (i < length && IsDigit(source[i]))
i++;
}
return i;
}
private static int SkipComment(string source, int i)
{
int level = LongBracketLevel(source, i);
if (level >= 0)
return SkipLongBracket(source, i, level);
int length = source.Length;
while (i < length && source[i] != '\n' && source[i] != '\r')
i++;
return i;
}
private static int LongBracketLevel(string source, int i)
{
if (i >= source.Length || source[i] != '[')
return -1;
int j = i + 1;
int level = 0;
while (j < source.Length && source[j] == '=')
{
level++;
j++;
}
return j < source.Length && source[j] == '[' ? level : -1;
}
private static int SkipLongBracket(string source, int i, int level)
{
int length = source.Length;
i += level + 2;
while (i < length)
{
if (source[i] == ']')
{
int j = i + 1;
int count = 0;
while (j < length && source[j] == '=')
{
count++;
j++;
}
if (count == level && j < length && source[j] == ']')
return j + 1;
}
i++;
}
return length;
}
private static int SkipShortString(string source, int start)
{
char quote = source[start];
int i = start + 1;
int length = source.Length;
while (i < length)
{
char c = source[i];
if (c == '\\')
{
i += 2;
continue;
}
if (c == quote)
return i + 1;
if (c == '\n' || c == '\r')
return i;
i++;
}
return length;
}
private static bool IsNameStart(char c) => c == '_' || char.IsLetter(c);
private static bool IsNamePart(char c) => c == '_' || char.IsLetterOrDigit(c);
private static bool IsDigit(char c) => c >= '0' && c <= '9';
private static bool IsHexDigit(char c) => IsDigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}
}
+14
ファイルの表示
@@ -0,0 +1,14 @@
using System;
namespace LuaScript.Compat.Syntax
{
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class LuaSyntaxRuleAttribute(int order) : Attribute
{
public int Order { get; } = order;
public bool IsCatalog { get; set; }
public string Keyword { get; set; } = "";
}
}
+21
ファイルの表示
@@ -0,0 +1,21 @@
namespace LuaScript.Compat.Syntax
{
internal readonly struct LuaSyntaxToken
{
public LuaSyntaxToken(LuaSyntaxTokenKind kind, string text)
{
Kind = kind;
Text = text;
}
public LuaSyntaxTokenKind Kind { get; }
public string Text { get; }
public bool IsTrivia => Kind is LuaSyntaxTokenKind.Whitespace or LuaSyntaxTokenKind.Newline or LuaSyntaxTokenKind.Comment;
public bool IsName(string value) => Kind == LuaSyntaxTokenKind.Name && Text == value;
public bool IsOperator(string value) => Kind == LuaSyntaxTokenKind.Operator && Text == value;
}
}
+14
ファイルの表示
@@ -0,0 +1,14 @@
namespace LuaScript.Compat.Syntax
{
internal enum LuaSyntaxTokenKind
{
Whitespace,
Newline,
Comment,
String,
InterpolatedString,
Number,
Name,
Operator,
}
}
+73
ファイルの表示
@@ -0,0 +1,73 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(70)]
internal sealed class AugmentedAssignmentRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (context.Current.Kind != LuaSyntaxTokenKind.Operator)
return false;
string? connective = Connective(context.Current.Text);
if (connective is null)
return false;
if (!context.TryReadTrailingLvalue(out _, out string target))
return false;
context.Advance();
string value = context.ReadLineExpression();
string separator = context.LastOutputIsTrivia() ? string.Empty : " ";
context.EmitRaw($"{separator}= {target} {connective} ({value})");
return true;
}
private static string? Connective(string op) => op switch
{
"+=" => "+",
"-=" => "-",
"*=" => "*",
"/=" => "/",
"%=" => "%",
"^=" => "^",
"..=" => "..",
"||=" => "or",
"&&=" => "and",
_ => null,
};
}
[LuaSyntaxRule(80)]
internal sealed class NilCoalesceAssignRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("??="))
return false;
if (!context.TryReadTrailingLvalue(out int start, out string target))
return false;
context.RemoveOutputFrom(start);
context.Advance();
string value = context.ReadLineExpression();
context.EmitRaw($"if {target} == nil then {target} = ({value}) end");
return true;
}
}
[LuaSyntaxRule(90)]
internal sealed class IncrementRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("++"))
return false;
if (!context.TryReadTrailingLvalue(out _, out string target))
return false;
context.Advance();
string separator = context.LastOutputIsTrivia() ? string.Empty : " ";
context.EmitRaw($"{separator}= {target} + 1");
return true;
}
}
}
+60
ファイルの表示
@@ -0,0 +1,60 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(10)]
internal sealed class IsNotRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsName("is"))
return false;
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
return false;
int notIndex = context.NextSignificantSameLine(context.Index + 1);
if (notIndex < 0 || !context.Input[notIndex].IsName("not"))
return false;
int after = context.NextSignificant(notIndex + 1);
if (after < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[after]))
return false;
context.EmitOperator("~=");
context.Index = notIndex + 1;
return true;
}
}
[LuaSyntaxRule(20)]
internal sealed class IsRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsName("is"))
return false;
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
return false;
int next = context.NextSignificantSameLine(context.Index + 1);
if (next < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[next]))
return false;
context.EmitOperator("==");
context.Advance();
return true;
}
}
[LuaSyntaxRule(30)]
internal sealed class NotEqualRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("!="))
return false;
context.EmitOperator("~=");
context.Advance();
return true;
}
}
}
+76
ファイルの表示
@@ -0,0 +1,76 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(2, IsCatalog = true, Keyword = MarkerKeyword)]
internal sealed class LuaFastRule : ILuaSyntaxRule
{
private const string MarkerKeyword = "fast";
private const string Message = "[fast]: only obj.fill, obj.convolve and obj.resize can be accelerated.";
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("["))
return false;
if (context.TryPreviousOutputSignificantSameLine(out var previous) && LuaSyntaxFacts.IsValueEnd(previous))
return false;
int nameIndex = context.NextSignificant(context.Index + 1);
if (nameIndex < 0 || !context.Input[nameIndex].IsName(MarkerKeyword))
return false;
int closeIndex = context.NextSignificant(nameIndex + 1);
if (closeIndex < 0 || !context.Input[closeIndex].IsOperator("]"))
return false;
int targetIndex = context.NextSignificant(closeIndex + 1);
if (targetIndex < 0 || context.Input[targetIndex].Kind != LuaSyntaxTokenKind.Name)
return false;
if (TryResolveTarget(context, targetIndex, out int funcIndex, out string function))
{
EmitBetween(context, closeIndex + 1, targetIndex);
context.Index = funcIndex + 1;
context.EmitRaw("__fast_" + function);
return true;
}
context.AddDiagnostic(Message);
EmitBetween(context, closeIndex + 1, targetIndex);
context.Index = targetIndex;
return true;
}
private static bool TryResolveTarget(LuaRewriteContext context, int objIndex, out int funcIndex, out string function)
{
funcIndex = -1;
function = string.Empty;
if (!context.Input[objIndex].IsName("obj"))
return false;
int dot = context.NextSignificant(objIndex + 1);
if (dot < 0 || !context.Input[dot].IsOperator("."))
return false;
int name = context.NextSignificant(dot + 1);
if (name < 0)
return false;
string text = context.Input[name].Text;
if (text is not ("fill" or "convolve" or "resize"))
return false;
int paren = context.NextSignificant(name + 1);
if (paren < 0 || !context.Input[paren].IsOperator("("))
return false;
funcIndex = name;
function = text;
return true;
}
private static void EmitBetween(LuaRewriteContext context, int from, int to)
{
for (int i = from; i < to; i++)
context.Emit(context.Input[i]);
}
}
}
+117
ファイルの表示
@@ -0,0 +1,117 @@
using System.Collections.Generic;
using System.Text;
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(5)]
internal sealed class LuaInterpolatedStringRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (context.Current.Kind != LuaSyntaxTokenKind.InterpolatedString)
return false;
string text = context.Current.Text;
int end = text.Length;
if (end >= 2 && text[end - 1] == '`')
end--;
string content = text.Substring(1, end - 1);
var pieces = new List<string>();
var literal = new StringBuilder();
int i = 0;
while (i < content.Length)
{
char c = content[i];
if (c == '\\' && i + 1 < content.Length)
{
literal.Append(content[i]);
literal.Append(content[i + 1]);
i += 2;
continue;
}
if (c == '{')
{
int close = FindClosingBrace(content, i + 1);
if (close < 0)
{
literal.Append(c);
i++;
continue;
}
string expression = content.Substring(i + 1, close - i - 1).Trim();
if (expression.Length > 0)
{
FlushLiteral(pieces, literal);
pieces.Add($"tostring({LuaSyntaxExtensions.Rewrite(expression)})");
}
i = close + 1;
continue;
}
literal.Append(c);
i++;
}
FlushLiteral(pieces, literal);
context.Advance();
if (pieces.Count == 0)
{
context.EmitRaw("\"\"");
return true;
}
if (pieces.Count == 1)
{
context.EmitRaw(pieces[0]);
return true;
}
context.EmitRaw($"({string.Join(" .. ", pieces)})");
return true;
}
private static void FlushLiteral(List<string> pieces, StringBuilder literal)
{
if (literal.Length == 0)
return;
pieces.Add($"\"{literal.ToString().Replace("\"", "\\\"")}\"");
literal.Clear();
}
private static int FindClosingBrace(string content, int from)
{
int depth = 0;
char quote = '\0';
for (int i = from; i < content.Length; i++)
{
char c = content[i];
if (quote != '\0')
{
if (c == '\\')
{
i++;
continue;
}
if (c == quote)
quote = '\0';
continue;
}
if (c == '"' || c == '\'')
{
quote = c;
continue;
}
if (c == '{')
{
depth++;
continue;
}
if (c == '}')
{
if (depth == 0)
return i;
depth--;
}
}
return -1;
}
}
}
+74
ファイルの表示
@@ -0,0 +1,74 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(35)]
internal sealed class LuaLambdaRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("=>"))
return false;
if (!context.TryReadTrailingLvalue(out int start, out string target))
return false;
if (!TryNormalizeParameters(target, out string parameters))
return false;
int body = context.NextSignificant(context.Index + 1);
if (body < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[body]))
return false;
context.RemoveOutputFrom(start);
context.Advance();
string expression = context.ReadForwardOrOperand();
if (expression.Length == 0)
return false;
context.EmitRaw($"(function({parameters}) return {LuaSyntaxExtensions.Rewrite(expression)} end)");
return true;
}
private static bool TryNormalizeParameters(string text, out string parameters)
{
parameters = string.Empty;
text = text.Trim();
bool wrapped = text.StartsWith("(") && text.EndsWith(")");
if (wrapped)
text = text.Substring(1, text.Length - 2).Trim();
if (text.Length == 0)
return wrapped;
var names = text.Split(',');
for (int i = 0; i < names.Length; i++)
{
string name = names[i].Trim();
if (name == "...")
{
if (i != names.Length - 1)
return false;
continue;
}
if (!IsName(name) || LuaKeywords.IsReserved(name))
return false;
if (!wrapped && names.Length > 1)
return false;
}
parameters = string.Join(", ", System.Array.ConvertAll(names, static n => n.Trim()));
return true;
}
private static bool IsName(string text)
{
if (text.Length == 0)
return false;
if (text[0] != '_' && !char.IsLetter(text[0]))
return false;
for (int i = 1; i < text.Length; i++)
{
if (text[i] != '_' && !char.IsLetterOrDigit(text[i]))
return false;
}
return true;
}
}
}
+44
ファイルの表示
@@ -0,0 +1,44 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(40)]
internal sealed class LogicalNotRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("!"))
return false;
context.Advance();
context.EmitWord("not");
return true;
}
}
[LuaSyntaxRule(50)]
internal sealed class AndAliasRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("&&"))
return false;
context.Advance();
context.EmitWord("and");
return true;
}
}
[LuaSyntaxRule(60)]
internal sealed class OrAliasRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("||"))
return false;
context.Advance();
context.EmitWord("or");
return true;
}
}
}
+20
ファイルの表示
@@ -0,0 +1,20 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(100)]
internal sealed class NilCoalesceRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("??"))
return false;
if (!context.TryPopOrOperand(out string left))
return false;
context.Advance();
string right = context.ReadForwardOrOperand();
string temporary = context.NextTemporary();
context.EmitRaw($"(function() local {temporary} = ({left}) if {temporary} ~= nil then return {temporary} else return ({right}) end end)()");
return true;
}
}
}
+26
ファイルの表示
@@ -0,0 +1,26 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(110)]
internal sealed class LuaNumericRangeRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsName("in"))
return false;
int open = context.NextSignificant(context.Index + 1);
if (open < 0 || !context.Input[open].IsOperator("<"))
return false;
if (!LuaRangeSyntax.TryParse(context.Input, open, out var parts, out int end))
return false;
string stopExpression = parts.Exclusive ? $"({parts.Stop}) - 1" : parts.Stop;
string replacement = parts.Step is null
? $"= {parts.Start}, {stopExpression}"
: $"= {parts.Start}, {stopExpression}, {parts.Step}";
context.EmitRaw(replacement);
context.Index = end;
return true;
}
}
}
+122
ファイルの表示
@@ -0,0 +1,122 @@
using System.Collections.Generic;
using System.Text;
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(98)]
internal sealed class LuaPipeRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("|>"))
return false;
int targetStart = context.NextSignificant(context.Index + 1);
if (targetStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[targetStart]))
return false;
if (!context.TryPopOrOperand(out string left))
return false;
context.Advance();
var segment = ReadSegment(context);
string call = BuildCall(segment, left);
context.EmitRaw(call);
return true;
}
private static List<LuaSyntaxToken> ReadSegment(LuaRewriteContext context)
{
var tokens = new List<LuaSyntaxToken>();
int depth = 0;
while (!context.AtEnd)
{
var token = context.Current;
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
break;
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
break;
if (token.Kind == LuaSyntaxTokenKind.Operator)
{
if (token.Text is "(" or "[" or "{")
{
depth++;
}
else if (token.Text is ")" or "]" or "}")
{
if (depth == 0)
break;
depth--;
}
else if (depth == 0 && token.Text is "," or ";" or "|>")
{
break;
}
}
tokens.Add(token);
context.Advance();
}
while (tokens.Count > 0 && tokens[0].IsTrivia)
tokens.RemoveAt(0);
while (tokens.Count > 0 && tokens[tokens.Count - 1].IsTrivia)
tokens.RemoveAt(tokens.Count - 1);
return tokens;
}
private static string BuildCall(List<LuaSyntaxToken> segment, string left)
{
string argument = $"({left})";
if (segment.Count == 0)
return argument;
if (segment[segment.Count - 1].IsOperator(")"))
{
int open = FindOpeningParen(segment);
if (open > 0)
{
string callee = Concat(segment, 0, open);
string arguments = Concat(segment, open + 1, segment.Count - 1);
return arguments.Length == 0
? $"{callee}({argument})"
: $"{callee}({argument}, {arguments})";
}
}
return $"{Concat(segment, 0, segment.Count)}({argument})";
}
private static int FindOpeningParen(List<LuaSyntaxToken> segment)
{
int depth = 0;
for (int i = segment.Count - 1; i >= 0; i--)
{
var token = segment[i];
if (token.Kind != LuaSyntaxTokenKind.Operator)
continue;
if (token.Text is ")" or "]" or "}")
{
depth++;
}
else if (token.Text is "(" or "[" or "{")
{
depth--;
if (depth == 0)
return token.Text == "(" ? i : -1;
}
}
return -1;
}
private static string Concat(List<LuaSyntaxToken> segment, int begin, int end)
{
while (begin < end && segment[begin].IsTrivia)
begin++;
while (end > begin && segment[end - 1].IsTrivia)
end--;
var builder = new StringBuilder();
for (int i = begin; i < end; i++)
builder.Append(segment[i].Text);
return builder.ToString();
}
}
}
+49
ファイルの表示
@@ -0,0 +1,49 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(108)]
internal sealed class LuaRangeMembershipRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsName("in"))
return false;
if (IsForHeader(context))
return false;
int open = context.NextSignificant(context.Index + 1);
if (open < 0 || !context.Input[open].IsOperator("<"))
return false;
if (!LuaRangeSyntax.TryParse(context.Input, open, out var parts, out int end))
return false;
if (parts.Step is not null)
return false;
if (!context.TryPopOrOperand(out string left))
return false;
string temporary = context.NextTemporary();
string upper = parts.Exclusive ? "<" : "<=";
context.EmitRaw($"(function() local {temporary} = ({left}) return {temporary} >= ({LuaSyntaxExtensions.Rewrite(parts.Start)}) and {temporary} {upper} ({LuaSyntaxExtensions.Rewrite(parts.Stop)}) end)()");
context.Index = end;
return true;
}
private static bool IsForHeader(LuaRewriteContext context)
{
var output = context.Output;
for (int i = output.Count - 1; i >= 0; i--)
{
var token = output[i];
if (token.Kind == LuaSyntaxTokenKind.Newline)
return false;
if (token.Kind != LuaSyntaxTokenKind.Name)
continue;
if (token.Text is "do" or "then")
return false;
if (token.Text == "for")
return true;
}
return false;
}
}
}
+105
ファイルの表示
@@ -0,0 +1,105 @@
using System.Text;
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(92)]
internal sealed class LuaSafeNavigationRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("?"))
return false;
int accessor = context.NextSignificantSameLine(context.Index + 1);
if (accessor < 0)
return false;
if (context.Input[accessor].IsOperator("."))
return TryApplyMember(context, accessor);
if (context.Input[accessor].IsOperator("["))
return TryApplyIndex(context, accessor);
return false;
}
private static bool TryApplyMember(LuaRewriteContext context, int accessor)
{
int name = context.NextSignificantSameLine(accessor + 1);
if (name < 0)
return false;
var token = context.Input[name];
if (token.Kind != LuaSyntaxTokenKind.Name || LuaKeywords.IsReserved(token.Text))
return false;
if (!context.TryReadTrailingLvalue(out int start, out string target))
return false;
context.RemoveOutputFrom(start);
context.Index = name + 1;
string temporary = context.NextTemporary();
context.EmitRaw($"(function() local {temporary} = ({target}) if {temporary} == nil then return nil end return {temporary}.{token.Text} end)()");
return true;
}
private static bool TryApplyIndex(LuaRewriteContext context, int accessor)
{
int close = FindClosingBracket(context, accessor + 1);
if (close < 0)
return false;
string key = Concat(context, accessor + 1, close);
if (key.Length == 0)
return false;
if (!context.TryReadTrailingLvalue(out int start, out string target))
return false;
context.RemoveOutputFrom(start);
context.Index = close + 1;
string temporary = context.NextTemporary();
context.EmitRaw($"(function() local {temporary} = ({target}) if {temporary} == nil then return nil end return {temporary}[{LuaSyntaxExtensions.Rewrite(key)}] end)()");
return true;
}
private static int FindClosingBracket(LuaRewriteContext context, int from)
{
int depth = 0;
for (int i = from; i < context.Input.Count; i++)
{
var token = context.Input[i];
if (token.Kind != LuaSyntaxTokenKind.Operator)
continue;
if (token.Text is "(" or "[" or "{")
{
depth++;
continue;
}
if (token.Text is ")" or "}")
{
if (depth == 0)
return -1;
depth--;
continue;
}
if (token.Text == "]")
{
if (depth == 0)
return i;
depth--;
}
}
return -1;
}
private static string Concat(LuaRewriteContext context, int begin, int end)
{
while (begin < end && context.Input[begin].IsTrivia)
begin++;
while (end > begin && context.Input[end - 1].IsTrivia)
end--;
var builder = new StringBuilder();
for (int i = begin; i < end; i++)
builder.Append(context.Input[i].Text);
return builder.ToString();
}
}
}
+85
ファイルの表示
@@ -0,0 +1,85 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(96)]
internal sealed class LuaTernaryRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("?"))
return false;
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
return false;
int thenStart = context.NextSignificantSameLine(context.Index + 1);
if (thenStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[thenStart]))
return false;
int colon = FindColon(context, context.Index + 1);
if (colon < 0)
return false;
int elseStart = context.NextSignificantSameLine(colon + 1);
if (elseStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[elseStart]))
return false;
if (!context.TryPopOrOperand(out string condition))
return false;
context.Index++;
string thenExpression = ReadUntil(context, colon);
context.Index = colon + 1;
string elseExpression = context.ReadForwardOrOperand();
context.EmitRaw($"(function() if {condition} then return ({LuaSyntaxExtensions.Rewrite(thenExpression)}) else return ({LuaSyntaxExtensions.Rewrite(elseExpression)}) end end)()");
return true;
}
private static int FindColon(LuaRewriteContext context, int from)
{
int depth = 0;
for (int i = from; i < context.Input.Count; i++)
{
var token = context.Input[i];
if (token.Kind == LuaSyntaxTokenKind.Newline)
return -1;
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
return -1;
if (token.Kind != LuaSyntaxTokenKind.Operator)
continue;
if (token.Text is "(" or "[" or "{")
{
depth++;
continue;
}
if (token.Text is ")" or "]" or "}")
{
if (depth == 0)
return -1;
depth--;
continue;
}
if (depth > 0)
continue;
if (token.Text is "," or ";" or "?")
return -1;
if (token.Text == ":")
return i;
}
return -1;
}
private static string ReadUntil(LuaRewriteContext context, int stop)
{
var builder = new System.Text.StringBuilder();
int begin = context.Index;
int end = stop;
while (begin < end && context.Input[begin].IsTrivia)
begin++;
while (end > begin && context.Input[end - 1].IsTrivia)
end--;
for (int i = begin; i < end; i++)
builder.Append(context.Input[i].Text);
return builder.ToString();
}
}
}
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderClass(
string Namespace,
EquatableArray<GpuShaderTypePart> TypeChain,
EquatableArray<GpuShaderMethod> Methods,
EquatableArray<string> Errors);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderFile(string Path, string Source);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderInvocation(string Resources, string Constants, string Target, string Width, string Height);
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderMethod(
string Accessibility,
bool IsStatic,
string ReturnType,
string MethodName,
EquatableArray<GpuShaderParameter> Parameters,
string FileName,
string EntryPoint,
GpuShaderInvocation Invocation);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderMethodSource(GpuShaderMethod Method, string Bytecode);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderParameter(string Prefix, string Type, string Name);
}
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System.Collections.Immutable;
namespace LuaScript.Generator
{
internal sealed record GpuShaderResolution(ImmutableArray<GpuShaderMethodSource> Methods, ImmutableArray<string> Errors);
}
+436
ファイルの表示
@@ -0,0 +1,436 @@
using System.Collections.Immutable;
using System.Globalization;
using System.IO;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace LuaScript.Generator
{
[Generator]
public sealed class GpuShaderSourceGenerator : IIncrementalGenerator
{
private const string AttributeName = "LuaScript.Engine.Processing.GpuPixelOperationShaderAttribute";
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var classes = context.SyntaxProvider
.CreateSyntaxProvider(
static (node, _) => node is ClassDeclarationSyntax { AttributeLists.Count: > 0 },
static (ctx, _) => CreateClass(ctx))
.Where(static model => model is not null)
.Select(static (model, _) => model!);
var files = context.AdditionalTextsProvider
.Where(static file => file.Path.EndsWith(".hlsl", StringComparison.OrdinalIgnoreCase))
.Select(static (file, token) => new GpuShaderFile(Normalize(file.Path), file.GetText(token)?.ToString() ?? string.Empty))
.Collect()
.Select(static (items, _) => new EquatableArray<GpuShaderFile>([.. items]));
context.RegisterSourceOutput(classes.Combine(files), static (context, source) =>
{
var (model, files) = source;
var resolved = Resolve(model, files);
if (resolved.Errors.Length > 0)
{
context.AddSource(ErrorHintName(model), SourceText.From(EmitErrors(resolved.Errors), Encoding.UTF8));
return;
}
context.AddSource(HintName(model), SourceText.From(Emit(model, resolved.Methods), Encoding.UTF8));
});
}
private static GpuShaderClass? CreateClass(GeneratorSyntaxContext context)
{
if (context.Node is not ClassDeclarationSyntax declaration)
return null;
if (context.SemanticModel.GetDeclaredSymbol(declaration) is not INamedTypeSymbol type)
return null;
var attributes = type.GetAttributes()
.Where(static attribute => attribute.AttributeClass?.ToDisplayString() == AttributeName)
.ToArray();
if (attributes.Length == 0)
return null;
var chain = new List<GpuShaderTypePart>();
for (var current = type; current is not null; current = current.ContainingType)
chain.Insert(0, new GpuShaderTypePart(current.Name, current.IsStatic));
var methods = ImmutableArray.CreateBuilder<GpuShaderMethod>();
var errors = ImmutableArray.CreateBuilder<string>();
foreach (var attribute in attributes)
{
if (attribute.ConstructorArguments.Length < 3 ||
attribute.ConstructorArguments[0].Value is not string methodName ||
attribute.ConstructorArguments[1].Value is not string fileName ||
attribute.ConstructorArguments[2].Value is not string entryPoint)
{
errors.Add("GPU shader attribute arguments are invalid");
continue;
}
var candidates = type.GetMembers(methodName).OfType<IMethodSymbol>().ToArray();
if (candidates.Length == 0)
{
errors.Add($"GPU shader method '{methodName}' was not found");
continue;
}
if (candidates.Length > 1)
{
errors.Add($"GPU shader method '{methodName}' is ambiguous");
continue;
}
var method = candidates[0];
string? error = Validate(method, fileName, entryPoint, out var invocation);
if (error is not null)
{
errors.Add($"GPU shader method '{methodName}': {error}");
continue;
}
var parameters = ImmutableArray.CreateBuilder<GpuShaderParameter>();
foreach (var parameter in method.Parameters)
parameters.Add(new GpuShaderParameter(ParameterPrefix(parameter), parameter.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), parameter.Name));
methods.Add(new GpuShaderMethod(
AccessibilityName(method.DeclaredAccessibility),
method.IsStatic,
method.ReturnType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
method.Name,
new EquatableArray<GpuShaderParameter>([.. parameters]),
Normalize(fileName),
entryPoint,
invocation));
}
return new GpuShaderClass(
type.ContainingNamespace.IsGlobalNamespace ? string.Empty : type.ContainingNamespace.ToDisplayString(),
new EquatableArray<GpuShaderTypePart>([.. chain]),
new EquatableArray<GpuShaderMethod>([.. methods]),
new EquatableArray<string>([.. errors]));
}
private static string? Validate(IMethodSymbol method, string fileName, string entryPoint, out GpuShaderInvocation invocation)
{
invocation = new GpuShaderInvocation(string.Empty, string.Empty, string.Empty, string.Empty, string.Empty);
if (string.IsNullOrWhiteSpace(fileName))
return "file name is empty";
if (string.IsNullOrWhiteSpace(entryPoint))
return "entry point is empty";
if (method.ReturnType.SpecialType != SpecialType.System_Boolean)
return "return type must be bool";
var parameters = method.Parameters;
if (parameters.Length == 4 &&
IsReadOnlySpanSingle(parameters[0].Type) &&
IsByteArray(parameters[1].Type) &&
IsInt32(parameters[2].Type) &&
IsInt32(parameters[3].Type))
{
invocation = new GpuShaderInvocation("[]", parameters[0].Name, parameters[1].Name, parameters[2].Name, parameters[3].Name);
return null;
}
if (parameters.Length == 5 &&
IsReadOnlySpanPixelShaderInput(parameters[0].Type) &&
IsReadOnlySpanSingle(parameters[1].Type) &&
IsByteArray(parameters[2].Type) &&
IsInt32(parameters[3].Type) &&
IsInt32(parameters[4].Type))
{
invocation = new GpuShaderInvocation(parameters[0].Name, parameters[1].Name, parameters[2].Name, parameters[3].Name, parameters[4].Name);
return null;
}
return "signature is invalid";
}
private static GpuShaderResolution Resolve(GpuShaderClass model, EquatableArray<GpuShaderFile> files)
{
var methods = ImmutableArray.CreateBuilder<GpuShaderMethodSource>();
var errors = ImmutableArray.CreateBuilder<string>();
errors.AddRange(model.Errors);
foreach (var method in model.Methods)
{
var matched = files.Where(file => Matches(file.Path, method.FileName)).ToArray();
if (matched.Length == 0)
{
errors.Add($"GPU shader file '{method.FileName}' for method '{method.MethodName}' was not found");
continue;
}
if (matched.Length > 1)
{
errors.Add($"GPU shader file '{method.FileName}' for method '{method.MethodName}' matched multiple additional files");
continue;
}
string? failure = ShaderCompiler.Compile(matched[0].Source, method.EntryPoint, out string bytecode);
if (failure is not null)
{
errors.Add($"GPU shader method '{method.MethodName}' failed to compile: {failure}");
continue;
}
methods.Add(new GpuShaderMethodSource(method, bytecode));
}
return new GpuShaderResolution([.. methods], [.. errors]);
}
private static bool Matches(string filePath, string registrationPath)
{
if (string.Equals(filePath, registrationPath, StringComparison.OrdinalIgnoreCase))
return true;
return filePath.EndsWith("/" + registrationPath, StringComparison.OrdinalIgnoreCase);
}
private static bool IsReadOnlySpanSingle(ITypeSymbol type)
{
return type is INamedTypeSymbol named &&
named.OriginalDefinition.ToDisplayString() == "System.ReadOnlySpan<T>" &&
named.TypeArguments.Length == 1 &&
named.TypeArguments[0].SpecialType == SpecialType.System_Single;
}
private static bool IsReadOnlySpanPixelShaderInput(ITypeSymbol type)
{
string display = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
return display.Contains("ReadOnlySpan", StringComparison.Ordinal) &&
display.Contains("PixelShaderInput", StringComparison.Ordinal);
}
private static bool IsByteArray(ITypeSymbol type)
{
return type is IArrayTypeSymbol array &&
array.Rank == 1 &&
array.ElementType.SpecialType == SpecialType.System_Byte;
}
private static bool IsInt32(ITypeSymbol type) => type.SpecialType == SpecialType.System_Int32;
private static string Normalize(string path) => path.Replace(Path.DirectorySeparatorChar, '/').Replace(Path.AltDirectorySeparatorChar, '/');
private static string AccessibilityName(Accessibility accessibility)
{
return accessibility switch
{
Accessibility.Public => "public",
Accessibility.Internal => "internal",
Accessibility.Protected => "protected",
Accessibility.ProtectedAndInternal => "private protected",
Accessibility.ProtectedOrInternal => "protected internal",
_ => "private",
};
}
private static string ParameterPrefix(IParameterSymbol parameter)
{
return parameter.RefKind switch
{
RefKind.In => "in ",
RefKind.Ref => "ref ",
RefKind.Out => "out ",
_ => string.Empty,
};
}
private static string Emit(GpuShaderClass model, ImmutableArray<GpuShaderMethodSource> sources)
{
var builder = new StringBuilder();
builder.AppendLine("#nullable enable");
if (model.Namespace.Length > 0)
{
builder.AppendLine("namespace " + model.Namespace);
builder.AppendLine("{");
}
int indent = model.Namespace.Length > 0 ? 1 : 0;
foreach (var type in model.TypeChain)
{
AppendIndent(builder, indent);
builder.Append(type.IsStatic ? "static partial class " : "partial class ");
builder.AppendLine(type.Name);
AppendIndent(builder, indent);
builder.AppendLine("{");
indent++;
}
for (int i = 0; i < sources.Length; i++)
{
if (i > 0)
builder.AppendLine();
EmitMethod(builder, indent, sources[i]);
}
for (int i = model.TypeChain.Count - 1; i >= 0; i--)
{
indent--;
AppendIndent(builder, indent);
builder.AppendLine("}");
}
if (model.Namespace.Length > 0)
builder.AppendLine("}");
return builder.ToString();
}
private static void EmitMethod(StringBuilder builder, int indent, GpuShaderMethodSource source)
{
var method = source.Method;
string field = "s_shader_" + method.MethodName;
AppendIndent(builder, indent);
builder.Append("private static readonly byte[] ");
builder.Append(field);
builder.Append(" = global::System.Convert.FromBase64String(");
builder.Append(Literal(source.Bytecode));
builder.AppendLine(");");
builder.AppendLine();
AppendIndent(builder, indent);
builder.Append(method.Accessibility);
builder.Append(' ');
if (method.IsStatic)
builder.Append("static ");
builder.Append("partial ");
builder.Append(method.ReturnType);
builder.Append(' ');
builder.Append(method.MethodName);
builder.Append('(');
for (int i = 0; i < method.Parameters.Count; i++)
{
if (i > 0)
builder.Append(", ");
var parameter = method.Parameters[i];
builder.Append(parameter.Prefix);
builder.Append(parameter.Type);
builder.Append(' ');
builder.Append(parameter.Name);
}
builder.AppendLine(")");
AppendIndent(builder, indent);
builder.AppendLine("{");
AppendIndent(builder, indent + 1);
builder.Append("return Run(");
builder.Append(field);
builder.Append(", ");
builder.Append(method.Invocation.Resources);
builder.Append(", ");
builder.Append(method.Invocation.Constants);
builder.Append(", ");
builder.Append(method.Invocation.Target);
builder.Append(", ");
builder.Append(method.Invocation.Width);
builder.Append(", ");
builder.Append(method.Invocation.Height);
builder.AppendLine(");");
AppendIndent(builder, indent);
builder.AppendLine("}");
}
private static void AppendIndent(StringBuilder builder, int indent)
{
for (int i = 0; i < indent; i++)
builder.Append(" ");
}
private static string EmitErrors(ImmutableArray<string> errors)
{
var builder = new StringBuilder();
foreach (var error in errors)
builder.AppendLine("#error " + error);
return builder.ToString();
}
private static string HintName(GpuShaderClass model)
{
var builder = new StringBuilder("GpuPixelOperationShader");
if (model.Namespace.Length > 0)
{
builder.Append('.');
builder.Append(HintPart(model.Namespace));
}
foreach (var type in model.TypeChain)
{
builder.Append('.');
builder.Append(HintPart(type.Name));
}
builder.Append(".g.cs");
return builder.ToString();
}
private static string ErrorHintName(GpuShaderClass model)
{
return Path.ChangeExtension(HintName(model), ".Errors.g.cs");
}
private static string HintPart(string value)
{
var builder = new StringBuilder(value.Length);
foreach (char c in value)
builder.Append(char.IsLetterOrDigit(c) ? c : '_');
return builder.ToString();
}
private static string Literal(string value)
{
var builder = new StringBuilder(value.Length + 2);
builder.Append('"');
foreach (char c in value)
{
switch (c)
{
case '\\':
builder.Append(@"\\");
break;
case '"':
builder.Append("\\\"");
break;
case '\0':
builder.Append(@"\0");
break;
case '\a':
builder.Append(@"\a");
break;
case '\b':
builder.Append(@"\b");
break;
case '\f':
builder.Append(@"\f");
break;
case '\n':
builder.Append(@"\n");
break;
case '\r':
builder.Append(@"\r");
break;
case '\t':
builder.Append(@"\t");
break;
case '\v':
builder.Append(@"\v");
break;
default:
if (char.IsControl(c))
{
builder.Append(@"\u");
builder.Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
}
else
{
builder.Append(c);
}
break;
}
}
builder.Append('"');
return builder.ToString();
}
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderTypePart(string Name, bool IsStatic);
}
+96
ファイルの表示
@@ -0,0 +1,96 @@
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
namespace LuaScript.Generator
{
internal static class ShaderCompiler
{
private const string Profile = "ps_5_0";
public static string? Compile(string source, string entryPoint, out string bytecode)
{
bytecode = string.Empty;
byte[] data = Encoding.UTF8.GetBytes(source);
IntPtr code = IntPtr.Zero;
IntPtr errors = IntPtr.Zero;
try
{
int hr = D3DCompile(data, (IntPtr)data.Length, null, IntPtr.Zero, IntPtr.Zero, entryPoint, Profile, 0u, 0u, out code, out errors);
if (hr < 0 || code == IntPtr.Zero)
return ReadError(errors, hr);
bytecode = Convert.ToBase64String(ReadBlob(code));
return null;
}
catch (DllNotFoundException)
{
return "the Direct3D shader compiler is unavailable on this build host";
}
catch (EntryPointNotFoundException)
{
return "the Direct3D shader compiler is unavailable on this build host";
}
finally
{
Release(errors);
Release(code);
}
}
private static byte[] ReadBlob(IntPtr blob)
{
IntPtr pointer = Invoke<GetBufferPointerDelegate>(blob, 3)(blob);
int size = checked((int)(long)Invoke<GetBufferSizeDelegate>(blob, 4)(blob));
var buffer = new byte[size];
Marshal.Copy(pointer, buffer, 0, size);
return buffer;
}
private static string ReadError(IntPtr blob, int hr)
{
string fallback = "HRESULT 0x" + hr.ToString("X8", CultureInfo.InvariantCulture);
if (blob == IntPtr.Zero)
return fallback;
IntPtr pointer = Invoke<GetBufferPointerDelegate>(blob, 3)(blob);
int size = checked((int)(long)Invoke<GetBufferSizeDelegate>(blob, 4)(blob));
string message = (Marshal.PtrToStringAnsi(pointer, size) ?? string.Empty).Trim();
return message.Length > 0 ? message : fallback;
}
private static void Release(IntPtr unknown)
{
if (unknown != IntPtr.Zero)
Invoke<ReleaseDelegate>(unknown, 2)(unknown);
}
private static T Invoke<T>(IntPtr instance, int slot) where T : Delegate
{
IntPtr table = Marshal.ReadIntPtr(instance);
IntPtr function = Marshal.ReadIntPtr(table, slot * IntPtr.Size);
return (T)Marshal.GetDelegateForFunctionPointer(function, typeof(T));
}
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate IntPtr GetBufferPointerDelegate(IntPtr self);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate IntPtr GetBufferSizeDelegate(IntPtr self);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseDelegate(IntPtr self);
[DllImport("d3dcompiler_47.dll", CallingConvention = CallingConvention.StdCall)]
private static extern int D3DCompile(
byte[] srcData,
IntPtr srcDataSize,
[MarshalAs(UnmanagedType.LPStr)] string? sourceName,
IntPtr defines,
IntPtr include,
[MarshalAs(UnmanagedType.LPStr)] string entryPoint,
[MarshalAs(UnmanagedType.LPStr)] string target,
uint flags1,
uint flags2,
out IntPtr code,
out IntPtr errorMsgs);
}
}
+35 -58
ファイルの表示
@@ -5,60 +5,6 @@ using Microsoft.CodeAnalysis.Text;
namespace LuaScript.Generator
{
internal enum LuaParameterKind
{
ExecutionContext,
Arguments,
DynValue,
Double,
Int,
Bool,
}
internal enum LuaReturnKind
{
DynValue,
Double,
Void,
}
internal sealed record LuaParameterModel(string Name, LuaParameterKind Kind, string DefaultLiteral);
internal sealed record LuaFunctionModel(
string LuaName,
string MethodName,
LuaReturnKind ReturnKind,
EquatableArray<LuaParameterModel> Parameters);
internal sealed record LuaConstantModel(string LuaName, string MemberName);
internal enum LuaUpdateKind
{
Direct,
OptionalValue,
OptionalReference,
}
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind);
internal sealed record LuaCatalogEntry(
string Table,
string Name,
bool IsFunction,
EquatableArray<string> Parameters);
internal sealed record LuaTypePart(string Name, bool IsStatic);
internal sealed record LuaTableModel(
string Namespace,
EquatableArray<LuaTypePart> TypeChain,
string TableName,
string ContextType,
EquatableArray<LuaFunctionModel> Functions,
EquatableArray<LuaConstantModel> Constants,
EquatableArray<LuaUpdateModel> Updates,
EquatableArray<LuaCatalogEntry> Entries);
[Generator]
public sealed class LuaApiGenerator : IIncrementalGenerator
{
@@ -309,12 +255,30 @@ namespace LuaScript.Generator
var returnType = method.ReturnType;
LuaUpdateKind kind;
ITypeSymbol valueType;
if (returnType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
{
kind = LuaUpdateKind.OptionalValue;
valueType = ((INamedTypeSymbol)returnType).TypeArguments[0];
}
else if (returnType.IsReferenceType)
{
kind = LuaUpdateKind.OptionalReference;
valueType = returnType;
}
else
{
kind = LuaUpdateKind.Direct;
valueType = returnType;
}
var valueKind = valueType.SpecialType switch
{
SpecialType.System_Double or SpecialType.System_Int32 => LuaValueKind.Number,
SpecialType.System_Boolean => LuaValueKind.Boolean,
SpecialType.System_String => LuaValueKind.String,
_ => LuaValueKind.Other,
};
bool inCatalog = true;
foreach (var argument in attribute.NamedArguments)
@@ -325,7 +289,7 @@ namespace LuaScript.Generator
if (inCatalog)
entry = new LuaCatalogEntry(tableName, luaName, false, EquatableArray<string>.Empty);
return new LuaUpdateModel(luaName, method.Name, kind);
return new LuaUpdateModel(luaName, method.Name, kind, valueKind);
}
private static string FormatDouble(double value) =>
@@ -387,13 +351,19 @@ namespace LuaScript.Generator
switch (update.Kind)
{
case LuaUpdateKind.OptionalValue:
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table[\"{update.LuaName}\"] = value.Value; }}");
builder.AppendLine(update.ValueKind == LuaValueKind.Other
? $"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table[\"{update.LuaName}\"] = value.Value; }}"
: $"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, "value.Value")}); }}");
break;
case LuaUpdateKind.OptionalReference:
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value is not null) table[\"{update.LuaName}\"] = value; }}");
builder.AppendLine(update.ValueKind == LuaValueKind.Other
? $"{body}{{ var value = {update.MethodName}(context); if (value is not null) table[\"{update.LuaName}\"] = value; }}"
: $"{body}{{ var value = {update.MethodName}(context); if (value is not null) table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, "value")}); }}");
break;
default:
builder.AppendLine($"{body}table[\"{update.LuaName}\"] = {update.MethodName}(context);");
builder.AppendLine(update.ValueKind == LuaValueKind.Other
? $"{body}table[\"{update.LuaName}\"] = {update.MethodName}(context);"
: $"{body}table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, $"{update.MethodName}(context)")});");
break;
}
}
@@ -409,6 +379,13 @@ namespace LuaScript.Generator
return builder.ToString();
}
private static string WrapValue(LuaValueKind kind, string expression) => kind switch
{
LuaValueKind.Number => $"global::MoonSharp.Interpreter.DynValue.NewNumber({expression})",
LuaValueKind.Boolean => $"global::MoonSharp.Interpreter.DynValue.NewBoolean({expression})",
_ => $"global::MoonSharp.Interpreter.DynValue.NewString({expression})",
};
private static string EmitArguments(EquatableArray<LuaParameterModel> parameters)
{
var rendered = new List<string>();
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace LuaScript.Generator
{
internal sealed record LuaCatalogEntry(
string Table,
string Name,
bool IsFunction,
EquatableArray<string> Parameters);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record LuaConstantModel(string LuaName, string MemberName);
}
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace LuaScript.Generator
{
internal sealed record LuaFunctionModel(
string LuaName,
string MethodName,
LuaReturnKind ReturnKind,
EquatableArray<LuaParameterModel> Parameters);
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace LuaScript.Generator
{
internal enum LuaParameterKind
{
ExecutionContext,
Arguments,
DynValue,
Double,
Int,
Bool,
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record LuaParameterModel(string Name, LuaParameterKind Kind, string DefaultLiteral);
}
+9
ファイルの表示
@@ -0,0 +1,9 @@
namespace LuaScript.Generator
{
internal enum LuaReturnKind
{
DynValue,
Double,
Void,
}
}
+102
ファイルの表示
@@ -0,0 +1,102 @@
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace LuaScript.Generator
{
[Generator]
public sealed class LuaSyntaxRuleGenerator : IIncrementalGenerator
{
private const string RuleAttributeName = "LuaScript.Compat.Syntax.LuaSyntaxRuleAttribute";
private const string RuleInterfaceName = "LuaScript.Compat.Syntax.ILuaSyntaxRule";
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var rules = context.SyntaxProvider
.ForAttributeWithMetadataName(
RuleAttributeName,
static (node, _) => node is ClassDeclarationSyntax,
static (ctx, _) => CreateModel(ctx))
.Where(static model => model is not null)
.Select(static (model, _) => model!);
context.RegisterSourceOutput(rules.Collect(), static (ctx, models) =>
{
if (models.Length == 0)
return;
ctx.AddSource("LuaSyntaxRuleRegistry.g.cs", SourceText.From(Emit(models), Encoding.UTF8));
});
}
private static LuaSyntaxRuleModel? CreateModel(GeneratorAttributeSyntaxContext context)
{
if (context.TargetSymbol is not INamedTypeSymbol symbol)
return null;
if (!symbol.AllInterfaces.Any(static contract => contract.ToDisplayString() == RuleInterfaceName))
return null;
int order = 0;
var arguments = context.Attributes[0].ConstructorArguments;
if (arguments.Length > 0 && arguments[0].Value is int value)
order = value;
bool isCatalog = false;
string keyword = string.Empty;
foreach (var argument in context.Attributes[0].NamedArguments)
{
if (argument.Key == "IsCatalog" && argument.Value.Value is bool catalogValue)
isCatalog = catalogValue;
else if (argument.Key == "Keyword" && argument.Value.Value is string keywordValue)
keyword = keywordValue;
}
return new LuaSyntaxRuleModel(symbol.ToDisplayString(), order, isCatalog ? keyword : string.Empty);
}
private static string Emit(ImmutableArray<LuaSyntaxRuleModel> models)
{
var ordered = models
.OrderBy(static m => m.Order)
.ThenBy(static m => m.TypeName, StringComparer.Ordinal)
.ToArray();
var builder = new StringBuilder();
builder.AppendLine("#nullable enable");
builder.AppendLine("namespace LuaScript.Compat.Syntax");
builder.AppendLine("{");
builder.AppendLine(" internal static class LuaSyntaxRuleRegistry");
builder.AppendLine(" {");
builder.AppendLine(" internal static readonly global::LuaScript.Compat.Syntax.ILuaSyntaxRule[] Rules = new global::LuaScript.Compat.Syntax.ILuaSyntaxRule[]");
builder.AppendLine(" {");
foreach (var model in ordered)
builder.AppendLine($" new global::{model.TypeName}(),");
builder.AppendLine(" };");
var keywords = ordered
.Where(static m => m.CatalogKeyword.Length > 0)
.Select(static m => m.CatalogKeyword)
.Distinct()
.ToArray();
if (keywords.Length == 0)
{
builder.AppendLine(" internal static readonly string[] CatalogKeywords = global::System.Array.Empty<string>();");
}
else
{
builder.AppendLine(" internal static readonly string[] CatalogKeywords = new string[]");
builder.AppendLine(" {");
foreach (var keyword in keywords)
builder.AppendLine($" \"{keyword}\",");
builder.AppendLine(" };");
}
builder.AppendLine(" }");
builder.AppendLine("}");
return builder.ToString();
}
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record LuaSyntaxRuleModel(string TypeName, int Order, string CatalogKeyword);
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace LuaScript.Generator
{
internal sealed record LuaTableModel(
string Namespace,
EquatableArray<LuaTypePart> TypeChain,
string TableName,
string ContextType,
EquatableArray<LuaFunctionModel> Functions,
EquatableArray<LuaConstantModel> Constants,
EquatableArray<LuaUpdateModel> Updates,
EquatableArray<LuaCatalogEntry> Entries);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record LuaTypePart(string Name, bool IsStatic);
}
+9
ファイルの表示
@@ -0,0 +1,9 @@
namespace LuaScript.Generator
{
internal enum LuaUpdateKind
{
Direct,
OptionalValue,
OptionalReference,
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind, LuaValueKind ValueKind);
}
+10
ファイルの表示
@@ -0,0 +1,10 @@
namespace LuaScript.Generator
{
internal enum LuaValueKind
{
Number,
Boolean,
String,
Other,
}
}
+2 -2
ファイルの表示
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.13.4</Version>
<Version>1.20.3</Version>
<IsRoslynComponent>true</IsRoslynComponent>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
</PropertyGroup>
+134
ファイルの表示
@@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using LuaScript.Engine.Shader;
namespace LuaScript.Engine.Processing
{
[GpuPixelOperationShader(nameof(RunConvolve), "Shaders/convolve.hlsl", "convolve")]
internal sealed partial class GpuConvolveOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
{
private const int ConvolveWorkThreshold = 262144;
private const int MaxConvolveSize = 31;
private const int MaxConvolveValidationCount = 64;
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
private readonly float[] _constants = new float[1024];
private readonly List<ConvolveValidation> _validations = [];
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
{
if (!IsTextureSupported(target, width, height) || !IsSupported(kernel, size, divisor, offset))
return false;
long work = (long)width * height * size * size;
if (!force && work < ConvolveWorkThreshold || !EnsureValidated(target, width, height, kernel, size, divisor, offset))
return false;
SetConstants(width, height, kernel, size, divisor, offset);
_resources[0] = new PixelShaderInput(target, width, height);
return RunConvolve(_resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), target, width, height);
}
private bool EnsureValidated(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
{
for (int i = 0; i < _validations.Count; i++)
{
if (_validations[i].Matches(kernel, size, divisor, offset))
return _validations[i].Valid;
}
if (_validations.Count >= MaxConvolveValidationCount)
_validations.Clear();
bool valid = Validate(target, width, height, kernel, size, divisor, offset);
_validations.Add(new ConvolveValidation(kernel, size, divisor, offset, valid));
return valid;
}
private bool Validate(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
{
int probeWidth = Math.Min(width, 8);
int probeHeight = Math.Min(height, 7);
var probe = CopyProbe(target, width, height, probeWidth, probeHeight);
var cpu = (byte[])probe.Clone();
var gpu = (byte[])probe.Clone();
double[]? scratch = null;
PixelBufferSoftwareProcessor.Convolve(cpu, probeWidth, probeHeight, kernel, size, divisor, offset, ref scratch);
SetConstants(probeWidth, probeHeight, kernel, size, divisor, offset);
_resources[0] = new PixelShaderInput(gpu, probeWidth, probeHeight);
return RunConvolve(_resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), gpu, probeWidth, probeHeight) && Equal(cpu, gpu);
}
private void SetConstants(int width, int height, double[] kernel, int size, double divisor, double offset)
{
_constants[0] = width;
_constants[1] = height;
_constants[2] = (float)divisor;
_constants[3] = (float)offset;
_constants[4] = size;
_constants[5] = size / 2;
_constants[6] = 0f;
_constants[7] = 0f;
int taps = size * size;
for (int i = 0; i < taps; i++)
_constants[i + 8] = (float)kernel[i];
}
private static bool IsSupported(double[] kernel, int size, double divisor, double offset)
{
if (size < 1 || (size & 1) == 0 || size > MaxConvolveSize || divisor == 0d || !IsFloatCompatible(divisor) || !IsFloatCompatible(offset))
return false;
int taps = size * size;
if (kernel.Length < taps || taps + 8 > 1024)
return false;
for (int i = 0; i < taps; i++)
{
if (!IsFloatCompatible(kernel[i]))
return false;
}
return true;
}
private static bool IsFloatCompatible(double value)
{
return double.IsFinite(value) && float.IsFinite((float)value);
}
private partial bool RunConvolve(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
private sealed class ConvolveValidation
{
private readonly double[] _kernel;
private readonly int _size;
private readonly double _divisor;
private readonly double _offset;
public ConvolveValidation(double[] kernel, int size, double divisor, double offset, bool valid)
{
int taps = size * size;
_kernel = new double[taps];
Array.Copy(kernel, _kernel, taps);
_size = size;
_divisor = divisor;
_offset = offset;
Valid = valid;
}
public bool Valid { get; }
public bool Matches(double[] kernel, int size, double divisor, double offset)
{
if (_size != size || BitConverter.DoubleToInt64Bits(_divisor) != BitConverter.DoubleToInt64Bits(divisor) ||
BitConverter.DoubleToInt64Bits(_offset) != BitConverter.DoubleToInt64Bits(offset))
return false;
int taps = size * size;
for (int i = 0; i < taps; i++)
{
if (BitConverter.DoubleToInt64Bits(_kernel[i]) != BitConverter.DoubleToInt64Bits(kernel[i]))
return false;
}
return true;
}
}
}
}
+124
ファイルの表示
@@ -0,0 +1,124 @@
using System;
using LuaScript.Engine.Shader;
namespace LuaScript.Engine.Processing
{
[GpuPixelOperationShader(nameof(RunFillFull), "Shaders/fill.hlsl", "fill_full")]
[GpuPixelOperationShader(nameof(RunFillPartial), "Shaders/fill.hlsl", "fill_partial")]
internal sealed partial class GpuFillOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
{
private const int FillFullThreshold = 1048576;
private const int FillPartialThreshold = 1048576;
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
private readonly float[] _constants = new float[8];
private bool? _fullValidated;
private bool? _partialValidated;
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
{
if (!IsTextureSupported(target, width, height) || !AreFinite(r, g, b, a))
return false;
long pixels = (long)width * height;
bool full = x == 0 && y == 0 && fillWidth == width && fillHeight == height;
if (full)
{
if (!force && pixels < FillFullThreshold || !EnsureFullValidated())
return false;
SetConstants(r, g, b, a);
return RunFillFull(_constants.AsSpan(0, 4), target, width, height);
}
long area = (long)fillWidth * fillHeight;
if (!force && (pixels < FillPartialThreshold || area * 4L < pixels * 3L) || !EnsurePartialValidated())
return false;
SetConstants(r, g, b, a);
_constants[4] = x;
_constants[5] = y;
_constants[6] = x + fillWidth;
_constants[7] = y + fillHeight;
_resources[0] = new PixelShaderInput(target, width, height);
return RunFillPartial(_resources.AsSpan(0, 1), _constants.AsSpan(0, 8), target, width, height);
}
private bool EnsureFullValidated()
{
if (_fullValidated.HasValue)
return _fullValidated.Value;
const int width = 7;
const int height = 5;
var source = CreateProbe(width, height);
var cpu = (byte[])source.Clone();
var gpu = (byte[])source.Clone();
PixelBufferSoftwareProcessor.Fill(cpu, width, height, 23d, 197d, 89d, 173d, 0, 0, width, height);
SetConstants(23d, 197d, 89d, 173d);
_fullValidated = RunFillFull(_constants.AsSpan(0, 4), gpu, width, height) && Equal(cpu, gpu);
return _fullValidated.Value;
}
private bool EnsurePartialValidated()
{
if (_partialValidated.HasValue)
return _partialValidated.Value;
const int width = 7;
const int height = 5;
var source = CreateProbe(width, height);
var cpu = (byte[])source.Clone();
var gpu = (byte[])source.Clone();
PixelBufferSoftwareProcessor.Fill(cpu, width, height, 23d, 197d, 89d, 173d, 1, 2, 4, 2);
SetConstants(23d, 197d, 89d, 173d);
_constants[4] = 1f;
_constants[5] = 2f;
_constants[6] = 5f;
_constants[7] = 4f;
_resources[0] = new PixelShaderInput(gpu, width, height);
_partialValidated = RunFillPartial(_resources.AsSpan(0, 1), _constants.AsSpan(0, 8), gpu, width, height) && Equal(cpu, gpu);
return _partialValidated.Value;
}
private void SetConstants(double r, double g, double b, double a)
{
double aK = Math.Clamp(a, 0d, 255d) / 255d;
byte pb = (byte)Math.Clamp(b * aK, 0d, 255d);
byte pg = (byte)Math.Clamp(g * aK, 0d, 255d);
byte pr = (byte)Math.Clamp(r * aK, 0d, 255d);
byte pa = (byte)Math.Clamp(a, 0d, 255d);
_constants[0] = pr / 255f;
_constants[1] = pg / 255f;
_constants[2] = pb / 255f;
_constants[3] = pa / 255f;
}
private static bool AreFinite(double r, double g, double b, double a)
{
return double.IsFinite(r) && double.IsFinite(g) && double.IsFinite(b) && double.IsFinite(a);
}
private static byte[] CreateProbe(int width, int height)
{
var data = new byte[width * height * 4];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int index = (y * width + x) * 4;
byte a = (byte)((x * 31 + y * 47) & 255);
data[index] = a == 0 ? (byte)0 : (byte)((x * 17 + y * 29) % (a + 1));
data[index + 1] = a == 0 ? (byte)0 : (byte)((x * 43 + y * 11) % (a + 1));
data[index + 2] = a == 0 ? (byte)0 : (byte)((x * 7 + y * 53) % (a + 1));
data[index + 3] = a;
}
}
return data;
}
private partial bool RunFillFull(ReadOnlySpan<float> constants, byte[] target, int width, int height);
private partial bool RunFillPartial(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
}
}
+30
ファイルの表示
@@ -0,0 +1,30 @@
using LuaScript.Engine.Shader;
namespace LuaScript.Engine.Processing
{
internal sealed class GpuPixelBufferProcessor(PixelShaderRunner runner) : IPixelBufferProcessor
{
private readonly object _gate = new();
private readonly GpuFillOperation _fill = new(runner);
private readonly GpuConvolveOperation _convolve = new(runner);
private readonly GpuResizeOperation _resize = new(runner);
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
{
lock (_gate)
return _fill.TryFill(target, width, height, r, g, b, a, x, y, fillWidth, fillHeight, force);
}
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
{
lock (_gate)
return _convolve.TryConvolve(target, width, height, kernel, size, divisor, offset, force);
}
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
{
lock (_gate)
return _resize.TryResize(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target, force);
}
}
}
+47
ファイルの表示
@@ -0,0 +1,47 @@
using System;
using LuaScript.Engine.Shader;
namespace LuaScript.Engine.Processing
{
internal abstract class GpuPixelOperation(PixelShaderRunner runner)
{
protected const int MaxTextureSize = 16384;
protected bool Run(byte[] bytecode, ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height)
{
return runner.TryRunHardware(
bytecode,
resources,
constants,
PixelShaderBlend.Copy,
PixelShaderSampler.None,
target,
width,
height,
out _) == PixelShaderRunStatus.Success;
}
protected static bool IsTextureSupported(byte[] buffer, int width, int height)
{
return IsTextureSizeSupported(width, height) && (long)buffer.Length >= (long)width * height * 4;
}
protected static bool IsTextureSizeSupported(int width, int height)
{
return width > 0 && height > 0 && width <= MaxTextureSize && height <= MaxTextureSize;
}
protected static bool Equal(byte[] expected, byte[] actual)
{
return expected.AsSpan().SequenceEqual(actual);
}
protected static byte[] CopyProbe(byte[] source, int width, int height, int probeWidth, int probeHeight)
{
var data = new byte[probeWidth * probeHeight * 4];
for (int y = 0; y < probeHeight; y++)
Buffer.BlockCopy(source, y * width * 4, data, y * probeWidth * 4, probeWidth * 4);
return data;
}
}
}
+14
ファイルの表示
@@ -0,0 +1,14 @@
using System;
namespace LuaScript.Engine.Processing
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
internal sealed class GpuPixelOperationShaderAttribute(string methodName, string fileName, string entryPoint) : Attribute
{
public string MethodName { get; } = methodName;
public string FileName { get; } = fileName;
public string EntryPoint { get; } = entryPoint;
}
}
+82
ファイルの表示
@@ -0,0 +1,82 @@
using System;
using LuaScript.Engine.Shader;
namespace LuaScript.Engine.Processing
{
[GpuPixelOperationShader(nameof(RunResizeNearest), "Shaders/resize.hlsl", "resize_nearest")]
[GpuPixelOperationShader(nameof(RunResizeLinear), "Shaders/resize.hlsl", "resize_linear")]
internal sealed partial class GpuResizeOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
{
private const int ResizeThreshold = 262144;
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
private readonly float[] _constants = new float[4];
private byte[] _target = [];
private bool? _nearestValidated;
private bool? _linearValidated;
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
{
target = null;
if (!IsTextureSupported(source, sourceWidth, sourceHeight) || !IsTextureSizeSupported(targetWidth, targetHeight))
return false;
long pixels = (long)targetWidth * targetHeight;
if (!force && pixels < ResizeThreshold || !(linear ? EnsureLinearValidated(source, sourceWidth, sourceHeight) : EnsureNearestValidated(source, sourceWidth, sourceHeight)))
return false;
return RunShader(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target);
}
private bool EnsureNearestValidated(byte[] source, int sourceWidth, int sourceHeight)
{
if (_nearestValidated.HasValue)
return _nearestValidated.Value;
_nearestValidated = Validate(source, sourceWidth, sourceHeight, false);
return _nearestValidated.Value;
}
private bool EnsureLinearValidated(byte[] source, int sourceWidth, int sourceHeight)
{
if (_linearValidated.HasValue)
return _linearValidated.Value;
_linearValidated = Validate(source, sourceWidth, sourceHeight, true);
return _linearValidated.Value;
}
private bool Validate(byte[] source, int sourceWidth, int sourceHeight, bool linear)
{
int probeWidth = Math.Min(sourceWidth, 8);
int probeHeight = Math.Min(sourceHeight, 7);
int targetWidth = Math.Max(1, probeWidth * 2 - 3);
int targetHeight = Math.Max(1, probeHeight * 2 - 5);
var probe = CopyProbe(source, sourceWidth, sourceHeight, probeWidth, probeHeight);
byte[]? sourceScratch = null;
byte[]? targetScratch = null;
var cpu = PixelBufferSoftwareProcessor.Resize(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, ref sourceScratch, ref targetScratch);
return RunShader(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, out var gpu) && gpu is not null && Equal(cpu, gpu);
}
private bool RunShader(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
{
int count = checked(targetWidth * targetHeight * 4);
if (_target.Length != count)
_target = new byte[count];
_constants[0] = sourceWidth;
_constants[1] = sourceHeight;
_constants[2] = targetWidth;
_constants[3] = targetHeight;
_resources[0] = new PixelShaderInput(source, sourceWidth, sourceHeight);
target = _target;
return linear
? RunResizeLinear(_resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _target, targetWidth, targetHeight)
: RunResizeNearest(_resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _target, targetWidth, targetHeight);
}
private partial bool RunResizeNearest(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
private partial bool RunResizeLinear(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
}
}
+50
ファイルの表示
@@ -0,0 +1,50 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="LuaScript" />
<InternalsVisibleTo Include="LuaScript.Tests" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LuaScript.Runtime\LuaScript.Runtime.csproj" />
<ProjectReference Include="..\LuaScript.Generator\LuaScript.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<AdditionalFiles Include="Shaders\*.hlsl" />
</ItemGroup>
<ItemGroup>
<Reference Include="SharpGen.Runtime">
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.Direct3D11">
<HintPath>$(YMM4DirPath)Vortice.Direct3D11.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.DirectX">
<HintPath>$(YMM4DirPath)Vortice.DirectX.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.D3DCompiler.dll">
<HintPath>$(YMM4DirPath)Vortice.D3DCompiler.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.DXGI.dll">
<HintPath>$(YMM4DirPath)Vortice.DXGI.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.Mathematics">
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
<Private>false</Private>
</Reference>
</ItemGroup>
</Project>
+674
ファイルの表示
@@ -0,0 +1,674 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Vortice.D3DCompiler;
using Vortice.Direct3D;
using Vortice.Direct3D11;
using Vortice.DXGI;
using Vortice.Mathematics;
namespace LuaScript.Engine.Shader
{
internal sealed unsafe class PixelShaderRunner : IPixelShaderRunner, IDisposable
{
private const int MaxResources = 8;
private const int ConstantBufferSize = 4096;
private const int RandomSeed = 20260704;
private const string VertexShaderSource = """
struct VsOutput { float4 pos : SV_Position; float2 uv : TEXCOORD0; };
VsOutput vsmain(uint id : SV_VertexID)
{
VsOutput output;
float2 t = float2((id << 1) & 2, id & 2);
output.uv = t;
output.pos = float4(t.x * 2.0 - 1.0, 1.0 - t.y * 2.0, 0.0, 1.0);
return output;
}
""";
private static readonly FeatureLevel[] s_featureLevels = [FeatureLevel.Level_11_0];
private sealed record CompiledShader(ID3D11PixelShader? Shader, string? Error);
private struct InputSlot
{
public ID3D11Texture2D? Texture;
public ID3D11ShaderResourceView? View;
public int Width;
public int Height;
}
private readonly Lock _locker = new();
private readonly Dictionary<(string Hlsl, string Entry), CompiledShader> _shaders = [];
private readonly Dictionary<byte[], ID3D11PixelShader> _precompiled = new(ReferenceEqualityComparer.Instance);
private readonly InputSlot[] _inputs = new InputSlot[MaxResources];
private readonly ID3D11ShaderResourceView[] _boundViews = new ID3D11ShaderResourceView[MaxResources];
private readonly ID3D11ShaderResourceView[] _nullViews = new ID3D11ShaderResourceView[MaxResources];
private byte[] _compositeBuffer = [];
public IBufferCompositor Compositor { get; set; } = SoftwareCompositor.Instance;
public Action<string, Exception?>? Logger { get; set; }
private ID3D11Device? _device;
private ID3D11DeviceContext? _context;
private DriverType _driverType;
private ID3D11VertexShader? _vertexShader;
private ID3D11Buffer? _constantBuffer;
private ID3D11RasterizerState? _rasterizer;
private readonly ID3D11BlendState?[] _blendStates = new ID3D11BlendState?[4];
private readonly ID3D11SamplerState?[] _samplerStates = new ID3D11SamplerState?[6];
private ID3D11Texture2D? _randomTexture;
private ID3D11ShaderResourceView? _randomView;
private ID3D11Texture2D? _targetTexture;
private ID3D11RenderTargetView? _targetView;
private int _targetWidth;
private int _targetHeight;
private ID3D11Texture2D? _stagingTexture;
private int _stagingWidth;
private int _stagingHeight;
private bool _disposed;
private bool _unavailable;
private bool _hardwareUnavailable;
private bool _failureLogged;
private int _recreateBudget = 3;
public PixelShaderRunStatus TryRun(
string hlsl,
string entryPoint,
ReadOnlySpan<PixelShaderInput> resources,
ReadOnlySpan<float> constants,
PixelShaderBlend blend,
PixelShaderSampler sampler,
byte[] target,
int targetWidth,
int targetHeight,
out string? error)
{
error = null;
lock (_locker)
{
if (!CanRun(target, targetWidth, targetHeight))
return PixelShaderRunStatus.Unavailable;
try
{
if (!EnsureDevice())
return PixelShaderRunStatus.Unavailable;
var compiled = GetOrCompile(hlsl, entryPoint);
if (compiled.Shader is null)
{
error = compiled.Error;
return PixelShaderRunStatus.CompileError;
}
Execute(compiled.Shader, resources, constants, blend, sampler, target, targetWidth, targetHeight);
return PixelShaderRunStatus.Success;
}
catch (Exception ex)
{
HandleFailure(ex);
return PixelShaderRunStatus.Unavailable;
}
}
}
public PixelShaderRunStatus TryRunHardware(
byte[] bytecode,
ReadOnlySpan<PixelShaderInput> resources,
ReadOnlySpan<float> constants,
PixelShaderBlend blend,
PixelShaderSampler sampler,
byte[] target,
int targetWidth,
int targetHeight,
out string? error)
{
error = null;
lock (_locker)
{
if (!CanRun(target, targetWidth, targetHeight))
return PixelShaderRunStatus.Unavailable;
try
{
if (!EnsureHardwareDevice())
return PixelShaderRunStatus.Unavailable;
Execute(GetOrCreate(bytecode), resources, constants, blend, sampler, target, targetWidth, targetHeight);
return PixelShaderRunStatus.Success;
}
catch (Exception ex)
{
HandleFailure(ex);
return PixelShaderRunStatus.Unavailable;
}
}
}
private bool CanRun(byte[] target, int targetWidth, int targetHeight)
{
return !_disposed && !_unavailable &&
targetWidth > 0 && targetHeight > 0 &&
(long)target.Length >= (long)targetWidth * targetHeight * 4;
}
public void Invalidate()
{
lock (_locker)
{
ReleaseShaders();
}
}
public void Dispose()
{
lock (_locker)
{
if (_disposed)
return;
_disposed = true;
ReleaseDeviceObjects();
}
}
private bool EnsureDevice()
{
if (_device is not null)
return true;
if (_recreateBudget <= 0)
{
MarkUnavailable(null);
return false;
}
_recreateBudget--;
DriverType driverType;
if (TryCreateDevice(DriverType.Hardware, out var device, out var context))
{
driverType = DriverType.Hardware;
}
else if (TryCreateDevice(DriverType.Warp, out device, out context))
{
driverType = DriverType.Warp;
}
else
{
MarkUnavailable(null);
return false;
}
return InitializeDevice(device, context, driverType, true);
}
private bool EnsureHardwareDevice()
{
if (_device is not null)
return _driverType == DriverType.Hardware;
if (_hardwareUnavailable)
return false;
if (_recreateBudget <= 0)
{
_hardwareUnavailable = true;
return false;
}
_recreateBudget--;
if (!TryCreateDevice(DriverType.Hardware, out var device, out var context))
{
_hardwareUnavailable = true;
return false;
}
return InitializeDevice(device, context, DriverType.Hardware, false);
}
private bool InitializeDevice(ID3D11Device? device, ID3D11DeviceContext? context, DriverType driverType, bool markUnavailable)
{
try
{
var vsBytecode = CompileOrThrow(VertexShaderSource, "vsmain", "vs_4_0");
var vertexShader = device!.CreateVertexShader(vsBytecode);
_device = device;
_context = context;
_driverType = driverType;
_hardwareUnavailable = driverType != DriverType.Hardware && _hardwareUnavailable;
_vertexShader = vertexShader;
_constantBuffer = device.CreateBuffer(new BufferDescription(
ConstantBufferSize, BindFlags.ConstantBuffer, ResourceUsage.Dynamic, CpuAccessFlags.Write));
_rasterizer = device.CreateRasterizerState(RasterizerDescription.CullNone);
CreateBlendStates(device);
CreateSamplerStates(device);
return true;
}
catch (Exception ex)
{
if (ReferenceEquals(_device, device))
{
ReleaseDeviceObjects();
}
else
{
context?.Dispose();
device?.Dispose();
}
if (markUnavailable)
MarkUnavailable(ex);
else
_hardwareUnavailable = true;
return false;
}
}
private static bool TryCreateDevice(DriverType driverType, out ID3D11Device? device, out ID3D11DeviceContext? context)
{
device = null;
context = null;
try
{
var result = D3D11.D3D11CreateDevice(
null, driverType, DeviceCreationFlags.BgraSupport, s_featureLevels,
out device, out context);
if (result.Success && device is not null && context is not null)
return true;
}
catch
{
}
context?.Dispose();
device?.Dispose();
device = null;
context = null;
return false;
}
private void CreateBlendStates(ID3D11Device device)
{
_blendStates[(int)PixelShaderBlendMode.Copy] = null;
_blendStates[(int)PixelShaderBlendMode.Mask] = device.CreateBlendState(new BlendDescription(
Blend.Zero, Blend.One, Blend.Zero, Blend.SourceAlpha));
_blendStates[(int)PixelShaderBlendMode.Draw] = device.CreateBlendState(new BlendDescription(
Blend.One, Blend.InverseSourceAlpha, Blend.One, Blend.InverseSourceAlpha));
_blendStates[(int)PixelShaderBlendMode.Add] = device.CreateBlendState(new BlendDescription(
Blend.One, Blend.One, Blend.One, Blend.One));
}
private void CreateSamplerStates(ID3D11Device device)
{
_samplerStates[(int)PixelShaderSampler.None] = null;
_samplerStates[(int)PixelShaderSampler.Clip] = CreateSampler(device, Filter.MinMagMipLinear, TextureAddressMode.Border);
_samplerStates[(int)PixelShaderSampler.Clamp] = CreateSampler(device, Filter.MinMagMipLinear, TextureAddressMode.Clamp);
_samplerStates[(int)PixelShaderSampler.Loop] = CreateSampler(device, Filter.MinMagMipLinear, TextureAddressMode.Wrap);
_samplerStates[(int)PixelShaderSampler.Mirror] = CreateSampler(device, Filter.MinMagMipLinear, TextureAddressMode.Mirror);
_samplerStates[(int)PixelShaderSampler.Dot] = CreateSampler(device, Filter.MinMagMipPoint, TextureAddressMode.Border);
}
private static ID3D11SamplerState CreateSampler(ID3D11Device device, Filter filter, TextureAddressMode address)
{
var description = new SamplerDescription(filter, address, address, address)
{
BorderColor = new Color4(0f, 0f, 0f, 0f),
};
return device.CreateSamplerState(description);
}
private CompiledShader GetOrCompile(string hlsl, string entryPoint)
{
var key = (hlsl, entryPoint);
if (_shaders.TryGetValue(key, out var cached))
return cached;
CompiledShader compiled;
byte[] source = Encoding.UTF8.GetBytes(hlsl);
var result = Compiler.Compile(source, entryPoint, string.Empty, "ps_5_0", out var bytecode, out var errors);
if (result.Failure || bytecode is null)
{
compiled = new CompiledShader(null, errors?.AsString()?.Trim() ?? result.ToString());
errors?.Dispose();
bytecode?.Dispose();
}
else
{
try
{
compiled = new CompiledShader(_device!.CreatePixelShader(bytecode.AsSpan()), null);
}
finally
{
errors?.Dispose();
bytecode.Dispose();
}
}
_shaders[key] = compiled;
return compiled;
}
private ID3D11PixelShader GetOrCreate(byte[] bytecode)
{
if (_precompiled.TryGetValue(bytecode, out var cached))
return cached;
var shader = _device!.CreatePixelShader(bytecode);
_precompiled[bytecode] = shader;
return shader;
}
private static byte[] CompileOrThrow(string source, string entryPoint, string profile)
{
var result = Compiler.Compile(Encoding.UTF8.GetBytes(source), entryPoint, string.Empty, profile, out var bytecode, out var errors);
try
{
if (result.Failure || bytecode is null)
throw new InvalidOperationException(errors?.AsString() ?? result.ToString());
return bytecode.AsBytes();
}
finally
{
errors?.Dispose();
bytecode?.Dispose();
}
}
private void Execute(
ID3D11PixelShader shader,
ReadOnlySpan<PixelShaderInput> resources,
ReadOnlySpan<float> constants,
PixelShaderBlend blend,
PixelShaderSampler sampler,
byte[] target,
int width,
int height)
{
var context = _context!;
bool composite = blend.Mode == PixelShaderBlendMode.Composite;
EnsureTarget(width, height);
if (!composite && blend.Mode != PixelShaderBlendMode.Copy)
UploadPixels(_targetTexture!, target, width, height);
UploadConstants(constants);
BindResources(resources);
context.OMSetRenderTargets(_targetView!);
context.OMSetBlendState(composite ? null : _blendStates[(int)blend.Mode]);
context.RSSetViewport(0f, 0f, width, height);
context.RSSetState(_rasterizer);
context.IASetInputLayout(null);
context.IASetPrimitiveTopology(PrimitiveTopology.TriangleList);
context.VSSetShader(_vertexShader);
context.PSSetShader(shader);
context.PSSetConstantBuffer(0, _constantBuffer);
context.PSSetSampler(0, _samplerStates[(int)sampler]);
context.PSSetShaderResources(0, _boundViews);
context.Draw(3, 0);
context.PSSetShaderResources(0, _nullViews);
context.UnsetRenderTargets();
if (composite)
{
int length = width * height * 4;
if (_compositeBuffer.Length < length)
_compositeBuffer = new byte[length];
ReadBack(_compositeBuffer, width, height);
Compositor.TryCompose(target, width, height, _compositeBuffer, width, height,
new DrawCommand(width * 0.5, height * 0.5, 0d, 1d, 1d, 0d, null, 0d, blend.CompositeBlend));
}
else
{
ReadBack(target, width, height);
}
}
private void EnsureTarget(int width, int height)
{
if (_targetTexture is null || _targetWidth != width || _targetHeight != height)
{
_targetView?.Dispose();
_targetTexture?.Dispose();
_targetTexture = _device!.CreateTexture2D(new Texture2DDescription
{
Width = width,
Height = height,
MipLevels = 1,
ArraySize = 1,
Format = Format.B8G8R8A8_UNorm,
SampleDescription = new SampleDescription(1, 0),
Usage = ResourceUsage.Default,
BindFlags = BindFlags.RenderTarget,
});
_targetView = _device.CreateRenderTargetView(_targetTexture);
_targetWidth = width;
_targetHeight = height;
}
if (_stagingTexture is null || _stagingWidth != width || _stagingHeight != height)
{
_stagingTexture?.Dispose();
_stagingTexture = _device!.CreateTexture2D(new Texture2DDescription
{
Width = width,
Height = height,
MipLevels = 1,
ArraySize = 1,
Format = Format.B8G8R8A8_UNorm,
SampleDescription = new SampleDescription(1, 0),
Usage = ResourceUsage.Staging,
CPUAccessFlags = CpuAccessFlags.Read,
});
_stagingWidth = width;
_stagingHeight = height;
}
}
private void UploadPixels(ID3D11Texture2D texture, byte[] pixels, int width, int height)
{
fixed (byte* source = pixels)
_context!.UpdateSubresource(texture, 0, null, (nint)source, width * 4, 0);
}
private void UploadConstants(ReadOnlySpan<float> constants)
{
var mapped = _context!.Map(_constantBuffer!, MapMode.WriteDiscard);
try
{
var destination = new Span<float>((void*)mapped.DataPointer, ConstantBufferSize / sizeof(float));
constants.CopyTo(destination);
destination[constants.Length..].Clear();
}
finally
{
_context.Unmap(_constantBuffer!);
}
}
private void BindResources(ReadOnlySpan<PixelShaderInput> resources)
{
for (int i = 0; i < MaxResources; i++)
{
if (i >= resources.Length)
{
_boundViews[i] = null!;
continue;
}
var resource = resources[i];
if (resource.IsRandom)
{
_boundViews[i] = EnsureRandomView();
continue;
}
ref var slot = ref _inputs[i];
if (slot.Texture is null || slot.Width != resource.Width || slot.Height != resource.Height)
{
slot.View?.Dispose();
slot.Texture?.Dispose();
slot.Texture = _device!.CreateTexture2D(new Texture2DDescription
{
Width = resource.Width,
Height = resource.Height,
MipLevels = 1,
ArraySize = 1,
Format = Format.B8G8R8A8_UNorm,
SampleDescription = new SampleDescription(1, 0),
Usage = ResourceUsage.Default,
BindFlags = BindFlags.ShaderResource,
});
slot.View = _device.CreateShaderResourceView(slot.Texture);
slot.Width = resource.Width;
slot.Height = resource.Height;
}
UploadPixels(slot.Texture, resource.Data!, resource.Width, resource.Height);
_boundViews[i] = slot.View!;
}
}
private ID3D11ShaderResourceView EnsureRandomView()
{
if (_randomView is not null)
return _randomView;
int size = PixelShaderInput.RandomSize;
var values = new float[size * size];
var random = new Random(RandomSeed);
for (int i = 0; i < values.Length; i++)
values[i] = (float)random.NextDouble();
fixed (float* source = values)
{
_randomTexture = _device!.CreateTexture2D(new Texture2DDescription
{
Width = size,
Height = size,
MipLevels = 1,
ArraySize = 1,
Format = Format.R32_Float,
SampleDescription = new SampleDescription(1, 0),
Usage = ResourceUsage.Immutable,
BindFlags = BindFlags.ShaderResource,
}, [new SubresourceData((nint)source, size * sizeof(float))]);
}
_randomView = _device!.CreateShaderResourceView(_randomTexture);
return _randomView;
}
private void ReadBack(byte[] target, int width, int height)
{
var context = _context!;
context.CopyResource(_stagingTexture!, _targetTexture!);
var mapped = context.Map(_stagingTexture!, 0, MapMode.Read);
try
{
int rowBytes = width * 4;
byte* source = (byte*)mapped.DataPointer;
fixed (byte* destination = target)
{
if (mapped.RowPitch == rowBytes)
{
Buffer.MemoryCopy(source, destination, target.Length, (long)rowBytes * height);
}
else
{
for (int row = 0; row < height; row++)
Buffer.MemoryCopy(
source + (long)mapped.RowPitch * row,
destination + (long)rowBytes * row,
rowBytes, rowBytes);
}
}
}
finally
{
context.Unmap(_stagingTexture!, 0);
}
}
private void HandleFailure(Exception ex)
{
if (!_failureLogged)
{
_failureLogged = true;
WriteLog("LuaScript: obj.pixelshader execution failed; the call is skipped.", ex);
}
ReleaseDeviceObjects();
if (_recreateBudget <= 0)
_unavailable = true;
}
private void MarkUnavailable(Exception? ex)
{
_unavailable = true;
if (_failureLogged)
return;
_failureLogged = true;
if (ex is null)
WriteLog("LuaScript: Direct3D 11 is unavailable; obj.pixelshader is disabled.", null);
else
WriteLog("LuaScript: Direct3D 11 initialization failed; obj.pixelshader is disabled.", ex);
}
private void WriteLog(string message, Exception? exception) => Logger?.Invoke(message, exception);
private void ReleaseShaders()
{
foreach (var compiled in _shaders.Values)
compiled.Shader?.Dispose();
_shaders.Clear();
foreach (var shader in _precompiled.Values)
shader.Dispose();
_precompiled.Clear();
}
private void ReleaseDeviceObjects()
{
ReleaseShaders();
for (int i = 0; i < _inputs.Length; i++)
{
_inputs[i].View?.Dispose();
_inputs[i].Texture?.Dispose();
_inputs[i] = default;
_boundViews[i] = null!;
}
for (int i = 0; i < _blendStates.Length; i++)
{
_blendStates[i]?.Dispose();
_blendStates[i] = null;
}
for (int i = 0; i < _samplerStates.Length; i++)
{
_samplerStates[i]?.Dispose();
_samplerStates[i] = null;
}
_randomView?.Dispose();
_randomView = null;
_randomTexture?.Dispose();
_randomTexture = null;
_targetView?.Dispose();
_targetView = null;
_targetTexture?.Dispose();
_targetTexture = null;
_targetWidth = 0;
_targetHeight = 0;
_stagingTexture?.Dispose();
_stagingTexture = null;
_stagingWidth = 0;
_stagingHeight = 0;
_constantBuffer?.Dispose();
_constantBuffer = null;
_rasterizer?.Dispose();
_rasterizer = null;
_vertexShader?.Dispose();
_vertexShader = null;
_context?.Dispose();
_context = null;
_device?.Dispose();
_device = null;
}
}
}
+58
ファイルの表示
@@ -0,0 +1,58 @@
Texture2D source : register(t0);
cbuffer Parameters : register(b0)
{
float4 values[256];
};
float get_value(uint index)
{
uint row = index >> 2;
uint column = index & 3u;
float4 value = values[row];
if (column == 0u)
return value.x;
if (column == 1u)
return value.y;
if (column == 2u)
return value.z;
return value.w;
}
float convolve_channel(float value)
{
return floor(saturate(value) * 255.0) / 255.0;
}
float4 convolve(float4 pos : SV_Position) : SV_Target
{
uint2 p = (uint2)floor(pos.xy);
int width = (int)get_value(0u);
int height = (int)get_value(1u);
float divisor = get_value(2u);
float offset = get_value(3u) / 255.0;
int kernelSize = (int)get_value(4u);
int radius = (int)get_value(5u);
float4 sum = 0.0;
for (int ky = 0; ky < kernelSize; ky++)
{
int sy = clamp((int)p.y + ky - radius, 0, height - 1);
for (int kx = 0; kx < kernelSize; kx++)
{
int sx = clamp((int)p.x + kx - radius, 0, width - 1);
float kv = get_value((uint)(8 + ky * kernelSize + kx));
float4 sourceValue = source[uint2((uint)sx, (uint)sy)];
float3 rgb = sourceValue.a <= 0.0 ? 0.0 : saturate(sourceValue.rgb / sourceValue.a);
sum += float4(rgb, sourceValue.a) * kv;
}
}
float3 rgbOut = saturate(sum.rgb / divisor + offset);
float alpha = saturate(sum.a / divisor + offset);
return float4(
convolve_channel(rgbOut.r * alpha),
convolve_channel(rgbOut.g * alpha),
convolve_channel(rgbOut.b * alpha),
convolve_channel(alpha));
}
+21
ファイルの表示
@@ -0,0 +1,21 @@
Texture2D source : register(t0);
cbuffer Parameters : register(b0)
{
float4 color;
float4 rect;
};
float4 fill_full(float4 pos : SV_Position) : SV_Target
{
return color;
}
float4 fill_partial(float4 pos : SV_Position) : SV_Target
{
uint2 p = (uint2)floor(pos.xy);
uint4 r = (uint4)rect;
if (p.x >= r.x && p.y >= r.y && p.x < r.z && p.y < r.w)
return color;
return source[p];
}
+56
ファイルの表示
@@ -0,0 +1,56 @@
Texture2D source : register(t0);
cbuffer Parameters : register(b0)
{
float4 size;
};
float channel(float value)
{
return floor(saturate(value) * 255.0) / 255.0;
}
float4 resize_pack(float4 value)
{
return float4(channel(value.r), channel(value.g), channel(value.b), channel(value.a));
}
float4 resize_nearest(float4 pos : SV_Position) : SV_Target
{
uint2 p = (uint2)floor(pos.xy);
uint sourceWidth = (uint)size.x;
uint sourceHeight = (uint)size.y;
uint targetWidth = (uint)size.z;
uint targetHeight = (uint)size.w;
uint sx = min(((p.x * 2u + 1u) * sourceWidth) / (targetWidth * 2u), sourceWidth - 1u);
uint sy = min(((p.y * 2u + 1u) * sourceHeight) / (targetHeight * 2u), sourceHeight - 1u);
return source[uint2(sx, sy)];
}
float4 resize_linear(float4 pos : SV_Position) : SV_Target
{
uint2 p = (uint2)floor(pos.xy);
float sourceWidth = size.x;
float sourceHeight = size.y;
float targetWidth = size.z;
float targetHeight = size.w;
float u = (p.x + 0.5) * sourceWidth / targetWidth - 0.5;
float v = (p.y + 0.5) * sourceHeight / targetHeight - 0.5;
int x0 = (int)floor(u);
int y0 = (int)floor(v);
float tx = u - x0;
float ty = v - y0;
int maxX = (int)sourceWidth - 1;
int maxY = (int)sourceHeight - 1;
uint xA = (uint)clamp(x0, 0, maxX);
uint yA = (uint)clamp(y0, 0, maxY);
uint xB = (uint)clamp(x0 + 1, 0, maxX);
uint yB = (uint)clamp(y0 + 1, 0, maxY);
float4 c00 = source[uint2(xA, yA)];
float4 c10 = source[uint2(xB, yA)];
float4 c01 = source[uint2(xA, yB)];
float4 c11 = source[uint2(xB, yB)];
float4 top = c00 * (1.0 - tx) + c10 * tx;
float4 bottom = c01 * (1.0 - tx) + c11 * tx;
return resize_pack(top * (1.0 - ty) + bottom * ty);
}
+128 -6
ファイルの表示
@@ -6,7 +6,7 @@ namespace LuaScript.Engine.Kernel
internal sealed class KernelExtractor
{
private readonly List<KExpr> _bindings = [];
private readonly Dictionary<string, int> _scope = new(StringComparer.Ordinal);
private Dictionary<string, int> _scope = new(StringComparer.Ordinal);
private readonly SortedSet<KernelUniform> _uniforms = [];
private string _widthVariable = string.Empty;
@@ -46,25 +46,26 @@ namespace LuaScript.Engine.Kernel
if (index >= block.Count || block[index] is not NumericForStmt outer)
return null;
if (index + 1 != block.Count)
int tail = index + 1;
if (tail < block.Count && IsPutPixelData(block[tail]))
tail++;
if (tail != block.Count)
return null;
if (!TryAxis(outer, out string outerVar, out KAxis outerAxis))
return null;
_scope.Remove(outerVar);
if (outer.Body.Count != 1 || outer.Body[0] is not NumericForStmt inner)
return null;
if (!TryAxis(inner, out string innerVar, out KAxis innerAxis))
return null;
_scope.Remove(innerVar);
if (outerAxis == innerAxis)
return null;
if (_pixelDataVariable is not null &&
(string.Equals(outerVar, _pixelDataVariable, StringComparison.Ordinal) ||
string.Equals(innerVar, _pixelDataVariable, StringComparison.Ordinal)))
return null;
if (_scope.ContainsKey(outerVar))
_scope.Remove(outerVar);
if (_scope.ContainsKey(innerVar))
_scope.Remove(innerVar);
_widthVariable = outerAxis == KAxis.X ? outerVar : innerVar;
_heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar;
@@ -72,6 +73,13 @@ namespace LuaScript.Engine.Kernel
return _pixelDataVariable is null ? BuildKernel(inner.Body) : BuildPixelDataKernel(inner.Body);
}
private bool IsPutPixelData(LuaStmt statement) =>
_pixelDataVariable is not null &&
statement is CallStmt { Call: CallExpr { Arguments.Count: 1 } call } &&
IsObjectMethod(call, "putpixeldata") &&
call.Arguments[0] is NameExpr { } handle &&
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal);
private bool TryBindPixelData(LocalStmt local)
{
if (local.Names.Count != 1 || local.Values.Count != 1 ||
@@ -105,6 +113,9 @@ namespace LuaScript.Engine.Kernel
case AssignStmt assign:
BindAssign(assign);
break;
case IfStmt conditional:
LowerConditional(conditional);
break;
case CallStmt { Call: MethodCallExpr set } when IsPixelDataSet(set, out int writeChannel):
var value = ClampChannel(Lower(set.Arguments[1]));
if (writeChannel == 0) outR = value;
@@ -140,11 +151,25 @@ namespace LuaScript.Engine.Kernel
if (expression is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
KernelUniforms.TryResolveMember("obj", field, out var uniform))
return uniform == KernelUniform.Width;
if (expression is NameExpr { } alias &&
TryUniformAlias(alias.Name, out var aliased))
return aliased == KernelUniform.Width;
return _pixelDataVariable is not null &&
expression is MemberExpr { Target: NameExpr { } target, Name: "width" } &&
string.Equals(target.Name, _pixelDataVariable, StringComparison.Ordinal);
}
private bool TryUniformAlias(string name, out KernelUniform uniform)
{
if (_scope.TryGetValue(name, out int slot) && _bindings[slot] is KUniformRef reference)
{
uniform = reference.Uniform;
return true;
}
uniform = default;
return false;
}
private bool TryPixelDataChannel(LuaExpr expression, out int channel)
{
channel = 0;
@@ -221,6 +246,9 @@ namespace LuaScript.Engine.Kernel
case AssignStmt assign:
BindAssign(assign);
break;
case IfStmt conditional:
LowerConditional(conditional);
break;
default:
return null;
}
@@ -276,6 +304,76 @@ namespace LuaScript.Engine.Kernel
_scope[((NameExpr)assign.Targets[i]).Name] = AddBinding(lowered[i]);
}
private void LowerConditional(IfStmt statement) =>
LowerConditional(statement.Clauses, 0, statement.ElseBody);
private void LowerConditional(IReadOnlyList<IfClause> clauses, int index, IReadOnlyList<LuaStmt>? elseBody)
{
var clause = clauses[index];
var condition = LowerBool(clause.Condition);
var baseline = _scope;
_scope = new Dictionary<string, int>(baseline, StringComparer.Ordinal);
LowerBranchBody(clause.Body);
var taken = _scope;
_scope = new Dictionary<string, int>(baseline, StringComparer.Ordinal);
if (index + 1 < clauses.Count)
LowerConditional(clauses, index + 1, elseBody);
else if (elseBody is not null)
LowerBranchBody(elseBody);
var skipped = _scope;
var merged = new Dictionary<string, int>(baseline.Count, StringComparer.Ordinal);
foreach (var name in baseline.Keys)
{
int whenTrue = taken[name];
int whenFalse = skipped[name];
merged[name] = whenTrue == whenFalse
? whenTrue
: AddBinding(new KSelect(condition, new KLocalRef(whenTrue), new KLocalRef(whenFalse)));
}
_scope = merged;
}
private void LowerBranchBody(IReadOnlyList<LuaStmt> body)
{
Dictionary<string, int>? shadowed = null;
HashSet<string>? introduced = null;
foreach (var statement in body)
{
switch (statement)
{
case LocalStmt local:
foreach (var name in local.Names)
{
if (introduced?.Contains(name) == true || shadowed?.ContainsKey(name) == true)
continue;
if (_scope.TryGetValue(name, out int slot))
(shadowed ??= new(StringComparer.Ordinal))[name] = slot;
else
(introduced ??= new(StringComparer.Ordinal)).Add(name);
}
BindLocal(local);
break;
case AssignStmt assign:
BindAssign(assign);
break;
case IfStmt nested:
LowerConditional(nested);
break;
default:
throw new KernelUnsupportedException("Unsupported statement in a conditional branch.");
}
}
if (shadowed is not null)
foreach (var (name, slot) in shadowed)
_scope[name] = slot;
if (introduced is not null)
foreach (var name in introduced)
_scope.Remove(name);
}
private void EnsureNotCoordinateName(string name)
{
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
@@ -343,6 +441,16 @@ namespace LuaScript.Engine.Kernel
if (member.Target is NameExpr target && KernelUniforms.TryResolveMember(target.Name, member.Name, out var uniform))
return UseUniform(uniform);
if (_pixelDataVariable is not null &&
member.Target is NameExpr { } handle &&
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
{
if (string.Equals(member.Name, "width", StringComparison.Ordinal))
return UseUniform(KernelUniform.Width);
if (string.Equals(member.Name, "height", StringComparison.Ordinal))
return UseUniform(KernelUniform.Height);
}
throw new KernelUnsupportedException("Unsupported member access in pixel kernel.");
}
@@ -474,6 +582,20 @@ namespace LuaScript.Engine.Kernel
return true;
}
}
if (bound.Left is NameExpr { } alias && TryUniformAlias(alias.Name, out var aliased))
{
if (aliased == KernelUniform.Width)
{
axis = KAxis.X;
return true;
}
if (aliased == KernelUniform.Height)
{
axis = KAxis.Y;
return true;
}
}
return false;
}
+2 -2
ファイルの表示
@@ -1,9 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.13.4</Version>
<Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
</PropertyGroup>
+2 -2
ファイルの表示
@@ -1,9 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.13.4</Version>
<Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+36
ファイルの表示
@@ -9,6 +9,13 @@ namespace LuaScript.Anchor
public static int ClampCount(int count) => Math.Clamp(count, 0, MaxAnchors);
public static int NormalizeCount(string group, int count)
{
if (count <= 0 && string.Equals(group, TrackGroup, StringComparison.Ordinal))
return 1;
return ClampCount(count);
}
public static void ApplyOption(string option, ref AnchorConnection connection, ref bool is3D)
{
switch (option)
@@ -52,6 +59,35 @@ namespace LuaScript.Anchor
z = 0d;
}
public static ImmutableList<LuaAnchorPoint> SetPosition(
ImmutableList<LuaAnchorPoint> source, string group, int index, double x, double y, double z)
{
for (int i = 0; i < source.Count; i++)
{
var a = source[i];
if (a.Index == index && string.Equals(a.Group, group, StringComparison.Ordinal))
{
return source.SetItem(i, new LuaAnchorPoint
{
Group = group,
Index = index,
X = x,
Y = y,
Z = z,
});
}
}
return source.Add(new LuaAnchorPoint
{
Group = group,
Index = index,
X = x,
Y = y,
Z = z,
});
}
public static ImmutableList<LuaAnchorPoint> ApplyDrag(
ImmutableList<LuaAnchorPoint> source, string group, int index, double dx, double dy, double dz)
{
+1
ファイルの表示
@@ -60,6 +60,7 @@ namespace LuaScript.Api
}
var candidates = Keywords
.Concat(LuaScript.Compat.Syntax.LuaSyntaxRuleRegistry.CatalogKeywords)
.Concat(globals)
.Concat(tableMembers.Keys)
.Concat(tableMembers.Values.SelectMany(x => x))
+257 -1
ファイルの表示
@@ -1,4 +1,5 @@
using LuaScript.Anchor;
using LuaScript.Compat;
namespace LuaScript
{
@@ -71,6 +72,12 @@ namespace LuaScript
public Func<ISceneObjectResolver>? ResolverProvider { get; set; }
public Func<string, double, (byte[] Buffer, int Width, int Height)>? SceneImageLoader { get; set; }
public Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] Buffer, int Width, int Height)>? BrushImageLoader { get; set; }
public Func<string, string, int, (int Count, int Rate, double[] Data)>? AudioLoader { get; set; }
private readonly Dictionary<string, string> _stringParameters = new(StringComparer.Ordinal);
public IReadOnlyDictionary<string, string> StringParameters => _stringParameters;
@@ -155,11 +162,71 @@ namespace LuaScript
_buffers["t"] = temp;
}
Compositor.TryCompose(temp.Data, temp.Width, temp.Height, src, ImageWidth, ImageHeight, command);
Compositor.TryCompose(temp.Data, temp.Width, temp.Height, src, ImageWidth, ImageHeight, command with { Blend = 0d });
}
private readonly Dictionary<string, (byte[] Data, int Width, int Height)> _buffers = new(StringComparer.Ordinal);
internal IPixelShaderRunner? ShaderRunner { get; set; }
internal IPixelBufferProcessor? PixelProcessor { get; set; }
internal AviUtlPixelShaderLibrary PixelShaders { get; set; } = AviUtlPixelShaderLibrary.Empty;
internal bool TryGetShaderResource(string id, out byte[] data, out int width, out int height) =>
TryReadBuffer(id, out data, out width, out height);
internal bool TryGetShaderTarget(string id, out byte[] data, out int width, out int height)
{
data = [];
width = 0;
height = 0;
switch (BufferKind(id, out string key))
{
case 'o':
EnsurePixelBuffer();
if (_pixelBuffer is null)
return false;
data = _pixelBuffer;
width = ImageWidth;
height = ImageHeight;
return true;
case 't':
case 'c':
if (!_buffers.TryGetValue(key, out var stored))
{
int w = Math.Max(1, ImageWidth);
int h = Math.Max(1, ImageHeight);
stored = (new byte[w * h * 4], w, h);
_buffers[key] = stored;
}
data = stored.Data;
width = stored.Width;
height = stored.Height;
return true;
case 'f':
GetFrameBuffer(out data, out width, out height);
return true;
default:
return false;
}
}
internal bool NotifyShaderTargetWritten(string id)
{
switch (BufferKind(id, out _))
{
case 'o':
MarkPixelsDirty();
return false;
case 'f':
ReplaceBuffer(_frameBuffer, _frameBufferWidth, _frameBufferHeight);
return true;
default:
return false;
}
}
internal bool CopyBuffer(string dst, string src)
{
if (!TryReadBuffer(src, out var data, out int w, out int h))
@@ -192,11 +259,47 @@ namespace LuaScript
return true;
}
return false;
case 'f':
GetFrameBuffer(out data, out width, out height);
return true;
default:
return false;
}
}
private byte[] _frameBuffer = [];
private int _frameBufferWidth;
private int _frameBufferHeight;
private bool _frameBufferValid;
internal void ResetFrameBuffer() => _frameBufferValid = false;
private void GetFrameBuffer(out byte[] data, out int width, out int height)
{
int w = Math.Max(1, SceneWidth);
int h = Math.Max(1, SceneHeight);
int length = w * h * 4;
if (_frameBuffer.Length < length)
{
_frameBuffer = new byte[length];
_frameBufferValid = false;
}
if (!_frameBufferValid || _frameBufferWidth != w || _frameBufferHeight != h)
{
Array.Clear(_frameBuffer, 0, length);
_frameBufferWidth = w;
_frameBufferHeight = h;
EnsurePixelBuffer();
if (_pixelBuffer is not null && !ReferenceEquals(_pixelBuffer, _frameBuffer))
Compositor.TryCompose(_frameBuffer, w, h, _pixelBuffer, ImageWidth, ImageHeight,
new DrawCommand(w * 0.5 + X, h * 0.5 + Y, 0d, Zoom, Alpha / 255d, Aspect, null, 1d, 0d));
_frameBufferValid = true;
}
data = _frameBuffer;
width = w;
height = h;
}
private bool TryWriteBuffer(string id, byte[] data, int width, int height)
{
int n = width * height * 4;
@@ -403,5 +506,158 @@ namespace LuaScript
p[3] = (byte)Math.Clamp(a, 0d, 255d);
}
}
private double[]? _convolveSource;
private byte[]? _resizeSource;
private byte[]? _resizeBuffer;
public unsafe void FillBuffer(double r, double g, double b, double a, int x, int y, int w, int h, bool force = false)
{
EnsurePixelBuffer();
if (_pixelBuffer is null)
return;
int cw = ImageWidth;
int ch = ImageHeight;
int x0 = Math.Clamp(x, 0, cw);
int y0 = Math.Clamp(y, 0, ch);
int x1 = Math.Clamp(x + w, 0, cw);
int y1 = Math.Clamp(y + h, 0, ch);
if (x1 <= x0 || y1 <= y0)
return;
if (PixelProcessor?.TryFill(_pixelBuffer, cw, ch, r, g, b, a, x0, y0, x1 - x0, y1 - y0, force) == true)
{
_isPixelsDirty = true;
return;
}
_isPixelsDirty = true;
PixelBufferSoftwareProcessor.Fill(_pixelBuffer, cw, ch, r, g, b, a, x0, y0, x1 - x0, y1 - y0);
}
public unsafe void ReadRegion(int x, int y, int w, int h, double[] destination)
{
EnsurePixelBuffer();
int cw = ImageWidth;
int ch = ImageHeight;
if (_pixelBuffer is null)
{
Array.Clear(destination, 0, w * h * 4);
return;
}
fixed (byte* buf = _pixelBuffer)
{
for (int j = 0; j < h; j++)
{
int sy = y + j;
for (int i = 0; i < w; i++)
{
int sx = x + i;
int di = (j * w + i) * 4;
if ((uint)sx >= (uint)cw || (uint)sy >= (uint)ch)
{
destination[di] = 0d;
destination[di + 1] = 0d;
destination[di + 2] = 0d;
destination[di + 3] = 0d;
continue;
}
byte* p = buf + (sy * cw + sx) * 4;
double a = p[3];
if (a <= 0d)
{
destination[di] = 0d;
destination[di + 1] = 0d;
destination[di + 2] = 0d;
destination[di + 3] = 0d;
}
else
{
double s = 255d / a;
destination[di] = Math.Clamp(p[2] * s, 0d, 255d);
destination[di + 1] = Math.Clamp(p[1] * s, 0d, 255d);
destination[di + 2] = Math.Clamp(p[0] * s, 0d, 255d);
destination[di + 3] = a;
}
}
}
}
}
public unsafe void WriteRegion(int x, int y, int w, int h, double[] source)
{
EnsurePixelBuffer();
if (_pixelBuffer is null)
return;
int cw = ImageWidth;
int ch = ImageHeight;
_isPixelsDirty = true;
fixed (byte* buf = _pixelBuffer)
{
for (int j = 0; j < h; j++)
{
int dy = y + j;
if ((uint)dy >= (uint)ch)
continue;
for (int i = 0; i < w; i++)
{
int dx = x + i;
if ((uint)dx >= (uint)cw)
continue;
int si = (j * w + i) * 4;
double a = Math.Clamp(source[si + 3], 0d, 255d);
double aK = a / 255d;
byte* p = buf + (dy * cw + dx) * 4;
p[0] = (byte)Math.Clamp(source[si + 2] * aK, 0d, 255d);
p[1] = (byte)Math.Clamp(source[si + 1] * aK, 0d, 255d);
p[2] = (byte)Math.Clamp(source[si] * aK, 0d, 255d);
p[3] = (byte)a;
}
}
}
}
public unsafe void Convolve(double[] kernel, int size, double divisor, double offset, bool force = false)
{
EnsurePixelBuffer();
if (_pixelBuffer is null)
return;
int cw = ImageWidth;
int ch = ImageHeight;
if (PixelProcessor?.TryConvolve(_pixelBuffer, cw, ch, kernel, size, divisor, offset, force) == true)
{
_isPixelsDirty = true;
return;
}
_isPixelsDirty = true;
PixelBufferSoftwareProcessor.Convolve(_pixelBuffer, cw, ch, kernel, size, divisor, offset, ref _convolveSource);
}
public unsafe void Resize(int newWidth, int newHeight, bool linear, bool force = false)
{
EnsurePixelBuffer();
if (_pixelBuffer is null)
return;
newWidth = Math.Max(1, newWidth);
newHeight = Math.Max(1, newHeight);
int cw = ImageWidth;
int ch = ImageHeight;
if (PixelProcessor?.TryResize(_pixelBuffer, cw, ch, newWidth, newHeight, linear, out var processed, force) == true && processed is not null)
{
ReplaceBuffer(processed, newWidth, newHeight);
return;
}
var dst = PixelBufferSoftwareProcessor.Resize(_pixelBuffer, cw, ch, newWidth, newHeight, linear, ref _resizeSource, ref _resizeBuffer);
ReplaceBuffer(dst, newWidth, newHeight);
}
}
}
+11
ファイルの表示
@@ -0,0 +1,11 @@
namespace LuaScript
{
internal interface IPixelBufferProcessor
{
bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false);
bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false);
bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false);
}
}
+460 -13
ファイルの表示
@@ -37,6 +37,17 @@ namespace LuaScript.Engine
private readonly Dictionary<string, byte[]> _stringNameBytes = new(StringComparer.Ordinal);
private byte[] _stringValueBytes = new byte[256];
private byte[] _sceneValueBytes = new byte[256];
private byte[] _objectMetaBytes = new byte[256];
private static readonly byte[] s_shaderTransparentPixel = new byte[4];
private readonly PixelShaderInput[] _shaderInputs = new PixelShaderInput[NativeProtocol.ShaderResourcesMax];
private readonly byte[]?[] _shaderResourceData = new byte[NativeProtocol.ShaderResourcesMax][];
private readonly float[] _shaderConstants = new float[NativeProtocol.ShaderConstantsMax];
private byte[] _shaderTarget = [];
private byte[] _pixelProcessTarget = [];
private double[] _pixelProcessKernel = [];
private long PixelRegionCapacity => _allocatedSize - _pixelOffset - NativeProtocol.ShaderRegionBytes;
public LuaJitWorker(string nativeDir, string scriptPath)
{
@@ -63,11 +74,16 @@ namespace LuaScript.Engine
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
Func<string, (byte[] buffer, int w, int h)> loadImage,
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
Func<string, double, (byte[] buffer, int w, int h)> loadScene,
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush,
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
Action<DrawCommand> addDraw,
Action<string, int, bool, int, double[]> setAnchor,
Func<string, SceneValue> sceneGetValue,
Action<string, SceneValue> sceneSetValue,
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio,
PixelShaderInvoke? runPixelShader,
IPixelBufferProcessor? pixelProcessor,
out bool pixelsDirty,
out bool bufferReplaced,
out int resultWidth,
@@ -111,16 +127,18 @@ namespace LuaScript.Engine
view.Write(NativeProtocol.OffScriptVersion, _scriptVersion);
view.Write(NativeProtocol.OffPixelsDirty, 0);
view.Write(NativeProtocol.OffErrorLen, 0);
view.Write(NativeProtocol.OffCallbackFound, pixelProcessor is null ? -1 : 1);
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdRun);
_workEvent!.Set();
var stopwatch = Stopwatch.StartNew();
long budget = timeoutMs;
int status;
while (true)
{
long remaining = timeoutMs - stopwatch.ElapsedMilliseconds;
long remaining = budget - stopwatch.ElapsedMilliseconds;
if (remaining <= 0 || !_doneEvent!.WaitOne((int)remaining))
{
KillWorker();
@@ -132,6 +150,7 @@ namespace LuaScript.Engine
if (status != NativeProtocol.StatusCallback)
break;
long callbackStart = stopwatch.ElapsedMilliseconds;
int callbackKind = view.ReadInt32(NativeProtocol.OffCallbackKind);
if (callbackKind == NativeProtocol.CbKindRequestPixels)
{
@@ -151,8 +170,9 @@ namespace LuaScript.Engine
}
else
{
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, setAnchor, sceneGetValue, sceneSetValue);
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, loadScene, loadBrush, addEffect, setAnchor, sceneGetValue, sceneSetValue, loadAudio, runPixelShader, pixelProcessor);
}
budget += stopwatch.ElapsedMilliseconds - callbackStart;
_workEvent.Set();
}
@@ -177,7 +197,7 @@ namespace LuaScript.Engine
bufferReplaced = resultWidth != width || resultHeight != height;
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
if (pixelsDirty && (long)resultWidth * resultHeight * 4 > _allocatedSize - _pixelOffset)
if (pixelsDirty && (long)resultWidth * resultHeight * 4 > PixelRegionCapacity)
{
error = "native worker reported a pixel buffer beyond capacity";
return false;
@@ -196,7 +216,39 @@ namespace LuaScript.Engine
try
{
long offset = _view.PointerOffset + _pixelOffset;
access((nint)(ptr + offset), (long)handle.ByteLength - offset);
access((nint)(ptr + offset), PixelRegionCapacity);
}
finally
{
handle.ReleasePointer();
}
}
private unsafe void ReadRegion(long offset, byte[] destination, int length)
{
var handle = _view!.SafeMemoryMappedViewHandle;
byte* ptr = null;
handle.AcquirePointer(ref ptr);
try
{
fixed (byte* dst = destination)
Buffer.MemoryCopy(ptr + _view.PointerOffset + offset, dst, destination.Length, length);
}
finally
{
handle.ReleasePointer();
}
}
private unsafe void WriteRegion(long offset, byte[] source, int length)
{
var handle = _view!.SafeMemoryMappedViewHandle;
byte* ptr = null;
handle.AcquirePointer(ref ptr);
try
{
fixed (byte* src = source)
Buffer.MemoryCopy(src, ptr + _view.PointerOffset + offset, (ulong)handle.ByteLength - (ulong)(_view.PointerOffset + offset), (ulong)length);
}
finally
{
@@ -280,10 +332,15 @@ namespace LuaScript.Engine
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
Func<string, (byte[] buffer, int w, int h)> loadImage,
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
Func<string, double, (byte[] buffer, int w, int h)> loadScene,
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush,
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
Action<string, int, bool, int, double[]> setAnchor,
Func<string, SceneValue> sceneGetValue,
Action<string, SceneValue> sceneSetValue)
Action<string, SceneValue> sceneSetValue,
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio,
PixelShaderInvoke? runPixelShader,
IPixelBufferProcessor? pixelProcessor)
{
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
switch (kind)
@@ -303,6 +360,15 @@ namespace LuaScript.Engine
case NativeProtocol.CbKindLoadMovie:
ResolveLoadMovieCallback(view, loadMovie);
break;
case NativeProtocol.CbKindLoadScene:
ResolveLoadSceneCallback(view, loadScene);
break;
case NativeProtocol.CbKindLoadBrush:
ResolveLoadBrushCallback(view, loadBrush);
break;
case NativeProtocol.CbKindBrush:
ResolveBrushCallback(view, loadBrush);
break;
case NativeProtocol.CbKindEffect:
ResolveEffectCallback(view, addEffect);
break;
@@ -315,9 +381,237 @@ namespace LuaScript.Engine
case NativeProtocol.CbKindSceneSet:
ResolveSceneSetCallback(view, sceneSetValue);
break;
case NativeProtocol.CbKindGetAudio:
ResolveGetAudioCallback(view, loadAudio);
break;
case NativeProtocol.CbKindPixelShaderStage:
ResolveShaderStageCallback(view);
break;
case NativeProtocol.CbKindPixelShaderRun:
ResolveShaderRunCallback(view, runPixelShader);
break;
case NativeProtocol.CbKindPixelProcess:
ResolvePixelProcessCallback(view, pixelProcessor);
break;
}
}
private void ResolvePixelProcessCallback(MemoryMappedViewAccessor view, IPixelBufferProcessor? pixelProcessor)
{
bool processed = false;
if (pixelProcessor is not null)
{
int width = view.ReadInt32(NativeProtocol.OffWidth);
int height = view.ReadInt32(NativeProtocol.OffHeight);
long length = (long)width * height * 4;
if (width > 0 && height > 0 && length <= PixelRegionCapacity && length <= int.MaxValue)
{
int pixelLength = (int)length;
if (_pixelProcessTarget.Length < pixelLength)
_pixelProcessTarget = new byte[pixelLength];
int operation = (int)view.ReadDouble(NativeProtocol.CallbackResultOffset);
bool force = view.ReadDouble(NativeProtocol.CallbackResultOffset + 9 * 8) != 0d;
processed = operation switch
{
NativeProtocol.PixelProcessFill => TryProcessFill(view, pixelProcessor, width, height, pixelLength, force),
NativeProtocol.PixelProcessConvolve => TryProcessConvolve(view, pixelProcessor, width, height, pixelLength, force),
NativeProtocol.PixelProcessResize => TryProcessResize(view, pixelProcessor, pixelLength, force),
_ => false,
};
}
}
view.Write(NativeProtocol.OffCallbackFound, processed ? 1 : pixelProcessor is null ? -1 : 0);
}
private bool TryProcessFill(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int width, int height, int pixelLength, bool force)
{
long offset = NativeProtocol.CallbackResultOffset;
double r = view.ReadDouble(offset + 1 * 8);
double g = view.ReadDouble(offset + 2 * 8);
double b = view.ReadDouble(offset + 3 * 8);
double a = view.ReadDouble(offset + 4 * 8);
int x = (int)view.ReadDouble(offset + 5 * 8);
int y = (int)view.ReadDouble(offset + 6 * 8);
int fillWidth = (int)view.ReadDouble(offset + 7 * 8);
int fillHeight = (int)view.ReadDouble(offset + 8 * 8);
if (x != 0 || y != 0 || fillWidth != width || fillHeight != height)
ReadRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
if (!pixelProcessor.TryFill(_pixelProcessTarget, width, height, r, g, b, a, x, y, fillWidth, fillHeight, force))
return false;
WriteRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
return true;
}
private bool TryProcessConvolve(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int width, int height, int pixelLength, bool force)
{
long offset = NativeProtocol.CallbackResultOffset;
int size = (int)view.ReadDouble(offset + 1 * 8);
double divisor = view.ReadDouble(offset + 2 * 8);
double kernelOffset = view.ReadDouble(offset + 3 * 8);
if (size < 1 || (size & 1) == 0)
return false;
int taps = size * size;
if (taps <= 0 || taps * 8 > Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax))
return false;
if (_pixelProcessKernel.Length < taps)
_pixelProcessKernel = new double[taps];
ReadRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
view.ReadArray(NativeProtocol.CallbackTagOffset, _pixelProcessKernel, 0, taps);
if (!pixelProcessor.TryConvolve(_pixelProcessTarget, width, height, _pixelProcessKernel, size, divisor, kernelOffset, force))
return false;
WriteRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
return true;
}
private bool TryProcessResize(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int sourceLength, bool force)
{
long offset = NativeProtocol.CallbackResultOffset;
int targetWidth = (int)view.ReadDouble(offset + 1 * 8);
int targetHeight = (int)view.ReadDouble(offset + 2 * 8);
bool linear = view.ReadDouble(offset + 3 * 8) != 0d;
long length = (long)targetWidth * targetHeight * 4;
int sourceWidth = view.ReadInt32(NativeProtocol.OffWidth);
int sourceHeight = view.ReadInt32(NativeProtocol.OffHeight);
if (targetWidth <= 0 || targetHeight <= 0 || length > PixelRegionCapacity || length > int.MaxValue)
return false;
ReadRegion(_pixelOffset, _pixelProcessTarget, sourceLength);
if (!pixelProcessor.TryResize(_pixelProcessTarget, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out var target, force) || target is null)
return false;
WriteRegion(_pixelOffset, target, (int)length);
view.Write(NativeProtocol.OffWidth, targetWidth);
view.Write(NativeProtocol.OffHeight, targetHeight);
return true;
}
private void ResolveShaderStageCallback(MemoryMappedViewAccessor view)
{
long meta = NativeProtocol.ShaderMetaOffset(_allocatedSize);
int width = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageWidth * 8);
int height = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageHeight * 8);
int slot = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageKind * 8);
if ((uint)slot >= NativeProtocol.ShaderResourcesMax ||
!TryStageShaderInput(slot, width, height, NativeProtocol.ShaderImageOffset(_allocatedSize)))
{
view.Write(NativeProtocol.OffCallbackFound, 0);
return;
}
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private bool TryStageShaderInput(int slot, int width, int height, long sourceOffset)
{
long length = (long)width * height * 4;
if (width <= 0 || height <= 0 || length > NativeProtocol.MaxPixelBufferSize)
return false;
ref byte[]? data = ref _shaderResourceData[slot];
if (data is null || data.Length < length)
data = new byte[length];
ReadRegion(sourceOffset, data, (int)length);
_shaderInputs[slot] = new PixelShaderInput(data, width, height);
return true;
}
private void ResolveShaderRunCallback(MemoryMappedViewAccessor view, PixelShaderInvoke? runPixelShader)
{
long meta = NativeProtocol.ShaderMetaOffset(_allocatedSize);
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string name = ResolveTag(tagLen);
int resourceCount = Math.Clamp((int)view.ReadDouble(meta + NativeProtocol.ShaderMetaResourceCount * 8), 0, NativeProtocol.ShaderResourcesMax);
int blendMode = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaBlendMode * 8);
double compositeBlend = view.ReadDouble(meta + NativeProtocol.ShaderMetaCompositeBlend * 8);
int samplerValue = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaSampler * 8);
int constantCount = Math.Clamp((int)view.ReadDouble(meta + NativeProtocol.ShaderMetaConstantCount * 8), 0, NativeProtocol.ShaderConstantsMax);
int targetWidth = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageWidth * 8);
int targetHeight = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageHeight * 8);
int targetKind = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageKind * 8);
for (int i = 0; i < resourceCount; i++)
{
int kind = (int)view.ReadDouble(meta + (NativeProtocol.ShaderMetaResourceKinds + i) * 8);
switch (kind)
{
case NativeProtocol.ShaderResourceStaged:
break;
case NativeProtocol.ShaderResourceRandom:
_shaderInputs[i] = PixelShaderInput.Random;
break;
case NativeProtocol.ShaderResourceObject:
if (!TryStageShaderInput(i, view.ReadInt32(NativeProtocol.OffWidth), view.ReadInt32(NativeProtocol.OffHeight), _pixelOffset))
_shaderInputs[i] = new PixelShaderInput(s_shaderTransparentPixel, 1, 1);
break;
default:
_shaderInputs[i] = new PixelShaderInput(s_shaderTransparentPixel, 1, 1);
break;
}
}
if (constantCount > 0)
view.ReadArray(NativeProtocol.ShaderConstantsOffset(_allocatedSize), _shaderConstants, 0, constantCount);
var status = PixelShaderRunStatus.Unavailable;
string? error = null;
long targetLength = (long)targetWidth * targetHeight * 4;
if (runPixelShader is not null &&
targetWidth > 0 && targetHeight > 0 &&
targetLength <= NativeProtocol.MaxPixelBufferSize &&
(targetKind != NativeProtocol.ShaderTargetObject || targetLength <= PixelRegionCapacity))
{
int length = (int)targetLength;
if (_shaderTarget.Length < length)
_shaderTarget = new byte[length];
long targetOffset = targetKind == NativeProtocol.ShaderTargetObject
? _pixelOffset
: NativeProtocol.ShaderImageOffset(_allocatedSize);
ReadRegion(targetOffset, _shaderTarget, length);
var blend = blendMode switch
{
(int)PixelShaderBlendMode.Mask => PixelShaderBlend.Mask,
(int)PixelShaderBlendMode.Draw => PixelShaderBlend.Draw,
(int)PixelShaderBlendMode.Add => PixelShaderBlend.Add,
(int)PixelShaderBlendMode.Composite => PixelShaderBlend.Composite(compositeBlend),
_ => PixelShaderBlend.Copy,
};
var sampler = (uint)samplerValue <= (uint)PixelShaderSampler.Dot
? (PixelShaderSampler)samplerValue
: PixelShaderSampler.None;
try
{
status = runPixelShader(
name,
_shaderInputs.AsSpan(0, resourceCount),
_shaderConstants.AsSpan(0, constantCount),
blend, sampler,
_shaderTarget, targetWidth, targetHeight,
out error);
}
catch
{
status = PixelShaderRunStatus.Unavailable;
}
if (status == PixelShaderRunStatus.Success)
WriteRegion(targetOffset, _shaderTarget, length);
}
if (status == PixelShaderRunStatus.CompileError)
{
var bytes = Encoding.UTF8.GetBytes(error ?? "obj.pixelshader: compile error");
int errorLength = Math.Min(bytes.Length, NativeProtocol.CallbackTagMax);
view.WriteArray(NativeProtocol.CallbackTagOffset, bytes, 0, errorLength);
view.Write(NativeProtocol.OffCallbackTagLen, errorLength);
}
view.Write(meta + NativeProtocol.ShaderMetaStatus * 8, (double)status);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveSceneGetCallback(MemoryMappedViewAccessor view, Func<string, SceneValue> getValue)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
@@ -382,6 +676,40 @@ namespace LuaScript.Engine
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private static readonly double[] s_noAudioData = [];
private void ResolveGetAudioCallback(
MemoryMappedViewAccessor view,
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
int separator = Array.IndexOf(_callbackTag, (byte)0, 0, tagLen);
string file = Encoding.UTF8.GetString(_callbackTag, 0, separator >= 0 ? separator : tagLen);
string type = separator >= 0
? Encoding.UTF8.GetString(_callbackTag, separator + 1, tagLen - separator - 1)
: "pcm";
int size = (int)view.ReadDouble(NativeProtocol.CallbackResultOffset);
int count = 0;
int rate = 0;
double[] data = s_noAudioData;
try { (count, rate, data) = loadAudio(file, type, size); }
catch
{
count = 0;
rate = 0;
data = s_noAudioData;
}
count = Math.Clamp(count, 0, Math.Min(data.Length, NativeProtocol.CallbackTagMax / 8));
if (count > 0)
view.WriteArray(NativeProtocol.CallbackTagOffset, data, 0, count);
view.Write(NativeProtocol.CallbackResultOffset, (double)count);
view.Write(NativeProtocol.CallbackResultOffset + 8, (double)rate);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveSetAnchorCallback(MemoryMappedViewAccessor view, Action<string, int, bool, int, double[]> setAnchor)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
@@ -469,6 +797,9 @@ namespace LuaScript.Engine
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(result + NativeProtocol.CbVolume * 8, value.Volume);
view.Write(result + NativeProtocol.CbLength * 8, (double)value.Length);
WriteObjectMeta(view, value.Character, value.Text, value.Kind);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
else
@@ -477,6 +808,27 @@ namespace LuaScript.Engine
}
}
private void WriteObjectMeta(MemoryMappedViewAccessor view, string character, string text, string kind)
{
character ??= string.Empty;
text ??= string.Empty;
kind ??= string.Empty;
int maxBytes = Encoding.UTF8.GetMaxByteCount(character.Length + text.Length + kind.Length) + 2;
if (_objectMetaBytes.Length < maxBytes)
_objectMetaBytes = new byte[Math.Max(maxBytes, _objectMetaBytes.Length * 2)];
int length = Encoding.UTF8.GetBytes(character, 0, character.Length, _objectMetaBytes, 0);
_objectMetaBytes[length++] = 0;
length += Encoding.UTF8.GetBytes(text, 0, text.Length, _objectMetaBytes, length);
_objectMetaBytes[length++] = 0;
length += Encoding.UTF8.GetBytes(kind, 0, kind.Length, _objectMetaBytes, length);
if (length > NativeProtocol.CallbackTagMax)
length = NativeProtocol.CallbackTagMax;
view.WriteArray(NativeProtocol.CallbackTagOffset, _objectMetaBytes, 0, length);
view.Write(NativeProtocol.OffCallbackTagLen, length);
}
private void ResolveLoadFigureCallback(
MemoryMappedViewAccessor view,
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure)
@@ -496,7 +848,7 @@ namespace LuaScript.Engine
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - _pixelOffset;
long capacity = PixelRegionCapacity;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
@@ -531,7 +883,7 @@ namespace LuaScript.Engine
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - _pixelOffset;
long capacity = PixelRegionCapacity;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
@@ -557,7 +909,7 @@ namespace LuaScript.Engine
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - _pixelOffset;
long capacity = PixelRegionCapacity;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
@@ -584,7 +936,7 @@ namespace LuaScript.Engine
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - _pixelOffset;
long capacity = PixelRegionCapacity;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
@@ -597,16 +949,100 @@ namespace LuaScript.Engine
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveEffectCallback(MemoryMappedViewAccessor view, Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect)
private void ResolveLoadSceneCallback(
MemoryMappedViewAccessor view,
Func<string, double, (byte[] buffer, int w, int h)> loadScene)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string name = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
double time = view.ReadDouble(NativeProtocol.CallbackResultOffset);
(byte[] buffer, int w, int h) result;
try { result = loadScene(name, time); }
catch { result = ([], 0, 0); }
long pixelSize = (long)result.w * result.h * 4;
if (result.w <= 0 || result.h <= 0 || pixelSize > PixelRegionCapacity)
{
view.Write(NativeProtocol.OffLoadResultWidth, 0);
view.Write(NativeProtocol.OffLoadResultHeight, 0);
view.Write(NativeProtocol.OffCallbackFound, 0);
return;
}
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
WritePixelRegion(result.buffer, (int)pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private static readonly KeyValuePair<string, object>[] s_noBrushArguments = [];
private void ResolveLoadBrushCallback(
MemoryMappedViewAccessor view,
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string name = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
WriteBrushResult(view, loadBrush, name, s_noBrushArguments);
}
private void ResolveBrushCallback(
MemoryMappedViewAccessor view,
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
var segments = Encoding.UTF8.GetString(_callbackTag, 0, tagLen).Split('\0');
if (segments.Length == 0)
{
view.Write(NativeProtocol.OffLoadResultWidth, 0);
view.Write(NativeProtocol.OffLoadResultHeight, 0);
view.Write(NativeProtocol.OffCallbackFound, 0);
return;
}
WriteBrushResult(view, loadBrush, segments[0], ParseNamedArguments(segments));
}
private void WriteBrushResult(
MemoryMappedViewAccessor view,
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush,
string name,
IReadOnlyList<KeyValuePair<string, object>> arguments)
{
long rOff = NativeProtocol.CallbackResultOffset;
double width = view.ReadDouble(rOff + 0 * 8);
double height = view.ReadDouble(rOff + 1 * 8);
(byte[] buffer, int w, int h) result;
try { result = loadBrush(name, width, height, arguments); }
catch { result = ([], 0, 0); }
long pixelSize = (long)result.w * result.h * 4;
if (result.w <= 0 || result.h <= 0 || pixelSize > PixelRegionCapacity)
{
view.Write(NativeProtocol.OffLoadResultWidth, 0);
view.Write(NativeProtocol.OffLoadResultHeight, 0);
view.Write(NativeProtocol.OffCallbackFound, 0);
return;
}
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
WritePixelRegion(result.buffer, (int)pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private static IReadOnlyList<KeyValuePair<string, object>> ParseNamedArguments(string[] segments)
{
if (segments.Length < 3)
return s_noBrushArguments;
string effectName = segments[0];
var arguments = new List<KeyValuePair<string, object>>();
for (int i = 1; i + 1 < segments.Length; i += 2)
{
@@ -623,8 +1059,19 @@ namespace LuaScript.Engine
value = raw;
arguments.Add(new KeyValuePair<string, object>(key, value));
}
return arguments;
}
try { addEffect(effectName, arguments); }
private void ResolveEffectCallback(MemoryMappedViewAccessor view, Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
var segments = Encoding.UTF8.GetString(_callbackTag, 0, tagLen).Split('\0');
if (segments.Length == 0)
return;
try { addEffect(segments[0], ParseNamedArguments(segments)); }
catch { }
view.Write(NativeProtocol.OffCallbackFound, 1);
}
@@ -643,7 +1090,7 @@ namespace LuaScript.Engine
private void EnsureWorker(int width, int height, int stringCapacity)
{
long required = NativeProtocol.PixelOffset(stringCapacity) + (long)width * height * 4;
long required = NativeProtocol.PixelOffset(stringCapacity) + (long)width * height * 4 + NativeProtocol.ShaderRegionBytes;
if (_alive && _process is { HasExited: false } && _stringParamsCapacity == stringCapacity && required <= _allocatedSize)
return;
+408 -14
ファイルの表示
@@ -181,9 +181,17 @@ namespace LuaScript
script.AttachDebugger(_debugger);
_globalRegistrar = new AviUtlGlobalRegistrar(CurrentTimeRatio);
_globalRegistrar.RegisterLuaMembers(script.Globals);
RegisterFastPrimitives(script);
_script = script;
}
private void RegisterFastPrimitives(Script script)
{
script.Globals.Set("__fast_fill", DynValue.NewCallback((_, args) => FillCore(args, true)));
script.Globals.Set("__fast_convolve", DynValue.NewCallback((_, args) => ConvolveCore(args, true)));
script.Globals.Set("__fast_resize", DynValue.NewCallback((_, args) => ResizeCore(args, true)));
}
private void EnsureScriptIntegrity()
{
if (_script is null) return;
@@ -548,6 +556,18 @@ namespace LuaScript
args[1].String,
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
break;
case "scene" when args.Count > 1 && args[1].Type == DataType.String:
LoadScene(
args[1].String,
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
break;
case "brush" when args.Count > 1 && args[1].Type == DataType.String:
LoadBrush(
args[1].String,
args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d,
args.Count > 3 ? args[3].CastToNumber() ?? 0d : 0d,
s_noNamedArguments);
break;
}
return DynValue.Void;
}
@@ -632,6 +652,135 @@ namespace LuaScript
return DynValue.Void;
}
[LuaFunction("pixelshader")]
private DynValue PixelShader(CallbackArguments args)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 2 ||
args[0].Type != DataType.String || args[1].Type != DataType.String)
return DynValue.Void;
var ctx = _activeContext;
var runner = ctx.ShaderRunner;
if (runner is null)
return DynValue.Void;
string name = args[0].String;
if (!ctx.PixelShaders.TryGet(name, out string hlsl))
throw new ScriptRuntimeException($"obj.pixelshader: shader '{name}' is not defined in this script.");
int resourceCount = CollectShaderResources(ctx, args.Count > 2 ? args[2] : DynValue.Nil);
int constantCount = CollectShaderConstants(args.Count > 3 ? args[3] : DynValue.Nil);
var blend = ParseShaderBlend(args.Count > 4 ? args[4] : DynValue.Nil);
var sampler = ParseShaderSampler(args.Count > 5 ? args[5] : DynValue.Nil);
string target = args[1].String;
if (!ctx.TryGetShaderTarget(target, out byte[] targetData, out int targetWidth, out int targetHeight))
return DynValue.Void;
var status = runner.TryRun(
hlsl,
AviUtlPixelShaderLibrary.EntryPointOf(name),
_shaderResources.AsSpan(0, resourceCount),
_shaderConstants.AsSpan(0, constantCount),
blend, sampler,
targetData, targetWidth, targetHeight,
out string? error);
if (status == PixelShaderRunStatus.CompileError)
throw new ScriptRuntimeException($"obj.pixelshader: shader '{name}' failed to compile.\n{error}");
if (status == PixelShaderRunStatus.Success && ctx.NotifyShaderTargetWritten(target))
RefreshObjDimensions();
return DynValue.Void;
}
private const int MaxShaderResources = 8;
private const int MaxShaderConstants = 1024;
private static readonly byte[] s_transparentPixel = new byte[4];
private readonly PixelShaderInput[] _shaderResources = new PixelShaderInput[MaxShaderResources];
private readonly float[] _shaderConstants = new float[MaxShaderConstants];
private static PixelShaderInput TransparentShaderResource => new(s_transparentPixel, 1, 1);
private int CollectShaderResources(AviUtlScriptContext ctx, DynValue value)
{
if (value.Type == DataType.String)
{
_shaderResources[0] = ResolveShaderResource(ctx, value.String);
return 1;
}
if (value.Type != DataType.Table)
return 0;
var table = value.Table;
int count = table.Length;
if (count > MaxShaderResources)
throw new ScriptRuntimeException($"obj.pixelshader: too many resources ({count}). Up to {MaxShaderResources} are supported.");
for (int i = 0; i < count; i++)
{
var entry = table.Get(i + 1);
_shaderResources[i] = entry.Type == DataType.String
? ResolveShaderResource(ctx, entry.String)
: TransparentShaderResource;
}
return count;
}
private static PixelShaderInput ResolveShaderResource(AviUtlScriptContext ctx, string id)
{
if (string.Equals(id, "random", StringComparison.Ordinal))
return PixelShaderInput.Random;
if (ctx.TryGetShaderResource(id, out var data, out int width, out int height))
return new PixelShaderInput(data, width, height);
return TransparentShaderResource;
}
private int CollectShaderConstants(DynValue value)
{
if (value.Type != DataType.Table)
return 0;
var table = value.Table;
int count = table.Length;
if (count > MaxShaderConstants)
throw new ScriptRuntimeException($"obj.pixelshader: too many constants ({count}). Up to {MaxShaderConstants} are supported.");
for (int i = 0; i < count; i++)
_shaderConstants[i] = (float)(table.Get(i + 1).CastToNumber() ?? 0d);
return count;
}
private static PixelShaderBlend ParseShaderBlend(DynValue value)
{
if (value.Type == DataType.Number)
return PixelShaderBlend.Composite(value.Number);
if (value.Type != DataType.String)
return PixelShaderBlend.Copy;
return value.String switch
{
"copy" => PixelShaderBlend.Copy,
"mask" => PixelShaderBlend.Mask,
"draw" => PixelShaderBlend.Draw,
"add" => PixelShaderBlend.Add,
_ => throw new ScriptRuntimeException($"obj.pixelshader: unknown blend '{value.String}'. Use copy, mask, draw, add or a blend number."),
};
}
private static PixelShaderSampler ParseShaderSampler(DynValue value)
{
if (value.Type != DataType.String)
return PixelShaderSampler.None;
return value.String switch
{
"clip" => PixelShaderSampler.Clip,
"clamp" => PixelShaderSampler.Clamp,
"loop" => PixelShaderSampler.Loop,
"mirror" => PixelShaderSampler.Mirror,
"dot" => PixelShaderSampler.Dot,
_ => throw new ScriptRuntimeException($"obj.pixelshader: unknown sampler '{value.String}'. Use clip, clamp, loop, mirror or dot."),
};
}
[LuaFunction("getvalue")]
private DynValue GetValue(CallbackArguments args)
{
@@ -642,6 +791,47 @@ namespace LuaScript
return value.Type == DataType.Number ? value : DynValue.NewNumber(0d);
}
private static readonly double[] s_noAudioData = [];
[LuaFunction("getaudio")]
private DynValue GetAudio(CallbackArguments args)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || _script is null || args.Count < 2 || args[1].Type != DataType.String)
return DynValue.NewTuple(DynValue.NewNumber(0d), DynValue.NewNumber(0d));
string file = args[1].String;
string type = args.Count > 2 && args[2].Type == DataType.String ? args[2].String : "pcm";
int size = args.Count > 3 ? (int)(args[3].CastToNumber() ?? 0d) : 0;
int count = 0;
int rate = 0;
double[] data = s_noAudioData;
var loader = _activeContext.AudioLoader;
if (loader is not null)
(count, rate, data) = loader(file, type, size);
if (count > data.Length)
count = data.Length;
var bufArg = args[0];
Table? table = bufArg.Type == DataType.Table ? bufArg.Table : null;
bool created = false;
if (table is null && bufArg.IsNil())
{
table = new Table(_script);
created = true;
}
if (table is not null)
{
for (int i = 0; i < count; i++)
table.Set(i + 1, DynValue.NewNumber(data[i]));
}
return created
? DynValue.NewTuple(DynValue.NewNumber(count), DynValue.NewNumber(rate), DynValue.NewTable(table!))
: DynValue.NewTuple(DynValue.NewNumber(count), DynValue.NewNumber(rate));
}
[LuaFunction("setoption")]
private DynValue SetOption(CallbackArguments args)
{
@@ -699,9 +889,7 @@ namespace LuaScript
return DynValue.NewNumber(0d);
var anchorName = args[0].String;
int count = AnchorSupport.ClampCount((int)(args[1].CastToNumber() ?? 0d));
if (string.Equals(anchorName, AnchorSupport.TrackGroup, StringComparison.Ordinal))
return DynValue.NewNumber(0d);
int count = AnchorSupport.NormalizeCount(anchorName, (int)(args[1].CastToNumber() ?? 0d));
var connection = AnchorConnection.None;
bool is3D = false;
@@ -735,9 +923,19 @@ namespace LuaScript
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Void;
string name = args[0].String;
_activeContext.AddEffect(new AviUtlEffectRequest(args[0].String, CollectNamedArguments(args, 1)));
return DynValue.Void;
}
private static readonly KeyValuePair<string, object>[] s_noNamedArguments = [];
private static IReadOnlyList<KeyValuePair<string, object>> CollectNamedArguments(CallbackArguments args, int start)
{
if (start + 1 >= args.Count)
return s_noNamedArguments;
var arguments = new List<KeyValuePair<string, object>>();
for (int i = 1; i + 1 < args.Count; i += 2)
for (int i = start; i + 1 < args.Count; i += 2)
{
if (args[i].Type != DataType.String)
continue;
@@ -751,8 +949,27 @@ namespace LuaScript
};
arguments.Add(new KeyValuePair<string, object>(args[i].String, boxed));
}
return arguments;
}
_activeContext.AddEffect(new AviUtlEffectRequest(name, arguments));
[LuaFunction("brush")]
private DynValue Brush(CallbackArguments args)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Void;
int start = 1;
double width = 0d;
double height = 0d;
if (args.Count > 2 && args[1].Type == DataType.Number && args[2].Type == DataType.Number)
{
width = args[1].Number;
height = args[2].Number;
start = 3;
}
LoadBrush(args[0].String, width, height, CollectNamedArguments(args, start));
return DynValue.Void;
}
@@ -778,6 +995,150 @@ namespace LuaScript
};
}
private double[] _regionScratch = [];
private double[] _kernelScratch = [];
private static readonly DynValue[] s_byteNumbers = CreateByteNumbers();
private static DynValue[] CreateByteNumbers()
{
var values = new DynValue[256];
for (int i = 0; i < values.Length; i++)
values[i] = DynValue.NewNumber(i).AsReadOnly();
return values;
}
private static DynValue ChannelValue(double value)
{
int b = (int)value;
return b == value && (uint)b < 256u ? s_byteNumbers[b] : DynValue.NewNumber(value);
}
[LuaFunction("fill")]
private DynValue Fill(CallbackArguments args) => FillCore(args, false);
private DynValue FillCore(CallbackArguments args, bool force)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null)
return DynValue.Void;
var ctx = _activeContext;
double r = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
double g = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
double b = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
double a = args.Count > 3 ? args[3].CastToNumber() ?? 255d : 255d;
int x = args.Count > 4 ? (int)(args[4].CastToNumber() ?? 0d) : 0;
int y = args.Count > 5 ? (int)(args[5].CastToNumber() ?? 0d) : 0;
int w = args.Count > 6 ? (int)(args[6].CastToNumber() ?? 0d) : ctx.ImageWidth;
int h = args.Count > 7 ? (int)(args[7].CastToNumber() ?? 0d) : ctx.ImageHeight;
ctx.FillBuffer(r, g, b, a, x, y, w, h, force);
return DynValue.Void;
}
[LuaFunction("getpixelregion")]
private DynValue GetPixelRegion(CallbackArguments args)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || _script is null || args.Count < 4)
return DynValue.Nil;
int x = (int)(args[0].CastToNumber() ?? 0d);
int y = (int)(args[1].CastToNumber() ?? 0d);
int w = (int)(args[2].CastToNumber() ?? 0d);
int h = (int)(args[3].CastToNumber() ?? 0d);
var table = new Table(_script);
if (w <= 0 || h <= 0)
return DynValue.NewTable(table);
int count = w * h * 4;
if (_regionScratch.Length < count)
_regionScratch = new double[count];
_activeContext.ReadRegion(x, y, w, h, _regionScratch);
for (int i = 0; i < count; i++)
table.Set(i + 1, ChannelValue(_regionScratch[i]));
return DynValue.NewTable(table);
}
[LuaFunction("putpixelregion")]
private DynValue PutPixelRegion(CallbackArguments args)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 5 || args[4].Type != DataType.Table)
return DynValue.Void;
int x = (int)(args[0].CastToNumber() ?? 0d);
int y = (int)(args[1].CastToNumber() ?? 0d);
int w = (int)(args[2].CastToNumber() ?? 0d);
int h = (int)(args[3].CastToNumber() ?? 0d);
if (w <= 0 || h <= 0)
return DynValue.Void;
int count = w * h * 4;
if (_regionScratch.Length < count)
_regionScratch = new double[count];
var table = args[4].Table;
for (int i = 0; i < count; i++)
_regionScratch[i] = table.Get(i + 1).CastToNumber() ?? 0d;
_activeContext.WriteRegion(x, y, w, h, _regionScratch);
return DynValue.Void;
}
[LuaFunction("convolve")]
private DynValue Convolve(CallbackArguments args) => ConvolveCore(args, false);
private DynValue ConvolveCore(CallbackArguments args, bool force)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 2 || args[0].Type != DataType.Table)
return DynValue.Void;
int size = (int)(args[1].CastToNumber() ?? 0d);
if (size < 1 || (size & 1) == 0)
return DynValue.Void;
int taps = size * size;
var kernel = args[0].Table;
if (_kernelScratch.Length < taps)
_kernelScratch = new double[taps];
double sum = 0d;
for (int i = 0; i < taps; i++)
{
double v = kernel.Get(i + 1).CastToNumber() ?? 0d;
_kernelScratch[i] = v;
sum += v;
}
double divisor = args.Count > 2 ? args[2].CastToNumber() ?? sum : sum;
if (divisor == 0d)
divisor = 1d;
double offset = args.Count > 3 ? args[3].CastToNumber() ?? 0d : 0d;
_activeContext.Convolve(_kernelScratch, size, divisor, offset, force);
return DynValue.Void;
}
[LuaFunction("resize")]
private DynValue Resize(CallbackArguments args) => ResizeCore(args, false);
private DynValue ResizeCore(CallbackArguments args, bool force)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 2)
return DynValue.Void;
int w = (int)(args[0].CastToNumber() ?? 0d);
int h = (int)(args[1].CastToNumber() ?? 0d);
if (w <= 0 || h <= 0)
return DynValue.Void;
bool linear = !(args.Count > 2 && args[2].Type == DataType.String && args[2].String == "nearest");
_activeContext.Resize(w, h, linear, force);
RefreshObjDimensions();
return DynValue.Void;
}
private double CurrentAntialias() =>
_options.TryGetValue("antialias", out var value) && value.Type == DataType.Number
? value.Number
@@ -820,6 +1181,34 @@ namespace LuaScript
RefreshObjDimensions();
}
private void LoadScene(string name, double time)
{
var ctx = _activeContext!;
var loader = ctx.SceneImageLoader;
if (loader is null)
return;
var (buffer, w, h) = loader(name, time);
if (w <= 0 || h <= 0)
return;
ctx.ReplaceBuffer(buffer, w, h);
RefreshObjDimensions();
}
private void LoadBrush(string name, double width, double height, IReadOnlyList<KeyValuePair<string, object>> arguments)
{
var ctx = _activeContext!;
var loader = ctx.BrushImageLoader;
if (loader is null)
return;
double w = width > 0d ? width : ctx.ImageWidth;
double h = height > 0d ? height : ctx.ImageHeight;
var (buffer, bw, bh) = loader(name, w, h, arguments);
if (bw <= 0 || bh <= 0)
return;
ctx.ReplaceBuffer(buffer, bw, bh);
RefreshObjDimensions();
}
private void LoadMovie(string path, double time)
{
_mediaLoader ??= _mediaLoaderFactory();
@@ -833,14 +1222,14 @@ namespace LuaScript
int w = _activeContext!.ImageWidth;
int h = _activeContext.ImageHeight;
var obj = _objScope.Table;
obj["w"] = w;
obj["h"] = h;
obj["hw"] = w / 2d;
obj["hh"] = h / 2d;
obj["cx"] = w / 2d;
obj["cy"] = h / 2d;
obj["cz"] = 0d;
obj["diagonal"] = Math.Sqrt((double)w * w + (double)h * h);
obj.Set("w", DynValue.NewNumber(w));
obj.Set("h", DynValue.NewNumber(h));
obj.Set("hw", DynValue.NewNumber(w / 2d));
obj.Set("hh", DynValue.NewNumber(h / 2d));
obj.Set("cx", DynValue.NewNumber(w / 2d));
obj.Set("cy", DynValue.NewNumber(h / 2d));
obj.Set("cz", DynValue.NewNumber(0d));
obj.Set("diagonal", DynValue.NewNumber(Math.Sqrt((double)w * w + (double)h * h)));
}
private static DynValue BuildObjectTable(Script script, SceneObjectInfo info)
@@ -862,6 +1251,11 @@ namespace LuaScript
["rzr"] = info.Rz * Math.PI / 180d,
["alpha"] = info.Alpha,
["layer"] = info.Layer,
["volume"] = info.Volume,
["length"] = info.Length,
["character"] = info.Character ?? string.Empty,
["text"] = info.Text ?? string.Empty,
["kind"] = info.Kind ?? string.Empty,
};
return DynValue.NewTable(table);
}
+49 -2
ファイルの表示
@@ -43,7 +43,7 @@ namespace LuaScript.Engine
public const int CallbackTagOffset = ErrorOffset + ErrorMax;
public const int CallbackTagMax = 8192;
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
public const int CallbackResultCount = 8;
public const int CallbackResultCount = 10;
public const int StringParamsOffset = CallbackResultOffset + CallbackResultCount * 8;
public const int MinStringParamsCapacity = 64 * 1024;
@@ -61,6 +61,17 @@ namespace LuaScript.Engine
public const int CbKindFlushDraws = 10;
public const int CbKindSceneGet = 11;
public const int CbKindSceneSet = 12;
public const int CbKindPixelShaderStage = 13;
public const int CbKindPixelShaderRun = 14;
public const int CbKindLoadScene = 15;
public const int CbKindLoadBrush = 16;
public const int CbKindBrush = 17;
public const int CbKindGetAudio = 18;
public const int CbKindPixelProcess = 19;
public const int PixelProcessFill = 0;
public const int PixelProcessConvolve = 1;
public const int PixelProcessResize = 2;
public const int DrawRingCapacity = 4096;
public const int DrawEntryDoubles = 24;
@@ -75,6 +86,8 @@ namespace LuaScript.Engine
public const int CbRz = 5;
public const int CbAlpha = 6;
public const int CbLayer = 7;
public const int CbVolume = 8;
public const int CbLength = 9;
public static long DrawRingOffset(int stringCapacity) => StringParamsOffset + stringCapacity;
@@ -153,7 +166,41 @@ namespace LuaScript.Engine
public const int MaxPixelBufferSize = 3840 * 2160 * 4;
public const int ShaderMetaDoubles = 20;
public const int ShaderConstantsMax = 1024;
public const int ShaderResourcesMax = 8;
public const int ShaderMetaResourceCount = 0;
public const int ShaderMetaBlendMode = 1;
public const int ShaderMetaCompositeBlend = 2;
public const int ShaderMetaSampler = 3;
public const int ShaderMetaConstantCount = 4;
public const int ShaderMetaImageWidth = 5;
public const int ShaderMetaImageHeight = 6;
public const int ShaderMetaImageKind = 7;
public const int ShaderMetaStatus = 8;
public const int ShaderMetaResourceKinds = 9;
public const int ShaderResourceStaged = 0;
public const int ShaderResourceRandom = 1;
public const int ShaderResourceTransparent = 2;
public const int ShaderResourceObject = 3;
public const int ShaderTargetExchange = 0;
public const int ShaderTargetObject = 1;
public const long ShaderRegionBytes = ShaderMetaDoubles * 8 + ShaderConstantsMax * 4 + MaxPixelBufferSize;
public static long ShaderMetaOffset(long bufferSize) => bufferSize - ShaderRegionBytes;
public static long ShaderConstantsOffset(long bufferSize) => ShaderMetaOffset(bufferSize) + ShaderMetaDoubles * 8;
public static long ShaderImageOffset(long bufferSize) => ShaderConstantsOffset(bufferSize) + ShaderConstantsMax * 4;
public static long BufferSize(int width, int height, int stringCapacity) =>
PixelOffset(stringCapacity) + Math.Max((long)width * height * 4, MaxPixelBufferSize);
PixelOffset(stringCapacity) + PixelRegionSize(width, height) + ShaderRegionBytes;
public static long PixelRegionSize(int width, int height) =>
(Math.Max((long)width * height * 4, MaxPixelBufferSize) + 7) & ~7L;
}
}
+166
ファイルの表示
@@ -0,0 +1,166 @@
using System;
namespace LuaScript
{
internal static unsafe class PixelBufferSoftwareProcessor
{
public static void Fill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
{
double aK = Math.Clamp(a, 0d, 255d) / 255d;
byte pb = (byte)Math.Clamp(b * aK, 0d, 255d);
byte pg = (byte)Math.Clamp(g * aK, 0d, 255d);
byte pr = (byte)Math.Clamp(r * aK, 0d, 255d);
byte pa = (byte)Math.Clamp(a, 0d, 255d);
int x1 = x + fillWidth;
int y1 = y + fillHeight;
fixed (byte* buf = target)
{
for (int py = y; py < y1; py++)
{
byte* p = buf + (py * width + x) * 4;
for (int px = x; px < x1; px++)
{
p[0] = pb;
p[1] = pg;
p[2] = pr;
p[3] = pa;
p += 4;
}
}
}
}
public static void Convolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, ref double[]? sourceScratch)
{
int count = width * height * 4;
if (sourceScratch is null || sourceScratch.Length < count)
sourceScratch = new double[count];
var src = sourceScratch;
fixed (byte* buf = target)
{
for (int pi = 0; pi < width * height; pi++)
{
byte* p = buf + pi * 4;
int di = pi * 4;
double a = p[3];
src[di + 3] = a;
if (a <= 0d)
{
src[di] = 0d;
src[di + 1] = 0d;
src[di + 2] = 0d;
}
else
{
double s = 255d / a;
src[di] = Math.Clamp(p[2] * s, 0d, 255d);
src[di + 1] = Math.Clamp(p[1] * s, 0d, 255d);
src[di + 2] = Math.Clamp(p[0] * s, 0d, 255d);
}
}
}
int half = size / 2;
fixed (byte* buf = target)
{
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
double sr = 0d, sg = 0d, sb = 0d, sa = 0d;
for (int ky = 0; ky < size; ky++)
{
int sy = Math.Clamp(y + ky - half, 0, height - 1);
for (int kx = 0; kx < size; kx++)
{
int sx = Math.Clamp(x + kx - half, 0, width - 1);
double kv = kernel[ky * size + kx];
int si = (sy * width + sx) * 4;
sr += src[si] * kv;
sg += src[si + 1] * kv;
sb += src[si + 2] * kv;
sa += src[si + 3] * kv;
}
}
double rr = Math.Clamp(sr / divisor + offset, 0d, 255d);
double gg = Math.Clamp(sg / divisor + offset, 0d, 255d);
double bb = Math.Clamp(sb / divisor + offset, 0d, 255d);
double aa = Math.Clamp(sa / divisor + offset, 0d, 255d);
double aK = aa / 255d;
byte* p = buf + (y * width + x) * 4;
p[0] = (byte)Math.Clamp(bb * aK, 0d, 255d);
p[1] = (byte)Math.Clamp(gg * aK, 0d, 255d);
p[2] = (byte)Math.Clamp(rr * aK, 0d, 255d);
p[3] = (byte)aa;
}
}
}
}
public static byte[] Resize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, ref byte[]? sourceScratch, ref byte[]? targetScratch)
{
int srcCount = sourceWidth * sourceHeight * 4;
if (sourceScratch is null || sourceScratch.Length < srcCount)
sourceScratch = new byte[srcCount];
Buffer.BlockCopy(source, 0, sourceScratch, 0, srcCount);
int dstCount = targetWidth * targetHeight * 4;
if (targetScratch is null || targetScratch.Length != dstCount)
targetScratch = new byte[dstCount];
var src = sourceScratch;
var dst = targetScratch;
fixed (byte* s = src)
fixed (byte* d = dst)
{
for (int y = 0; y < targetHeight; y++)
{
for (int x = 0; x < targetWidth; x++)
{
byte* o = d + (y * targetWidth + x) * 4;
if (!linear)
{
int sx = Math.Clamp((int)((x + 0.5) * sourceWidth / targetWidth), 0, sourceWidth - 1);
int sy = Math.Clamp((int)((y + 0.5) * sourceHeight / targetHeight), 0, sourceHeight - 1);
byte* p = s + (sy * sourceWidth + sx) * 4;
o[0] = p[0];
o[1] = p[1];
o[2] = p[2];
o[3] = p[3];
}
else
{
double u = (x + 0.5) * sourceWidth / targetWidth - 0.5;
double v = (y + 0.5) * sourceHeight / targetHeight - 0.5;
int x0 = (int)Math.Floor(u);
int y0 = (int)Math.Floor(v);
double tx = u - x0;
double ty = v - y0;
for (int c = 0; c < 4; c++)
{
double acc = 0d;
for (int j = 0; j < 2; j++)
{
int sy = Math.Clamp(y0 + j, 0, sourceHeight - 1);
double wy = j == 0 ? 1d - ty : ty;
for (int i = 0; i < 2; i++)
{
int sx = Math.Clamp(x0 + i, 0, sourceWidth - 1);
double wx = i == 0 ? 1d - tx : tx;
acc += s[(sy * sourceWidth + sx) * 4 + c] * wy * wx;
}
}
o[c] = (byte)Math.Clamp(acc, 0d, 255d);
}
}
}
}
}
return dst;
}
}
}
+15
ファイルの表示
@@ -0,0 +1,15 @@
using System;
namespace LuaScript.Engine
{
internal delegate PixelShaderRunStatus PixelShaderInvoke(
string name,
ReadOnlySpan<PixelShaderInput> resources,
ReadOnlySpan<float> constants,
PixelShaderBlend blend,
PixelShaderSampler sampler,
byte[] target,
int targetWidth,
int targetHeight,
out string? error);
}
+3 -2
ファイルの表示
@@ -1,15 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.13.4</Version>
<Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="LuaScript.Gpu" />
<InternalsVisibleTo Include="LuaScript" />
<InternalsVisibleTo Include="LuaScript.Tests" />
</ItemGroup>
+6 -1
ファイルの表示
@@ -9,5 +9,10 @@ namespace LuaScript
double Zoom,
double Rz,
double Alpha,
int Layer);
int Layer,
int Length,
double Volume,
string Character,
string Text,
string Kind);
}
+19
ファイルの表示
@@ -0,0 +1,19 @@
using System;
namespace LuaScript
{
internal interface IPixelShaderRunner
{
PixelShaderRunStatus TryRun(
string hlsl,
string entryPoint,
ReadOnlySpan<PixelShaderInput> resources,
ReadOnlySpan<float> constants,
PixelShaderBlend blend,
PixelShaderSampler sampler,
byte[] target,
int targetWidth,
int targetHeight,
out string? error);
}
}
+15
ファイルの表示
@@ -0,0 +1,15 @@
namespace LuaScript
{
internal readonly record struct PixelShaderBlend(PixelShaderBlendMode Mode, double CompositeBlend)
{
public static PixelShaderBlend Copy { get; } = new(PixelShaderBlendMode.Copy, 0d);
public static PixelShaderBlend Mask { get; } = new(PixelShaderBlendMode.Mask, 0d);
public static PixelShaderBlend Draw { get; } = new(PixelShaderBlendMode.Draw, 0d);
public static PixelShaderBlend Add { get; } = new(PixelShaderBlendMode.Add, 0d);
public static PixelShaderBlend Composite(double blend) => new(PixelShaderBlendMode.Composite, blend);
}
}
+11
ファイルの表示
@@ -0,0 +1,11 @@
namespace LuaScript
{
internal enum PixelShaderBlendMode
{
Copy,
Mask,
Draw,
Add,
Composite,
}
}
+11
ファイルの表示
@@ -0,0 +1,11 @@
namespace LuaScript
{
internal readonly record struct PixelShaderInput(byte[]? Data, int Width, int Height)
{
public const int RandomSize = 256;
public static PixelShaderInput Random { get; } = new(null, RandomSize, RandomSize);
public bool IsRandom => Data is null;
}
}
+9
ファイルの表示
@@ -0,0 +1,9 @@
namespace LuaScript
{
internal enum PixelShaderRunStatus
{
Success,
Unavailable,
CompileError,
}
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace LuaScript
{
internal enum PixelShaderSampler
{
None,
Clip,
Clamp,
Loop,
Mirror,
Dot,
}
}
+29
ファイルの表示
@@ -13,6 +13,35 @@ namespace LuaScript.Tests
Assert.Equal(AnchorSupport.MaxAnchors, AnchorSupport.ClampCount(100));
}
[Fact]
public void NormalizeCount_DefaultsTrackToSinglePoint()
{
Assert.Equal(1, AnchorSupport.NormalizeCount(AnchorSupport.TrackGroup, 0));
Assert.Equal(1, AnchorSupport.NormalizeCount(AnchorSupport.TrackGroup, -3));
Assert.Equal(4, AnchorSupport.NormalizeCount(AnchorSupport.TrackGroup, 4));
Assert.Equal(0, AnchorSupport.NormalizeCount("pos", 0));
Assert.Equal(AnchorSupport.MaxAnchors, AnchorSupport.NormalizeCount("pos", 100));
}
[Fact]
public void SetPosition_ReplacesOrAppendsAbsolute()
{
var source = ImmutableList.Create(new LuaAnchorPoint { Group = "pos", Index = 2, X = 10, Y = 20, Z = 30 });
var replaced = AnchorSupport.SetPosition(source, "pos", 2, 1, 2, 3);
Assert.Single(replaced);
Assert.Equal(1, replaced[0].X);
Assert.Equal(2, replaced[0].Y);
Assert.Equal(3, replaced[0].Z);
var appended = AnchorSupport.SetPosition(source, "pos", 5, 7, 8, 9);
Assert.Equal(2, appended.Count);
Assert.Equal(5, appended[1].Index);
Assert.Equal(7, appended[1].X);
Assert.Equal(8, appended[1].Y);
Assert.Equal(9, appended[1].Z);
}
[Fact]
public void ApplyOption_SetsConnectionAndDimension()
{
+132
ファイルの表示
@@ -0,0 +1,132 @@
using LuaScript.Compat;
namespace LuaScript.Tests
{
public sealed class AviUtlAudioConverterTests
{
private static float[] Interleave(double[] left, double[] right)
{
var data = new float[left.Length * 2];
for (int i = 0; i < left.Length; i++)
{
data[i * 2] = (float)left[i];
data[i * 2 + 1] = (float)right[i];
}
return data;
}
[Fact]
public void RequiredFrames_MatchesTypeWindows()
{
Assert.Equal(16, AviUtlAudioConverter.RequiredFrames("pcm", 16));
Assert.Equal(AviUtlAudioConverter.MaxSamples, AviUtlAudioConverter.RequiredFrames("pcm", 0));
Assert.Equal(AviUtlAudioConverter.MaxSamples, AviUtlAudioConverter.RequiredFrames("pcm", 99999));
Assert.Equal(AviUtlAudioConverter.SpectrumWindow, AviUtlAudioConverter.RequiredFrames("spectrum", 32));
Assert.Equal(AviUtlAudioConverter.FourierWindow, AviUtlAudioConverter.RequiredFrames("fourier", 0));
Assert.Equal(AviUtlAudioConverter.FourierWindow, AviUtlAudioConverter.RequiredFrames("fourier.l", 0));
Assert.Equal(0, AviUtlAudioConverter.RequiredFrames("unknown", 8));
}
[Fact]
public void Pcm_ScalesMonoMixTo16BitRange()
{
var converter = new AviUtlAudioConverter();
var data = Interleave([0.5d, -1d, 0d], [0.5d, -1d, 1d]);
var dest = new double[AviUtlAudioConverter.MaxSamples];
int count = converter.Convert("pcm", data, 3, 3, dest);
Assert.Equal(3, count);
Assert.Equal(16384d, dest[0]);
Assert.Equal(-32768d, dest[1]);
Assert.Equal(16384d, dest[2]);
}
[Fact]
public void Pcm_SelectsChannelBySuffix()
{
var converter = new AviUtlAudioConverter();
var data = Interleave([0.25d, 0.25d], [-0.5d, -0.5d]);
var dest = new double[AviUtlAudioConverter.MaxSamples];
converter.Convert("pcm.l", data, 2, 2, dest);
Assert.Equal(8192d, dest[0]);
converter.Convert("pcm.r", data, 2, 2, dest);
Assert.Equal(-16384d, dest[0]);
}
[Fact]
public void Pcm_ReturnsFewerWhenSourceIsShort()
{
var converter = new AviUtlAudioConverter();
var data = Interleave([0.1d, 0.2d], [0.1d, 0.2d]);
var dest = new double[AviUtlAudioConverter.MaxSamples];
int count = converter.Convert("pcm", data, 2, 100, dest);
Assert.Equal(2, count);
}
[Fact]
public void Spectrum_PeaksInBandContainingSineFrequency()
{
var converter = new AviUtlAudioConverter();
const int frames = AviUtlAudioConverter.SpectrumWindow;
const int cycle = 64;
var mono = new double[frames];
for (int i = 0; i < frames; i++)
mono[i] = Math.Sin(2d * Math.PI * i * cycle / frames);
var data = Interleave(mono, mono);
var dest = new double[AviUtlAudioConverter.MaxSamples];
int count = converter.Convert("spectrum", data, frames, 32, dest);
Assert.Equal(32, count);
int expectedBand = cycle * 32 / AviUtlAudioConverter.SpectrumBins;
int peakBand = 0;
for (int i = 1; i < count; i++)
{
if (dest[i] > dest[peakBand])
peakBand = i;
}
Assert.Equal(expectedBand, peakBand);
Assert.True(dest[peakBand] > 1000d);
}
[Fact]
public void Fourier_ReturnsNormalizedMagnitudes()
{
var converter = new AviUtlAudioConverter();
const int frames = AviUtlAudioConverter.FourierWindow;
const int cycle = 8;
var mono = new double[frames];
for (int i = 0; i < frames; i++)
mono[i] = Math.Sin(2d * Math.PI * i * cycle / frames);
var data = Interleave(mono, mono);
var dest = new double[AviUtlAudioConverter.MaxSamples];
int count = converter.Convert("fourier", data, frames, 0, dest);
Assert.Equal(AviUtlAudioConverter.MaxSamples, count);
int peak = 0;
for (int i = 1; i < count; i++)
{
if (dest[i] > dest[peak])
peak = i;
}
Assert.Equal(cycle - 1, peak);
Assert.Equal(1d, dest[peak], 3);
}
[Fact]
public void UnknownTypeOrEmptySource_YieldsZero()
{
var converter = new AviUtlAudioConverter();
var dest = new double[AviUtlAudioConverter.MaxSamples];
Assert.Equal(0, converter.Convert("waveform", new float[8], 4, 4, dest));
Assert.Equal(0, converter.Convert("pcm", [], 0, 4, dest));
}
}
}
+144
ファイルの表示
@@ -0,0 +1,144 @@
using LuaScript.Compat;
namespace LuaScript.Tests
{
public sealed class AviUtlPixelShaderLibraryTests
{
[Fact]
public void Parse_EmptyOrNull_ReturnsEmpty()
{
Assert.Equal(0, AviUtlPixelShaderLibrary.Parse(null).Count);
Assert.Equal(0, AviUtlPixelShaderLibrary.Parse(string.Empty).Count);
Assert.Same(AviUtlPixelShaderLibrary.Empty, AviUtlPixelShaderLibrary.Parse(string.Empty));
}
[Fact]
public void Parse_SingleShader_ExtractsBody()
{
var source = "--[[pixelshader@psmain:\nfloat4 psmain(float4 pos : SV_Position) : SV_Target { return 0; }\n]]\nobj.pixelshader(\"psmain\", \"object\", \"object\")";
var library = AviUtlPixelShaderLibrary.Parse(source);
Assert.Equal(1, library.Count);
Assert.True(library.TryGet("psmain", out var hlsl));
Assert.Contains("float4 psmain", hlsl);
Assert.DoesNotContain("]]", hlsl);
}
[Fact]
public void Parse_MultipleShaders_AllExtracted()
{
var source = "--[[pixelshader@first:\nA\n]]\ncode\n--[[pixelshader@second:\nB\n]]";
var library = AviUtlPixelShaderLibrary.Parse(source);
Assert.Equal(2, library.Count);
Assert.True(library.TryGet("first", out var a));
Assert.Equal("\nA\n", a);
Assert.True(library.TryGet("second", out var b));
Assert.Equal("\nB\n", b);
}
[Fact]
public void Parse_NameWithUnderscoreAndDigits_Extracted()
{
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@dithering_z2:\nX\n]]");
Assert.True(library.TryGet("dithering_z2", out _));
}
[Fact]
public void Parse_LeadingWhitespace_Extracted()
{
var library = AviUtlPixelShaderLibrary.Parse(" \t--[[pixelshader@ps:\nX\n]]");
Assert.True(library.TryGet("ps", out _));
}
[Fact]
public void Parse_MarkerNotAtLineStart_Ignored()
{
var library = AviUtlPixelShaderLibrary.Parse("local x = 1 --[[pixelshader@ps:\nX\n]]");
Assert.Equal(0, library.Count);
}
[Fact]
public void Parse_BodyEndsAtFirstDoubleBracket()
{
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\nsrc[a[0]]\n]]");
Assert.True(library.TryGet("ps", out var hlsl));
Assert.Equal("\nsrc[a[0", hlsl);
}
[Fact]
public void Parse_UnterminatedBlock_Ignored()
{
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\nfloat4 ps() : SV_Target { return 0; }");
Assert.Equal(0, library.Count);
}
[Fact]
public void Parse_MissingColon_Ignored()
{
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps\nX\n]]");
Assert.Equal(0, library.Count);
}
[Fact]
public void Parse_EmptyName_Ignored()
{
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@:\nX\n]]");
Assert.Equal(0, library.Count);
}
[Fact]
public void Parse_DuplicateName_FirstDefinitionWins()
{
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\nA\n]]\n--[[pixelshader@ps:\nB\n]]");
Assert.True(library.TryGet("ps", out var hlsl));
Assert.Equal("\nA\n", hlsl);
}
[Fact]
public void Parse_CrlfSource_Extracted()
{
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\r\nX\r\n]]\r\n");
Assert.True(library.TryGet("ps", out var hlsl));
Assert.Equal("\r\nX\r\n", hlsl);
}
[Fact]
public void Parse_InsideSectionBody_Extracted()
{
var source = "@通常\n--track@a:A,0,100,0\n--[[pixelshader@ps:\nX\n]]\nobj.pixelshader(\"ps\", \"object\", \"object\")";
var library = AviUtlPixelShaderLibrary.Parse(source);
Assert.True(library.TryGet("ps", out _));
}
[Fact]
public void TryGet_CrossScriptName_ResolvesLocalPart()
{
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\nX\n]]");
Assert.True(library.TryGet("ps@OtherScript", out var hlsl));
Assert.Equal("\nX\n", hlsl);
}
[Fact]
public void TryGet_UnknownOrEmptyName_ReturnsFalse()
{
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\nX\n]]");
Assert.False(library.TryGet("other", out _));
Assert.False(library.TryGet(string.Empty, out _));
}
[Fact]
public void EntryPointOf_StripsScriptSuffix()
{
Assert.Equal("ps", AviUtlPixelShaderLibrary.EntryPointOf("ps@Script"));
Assert.Equal("ps", AviUtlPixelShaderLibrary.EntryPointOf("ps"));
}
[Fact]
public void Parse_ComputeShaderBlock_Ignored()
{
var library = AviUtlPixelShaderLibrary.Parse("--[[computeshader@cs:\nX\n]]");
Assert.Equal(0, library.Count);
}
}
}
+31
ファイルの表示
@@ -0,0 +1,31 @@
using LuaScript.Compat;
namespace LuaScript.Tests
{
public sealed class AviUtlScriptShaderTests
{
private const string ShaderBlock = "--[[pixelshader@ps:\nTexture2D src : register(t0);\nfloat4 ps(float4 pos : SV_Position) : SV_Target\n{\n float4 c = src[uint2(floor(pos.xy))];\n return (c.a != 0.0 && c.r > 0.5) ? c : float4(0, 0, 0, 0);\n}\n]]";
[Fact]
public void Transform_PreservesShaderBlockVerbatim()
{
var source = ShaderBlock + "\nobj.pixelshader(\"ps\", \"object\", \"object\")";
var transformed = AviUtlScript.Transform(source);
Assert.Contains(ShaderBlock, transformed.Replace("\r\n", "\n"));
var library = AviUtlPixelShaderLibrary.Parse(source);
Assert.True(library.TryGet("ps", out var hlsl));
Assert.Contains("c.a != 0.0 && c.r > 0.5", hlsl);
}
[Fact]
public void Transform_SectionedScript_ShaderStaysInSourceLibrary()
{
var source = "@main\n--track@a:A,0,100,0\n" + ShaderBlock + "\nobj.pixelshader(\"ps\", \"object\", \"object\")\n@sub\nobj.x = 1";
var transformed = AviUtlScript.Transform(source);
Assert.Contains("obj.pixelshader", transformed);
Assert.True(AviUtlPixelShaderLibrary.Parse(source).TryGet("ps", out _));
}
}
}
+37
ファイルの表示
@@ -133,5 +133,42 @@ namespace LuaScript.Tests
double expectedRand = AviUtlRandom.Next(-100, 100, 3, 2);
Assert.Equal(500d * expectedRand / 100d, moved);
}
[Fact]
public void ChangedLines_EmptyWhenNoRewrite()
{
var (_, _, changed, _) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = 2");
Assert.Empty(changed);
}
[Fact]
public void ChangedLines_ReportRewrittenLineInRunnableSpace()
{
var (_, _, changed, _) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = obj.x != 0\nobj.z = 3");
Assert.Equal(new[] { 2 }, changed);
}
[Fact]
public void ChangedLines_AreSortedAndCoverEveryRewrittenLine()
{
var (_, _, changed, _) = AviUtlScript.TransformWithMap("a = x != 0\nb = y\nc = z ?? 5\nw++");
Assert.Equal(new[] { 1, 3, 4 }, changed);
}
[Fact]
public void ChangedLines_DeduplicateMultipleRewritesOnOneLine()
{
var (_, _, changed, _) = AviUtlScript.TransformWithMap("a = x != 0 and y != 1 and z != 2");
Assert.Equal(new[] { 1 }, changed);
}
[Fact]
public void ChangedLines_TrackRunnableLineAfterHoistedPrelude()
{
var (_, _, changed, _) = AviUtlScript.TransformWithMap("--dialog:V,local v=3;\nresult = v != 0");
Assert.NotEmpty(changed);
for (int i = 1; i < changed.Length; i++)
Assert.True(changed[i] > changed[i - 1]);
}
}
}
+19 -1
ファイルの表示
@@ -23,6 +23,12 @@ namespace LuaScript.Tests
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r%64,math.abs(g-128),math.sqrt(b*255),a) end end")]
[InlineData("local x=99 local k=3 for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/obj.w*255+k,g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,math.fmod(r,64),math.fmod(g,7)*36,math.fmod(b-128,60)+128,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 local o=0 if v>128 then o=255 else o=32 end obj.setpixel(x,y,o,o,o,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 local o=0 if v>170 then o=255 elseif v>85 then o=128 elseif v>40 then o=64 end obj.setpixel(x,y,o,g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>g then r=g end if b<64 and g>32 then b=g elseif b>192 then b=192 end obj.setpixel(x,y,r,g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=0 if r>128 then local r=g*0.5 v=r+1 if v>100 then v=100 end else v=r end obj.setpixel(x,y,v,g,b,a) end end")]
[InlineData("local w=obj.w local h=obj.h for y=0,h-1 do for x=0,w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/w*255,y/h*255,b,a) end end")]
public void CpuKernelMatchesMoonSharp(string script)
{
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
@@ -46,6 +52,9 @@ namespace LuaScript.Tests
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,b) pd:set(i+2,g) pd:set(i+3,r) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,obj.h-1 do for x=0,obj.w-1 do local i=(y*obj.w+x)*4 local r=pd:get(i+1) local a=pd:get(i+4) pd:set(i+1,r*a/255) pd:set(i+2,pd:get(i+2)*obj.track0/100) pd:set(i+3,math.min(255,pd:get(i+3)+50)) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,r*3) pd:set(i+2,g-300) pd:set(i+3,b*2-255) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,255-r) pd:set(i+2,255-g) pd:set(i+3,255-b) end end obj.putpixeldata(pd)")]
[InlineData("local data=obj.getpixeldata() local w=data.width local h=data.height for y=0,h-1 do for x=0,w-1 do local i=(y*w+x)*4 local r=data:get(i+1) local g=data:get(i+2) local b=data:get(i+3) data:set(i+1,g) data:set(i+2,b) data:set(i+3,r) end end obj.putpixeldata(data)")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) local v=(r+g+b)/3 local o=0 if v>128 then o=255 end pd:set(i+1,o) pd:set(i+2,o) pd:set(i+3,o) end end")]
public void GetPixelDataKernelMatchesMoonSharp(string script)
{
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height, ["track0"] = 73d };
@@ -60,6 +69,9 @@ namespace LuaScript.Tests
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local i=i+4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for pd=0,pd.width-1 do local i=(y*2+pd)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local pd=0 pd:set(i+1,0) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) if r>128 then pd:set(i+1,255) end pd:set(i+2,0) pd:set(i+3,0) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end obj.putpixeldata(other)")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end obj.putpixeldata(pd) obj.putpixeldata(pd)")]
public void GetPixelDataNonKernelScriptsAreRejected(string script)
{
Assert.Null(KernelExtractor.TryExtract(script));
@@ -92,8 +104,12 @@ namespace LuaScript.Tests
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) total=total+r obj.setpixel(x,y,r,g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x+1,y) obj.setpixel(x,y,r,g,b,a) end end")]
[InlineData("for i=0,10 do end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,obj.rand(0,255),g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then obj.setpixel(x,y,255,g,b,a) end end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then local y=0 r=y end obj.setpixel(x,y,r,g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end obj.putpixeldata(pd)")]
[InlineData("local w=5 for y=0,obj.h-1 do for x=0,w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end")]
public void NonKernelScriptsAreRejected(string script)
{
Assert.Null(KernelExtractor.TryExtract(script));
@@ -178,6 +194,8 @@ namespace LuaScript.Tests
return DynValue.NewTable(pd);
});
obj["putpixeldata"] = DynValue.NewCallback((_, _) => DynValue.Void);
engine.Globals["obj"] = obj;
engine.DoString(script);
}
+12
ファイルの表示
@@ -62,6 +62,18 @@ namespace LuaScript.Tests
Assert.Contains($"uniforms[{index / 4}].{"xyzw"[index % 4]}", hlsl);
}
[Fact]
public void ConditionalStatementEmitsTernary()
{
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 v=(r+g+b)/3 local o=0 if v>170 then o=255 elseif v>85 then o=128 end " +
"obj.setpixel(x,y,o,o,o,a) end end";
string hlsl = HlslKernelEmitter.Emit(Extract(script));
Assert.Contains(" ? (", hlsl);
Assert.Contains(" > ", hlsl);
}
[Fact]
public void EmissionIsDeterministic()
{
+1
ファイルの表示
@@ -24,6 +24,7 @@ namespace LuaScript.Tests
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,((r>128 and g<64) or (not (b>200))) and 255 or 0,g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,(r>=200) and 255 or 0,(g<=50) and 255 or 0,(b==0) and 255 or ((b~=0) and 100 or 0),a) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,r*3) pd:set(i+2,g-300) pd:set(i+3,b*2-255) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 local o=0 if v>170 then o=255 elseif v>85 then o=128 else o=r end obj.setpixel(x,y,o,o,o,a) end end")]
public void SimdBlockMatchesScalarRow(string script)
{
var program = KernelExtractor.TryExtract(script);
+7 -2
ファイルの表示
@@ -11,6 +11,8 @@ namespace LuaScript.Tests
"repeat", "return", "then", "true", "until", "while"
];
private static readonly string[] SyntaxKeywords = ["fast"];
private static readonly string[] Globals =
[
"time", "frame", "totalframe", "framerate",
@@ -47,8 +49,10 @@ namespace LuaScript.Tests
"obj.getobject", "obj.getpixel", "obj.setpixel",
"obj.getpixeldata", "obj.putpixeldata", "obj.rand", "obj.load",
"obj.setfont", "obj.draw", "obj.drawpoly", "obj.copybuffer",
"obj.getvalue", "obj.setoption", "obj.getoption", "obj.pixeloption",
"obj.setanchor", "obj.effect", "obj.getinfo"
"obj.pixelshader",
"obj.getvalue", "obj.getaudio", "obj.setoption", "obj.getoption", "obj.pixeloption",
"obj.setanchor", "obj.effect", "obj.brush", "obj.getinfo",
"obj.fill", "obj.getpixelregion", "obj.putpixelregion", "obj.convolve", "obj.resize"
]),
("math", [
"math.abs", "math.ceil", "math.cos", "math.exp", "math.floor",
@@ -102,6 +106,7 @@ namespace LuaScript.Tests
private static string[] ExpectedStaticCandidates() =>
Keywords
.Concat(SyntaxKeywords)
.Concat(Globals)
.Concat(Namespaces.SelectMany(n => n.Members))
.Distinct()
+274
ファイルの表示
@@ -0,0 +1,274 @@
using LuaScript;
namespace LuaScript.Tests
{
public sealed class LuaScriptEngineBufferOpsTests
{
private sealed class StubMediaLoader : IMediaSourceLoader
{
public byte[] RenderText(string text, string fontFamily, double fontSize, bool bold, bool italic, int colorRgb, out int width, out int height)
{
width = 1;
height = 1;
return new byte[4];
}
public byte[] DecodeImage(string path, out int width, out int height)
{
width = 1;
height = 1;
return new byte[4];
}
public byte[] DecodeMovie(string path, double time, out int width, out int height)
{
width = 1;
height = 1;
return new byte[4];
}
public void Dispose() { }
}
private static LuaScriptEngine CreateEngine() => new(static () => new StubMediaLoader());
private static AviUtlScriptContext NewContext(byte[] buffer, int width, int height)
{
var ctx = new AviUtlScriptContext { Framerate = 30 };
ctx.SetResolvedBuffer(buffer, width, height);
return ctx;
}
private static byte[] Bgra(params (byte B, byte G, byte R, byte A)[] pixels)
{
var buffer = new byte[pixels.Length * 4];
for (int i = 0; i < pixels.Length; i++)
{
buffer[i * 4 + 0] = pixels[i].B;
buffer[i * 4 + 1] = pixels[i].G;
buffer[i * 4 + 2] = pixels[i].R;
buffer[i * 4 + 3] = pixels[i].A;
}
return buffer;
}
private sealed class RecordingProcessor : IPixelBufferProcessor
{
public int FillCalls;
public int ConvolveCalls;
public int ResizeCalls;
public bool LastFillForce;
public bool LastConvolveForce;
public bool LastResizeForce;
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
{
FillCalls++;
LastFillForce = force;
return false;
}
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
{
ConvolveCalls++;
LastConvolveForce = force;
return false;
}
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
{
ResizeCalls++;
LastResizeForce = force;
target = null;
return false;
}
}
[Fact]
public void BufferOps_ConsultPixelProcessorAndFallBackToCpu()
{
using var engine = CreateEngine();
var ctx = NewContext(new byte[2 * 2 * 4], 2, 2);
var processor = new RecordingProcessor();
ctx.PixelProcessor = processor;
engine.Execute("obj.fill(200, 100, 50, 255) obj.convolve({1,1,1,1,1,1,1,1,1}, 3) obj.resize(4, 4)", ctx);
Assert.Equal(1, processor.FillCalls);
Assert.Equal(1, processor.ConvolveCalls);
Assert.Equal(1, processor.ResizeCalls);
Assert.Equal(4, ctx.ImageWidth);
Assert.Equal(4, ctx.ImageHeight);
Assert.False(processor.LastFillForce);
Assert.False(processor.LastConvolveForce);
Assert.False(processor.LastResizeForce);
}
[Fact]
public void FastMarker_ForcesPixelProcessorRegardlessOfSize()
{
using var engine = CreateEngine();
var ctx = NewContext(new byte[2 * 2 * 4], 2, 2);
var processor = new RecordingProcessor();
ctx.PixelProcessor = processor;
engine.Execute("__fast_fill(200, 100, 50, 255) __fast_convolve({1,1,1,1,1,1,1,1,1}, 3) __fast_resize(4, 4)", ctx);
Assert.Equal(1, processor.FillCalls);
Assert.Equal(1, processor.ConvolveCalls);
Assert.Equal(1, processor.ResizeCalls);
Assert.True(processor.LastFillForce);
Assert.True(processor.LastConvolveForce);
Assert.True(processor.LastResizeForce);
}
[Fact]
public void Fill_WholeBuffer_WritesPremultipliedColor()
{
using var engine = CreateEngine();
var ctx = NewContext(new byte[2 * 2 * 4], 2, 2);
engine.Execute("obj.fill(200, 100, 50, 255)", ctx);
var buffer = ctx.GetPixelBuffer()!;
for (int i = 0; i < 4; i++)
{
Assert.Equal(50, buffer[i * 4 + 0]);
Assert.Equal(100, buffer[i * 4 + 1]);
Assert.Equal(200, buffer[i * 4 + 2]);
Assert.Equal(255, buffer[i * 4 + 3]);
}
}
[Fact]
public void Fill_Rectangle_TouchesOnlyRequestedPixels()
{
using var engine = CreateEngine();
var ctx = NewContext(new byte[3 * 1 * 4], 3, 1);
engine.Execute("obj.fill(255, 255, 255, 255, 1, 0, 1, 1)", ctx);
var buffer = ctx.GetPixelBuffer()!;
Assert.Equal(new byte[] { 0, 0, 0, 0 }, buffer.AsSpan(0, 4).ToArray());
Assert.Equal(new byte[] { 255, 255, 255, 255 }, buffer.AsSpan(4, 4).ToArray());
Assert.Equal(new byte[] { 0, 0, 0, 0 }, buffer.AsSpan(8, 4).ToArray());
}
[Fact]
public void GetPixelRegion_ReturnsStraightRgba()
{
using var engine = CreateEngine();
var ctx = NewContext(Bgra((50, 100, 200, 255)), 1, 1);
engine.Execute("local t = obj.getpixelregion(0, 0, 1, 1) obj.x = t[1] obj.y = t[2] obj.z = t[3] obj.alpha = t[4]", ctx);
Assert.Equal(200d, ctx.X);
Assert.Equal(100d, ctx.Y);
Assert.Equal(50d, ctx.Z);
Assert.Equal(255d, ctx.Alpha);
}
[Fact]
public void GetPixelRegion_OutOfBounds_YieldsTransparent()
{
using var engine = CreateEngine();
var ctx = NewContext(Bgra((10, 20, 30, 255)), 1, 1);
engine.Execute("local t = obj.getpixelregion(1, 0, 1, 1) obj.x = t[1] + t[2] + t[3] + t[4]", ctx);
Assert.Equal(0d, ctx.X);
}
[Fact]
public void PutPixelRegion_WritesPremultipliedColor()
{
using var engine = CreateEngine();
var ctx = NewContext(new byte[2 * 1 * 4], 2, 1);
engine.Execute("obj.putpixelregion(0, 0, 2, 1, {200, 100, 50, 255, 10, 20, 30, 255})", ctx);
var buffer = ctx.GetPixelBuffer()!;
Assert.Equal(new byte[] { 50, 100, 200, 255 }, buffer.AsSpan(0, 4).ToArray());
Assert.Equal(new byte[] { 30, 20, 10, 255 }, buffer.AsSpan(4, 4).ToArray());
}
[Fact]
public void RegionRoundTrip_PreservesOpaquePixels()
{
using var engine = CreateEngine();
var original = Bgra((10, 20, 30, 255), (40, 50, 60, 255), (70, 80, 90, 255), (100, 110, 120, 255));
var ctx = NewContext((byte[])original.Clone(), 2, 2);
engine.Execute(
"local t = obj.getpixelregion(0, 0, obj.w, obj.h) obj.fill(0, 0, 0, 0) obj.putpixelregion(0, 0, obj.w, obj.h, t)",
ctx);
Assert.Equal(original, ctx.GetPixelBuffer());
}
[Fact]
public void Convolve_Identity_LeavesOpaqueBufferUnchanged()
{
using var engine = CreateEngine();
var original = Bgra((10, 20, 30, 255), (40, 50, 60, 255), (70, 80, 90, 255), (100, 110, 120, 255));
var ctx = NewContext((byte[])original.Clone(), 2, 2);
engine.Execute("obj.convolve({0, 0, 0, 0, 1, 0, 0, 0, 0}, 3)", ctx);
Assert.Equal(original, ctx.GetPixelBuffer());
}
[Fact]
public void Convolve_BoxBlur_AveragesHorizontalStep()
{
using var engine = CreateEngine();
var ctx = NewContext(Bgra((0, 0, 0, 255), (255, 255, 255, 255)), 2, 1);
engine.Execute("obj.convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)", ctx);
var buffer = ctx.GetPixelBuffer()!;
Assert.Equal(85, buffer[2]);
Assert.Equal(85, buffer[1]);
Assert.Equal(85, buffer[0]);
Assert.Equal(170, buffer[6]);
Assert.Equal(255, buffer[3]);
Assert.Equal(255, buffer[7]);
}
[Fact]
public void Resize_Nearest_ReplicatesBlocks()
{
using var engine = CreateEngine();
var ctx = NewContext(Bgra((11, 12, 13, 255), (21, 22, 23, 255), (31, 32, 33, 255), (41, 42, 43, 255)), 2, 2);
engine.Execute("obj.resize(4, 4, 'nearest')", ctx);
Assert.Equal(4, ctx.ImageWidth);
Assert.Equal(4, ctx.ImageHeight);
Assert.True(ctx.BufferReplaced);
var buffer = ctx.GetPixelBuffer()!;
byte SampleR(int x, int y) => buffer[(y * 4 + x) * 4 + 2];
Assert.Equal(13, SampleR(0, 0));
Assert.Equal(13, SampleR(1, 1));
Assert.Equal(23, SampleR(2, 0));
Assert.Equal(33, SampleR(0, 2));
Assert.Equal(43, SampleR(3, 3));
}
[Fact]
public void Resize_UpdatesObjDimensions()
{
using var engine = CreateEngine();
var ctx = NewContext(new byte[4 * 4 * 4], 4, 4);
engine.Execute("obj.resize(8, 2) obj.x = obj.w obj.y = obj.h obj.z = obj.diagonal", ctx);
Assert.Equal(8, ctx.ImageWidth);
Assert.Equal(2, ctx.ImageHeight);
Assert.Equal(8d, ctx.X);
Assert.Equal(2d, ctx.Y);
Assert.Equal(Math.Sqrt(8d * 8d + 2d * 2d), ctx.Z);
}
}
}
+164
ファイルの表示
@@ -0,0 +1,164 @@
using LuaScript;
namespace LuaScript.Tests
{
public sealed class LuaScriptEngineGetAudioTests
{
private sealed class StubMediaLoader : IMediaSourceLoader
{
public byte[] RenderText(string text, string fontFamily, double fontSize, bool bold, bool italic, int colorRgb, out int width, out int height)
{
width = 1;
height = 1;
return new byte[4];
}
public byte[] DecodeImage(string path, out int width, out int height)
{
width = 1;
height = 1;
return new byte[4];
}
public byte[] DecodeMovie(string path, double time, out int width, out int height)
{
width = 1;
height = 1;
return new byte[4];
}
public void Dispose() { }
}
private static LuaScriptEngine CreateEngine() => new(static () => new StubMediaLoader());
private static AviUtlScriptContext NewContext()
{
return new AviUtlScriptContext
{
ImageWidth = 2,
ImageHeight = 2,
Framerate = 30,
};
}
[Fact]
public void GetAudio_FillsBufferTableFromLoader()
{
using var engine = CreateEngine();
var ctx = NewContext();
string? capturedFile = null;
string? capturedType = null;
int capturedSize = -1;
ctx.AudioLoader = (file, type, size) =>
{
capturedFile = file;
capturedType = type;
capturedSize = size;
return (3, 44100, [1.5d, -2.5d, 3d]);
};
engine.Execute(
"local buf = {}\n" +
"local n, rate = obj.getaudio(buf, 'audiobuffer', 'pcm', 3)\n" +
"obj.x = n\n" +
"obj.y = rate\n" +
"obj.z = buf[1]\n" +
"obj.ox = buf[2]\n" +
"obj.oy = buf[3]",
ctx);
Assert.Equal("audiobuffer", capturedFile);
Assert.Equal("pcm", capturedType);
Assert.Equal(3, capturedSize);
Assert.Equal(3d, ctx.X);
Assert.Equal(44100d, ctx.Y);
Assert.Equal(1.5d, ctx.Z);
Assert.Equal(-2.5d, ctx.Ox);
Assert.Equal(3d, ctx.Oy);
}
[Fact]
public void GetAudio_NilBuffer_ReturnsTableAsThirdValue()
{
using var engine = CreateEngine();
var ctx = NewContext();
ctx.AudioLoader = (_, type, _) => (2, 48000, [7d, 8d]);
engine.Execute(
"local n, rate, buf = obj.getaudio(nil, 'C:/test.wav', 'spectrum.r', 2)\n" +
"obj.x = n\n" +
"obj.y = rate\n" +
"obj.z = buf[1]\n" +
"obj.ox = buf[2]",
ctx);
Assert.Equal(2d, ctx.X);
Assert.Equal(48000d, ctx.Y);
Assert.Equal(7d, ctx.Z);
Assert.Equal(8d, ctx.Ox);
}
[Fact]
public void GetAudio_DefaultsTypeToPcm()
{
using var engine = CreateEngine();
var ctx = NewContext();
string? capturedType = null;
int capturedSize = -1;
ctx.AudioLoader = (_, type, size) =>
{
capturedType = type;
capturedSize = size;
return (0, 48000, []);
};
engine.Execute("obj.x = obj.getaudio({}, 'audiobuffer')", ctx);
Assert.Equal("pcm", capturedType);
Assert.Equal(0, capturedSize);
Assert.Equal(0d, ctx.X);
}
[Fact]
public void GetAudio_WithoutLoader_ReturnsZero()
{
using var engine = CreateEngine();
var ctx = NewContext();
engine.Execute(
"local n, rate, buf = obj.getaudio(nil, 'audiobuffer', 'pcm', 8)\n" +
"obj.x = n\n" +
"obj.y = rate\n" +
"obj.z = #buf\n" +
"obj.ox = obj.getaudio({}, 7)",
ctx);
Assert.Equal(0d, ctx.X);
Assert.Equal(0d, ctx.Y);
Assert.Equal(0d, ctx.Z);
Assert.Equal(0d, ctx.Ox);
}
[Fact]
public void GetAudio_ClampsCountToDataLength()
{
using var engine = CreateEngine();
var ctx = NewContext();
ctx.AudioLoader = (_, _, _) => (10, 48000, [5d]);
engine.Execute(
"local n, _, buf = obj.getaudio(nil, 'audiobuffer', 'pcm', 10)\n" +
"obj.x = n\n" +
"obj.y = #buf",
ctx);
Assert.Equal(1d, ctx.X);
Assert.Equal(1d, ctx.Y);
}
}
}
149ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。 さらに表示