コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
9a9c2ec405
|
||
|
|
103b612082
|
||
|
|
9e1da1839e
|
||
|
|
c19e12aa87
|
||
|
|
ed4c38772f
|
||
|
|
d31fd77aee
|
||
|
|
eb0199131d
|
||
|
|
36935bdf1d
|
||
|
|
7d9a9f1cb8
|
||
|
|
3ce2483062
|
||
|
|
fc8a07f935
|
||
|
|
d1279c25fa
|
||
|
|
048c6d6707
|
||
|
|
3a29862423
|
||
|
|
8c69864456
|
||
|
|
8a7b328db4
|
||
|
|
8517bf5f50
|
||
|
|
b928101e3e
|
||
|
|
7fb671e8c6
|
||
|
|
20ff47edce
|
||
|
|
8f9b7c725f
|
||
|
|
499f8ba078
|
||
|
|
66f2d398b7
|
||
|
|
935bca6fbb
|
||
|
|
4c7ef12361
|
||
|
|
65e7864221
|
||
|
|
25430c4dcf
|
||
|
|
f0234d21e4
|
||
|
|
bfe23707f0
|
||
|
|
e74af227d8
|
||
|
|
2b5901379f
|
||
|
|
deb94b3f29
|
||
|
|
74a65b7a8b
|
||
|
|
a4cc0f3220
|
||
|
|
86f889cbd2
|
||
|
|
c2f48230f3
|
||
|
|
4153956b37
|
||
|
|
3763db1cfc
|
||
|
|
9bcab1ae28
|
||
|
|
6e13a4d1c2
|
||
|
|
8dc87d63be
|
||
|
|
0afb7afc21
|
||
|
|
2769a29808
|
||
|
|
1f21b4c49c
|
||
|
|
cafc6d6e48
|
||
|
|
49a2ce29b2
|
||
|
|
d728c8d056
|
||
|
|
b6eac20941
|
||
|
|
d8589007b3
|
||
|
|
85596f76f7
|
||
|
|
018999ff5e
|
||
|
|
c5da497bb3
|
||
|
|
f46cb08f85
|
||
|
|
b0a5293b89
|
||
|
|
67a1b4fa31
|
||
|
|
2d0fb2c47a
|
||
|
|
45d5164afa
|
||
|
|
ba20fc8187
|
||
|
|
669b24c2b3
|
||
|
|
91a3e3f762
|
||
|
|
722ae62326
|
||
|
|
fee1f293c7
|
||
|
|
b6764fe637
|
||
|
|
01e368207d
|
||
|
|
29ea2ea45c
|
||
|
|
1d60d8b245
|
||
|
|
8f2aafdffd
|
||
|
|
f26816343f
|
||
|
|
0cab8972e0
|
||
|
|
f2aa668cf6
|
||
|
|
ed27979f64
|
||
|
|
7b958ea171
|
||
|
|
332dab3889
|
||
|
|
75d457a7ab
|
||
|
|
50e1801878
|
||
|
|
793d010bdb
|
||
|
|
b564b0b185
|
||
|
|
6d83fe93d8
|
||
|
|
db9c3747ea
|
||
|
|
7d887afe5a
|
||
|
|
ac34830367
|
||
|
|
8ed188d0e2
|
||
|
|
9c55c08caf
|
||
|
|
42868023f3
|
||
|
|
e146b36fa0
|
||
|
|
5fac495848
|
||
|
|
4fd519249f
|
||
|
|
1b26df959f
|
||
|
|
3cd67212a1
|
||
|
|
46692dfe95
|
||
|
|
e8d9cef129
|
||
|
|
18036cd74e
|
||
|
|
c8f857d2b4
|
||
|
|
ac7f797566
|
||
|
|
8beae1a277
|
||
|
|
6eb4d7c9af
|
||
|
|
a843f460de
|
||
|
|
27f04c7560
|
||
|
|
43c0ce88b3
|
||
|
|
00f0d991c1
|
||
|
|
784d294ca6
|
||
|
|
260d427bcf
|
||
|
|
b62f4a3a7d
|
||
|
|
79a408cafd
|
||
|
|
807df7df8a
|
||
|
|
0c5e3066c1
|
||
|
|
fbaff95503
|
||
|
|
8dec38a911
|
||
|
|
902d729c19
|
||
|
|
79f8ff8839
|
||
|
|
9a630ecb5a
|
||
|
|
d9e6132a1f
|
||
|
|
e685e7aa40
|
||
|
|
bf49fe9984
|
||
|
|
c05a1479f9
|
||
|
|
80ddb663b0
|
||
|
|
2f1bbc3828
|
||
|
|
e911f6e83f
|
||
|
|
6162ce5c19
|
||
|
|
59dcb82b49
|
||
|
|
d37726cdf6
|
||
|
|
0c09cf4a51
|
||
|
|
0d4809924d
|
||
|
|
1e97e7d8fe
|
||
|
|
06cfefe1b4
|
||
|
|
37b1371f57
|
||
|
|
9db756c974
|
||
|
|
43f3161ebb
|
||
|
|
4b3b74edae
|
||
|
|
5129ece749
|
||
|
|
24ef4135cf
|
||
|
|
044fdbf1eb
|
||
|
|
9e1ad6c133
|
||
|
|
6d8def9f08
|
||
|
|
7a9f1ff6e8
|
||
|
|
82db144b86
|
||
|
|
d3fb73ed94
|
||
|
|
7dd777fbc6
|
||
|
|
aa17df08d8
|
||
|
|
e5c4485f16
|
||
|
|
9b901f91b6
|
||
|
|
2b24a407e6
|
||
|
|
150b4818d4
|
||
|
|
34b7d60ca6
|
||
|
|
7dc6083fd7
|
||
|
|
245fb9c323
|
||
|
|
42c3bc4f4b
|
||
|
|
d273f99593
|
||
|
|
e1763e0c81
|
||
|
|
7221ce3aca
|
||
|
|
5f3ad96ea2
|
||
|
|
4e0bf831c5
|
||
|
|
0fedfd5804
|
||
|
|
f11225e2a1
|
||
|
|
92e8c43160
|
||
|
|
5fb9eae7a0
|
||
|
|
f109232cae
|
||
|
|
1596a048cd
|
||
|
|
0b0c795d7a
|
||
|
|
2be3c3d28b
|
||
|
|
3f9e4ebca4
|
||
|
|
03042b17e7
|
||
|
|
5e6d74dfee
|
||
|
|
40d68416c2
|
||
|
|
de6472c34b
|
||
|
|
55c8bffb70
|
||
|
|
8ca66bceb8
|
||
|
|
865f5117ea
|
||
|
|
b30f7a818b
|
||
|
|
95786a1f0a
|
||
|
|
cc07e2a83d
|
||
|
|
08e5e432b7
|
||
|
|
1e9b039cef
|
||
|
|
bad39fe0db
|
||
|
|
a5567a804d
|
||
|
|
a9cb4a9cda
|
||
|
|
9e9b5277af
|
||
|
|
1d8705c7ee
|
||
|
|
14683c7909
|
||
|
|
42b123ebc3
|
||
|
|
b0114abdb7
|
||
|
|
c21de5b3eb
|
||
|
|
bd891d9a1e
|
||
|
|
d2bef10085
|
||
|
|
3eafcdc70e
|
||
|
|
6f26fc95fa
|
||
|
|
88ce786d05
|
||
|
|
d69ae5f06e
|
||
|
|
d42d8a6764
|
||
|
|
8f9ace2dc8
|
||
|
|
c416e955a4
|
||
|
|
7362e70ab8
|
||
|
|
c9741836a5
|
||
|
|
afd57d758d
|
||
|
|
c56432dbd6
|
||
|
|
9493aef779
|
||
|
|
5d55f2c083
|
||
|
|
09918c2858
|
||
|
|
a687bba0ff
|
||
|
|
bb591b6fef
|
||
|
|
27d7294290
|
||
|
|
8d1cf91499
|
||
|
|
b2a1900616
|
||
|
|
f786250866
|
||
|
|
20dfba6e7e
|
||
|
|
5e40f45910
|
||
|
|
ea4f096bc4
|
||
|
|
d7812f39dc
|
||
|
|
77fdf60ec9
|
||
|
|
bcb9925953
|
||
|
|
ec7d8a1da4
|
||
|
|
098d6e498b
|
||
|
|
ccf37dd1d3
|
||
|
|
2ce3068d54
|
||
|
|
c2a1990501
|
||
|
|
4ac25584b9
|
||
|
|
5e40f30124
|
||
|
|
9d541e06b9
|
||
|
|
bca7b5707e
|
||
|
|
a17289a2da
|
||
|
|
71e6b71056
|
||
|
|
13a0602adb
|
||
|
|
6a0c993755
|
||
|
|
484a26ec45
|
||
|
|
a121a598b6
|
||
|
|
6dd70413a9
|
||
|
|
ac482b6041
|
||
|
|
c2761c0796
|
||
|
|
3bbd411d86
|
||
|
|
324faabb96
|
||
|
|
32b706cb8b
|
||
|
|
aa97c52b38
|
||
|
|
a2f0231739
|
||
|
|
2905192d3a
|
||
|
|
ee6f6bd9c1
|
||
|
|
8853f5e403
|
||
|
|
867de7aa73
|
||
|
|
e384d7e490
|
||
|
|
87e060d71d
|
||
|
|
9c6167d224
|
||
|
|
a8a91103e1
|
||
|
|
4a2f4b2dbb
|
||
|
|
33fc45639b
|
||
|
|
7af803e46e
|
||
|
|
48e8287704
|
||
|
|
7eff4591f0
|
||
|
|
5b1bb4ad6e
|
||
|
|
7f3e6b0019
|
||
|
|
7519a11851
|
||
|
|
4193c40f41
|
||
|
|
cd68bf86b0
|
||
|
|
9948204265
|
||
|
|
25670bde90
|
||
|
|
ae230c0e10
|
||
|
|
7ee8f1ccf0
|
||
|
|
da88898a67
|
||
|
|
3c63ba0729
|
||
|
|
e7382ac289
|
||
|
|
ee7e4f43bc
|
||
|
|
7dc6e9fb40
|
||
|
|
803534d804
|
||
|
|
a25803fa30
|
||
|
|
e42401670f
|
||
|
|
a139326c39
|
||
|
|
496c237f50
|
||
|
|
dfbcbded98
|
||
|
|
2ebbe3ced0
|
||
|
|
9671cba5a1
|
||
|
|
947532f064
|
||
|
|
6e3594eb01
|
||
|
|
abc7b2cde2
|
||
|
|
68d862ded0
|
||
|
|
d3060fd202
|
||
|
|
1d92d80a86
|
||
|
|
86ad19105f
|
||
|
|
2cd5ab273a
|
||
|
|
d75aeee3c2
|
||
|
|
981fb2ceeb
|
||
|
|
01a0dcb9ae
|
||
|
|
460b5e6252
|
||
|
|
fb02580836
|
||
|
|
58a5f59b19
|
||
|
|
95598b1a88
|
||
|
|
7f436ebe17
|
||
|
|
d620f7ea3b
|
||
|
|
ad377a0923
|
||
|
|
f374038000
|
||
|
|
ddba8d63c2
|
||
|
|
ab2e195139
|
||
|
|
85c585db89
|
||
|
|
93eb681b0e
|
||
|
|
30ca75f65e
|
||
|
|
a07916de6b
|
||
|
|
467a4b0dd8
|
||
|
|
03aad4cc6e
|
||
|
|
b638c7b9c2
|
||
|
|
ede56971cd
|
||
|
|
94c11dffcb
|
||
|
|
28c1f70fa1
|
||
|
|
2ecde28980
|
||
|
|
1c2c3915e9
|
||
|
|
9f2cab9961
|
||
|
|
e1778c7c73
|
||
|
|
98426f4ca8
|
||
|
|
7358e2b0a1
|
||
|
|
1af7b8fc8b
|
||
|
|
26d7b0c470
|
||
|
|
96400605ba
|
||
|
|
695cb2f04d
|
||
|
|
6b39a4cceb
|
||
|
|
4b4252855b
|
||
|
|
0d6c3285e1
|
||
|
|
3bcf206a95
|
||
|
|
c65bb5b08f
|
||
|
|
e5b9b98a27
|
||
|
|
7906d4c735
|
||
|
|
d879f3c6fa
|
||
|
|
e7ae3bf290
|
||
|
|
735fd86bed
|
||
|
|
813b3d6686
|
||
|
|
ca43e3706b
|
||
|
|
ef4d7e8024
|
||
|
|
299da15bb8
|
||
|
|
ffba68aeb0
|
||
|
|
1085294aa0
|
||
|
|
cb7e4622e8
|
||
|
|
06e2afa7ed
|
||
|
|
3e60c6d77f
|
||
|
|
594517b436
|
||
|
|
1d3b924492
|
||
|
|
b6cd4bb43e
|
||
|
|
5c0745e039
|
||
|
|
c5fd507ab5
|
||
|
|
dfc39e9e19
|
||
|
|
48d7969a84
|
||
|
|
9eb5a44f2d
|
||
|
|
fc2fc6ab77
|
||
|
|
bc7fa914a4
|
||
|
|
c436f24ee0
|
||
|
|
5a192f5a6f
|
||
|
|
a032f0728f
|
||
|
|
548432f3a9
|
||
|
|
3bd1e5384e
|
||
|
|
738da05e59
|
||
|
|
d457b65f44
|
||
|
|
270cf025ff
|
||
|
|
c657892b7b
|
||
|
|
87cdd4ed90
|
||
|
|
5c1c1272db
|
||
|
|
bcac943775
|
||
|
|
3d0ff687e2
|
||
|
|
ce0da92ac8
|
||
|
|
7dbe063ac8
|
||
|
|
1acaef291c
|
||
|
|
26c96b302f
|
||
|
|
c4011d8eef
|
||
|
|
451b017f6f
|
||
|
|
d6b6e440bf
|
||
|
|
7601b77902
|
||
|
|
0799785cad
|
||
|
|
d607e4ec49
|
||
|
|
c7e5b91509
|
||
|
|
cf23d184fe
|
||
|
|
d2b518f611
|
||
|
|
c186a6b27d
|
||
|
|
5f411e89ec
|
||
|
|
16ed6336c3
|
||
|
|
6d2a5cbe24
|
||
|
|
94f7ad4f50
|
||
|
|
3ba77aab18
|
||
|
|
90fe288f66
|
||
|
|
6b2b5d879f | ||
|
|
d01d5d6df5 | ||
|
|
a093c458a2
|
||
|
|
0e65bf1883
|
||
|
|
d8f728b3f9
|
||
|
|
244e75a238
|
||
|
|
75cc4bd62e
|
||
|
|
6385dbeb6d
|
||
|
|
bc395a0181
|
||
|
|
a0dec019fe
|
検索条件に一致するファイルはありません
+42
-37
@@ -1,54 +1,59 @@
|
||||
# v1.7.0 - Lua スクリプト for YMM4
|
||||
# v1.15.0 - Lua スクリプト for YMM4
|
||||
|
||||
AviUtl のアニメーション効果スクリプト互換層に**映像エフェクトの適用(`obj.effect()`)**を
|
||||
追加したリリースです。スクリプトから YMM4 に登録された映像エフェクトを呼び出し、
|
||||
図形やピクセルで生成した画像へ連鎖適用できるようになりました。
|
||||
AviUtl ExEdit2 互換のピクセルシェーダーを追加したリリースです。スクリプト内のコメントに HLSL で記述したピクセルシェーダーを obj.pixelshader で GPU 実行できます。記法と引数の並びは AviUtl ExEdit2 と同一で、MoonSharp とネイティブのどちらの実行エンジンでも動作します。互換にとどまらず YMM4 側の拡張も加えており、blend 引数へ obj.setoption("blend", 番号) と同じ番号を数値で渡すと、シェーダーの出力を YMM4 の全合成モードで出力先へ合成できます。また、YMM4 の構造上取得できないフレームバッファは、シーンサイズの仮想フレームバッファとして再解釈して対応しました。既存のスクリプトの書き方と実行結果に変更はありません。
|
||||
|
||||
---
|
||||
|
||||
## 新機能
|
||||
|
||||
### 1. obj.effect() による YMM4 映像エフェクトの適用
|
||||
### obj.pixelshader
|
||||
|
||||
`obj.effect(エフェクト名, パラメータ名, 値, パラメータ名, 値, ...)` を実装しました。
|
||||
スクリプトが生成した画像に対して、YMM4 の映像エフェクトを適用します。
|
||||
スクリプト内に定義した HLSL のピクセルシェーダーを GPU で実行する obj.pixelshader(登録名, 出力先, リソース [, 定数 [, blend [, sampler]]]) を追加しました。
|
||||
|
||||
- エフェクト名は YMM4 の登録名または別名で指定します。`EffectFactories` から取得できる
|
||||
全映像エフェクト(標準エフェクトおよびユーザー製プラグインを含む)が対象です。
|
||||
- パラメータは表示名またはプロパティ名で指定します。型に応じて設定され、Animation は
|
||||
定数値、真偽値、列挙(名前または番号)、色(0xRRGGBB)、数値、文字列に対応します。
|
||||
- パラメータはキー/値のペアで複数同時に指定できます。
|
||||
- `obj.effect` を複数回呼び出すと、呼んだ順に**独立したエフェクトインスタンス**として
|
||||
連鎖適用されます。同じエフェクトを複数回重ねて適用することもできます。
|
||||
- エフェクトは、スクリプトが生成した画像(図形やピクセル)または入力画像に対して、
|
||||
YMM4 本体と同じ `SetInput` → `Update` → `Output` のチェーンで適用されます。
|
||||
- パラメータはフレームごとに再評価されるため、`obj.time` などに応じて値を計算すれば
|
||||
エフェクトのパラメータをアニメーションさせられます。
|
||||
- シェーダーは AviUtl ExEdit2 と同じ記法の複数行コメントで定義します。--[[pixelshader@登録名: で始まるコメントに HLSL を記述し、登録名がエントリーポイントの関数名になります。1 つのスクリプトに複数のシェーダーを定義できます。
|
||||
- 出力先は "object"、"tempbuffer"、"cache:名前"、"framebuffer" に対応します。"tempbuffer" と "cache:名前" のバッファが存在しない場合は、オブジェクト画像と同じサイズで自動生成します。
|
||||
- リソースは参照するバッファ名の配列で、シェーダーリソース t0~t7 に設定されます。最大 8 個です。1 つの場合は文字列で直接指定できます。"random" を指定すると 0.0~1.0 の乱数値を持つ 256x256 の R32_FLOAT 領域になり、乱数の内容はフレームを跨いで変わりません。存在しないバッファ名を指定した場合は 1x1 の透明画像が設定されます。
|
||||
- 定数は数値の配列で、定数バッファ b0 へ float の配列として詰めて設定されます。最大 1024 個です。
|
||||
- blend は出力先への合成方法です。"copy" はそのまま、"mask" はα値のみ乗算、"draw" はアルファブレンド、"add" は加算で、省略時は "copy" です。
|
||||
- sampler は SamplerState s0 の種別で、"clip"、"clamp"、"loop"、"mirror"、"dot" に対応します。省略時は未設定です。
|
||||
- ピクセルシェーダーの入力シグネチャは float4 名前(float4 pos : SV_Position) : SV_Target と、float2 uv : TEXCOORD を加えた形式の 2 種類を使用できます。uv は描画範囲が 0.0~1.0 になるように設定されます。
|
||||
- 実行は Direct3D 11 の機能レベル 11_0 で行い、シェーダーモデルは ps_5_0 です。ハードウェアのデバイスを作成できない環境では WARP ラスタライザーへ、それも作成できない環境では呼び出しのスキップへ自動的に切り替わります。スキップした場合、画像は変化しません。
|
||||
- HLSL のコンパイルエラーはスクリプトの実行時エラーとして報告し、エディターの診断へ波線とエラー内容を表示します。未定義の登録名、綴りの誤った blend、綴りの誤った sampler も実行時エラーとして報告します。
|
||||
- MoonSharp とネイティブの両方の実行エンジンで動作します。ディレクティブを書かない自動選択のスクリプトでも動作します。シェーダーの実行自体は、どちらのエンジンでもホスト側の GPU で行われます。
|
||||
- 構文拡張の変換はシェーダー定義のコメントをそのまま保持するため、独自記法とシェーダー定義は同じスクリプトの中で併用できます。
|
||||
|
||||
### 合成モードの数値指定
|
||||
|
||||
blend 引数へ数値を渡す指定を追加しました。obj.setoption("blend", 番号) と同じ並びの番号で、シェーダーの出力を YMM4 の合成モードで出力先へ合成します。通常、乗算、スクリーン、オーバーレイなどの全種類を使用でき、合成の実装は obj.draw の合成モードと同じ経路を通るため、結果も一致します。範囲外の番号は通常になります。
|
||||
|
||||
### 仮想フレームバッファ
|
||||
|
||||
YMM4 のエフェクトは自分のオブジェクトの画像しか受け取れないため、AviUtl の "framebuffer" が指す背景込みの画面は取得できません。そこで、シーンサイズの仮想フレームバッファとして再解釈して対応しました。
|
||||
|
||||
- 内容は、シーンサイズの透明な領域へ、オブジェクトを現在の位置・拡大率・縦横比・不透明度で合成した画像です。回転は反映しません。背景は含まれません。内容はフレームごとに作り直します。
|
||||
- obj.pixelshader のリソースに "framebuffer" を指定すると、この画像がシェーダーリソースとして設定されます。
|
||||
- obj.pixelshader の出力先に "framebuffer" を指定すると、シェーダーはシーンサイズの領域へ描画し、その結果でオブジェクト画像を置き換えます。オブジェクトが既定の位置と拡大率であれば、置き換え後の画像はシーン全体を覆います。
|
||||
- obj.copybuffer のコピー元に "frm" を指定できるようになりました。コピー先には指定できません。
|
||||
|
||||
---
|
||||
|
||||
## 注意事項
|
||||
## 互換性・後方互換
|
||||
|
||||
- `obj.effect`(および `obj.load`)は描画系 API のため MoonSharp エンジンで実行されます。
|
||||
ネイティブ(LuaJIT)経路ではエフェクトは適用されません。
|
||||
- エフェクトの登録名はローカライズされるため、指定名は実行環境の表示言語に依存する
|
||||
場合があります。言語に依存させたくない場合は、英語の別名やプロパティ名を用いて
|
||||
ください。
|
||||
- Animation パラメータは定数値として設定されます。キーフレーム曲線は指定できません。
|
||||
時間変化させたい場合はスクリプト側で値を計算してください。
|
||||
- 指定したエフェクトが見つからない、または生成・更新に失敗した場合、その要求は安全に
|
||||
スキップされ、画像はそのまま通過します。描画は停止しません。
|
||||
- 対象エフェクトの解決は導入状況に依存します。ユーザー製エフェクトは未導入の場合、
|
||||
名前が解決されずスキップされます。
|
||||
- obj.pixelshader は新規の API です。既存のスクリプトはそのまま動作し、実行結果も変わりません。
|
||||
- obj.setoption("drawtarget", "tempbuffer") 使用時の obj.draw の合成は、従来どおり通常の合成です。blend の設定はフレームバッファへの描画にのみ適用されます。
|
||||
- ネイティブエンジンのワーカープロセスは、シェーダーの受け渡しに使う共有メモリ領域を常時確保するようになりました。確保量は約 32MB 増えますが、使用しない限り物理メモリは消費しません。
|
||||
- v1.14.0 までの仕様に変更はありません。
|
||||
|
||||
---
|
||||
|
||||
## 内部実装
|
||||
|
||||
- スクリプトの `obj.effect` 呼び出しを実行コンテキストに記録し、スクリプト実行後に
|
||||
描画スレッドで Direct2D エフェクトチェーンとして適用する仕組みを追加しました。
|
||||
- `EffectFactories.VideoEffectFactories` を登録名・別名で索引し、リフレクションで
|
||||
対象プロパティを解決してパラメータを設定します。
|
||||
- YMM4 の API 変更に対する多層フォールバックを実装しました。レジストリ構築、
|
||||
パラメータ解決、各エフェクトの生成・更新・適用をそれぞれ例外隔離し、失敗時は
|
||||
当該エフェクトをスキップして元画像を通過させます(描画自体は停止しません)。
|
||||
- シェーダー定義の解析器を互換層に新設しました。行頭の --[[pixelshader@ を走査し、同名の定義は初出を優先します。名前@スクリプト名 の形式はローカルの名前で解決します。
|
||||
- シェーダー実行の契約をランタイムに新設しました。合成指定は種別と合成番号を持つ構造体で、リソース・サンプラー・実行結果の型と合わせて、実行器の実装をエンジンから分離しています。
|
||||
- Direct3D 11 の実行器はプラグイン本体に置き、自前のデバイスを保持します。頂点シェーダーは SV_VertexID から生成するフルスクリーン三角形で、コンパイル結果はソースとエントリーポイントの組で、テクスチャはサイズの組でそれぞれ再利用します。デバイスロストの際は 3 回まで再生成し、それを超えると無効化して警告を 1 回だけ記録します。
|
||||
- 数値指定の合成は、シェーダーを copy で描画した結果を読み戻し、既存のバッファ合成器で出力先へ合成する 2 段構成です。ハードウェアのバッファ合成器が合成モードを Direct2D で適用するようになりました。ソフトウェアの合成へ切り替わった環境では通常の合成になり、切り替わりを警告として 1 回だけ記録します。
|
||||
- ネイティブエンジンでは、共有メモリの末尾へシェーダー交換領域を追加しました。領域はメタ情報、定数、画像域から成り、ワーカーがリソースを 1 枚ずつ交換域へ書いてホストへ引き渡し、ホストが実行して結果を書き戻します。オブジェクト画像が対象の場合は既存のピクセル領域を直接読み書きし、転送を省きます。領域は 8 バイト整列で確保し、ワーカーの容量判定も領域込みで行います。
|
||||
- 両エンジンとも、リソース・定数・転送先の受け渡しには再利用の配列を使い、フレームごとのメモリ確保を発生させません。
|
||||
- 仮想フレームバッファは、参照時に一度だけ構築してフレーム内で再利用します。ネイティブエンジンではワーカー側に同じ構築処理を持ち、スクリプト実行前の初期値から合成するため、両エンジンの内容が一致します。
|
||||
- ドキュメントは付属の 8 言語、サイトの obj の関数のページ、README を更新しました。
|
||||
- テストは 3259 件です。v1.14.0 の 3215 件から、シェーダー定義の解析、MoonSharp 束縛の引数と各エラー、数値指定の合成、仮想フレームバッファの参照と置き換え、ネイティブの往復でのリソース転送と書き戻し、コンパイルエラーの伝播、実行器が無い環境でのスキップ、構文拡張の変換がシェーダー定義を保持すること、および自動振り分けの検証を追加しました。
|
||||
@@ -1,5 +1,5 @@
|
||||
========================================
|
||||
Luaスクリプト for YMM4 v1.7.0
|
||||
Luaスクリプト for YMM4 v1.15.0
|
||||
========================================
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||
ピクセルを直接制御できるプラグインです。
|
||||
@@ -26,7 +26,9 @@ obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動
|
||||
|
||||
- スクリプトエラー時の挙動: コンパイルエラーまたは実行時エラーが発生した場合、
|
||||
そのフレームでの座標・透明度・回転・ピクセルの変更は適用されず、入力された
|
||||
元の状態がそのまま出力されます。エラー内容はログへ出力されます。
|
||||
元の状態がそのまま出力されます。エラー内容はログへ出力されるほか、スクリプト
|
||||
エディタの該当箇所へ赤い波線が表示され、ポイントするとエラー内容をツールチップ
|
||||
で確認できます。
|
||||
|
||||
- ファイルアクセスの制限: スクリプトからのファイル読み込みは許可されておらず、
|
||||
io・os等のモジュールも有効化されていません。
|
||||
|
||||
@@ -73,6 +73,10 @@ jobs:
|
||||
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/MoonSharp.Interpreter.dll" "$stageRoot/"
|
||||
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
|
||||
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<aviUtlCompat>
|
||||
<effect engine="both" names="ぼかし" target="GaussianBlurEffect">
|
||||
<param name="範囲" property="Blur" scale="0.5" />
|
||||
<param name="サイズ固定" property="IsHardBorderMode" />
|
||||
</effect>
|
||||
<effect engine="both" names="境界ぼかし" target="BorderBlurEffect">
|
||||
<param name="範囲" property="Blur" />
|
||||
</effect>
|
||||
<effect engine="both" names="方向ブラー" target="DirectionalBlurEffect">
|
||||
<param name="範囲" property="StandardDeviation" scale="0.5" />
|
||||
<param name="角度" property="Angle" />
|
||||
<param name="サイズ固定" property="IsHardBorderMode" />
|
||||
</effect>
|
||||
<effect engine="both" names="放射ブラー" target="RadialBlurEffect">
|
||||
<param name="範囲" property="Blur" />
|
||||
<param name="X" property="X" />
|
||||
<param name="Y" property="Y" />
|
||||
<param name="サイズを固定" property="IsHardBorderMode" />
|
||||
</effect>
|
||||
<effect engine="both" names="閃光" target="RadialLightEffect">
|
||||
<param name="範囲" property="Value" />
|
||||
<param name="X" property="X" />
|
||||
<param name="Y" property="Y" />
|
||||
<param name="サイズを固定" property="IsHardBorderMode" />
|
||||
</effect>
|
||||
<effect engine="both" names="クロマキー" target="ChromaKeyEffect">
|
||||
<param name="色相範囲" property="Tolerance" scale="0.390625" />
|
||||
<param name="境界補正" property="Feather" />
|
||||
</effect>
|
||||
<effect engine="both" names="クリッピング" target="CropEffect">
|
||||
<param name="上" property="Top" />
|
||||
<param name="下" property="Bottom" />
|
||||
<param name="左" property="Left" />
|
||||
<param name="右" property="Right" />
|
||||
<param name="中心の位置を変更" property="IsCentering" />
|
||||
</effect>
|
||||
<effect engine="both" names="斜めクリッピング" target="CropByAngleEffect">
|
||||
<param name="中心X" property="X" />
|
||||
<param name="中心Y" property="Y" />
|
||||
<param name="角度" property="Angle" />
|
||||
<param name="ぼかし" property="Blur" scale="0.5" />
|
||||
<param name="幅" property="Width" />
|
||||
</effect>
|
||||
<effect engine="both" names="領域拡張" target="MarginEffect">
|
||||
<param name="上" property="Top" />
|
||||
<param name="下" property="Bottom" />
|
||||
<param name="左" property="Left" />
|
||||
<param name="右" property="Right" />
|
||||
</effect>
|
||||
<effect engine="both" names="座標" target="DrawPositionEffect">
|
||||
<param name="X" property="X" />
|
||||
<param name="Y" property="Y" />
|
||||
<param name="Z" property="Z" />
|
||||
</effect>
|
||||
<effect engine="both" names="回転" target="RotateEffect">
|
||||
<param name="X" property="X" />
|
||||
<param name="Y" property="Y" />
|
||||
<param name="Z" property="Z" />
|
||||
</effect>
|
||||
<effect engine="both" names="リサイズ" target="ZoomEffect">
|
||||
<param name="拡大率" property="Zoom" />
|
||||
<param name="X" property="ZoomX" />
|
||||
<param name="Y" property="ZoomY" />
|
||||
<param name="補間なし" property="IsNearestNeighbor" />
|
||||
</effect>
|
||||
<effect engine="both" names="画像ループ" target="TilingEffect">
|
||||
<param name="横回数" property="X" />
|
||||
<param name="縦回数" property="Y" />
|
||||
</effect>
|
||||
<effect engine="both" names="極座標変換" target="PolarTransformEffect">
|
||||
<param name="中心幅" property="CoreWidth" />
|
||||
<param name="渦巻" property="TwistAngle" scale="360" />
|
||||
</effect>
|
||||
<effect engine="both" names="グラデーション" target="GradientEffect">
|
||||
<param name="強さ" property="Opacity" />
|
||||
<param name="中心X" property="X" />
|
||||
<param name="中心Y" property="Y" />
|
||||
<param name="角度" property="Rotation" />
|
||||
<param name="幅" property="Size" />
|
||||
</effect>
|
||||
<effect engine="both" names="単色化" target="MonocolorizationEffect">
|
||||
<param name="強さ" property="Strength" />
|
||||
<param name="輝度を保持する" property="KeepBrightness" />
|
||||
</effect>
|
||||
<effect engine="both" names="縁取り" target="OutlineEffect">
|
||||
<param name="サイズ" property="StrokeThickness" />
|
||||
<param name="ぼかし" property="Blur" />
|
||||
</effect>
|
||||
<effect engine="both" names="反転" target="InvertEffect" />
|
||||
<effect engine="both" names="モザイク" target="MosaicEffect">
|
||||
<param name="サイズ" property="Size" />
|
||||
</effect>
|
||||
<effect engine="both" names="ディスプレイスメントマップ" target="DisplacementMapEffect">
|
||||
<param name="ぼかし" property="Blur" scale="0.5" />
|
||||
</effect>
|
||||
<effect engine="both" names="動画ファイル合成" target="TextureEffect">
|
||||
<param name="X" property="X" />
|
||||
<param name="Y" property="Y" />
|
||||
<param name="拡大率" property="Zoom" />
|
||||
</effect>
|
||||
<effect engine="both" names="色調補正" target="ColorCorrectionEffect">
|
||||
<param name="明るさ" property="Lightness" />
|
||||
<param name="コントラスト" property="Contrast" />
|
||||
<param name="色相" property="HueRotation" />
|
||||
<param name="輝度" property="Brightness" />
|
||||
<param name="彩度" property="Saturation" />
|
||||
</effect>
|
||||
<effect engine="both" names="色ずれ" target="ColorShiftEffect">
|
||||
<param name="ずれ幅" property="Shift" />
|
||||
<param name="角度" property="Angle" />
|
||||
<param name="強さ" property="Strength" />
|
||||
</effect>
|
||||
</aviUtlCompat>
|
||||
@@ -0,0 +1,137 @@
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal static class AviUtlGlobalFunctions
|
||||
{
|
||||
public static int BitOr(double a, double b) => ToBitOperand(a) | ToBitOperand(b);
|
||||
|
||||
public static int BitAnd(double a, double b) => ToBitOperand(a) & ToBitOperand(b);
|
||||
|
||||
public static int BitXor(double a, double b) => ToBitOperand(a) ^ ToBitOperand(b);
|
||||
|
||||
public static int BitShift(double value, double shift)
|
||||
{
|
||||
int v = ToBitOperand(value);
|
||||
int n = ToBitOperand(shift);
|
||||
return n >= 0 ? v << n : v >> -n;
|
||||
}
|
||||
|
||||
public static int ToBitOperand(double value)
|
||||
{
|
||||
if (double.IsNaN(value))
|
||||
return 0;
|
||||
if (value <= int.MinValue)
|
||||
return int.MinValue;
|
||||
if (value >= int.MaxValue)
|
||||
return int.MaxValue;
|
||||
return (int)Math.Ceiling(value - 0.5);
|
||||
}
|
||||
|
||||
public static int RgbCompose(double r, double g, double b) =>
|
||||
(ToColorChannel(r) << 16) | (ToColorChannel(g) << 8) | ToColorChannel(b);
|
||||
|
||||
public static void RgbComponents(double color, out int r, out int g, out int b)
|
||||
{
|
||||
int c = ToColor(color);
|
||||
r = (c >> 16) & 0xFF;
|
||||
g = (c >> 8) & 0xFF;
|
||||
b = c & 0xFF;
|
||||
}
|
||||
|
||||
public static int RgbInterpolate(double r1, double g1, double b1, double r2, double g2, double b2, double t) =>
|
||||
RgbCompose(r1 + (r2 - r1) * t, g1 + (g2 - g1) * t, b1 + (b2 - b1) * t);
|
||||
|
||||
public static int HsvCompose(double h, double s, double v)
|
||||
{
|
||||
h = WrapHue(h);
|
||||
s = ClampRatio(s);
|
||||
v = ClampRatio(v);
|
||||
|
||||
double c = v * s;
|
||||
double x = c * (1d - Math.Abs(h / 60d % 2d - 1d));
|
||||
double m = v - c;
|
||||
int sector = (int)Math.Floor(h / 60d);
|
||||
|
||||
double r, g, b;
|
||||
if (sector == 0) { r = c; g = x; b = 0d; }
|
||||
else if (sector == 1) { r = x; g = c; b = 0d; }
|
||||
else if (sector == 2) { r = 0d; g = c; b = x; }
|
||||
else if (sector == 3) { r = 0d; g = x; b = c; }
|
||||
else if (sector == 4) { r = x; g = 0d; b = c; }
|
||||
else { r = c; g = 0d; b = x; }
|
||||
|
||||
return (ToColorChannel(RoundHalfUp((r + m) * 255d)) << 16) |
|
||||
(ToColorChannel(RoundHalfUp((g + m) * 255d)) << 8) |
|
||||
ToColorChannel(RoundHalfUp((b + m) * 255d));
|
||||
}
|
||||
|
||||
public static void HsvComponents(double color, out int h, out int s, out int v)
|
||||
{
|
||||
RgbComponents(color, out int r, out int g, out int b);
|
||||
double rf = r / 255d;
|
||||
double gf = g / 255d;
|
||||
double bf = b / 255d;
|
||||
|
||||
double max = Math.Max(rf, Math.Max(gf, bf));
|
||||
double min = Math.Min(rf, Math.Min(gf, bf));
|
||||
double delta = max - min;
|
||||
|
||||
double hue = 0d;
|
||||
if (delta > 0d)
|
||||
{
|
||||
if (max == rf)
|
||||
hue = 60d * (((gf - bf) / delta % 6d + 6d) % 6d);
|
||||
else if (max == gf)
|
||||
hue = 60d * ((bf - rf) / delta + 2d);
|
||||
else
|
||||
hue = 60d * ((rf - gf) / delta + 4d);
|
||||
}
|
||||
|
||||
h = (int)RoundHalfUp(hue);
|
||||
s = (int)RoundHalfUp(max > 0d ? delta / max * 100d : 0d);
|
||||
v = (int)RoundHalfUp(max * 100d);
|
||||
}
|
||||
|
||||
public static int HsvInterpolate(double h1, double s1, double v1, double h2, double s2, double v2, double t) =>
|
||||
HsvCompose(h1 + (h2 - h1) * t, s1 + (s2 - s1) * t, v1 + (v2 - v1) * t);
|
||||
|
||||
private static int ToColorChannel(double value)
|
||||
{
|
||||
if (double.IsNaN(value) || value <= 0d)
|
||||
return 0;
|
||||
if (value >= 255d)
|
||||
return 255;
|
||||
return (int)Math.Floor(value);
|
||||
}
|
||||
|
||||
private static int ToColor(double value)
|
||||
{
|
||||
if (double.IsNaN(value))
|
||||
return 0;
|
||||
if (value <= int.MinValue)
|
||||
value = int.MinValue;
|
||||
else if (value >= int.MaxValue)
|
||||
value = int.MaxValue;
|
||||
long floored = (long)Math.Floor(value);
|
||||
return (int)(floored & 0xFFFFFF);
|
||||
}
|
||||
|
||||
private static double WrapHue(double h)
|
||||
{
|
||||
if (double.IsNaN(h) || double.IsInfinity(h))
|
||||
return 0d;
|
||||
double wrapped = h - Math.Floor(h / 360d) * 360d;
|
||||
return wrapped >= 360d ? 0d : wrapped;
|
||||
}
|
||||
|
||||
private static double ClampRatio(double value)
|
||||
{
|
||||
if (double.IsNaN(value) || value <= 0d)
|
||||
return 0d;
|
||||
if (value >= 100d)
|
||||
return 1d;
|
||||
return value / 100d;
|
||||
}
|
||||
|
||||
private static double RoundHalfUp(double value) => Math.Floor(value + 0.5);
|
||||
}
|
||||
}
|
||||
差分なしでファイル名を変更。
@@ -0,0 +1,26 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.15.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="LuaScript" />
|
||||
<InternalsVisibleTo Include="LuaScript.Runtime" />
|
||||
<InternalsVisibleTo Include="LuaScript.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\LuaScript.Kernel\LuaScript.Kernel.csproj" />
|
||||
<ProjectReference Include="..\LuaScript.Generator\LuaScript.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="AviUtlCompatMap.xml" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,138 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal sealed class AviUtlCompatMap
|
||||
{
|
||||
private const string ResourceSuffix = "AviUtlCompatMap.xml";
|
||||
|
||||
private readonly Dictionary<string, List<AviUtlEffectMapping>> _effects;
|
||||
|
||||
public static AviUtlCompatMap Default { get; } = Load();
|
||||
|
||||
private AviUtlCompatMap(Dictionary<string, List<AviUtlEffectMapping>> effects)
|
||||
{
|
||||
_effects = effects;
|
||||
}
|
||||
|
||||
public bool TryResolve(string name, AviUtlEngine target, out AviUtlEffectMapping mapping)
|
||||
{
|
||||
mapping = null!;
|
||||
if (string.IsNullOrEmpty(name) || !_effects.TryGetValue(Normalize(name), out var candidates))
|
||||
return false;
|
||||
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
if (candidate.Engine.Includes(target))
|
||||
{
|
||||
mapping = candidate;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static AviUtlEngine ResolveTarget(string? script)
|
||||
{
|
||||
if (string.IsNullOrEmpty(script))
|
||||
return AviUtlEngine.AviUtl;
|
||||
|
||||
foreach (var raw in ScriptParserHelper.SplitLines(script))
|
||||
{
|
||||
var line = raw.Trim();
|
||||
if (!line.StartsWith("--!", System.StringComparison.Ordinal))
|
||||
continue;
|
||||
var token = line[3..].Trim().ToLowerInvariant();
|
||||
if (token == "aviutl2")
|
||||
return AviUtlEngine.AviUtl2;
|
||||
if (token == "aviutl")
|
||||
return AviUtlEngine.AviUtl;
|
||||
}
|
||||
return AviUtlEngine.AviUtl;
|
||||
}
|
||||
|
||||
private static AviUtlCompatMap Load()
|
||||
{
|
||||
var effects = new Dictionary<string, List<AviUtlEffectMapping>>(StringComparer.OrdinalIgnoreCase);
|
||||
try
|
||||
{
|
||||
using var stream = OpenResource();
|
||||
if (stream is not null)
|
||||
Populate(effects, stream);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
return new AviUtlCompatMap(effects);
|
||||
}
|
||||
|
||||
private static void Populate(Dictionary<string, List<AviUtlEffectMapping>> effects, Stream stream)
|
||||
{
|
||||
var root = XDocument.Load(stream).Root;
|
||||
if (root is null)
|
||||
return;
|
||||
|
||||
foreach (var element in root.Elements("effect"))
|
||||
{
|
||||
var target = (string?)element.Attribute("target");
|
||||
if (string.IsNullOrWhiteSpace(target))
|
||||
continue;
|
||||
|
||||
if (!AviUtlEngineExtensions.TryParse(((string?)element.Attribute("engine"))?.Trim().ToLowerInvariant(), out var engine))
|
||||
engine = AviUtlEngine.Both;
|
||||
|
||||
var parameters = element.Elements("param").Select(ParseParameter).ToArray();
|
||||
var mapping = new AviUtlEffectMapping(engine, target.Trim(), parameters);
|
||||
|
||||
foreach (var name in SplitNames((string?)element.Attribute("names")))
|
||||
{
|
||||
if (!effects.TryGetValue(name, out var list))
|
||||
{
|
||||
list = [];
|
||||
effects[name] = list;
|
||||
}
|
||||
list.Add(mapping);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static AviUtlParameterMapping ParseParameter(XElement element)
|
||||
{
|
||||
var source = ((string?)element.Attribute("name") ?? string.Empty).Trim();
|
||||
var property = ((string?)element.Attribute("property") ?? string.Empty).Trim();
|
||||
double scale = ParseDouble((string?)element.Attribute("scale"), 1d);
|
||||
double offset = ParseDouble((string?)element.Attribute("offset"), 0d);
|
||||
return new AviUtlParameterMapping(source, property, scale, offset);
|
||||
}
|
||||
|
||||
private static IEnumerable<string> SplitNames(string? names)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(names))
|
||||
yield break;
|
||||
foreach (var part in names.Split(','))
|
||||
{
|
||||
var trimmed = part.Trim();
|
||||
if (trimmed.Length != 0)
|
||||
yield return Normalize(trimmed);
|
||||
}
|
||||
}
|
||||
|
||||
private static double ParseDouble(string? value, double fallback) =>
|
||||
double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double result) ? result : fallback;
|
||||
|
||||
private static string Normalize(string value) => value.Trim().ToLowerInvariant();
|
||||
|
||||
private static Stream? OpenResource()
|
||||
{
|
||||
var assembly = typeof(AviUtlCompatMap).Assembly;
|
||||
var name = assembly.GetManifestResourceNames()
|
||||
.FirstOrDefault(n => n.EndsWith(ResourceSuffix, System.StringComparison.Ordinal));
|
||||
return name is null ? null : assembly.GetManifestResourceStream(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal sealed class AviUtlEffectMapping
|
||||
{
|
||||
private readonly Dictionary<string, AviUtlParameterMapping> _parameters;
|
||||
|
||||
public AviUtlEngine Engine { get; }
|
||||
|
||||
public string TargetType { get; }
|
||||
|
||||
public AviUtlEffectMapping(AviUtlEngine engine, string targetType, IEnumerable<AviUtlParameterMapping> parameters)
|
||||
{
|
||||
Engine = engine;
|
||||
TargetType = targetType;
|
||||
_parameters = new Dictionary<string, AviUtlParameterMapping>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var parameter in parameters)
|
||||
_parameters[parameter.Source] = parameter;
|
||||
}
|
||||
|
||||
public bool TryGetParameter(string source, out AviUtlParameterMapping mapping) =>
|
||||
_parameters.TryGetValue(source, out mapping);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal enum AviUtlEngine
|
||||
{
|
||||
AviUtl,
|
||||
AviUtl2,
|
||||
Both,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal static class AviUtlEngineExtensions
|
||||
{
|
||||
public static bool Includes(this AviUtlEngine scope, AviUtlEngine target) =>
|
||||
scope == AviUtlEngine.Both || scope == target;
|
||||
|
||||
public static bool TryParse(string? value, out AviUtlEngine engine)
|
||||
{
|
||||
switch (value)
|
||||
{
|
||||
case "aviutl":
|
||||
engine = AviUtlEngine.AviUtl;
|
||||
return true;
|
||||
case "aviutl2":
|
||||
engine = AviUtlEngine.AviUtl2;
|
||||
return true;
|
||||
case "both":
|
||||
engine = AviUtlEngine.Both;
|
||||
return true;
|
||||
default:
|
||||
engine = AviUtlEngine.AviUtl;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal readonly record struct AviUtlParameterMapping(string Source, string Property, double Scale, double Offset)
|
||||
{
|
||||
public double Transform(double value) => value * Scale + Offset;
|
||||
}
|
||||
}
|
||||
差分なしでファイル名を変更。
+4
-51
@@ -43,26 +43,8 @@ namespace LuaScript.Compat
|
||||
if (string.IsNullOrEmpty(source))
|
||||
return layout;
|
||||
|
||||
var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
|
||||
|
||||
int sectionStart = 0;
|
||||
int sectionEnd = lines.Length;
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
if (!IsSectionHeader(lines[i]))
|
||||
continue;
|
||||
sectionStart = i + 1;
|
||||
sectionEnd = lines.Length;
|
||||
for (int j = sectionStart; j < lines.Length; j++)
|
||||
{
|
||||
if (IsSectionHeader(lines[j]))
|
||||
{
|
||||
sectionEnd = j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
var lines = ScriptParserHelper.SplitLines(source);
|
||||
ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
|
||||
|
||||
for (int i = sectionStart; i < sectionEnd; i++)
|
||||
layout.ParseLine(lines[i]);
|
||||
@@ -72,21 +54,8 @@ namespace LuaScript.Compat
|
||||
|
||||
private void ParseLine(string line)
|
||||
{
|
||||
int i = SkipSpaces(line, 0);
|
||||
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
|
||||
if (!ScriptParserHelper.TryParseDirective(line, out string name, out string content))
|
||||
return;
|
||||
i += 2;
|
||||
if (i < line.Length && line[i] == '!')
|
||||
return;
|
||||
|
||||
int nameStart = i;
|
||||
while (i < line.Length && IsNameChar(line[i]))
|
||||
i++;
|
||||
if (i >= line.Length || line[i] != ':')
|
||||
return;
|
||||
|
||||
string name = line.Substring(nameStart, i - nameStart);
|
||||
string content = line.Substring(i + 1);
|
||||
|
||||
if (name.StartsWith("track", StringComparison.OrdinalIgnoreCase) &&
|
||||
TryGetIndex(name, 5, MaxTracks, out int trackIndex))
|
||||
@@ -174,27 +143,11 @@ namespace LuaScript.Compat
|
||||
|
||||
private static string FirstToken(string content)
|
||||
{
|
||||
int start = SkipSpaces(content, 0);
|
||||
int start = ScriptParserHelper.SkipSpaces(content, 0);
|
||||
int i = start;
|
||||
while (i < content.Length && content[i] != ',' && content[i] != ' ' && content[i] != '\t')
|
||||
i++;
|
||||
return content.Substring(start, i - start);
|
||||
}
|
||||
|
||||
private static bool IsSectionHeader(string line)
|
||||
{
|
||||
int i = SkipSpaces(line, 0);
|
||||
return i < line.Length && line[i] == '@';
|
||||
}
|
||||
|
||||
private static int SkipSpaces(string text, int index)
|
||||
{
|
||||
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
|
||||
index++;
|
||||
return index;
|
||||
}
|
||||
|
||||
private static bool IsNameChar(char c) =>
|
||||
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
|
||||
}
|
||||
}
|
||||
@@ -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 == '_';
|
||||
}
|
||||
}
|
||||
@@ -13,75 +13,49 @@ namespace LuaScript.Compat
|
||||
Param,
|
||||
}
|
||||
|
||||
public static string Transform(string source)
|
||||
public static string Transform(string source) => TransformWithMap(source).Code;
|
||||
|
||||
public static (string Code, int[] LineMap, int[] ChangedLines) TransformWithMap(string source)
|
||||
{
|
||||
if (string.IsNullOrEmpty(source))
|
||||
return source;
|
||||
return (source, [], []);
|
||||
|
||||
var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
|
||||
|
||||
int sectionStart = 0;
|
||||
int sectionEnd = lines.Length;
|
||||
bool hasSection = false;
|
||||
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
if (!IsSectionHeader(lines[i]))
|
||||
continue;
|
||||
|
||||
hasSection = true;
|
||||
sectionStart = i + 1;
|
||||
sectionEnd = lines.Length;
|
||||
for (int j = sectionStart; j < lines.Length; j++)
|
||||
{
|
||||
if (IsSectionHeader(lines[j]))
|
||||
{
|
||||
sectionEnd = j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
var lines = ScriptParserHelper.SplitLines(source);
|
||||
bool hasSection = ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
|
||||
|
||||
var prelude = new List<string>();
|
||||
for (int i = sectionStart; i < sectionEnd; i++)
|
||||
AppendDeclarations(lines[i], prelude);
|
||||
|
||||
if (!hasSection && prelude.Count == 0)
|
||||
return source;
|
||||
{
|
||||
var (code, changed) = LuaSyntaxExtensions.RewriteWithMap(source);
|
||||
return (code, [], changed);
|
||||
}
|
||||
|
||||
var builder = new StringBuilder(source.Length + 64);
|
||||
var lineMap = new int[prelude.Count + (sectionEnd - sectionStart)];
|
||||
int row = 0;
|
||||
|
||||
foreach (var declaration in prelude)
|
||||
{
|
||||
builder.Append(declaration).Append('\n');
|
||||
lineMap[row++] = -1;
|
||||
}
|
||||
for (int i = sectionStart; i < sectionEnd; i++)
|
||||
{
|
||||
builder.Append(lines[i]).Append('\n');
|
||||
lineMap[row++] = i;
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static bool IsSectionHeader(string line)
|
||||
{
|
||||
int i = SkipSpaces(line, 0);
|
||||
return i < line.Length && line[i] == '@';
|
||||
var (rewritten, changedLines) = LuaSyntaxExtensions.RewriteWithMap(builder.ToString());
|
||||
return (rewritten, lineMap, changedLines);
|
||||
}
|
||||
|
||||
private static void AppendDeclarations(string line, List<string> prelude)
|
||||
{
|
||||
int i = SkipSpaces(line, 0);
|
||||
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
|
||||
if (!ScriptParserHelper.TryParseDirective(line, out string name, out string content))
|
||||
return;
|
||||
i += 2;
|
||||
if (i < line.Length && line[i] == '!')
|
||||
return;
|
||||
|
||||
int nameStart = i;
|
||||
while (i < line.Length && IsNameChar(line[i]))
|
||||
i++;
|
||||
if (i >= line.Length || line[i] != ':')
|
||||
return;
|
||||
|
||||
string name = line.Substring(nameStart, i - nameStart);
|
||||
string content = line.Substring(i + 1);
|
||||
|
||||
switch (Classify(name))
|
||||
{
|
||||
@@ -125,15 +99,5 @@ namespace LuaScript.Compat
|
||||
if (trimmed.Length != 0)
|
||||
prelude.Add(trimmed);
|
||||
}
|
||||
|
||||
private static int SkipSpaces(string text, int index)
|
||||
{
|
||||
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
|
||||
index++;
|
||||
return index;
|
||||
}
|
||||
|
||||
private static bool IsNameChar(char c) =>
|
||||
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
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) 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();
|
||||
}
|
||||
}
|
||||
|
||||
return context.Changed ? (context.Serialize(), context.ChangedLines) : (source, []);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using LuaScript.Compat.Syntax;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal readonly struct ScriptParameterUsage
|
||||
{
|
||||
private readonly HashSet<string>? _members;
|
||||
private readonly bool _color;
|
||||
|
||||
private ScriptParameterUsage(HashSet<string>? members, bool color)
|
||||
{
|
||||
_members = members;
|
||||
_color = color;
|
||||
}
|
||||
|
||||
public static readonly ScriptParameterUsage None = default;
|
||||
|
||||
public bool Color => _color;
|
||||
|
||||
public bool Uses(string member) => _members is not null && _members.Contains(member);
|
||||
|
||||
public bool Check0 => Uses("check0");
|
||||
public bool Check1 => Uses("check1");
|
||||
public bool Check2 => Uses("check2");
|
||||
public bool Check3 => Uses("check3");
|
||||
|
||||
public bool Check(int index) => (uint)index < 4 && Uses("check" + (char)('0' + index));
|
||||
|
||||
public bool Slider(int index) => (uint)index < 4 && Uses("slider" + (char)('0' + index));
|
||||
|
||||
public static ScriptParameterUsage Detect(string? script)
|
||||
{
|
||||
if (string.IsNullOrEmpty(script))
|
||||
return None;
|
||||
|
||||
var tokens = LuaSyntaxLexer.Tokenize(script);
|
||||
|
||||
HashSet<string>? members = null;
|
||||
bool color = false;
|
||||
|
||||
for (int i = 0; i < tokens.Count; i++)
|
||||
{
|
||||
var token = tokens[i];
|
||||
if (token.Kind != LuaSyntaxTokenKind.Name)
|
||||
continue;
|
||||
|
||||
if (token.Text == "color")
|
||||
{
|
||||
int previous = PreviousSignificant(tokens, i);
|
||||
if (previous < 0 || !tokens[previous].IsOperator("."))
|
||||
color = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (token.Text == "obj")
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal static class ScriptParserHelper
|
||||
{
|
||||
public static bool IsSectionHeader(string line)
|
||||
{
|
||||
int i = SkipSpaces(line, 0);
|
||||
return i < line.Length && line[i] == '@';
|
||||
}
|
||||
|
||||
public static int SkipSpaces(string text, int index)
|
||||
{
|
||||
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
|
||||
index++;
|
||||
return index;
|
||||
}
|
||||
|
||||
public static bool IsNameChar(char c) =>
|
||||
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
|
||||
|
||||
public static string[] SplitLines(string source) =>
|
||||
source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
|
||||
|
||||
public static bool TryFindSection(string[] lines, out int start, out int end)
|
||||
{
|
||||
start = 0;
|
||||
end = lines.Length;
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
if (!IsSectionHeader(lines[i]))
|
||||
continue;
|
||||
start = i + 1;
|
||||
end = lines.Length;
|
||||
for (int j = start; j < lines.Length; j++)
|
||||
{
|
||||
if (IsSectionHeader(lines[j]))
|
||||
{
|
||||
end = j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool TryParseDirective(string line, out string name, out string content)
|
||||
{
|
||||
name = string.Empty;
|
||||
content = string.Empty;
|
||||
int i = SkipSpaces(line, 0);
|
||||
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
|
||||
return false;
|
||||
i += 2;
|
||||
if (i < line.Length && line[i] == '!')
|
||||
return false;
|
||||
|
||||
int nameStart = i;
|
||||
while (i < line.Length && IsNameChar(line[i]))
|
||||
i++;
|
||||
if (i >= line.Length || line[i] != ':')
|
||||
return false;
|
||||
|
||||
name = line.Substring(nameStart, i - nameStart);
|
||||
content = line.Substring(i + 1);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace LuaScript.Compat.Syntax
|
||||
{
|
||||
internal interface ILuaSyntaxRule
|
||||
{
|
||||
bool TryApply(LuaRewriteContext context);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
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 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 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
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 (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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace LuaScript.Compat.Syntax
|
||||
{
|
||||
internal enum LuaSyntaxTokenKind
|
||||
{
|
||||
Whitespace,
|
||||
Newline,
|
||||
Comment,
|
||||
String,
|
||||
Number,
|
||||
Name,
|
||||
Operator,
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
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 (!TryParseRange(context.Input, open, out string replacement, out int end))
|
||||
return false;
|
||||
|
||||
context.EmitRaw(replacement);
|
||||
context.Index = end;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryParseRange(IReadOnlyList<LuaSyntaxToken> input, int open, out string replacement, out int end)
|
||||
{
|
||||
replacement = string.Empty;
|
||||
end = open;
|
||||
|
||||
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;
|
||||
|
||||
string stopExpression = exclusive ? $"({stop}) - 1" : stop;
|
||||
replacement = step is null ? $"= {start}, {stopExpression}" : $"= {start}, {stopExpression}, {step}";
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System.Collections;
|
||||
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal readonly struct EquatableArray<T>(T[] items) : IEquatable<EquatableArray<T>>, IReadOnlyList<T>
|
||||
where T : IEquatable<T>
|
||||
{
|
||||
private readonly T[] _items = items;
|
||||
|
||||
public static readonly EquatableArray<T> Empty = new([]);
|
||||
|
||||
public int Count => _items?.Length ?? 0;
|
||||
|
||||
public T this[int index] => _items[index];
|
||||
|
||||
public bool Equals(EquatableArray<T> other)
|
||||
{
|
||||
var a = _items ?? [];
|
||||
var b = other._items ?? [];
|
||||
if (a.Length != b.Length)
|
||||
return false;
|
||||
for (int i = 0; i < a.Length; i++)
|
||||
{
|
||||
if (!a[i].Equals(b[i]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public override bool Equals(object? obj) => obj is EquatableArray<T> other && Equals(other);
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
var items = _items ?? [];
|
||||
int hash = 17;
|
||||
foreach (var item in items)
|
||||
hash = hash * 31 + (item?.GetHashCode() ?? 0);
|
||||
return hash;
|
||||
}
|
||||
|
||||
public IEnumerator<T> GetEnumerator() => ((IEnumerable<T>)(_items ?? [])).GetEnumerator();
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace System.Runtime.CompilerServices
|
||||
{
|
||||
internal static class IsExternalInit;
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
using System.Text;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
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
|
||||
{
|
||||
private const string TableAttributeName = "LuaScript.Api.LuaTableAttribute";
|
||||
private const string FunctionAttributeName = "LuaScript.Api.LuaFunctionAttribute";
|
||||
private const string ConstantAttributeName = "LuaScript.Api.LuaConstantAttribute";
|
||||
private const string VariableAttributeName = "LuaScript.Api.LuaVariableAttribute";
|
||||
private const string BuiltinAttributeName = "LuaScript.Api.LuaBuiltinAttribute";
|
||||
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
{
|
||||
var tables = context.SyntaxProvider
|
||||
.ForAttributeWithMetadataName(
|
||||
TableAttributeName,
|
||||
static (node, _) => node is ClassDeclarationSyntax,
|
||||
static (ctx, _) => CreateModel(ctx))
|
||||
.Where(static model => model is not null)
|
||||
.Select(static (model, _) => model!);
|
||||
|
||||
var assemblyEntries = context.CompilationProvider
|
||||
.Select(static (compilation, _) => CollectAssemblyEntries(compilation));
|
||||
|
||||
context.RegisterSourceOutput(tables, static (ctx, model) =>
|
||||
{
|
||||
if (model.Functions.Count == 0 && model.Constants.Count == 0 && model.Updates.Count == 0)
|
||||
return;
|
||||
ctx.AddSource(RegistrationHintName(model), SourceText.From(EmitRegistration(model), Encoding.UTF8));
|
||||
});
|
||||
|
||||
var catalog = tables.Collect().Combine(assemblyEntries);
|
||||
context.RegisterSourceOutput(catalog, static (ctx, source) =>
|
||||
{
|
||||
var (models, extra) = source;
|
||||
var entries = models
|
||||
.OrderBy(static m => m.Namespace, StringComparer.Ordinal)
|
||||
.ThenBy(static m => string.Join("+", m.TypeChain.Select(static p => p.Name)), StringComparer.Ordinal)
|
||||
.SelectMany(static m => m.Entries)
|
||||
.Concat(extra)
|
||||
.ToArray();
|
||||
if (entries.Length == 0)
|
||||
return;
|
||||
ctx.AddSource("LuaApiCatalog.g.cs", SourceText.From(EmitCatalog(entries), Encoding.UTF8));
|
||||
});
|
||||
}
|
||||
|
||||
private static LuaTableModel? CreateModel(GeneratorAttributeSyntaxContext context)
|
||||
{
|
||||
if (context.TargetSymbol is not INamedTypeSymbol symbol)
|
||||
return null;
|
||||
|
||||
var tableArguments = context.Attributes[0].ConstructorArguments;
|
||||
string tableName = tableArguments.Length > 0 && tableArguments[0].Value is string name ? name : string.Empty;
|
||||
|
||||
var chain = new List<LuaTypePart>();
|
||||
for (var type = symbol; type is not null; type = type.ContainingType)
|
||||
chain.Insert(0, new LuaTypePart(type.Name, type.IsStatic));
|
||||
|
||||
var entries = new List<(int Position, LuaCatalogEntry Entry)>();
|
||||
foreach (var attribute in symbol.GetAttributes())
|
||||
{
|
||||
string? attributeName = attribute.AttributeClass?.ToDisplayString();
|
||||
if (attributeName is not (VariableAttributeName or BuiltinAttributeName or FunctionAttributeName))
|
||||
continue;
|
||||
var entry = CreateAttributeEntry(attribute, tableName);
|
||||
if (entry is null)
|
||||
continue;
|
||||
int position = attribute.ApplicationSyntaxReference?.Span.Start ?? 0;
|
||||
entries.Add((position, entry));
|
||||
}
|
||||
var classEntries = entries.OrderBy(static e => e.Position).Select(static e => e.Entry).ToList();
|
||||
|
||||
var functions = new List<(int Position, LuaFunctionModel Function, LuaCatalogEntry Entry)>();
|
||||
var constants = new List<(int Position, LuaConstantModel Constant, LuaCatalogEntry Entry)>();
|
||||
var updates = new List<(int Position, LuaUpdateModel Update, LuaCatalogEntry? Entry)>();
|
||||
string contextType = string.Empty;
|
||||
foreach (var member in symbol.GetMembers())
|
||||
{
|
||||
int position = member.DeclaringSyntaxReferences.Length > 0
|
||||
? member.DeclaringSyntaxReferences[0].Span.Start
|
||||
: 0;
|
||||
|
||||
if (member is IMethodSymbol method)
|
||||
{
|
||||
var functionAttribute = FindAttribute(method, FunctionAttributeName);
|
||||
if (functionAttribute is not null)
|
||||
{
|
||||
var function = CreateFunctionModel(method, functionAttribute, out var catalogParameters);
|
||||
if (function is null)
|
||||
continue;
|
||||
functions.Add((position, function, new LuaCatalogEntry(tableName, function.LuaName, true, catalogParameters)));
|
||||
continue;
|
||||
}
|
||||
|
||||
var variableAttribute = FindAttribute(method, VariableAttributeName);
|
||||
if (variableAttribute is not null)
|
||||
{
|
||||
var update = CreateUpdateModel(method, variableAttribute, tableName, ref contextType, out var entry);
|
||||
if (update is not null)
|
||||
updates.Add((position, update, entry));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (member is IFieldSymbol or IPropertySymbol)
|
||||
{
|
||||
var attribute = FindAttribute(member, ConstantAttributeName);
|
||||
if (attribute is null)
|
||||
continue;
|
||||
if (attribute.ConstructorArguments.Length == 0 || attribute.ConstructorArguments[0].Value is not string constantName)
|
||||
continue;
|
||||
constants.Add((
|
||||
position,
|
||||
new LuaConstantModel(constantName, member.Name),
|
||||
new LuaCatalogEntry(tableName, constantName, false, EquatableArray<string>.Empty)));
|
||||
}
|
||||
}
|
||||
|
||||
var orderedMembers = functions
|
||||
.Select(static f => (Position: f.Position, Entry: f.Entry))
|
||||
.Concat(constants.Select(static c => (Position: c.Position, Entry: c.Entry)))
|
||||
.Concat(updates.Where(static u => u.Entry is not null).Select(static u => (Position: u.Position, Entry: u.Entry!)))
|
||||
.OrderBy(static e => e.Position)
|
||||
.Select(static e => e.Entry);
|
||||
|
||||
return new LuaTableModel(
|
||||
symbol.ContainingNamespace.ToDisplayString(),
|
||||
new EquatableArray<LuaTypePart>([.. chain]),
|
||||
tableName,
|
||||
contextType,
|
||||
new EquatableArray<LuaFunctionModel>([.. functions.OrderBy(static f => f.Position).Select(static f => f.Function)]),
|
||||
new EquatableArray<LuaConstantModel>([.. constants.OrderBy(static c => c.Position).Select(static c => c.Constant)]),
|
||||
new EquatableArray<LuaUpdateModel>([.. updates.OrderBy(static u => u.Position).Select(static u => u.Update)]),
|
||||
new EquatableArray<LuaCatalogEntry>([.. classEntries, .. orderedMembers]));
|
||||
}
|
||||
|
||||
private static AttributeData? FindAttribute(ISymbol symbol, string attributeName)
|
||||
{
|
||||
foreach (var attribute in symbol.GetAttributes())
|
||||
{
|
||||
if (attribute.AttributeClass?.ToDisplayString() == attributeName)
|
||||
return attribute;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static LuaCatalogEntry? CreateAttributeEntry(AttributeData attribute, string defaultTable)
|
||||
{
|
||||
if (attribute.ConstructorArguments.Length == 0 || attribute.ConstructorArguments[0].Value is not string name)
|
||||
return null;
|
||||
|
||||
string table = defaultTable;
|
||||
foreach (var argument in attribute.NamedArguments)
|
||||
{
|
||||
if (argument.Key == "Table" && argument.Value.Value is string overridden)
|
||||
table = overridden;
|
||||
}
|
||||
|
||||
bool isFunction = attribute.AttributeClass?.ToDisplayString() is (BuiltinAttributeName or FunctionAttributeName);
|
||||
var parameters = isFunction && attribute.ConstructorArguments.Length > 1
|
||||
? ExtractStringArray(attribute.ConstructorArguments[1])
|
||||
: EquatableArray<string>.Empty;
|
||||
|
||||
return new LuaCatalogEntry(table, name, isFunction, parameters);
|
||||
}
|
||||
|
||||
private static EquatableArray<string> ExtractStringArray(TypedConstant constant)
|
||||
{
|
||||
if (constant.Kind != TypedConstantKind.Array)
|
||||
return EquatableArray<string>.Empty;
|
||||
return new EquatableArray<string>([.. constant.Values.Select(static v => v.Value as string ?? string.Empty)]);
|
||||
}
|
||||
|
||||
private static LuaFunctionModel? CreateFunctionModel(IMethodSymbol method, AttributeData attribute, out EquatableArray<string> catalogParameters)
|
||||
{
|
||||
catalogParameters = EquatableArray<string>.Empty;
|
||||
if (attribute.ConstructorArguments.Length == 0 || attribute.ConstructorArguments[0].Value is not string luaName)
|
||||
return null;
|
||||
|
||||
LuaReturnKind returnKind;
|
||||
if (method.ReturnsVoid)
|
||||
returnKind = LuaReturnKind.Void;
|
||||
else if (method.ReturnType.ToDisplayString() == "MoonSharp.Interpreter.DynValue")
|
||||
returnKind = LuaReturnKind.DynValue;
|
||||
else if (method.ReturnType.SpecialType == SpecialType.System_Double)
|
||||
returnKind = LuaReturnKind.Double;
|
||||
else
|
||||
return null;
|
||||
|
||||
var parameters = new List<LuaParameterModel>();
|
||||
foreach (var parameter in method.Parameters)
|
||||
{
|
||||
LuaParameterKind kind;
|
||||
string defaultLiteral = string.Empty;
|
||||
switch (parameter.Type.ToDisplayString())
|
||||
{
|
||||
case "MoonSharp.Interpreter.ScriptExecutionContext":
|
||||
kind = LuaParameterKind.ExecutionContext;
|
||||
break;
|
||||
case "MoonSharp.Interpreter.CallbackArguments":
|
||||
kind = LuaParameterKind.Arguments;
|
||||
break;
|
||||
case "MoonSharp.Interpreter.DynValue":
|
||||
kind = LuaParameterKind.DynValue;
|
||||
break;
|
||||
case "double":
|
||||
kind = LuaParameterKind.Double;
|
||||
defaultLiteral = FormatDouble(parameter.HasExplicitDefaultValue ? (double)parameter.ExplicitDefaultValue! : 0d);
|
||||
break;
|
||||
case "int":
|
||||
kind = LuaParameterKind.Int;
|
||||
defaultLiteral = FormatDouble(parameter.HasExplicitDefaultValue ? (int)parameter.ExplicitDefaultValue! : 0);
|
||||
break;
|
||||
case "bool":
|
||||
kind = LuaParameterKind.Bool;
|
||||
defaultLiteral = parameter.HasExplicitDefaultValue && (bool)parameter.ExplicitDefaultValue! ? "true" : "false";
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
parameters.Add(new LuaParameterModel(parameter.Name, kind, defaultLiteral));
|
||||
}
|
||||
|
||||
var explicitParameters = attribute.ConstructorArguments.Length > 1
|
||||
? ExtractStringArray(attribute.ConstructorArguments[1])
|
||||
: EquatableArray<string>.Empty;
|
||||
catalogParameters = explicitParameters.Count > 0
|
||||
? explicitParameters
|
||||
: new EquatableArray<string>([.. parameters
|
||||
.Where(static p => p.Kind is not (LuaParameterKind.ExecutionContext or LuaParameterKind.Arguments))
|
||||
.Select(static p => p.Name)]);
|
||||
|
||||
return new LuaFunctionModel(luaName, method.Name, returnKind, new EquatableArray<LuaParameterModel>([.. parameters]));
|
||||
}
|
||||
|
||||
private static LuaUpdateModel? CreateUpdateModel(IMethodSymbol method, AttributeData attribute, string tableName, ref string contextType, out LuaCatalogEntry? entry)
|
||||
{
|
||||
entry = null;
|
||||
if (attribute.ConstructorArguments.Length == 0 || attribute.ConstructorArguments[0].Value is not string luaName)
|
||||
return null;
|
||||
if (method.Parameters.Length != 1)
|
||||
return null;
|
||||
|
||||
string parameterType = method.Parameters[0].Type.ToDisplayString();
|
||||
if (contextType.Length == 0)
|
||||
contextType = parameterType;
|
||||
else if (contextType != parameterType)
|
||||
return null;
|
||||
|
||||
var returnType = method.ReturnType;
|
||||
LuaUpdateKind kind;
|
||||
if (returnType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
|
||||
kind = LuaUpdateKind.OptionalValue;
|
||||
else if (returnType.IsReferenceType)
|
||||
kind = LuaUpdateKind.OptionalReference;
|
||||
else
|
||||
kind = LuaUpdateKind.Direct;
|
||||
|
||||
bool inCatalog = true;
|
||||
foreach (var argument in attribute.NamedArguments)
|
||||
{
|
||||
if (argument.Key == "InCatalog" && argument.Value.Value is bool value)
|
||||
inCatalog = value;
|
||||
}
|
||||
|
||||
if (inCatalog)
|
||||
entry = new LuaCatalogEntry(tableName, luaName, false, EquatableArray<string>.Empty);
|
||||
return new LuaUpdateModel(luaName, method.Name, kind);
|
||||
}
|
||||
|
||||
private static string FormatDouble(double value) =>
|
||||
value.ToString("R", System.Globalization.CultureInfo.InvariantCulture) + "d";
|
||||
|
||||
private static string RegistrationHintName(LuaTableModel model)
|
||||
{
|
||||
var chain = string.Join(".", model.TypeChain.Select(static p => p.Name));
|
||||
return $"{model.Namespace}.{chain}.LuaRegistration.g.cs";
|
||||
}
|
||||
|
||||
private static string EmitRegistration(LuaTableModel model)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
builder.AppendLine("#nullable enable");
|
||||
builder.AppendLine($"namespace {model.Namespace}");
|
||||
builder.AppendLine("{");
|
||||
|
||||
string indent = " ";
|
||||
foreach (var part in model.TypeChain)
|
||||
{
|
||||
builder.AppendLine($"{indent}{(part.IsStatic ? "static partial class " : "partial class ")}{part.Name}");
|
||||
builder.AppendLine($"{indent}{{");
|
||||
indent += " ";
|
||||
}
|
||||
|
||||
bool isStatic = model.TypeChain[model.TypeChain.Count - 1].IsStatic;
|
||||
string body = indent + " ";
|
||||
|
||||
if (model.Constants.Count > 0 || model.Functions.Count > 0)
|
||||
{
|
||||
builder.AppendLine($"{indent}internal {(isStatic ? "static " : "")}void RegisterLuaMembers(global::MoonSharp.Interpreter.Table table)");
|
||||
builder.AppendLine($"{indent}{{");
|
||||
|
||||
foreach (var constant in model.Constants)
|
||||
builder.AppendLine($"{body}table[\"{constant.LuaName}\"] = {constant.MemberName};");
|
||||
|
||||
foreach (var function in model.Functions)
|
||||
{
|
||||
string call = $"{function.MethodName}({EmitArguments(function.Parameters)})";
|
||||
string lambda = function.ReturnKind switch
|
||||
{
|
||||
LuaReturnKind.DynValue => $"(execCtx, args) => {call}",
|
||||
LuaReturnKind.Double => $"(execCtx, args) => global::MoonSharp.Interpreter.DynValue.NewNumber({call})",
|
||||
_ => $"(execCtx, args) => {{ {call}; return global::MoonSharp.Interpreter.DynValue.Void; }}",
|
||||
};
|
||||
builder.AppendLine($"{body}table[\"{function.LuaName}\"] = global::MoonSharp.Interpreter.DynValue.NewCallback({lambda});");
|
||||
}
|
||||
|
||||
builder.AppendLine($"{indent}}}");
|
||||
}
|
||||
|
||||
if (model.Updates.Count > 0)
|
||||
{
|
||||
builder.AppendLine($"{indent}internal {(isStatic ? "static " : "")}void UpdateLuaMembers(global::MoonSharp.Interpreter.Table table, global::{model.ContextType} context)");
|
||||
builder.AppendLine($"{indent}{{");
|
||||
foreach (var update in model.Updates)
|
||||
{
|
||||
switch (update.Kind)
|
||||
{
|
||||
case LuaUpdateKind.OptionalValue:
|
||||
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table[\"{update.LuaName}\"] = value.Value; }}");
|
||||
break;
|
||||
case LuaUpdateKind.OptionalReference:
|
||||
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value is not null) table[\"{update.LuaName}\"] = value; }}");
|
||||
break;
|
||||
default:
|
||||
builder.AppendLine($"{body}table[\"{update.LuaName}\"] = {update.MethodName}(context);");
|
||||
break;
|
||||
}
|
||||
}
|
||||
builder.AppendLine($"{indent}}}");
|
||||
}
|
||||
|
||||
for (int i = model.TypeChain.Count - 1; i >= 0; i--)
|
||||
{
|
||||
indent = new string(' ', 4 * (i + 1));
|
||||
builder.AppendLine($"{indent}}}");
|
||||
}
|
||||
builder.AppendLine("}");
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static string EmitArguments(EquatableArray<LuaParameterModel> parameters)
|
||||
{
|
||||
var rendered = new List<string>();
|
||||
int position = 0;
|
||||
foreach (var parameter in parameters)
|
||||
{
|
||||
if (parameter.Kind == LuaParameterKind.ExecutionContext)
|
||||
{
|
||||
rendered.Add("execCtx");
|
||||
continue;
|
||||
}
|
||||
if (parameter.Kind == LuaParameterKind.Arguments)
|
||||
{
|
||||
rendered.Add("args");
|
||||
continue;
|
||||
}
|
||||
rendered.Add(parameter.Kind switch
|
||||
{
|
||||
LuaParameterKind.DynValue => $"args.Count > {position} ? args[{position}] : global::MoonSharp.Interpreter.DynValue.Nil",
|
||||
LuaParameterKind.Double => $"args.Count > {position} ? args[{position}].CastToNumber() ?? {parameter.DefaultLiteral} : {parameter.DefaultLiteral}",
|
||||
LuaParameterKind.Int => $"(int)(args.Count > {position} ? args[{position}].CastToNumber() ?? {parameter.DefaultLiteral} : {parameter.DefaultLiteral})",
|
||||
_ => $"args.Count > {position} ? args[{position}].CastToBool() : {parameter.DefaultLiteral}",
|
||||
});
|
||||
position++;
|
||||
}
|
||||
return string.Join(", ", rendered);
|
||||
}
|
||||
|
||||
private static string EmitCatalog(LuaCatalogEntry[] entries)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
builder.AppendLine("#nullable enable");
|
||||
builder.AppendLine("namespace LuaScript.Generated");
|
||||
builder.AppendLine("{");
|
||||
builder.AppendLine(" internal static class LuaApiModuleInitializer");
|
||||
builder.AppendLine(" {");
|
||||
builder.AppendLine(" [global::System.Runtime.CompilerServices.ModuleInitializer]");
|
||||
builder.AppendLine(" internal static void Initialize()");
|
||||
builder.AppendLine(" {");
|
||||
builder.AppendLine(" global::LuaScript.Api.LuaApiCatalog.Register(new global::LuaScript.Api.LuaApiMember[]");
|
||||
builder.AppendLine(" {");
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
string kind = entry.IsFunction
|
||||
? "global::LuaScript.Api.LuaApiMemberKind.Function"
|
||||
: "global::LuaScript.Api.LuaApiMemberKind.Variable";
|
||||
string parameters = entry.Parameters.Count == 0
|
||||
? "global::System.Array.Empty<string>()"
|
||||
: $"new string[] {{ {string.Join(", ", entry.Parameters.Select(static p => $"\"{p}\""))} }}";
|
||||
builder.AppendLine($" new(\"{entry.Table}\", \"{entry.Name}\", {kind}, {parameters}),");
|
||||
}
|
||||
builder.AppendLine(" });");
|
||||
builder.AppendLine(" }");
|
||||
builder.AppendLine(" }");
|
||||
builder.AppendLine("}");
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static IReadOnlyList<LuaCatalogEntry> CollectAssemblyEntries(Compilation compilation)
|
||||
{
|
||||
var entries = new List<(int Position, LuaCatalogEntry Entry)>();
|
||||
foreach (var attribute in compilation.Assembly.GetAttributes())
|
||||
{
|
||||
string? attributeName = attribute.AttributeClass?.ToDisplayString();
|
||||
if (attributeName is not (VariableAttributeName or BuiltinAttributeName or FunctionAttributeName))
|
||||
continue;
|
||||
var entry = CreateAttributeEntry(attribute, string.Empty);
|
||||
if (entry is null)
|
||||
continue;
|
||||
entries.Add((attribute.ApplicationSyntaxReference?.Span.Start ?? 0, entry));
|
||||
}
|
||||
return [.. entries.OrderBy(static e => e.Position).Select(static e => e.Entry)];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.15.0</Version>
|
||||
<IsRoslynComponent>true</IsRoslynComponent>
|
||||
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="5.3.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="5.3.0" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,76 @@
|
||||
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
|
||||
{
|
||||
internal sealed record LuaSyntaxRuleModel(string TypeName, int Order);
|
||||
|
||||
[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;
|
||||
|
||||
return new LuaSyntaxRuleModel(symbol.ToDisplayString(), order);
|
||||
}
|
||||
|
||||
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(" };");
|
||||
builder.AppendLine(" }");
|
||||
builder.AppendLine("}");
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.Intrinsics;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed class CpuKernel(CpuKernel.RowDelegate row, CpuKernel.RowDelegate? block)
|
||||
{
|
||||
public delegate void RowDelegate(byte[] buffer, int rowBase, int xStart, int xEnd, double y, double[] uniforms);
|
||||
|
||||
private const int ParallelThreshold = 64;
|
||||
private const int WarmupRunsPerPath = 1;
|
||||
private const int TimedRunsPerPath = 3;
|
||||
|
||||
private readonly RowDelegate _row = row;
|
||||
private readonly RowDelegate? _block = block;
|
||||
private long _rowTicks;
|
||||
private long _blockTicks;
|
||||
private int _rowRuns;
|
||||
private int _blockRuns;
|
||||
private bool _nextIsBlock = true;
|
||||
private bool _decided;
|
||||
private bool _useBlock;
|
||||
|
||||
public bool? BlockAdopted => _decided ? _useBlock : null;
|
||||
|
||||
public void Execute(byte[] buffer, int width, int height, double[] uniforms)
|
||||
{
|
||||
if (_block is null || !Vector256.IsHardwareAccelerated)
|
||||
{
|
||||
Run(buffer, width, height, uniforms, false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (_decided)
|
||||
{
|
||||
Run(buffer, width, height, uniforms, _useBlock);
|
||||
return;
|
||||
}
|
||||
|
||||
bool useBlock = _nextIsBlock;
|
||||
_nextIsBlock = !_nextIsBlock;
|
||||
|
||||
long start = Stopwatch.GetTimestamp();
|
||||
Run(buffer, width, height, uniforms, useBlock);
|
||||
long elapsed = Stopwatch.GetTimestamp() - start;
|
||||
|
||||
if (useBlock)
|
||||
{
|
||||
if (_blockRuns >= WarmupRunsPerPath)
|
||||
_blockTicks += elapsed;
|
||||
_blockRuns++;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_rowRuns >= WarmupRunsPerPath)
|
||||
_rowTicks += elapsed;
|
||||
_rowRuns++;
|
||||
}
|
||||
|
||||
if (_rowRuns >= WarmupRunsPerPath + TimedRunsPerPath &&
|
||||
_blockRuns >= WarmupRunsPerPath + TimedRunsPerPath)
|
||||
{
|
||||
_useBlock = _blockTicks < _rowTicks;
|
||||
_decided = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void Run(byte[] buffer, int width, int height, double[] uniforms, bool useBlock)
|
||||
{
|
||||
var row = _row;
|
||||
var block = useBlock ? _block : null;
|
||||
int stride = width * 4;
|
||||
int blockWidth = block is null ? 0 : width & ~3;
|
||||
|
||||
void RunRow(int y)
|
||||
{
|
||||
int rowBase = y * stride;
|
||||
if (blockWidth > 0)
|
||||
block!(buffer, rowBase, 0, blockWidth, y, uniforms);
|
||||
if (blockWidth < width)
|
||||
row(buffer, rowBase, blockWidth, width, y, uniforms);
|
||||
}
|
||||
|
||||
if (height < ParallelThreshold)
|
||||
{
|
||||
for (int y = 0; y < height; y++)
|
||||
RunRow(y);
|
||||
return;
|
||||
}
|
||||
|
||||
Parallel.For(0, height, RunRow);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal static class CpuKernelCompiler
|
||||
{
|
||||
private static readonly MethodInfo Clamp = typeof(Math).GetMethod(nameof(Math.Clamp), [typeof(double), typeof(double), typeof(double)])!;
|
||||
private static readonly MethodInfo Floor = Unary(nameof(Math.Floor));
|
||||
private static readonly MethodInfo Pow = Binary(nameof(Math.Pow));
|
||||
|
||||
private static readonly Dictionary<KFunc, MethodInfo> Functions = new()
|
||||
{
|
||||
[KFunc.Abs] = Unary(nameof(Math.Abs)),
|
||||
[KFunc.Floor] = Floor,
|
||||
[KFunc.Ceil] = Unary(nameof(Math.Ceiling)),
|
||||
[KFunc.Sqrt] = Unary(nameof(Math.Sqrt)),
|
||||
[KFunc.Sin] = Unary(nameof(Math.Sin)),
|
||||
[KFunc.Cos] = Unary(nameof(Math.Cos)),
|
||||
[KFunc.Tan] = Unary(nameof(Math.Tan)),
|
||||
[KFunc.Asin] = Unary(nameof(Math.Asin)),
|
||||
[KFunc.Acos] = Unary(nameof(Math.Acos)),
|
||||
[KFunc.Atan] = Unary(nameof(Math.Atan)),
|
||||
[KFunc.Atan2] = Binary(nameof(Math.Atan2)),
|
||||
[KFunc.Exp] = Unary(nameof(Math.Exp)),
|
||||
[KFunc.Log] = Unary(nameof(Math.Log)),
|
||||
[KFunc.Pow] = Pow,
|
||||
[KFunc.Min] = Binary(nameof(Math.Min)),
|
||||
[KFunc.Max] = Binary(nameof(Math.Max)),
|
||||
};
|
||||
|
||||
public static CpuKernel Compile(KernelProgram program) =>
|
||||
new(CompileRow(program), SimdKernelCompiler.TryCompile(program));
|
||||
|
||||
public static CpuKernel.RowDelegate CompileRow(KernelProgram program)
|
||||
{
|
||||
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
|
||||
var rowBase = Expression.Parameter(typeof(int), "rowBase");
|
||||
var xStart = Expression.Parameter(typeof(int), "xStart");
|
||||
var xEnd = Expression.Parameter(typeof(int), "xEnd");
|
||||
var y = Expression.Parameter(typeof(double), "y");
|
||||
var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
|
||||
|
||||
var x = Expression.Variable(typeof(int), "x");
|
||||
var index = Expression.Variable(typeof(int), "index");
|
||||
var alphaRaw = Expression.Variable(typeof(double), "alphaRaw");
|
||||
var transparent = Expression.Variable(typeof(bool), "transparent");
|
||||
var scale = Expression.Variable(typeof(double), "scale");
|
||||
var inputs = new[]
|
||||
{
|
||||
Expression.Variable(typeof(double), "inR"),
|
||||
Expression.Variable(typeof(double), "inG"),
|
||||
Expression.Variable(typeof(double), "inB"),
|
||||
Expression.Variable(typeof(double), "inA"),
|
||||
};
|
||||
var slots = new ParameterExpression[program.Bindings.Count];
|
||||
for (int i = 0; i < slots.Length; i++)
|
||||
slots[i] = Expression.Variable(typeof(double), "slot" + i);
|
||||
|
||||
var context = new Context(x, y, uniforms, inputs, slots);
|
||||
|
||||
var statements = new List<Expression>
|
||||
{
|
||||
Expression.Assign(index, Expression.Add(rowBase, Expression.Multiply(x, Constant(4)))),
|
||||
Expression.Assign(alphaRaw, ToDouble(ReadByte(buffer, index, 3))),
|
||||
Expression.Assign(transparent, Expression.LessThanOrEqual(alphaRaw, Constant(0d))),
|
||||
Expression.Assign(scale, Select(transparent, Constant(0d), Expression.Divide(Constant(255d), alphaRaw))),
|
||||
Expression.Assign(inputs[3], Select(transparent, Constant(0d), alphaRaw)),
|
||||
Expression.Assign(inputs[0], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 2)), scale)))),
|
||||
Expression.Assign(inputs[1], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 1)), scale)))),
|
||||
Expression.Assign(inputs[2], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 0)), scale)))),
|
||||
};
|
||||
|
||||
for (int i = 0; i < slots.Length; i++)
|
||||
statements.Add(Expression.Assign(slots[i], Build(program.Bindings[i], context)));
|
||||
|
||||
var outA = Expression.Variable(typeof(double), "outA");
|
||||
var alphaScale = Expression.Variable(typeof(double), "alphaScale");
|
||||
statements.Add(Expression.Assign(outA, Build(program.OutputA, context)));
|
||||
statements.Add(Expression.Assign(alphaScale, Expression.Divide(ClampByte(outA), Constant(255d))));
|
||||
statements.Add(WriteByte(buffer, index, 0, ClampByte(Expression.Multiply(Build(program.OutputB, context), alphaScale))));
|
||||
statements.Add(WriteByte(buffer, index, 1, ClampByte(Expression.Multiply(Build(program.OutputG, context), alphaScale))));
|
||||
statements.Add(WriteByte(buffer, index, 2, ClampByte(Expression.Multiply(Build(program.OutputR, context), alphaScale))));
|
||||
statements.Add(WriteByte(buffer, index, 3, ClampByte(outA)));
|
||||
statements.Add(Expression.PostIncrementAssign(x));
|
||||
|
||||
var breakLabel = Expression.Label("break");
|
||||
var loop = Expression.Loop(
|
||||
Expression.IfThenElse(
|
||||
Expression.LessThan(x, xEnd),
|
||||
Expression.Block(statements),
|
||||
Expression.Break(breakLabel)),
|
||||
breakLabel);
|
||||
|
||||
var locals = new List<ParameterExpression> { x, index, alphaRaw, transparent, scale, outA, alphaScale };
|
||||
locals.AddRange(inputs);
|
||||
locals.AddRange(slots);
|
||||
|
||||
var body = Expression.Block(locals, Expression.Assign(x, xStart), loop);
|
||||
|
||||
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, y, uniforms);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
private sealed record Context(
|
||||
ParameterExpression X,
|
||||
ParameterExpression Y,
|
||||
ParameterExpression Uniforms,
|
||||
ParameterExpression[] Inputs,
|
||||
ParameterExpression[] Slots);
|
||||
|
||||
private static Expression Build(KExpr expression, Context context)
|
||||
{
|
||||
switch (expression)
|
||||
{
|
||||
case KConst value:
|
||||
return Constant(value.Value);
|
||||
case KInput input:
|
||||
return context.Inputs[(int)input.Channel];
|
||||
case KCoord coord:
|
||||
return coord.Axis == KAxis.X ? ToDouble(context.X) : context.Y;
|
||||
case KUniformRef uniform:
|
||||
return Expression.ArrayIndex(context.Uniforms, Constant((int)uniform.Uniform));
|
||||
case KLocalRef local:
|
||||
return context.Slots[local.Slot];
|
||||
case KNegate negate:
|
||||
return Expression.Negate(Build(negate.Operand, context));
|
||||
case KArith arithmetic:
|
||||
return BuildArithmetic(arithmetic, context);
|
||||
case KCall call:
|
||||
return BuildCall(call, context);
|
||||
case KSelect select:
|
||||
return Select(BuildBool(select.Condition, context), Build(select.WhenTrue, context), Build(select.WhenFalse, context));
|
||||
}
|
||||
throw new KernelUnsupportedException("Unsupported CPU expression.");
|
||||
}
|
||||
|
||||
private static Expression BuildArithmetic(KArith arithmetic, Context context)
|
||||
{
|
||||
var left = Build(arithmetic.Left, context);
|
||||
var right = Build(arithmetic.Right, context);
|
||||
return arithmetic.Op switch
|
||||
{
|
||||
KArithOp.Add => Expression.Add(left, right),
|
||||
KArithOp.Subtract => Expression.Subtract(left, right),
|
||||
KArithOp.Multiply => Expression.Multiply(left, right),
|
||||
KArithOp.Divide => Expression.Divide(left, right),
|
||||
KArithOp.Modulo => FlooredModulo(left, right),
|
||||
KArithOp.Power => Expression.Call(Pow, left, right),
|
||||
_ => throw new KernelUnsupportedException("Unsupported arithmetic operator."),
|
||||
};
|
||||
}
|
||||
|
||||
private static Expression BuildCall(KCall call, Context context)
|
||||
{
|
||||
if (call.Func == KFunc.Fmod)
|
||||
return Expression.Modulo(Build(call.Arguments[0], context), Build(call.Arguments[1], context));
|
||||
var method = Functions[call.Func];
|
||||
if (call.Arguments.Count == 1)
|
||||
return Expression.Call(method, Build(call.Arguments[0], context));
|
||||
return Expression.Call(method, Build(call.Arguments[0], context), Build(call.Arguments[1], context));
|
||||
}
|
||||
|
||||
private static Expression BuildBool(KBool condition, Context context)
|
||||
{
|
||||
switch (condition)
|
||||
{
|
||||
case KBoolConst value:
|
||||
return Expression.Constant(value.Value);
|
||||
case KNot not:
|
||||
return Expression.Not(BuildBool(not.Operand, context));
|
||||
case KLogical logical:
|
||||
return logical.IsAnd
|
||||
? Expression.AndAlso(BuildBool(logical.Left, context), BuildBool(logical.Right, context))
|
||||
: Expression.OrElse(BuildBool(logical.Left, context), BuildBool(logical.Right, context));
|
||||
case KCompare compare:
|
||||
var left = Build(compare.Left, context);
|
||||
var right = Build(compare.Right, context);
|
||||
return compare.Op switch
|
||||
{
|
||||
KCompareOp.Less => Expression.LessThan(left, right),
|
||||
KCompareOp.Greater => Expression.GreaterThan(left, right),
|
||||
KCompareOp.LessEqual => Expression.LessThanOrEqual(left, right),
|
||||
KCompareOp.GreaterEqual => Expression.GreaterThanOrEqual(left, right),
|
||||
KCompareOp.Equal => Expression.Equal(left, right),
|
||||
KCompareOp.NotEqual => Expression.NotEqual(left, right),
|
||||
_ => throw new KernelUnsupportedException("Unsupported comparison."),
|
||||
};
|
||||
}
|
||||
throw new KernelUnsupportedException("Unsupported CPU condition.");
|
||||
}
|
||||
|
||||
private static Expression FlooredModulo(Expression left, Expression right) =>
|
||||
Expression.Subtract(left, Expression.Multiply(Expression.Call(Floor, Expression.Divide(left, right)), right));
|
||||
|
||||
private static Expression Select(Expression condition, Expression whenTrue, Expression whenFalse) =>
|
||||
Expression.Condition(condition, whenTrue, whenFalse);
|
||||
|
||||
private static Expression ClampByte(Expression value) =>
|
||||
Expression.Call(Clamp, value, Constant(0d), Constant(255d));
|
||||
|
||||
private static Expression ReadByte(ParameterExpression buffer, ParameterExpression index, int offset) =>
|
||||
Expression.ArrayIndex(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset)));
|
||||
|
||||
private static Expression WriteByte(ParameterExpression buffer, ParameterExpression index, int offset, Expression value) =>
|
||||
Expression.Assign(
|
||||
Expression.ArrayAccess(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset))),
|
||||
Expression.Convert(value, typeof(byte)));
|
||||
|
||||
private static Expression ToDouble(Expression value) => Expression.Convert(value, typeof(double));
|
||||
|
||||
private static ConstantExpression Constant(double value) => Expression.Constant(value, typeof(double));
|
||||
|
||||
private static ConstantExpression Constant(int value) => Expression.Constant(value, typeof(int));
|
||||
|
||||
private static MethodInfo Unary(string name) => typeof(Math).GetMethod(name, [typeof(double)])!;
|
||||
|
||||
private static MethodInfo Binary(string name) => typeof(Math).GetMethod(name, [typeof(double), typeof(double)])!;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal static class HlslKernelEmitter
|
||||
{
|
||||
public const int ConstantVectorCount = 16;
|
||||
|
||||
public const int ConstantFloatCount = ConstantVectorCount * 4;
|
||||
|
||||
public static string Emit(KernelProgram program)
|
||||
{
|
||||
var builder = new StringBuilder(1024);
|
||||
|
||||
builder.Append("Texture2D InputTexture : register(t0);\n");
|
||||
builder.Append("SamplerState InputSampler : register(s0);\n");
|
||||
builder.Append("cbuffer constants : register(b0)\n{\n");
|
||||
builder.Append(" float4 uniforms[").Append(ConstantVectorCount).Append("];\n");
|
||||
builder.Append("};\n\n");
|
||||
builder.Append("float4 main(float4 pos : SV_POSITION, float4 posScene : SCENE_POSITION, float4 uv : TEXCOORD0) : SV_Target\n{\n");
|
||||
builder.Append(" float4 src = InputTexture.Sample(InputSampler, uv.xy);\n");
|
||||
builder.Append(" float srcA = src.a;\n");
|
||||
builder.Append(" float invA = srcA <= 0.0 ? 0.0 : 1.0 / srcA;\n");
|
||||
builder.Append(" float inR = clamp(src.r * invA * 255.0, 0.0, 255.0);\n");
|
||||
builder.Append(" float inG = clamp(src.g * invA * 255.0, 0.0, 255.0);\n");
|
||||
builder.Append(" float inB = clamp(src.b * invA * 255.0, 0.0, 255.0);\n");
|
||||
builder.Append(" float inA = srcA * 255.0;\n");
|
||||
builder.Append(" float px = uv.x * ").Append(Uniform(KernelUniform.Width)).Append(" - 0.5;\n");
|
||||
builder.Append(" float py = uv.y * ").Append(Uniform(KernelUniform.Height)).Append(" - 0.5;\n");
|
||||
|
||||
for (int i = 0; i < program.Bindings.Count; i++)
|
||||
{
|
||||
builder.Append(" float slot").Append(i).Append(" = ");
|
||||
EmitExpression(builder, program.Bindings[i]);
|
||||
builder.Append(";\n");
|
||||
}
|
||||
|
||||
builder.Append(" float outA = clamp(");
|
||||
EmitExpression(builder, program.OutputA);
|
||||
builder.Append(", 0.0, 255.0);\n");
|
||||
builder.Append(" float alphaK = outA / 255.0;\n");
|
||||
|
||||
builder.Append(" float oR = floor(clamp((");
|
||||
EmitExpression(builder, program.OutputR);
|
||||
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
|
||||
builder.Append(" float oG = floor(clamp((");
|
||||
EmitExpression(builder, program.OutputG);
|
||||
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
|
||||
builder.Append(" float oB = floor(clamp((");
|
||||
EmitExpression(builder, program.OutputB);
|
||||
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
|
||||
builder.Append(" float oA = floor(outA) / 255.0;\n");
|
||||
builder.Append(" return float4(oR, oG, oB, oA);\n}\n");
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static void EmitExpression(StringBuilder builder, KExpr expression)
|
||||
{
|
||||
switch (expression)
|
||||
{
|
||||
case KConst value:
|
||||
builder.Append(Number(value.Value));
|
||||
return;
|
||||
case KInput input:
|
||||
builder.Append(input.Channel switch
|
||||
{
|
||||
KChannel.R => "inR",
|
||||
KChannel.G => "inG",
|
||||
KChannel.B => "inB",
|
||||
_ => "inA",
|
||||
});
|
||||
return;
|
||||
case KCoord coord:
|
||||
builder.Append(coord.Axis == KAxis.X ? "px" : "py");
|
||||
return;
|
||||
case KUniformRef uniform:
|
||||
builder.Append(Uniform(uniform.Uniform));
|
||||
return;
|
||||
case KLocalRef local:
|
||||
builder.Append("slot").Append(local.Slot);
|
||||
return;
|
||||
case KNegate negate:
|
||||
builder.Append("(-(");
|
||||
EmitExpression(builder, negate.Operand);
|
||||
builder.Append("))");
|
||||
return;
|
||||
case KArith arithmetic:
|
||||
EmitArithmetic(builder, arithmetic);
|
||||
return;
|
||||
case KCall call:
|
||||
EmitCall(builder, call);
|
||||
return;
|
||||
case KSelect select:
|
||||
builder.Append('(');
|
||||
EmitCondition(builder, select.Condition);
|
||||
builder.Append(" ? (");
|
||||
EmitExpression(builder, select.WhenTrue);
|
||||
builder.Append(") : (");
|
||||
EmitExpression(builder, select.WhenFalse);
|
||||
builder.Append("))");
|
||||
return;
|
||||
}
|
||||
throw new KernelUnsupportedException("Unsupported HLSL expression.");
|
||||
}
|
||||
|
||||
private static void EmitArithmetic(StringBuilder builder, KArith arithmetic)
|
||||
{
|
||||
if (arithmetic.Op == KArithOp.Power)
|
||||
{
|
||||
builder.Append("pow(");
|
||||
EmitExpression(builder, arithmetic.Left);
|
||||
builder.Append(", ");
|
||||
EmitExpression(builder, arithmetic.Right);
|
||||
builder.Append(')');
|
||||
return;
|
||||
}
|
||||
|
||||
if (arithmetic.Op == KArithOp.Modulo)
|
||||
{
|
||||
builder.Append('(');
|
||||
EmitExpression(builder, arithmetic.Left);
|
||||
builder.Append(" - floor((");
|
||||
EmitExpression(builder, arithmetic.Left);
|
||||
builder.Append(") / (");
|
||||
EmitExpression(builder, arithmetic.Right);
|
||||
builder.Append(")) * (");
|
||||
EmitExpression(builder, arithmetic.Right);
|
||||
builder.Append("))");
|
||||
return;
|
||||
}
|
||||
|
||||
builder.Append('(');
|
||||
EmitExpression(builder, arithmetic.Left);
|
||||
builder.Append(arithmetic.Op switch
|
||||
{
|
||||
KArithOp.Add => " + ",
|
||||
KArithOp.Subtract => " - ",
|
||||
KArithOp.Multiply => " * ",
|
||||
KArithOp.Divide => " / ",
|
||||
_ => throw new KernelUnsupportedException("Unsupported arithmetic operator."),
|
||||
});
|
||||
EmitExpression(builder, arithmetic.Right);
|
||||
builder.Append(')');
|
||||
}
|
||||
|
||||
private static void EmitCall(StringBuilder builder, KCall call)
|
||||
{
|
||||
builder.Append(KFunctions.Intrinsic(call.Func)).Append('(');
|
||||
for (int i = 0; i < call.Arguments.Count; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
builder.Append(", ");
|
||||
EmitExpression(builder, call.Arguments[i]);
|
||||
}
|
||||
builder.Append(')');
|
||||
}
|
||||
|
||||
private static void EmitCondition(StringBuilder builder, KBool condition)
|
||||
{
|
||||
switch (condition)
|
||||
{
|
||||
case KBoolConst value:
|
||||
builder.Append(value.Value ? "true" : "false");
|
||||
return;
|
||||
case KNot not:
|
||||
builder.Append("(!(");
|
||||
EmitCondition(builder, not.Operand);
|
||||
builder.Append("))");
|
||||
return;
|
||||
case KLogical logical:
|
||||
builder.Append('(');
|
||||
EmitCondition(builder, logical.Left);
|
||||
builder.Append(logical.IsAnd ? " && " : " || ");
|
||||
EmitCondition(builder, logical.Right);
|
||||
builder.Append(')');
|
||||
return;
|
||||
case KCompare compare:
|
||||
builder.Append('(');
|
||||
EmitExpression(builder, compare.Left);
|
||||
builder.Append(compare.Op switch
|
||||
{
|
||||
KCompareOp.Less => " < ",
|
||||
KCompareOp.Greater => " > ",
|
||||
KCompareOp.LessEqual => " <= ",
|
||||
KCompareOp.GreaterEqual => " >= ",
|
||||
KCompareOp.Equal => " == ",
|
||||
_ => " != ",
|
||||
});
|
||||
EmitExpression(builder, compare.Right);
|
||||
builder.Append(')');
|
||||
return;
|
||||
}
|
||||
throw new KernelUnsupportedException("Unsupported HLSL condition.");
|
||||
}
|
||||
|
||||
private static string Uniform(KernelUniform uniform)
|
||||
{
|
||||
int index = (int)uniform;
|
||||
return $"uniforms[{index / 4}].{"xyzw"[index % 4]}";
|
||||
}
|
||||
|
||||
private static string Number(double value)
|
||||
{
|
||||
if (double.IsPositiveInfinity(value))
|
||||
return "3.4028235e38";
|
||||
if (double.IsNegativeInfinity(value))
|
||||
return "-3.4028235e38";
|
||||
if (double.IsNaN(value))
|
||||
return "(0.0 / 0.0)";
|
||||
|
||||
string text = value.ToString("R", CultureInfo.InvariantCulture);
|
||||
if (!text.Contains('.') && !text.Contains('e') && !text.Contains('E'))
|
||||
text += ".0";
|
||||
return text;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed class KernelExtractor
|
||||
{
|
||||
private readonly List<KExpr> _bindings = [];
|
||||
private readonly Dictionary<string, int> _scope = new(StringComparer.Ordinal);
|
||||
private readonly SortedSet<KernelUniform> _uniforms = [];
|
||||
|
||||
private string _widthVariable = string.Empty;
|
||||
private string _heightVariable = string.Empty;
|
||||
private bool _coordsEnabled;
|
||||
private string? _pixelDataVariable;
|
||||
private string _baseIndexVariable = string.Empty;
|
||||
private readonly bool[] _writtenChannels = new bool[4];
|
||||
|
||||
public static KernelProgram? TryExtract(string runnableScript)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new KernelExtractor().Extract(runnableScript);
|
||||
}
|
||||
catch (KernelUnsupportedException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private KernelProgram? Extract(string runnableScript)
|
||||
{
|
||||
var block = LuaParser.Parse(runnableScript);
|
||||
|
||||
int index = 0;
|
||||
while (index < block.Count && block[index] is LocalStmt prelude)
|
||||
{
|
||||
if (TryBindPixelData(prelude))
|
||||
{
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
BindLocal(prelude);
|
||||
index++;
|
||||
}
|
||||
|
||||
if (index >= block.Count || block[index] is not NumericForStmt outer)
|
||||
return null;
|
||||
if (index + 1 != block.Count)
|
||||
return null;
|
||||
|
||||
if (!TryAxis(outer, out string outerVar, out KAxis outerAxis))
|
||||
return null;
|
||||
if (outer.Body.Count != 1 || outer.Body[0] is not NumericForStmt inner)
|
||||
return null;
|
||||
if (!TryAxis(inner, out string innerVar, out KAxis innerAxis))
|
||||
return null;
|
||||
if (outerAxis == innerAxis)
|
||||
return null;
|
||||
if (_pixelDataVariable is not null &&
|
||||
(string.Equals(outerVar, _pixelDataVariable, StringComparison.Ordinal) ||
|
||||
string.Equals(innerVar, _pixelDataVariable, StringComparison.Ordinal)))
|
||||
return null;
|
||||
if (_scope.ContainsKey(outerVar))
|
||||
_scope.Remove(outerVar);
|
||||
if (_scope.ContainsKey(innerVar))
|
||||
_scope.Remove(innerVar);
|
||||
|
||||
_widthVariable = outerAxis == KAxis.X ? outerVar : innerVar;
|
||||
_heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar;
|
||||
|
||||
return _pixelDataVariable is null ? BuildKernel(inner.Body) : BuildPixelDataKernel(inner.Body);
|
||||
}
|
||||
|
||||
private bool TryBindPixelData(LocalStmt local)
|
||||
{
|
||||
if (local.Names.Count != 1 || local.Values.Count != 1 ||
|
||||
local.Values[0] is not CallExpr { Target: MemberExpr { Target: NameExpr { Name: "obj" }, Name: "getpixeldata" }, Arguments.Count: 0 })
|
||||
return false;
|
||||
if (_pixelDataVariable is not null)
|
||||
throw new KernelUnsupportedException("Multiple pixel-data handles are not supported.");
|
||||
_pixelDataVariable = local.Names[0];
|
||||
return true;
|
||||
}
|
||||
|
||||
private KernelProgram? BuildPixelDataKernel(IReadOnlyList<LuaStmt> body)
|
||||
{
|
||||
if (body.Count < 5)
|
||||
return null;
|
||||
if (body[0] is not LocalStmt { Names.Count: 1, Values.Count: 1 } baseStmt || !IsBaseIndex(baseStmt.Values[0]))
|
||||
return null;
|
||||
|
||||
EnsureNotCoordinateName(baseStmt.Names[0]);
|
||||
_baseIndexVariable = baseStmt.Names[0];
|
||||
_coordsEnabled = true;
|
||||
|
||||
KExpr? outR = null, outG = null, outB = null;
|
||||
for (int i = 1; i < body.Count; i++)
|
||||
{
|
||||
switch (body[i])
|
||||
{
|
||||
case LocalStmt local:
|
||||
BindLocal(local);
|
||||
break;
|
||||
case AssignStmt assign:
|
||||
BindAssign(assign);
|
||||
break;
|
||||
case CallStmt { Call: MethodCallExpr set } when IsPixelDataSet(set, out int writeChannel):
|
||||
var value = ClampChannel(Lower(set.Arguments[1]));
|
||||
if (writeChannel == 0) outR = value;
|
||||
else if (writeChannel == 1) outG = value;
|
||||
else outB = value;
|
||||
_writtenChannels[writeChannel] = true;
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (outR is null || outG is null || outB is null)
|
||||
return null;
|
||||
|
||||
return new KernelProgram(_bindings, outR, outG, outB, new KInput(KChannel.A), [.. _uniforms]);
|
||||
}
|
||||
|
||||
private bool IsBaseIndex(LuaExpr expression)
|
||||
{
|
||||
if (expression is not BinaryExpr { Operator: "*", Right: NumberExpr { Value: 4d } } scaled ||
|
||||
scaled.Left is not BinaryExpr { Operator: "+" } sum)
|
||||
return false;
|
||||
if (!IsCoordinate(sum.Right, KAxis.X))
|
||||
return false;
|
||||
if (sum.Left is not BinaryExpr { Operator: "*" } stride)
|
||||
return false;
|
||||
return IsCoordinate(stride.Left, KAxis.Y) && IsWidth(stride.Right);
|
||||
}
|
||||
|
||||
private bool IsWidth(LuaExpr expression)
|
||||
{
|
||||
if (expression is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
||||
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||
return uniform == KernelUniform.Width;
|
||||
return _pixelDataVariable is not null &&
|
||||
expression is MemberExpr { Target: NameExpr { } target, Name: "width" } &&
|
||||
string.Equals(target.Name, _pixelDataVariable, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private bool TryPixelDataChannel(LuaExpr expression, out int channel)
|
||||
{
|
||||
channel = 0;
|
||||
if (expression is not MethodCallExpr { Method: "get", Arguments.Count: 1 } call ||
|
||||
call.Target is not NameExpr { } handle ||
|
||||
!string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||
return false;
|
||||
if (!TryChannelOffset(call.Arguments[0], 1, 4, out channel))
|
||||
return false;
|
||||
channel--;
|
||||
return !_writtenChannels[channel];
|
||||
}
|
||||
|
||||
private bool IsPixelDataSet(MethodCallExpr call, out int channel)
|
||||
{
|
||||
channel = 0;
|
||||
if (call.Method != "set" || call.Arguments.Count != 2 ||
|
||||
call.Target is not NameExpr { } handle ||
|
||||
!string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||
return false;
|
||||
if (!TryChannelOffset(call.Arguments[0], 1, 3, out channel))
|
||||
return false;
|
||||
channel--;
|
||||
return true;
|
||||
}
|
||||
|
||||
private KExpr ClampChannel(KExpr value)
|
||||
{
|
||||
var bound = new KLocalRef(AddBinding(value));
|
||||
return new KSelect(
|
||||
new KCompare(KCompareOp.Less, bound, new KConst(0d)),
|
||||
new KConst(0d),
|
||||
new KSelect(
|
||||
new KCompare(KCompareOp.Greater, bound, new KConst(255d)),
|
||||
new KConst(255d),
|
||||
bound));
|
||||
}
|
||||
|
||||
private bool TryChannelOffset(LuaExpr expression, int min, int max, out int offset)
|
||||
{
|
||||
offset = 0;
|
||||
if (expression is not BinaryExpr { Operator: "+", Left: NameExpr baseName, Right: NumberExpr number } ||
|
||||
!string.Equals(baseName.Name, _baseIndexVariable, StringComparison.Ordinal))
|
||||
return false;
|
||||
offset = (int)number.Value;
|
||||
return offset == number.Value && offset >= min && offset <= max;
|
||||
}
|
||||
|
||||
private KernelProgram? BuildKernel(IReadOnlyList<LuaStmt> body)
|
||||
{
|
||||
if (body.Count < 2)
|
||||
return null;
|
||||
|
||||
if (body[0] is not LocalStmt sample || sample.Values.Count != 1 ||
|
||||
!IsGetPixel(sample.Values[0]))
|
||||
return null;
|
||||
if (sample.Names.Count is < 1 or > 4)
|
||||
return null;
|
||||
|
||||
_coordsEnabled = true;
|
||||
for (int i = 0; i < sample.Names.Count; i++)
|
||||
{
|
||||
EnsureNotCoordinateName(sample.Names[i]);
|
||||
_scope[sample.Names[i]] = AddBinding(new KInput((KChannel)i));
|
||||
}
|
||||
|
||||
for (int i = 1; i < body.Count - 1; i++)
|
||||
{
|
||||
switch (body[i])
|
||||
{
|
||||
case LocalStmt local:
|
||||
BindLocal(local);
|
||||
break;
|
||||
case AssignStmt assign:
|
||||
BindAssign(assign);
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (body[^1] is not CallStmt { Call: CallExpr call } || !IsObjectMethod(call, "setpixel"))
|
||||
return null;
|
||||
if (call.Arguments.Count is < 5 or > 6)
|
||||
return null;
|
||||
if (!IsCoordinate(call.Arguments[0], KAxis.X) || !IsCoordinate(call.Arguments[1], KAxis.Y))
|
||||
return null;
|
||||
|
||||
var outR = Lower(call.Arguments[2]);
|
||||
var outG = Lower(call.Arguments[3]);
|
||||
var outB = Lower(call.Arguments[4]);
|
||||
var outA = call.Arguments.Count == 6 ? Lower(call.Arguments[5]) : new KConst(255d);
|
||||
|
||||
return new KernelProgram(_bindings, outR, outG, outB, outA, [.. _uniforms]);
|
||||
}
|
||||
|
||||
private void BindLocal(LocalStmt local)
|
||||
{
|
||||
if (local.Values.Count == 1 && IsGetPixel(local.Values[0]))
|
||||
throw new KernelUnsupportedException("Unexpected pixel sample.");
|
||||
if (local.Names.Count != local.Values.Count)
|
||||
throw new KernelUnsupportedException("Multiple-value assignment is not supported.");
|
||||
|
||||
var lowered = new KExpr[local.Values.Count];
|
||||
for (int i = 0; i < local.Values.Count; i++)
|
||||
lowered[i] = Lower(local.Values[i]);
|
||||
for (int i = 0; i < local.Names.Count; i++)
|
||||
{
|
||||
EnsureNotCoordinateName(local.Names[i]);
|
||||
_scope[local.Names[i]] = AddBinding(lowered[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private void BindAssign(AssignStmt assign)
|
||||
{
|
||||
if (assign.Targets.Count != assign.Values.Count)
|
||||
throw new KernelUnsupportedException("Unbalanced assignment is not supported.");
|
||||
|
||||
foreach (var target in assign.Targets)
|
||||
{
|
||||
if (target is not NameExpr name || !_scope.ContainsKey(name.Name))
|
||||
throw new KernelUnsupportedException("Assignment target must be a local variable.");
|
||||
}
|
||||
|
||||
var lowered = new KExpr[assign.Values.Count];
|
||||
for (int i = 0; i < assign.Values.Count; i++)
|
||||
lowered[i] = Lower(assign.Values[i]);
|
||||
for (int i = 0; i < assign.Targets.Count; i++)
|
||||
_scope[((NameExpr)assign.Targets[i]).Name] = AddBinding(lowered[i]);
|
||||
}
|
||||
|
||||
private void EnsureNotCoordinateName(string name)
|
||||
{
|
||||
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
|
||||
string.Equals(name, _heightVariable, StringComparison.Ordinal))
|
||||
throw new KernelUnsupportedException("Local variable shadows a loop coordinate.");
|
||||
if (_pixelDataVariable is not null && string.Equals(name, _pixelDataVariable, StringComparison.Ordinal))
|
||||
throw new KernelUnsupportedException("Local variable shadows the pixel-data handle.");
|
||||
if (_baseIndexVariable.Length > 0 && string.Equals(name, _baseIndexVariable, StringComparison.Ordinal))
|
||||
throw new KernelUnsupportedException("Local variable shadows the base index.");
|
||||
}
|
||||
|
||||
private int AddBinding(KExpr expression)
|
||||
{
|
||||
_bindings.Add(expression);
|
||||
return _bindings.Count - 1;
|
||||
}
|
||||
|
||||
private KExpr Lower(LuaExpr expression)
|
||||
{
|
||||
switch (expression)
|
||||
{
|
||||
case NumberExpr number:
|
||||
return new KConst(number.Value);
|
||||
case NameExpr name:
|
||||
return LowerName(name.Name);
|
||||
case MemberExpr member:
|
||||
return LowerMember(member);
|
||||
case CallExpr call:
|
||||
return LowerCall(call);
|
||||
case MethodCallExpr method when TryPixelDataChannel(method, out int channel):
|
||||
return new KInput((KChannel)channel);
|
||||
case UnaryExpr { Operator: "-" } unary:
|
||||
return new KNegate(Lower(unary.Operand));
|
||||
case BinaryExpr binary:
|
||||
return LowerBinary(binary);
|
||||
}
|
||||
throw new KernelUnsupportedException("Unsupported expression in pixel kernel.");
|
||||
}
|
||||
|
||||
private KExpr LowerName(string name)
|
||||
{
|
||||
if (_scope.TryGetValue(name, out int slot))
|
||||
return new KLocalRef(slot);
|
||||
if (_coordsEnabled && string.Equals(name, _widthVariable, StringComparison.Ordinal))
|
||||
return new KCoord(KAxis.X);
|
||||
if (_coordsEnabled && string.Equals(name, _heightVariable, StringComparison.Ordinal))
|
||||
return new KCoord(KAxis.Y);
|
||||
if (KernelUniforms.TryResolveGlobal(name, out var uniform))
|
||||
return UseUniform(uniform);
|
||||
throw new KernelUnsupportedException($"Unknown identifier '{name}'.");
|
||||
}
|
||||
|
||||
private KExpr LowerMember(MemberExpr member)
|
||||
{
|
||||
if (member.Target is NameExpr { Name: "math" })
|
||||
{
|
||||
return member.Name switch
|
||||
{
|
||||
"pi" => new KConst(Math.PI),
|
||||
"huge" => new KConst(double.PositiveInfinity),
|
||||
_ => throw new KernelUnsupportedException($"Unsupported math field '{member.Name}'."),
|
||||
};
|
||||
}
|
||||
|
||||
if (member.Target is NameExpr target && KernelUniforms.TryResolveMember(target.Name, member.Name, out var uniform))
|
||||
return UseUniform(uniform);
|
||||
|
||||
throw new KernelUnsupportedException("Unsupported member access in pixel kernel.");
|
||||
}
|
||||
|
||||
private KExpr LowerCall(CallExpr call)
|
||||
{
|
||||
if (call.Target is not MemberExpr { Target: NameExpr { Name: "math" }, Name: var function } ||
|
||||
!KFunctions.TryResolve(function, out var spec))
|
||||
throw new KernelUnsupportedException("Unsupported function call in pixel kernel.");
|
||||
|
||||
int count = call.Arguments.Count;
|
||||
if (count < spec.MinArgs || count > spec.MaxArgs)
|
||||
throw new KernelUnsupportedException($"Wrong argument count for 'math.{function}'.");
|
||||
|
||||
var arguments = new KExpr[count];
|
||||
for (int i = 0; i < count; i++)
|
||||
arguments[i] = Lower(call.Arguments[i]);
|
||||
|
||||
if (spec.Func is KFunc.Min or KFunc.Max)
|
||||
{
|
||||
var folded = arguments[0];
|
||||
for (int i = 1; i < count; i++)
|
||||
folded = new KCall(spec.Func, [folded, arguments[i]]);
|
||||
return folded;
|
||||
}
|
||||
|
||||
return new KCall(spec.Func, arguments);
|
||||
}
|
||||
|
||||
private KExpr LowerBinary(BinaryExpr binary)
|
||||
{
|
||||
switch (binary.Operator)
|
||||
{
|
||||
case "+": return new KArith(KArithOp.Add, Lower(binary.Left), Lower(binary.Right));
|
||||
case "-": return new KArith(KArithOp.Subtract, Lower(binary.Left), Lower(binary.Right));
|
||||
case "*": return new KArith(KArithOp.Multiply, Lower(binary.Left), Lower(binary.Right));
|
||||
case "/": return new KArith(KArithOp.Divide, Lower(binary.Left), Lower(binary.Right));
|
||||
case "%": return new KArith(KArithOp.Modulo, Lower(binary.Left), Lower(binary.Right));
|
||||
case "^": return new KArith(KArithOp.Power, Lower(binary.Left), Lower(binary.Right));
|
||||
case "or" when binary.Left is BinaryExpr { Operator: "and" } conditional:
|
||||
return new KSelect(LowerBool(conditional.Left), Lower(conditional.Right), Lower(binary.Right));
|
||||
}
|
||||
throw new KernelUnsupportedException($"Unsupported operator '{binary.Operator}' in value position.");
|
||||
}
|
||||
|
||||
private KBool LowerBool(LuaExpr expression)
|
||||
{
|
||||
switch (expression)
|
||||
{
|
||||
case BoolExpr boolean:
|
||||
return new KBoolConst(boolean.Value);
|
||||
case UnaryExpr { Operator: "not" } unary:
|
||||
return new KNot(LowerBool(unary.Operand));
|
||||
case BinaryExpr { Operator: "and" } conjunction:
|
||||
return new KLogical(true, LowerBool(conjunction.Left), LowerBool(conjunction.Right));
|
||||
case BinaryExpr { Operator: "or" } disjunction:
|
||||
return new KLogical(false, LowerBool(disjunction.Left), LowerBool(disjunction.Right));
|
||||
case BinaryExpr binary when TryCompareOp(binary.Operator, out var op):
|
||||
return new KCompare(op, Lower(binary.Left), Lower(binary.Right));
|
||||
case NameExpr name when IsCheck(LowerName(name.Name)):
|
||||
return new KCompare(KCompareOp.NotEqual, LowerName(name.Name), new KConst(0d));
|
||||
case MemberExpr member when IsCheck(LowerMember(member)):
|
||||
return new KCompare(KCompareOp.NotEqual, LowerMember(member), new KConst(0d));
|
||||
}
|
||||
throw new KernelUnsupportedException("Unsupported condition in pixel kernel.");
|
||||
}
|
||||
|
||||
private static bool IsCheck(KExpr expression) =>
|
||||
expression is KUniformRef { Uniform: KernelUniform.Check0 or KernelUniform.Check1 or KernelUniform.Check2 or KernelUniform.Check3 };
|
||||
|
||||
private static bool TryCompareOp(string symbol, out KCompareOp op)
|
||||
{
|
||||
switch (symbol)
|
||||
{
|
||||
case "<": op = KCompareOp.Less; return true;
|
||||
case ">": op = KCompareOp.Greater; return true;
|
||||
case "<=": op = KCompareOp.LessEqual; return true;
|
||||
case ">=": op = KCompareOp.GreaterEqual; return true;
|
||||
case "==": op = KCompareOp.Equal; return true;
|
||||
case "~=": op = KCompareOp.NotEqual; return true;
|
||||
default: op = default; return false;
|
||||
}
|
||||
}
|
||||
|
||||
private KExpr UseUniform(KernelUniform uniform)
|
||||
{
|
||||
_uniforms.Add(uniform);
|
||||
return new KUniformRef(uniform);
|
||||
}
|
||||
|
||||
private bool TryAxis(NumericForStmt loop, out string variable, out KAxis axis)
|
||||
{
|
||||
variable = loop.Variable;
|
||||
axis = default;
|
||||
|
||||
if (loop.Start is not NumberExpr { Value: 0d })
|
||||
return false;
|
||||
if (loop.Step is not null && loop.Step is not NumberExpr { Value: 1d })
|
||||
return false;
|
||||
if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound)
|
||||
return false;
|
||||
if (bound.Left is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
||||
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||
{
|
||||
if (uniform == KernelUniform.Width)
|
||||
{
|
||||
axis = KAxis.X;
|
||||
return true;
|
||||
}
|
||||
if (uniform == KernelUniform.Height)
|
||||
{
|
||||
axis = KAxis.Y;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_pixelDataVariable is not null &&
|
||||
bound.Left is MemberExpr { Target: NameExpr { } handle, Name: var pixelField } &&
|
||||
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||
{
|
||||
if (pixelField == "width")
|
||||
{
|
||||
axis = KAxis.X;
|
||||
return true;
|
||||
}
|
||||
if (pixelField == "height")
|
||||
{
|
||||
axis = KAxis.Y;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool IsGetPixel(LuaExpr expression) =>
|
||||
expression is CallExpr call && IsObjectMethod(call, "getpixel") &&
|
||||
call.Arguments.Count == 2 &&
|
||||
IsCoordinate(call.Arguments[0], KAxis.X) && IsCoordinate(call.Arguments[1], KAxis.Y);
|
||||
|
||||
private bool IsCoordinate(LuaExpr expression, KAxis axis) =>
|
||||
expression is NameExpr name &&
|
||||
string.Equals(name.Name, axis == KAxis.X ? _widthVariable : _heightVariable, StringComparison.Ordinal);
|
||||
|
||||
private static bool IsObjectMethod(CallExpr call, string method) =>
|
||||
call.Target is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var name } &&
|
||||
string.Equals(name, method, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed class KernelUnsupportedException(string reason) : Exception(reason);
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using System.Runtime.Intrinsics;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal static class SimdKernelCompiler
|
||||
{
|
||||
private static readonly Type Vec = typeof(Vector256<double>);
|
||||
|
||||
private static readonly MethodInfo Broadcast = typeof(Vector256).GetMethod(nameof(Vector256.Create), [typeof(double)])!;
|
||||
private static readonly MethodInfo Create4 = typeof(Vector256).GetMethod(nameof(Vector256.Create), [typeof(double), typeof(double), typeof(double), typeof(double)])!;
|
||||
private static readonly MethodInfo GetElement = VecOp(nameof(Vector256.GetElement), 1, 1);
|
||||
private static readonly MethodInfo Add = VecOp(nameof(Vector256.Add), 2);
|
||||
private static readonly MethodInfo Subtract = VecOp(nameof(Vector256.Subtract), 2);
|
||||
private static readonly MethodInfo Multiply = VecOp(nameof(Vector256.Multiply), 2);
|
||||
private static readonly MethodInfo Divide = VecOp(nameof(Vector256.Divide), 2);
|
||||
private static readonly MethodInfo Negate = VecOp(nameof(Vector256.Negate), 1);
|
||||
private static readonly MethodInfo Abs = VecOp(nameof(Vector256.Abs), 1);
|
||||
private static readonly MethodInfo Sqrt = VecOp(nameof(Vector256.Sqrt), 1);
|
||||
private static readonly MethodInfo FloorFn = typeof(Vector256).GetMethod(nameof(Vector256.Floor), [Vec])!;
|
||||
private static readonly MethodInfo CeilingFn = typeof(Vector256).GetMethod(nameof(Vector256.Ceiling), [Vec])!;
|
||||
private static readonly MethodInfo ConditionalSelect = VecOp(nameof(Vector256.ConditionalSelect), 3);
|
||||
private static readonly MethodInfo LessThan = VecOp(nameof(Vector256.LessThan), 2);
|
||||
private static readonly MethodInfo GreaterThan = VecOp(nameof(Vector256.GreaterThan), 2);
|
||||
private static readonly MethodInfo LessThanOrEqual = VecOp(nameof(Vector256.LessThanOrEqual), 2);
|
||||
private static readonly MethodInfo GreaterThanOrEqual = VecOp(nameof(Vector256.GreaterThanOrEqual), 2);
|
||||
private static readonly MethodInfo EqualsFn = VecOp(nameof(Vector256.Equals), 2);
|
||||
private static readonly MethodInfo BitwiseAnd = VecOp(nameof(Vector256.BitwiseAnd), 2);
|
||||
private static readonly MethodInfo BitwiseOr = VecOp(nameof(Vector256.BitwiseOr), 2);
|
||||
private static readonly MethodInfo OnesComplement = VecOp(nameof(Vector256.OnesComplement), 1);
|
||||
|
||||
private static readonly Expression Zero = Expression.Constant(Vector256<double>.Zero, Vec);
|
||||
private static readonly Expression AllBits = Expression.Constant(Vector256<double>.AllBitsSet, Vec);
|
||||
private static readonly Expression V255 = Expression.Constant(Vector256.Create(255d), Vec);
|
||||
|
||||
public static CpuKernel.RowDelegate? TryCompile(KernelProgram program)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Compile(program);
|
||||
}
|
||||
catch (KernelUnsupportedException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static CpuKernel.RowDelegate Compile(KernelProgram program)
|
||||
{
|
||||
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
|
||||
var rowBase = Expression.Parameter(typeof(int), "rowBase");
|
||||
var xStart = Expression.Parameter(typeof(int), "xStart");
|
||||
var xEnd = Expression.Parameter(typeof(int), "xEnd");
|
||||
var yScalar = Expression.Parameter(typeof(double), "y");
|
||||
var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
|
||||
|
||||
var x = Expression.Variable(typeof(int), "x");
|
||||
var index = Expression.Variable(typeof(int), "index");
|
||||
var yVec = Expression.Variable(Vec, "yVec");
|
||||
var xVec = Expression.Variable(Vec, "xVec");
|
||||
var alphaRaw = Expression.Variable(Vec, "alphaRaw");
|
||||
var transparent = Expression.Variable(Vec, "transparent");
|
||||
var scale = Expression.Variable(Vec, "scale");
|
||||
var inputs = new[]
|
||||
{
|
||||
Expression.Variable(Vec, "inR"),
|
||||
Expression.Variable(Vec, "inG"),
|
||||
Expression.Variable(Vec, "inB"),
|
||||
Expression.Variable(Vec, "inA"),
|
||||
};
|
||||
var slots = new ParameterExpression[program.Bindings.Count];
|
||||
for (int i = 0; i < slots.Length; i++)
|
||||
slots[i] = Expression.Variable(Vec, "slot" + i);
|
||||
|
||||
var context = new Context(xVec, yVec, uniforms, inputs, slots);
|
||||
|
||||
var statements = new List<Expression>
|
||||
{
|
||||
Expression.Assign(index, Expression.Add(rowBase, Expression.Multiply(x, Constant(4)))),
|
||||
Expression.Assign(xVec, Expression.Call(Create4,
|
||||
ToDouble(x),
|
||||
ToDouble(Expression.Add(x, Constant(1))),
|
||||
ToDouble(Expression.Add(x, Constant(2))),
|
||||
ToDouble(Expression.Add(x, Constant(3))))),
|
||||
Expression.Assign(alphaRaw, LoadChannel(buffer, index, 3)),
|
||||
Expression.Assign(transparent, Call(LessThanOrEqual, alphaRaw, Zero)),
|
||||
Expression.Assign(scale, Select(transparent, Zero, Call(Divide, V255, alphaRaw))),
|
||||
Expression.Assign(inputs[3], Select(transparent, Zero, alphaRaw)),
|
||||
Expression.Assign(inputs[0], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 2), scale)))),
|
||||
Expression.Assign(inputs[1], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 1), scale)))),
|
||||
Expression.Assign(inputs[2], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 0), scale)))),
|
||||
};
|
||||
|
||||
for (int i = 0; i < slots.Length; i++)
|
||||
statements.Add(Expression.Assign(slots[i], Build(program.Bindings[i], context)));
|
||||
|
||||
var outA = Expression.Variable(Vec, "outA");
|
||||
var alphaScale = Expression.Variable(Vec, "alphaScale");
|
||||
statements.Add(Expression.Assign(outA, Build(program.OutputA, context)));
|
||||
statements.Add(Expression.Assign(alphaScale, Call(Divide, ClampByte(outA), V255)));
|
||||
statements.Add(StoreChannel(buffer, index, 0, ClampByte(Call(Multiply, Build(program.OutputB, context), alphaScale))));
|
||||
statements.Add(StoreChannel(buffer, index, 1, ClampByte(Call(Multiply, Build(program.OutputG, context), alphaScale))));
|
||||
statements.Add(StoreChannel(buffer, index, 2, ClampByte(Call(Multiply, Build(program.OutputR, context), alphaScale))));
|
||||
statements.Add(StoreChannel(buffer, index, 3, ClampByte(outA)));
|
||||
statements.Add(Expression.AddAssign(x, Constant(4)));
|
||||
|
||||
var breakLabel = Expression.Label("break");
|
||||
var loop = Expression.Loop(
|
||||
Expression.IfThenElse(
|
||||
Expression.LessThan(x, xEnd),
|
||||
Expression.Block(statements),
|
||||
Expression.Break(breakLabel)),
|
||||
breakLabel);
|
||||
|
||||
var locals = new List<ParameterExpression> { x, index, yVec, xVec, alphaRaw, transparent, scale, outA, alphaScale };
|
||||
locals.AddRange(inputs);
|
||||
locals.AddRange(slots);
|
||||
|
||||
var body = Expression.Block(
|
||||
locals,
|
||||
Expression.Assign(yVec, Expression.Call(Broadcast, yScalar)),
|
||||
Expression.Assign(x, xStart),
|
||||
loop);
|
||||
|
||||
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, yScalar, uniforms);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
private sealed record Context(
|
||||
Expression X,
|
||||
Expression Y,
|
||||
ParameterExpression Uniforms,
|
||||
Expression[] Inputs,
|
||||
ParameterExpression[] Slots);
|
||||
|
||||
private static Expression Build(KExpr expression, Context context)
|
||||
{
|
||||
switch (expression)
|
||||
{
|
||||
case KConst value:
|
||||
return Expression.Constant(Vector256.Create(value.Value), Vec);
|
||||
case KInput input:
|
||||
return context.Inputs[(int)input.Channel];
|
||||
case KCoord coord:
|
||||
return coord.Axis == KAxis.X ? context.X : context.Y;
|
||||
case KUniformRef uniform:
|
||||
return Expression.Call(Broadcast, Expression.ArrayIndex(context.Uniforms, Constant((int)uniform.Uniform)));
|
||||
case KLocalRef local:
|
||||
return context.Slots[local.Slot];
|
||||
case KNegate negate:
|
||||
return Call(Negate, Build(negate.Operand, context));
|
||||
case KArith arithmetic:
|
||||
return BuildArithmetic(arithmetic, context);
|
||||
case KCall call:
|
||||
return BuildCall(call, context);
|
||||
case KSelect select:
|
||||
return Select(BuildBool(select.Condition, context), Build(select.WhenTrue, context), Build(select.WhenFalse, context));
|
||||
}
|
||||
throw new KernelUnsupportedException("Unsupported SIMD expression.");
|
||||
}
|
||||
|
||||
private static Expression BuildArithmetic(KArith arithmetic, Context context)
|
||||
{
|
||||
var left = Build(arithmetic.Left, context);
|
||||
var right = Build(arithmetic.Right, context);
|
||||
return arithmetic.Op switch
|
||||
{
|
||||
KArithOp.Add => Call(Add, left, right),
|
||||
KArithOp.Subtract => Call(Subtract, left, right),
|
||||
KArithOp.Multiply => Call(Multiply, left, right),
|
||||
KArithOp.Divide => Call(Divide, left, right),
|
||||
KArithOp.Modulo => Call(Subtract, left, Call(Multiply, Call(FloorFn, Call(Divide, left, right)), right)),
|
||||
_ => throw new KernelUnsupportedException("Unsupported SIMD arithmetic operator."),
|
||||
};
|
||||
}
|
||||
|
||||
private static Expression BuildCall(KCall call, Context context)
|
||||
{
|
||||
var argument = Build(call.Arguments[0], context);
|
||||
return call.Func switch
|
||||
{
|
||||
KFunc.Abs => Call(Abs, argument),
|
||||
KFunc.Floor => Call(FloorFn, argument),
|
||||
KFunc.Ceil => Call(CeilingFn, argument),
|
||||
KFunc.Sqrt => Call(Sqrt, argument),
|
||||
_ => throw new KernelUnsupportedException("Unsupported SIMD function."),
|
||||
};
|
||||
}
|
||||
|
||||
private static Expression BuildBool(KBool condition, Context context)
|
||||
{
|
||||
switch (condition)
|
||||
{
|
||||
case KBoolConst value:
|
||||
return value.Value ? AllBits : Zero;
|
||||
case KNot not:
|
||||
return Call(OnesComplement, BuildBool(not.Operand, context));
|
||||
case KLogical logical:
|
||||
return logical.IsAnd
|
||||
? Call(BitwiseAnd, BuildBool(logical.Left, context), BuildBool(logical.Right, context))
|
||||
: Call(BitwiseOr, BuildBool(logical.Left, context), BuildBool(logical.Right, context));
|
||||
case KCompare compare:
|
||||
var left = Build(compare.Left, context);
|
||||
var right = Build(compare.Right, context);
|
||||
return compare.Op switch
|
||||
{
|
||||
KCompareOp.Less => Call(LessThan, left, right),
|
||||
KCompareOp.Greater => Call(GreaterThan, left, right),
|
||||
KCompareOp.LessEqual => Call(LessThanOrEqual, left, right),
|
||||
KCompareOp.GreaterEqual => Call(GreaterThanOrEqual, left, right),
|
||||
KCompareOp.Equal => Call(EqualsFn, left, right),
|
||||
KCompareOp.NotEqual => Call(OnesComplement, Call(EqualsFn, left, right)),
|
||||
_ => throw new KernelUnsupportedException("Unsupported SIMD comparison."),
|
||||
};
|
||||
}
|
||||
throw new KernelUnsupportedException("Unsupported SIMD condition.");
|
||||
}
|
||||
|
||||
private static Expression ClampByte(Expression value)
|
||||
{
|
||||
var low = Select(Call(LessThan, value, Zero), Zero, value);
|
||||
return Select(Call(GreaterThan, low, V255), V255, low);
|
||||
}
|
||||
|
||||
private static Expression Select(Expression condition, Expression whenTrue, Expression whenFalse) =>
|
||||
Expression.Call(ConditionalSelect, condition, whenTrue, whenFalse);
|
||||
|
||||
private static Expression LoadChannel(ParameterExpression buffer, ParameterExpression index, int offset) =>
|
||||
Expression.Call(Create4,
|
||||
ToDouble(ReadByte(buffer, index, offset)),
|
||||
ToDouble(ReadByte(buffer, index, offset + 4)),
|
||||
ToDouble(ReadByte(buffer, index, offset + 8)),
|
||||
ToDouble(ReadByte(buffer, index, offset + 12)));
|
||||
|
||||
private static Expression StoreChannel(ParameterExpression buffer, ParameterExpression index, int offset, Expression value)
|
||||
{
|
||||
var writes = new Expression[4];
|
||||
for (int lane = 0; lane < 4; lane++)
|
||||
writes[lane] = Expression.Assign(
|
||||
Expression.ArrayAccess(buffer, Expression.Add(index, Constant(lane * 4 + offset))),
|
||||
Expression.Convert(Expression.Call(GetElement, value, Constant(lane)), typeof(byte)));
|
||||
return Expression.Block(writes);
|
||||
}
|
||||
|
||||
private static Expression ReadByte(ParameterExpression buffer, ParameterExpression index, int offset) =>
|
||||
Expression.ArrayIndex(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset)));
|
||||
|
||||
private static Expression Call(MethodInfo method, params Expression[] arguments) =>
|
||||
Expression.Call(method, arguments);
|
||||
|
||||
private static Expression ToDouble(Expression value) => Expression.Convert(value, typeof(double));
|
||||
|
||||
private static ConstantExpression Constant(int value) => Expression.Constant(value, typeof(int));
|
||||
|
||||
private static MethodInfo VecOp(string name, int vectorArgs, int intArgs = 0) =>
|
||||
typeof(Vector256).GetMethods()
|
||||
.Single(m => m.Name == name && m.IsGenericMethodDefinition &&
|
||||
m.GetParameters().Length == vectorArgs + intArgs &&
|
||||
m.GetParameters().Take(vectorArgs).All(p => IsVector(p.ParameterType)) &&
|
||||
m.GetParameters().Skip(vectorArgs).All(p => p.ParameterType == typeof(int)))
|
||||
.MakeGenericMethod(typeof(double));
|
||||
|
||||
private static bool IsVector(Type type) =>
|
||||
type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Vector256<>);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KArith(KArithOp Op, KExpr Left, KExpr Right) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KArithOp
|
||||
{
|
||||
Add,
|
||||
Subtract,
|
||||
Multiply,
|
||||
Divide,
|
||||
Modulo,
|
||||
Power,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KAxis
|
||||
{
|
||||
X,
|
||||
Y,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal abstract record KBool;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KBoolConst(bool Value) : KBool;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KCall(KFunc Func, IReadOnlyList<KExpr> Arguments) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KChannel
|
||||
{
|
||||
R,
|
||||
G,
|
||||
B,
|
||||
A,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KCompare(KCompareOp Op, KExpr Left, KExpr Right) : KBool;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KCompareOp
|
||||
{
|
||||
Less,
|
||||
Greater,
|
||||
LessEqual,
|
||||
GreaterEqual,
|
||||
Equal,
|
||||
NotEqual,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KConst(double Value) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KCoord(KAxis Axis) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal abstract record KExpr;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KFunc
|
||||
{
|
||||
Abs,
|
||||
Floor,
|
||||
Ceil,
|
||||
Sqrt,
|
||||
Sin,
|
||||
Cos,
|
||||
Tan,
|
||||
Asin,
|
||||
Acos,
|
||||
Atan,
|
||||
Atan2,
|
||||
Exp,
|
||||
Log,
|
||||
Pow,
|
||||
Min,
|
||||
Max,
|
||||
Fmod,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal readonly record struct KFunctionInfo(KFunc Func, string Name, int MinArgs, int MaxArgs);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal static class KFunctions
|
||||
{
|
||||
private static readonly KFunctionInfo[] Catalog =
|
||||
[
|
||||
new(KFunc.Abs, "abs", 1, 1),
|
||||
new(KFunc.Floor, "floor", 1, 1),
|
||||
new(KFunc.Ceil, "ceil", 1, 1),
|
||||
new(KFunc.Sqrt, "sqrt", 1, 1),
|
||||
new(KFunc.Sin, "sin", 1, 1),
|
||||
new(KFunc.Cos, "cos", 1, 1),
|
||||
new(KFunc.Tan, "tan", 1, 1),
|
||||
new(KFunc.Asin, "asin", 1, 1),
|
||||
new(KFunc.Acos, "acos", 1, 1),
|
||||
new(KFunc.Atan, "atan", 1, 1),
|
||||
new(KFunc.Atan2, "atan2", 2, 2),
|
||||
new(KFunc.Exp, "exp", 1, 1),
|
||||
new(KFunc.Log, "log", 1, 1),
|
||||
new(KFunc.Pow, "pow", 2, 2),
|
||||
new(KFunc.Min, "min", 2, int.MaxValue),
|
||||
new(KFunc.Max, "max", 2, int.MaxValue),
|
||||
new(KFunc.Fmod, "fmod", 2, 2),
|
||||
];
|
||||
|
||||
private static readonly Dictionary<string, KFunctionInfo> ByName = BuildByName();
|
||||
private static readonly string[] Intrinsics = BuildIntrinsics();
|
||||
|
||||
public static bool TryResolve(string name, out KFunctionInfo info) => ByName.TryGetValue(name, out info);
|
||||
|
||||
public static string Intrinsic(KFunc func) => Intrinsics[(int)func];
|
||||
|
||||
private static Dictionary<string, KFunctionInfo> BuildByName()
|
||||
{
|
||||
var map = new Dictionary<string, KFunctionInfo>(Catalog.Length, StringComparer.Ordinal);
|
||||
foreach (var info in Catalog)
|
||||
map[info.Name] = info;
|
||||
return map;
|
||||
}
|
||||
|
||||
private static string[] BuildIntrinsics()
|
||||
{
|
||||
var names = new string[Enum.GetValues<KFunc>().Length];
|
||||
foreach (var info in Catalog)
|
||||
names[(int)info.Func] = info.Name;
|
||||
return names;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KInput(KChannel Channel) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KLocalRef(int Slot) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KLogical(bool IsAnd, KBool Left, KBool Right) : KBool;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KNegate(KExpr Operand) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KNot(KBool Operand) : KBool;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KSelect(KBool Condition, KExpr WhenTrue, KExpr WhenFalse) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KUniformRef(KernelUniform Uniform) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KernelProgram(
|
||||
IReadOnlyList<KExpr> Bindings,
|
||||
KExpr OutputR,
|
||||
KExpr OutputG,
|
||||
KExpr OutputB,
|
||||
KExpr OutputA,
|
||||
IReadOnlyList<KernelUniform> Uniforms);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KernelUniform
|
||||
{
|
||||
Width,
|
||||
Height,
|
||||
HalfWidth,
|
||||
HalfHeight,
|
||||
CenterX,
|
||||
CenterY,
|
||||
CenterZ,
|
||||
Diagonal,
|
||||
X,
|
||||
Y,
|
||||
Z,
|
||||
Ox,
|
||||
Oy,
|
||||
Oz,
|
||||
Sx,
|
||||
Sy,
|
||||
Sz,
|
||||
Zoom,
|
||||
Aspect,
|
||||
Alpha,
|
||||
Rx,
|
||||
Ry,
|
||||
Rz,
|
||||
Rxr,
|
||||
Ryr,
|
||||
Rzr,
|
||||
Track0,
|
||||
Track1,
|
||||
Track2,
|
||||
Track3,
|
||||
Slider0,
|
||||
Slider1,
|
||||
Slider2,
|
||||
Slider3,
|
||||
Check0,
|
||||
Check1,
|
||||
Check2,
|
||||
Check3,
|
||||
Color,
|
||||
Time,
|
||||
Frame,
|
||||
TotalFrame,
|
||||
TotalTime,
|
||||
T,
|
||||
Framerate,
|
||||
Layer,
|
||||
Index,
|
||||
Num,
|
||||
SceneWidth,
|
||||
SceneHeight,
|
||||
SceneCenterX,
|
||||
SceneCenterY,
|
||||
TimelineFrame,
|
||||
TimelineTime,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal static class KernelUniforms
|
||||
{
|
||||
public static int Count { get; } = Enum.GetValues<KernelUniform>().Length;
|
||||
|
||||
private static readonly Dictionary<string, KernelUniform> Globals = new(StringComparer.Ordinal)
|
||||
{
|
||||
["time"] = KernelUniform.Time,
|
||||
["frame"] = KernelUniform.Frame,
|
||||
["totalframe"] = KernelUniform.TotalFrame,
|
||||
["framerate"] = KernelUniform.Framerate,
|
||||
["timelineframe"] = KernelUniform.TimelineFrame,
|
||||
["timelinetime"] = KernelUniform.TimelineTime,
|
||||
["layer"] = KernelUniform.Layer,
|
||||
["color"] = KernelUniform.Color,
|
||||
};
|
||||
|
||||
private static readonly Dictionary<string, KernelUniform> ObjectFields = new(StringComparer.Ordinal)
|
||||
{
|
||||
["w"] = KernelUniform.Width,
|
||||
["h"] = KernelUniform.Height,
|
||||
["hw"] = KernelUniform.HalfWidth,
|
||||
["hh"] = KernelUniform.HalfHeight,
|
||||
["cx"] = KernelUniform.CenterX,
|
||||
["cy"] = KernelUniform.CenterY,
|
||||
["cz"] = KernelUniform.CenterZ,
|
||||
["diagonal"] = KernelUniform.Diagonal,
|
||||
["x"] = KernelUniform.X,
|
||||
["y"] = KernelUniform.Y,
|
||||
["z"] = KernelUniform.Z,
|
||||
["ox"] = KernelUniform.Ox,
|
||||
["oy"] = KernelUniform.Oy,
|
||||
["oz"] = KernelUniform.Oz,
|
||||
["sx"] = KernelUniform.Sx,
|
||||
["sy"] = KernelUniform.Sy,
|
||||
["sz"] = KernelUniform.Sz,
|
||||
["zoom"] = KernelUniform.Zoom,
|
||||
["aspect"] = KernelUniform.Aspect,
|
||||
["alpha"] = KernelUniform.Alpha,
|
||||
["rx"] = KernelUniform.Rx,
|
||||
["ry"] = KernelUniform.Ry,
|
||||
["rz"] = KernelUniform.Rz,
|
||||
["rxr"] = KernelUniform.Rxr,
|
||||
["ryr"] = KernelUniform.Ryr,
|
||||
["rzr"] = KernelUniform.Rzr,
|
||||
["track0"] = KernelUniform.Track0,
|
||||
["track1"] = KernelUniform.Track1,
|
||||
["track2"] = KernelUniform.Track2,
|
||||
["track3"] = KernelUniform.Track3,
|
||||
["slider0"] = KernelUniform.Slider0,
|
||||
["slider1"] = KernelUniform.Slider1,
|
||||
["slider2"] = KernelUniform.Slider2,
|
||||
["slider3"] = KernelUniform.Slider3,
|
||||
["check0"] = KernelUniform.Check0,
|
||||
["check1"] = KernelUniform.Check1,
|
||||
["check2"] = KernelUniform.Check2,
|
||||
["check3"] = KernelUniform.Check3,
|
||||
["time"] = KernelUniform.Time,
|
||||
["frame"] = KernelUniform.Frame,
|
||||
["totalframe"] = KernelUniform.TotalFrame,
|
||||
["totaltime"] = KernelUniform.TotalTime,
|
||||
["t"] = KernelUniform.T,
|
||||
["framerate"] = KernelUniform.Framerate,
|
||||
["layer"] = KernelUniform.Layer,
|
||||
["index"] = KernelUniform.Index,
|
||||
["num"] = KernelUniform.Num,
|
||||
};
|
||||
|
||||
private static readonly Dictionary<string, KernelUniform> SceneFields = new(StringComparer.Ordinal)
|
||||
{
|
||||
["width"] = KernelUniform.SceneWidth,
|
||||
["height"] = KernelUniform.SceneHeight,
|
||||
["cx"] = KernelUniform.SceneCenterX,
|
||||
["cy"] = KernelUniform.SceneCenterY,
|
||||
};
|
||||
|
||||
public static bool TryResolveGlobal(string name, out KernelUniform uniform) =>
|
||||
Globals.TryGetValue(name, out uniform);
|
||||
|
||||
public static bool TryResolveMember(string target, string field, out KernelUniform uniform)
|
||||
{
|
||||
uniform = default;
|
||||
return target switch
|
||||
{
|
||||
"obj" => ObjectFields.TryGetValue(field, out uniform),
|
||||
"scene" => SceneFields.TryGetValue(field, out uniform),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
|
||||
public static string Field(KernelUniform uniform) => "u_" + uniform;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record AssignStmt(IReadOnlyList<LuaExpr> Targets, IReadOnlyList<LuaExpr> Values) : LuaStmt;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record BinaryExpr(string Operator, LuaExpr Left, LuaExpr Right) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record BoolExpr(bool Value) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record CallExpr(LuaExpr Target, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record CallStmt(LuaExpr Call) : LuaStmt;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record IfClause(LuaExpr Condition, IReadOnlyList<LuaStmt> Body);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record IfStmt(IReadOnlyList<IfClause> Clauses, IReadOnlyList<LuaStmt>? ElseBody) : LuaStmt;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record IndexExpr(LuaExpr Target, LuaExpr Key) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record LocalStmt(IReadOnlyList<string> Names, IReadOnlyList<LuaExpr> Values) : LuaStmt;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal abstract record LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal abstract record LuaStmt;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record MemberExpr(LuaExpr Target, string Name) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record MethodCallExpr(LuaExpr Target, string Method, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record NameExpr(string Name) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record NilExpr : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record NumberExpr(double Value) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record NumericForStmt(
|
||||
string Variable,
|
||||
LuaExpr Start,
|
||||
LuaExpr Stop,
|
||||
LuaExpr? Step,
|
||||
IReadOnlyList<LuaStmt> Body) : LuaStmt;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record StringExpr(string Value) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record UnaryExpr(string Operator, LuaExpr Operand) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal static class LuaLexer
|
||||
{
|
||||
private static readonly HashSet<string> Keywords = new(StringComparer.Ordinal)
|
||||
{
|
||||
"and", "break", "do", "else", "elseif", "end", "false", "for", "function",
|
||||
"if", "in", "local", "nil", "not", "or", "repeat", "return", "then",
|
||||
"true", "until", "while",
|
||||
};
|
||||
|
||||
public static List<LuaToken> Tokenize(string source)
|
||||
{
|
||||
var tokens = new List<LuaToken>();
|
||||
int i = 0;
|
||||
int length = source.Length;
|
||||
|
||||
while (i < length)
|
||||
{
|
||||
char c = source[i];
|
||||
|
||||
if (c is ' ' or '\t' or '\r' or '\n' or '\f' or '\v')
|
||||
{
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '-' && i + 1 < length && source[i + 1] == '-')
|
||||
{
|
||||
i = SkipComment(source, i + 2);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '"' || c == '\'')
|
||||
{
|
||||
i = ReadShortString(source, i, tokens);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '[' && i + 1 < length && (source[i + 1] == '[' || source[i + 1] == '='))
|
||||
{
|
||||
int level = LongBracketLevel(source, i);
|
||||
if (level >= 0)
|
||||
{
|
||||
i = ReadLongString(source, i, level, tokens);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (char.IsDigit(c) || (c == '.' && i + 1 < length && char.IsDigit(source[i + 1])))
|
||||
{
|
||||
i = ReadNumber(source, i, tokens);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (IsNameStart(c))
|
||||
{
|
||||
i = ReadName(source, i, tokens);
|
||||
continue;
|
||||
}
|
||||
|
||||
i = ReadSymbol(source, i, tokens);
|
||||
}
|
||||
|
||||
tokens.Add(new LuaToken(LuaTokenKind.Eof, string.Empty, 0d));
|
||||
return tokens;
|
||||
}
|
||||
|
||||
private static int SkipComment(string source, int i)
|
||||
{
|
||||
int level = LongBracketLevel(source, i);
|
||||
if (level >= 0)
|
||||
return SkipLongBracket(source, i, level);
|
||||
|
||||
int length = source.Length;
|
||||
while (i < length && source[i] != '\n')
|
||||
i++;
|
||||
return i;
|
||||
}
|
||||
|
||||
private static int LongBracketLevel(string source, int i)
|
||||
{
|
||||
if (i >= source.Length || source[i] != '[')
|
||||
return -1;
|
||||
int j = i + 1;
|
||||
int level = 0;
|
||||
while (j < source.Length && source[j] == '=')
|
||||
{
|
||||
level++;
|
||||
j++;
|
||||
}
|
||||
return j < source.Length && source[j] == '[' ? level : -1;
|
||||
}
|
||||
|
||||
private static int SkipLongBracket(string source, int i, int level)
|
||||
{
|
||||
int length = source.Length;
|
||||
i += level + 2;
|
||||
while (i < length)
|
||||
{
|
||||
if (source[i] == ']')
|
||||
{
|
||||
int j = i + 1;
|
||||
int count = 0;
|
||||
while (j < length && source[j] == '=')
|
||||
{
|
||||
count++;
|
||||
j++;
|
||||
}
|
||||
if (count == level && j < length && source[j] == ']')
|
||||
return j + 1;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
throw new KernelUnsupportedException("Unterminated long bracket.");
|
||||
}
|
||||
|
||||
private static int ReadLongString(string source, int start, int level, List<LuaToken> tokens)
|
||||
{
|
||||
int end = SkipLongBracket(source, start, level);
|
||||
int contentStart = start + level + 2;
|
||||
int contentEnd = end - level - 2;
|
||||
string text = source.Substring(contentStart, Math.Max(0, contentEnd - contentStart));
|
||||
tokens.Add(new LuaToken(LuaTokenKind.String, text, 0d));
|
||||
return end;
|
||||
}
|
||||
|
||||
private static int ReadShortString(string source, int start, List<LuaToken> tokens)
|
||||
{
|
||||
char quote = source[start];
|
||||
int i = start + 1;
|
||||
int length = source.Length;
|
||||
var value = new System.Text.StringBuilder();
|
||||
|
||||
while (i < length)
|
||||
{
|
||||
char c = source[i];
|
||||
if (c == quote)
|
||||
{
|
||||
tokens.Add(new LuaToken(LuaTokenKind.String, value.ToString(), 0d));
|
||||
return i + 1;
|
||||
}
|
||||
if (c == '\n')
|
||||
throw new KernelUnsupportedException("Unterminated string.");
|
||||
if (c == '\\')
|
||||
{
|
||||
i = ReadEscape(source, i + 1, value);
|
||||
continue;
|
||||
}
|
||||
value.Append(c);
|
||||
i++;
|
||||
}
|
||||
throw new KernelUnsupportedException("Unterminated string.");
|
||||
}
|
||||
|
||||
private static int ReadEscape(string source, int i, System.Text.StringBuilder value)
|
||||
{
|
||||
if (i >= source.Length)
|
||||
throw new KernelUnsupportedException("Unterminated string escape.");
|
||||
|
||||
char c = source[i];
|
||||
switch (c)
|
||||
{
|
||||
case 'n': value.Append('\n'); return i + 1;
|
||||
case 't': value.Append('\t'); return i + 1;
|
||||
case 'r': value.Append('\r'); return i + 1;
|
||||
case 'a': value.Append('\a'); return i + 1;
|
||||
case 'b': value.Append('\b'); return i + 1;
|
||||
case 'f': value.Append('\f'); return i + 1;
|
||||
case 'v': value.Append('\v'); return i + 1;
|
||||
case '\\': value.Append('\\'); return i + 1;
|
||||
case '"': value.Append('"'); return i + 1;
|
||||
case '\'': value.Append('\''); return i + 1;
|
||||
case '\n': value.Append('\n'); return i + 1;
|
||||
default:
|
||||
if (char.IsDigit(c))
|
||||
{
|
||||
int n = 0;
|
||||
int count = 0;
|
||||
while (i < source.Length && count < 3 && char.IsDigit(source[i]))
|
||||
{
|
||||
n = n * 10 + (source[i] - '0');
|
||||
i++;
|
||||
count++;
|
||||
}
|
||||
value.Append((char)n);
|
||||
return i;
|
||||
}
|
||||
value.Append(c);
|
||||
return i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
private static int ReadNumber(string source, int start, List<LuaToken> tokens)
|
||||
{
|
||||
int length = source.Length;
|
||||
int i = start;
|
||||
|
||||
if (source[i] == '0' && i + 1 < length && (source[i + 1] == 'x' || source[i + 1] == 'X'))
|
||||
{
|
||||
i += 2;
|
||||
int digitsStart = i;
|
||||
while (i < length && Uri.IsHexDigit(source[i]))
|
||||
i++;
|
||||
if (i == digitsStart)
|
||||
throw new KernelUnsupportedException("Malformed hexadecimal literal.");
|
||||
string hex = source.Substring(digitsStart, i - digitsStart);
|
||||
double hexValue = (double)ulong.Parse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
|
||||
tokens.Add(new LuaToken(LuaTokenKind.Number, source.Substring(start, i - start), hexValue));
|
||||
return i;
|
||||
}
|
||||
|
||||
while (i < length && char.IsDigit(source[i]))
|
||||
i++;
|
||||
if (i < length && source[i] == '.')
|
||||
{
|
||||
i++;
|
||||
while (i < length && char.IsDigit(source[i]))
|
||||
i++;
|
||||
}
|
||||
if (i < length && (source[i] == 'e' || source[i] == 'E'))
|
||||
{
|
||||
i++;
|
||||
if (i < length && (source[i] == '+' || source[i] == '-'))
|
||||
i++;
|
||||
while (i < length && char.IsDigit(source[i]))
|
||||
i++;
|
||||
}
|
||||
|
||||
string text = source.Substring(start, i - start);
|
||||
double value = double.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture);
|
||||
tokens.Add(new LuaToken(LuaTokenKind.Number, text, value));
|
||||
return i;
|
||||
}
|
||||
|
||||
private static int ReadName(string source, int start, List<LuaToken> tokens)
|
||||
{
|
||||
int i = start;
|
||||
int length = source.Length;
|
||||
while (i < length && IsNamePart(source[i]))
|
||||
i++;
|
||||
string text = source.Substring(start, i - start);
|
||||
tokens.Add(new LuaToken(Keywords.Contains(text) ? LuaTokenKind.Keyword : LuaTokenKind.Name, text, 0d));
|
||||
return i;
|
||||
}
|
||||
|
||||
private static int ReadSymbol(string source, int start, List<LuaToken> tokens)
|
||||
{
|
||||
int length = source.Length;
|
||||
char c = source[start];
|
||||
|
||||
if (c == '.' && start + 2 < length && source[start + 1] == '.' && source[start + 2] == '.')
|
||||
{
|
||||
tokens.Add(new LuaToken(LuaTokenKind.Symbol, "...", 0d));
|
||||
return start + 3;
|
||||
}
|
||||
|
||||
if (start + 1 < length)
|
||||
{
|
||||
string two = source.Substring(start, 2);
|
||||
switch (two)
|
||||
{
|
||||
case "==":
|
||||
case "~=":
|
||||
case "<=":
|
||||
case ">=":
|
||||
case "..":
|
||||
tokens.Add(new LuaToken(LuaTokenKind.Symbol, two, 0d));
|
||||
return start + 2;
|
||||
}
|
||||
}
|
||||
|
||||
switch (c)
|
||||
{
|
||||
case '+':
|
||||
case '-':
|
||||
case '*':
|
||||
case '/':
|
||||
case '%':
|
||||
case '^':
|
||||
case '#':
|
||||
case '<':
|
||||
case '>':
|
||||
case '=':
|
||||
case '(':
|
||||
case ')':
|
||||
case '{':
|
||||
case '}':
|
||||
case '[':
|
||||
case ']':
|
||||
case ';':
|
||||
case ':':
|
||||
case ',':
|
||||
case '.':
|
||||
tokens.Add(new LuaToken(LuaTokenKind.Symbol, c.ToString(), 0d));
|
||||
return start + 1;
|
||||
default:
|
||||
throw new KernelUnsupportedException($"Unexpected character '{c}'.");
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsNameStart(char c) => c == '_' || char.IsLetter(c);
|
||||
|
||||
private static bool IsNamePart(char c) => c == '_' || char.IsLetterOrDigit(c);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed class LuaParser
|
||||
{
|
||||
private readonly List<LuaToken> _tokens;
|
||||
private int _pos;
|
||||
|
||||
private LuaParser(List<LuaToken> tokens) => _tokens = tokens;
|
||||
|
||||
public static IReadOnlyList<LuaStmt> Parse(string source)
|
||||
{
|
||||
var parser = new LuaParser(LuaLexer.Tokenize(source));
|
||||
var block = parser.ParseBlock();
|
||||
parser.Expect(LuaTokenKind.Eof);
|
||||
return block;
|
||||
}
|
||||
|
||||
private LuaToken Current => _tokens[_pos];
|
||||
|
||||
private LuaToken Advance() => _tokens[_pos++];
|
||||
|
||||
private bool IsBlockEnd()
|
||||
{
|
||||
var t = Current;
|
||||
return t.Kind == LuaTokenKind.Eof ||
|
||||
t.IsKeyword("end") || t.IsKeyword("else") || t.IsKeyword("elseif") || t.IsKeyword("until");
|
||||
}
|
||||
|
||||
private IReadOnlyList<LuaStmt> ParseBlock()
|
||||
{
|
||||
var statements = new List<LuaStmt>();
|
||||
while (!IsBlockEnd())
|
||||
{
|
||||
if (Current.IsSymbol(";"))
|
||||
{
|
||||
Advance();
|
||||
continue;
|
||||
}
|
||||
statements.Add(ParseStatement());
|
||||
}
|
||||
return statements;
|
||||
}
|
||||
|
||||
private LuaStmt ParseStatement()
|
||||
{
|
||||
var t = Current;
|
||||
if (t.IsKeyword("local"))
|
||||
return ParseLocal();
|
||||
if (t.IsKeyword("if"))
|
||||
return ParseIf();
|
||||
if (t.IsKeyword("for"))
|
||||
return ParseFor();
|
||||
if (t.Kind == LuaTokenKind.Keyword)
|
||||
throw new KernelUnsupportedException($"Unsupported statement '{t.Text}'.");
|
||||
return ParseExpressionStatement();
|
||||
}
|
||||
|
||||
private LuaStmt ParseLocal()
|
||||
{
|
||||
Advance();
|
||||
if (Current.IsKeyword("function"))
|
||||
throw new KernelUnsupportedException("Local functions are not supported.");
|
||||
|
||||
var names = new List<string> { ExpectName() };
|
||||
while (Current.IsSymbol(","))
|
||||
{
|
||||
Advance();
|
||||
names.Add(ExpectName());
|
||||
}
|
||||
|
||||
IReadOnlyList<LuaExpr> values = [];
|
||||
if (Current.IsSymbol("="))
|
||||
{
|
||||
Advance();
|
||||
values = ParseExpressionList();
|
||||
}
|
||||
return new LocalStmt(names, values);
|
||||
}
|
||||
|
||||
private LuaStmt ParseIf()
|
||||
{
|
||||
Advance();
|
||||
var clauses = new List<IfClause>();
|
||||
|
||||
var condition = ParseExpression();
|
||||
ExpectKeyword("then");
|
||||
clauses.Add(new IfClause(condition, ParseBlock()));
|
||||
|
||||
while (Current.IsKeyword("elseif"))
|
||||
{
|
||||
Advance();
|
||||
var elseifCondition = ParseExpression();
|
||||
ExpectKeyword("then");
|
||||
clauses.Add(new IfClause(elseifCondition, ParseBlock()));
|
||||
}
|
||||
|
||||
IReadOnlyList<LuaStmt>? elseBody = null;
|
||||
if (Current.IsKeyword("else"))
|
||||
{
|
||||
Advance();
|
||||
elseBody = ParseBlock();
|
||||
}
|
||||
|
||||
ExpectKeyword("end");
|
||||
return new IfStmt(clauses, elseBody);
|
||||
}
|
||||
|
||||
private LuaStmt ParseFor()
|
||||
{
|
||||
Advance();
|
||||
string variable = ExpectName();
|
||||
if (!Current.IsSymbol("="))
|
||||
throw new KernelUnsupportedException("Generic for loops are not supported.");
|
||||
|
||||
Advance();
|
||||
var start = ParseExpression();
|
||||
ExpectSymbol(",");
|
||||
var stop = ParseExpression();
|
||||
|
||||
LuaExpr? step = null;
|
||||
if (Current.IsSymbol(","))
|
||||
{
|
||||
Advance();
|
||||
step = ParseExpression();
|
||||
}
|
||||
|
||||
ExpectKeyword("do");
|
||||
var body = ParseBlock();
|
||||
ExpectKeyword("end");
|
||||
return new NumericForStmt(variable, start, stop, step, body);
|
||||
}
|
||||
|
||||
private LuaStmt ParseExpressionStatement()
|
||||
{
|
||||
var first = ParseSuffixedExpression();
|
||||
|
||||
if (Current.IsSymbol("=") || Current.IsSymbol(","))
|
||||
{
|
||||
var targets = new List<LuaExpr> { first };
|
||||
while (Current.IsSymbol(","))
|
||||
{
|
||||
Advance();
|
||||
targets.Add(ParseSuffixedExpression());
|
||||
}
|
||||
ExpectSymbol("=");
|
||||
var values = ParseExpressionList();
|
||||
return new AssignStmt(targets, values);
|
||||
}
|
||||
|
||||
if (first is CallExpr or MethodCallExpr)
|
||||
return new CallStmt(first);
|
||||
|
||||
throw new KernelUnsupportedException("Expression is not a valid statement.");
|
||||
}
|
||||
|
||||
private List<LuaExpr> ParseExpressionList()
|
||||
{
|
||||
var values = new List<LuaExpr> { ParseExpression() };
|
||||
while (Current.IsSymbol(","))
|
||||
{
|
||||
Advance();
|
||||
values.Add(ParseExpression());
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private LuaExpr ParseExpression(int minPrecedence = 0)
|
||||
{
|
||||
var left = ParseUnary();
|
||||
while (true)
|
||||
{
|
||||
var (op, precedence, rightAssociative) = PeekBinaryOperator();
|
||||
if (op is null || precedence < minPrecedence)
|
||||
break;
|
||||
Advance();
|
||||
int nextMinimum = rightAssociative ? precedence : precedence + 1;
|
||||
var right = ParseExpression(nextMinimum);
|
||||
left = new BinaryExpr(op, left, right);
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
private LuaExpr ParseUnary()
|
||||
{
|
||||
var t = Current;
|
||||
if (t.IsKeyword("not") || t.IsSymbol("-") || t.IsSymbol("#"))
|
||||
{
|
||||
Advance();
|
||||
return new UnaryExpr(t.Text, ParseExpression(7));
|
||||
}
|
||||
return ParseValue();
|
||||
}
|
||||
|
||||
private (string? Operator, int Precedence, bool RightAssociative) PeekBinaryOperator()
|
||||
{
|
||||
var t = Current;
|
||||
if (t.IsKeyword("or")) return ("or", 1, false);
|
||||
if (t.IsKeyword("and")) return ("and", 2, false);
|
||||
if (t.Kind == LuaTokenKind.Symbol)
|
||||
{
|
||||
switch (t.Text)
|
||||
{
|
||||
case "<":
|
||||
case ">":
|
||||
case "<=":
|
||||
case ">=":
|
||||
case "~=":
|
||||
case "==":
|
||||
return (t.Text, 3, false);
|
||||
case "..":
|
||||
return ("..", 4, true);
|
||||
case "+":
|
||||
case "-":
|
||||
return (t.Text, 5, false);
|
||||
case "*":
|
||||
case "/":
|
||||
case "%":
|
||||
return (t.Text, 6, false);
|
||||
case "^":
|
||||
return ("^", 8, true);
|
||||
}
|
||||
}
|
||||
return (null, 0, false);
|
||||
}
|
||||
|
||||
private LuaExpr ParseValue()
|
||||
{
|
||||
var t = Current;
|
||||
switch (t.Kind)
|
||||
{
|
||||
case LuaTokenKind.Number:
|
||||
Advance();
|
||||
return new NumberExpr(t.Number);
|
||||
case LuaTokenKind.String:
|
||||
Advance();
|
||||
return new StringExpr(t.Text);
|
||||
case LuaTokenKind.Keyword when t.Text == "true":
|
||||
Advance();
|
||||
return new BoolExpr(true);
|
||||
case LuaTokenKind.Keyword when t.Text == "false":
|
||||
Advance();
|
||||
return new BoolExpr(false);
|
||||
case LuaTokenKind.Keyword when t.Text == "nil":
|
||||
Advance();
|
||||
return new NilExpr();
|
||||
}
|
||||
|
||||
if (t.IsKeyword("function") || t.IsSymbol("{") || t.IsSymbol("..."))
|
||||
throw new KernelUnsupportedException($"Unsupported expression near '{t.Text}'.");
|
||||
|
||||
return ParseSuffixedExpression();
|
||||
}
|
||||
|
||||
private LuaExpr ParseSuffixedExpression()
|
||||
{
|
||||
var expression = ParsePrimaryExpression();
|
||||
while (true)
|
||||
{
|
||||
var t = Current;
|
||||
if (t.IsSymbol("."))
|
||||
{
|
||||
Advance();
|
||||
expression = new MemberExpr(expression, ExpectName());
|
||||
}
|
||||
else if (t.IsSymbol("["))
|
||||
{
|
||||
Advance();
|
||||
var key = ParseExpression();
|
||||
ExpectSymbol("]");
|
||||
expression = new IndexExpr(expression, key);
|
||||
}
|
||||
else if (t.IsSymbol("("))
|
||||
{
|
||||
expression = new CallExpr(expression, ParseArguments());
|
||||
}
|
||||
else if (t.IsSymbol(":"))
|
||||
{
|
||||
Advance();
|
||||
string method = ExpectName();
|
||||
expression = new MethodCallExpr(expression, method, ParseArguments());
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
return expression;
|
||||
}
|
||||
|
||||
private LuaExpr ParsePrimaryExpression()
|
||||
{
|
||||
var t = Current;
|
||||
if (t.IsSymbol("("))
|
||||
{
|
||||
Advance();
|
||||
var inner = ParseExpression();
|
||||
ExpectSymbol(")");
|
||||
return inner;
|
||||
}
|
||||
if (t.Kind == LuaTokenKind.Name)
|
||||
{
|
||||
Advance();
|
||||
return new NameExpr(t.Text);
|
||||
}
|
||||
throw new KernelUnsupportedException($"Unexpected token '{t.Text}'.");
|
||||
}
|
||||
|
||||
private List<LuaExpr> ParseArguments()
|
||||
{
|
||||
ExpectSymbol("(");
|
||||
var arguments = new List<LuaExpr>();
|
||||
if (!Current.IsSymbol(")"))
|
||||
{
|
||||
arguments.Add(ParseExpression());
|
||||
while (Current.IsSymbol(","))
|
||||
{
|
||||
Advance();
|
||||
arguments.Add(ParseExpression());
|
||||
}
|
||||
}
|
||||
ExpectSymbol(")");
|
||||
return arguments;
|
||||
}
|
||||
|
||||
private string ExpectName()
|
||||
{
|
||||
if (Current.Kind != LuaTokenKind.Name)
|
||||
throw new KernelUnsupportedException($"Expected a name but found '{Current.Text}'.");
|
||||
return Advance().Text;
|
||||
}
|
||||
|
||||
private void Expect(LuaTokenKind kind)
|
||||
{
|
||||
if (Current.Kind != kind)
|
||||
throw new KernelUnsupportedException($"Expected {kind} but found '{Current.Text}'.");
|
||||
Advance();
|
||||
}
|
||||
|
||||
private void ExpectSymbol(string symbol)
|
||||
{
|
||||
if (!Current.IsSymbol(symbol))
|
||||
throw new KernelUnsupportedException($"Expected '{symbol}' but found '{Current.Text}'.");
|
||||
Advance();
|
||||
}
|
||||
|
||||
private void ExpectKeyword(string keyword)
|
||||
{
|
||||
if (!Current.IsKeyword(keyword))
|
||||
throw new KernelUnsupportedException($"Expected '{keyword}' but found '{Current.Text}'.");
|
||||
Advance();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal readonly struct LuaToken(LuaTokenKind kind, string text, double number)
|
||||
{
|
||||
public LuaTokenKind Kind { get; } = kind;
|
||||
public string Text { get; } = text;
|
||||
public double Number { get; } = number;
|
||||
|
||||
public bool Is(LuaTokenKind kind, string text) =>
|
||||
Kind == kind && string.Equals(Text, text, StringComparison.Ordinal);
|
||||
|
||||
public bool IsSymbol(string text) => Is(LuaTokenKind.Symbol, text);
|
||||
|
||||
public bool IsKeyword(string text) => Is(LuaTokenKind.Keyword, text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum LuaTokenKind
|
||||
{
|
||||
Name,
|
||||
Number,
|
||||
String,
|
||||
Keyword,
|
||||
Symbol,
|
||||
Eof,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.15.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="LuaScript" />
|
||||
<InternalsVisibleTo Include="LuaScript.Compat" />
|
||||
<InternalsVisibleTo Include="LuaScript.Runtime" />
|
||||
<InternalsVisibleTo Include="LuaScript.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,97 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Vortice.Mathematics;
|
||||
using Vortice.WIC;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class ImageDecoder : IDisposable
|
||||
{
|
||||
private const int MaxDimension = 8192;
|
||||
|
||||
private IWICImagingFactory? _factory;
|
||||
|
||||
public unsafe byte[] Decode(string path, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
if (string.IsNullOrEmpty(path) || !IsSupportedImage(path))
|
||||
return new byte[4];
|
||||
|
||||
try
|
||||
{
|
||||
_factory ??= new IWICImagingFactory();
|
||||
using var stream = _factory.CreateStream(path, FileAccess.Read);
|
||||
using var decoder = _factory.CreateDecoderFromStream(stream, DecodeOptions.CacheOnDemand);
|
||||
using var frame = decoder.GetFrame(0);
|
||||
using var converter = _factory.CreateFormatConverter();
|
||||
converter.Initialize(
|
||||
frame,
|
||||
Vortice.WIC.PixelFormat.Format32bppPBGRA,
|
||||
BitmapDitherType.None,
|
||||
null,
|
||||
0d,
|
||||
BitmapPaletteType.Custom);
|
||||
|
||||
converter.GetSize(out int w, out int h);
|
||||
if (w <= 0 || h <= 0 || w > MaxDimension || h > MaxDimension)
|
||||
return new byte[4];
|
||||
|
||||
var buffer = new byte[w * h * 4];
|
||||
fixed (byte* p = buffer)
|
||||
converter.CopyPixels(new RectI(0, 0, w, h), w * 4, buffer.Length, (nint)p);
|
||||
|
||||
width = w;
|
||||
height = h;
|
||||
return buffer;
|
||||
}
|
||||
catch
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsSupportedImage(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
return false;
|
||||
Span<byte> head = stackalloc byte[12];
|
||||
using var stream = File.OpenRead(path);
|
||||
int read = stream.Read(head);
|
||||
if (read < 4)
|
||||
return false;
|
||||
|
||||
if (head[0] == 0x89 && head[1] == 0x50 && head[2] == 0x4E && head[3] == 0x47)
|
||||
return true;
|
||||
if (head[0] == 0xFF && head[1] == 0xD8 && head[2] == 0xFF)
|
||||
return true;
|
||||
if (head[0] == 0x47 && head[1] == 0x49 && head[2] == 0x46 && head[3] == 0x38)
|
||||
return true;
|
||||
if (head[0] == 0x42 && head[1] == 0x4D)
|
||||
return true;
|
||||
if ((head[0] == 0x49 && head[1] == 0x49 && head[2] == 0x2A && head[3] == 0x00) ||
|
||||
(head[0] == 0x4D && head[1] == 0x4D && head[2] == 0x00 && head[3] == 0x2A))
|
||||
return true;
|
||||
if (read >= 12 &&
|
||||
head[0] == 0x52 && head[1] == 0x49 && head[2] == 0x46 && head[3] == 0x46 &&
|
||||
head[8] == 0x57 && head[9] == 0x45 && head[10] == 0x42 && head[11] == 0x50)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_factory?.Dispose();
|
||||
_factory = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.15.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="LuaScript" />
|
||||
<InternalsVisibleTo Include="LuaScript.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="SharpGen.Runtime">
|
||||
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="SharpGen.Runtime.COM">
|
||||
<HintPath>$(YMM4DirPath)SharpGen.Runtime.COM.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Direct2D1">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Direct2D1.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DirectX">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DirectX.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>
|
||||
<Reference Include="Vortice.MediaFoundation">
|
||||
<HintPath>$(YMM4DirPath)Vortice.MediaFoundation.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,213 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using SharpGen.Runtime.Win32;
|
||||
using Vortice.MediaFoundation;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class MovieDecoder : IDisposable
|
||||
{
|
||||
private const int MaxDimension = 8192;
|
||||
private const int FirstVideoStream = -4;
|
||||
private const int AllStreams = -2;
|
||||
private const int EndOfStreamFlag = 0x2;
|
||||
|
||||
private bool _mfStarted;
|
||||
private string? _path;
|
||||
private IMFSourceReader? _reader;
|
||||
private int _width;
|
||||
private int _height;
|
||||
private int _stride;
|
||||
|
||||
public unsafe byte[] Decode(string path, double timeSeconds, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
if (string.IsNullOrEmpty(path) || !IsSupportedVideo(path))
|
||||
return new byte[4];
|
||||
|
||||
try
|
||||
{
|
||||
EnsureReader(path);
|
||||
if (_reader is null || _width <= 0 || _height <= 0)
|
||||
return new byte[4];
|
||||
|
||||
SetPosition(_reader, (long)(Math.Max(0d, timeSeconds) * 10_000_000d));
|
||||
|
||||
using var sample = ReadVideoSample(_reader);
|
||||
if (sample is null)
|
||||
return new byte[4];
|
||||
|
||||
using var buffer = sample.ConvertToContiguousBuffer();
|
||||
buffer.Lock(out nint data, out _, out _);
|
||||
try
|
||||
{
|
||||
int w = _width;
|
||||
int h = _height;
|
||||
int absStride = Math.Abs(_stride);
|
||||
bool bottomUp = _stride < 0;
|
||||
var result = new byte[w * h * 4];
|
||||
byte* src = (byte*)data;
|
||||
fixed (byte* dst = result)
|
||||
{
|
||||
for (int y = 0; y < h; y++)
|
||||
{
|
||||
int sourceRow = bottomUp ? h - 1 - y : y;
|
||||
byte* s = src + sourceRow * absStride;
|
||||
byte* d = dst + y * w * 4;
|
||||
for (int x = 0; x < w; x++)
|
||||
{
|
||||
d[0] = s[0];
|
||||
d[1] = s[1];
|
||||
d[2] = s[2];
|
||||
d[3] = 255;
|
||||
s += 4;
|
||||
d += 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
width = w;
|
||||
height = h;
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
buffer.Unlock();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureReader(string path)
|
||||
{
|
||||
if (_reader is not null && string.Equals(_path, path, StringComparison.Ordinal))
|
||||
return;
|
||||
|
||||
DisposeReader();
|
||||
|
||||
if (!_mfStarted)
|
||||
{
|
||||
MediaFactory.MFStartup(false);
|
||||
_mfStarted = true;
|
||||
}
|
||||
|
||||
using var attributes = MediaFactory.MFCreateAttributes(1);
|
||||
attributes.Set(SourceReaderAttributeKeys.EnableAdvancedVideoProcessing, 1);
|
||||
var reader = MediaFactory.MFCreateSourceReaderFromURL(path, attributes);
|
||||
|
||||
reader.SetStreamSelection(AllStreams, false);
|
||||
reader.SetStreamSelection(FirstVideoStream, true);
|
||||
|
||||
using (var mediaType = MediaFactory.MFCreateMediaType())
|
||||
{
|
||||
mediaType.Set(MediaTypeAttributeKeys.MajorType, MediaTypeGuids.Video);
|
||||
mediaType.Set(MediaTypeAttributeKeys.Subtype, VideoFormatGuids.Rgb32);
|
||||
reader.SetCurrentMediaType(FirstVideoStream, mediaType);
|
||||
}
|
||||
|
||||
using var current = reader.GetCurrentMediaType(FirstVideoStream);
|
||||
var mediaAttributes = (IMFAttributes)current;
|
||||
ulong frameSize = Convert.ToUInt64(mediaAttributes.Get(MediaTypeAttributeKeys.FrameSize));
|
||||
int w = (int)(frameSize >> 32);
|
||||
int h = (int)(frameSize & 0xFFFFFFFF);
|
||||
|
||||
int stride;
|
||||
try { stride = Convert.ToInt32(mediaAttributes.Get(MediaTypeAttributeKeys.DefaultStride)); }
|
||||
catch { stride = w * 4; }
|
||||
if (stride == 0)
|
||||
stride = w * 4;
|
||||
|
||||
if (w <= 0 || h <= 0 || w > MaxDimension || h > MaxDimension)
|
||||
{
|
||||
reader.Dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
_reader = reader;
|
||||
_path = path;
|
||||
_width = w;
|
||||
_height = h;
|
||||
_stride = stride;
|
||||
}
|
||||
|
||||
private static void SetPosition(IMFSourceReader reader, long ticks)
|
||||
{
|
||||
var variant = new Variant
|
||||
{
|
||||
Value = ticks,
|
||||
ElementType = (VariantElementType)20,
|
||||
};
|
||||
reader.SetCurrentPosition(Guid.Empty, variant);
|
||||
}
|
||||
|
||||
private static IMFSample? ReadVideoSample(IMFSourceReader reader)
|
||||
{
|
||||
for (int guard = 0; guard < 256; guard++)
|
||||
{
|
||||
reader.ReadSample(FirstVideoStream, 0, out _, out int flags, out _, out IMFSample? sample);
|
||||
if (sample is not null)
|
||||
return sample;
|
||||
if ((flags & EndOfStreamFlag) != 0)
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool IsSupportedVideo(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
return false;
|
||||
Span<byte> head = stackalloc byte[16];
|
||||
using var stream = File.OpenRead(path);
|
||||
int read = stream.Read(head);
|
||||
if (read < 12)
|
||||
return false;
|
||||
|
||||
if (head[4] == 0x66 && head[5] == 0x74 && head[6] == 0x79 && head[7] == 0x70)
|
||||
return true;
|
||||
if (head[0] == 0x1A && head[1] == 0x45 && head[2] == 0xDF && head[3] == 0xA3)
|
||||
return true;
|
||||
if (head[0] == 0x52 && head[1] == 0x49 && head[2] == 0x46 && head[3] == 0x46 &&
|
||||
head[8] == 0x41 && head[9] == 0x56 && head[10] == 0x49 && head[11] == 0x20)
|
||||
return true;
|
||||
if (head[0] == 0x46 && head[1] == 0x4C && head[2] == 0x56)
|
||||
return true;
|
||||
if (head[0] == 0x30 && head[1] == 0x26 && head[2] == 0xB2 && head[3] == 0x75)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void DisposeReader()
|
||||
{
|
||||
_reader?.Dispose();
|
||||
_reader = null;
|
||||
_path = null;
|
||||
_width = 0;
|
||||
_height = 0;
|
||||
_stride = 0;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
DisposeReader();
|
||||
if (_mfStarted)
|
||||
{
|
||||
try { MediaFactory.MFShutdown(); }
|
||||
catch { }
|
||||
_mfStarted = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.DirectWrite;
|
||||
using Vortice.Mathematics;
|
||||
using Vortice.WIC;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class TextRenderer : IDisposable
|
||||
{
|
||||
private const int MaxDimension = 8192;
|
||||
private const string FallbackFamily = "Yu Gothic UI";
|
||||
|
||||
private ID2D1Factory? _d2dFactory;
|
||||
private IWICImagingFactory? _wicFactory;
|
||||
private IDWriteFactory? _dwriteFactory;
|
||||
|
||||
private void EnsureFactories()
|
||||
{
|
||||
_d2dFactory ??= D2D1.D2D1CreateFactory<ID2D1Factory>(
|
||||
Vortice.Direct2D1.FactoryType.MultiThreaded, DebugLevel.None);
|
||||
_wicFactory ??= new IWICImagingFactory();
|
||||
_dwriteFactory ??= DWrite.DWriteCreateFactory<IDWriteFactory>(
|
||||
Vortice.DirectWrite.FactoryType.Shared);
|
||||
}
|
||||
|
||||
public unsafe byte[] Render(
|
||||
string text, string fontFamily, double fontSize,
|
||||
bool bold, bool italic, int colorRgb,
|
||||
out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
if (string.IsNullOrEmpty(text))
|
||||
return new byte[4];
|
||||
|
||||
EnsureFactories();
|
||||
|
||||
float size = (float)Math.Clamp(fontSize, 1d, 4096d);
|
||||
using var format = _dwriteFactory!.CreateTextFormat(
|
||||
string.IsNullOrWhiteSpace(fontFamily) ? FallbackFamily : fontFamily,
|
||||
null,
|
||||
bold ? FontWeight.Bold : FontWeight.Normal,
|
||||
italic ? FontStyle.Italic : FontStyle.Normal,
|
||||
FontStretch.Normal,
|
||||
size,
|
||||
string.Empty);
|
||||
|
||||
using var layout = _dwriteFactory.CreateTextLayout(text, format, MaxDimension, MaxDimension);
|
||||
var metrics = layout.Metrics;
|
||||
int w = Math.Clamp((int)Math.Ceiling(metrics.WidthIncludingTrailingWhitespace), 1, MaxDimension);
|
||||
int h = Math.Clamp((int)Math.Ceiling(metrics.Height), 1, MaxDimension);
|
||||
|
||||
using var wic = _wicFactory!.CreateBitmap(
|
||||
w, h, Vortice.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnLoad);
|
||||
|
||||
var properties = new RenderTargetProperties(
|
||||
RenderTargetType.Default,
|
||||
new Vortice.DCommon.PixelFormat(Vortice.DXGI.Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
|
||||
96f, 96f,
|
||||
RenderTargetUsage.None,
|
||||
FeatureLevel.Default);
|
||||
|
||||
float r = ((colorRgb >> 16) & 0xFF) / 255f;
|
||||
float g = ((colorRgb >> 8) & 0xFF) / 255f;
|
||||
float b = (colorRgb & 0xFF) / 255f;
|
||||
|
||||
using (var target = _d2dFactory!.CreateWicBitmapRenderTarget(wic, properties))
|
||||
{
|
||||
target.BeginDraw();
|
||||
target.Clear(new Color4(0f, 0f, 0f, 0f));
|
||||
using (var brush = target.CreateSolidColorBrush(new Color4(r, g, b, 1f)))
|
||||
target.DrawTextLayout(new Vector2(-metrics.Left, -metrics.Top), layout, brush);
|
||||
target.EndDraw();
|
||||
}
|
||||
|
||||
var buffer = new byte[w * h * 4];
|
||||
fixed (byte* p = buffer)
|
||||
wic.CopyPixels(new RectI(0, 0, w, h), w * 4, buffer.Length, (nint)p);
|
||||
|
||||
width = w;
|
||||
height = h;
|
||||
return buffer;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_dwriteFactory?.Dispose();
|
||||
_wicFactory?.Dispose();
|
||||
_d2dFactory?.Dispose();
|
||||
_dwriteFactory = null;
|
||||
_wicFactory = null;
|
||||
_d2dFactory = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace LuaScript.Anchor
|
||||
{
|
||||
internal enum AnchorConnection
|
||||
{
|
||||
None,
|
||||
Line,
|
||||
Loop,
|
||||
Star,
|
||||
Arm,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Anchor
|
||||
{
|
||||
internal readonly record struct AnchorOptions(AnchorConnection Connection, bool Is3D);
|
||||
}
|
||||
268ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。
さらに表示
新しいイシューから参照
ユーザーをブロックする