コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
381a717942
|
検索条件に一致するファイルはありません
+43
-25
@@ -1,43 +1,61 @@
|
||||
# v1.13.4 - Lua スクリプト for YMM4
|
||||
# v1.10.0 - Lua スクリプト for YMM4
|
||||
|
||||
環境情報を取得する obj.getinfo を追加したリリースです。
|
||||
スクリプトの設置フォルダのパスや動画の出力状態に加えて、最大画像サイズ、BPMグリッドの情報、経過時間、本体のバージョンを名前で取得できます。MoonSharp とネイティブの両エンジンで同一の関数として動作します。
|
||||
あわせて、プラグインの内部構成を依存関係の層ごとの複数アセンブリへ分割し、Lua API の登録と入力補完をソースジェネレータによる宣言的な生成へ移行しました。既存のスクリプトの書き方と実行結果に変更はありません。
|
||||
エフェクトパネルへ新しいパラメータ入力欄を追加したリリースです。整数スライダー 4 本と、
|
||||
テキスト・フォント・フォルダ・ファイルの文字列入力をスクリプトから参照できるようにしました。
|
||||
文字列パラメータは MoonSharp とネイティブの両エンジンで同じ名前から参照でき、ネイティブでは
|
||||
共有メモリの文字列領域を必要量に応じて拡張・縮小します。あわせて毎フレームのアロケーションを
|
||||
見直し、補完候補を拡充しました。
|
||||
|
||||
---
|
||||
|
||||
## 新機能
|
||||
## 新機能・機能改善
|
||||
|
||||
### obj.getinfo による環境情報の取得
|
||||
### 1. 整数スライダー obj.slider0〜3
|
||||
|
||||
obj.getinfo(名前) は、名前で指定した環境情報を返します。対応していない名前を指定した場合は nil を返します。取得できる情報は次のとおりです。
|
||||
数値スライダーを 4 本追加しました。各値は `obj.slider0`〜`obj.slider3` として参照できます。
|
||||
|
||||
- "script_path" は、プラグインの設置フォルダのパスを返します。末尾には区切り文字が付きます。
|
||||
- "filter" は、フィルタ効果として処理中かどうかを返します。本プラグインでは常に true を返します。
|
||||
- "saving" は、動画を出力中のときだけ true を返します。
|
||||
- "image_max" は、最大画像サイズを横幅と高さの2つの値で返します。
|
||||
- "bpm" は、BPMグリッドのテンポと拍子と基準時間の3つの値を返します。基準時間の単位は秒です。BPMグリッドを設定していない場合はテンポが 0 になります。
|
||||
- "clock" は、YMM4 の起動からの経過時間を秒で返します。
|
||||
- "script_time" は、スクリプトの実行開始からの経過時間をミリ秒で返します。
|
||||
- "version" は、本体のバージョンを major×10000+minor×100+build の数値で返します。
|
||||
- 値は整数で、小数は扱いません。表示範囲は `obj.slider0` が 1〜10、`obj.slider1` が 0〜100、
|
||||
`obj.slider2` が 0〜1000、`obj.slider3` が -1000〜1000 です。
|
||||
- 状態の切り替えなど、補間を伴わない整数値の受け渡しに使えます。
|
||||
- MoonSharp・ネイティブ・CPU/GPU カーネルのいずれのレーンからも参照できます。
|
||||
|
||||
編集中のみプレビューへ枠を描き、出力時には描かないといった分岐へ利用できます。
|
||||
### 2. 文字列パラメータ obj.text / obj.font / obj.dir / obj.file_*
|
||||
|
||||
テキスト・フォント・フォルダ・ファイルの入力欄を追加しました。
|
||||
|
||||
- `obj.text` はテキスト入力欄の文字列、`obj.font` はフォント名、`obj.dir` はフォルダのパスです。
|
||||
- ファイル選択は種類ごとに `obj.file_video` / `obj.file_audio` / `obj.file_image` /
|
||||
`obj.file_project` / `obj.file_mp4` / `obj.file_exo` / `obj.file_subtitle` /
|
||||
`obj.file_shader` で参照し、選択したファイルのパスを取得します。
|
||||
- 取得したパスは `obj.load` へ渡して画像・動画の読み込みに使えます。
|
||||
- MoonSharp とネイティブの両エンジンで同じ名前から参照できます。
|
||||
|
||||
### 3. 補完候補の拡充
|
||||
|
||||
スクリプトエディタの補完候補へ `obj.slider0`〜`obj.slider3` と、追加した文字列パラメータの
|
||||
各名前を加えました。
|
||||
|
||||
---
|
||||
|
||||
## 互換性・後方互換
|
||||
|
||||
- 既存のスクリプトの書き方と実行結果に変更はありません。obj.getinfo は新規の関数であり、従来の呼び出しへは影響しません。
|
||||
- obj.getinfo は MoonSharp とネイティブの両エンジンで動作します。script_path、filter、saving、image_max、bpm、version は両エンジンで同一の値を返します。clock と script_time は経過時間の計測であり、値そのものは実行のたびに変わります。
|
||||
- v1.13.3 までの仕様に変更はありません。
|
||||
- スライダーと文字列パラメータは、スクリプト本体でそれらを参照したときだけエフェクトパネルへ
|
||||
表示されます。参照しない既存スクリプトの表示と挙動は変わりません。
|
||||
- CPU/GPU カーネルは数値計算に特化するため、文字列パラメータは扱いません。文字列を参照する
|
||||
スクリプトは MoonSharp かネイティブで実行してください。
|
||||
- トラックバー・チェックボックス・カラー・AviUtl 互換ヘッダの既存挙動は変わりません。
|
||||
|
||||
---
|
||||
|
||||
## 内部実装
|
||||
|
||||
- プラグインを依存関係の層ごとに LuaScript.Kernel、LuaScript.Compat、LuaScript.Media、LuaScript.Runtime、および本体の 5 つのアセンブリへ分割しました。名前空間は据え置き、参照の向きを一方向へ整理しています。
|
||||
- Lua API の登録と毎フレームの変数投影を、属性から生成するソースジェネレータへ移行しました。入力補完の候補もこの宣言から生成し、手書きの一覧を廃止しました。関数を 1 つ追加すると、登録と補完へ自動的に反映されます。
|
||||
- Kernel、Compat、Runtime の各プロジェクトを 1 ファイル 1 クラスへ整理し、ドメインごとのフォルダへ再配置しました。エンジンのテーブル管理は LuaScope へ汎用化しています。
|
||||
- 映像デコーダを LuaScript.Media プロジェクトへ分離し、ツールバーを View と ViewModel へ分離しました。ViewModel はフレームワークに依存しない構成へ整理しています。
|
||||
- obj.getinfo の実装では、BPMグリッドの情報を YMM4 のシーンから取得し、script_path と version は本体からエンジンへ渡します。経過時間は両エンジンがそれぞれ高精度タイマーで計測します。
|
||||
- テストは 3113 件です。v1.13.3 の 3092 件から、obj.getinfo の両エンジンでの実行結果の検証と、補完カタログの回帰検証、およびエンジンのテーブルライフサイクルの特性化検証を追加しました。
|
||||
- ネイティブの共有メモリへ文字列パラメータ領域を追加し、容量をワーカーの起動引数にしました。
|
||||
必要量が容量を超えると 2 倍へ拡張し、容量の半分以下に収まると縮小します。最小は 64KB で、
|
||||
容量の変化はワーカーの再生成のみで完結します。
|
||||
- 文字列パラメータの変更検出をバージョン方式へ変更し、フレームごとの署名文字列の生成を
|
||||
やめました。値の参照が変わったときだけ版数を進めます。
|
||||
- ネイティブの文字列書き込みで、名前のバイト列をキャッシュし、値のエンコード先バッファを
|
||||
再利用します。
|
||||
- スライダーの値は MoonSharp の obj テーブル・ネイティブのフィールド・CPU/GPU カーネルの
|
||||
ユニフォームへ配線しました。スクリプトの使用検出は obj メンバを汎用的に走査する方式へ
|
||||
再設計しました。
|
||||
@@ -1,5 +1,5 @@
|
||||
========================================
|
||||
Luaスクリプト for YMM4 v1.13.4
|
||||
Luaスクリプト for YMM4 v1.10.0
|
||||
========================================
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||
ピクセルを直接制御できるプラグインです。
|
||||
|
||||
@@ -73,10 +73,6 @@ 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/"
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</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" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="AviUtlCompatMap.xml" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,9 +0,0 @@
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal enum AviUtlEngine
|
||||
{
|
||||
AviUtl,
|
||||
AviUtl2,
|
||||
Both,
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal readonly record struct AviUtlParameterMapping(string Source, string Property, double Scale, double Offset)
|
||||
{
|
||||
public double Transform(double value) => value * Scale + Offset;
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace System.Runtime.CompilerServices
|
||||
{
|
||||
internal static class IsExternalInit;
|
||||
}
|
||||
@@ -1,486 +0,0 @@
|
||||
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)];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</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>
|
||||
@@ -1,95 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,270 +0,0 @@
|
||||
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<>);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KArith(KArithOp Op, KExpr Left, KExpr Right) : KExpr;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KArithOp
|
||||
{
|
||||
Add,
|
||||
Subtract,
|
||||
Multiply,
|
||||
Divide,
|
||||
Modulo,
|
||||
Power,
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KAxis
|
||||
{
|
||||
X,
|
||||
Y,
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal abstract record KBool;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KBoolConst(bool Value) : KBool;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KCall(KFunc Func, IReadOnlyList<KExpr> Arguments) : KExpr;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KChannel
|
||||
{
|
||||
R,
|
||||
G,
|
||||
B,
|
||||
A,
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KCompare(KCompareOp Op, KExpr Left, KExpr Right) : KBool;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KCompareOp
|
||||
{
|
||||
Less,
|
||||
Greater,
|
||||
LessEqual,
|
||||
GreaterEqual,
|
||||
Equal,
|
||||
NotEqual,
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KConst(double Value) : KExpr;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KCoord(KAxis Axis) : KExpr;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal abstract record KExpr;
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KFunc
|
||||
{
|
||||
Abs,
|
||||
Floor,
|
||||
Ceil,
|
||||
Sqrt,
|
||||
Sin,
|
||||
Cos,
|
||||
Tan,
|
||||
Asin,
|
||||
Acos,
|
||||
Atan,
|
||||
Atan2,
|
||||
Exp,
|
||||
Log,
|
||||
Pow,
|
||||
Min,
|
||||
Max,
|
||||
Fmod,
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal readonly record struct KFunctionInfo(KFunc Func, string Name, int MinArgs, int MaxArgs);
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KInput(KChannel Channel) : KExpr;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KLocalRef(int Slot) : KExpr;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KLogical(bool IsAnd, KBool Left, KBool Right) : KBool;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KNegate(KExpr Operand) : KExpr;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KNot(KBool Operand) : KBool;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KSelect(KBool Condition, KExpr WhenTrue, KExpr WhenFalse) : KExpr;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KUniformRef(KernelUniform Uniform) : KExpr;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KernelProgram(
|
||||
IReadOnlyList<KExpr> Bindings,
|
||||
KExpr OutputR,
|
||||
KExpr OutputG,
|
||||
KExpr OutputB,
|
||||
KExpr OutputA,
|
||||
IReadOnlyList<KernelUniform> Uniforms);
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record AssignStmt(IReadOnlyList<LuaExpr> Targets, IReadOnlyList<LuaExpr> Values) : LuaStmt;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record BinaryExpr(string Operator, LuaExpr Left, LuaExpr Right) : LuaExpr;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record BoolExpr(bool Value) : LuaExpr;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record CallExpr(LuaExpr Target, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record CallStmt(LuaExpr Call) : LuaStmt;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record IfClause(LuaExpr Condition, IReadOnlyList<LuaStmt> Body);
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record IfStmt(IReadOnlyList<IfClause> Clauses, IReadOnlyList<LuaStmt>? ElseBody) : LuaStmt;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record IndexExpr(LuaExpr Target, LuaExpr Key) : LuaExpr;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record LocalStmt(IReadOnlyList<string> Names, IReadOnlyList<LuaExpr> Values) : LuaStmt;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal abstract record LuaExpr;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal abstract record LuaStmt;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record MemberExpr(LuaExpr Target, string Name) : LuaExpr;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record MethodCallExpr(LuaExpr Target, string Method, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record NameExpr(string Name) : LuaExpr;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record NilExpr : LuaExpr;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record NumberExpr(double Value) : LuaExpr;
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record NumericForStmt(
|
||||
string Variable,
|
||||
LuaExpr Start,
|
||||
LuaExpr Stop,
|
||||
LuaExpr? Step,
|
||||
IReadOnlyList<LuaStmt> Body) : LuaStmt;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record StringExpr(string Value) : LuaExpr;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record UnaryExpr(string Operator, LuaExpr Operand) : LuaExpr;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum LuaTokenKind
|
||||
{
|
||||
Name,
|
||||
Number,
|
||||
String,
|
||||
Keyword,
|
||||
Symbol,
|
||||
Eof,
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</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>
|
||||
@@ -1,48 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</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>
|
||||
@@ -1,11 +0,0 @@
|
||||
namespace LuaScript.Anchor
|
||||
{
|
||||
internal enum AnchorConnection
|
||||
{
|
||||
None,
|
||||
Line,
|
||||
Loop,
|
||||
Star,
|
||||
Arm,
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Anchor
|
||||
{
|
||||
internal readonly record struct AnchorOptions(AnchorConnection Connection, bool Is3D);
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Anchor
|
||||
{
|
||||
internal readonly record struct AnchorRequestData(string Group, int Count, AnchorConnection Connection, bool Is3D);
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace LuaScript.Anchor
|
||||
{
|
||||
internal static class AnchorSupport
|
||||
{
|
||||
public const int MaxAnchors = 32;
|
||||
public const string TrackGroup = "track";
|
||||
|
||||
public static int ClampCount(int count) => Math.Clamp(count, 0, MaxAnchors);
|
||||
|
||||
public static void ApplyOption(string option, ref AnchorConnection connection, ref bool is3D)
|
||||
{
|
||||
switch (option)
|
||||
{
|
||||
case "line": connection = AnchorConnection.Line; break;
|
||||
case "loop": connection = AnchorConnection.Loop; break;
|
||||
case "star": connection = AnchorConnection.Star; break;
|
||||
case "arm": connection = AnchorConnection.Arm; break;
|
||||
case "xyz": is3D = true; break;
|
||||
}
|
||||
}
|
||||
|
||||
public static (double X, double Y) DefaultPosition(int index)
|
||||
{
|
||||
int col = index % 8;
|
||||
int row = index / 8;
|
||||
return ((col - 3.5) * 60d, (row - 1.5) * 60d);
|
||||
}
|
||||
|
||||
public static void ResolvePosition(IReadOnlyList<LuaAnchorPoint>? source, string group, int index,
|
||||
out double x, out double y, out double z)
|
||||
{
|
||||
if (source is not null)
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var a = source[i];
|
||||
if (a.Index == index && string.Equals(a.Group, group, StringComparison.Ordinal))
|
||||
{
|
||||
x = a.X;
|
||||
y = a.Y;
|
||||
z = a.Z;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var (dx, dy) = DefaultPosition(index);
|
||||
x = dx;
|
||||
y = dy;
|
||||
z = 0d;
|
||||
}
|
||||
|
||||
public static ImmutableList<LuaAnchorPoint> ApplyDrag(
|
||||
ImmutableList<LuaAnchorPoint> source, string group, int index, double dx, double dy, double dz)
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var a = source[i];
|
||||
if (a.Index == index && string.Equals(a.Group, group, StringComparison.Ordinal))
|
||||
{
|
||||
return source.SetItem(i, new LuaAnchorPoint
|
||||
{
|
||||
Group = group,
|
||||
Index = index,
|
||||
X = a.X + dx,
|
||||
Y = a.Y + dy,
|
||||
Z = a.Z + dz,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
var (bx, by) = DefaultPosition(index);
|
||||
return source.Add(new LuaAnchorPoint
|
||||
{
|
||||
Group = group,
|
||||
Index = index,
|
||||
X = bx + dx,
|
||||
Y = by + dy,
|
||||
Z = dz,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
namespace LuaScript.Anchor
|
||||
{
|
||||
public sealed class LuaAnchorPoint
|
||||
{
|
||||
public string Group { get; set; } = string.Empty;
|
||||
public int Index { get; set; }
|
||||
public double X { get; set; }
|
||||
public double Y { get; set; }
|
||||
public double Z { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
internal static class LuaApiCatalog
|
||||
{
|
||||
private static readonly object s_gate = new();
|
||||
private static readonly List<LuaApiMember> s_members = [];
|
||||
private static LuaApiMember[]? s_snapshot;
|
||||
private static int s_version;
|
||||
|
||||
internal static int Version
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (s_gate)
|
||||
return s_version;
|
||||
}
|
||||
}
|
||||
|
||||
internal static void Register(IReadOnlyList<LuaApiMember> members)
|
||||
{
|
||||
lock (s_gate)
|
||||
{
|
||||
s_members.AddRange(members);
|
||||
s_snapshot = null;
|
||||
s_version++;
|
||||
}
|
||||
}
|
||||
|
||||
internal static IReadOnlyList<LuaApiMember> Members
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (s_gate)
|
||||
return s_snapshot ??= [.. s_members];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
internal sealed record LuaApiMember(
|
||||
string Table,
|
||||
string Name,
|
||||
LuaApiMemberKind Kind,
|
||||
IReadOnlyList<string> Parameters)
|
||||
{
|
||||
public string QualifiedName => Table.Length == 0 ? Name : $"{Table}.{Name}";
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
internal enum LuaApiMemberKind
|
||||
{
|
||||
Function,
|
||||
Variable,
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[LuaTable("")]
|
||||
[LuaBuiltin("type", "v")]
|
||||
[LuaBuiltin("tostring", "v")]
|
||||
[LuaBuiltin("tonumber", "e", "base")]
|
||||
[LuaBuiltin("select", "n", "...")]
|
||||
[LuaBuiltin("error", "message", "level")]
|
||||
[LuaBuiltin("assert", "v", "message")]
|
||||
[LuaBuiltin("print", "...")]
|
||||
[LuaBuiltin("ipairs", "t")]
|
||||
[LuaBuiltin("pairs", "t")]
|
||||
[LuaBuiltin("next", "table", "index")]
|
||||
[LuaBuiltin("unpack", "list", "i", "j")]
|
||||
[LuaBuiltin("setmetatable", "table", "metatable")]
|
||||
[LuaBuiltin("getmetatable", "object")]
|
||||
[LuaBuiltin("rawget", "table", "index")]
|
||||
[LuaBuiltin("rawset", "table", "index", "value")]
|
||||
[LuaBuiltin("rawequal", "v1", "v2")]
|
||||
[LuaBuiltin("rawlen", "v")]
|
||||
[LuaBuiltin("pcall", "f", "...")]
|
||||
[LuaBuiltin("xpcall", "f", "msgh", "...")]
|
||||
internal static class LuaBasicLibrary;
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[LuaTable("bit32")]
|
||||
[LuaBuiltin("band", "...")]
|
||||
[LuaBuiltin("bor", "...")]
|
||||
[LuaBuiltin("bxor", "...")]
|
||||
[LuaBuiltin("bnot", "x")]
|
||||
[LuaBuiltin("lshift", "x", "disp")]
|
||||
[LuaBuiltin("rshift", "x", "disp")]
|
||||
[LuaBuiltin("arshift", "x", "disp")]
|
||||
[LuaBuiltin("extract", "n", "field", "width")]
|
||||
[LuaBuiltin("replace", "n", "v", "field", "width")]
|
||||
[LuaBuiltin("btest", "...")]
|
||||
[LuaBuiltin("countlz", "x")]
|
||||
[LuaBuiltin("countrz", "x")]
|
||||
internal static class LuaBit32Library;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
|
||||
internal sealed class LuaBuiltinAttribute(string name, params string[] parameters) : Attribute
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
public string[] Parameters { get; } = parameters;
|
||||
public string Table { get; init; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
internal static class LuaCompletionSource
|
||||
{
|
||||
internal static readonly string[] Keywords =
|
||||
[
|
||||
"and", "break", "do", "else", "elseif", "end", "false", "for",
|
||||
"function", "goto", "if", "in", "local", "nil", "not", "or",
|
||||
"repeat", "return", "then", "true", "until", "while"
|
||||
];
|
||||
|
||||
private sealed record Snapshot(
|
||||
int Version,
|
||||
string[] StaticCandidates,
|
||||
IReadOnlyDictionary<string, string[]> TableMembers);
|
||||
|
||||
private static Snapshot? s_snapshot;
|
||||
|
||||
internal static string[] StaticCandidates => Current().StaticCandidates;
|
||||
|
||||
internal static bool TryGetTableMembers(string table, out string[] members)
|
||||
{
|
||||
if (Current().TableMembers.TryGetValue(table, out var found))
|
||||
{
|
||||
members = found;
|
||||
return true;
|
||||
}
|
||||
members = [];
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Snapshot Current()
|
||||
{
|
||||
var snapshot = s_snapshot;
|
||||
int version = LuaApiCatalog.Version;
|
||||
if (snapshot is null || snapshot.Version != version)
|
||||
s_snapshot = snapshot = Build(version);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
private static Snapshot Build(int version)
|
||||
{
|
||||
var members = LuaApiCatalog.Members;
|
||||
|
||||
var tableMembers = new Dictionary<string, List<string>>(StringComparer.Ordinal);
|
||||
var globals = new List<string>();
|
||||
foreach (var member in members)
|
||||
{
|
||||
if (member.Table.Length == 0)
|
||||
{
|
||||
globals.Add(member.Name);
|
||||
continue;
|
||||
}
|
||||
if (!tableMembers.TryGetValue(member.Table, out var list))
|
||||
{
|
||||
list = [];
|
||||
tableMembers[member.Table] = list;
|
||||
}
|
||||
list.Add(member.QualifiedName);
|
||||
}
|
||||
|
||||
var candidates = Keywords
|
||||
.Concat(globals)
|
||||
.Concat(tableMembers.Keys)
|
||||
.Concat(tableMembers.Values.SelectMany(x => x))
|
||||
.Distinct()
|
||||
.OrderBy(x => x.Length)
|
||||
.ThenBy(x => x, StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
|
||||
var frozen = new Dictionary<string, string[]>(StringComparer.Ordinal);
|
||||
foreach (var (table, list) in tableMembers)
|
||||
frozen[table] = [.. list.Distinct()];
|
||||
|
||||
return new Snapshot(version, candidates, frozen);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)]
|
||||
internal sealed class LuaConstantAttribute(string name) : Attribute
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
|
||||
internal sealed class LuaFunctionAttribute(string name, params string[] parameters) : Attribute
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
public string[] Parameters { get; } = parameters;
|
||||
public string Table { get; init; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[LuaTable("math")]
|
||||
[LuaBuiltin("abs", "x")]
|
||||
[LuaBuiltin("ceil", "x")]
|
||||
[LuaBuiltin("cos", "x")]
|
||||
[LuaBuiltin("exp", "x")]
|
||||
[LuaBuiltin("floor", "x")]
|
||||
[LuaBuiltin("fmod", "x", "y")]
|
||||
[LuaVariable("huge")]
|
||||
[LuaBuiltin("log", "x", "base")]
|
||||
[LuaBuiltin("max", "x", "...")]
|
||||
[LuaBuiltin("min", "x", "...")]
|
||||
[LuaBuiltin("modf", "x")]
|
||||
[LuaVariable("pi")]
|
||||
[LuaBuiltin("random", "m", "n")]
|
||||
[LuaBuiltin("randomseed", "x")]
|
||||
[LuaBuiltin("sin", "x")]
|
||||
[LuaBuiltin("sqrt", "x")]
|
||||
[LuaBuiltin("tan", "x")]
|
||||
[LuaBuiltin("atan", "y", "x")]
|
||||
[LuaBuiltin("atan2", "y", "x")]
|
||||
[LuaBuiltin("deg", "x")]
|
||||
[LuaBuiltin("rad", "x")]
|
||||
[LuaBuiltin("ldexp", "m", "e")]
|
||||
[LuaBuiltin("frexp", "x")]
|
||||
[LuaBuiltin("sinh", "x")]
|
||||
[LuaBuiltin("cosh", "x")]
|
||||
[LuaBuiltin("tanh", "x")]
|
||||
[LuaBuiltin("type", "x")]
|
||||
[LuaBuiltin("tointeger", "x")]
|
||||
[LuaVariable("maxinteger")]
|
||||
[LuaVariable("mininteger")]
|
||||
internal static class LuaMathLibrary;
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[LuaTable("string")]
|
||||
[LuaBuiltin("format", "formatstring", "...")]
|
||||
[LuaBuiltin("len", "s")]
|
||||
[LuaBuiltin("sub", "s", "i", "j")]
|
||||
[LuaBuiltin("upper", "s")]
|
||||
[LuaBuiltin("lower", "s")]
|
||||
[LuaBuiltin("rep", "s", "n", "sep")]
|
||||
[LuaBuiltin("reverse", "s")]
|
||||
[LuaBuiltin("find", "s", "pattern", "init", "plain")]
|
||||
[LuaBuiltin("match", "s", "pattern", "init")]
|
||||
[LuaBuiltin("gmatch", "s", "pattern")]
|
||||
[LuaBuiltin("gsub", "s", "pattern", "repl", "n")]
|
||||
[LuaBuiltin("byte", "s", "i", "j")]
|
||||
[LuaBuiltin("char", "...")]
|
||||
[LuaBuiltin("dump", "function")]
|
||||
[LuaBuiltin("pack", "fmt", "...")]
|
||||
[LuaBuiltin("unpack", "fmt", "s", "pos")]
|
||||
[LuaBuiltin("packsize", "fmt")]
|
||||
internal static class LuaStringLibrary;
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
|
||||
internal sealed class LuaTableAttribute(string name) : Attribute
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[LuaTable("table")]
|
||||
[LuaBuiltin("insert", "list", "pos", "value")]
|
||||
[LuaBuiltin("remove", "list", "pos")]
|
||||
[LuaBuiltin("sort", "list", "comp")]
|
||||
[LuaBuiltin("concat", "list", "sep", "i", "j")]
|
||||
[LuaBuiltin("unpack", "list", "i", "j")]
|
||||
[LuaBuiltin("move", "a1", "f", "e", "t", "a2")]
|
||||
internal static class LuaTableLibrary;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly | AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
|
||||
internal sealed class LuaVariableAttribute(string name) : Attribute
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
public string Table { get; init; } = string.Empty;
|
||||
public bool InCatalog { get; init; } = true;
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
using MoonSharp.Interpreter;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class AviUtlFontState
|
||||
{
|
||||
public string Family { get; private set; } = string.Empty;
|
||||
public double Size { get; private set; } = 34d;
|
||||
public bool Bold { get; private set; }
|
||||
public bool Italic { get; private set; }
|
||||
public int Color { get; private set; } = 0xFFFFFF;
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
Family = string.Empty;
|
||||
Size = 34d;
|
||||
Bold = false;
|
||||
Italic = false;
|
||||
Color = 0xFFFFFF;
|
||||
}
|
||||
|
||||
public void Apply(DynValue name, DynValue size, DynValue style, DynValue color)
|
||||
{
|
||||
if (name.Type == DataType.String)
|
||||
Family = name.String;
|
||||
else if (name.Type == DataType.Number)
|
||||
Family = name.CastToString();
|
||||
|
||||
Size = size.CastToNumber() ?? Size;
|
||||
|
||||
if (style.CastToNumber() is double styleNumber)
|
||||
{
|
||||
double flags = Math.Floor(styleNumber);
|
||||
Bold = FloorMod(flags, 2d) == 1d;
|
||||
Italic = FloorMod(Math.Floor(flags / 2d), 2d) == 1d;
|
||||
}
|
||||
|
||||
Color = (int)(color.CastToNumber() ?? Color);
|
||||
}
|
||||
|
||||
private static double FloorMod(double value, double divisor) =>
|
||||
value - Math.Floor(value / divisor) * divisor;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace LuaScript.Diagnostics
|
||||
{
|
||||
internal static partial class DebugOutput
|
||||
{
|
||||
[LibraryImport("kernel32.dll", EntryPoint = "OutputDebugStringW", StringMarshalling = StringMarshalling.Utf16)]
|
||||
private static partial void OutputDebugStringW(string message);
|
||||
|
||||
internal static void Write(string message) => OutputDebugStringW(message);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace LuaScript.Diagnostics
|
||||
{
|
||||
internal interface ILuaScriptDiagnosticsListener
|
||||
{
|
||||
void OnDiagnosticsChanged();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
namespace LuaScript.Diagnostics
|
||||
{
|
||||
internal readonly record struct LuaScriptDiagnostic(
|
||||
LuaScriptDiagnosticKind Kind,
|
||||
int Line,
|
||||
int Column,
|
||||
int Length,
|
||||
string Message);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
namespace LuaScript.Diagnostics
|
||||
{
|
||||
internal enum LuaScriptDiagnosticKind
|
||||
{
|
||||
Compile,
|
||||
Runtime,
|
||||
Timeout,
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal static class DrawTransform
|
||||
{
|
||||
public static bool TryResolve(in DrawCommand command, int srcW, int srcH, out Matrix3x2 matrix)
|
||||
{
|
||||
if (command.Poly is { } poly)
|
||||
return DrawPolyMath.TrySolveAffine(poly, out matrix);
|
||||
|
||||
double aspect = Math.Clamp(command.Aspect, -1d, 1d);
|
||||
double zx = command.Zoom * (1d + aspect);
|
||||
double zy = command.Zoom * (1d - aspect);
|
||||
if (zx == 0d || zy == 0d)
|
||||
{
|
||||
matrix = Matrix3x2.Identity;
|
||||
return false;
|
||||
}
|
||||
|
||||
matrix =
|
||||
Matrix3x2.CreateTranslation(-srcW * 0.5f, -srcH * 0.5f) *
|
||||
Matrix3x2.CreateScale((float)zx, (float)zy) *
|
||||
Matrix3x2.CreateTranslation((float)command.Ox, (float)command.Oy);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class FallbackCompositor(
|
||||
IBufferCompositor primary,
|
||||
IBufferCompositor fallback,
|
||||
Action<Exception>? onDegraded = null) : IBufferCompositor, IDisposable
|
||||
{
|
||||
private bool _degraded;
|
||||
|
||||
public bool IsDegraded => _degraded;
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
if (!_degraded)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (primary.TryCompose(dst, dstW, dstH, src, srcW, srcH, command))
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_degraded = true;
|
||||
onDegraded?.Invoke(ex);
|
||||
}
|
||||
}
|
||||
return fallback.TryCompose(dst, dstW, dstH, src, srcW, srcH, command);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
(primary as IDisposable)?.Dispose();
|
||||
(fallback as IDisposable)?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal interface IBufferCompositor
|
||||
{
|
||||
bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command);
|
||||
}
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class SoftwareCompositor : IBufferCompositor
|
||||
{
|
||||
public static readonly SoftwareCompositor Instance = new();
|
||||
|
||||
private SoftwareCompositor()
|
||||
{
|
||||
}
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
bool linear = command.Antialias != 0d;
|
||||
if (command.Poly is { } poly)
|
||||
DrawPolyInto(dst, dstW, dstH, src, srcW, srcH, poly, command.Alpha, linear);
|
||||
else
|
||||
DrawInto(dst, dstW, dstH, src, srcW, srcH, command.Ox, command.Oy, command.Zoom, command.Aspect, command.Alpha, linear);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void DrawInto(
|
||||
byte[] dst, int dstW, int dstH,
|
||||
byte[] src, int srcW, int srcH,
|
||||
double ox, double oy, double zoom, double aspect, double alpha, bool linear)
|
||||
{
|
||||
if (srcW <= 0 || srcH <= 0 || dstW <= 0 || dstH <= 0)
|
||||
return;
|
||||
|
||||
double clampedAspect = Math.Clamp(aspect, -1d, 1d);
|
||||
double zx = zoom * (1d + clampedAspect);
|
||||
double zy = zoom * (1d - clampedAspect);
|
||||
if (zx == 0d || zy == 0d)
|
||||
return;
|
||||
|
||||
double ka = Math.Clamp(alpha, 0d, 1d);
|
||||
if (ka <= 0d)
|
||||
return;
|
||||
|
||||
double halfW = srcW * 0.5;
|
||||
double halfH = srcH * 0.5;
|
||||
double spanX = Math.Abs(halfW * zx);
|
||||
double spanY = Math.Abs(halfH * zy);
|
||||
|
||||
int x0 = Math.Max(0, (int)Math.Floor(ox - spanX));
|
||||
int x1 = Math.Min(dstW - 1, (int)Math.Ceiling(ox + spanX));
|
||||
int y0 = Math.Max(0, (int)Math.Floor(oy - spanY));
|
||||
int y1 = Math.Min(dstH - 1, (int)Math.Ceiling(oy + spanY));
|
||||
|
||||
for (int py = y0; py <= y1; py++)
|
||||
{
|
||||
for (int px = x0; px <= x1; px++)
|
||||
{
|
||||
double u = (px + 0.5 - ox) / zx + halfW;
|
||||
double v = (py + 0.5 - oy) / zy + halfH;
|
||||
if (u < 0d || u >= srcW || v < 0d || v >= srcH)
|
||||
continue;
|
||||
|
||||
Sample(src, srcW, srcH, u, v, linear, out double sb, out double sg, out double sr, out double sa);
|
||||
CompositeOver(dst, (py * dstW + px) * 4, sb * ka, sg * ka, sr * ka, sa * ka);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void DrawPolyInto(
|
||||
byte[] dst, int dstW, int dstH,
|
||||
byte[] src, int srcW, int srcH,
|
||||
double[] poly, double alpha, bool linear)
|
||||
{
|
||||
if (srcW <= 0 || srcH <= 0 || dstW <= 0 || dstH <= 0)
|
||||
return;
|
||||
if (!DrawPolyMath.TrySolveAffine(poly, out var forward))
|
||||
return;
|
||||
if (!Matrix3x2.Invert(forward, out var inverse))
|
||||
return;
|
||||
|
||||
double ka = Math.Clamp(alpha, 0d, 1d);
|
||||
if (ka <= 0d)
|
||||
return;
|
||||
|
||||
DrawPolyMath.Bounds(poly, out double minX, out double minY, out double maxX, out double maxY);
|
||||
int x0 = Math.Max(0, (int)Math.Floor(minX));
|
||||
int x1 = Math.Min(dstW - 1, (int)Math.Ceiling(maxX));
|
||||
int y0 = Math.Max(0, (int)Math.Floor(minY));
|
||||
int y1 = Math.Min(dstH - 1, (int)Math.Ceiling(maxY));
|
||||
|
||||
for (int py = y0; py <= y1; py++)
|
||||
{
|
||||
for (int px = x0; px <= x1; px++)
|
||||
{
|
||||
var uv = Vector2.Transform(new Vector2(px + 0.5f, py + 0.5f), inverse);
|
||||
double u = uv.X;
|
||||
double v = uv.Y;
|
||||
if (u < 0d || u >= srcW || v < 0d || v >= srcH)
|
||||
continue;
|
||||
|
||||
Sample(src, srcW, srcH, u, v, linear, out double sb, out double sg, out double sr, out double sa);
|
||||
CompositeOver(dst, (py * dstW + px) * 4, sb * ka, sg * ka, sr * ka, sa * ka);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void Sample(byte[] src, int srcW, int srcH, double u, double v, bool linear,
|
||||
out double b, out double g, out double r, out double a)
|
||||
{
|
||||
if (!linear)
|
||||
{
|
||||
int su = Math.Clamp((int)Math.Floor(u), 0, srcW - 1);
|
||||
int sv = Math.Clamp((int)Math.Floor(v), 0, srcH - 1);
|
||||
int si = (sv * srcW + su) * 4;
|
||||
b = src[si];
|
||||
g = src[si + 1];
|
||||
r = src[si + 2];
|
||||
a = src[si + 3];
|
||||
return;
|
||||
}
|
||||
|
||||
double fx = u - 0.5;
|
||||
double fy = v - 0.5;
|
||||
int x0 = (int)Math.Floor(fx);
|
||||
int y0 = (int)Math.Floor(fy);
|
||||
double tx = fx - x0;
|
||||
double ty = fy - y0;
|
||||
|
||||
b = g = r = a = 0d;
|
||||
for (int j = 0; j < 2; j++)
|
||||
{
|
||||
int sy = Math.Clamp(y0 + j, 0, srcH - 1);
|
||||
double wy = j == 0 ? 1d - ty : ty;
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
int sx = Math.Clamp(x0 + i, 0, srcW - 1);
|
||||
double w = wy * (i == 0 ? 1d - tx : tx);
|
||||
int si = (sy * srcW + sx) * 4;
|
||||
b += src[si] * w;
|
||||
g += src[si + 1] * w;
|
||||
r += src[si + 2] * w;
|
||||
a += src[si + 3] * w;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void CompositeOver(byte[] dst, int di, double sb, double sg, double sr, double sa)
|
||||
{
|
||||
double inv = 1d - sa / 255d;
|
||||
dst[di] = (byte)Math.Clamp(sb + dst[di] * inv, 0d, 255d);
|
||||
dst[di + 1] = (byte)Math.Clamp(sg + dst[di + 1] * inv, 0d, 255d);
|
||||
dst[di + 2] = (byte)Math.Clamp(sr + dst[di + 2] * inv, 0d, 255d);
|
||||
dst[di + 3] = (byte)Math.Clamp(sa + dst[di + 3] * inv, 0d, 255d);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class SynchronizedCompositor(IBufferCompositor inner, SemaphoreSlim gate) : IBufferCompositor, IDisposable
|
||||
{
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
gate.Wait();
|
||||
try
|
||||
{
|
||||
return inner.TryCompose(dst, dstW, dstH, src, srcW, srcH, command);
|
||||
}
|
||||
finally
|
||||
{
|
||||
gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => (inner as IDisposable)?.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal interface IMediaSourceLoader : IDisposable
|
||||
{
|
||||
byte[] RenderText(string text, string fontFamily, double fontSize, bool bold, bool italic, int colorRgb, out int width, out int height);
|
||||
byte[] DecodeImage(string path, out int width, out int height);
|
||||
byte[] DecodeMovie(string path, double time, out int width, out int height);
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
using MoonSharp.Interpreter;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class LuaScope
|
||||
{
|
||||
private readonly string? _globalName;
|
||||
private readonly Action<Table>? _register;
|
||||
private readonly Action<Table, AviUtlScriptContext>? _update;
|
||||
private readonly List<string> _removalBuffer = [];
|
||||
|
||||
private Table? _table;
|
||||
private HashSet<string>? _snapshot;
|
||||
|
||||
internal LuaScope(string? globalName, Action<Table>? register, Action<Table, AviUtlScriptContext>? update)
|
||||
{
|
||||
_globalName = globalName;
|
||||
_register = register;
|
||||
_update = update;
|
||||
}
|
||||
|
||||
internal Table Table => _table!;
|
||||
|
||||
internal void Create(Script script)
|
||||
{
|
||||
_snapshot = null;
|
||||
if (_globalName is null)
|
||||
{
|
||||
_table = script.Globals;
|
||||
return;
|
||||
}
|
||||
_table = Build(script);
|
||||
}
|
||||
|
||||
internal void Reconcile(Script script)
|
||||
{
|
||||
if (_globalName is null)
|
||||
return;
|
||||
if (ReferenceEquals(script.Globals.Get(_globalName).Table, _table))
|
||||
return;
|
||||
_table = Build(script);
|
||||
_snapshot = null;
|
||||
}
|
||||
|
||||
internal void ResetUserKeys()
|
||||
{
|
||||
if (_snapshot is null)
|
||||
return;
|
||||
var buffer = _removalBuffer;
|
||||
buffer.Clear();
|
||||
foreach (var key in _table!.Keys)
|
||||
{
|
||||
if (key.Type == DataType.String && !_snapshot.Contains(key.String))
|
||||
buffer.Add(key.String);
|
||||
}
|
||||
foreach (var key in buffer)
|
||||
_table[key] = DynValue.Nil;
|
||||
}
|
||||
|
||||
internal void Update(AviUtlScriptContext ctx) => _update?.Invoke(_table!, ctx);
|
||||
|
||||
internal void CaptureSnapshot()
|
||||
{
|
||||
var keys = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var key in _table!.Keys)
|
||||
{
|
||||
if (key.Type == DataType.String)
|
||||
keys.Add(key.String);
|
||||
}
|
||||
_snapshot = keys;
|
||||
}
|
||||
|
||||
private Table Build(Script script)
|
||||
{
|
||||
var table = new Table(script);
|
||||
_register?.Invoke(table);
|
||||
script.Globals[_globalName!] = table;
|
||||
return table;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,974 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using LuaScript.Anchor;
|
||||
using LuaScript.Api;
|
||||
using LuaScript.Compat;
|
||||
using MoonSharp.Interpreter;
|
||||
using MoonSharp.Interpreter.Debugging;
|
||||
using MoonSharp.Interpreter.Loaders;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed partial class LuaScriptEngine : IDisposable
|
||||
{
|
||||
private readonly record struct ExecutionResult(
|
||||
LuaScriptException? Exception,
|
||||
bool TimedOut);
|
||||
|
||||
[LuaTable("obj")]
|
||||
private sealed partial class ExecutionThread : IDisposable
|
||||
{
|
||||
private sealed class CancellationDebugger : IDebugger
|
||||
{
|
||||
private static readonly DebuggerAction s_runAction = new() { Action = DebuggerAction.ActionType.Run };
|
||||
|
||||
private CancellationToken _token;
|
||||
|
||||
internal void UpdateToken(CancellationToken token) => _token = token;
|
||||
|
||||
public DebuggerCaps GetDebuggerCaps() => 0;
|
||||
public void SetDebugService(DebugService debugService) { }
|
||||
public void SetSourceCode(SourceCode sourceCode) { }
|
||||
public void SetByteCode(string[] byteCode) { }
|
||||
public bool SignalRuntimeException(ScriptRuntimeException ex) => false;
|
||||
public void SignalExecutionEnded() { }
|
||||
public void Update(WatchType watchType, IEnumerable<WatchItem> items) { }
|
||||
public List<DynamicExpression> GetWatchItems() => [];
|
||||
public void RefreshBreakpoints(IEnumerable<SourceRef> refs) { }
|
||||
|
||||
public bool IsPauseRequested() => _token.IsCancellationRequested;
|
||||
|
||||
public DebuggerAction GetAction(int ip, SourceRef sourceref)
|
||||
{
|
||||
_token.ThrowIfCancellationRequested();
|
||||
return s_runAction;
|
||||
}
|
||||
}
|
||||
|
||||
private readonly SemaphoreSlim _workSignal = new(0);
|
||||
private readonly ManualResetEventSlim _doneSignal = new(false);
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private readonly Thread _thread;
|
||||
private readonly CancellationDebugger _debugger = new();
|
||||
|
||||
private string _jobCode = string.Empty;
|
||||
private AviUtlScriptContext? _jobContext;
|
||||
private LuaScriptException? _jobException;
|
||||
private volatile bool _disposeRequested;
|
||||
|
||||
private readonly Dictionary<string, DynValue> _options = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, DynValue> _pixelOptions = new(StringComparer.Ordinal);
|
||||
|
||||
private readonly Func<IMediaSourceLoader> _mediaLoaderFactory;
|
||||
private IMediaSourceLoader? _mediaLoader;
|
||||
private readonly AviUtlFontState _fontState = new();
|
||||
|
||||
private static readonly Stopwatch s_clock = Stopwatch.StartNew();
|
||||
|
||||
private Script? _script;
|
||||
private DynValue? _compiledChunk;
|
||||
private string _lastCompiledCode = string.Empty;
|
||||
private long _scriptStartTimestamp;
|
||||
private CancellationToken _activeCancellation;
|
||||
private AviUtlScriptContext? _activeContext;
|
||||
|
||||
private AviUtlGlobalRegistrar? _globalRegistrar;
|
||||
private SceneTableRegistrar? _sceneRegistrar;
|
||||
|
||||
private readonly LuaScope _objScope;
|
||||
private readonly LuaScope[] _scopes;
|
||||
private bool _scopesInitialized;
|
||||
|
||||
internal ExecutionThread(Func<IMediaSourceLoader> mediaLoaderFactory)
|
||||
{
|
||||
_mediaLoaderFactory = mediaLoaderFactory;
|
||||
_activeCancellation = _cts.Token;
|
||||
_debugger.UpdateToken(_cts.Token);
|
||||
_objScope = new LuaScope("obj", RegisterLuaMembers, UpdateLuaMembers);
|
||||
_scopes =
|
||||
[
|
||||
new LuaScope(null, null, (table, ctx) => _globalRegistrar!.UpdateLuaMembers(table, ctx)),
|
||||
new LuaScope("scene", RegisterSceneCallbacks, (table, ctx) => _sceneRegistrar!.UpdateLuaMembers(table, ctx)),
|
||||
_objScope,
|
||||
new LuaScope("anim", AnimTableRegistrar.RegisterFunctions, null),
|
||||
new LuaScope("ymm4", null, Ymm4TableRegistrar.UpdateLuaMembers),
|
||||
];
|
||||
_thread = new Thread(WorkerLoop)
|
||||
{
|
||||
IsBackground = true,
|
||||
Name = "LuaScriptWorker"
|
||||
};
|
||||
_thread.Start();
|
||||
}
|
||||
|
||||
internal ExecutionResult TryExecute(string code, AviUtlScriptContext ctx, int timeoutMs)
|
||||
{
|
||||
_jobCode = code;
|
||||
_jobContext = ctx;
|
||||
_jobException = null;
|
||||
_doneSignal.Reset();
|
||||
_workSignal.Release();
|
||||
|
||||
if (_doneSignal.Wait(timeoutMs))
|
||||
return new ExecutionResult(_jobException, false);
|
||||
|
||||
_cts.Cancel();
|
||||
return new ExecutionResult(null, TimedOut: true);
|
||||
}
|
||||
|
||||
private void WorkerLoop()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
_workSignal.Wait();
|
||||
if (_disposeRequested)
|
||||
return;
|
||||
ProcessJob();
|
||||
_doneSignal.Set();
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessJob()
|
||||
{
|
||||
var context = _jobContext!;
|
||||
_activeContext = context;
|
||||
|
||||
try
|
||||
{
|
||||
EnsureScript();
|
||||
EnsureScriptIntegrity();
|
||||
EnsureCompiled(_jobCode);
|
||||
SetupGlobals(context);
|
||||
_scriptStartTimestamp = Stopwatch.GetTimestamp();
|
||||
_script!.Call(_compiledChunk!);
|
||||
ReadBackGlobals(context);
|
||||
_jobException = null;
|
||||
}
|
||||
catch (OperationCanceledException) when (_cts.IsCancellationRequested)
|
||||
{
|
||||
_jobException = null;
|
||||
}
|
||||
catch (LuaScriptException ex)
|
||||
{
|
||||
_jobException = ex;
|
||||
}
|
||||
catch (ScriptRuntimeException ex)
|
||||
{
|
||||
_jobException = new LuaScriptRuntimeException(ex.DecoratedMessage ?? ex.Message, ex);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_jobException = new LuaScriptRuntimeException(ex.Message, ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_activeContext = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureScript()
|
||||
{
|
||||
if (_script is not null) return;
|
||||
var script = new Script(
|
||||
CoreModules.Basic |
|
||||
CoreModules.Math |
|
||||
CoreModules.String |
|
||||
CoreModules.Table |
|
||||
CoreModules.Bit32 |
|
||||
CoreModules.TableIterators |
|
||||
CoreModules.Metatables |
|
||||
CoreModules.ErrorHandling);
|
||||
script.Options.ScriptLoader = new DisabledFileScriptLoader();
|
||||
script.AttachDebugger(_debugger);
|
||||
_globalRegistrar = new AviUtlGlobalRegistrar(CurrentTimeRatio);
|
||||
_globalRegistrar.RegisterLuaMembers(script.Globals);
|
||||
_script = script;
|
||||
}
|
||||
|
||||
private void EnsureScriptIntegrity()
|
||||
{
|
||||
if (_script is null) return;
|
||||
if (_script.Globals.Get("math").Type == DataType.Table) return;
|
||||
_script = null;
|
||||
_compiledChunk = null;
|
||||
_lastCompiledCode = string.Empty;
|
||||
_scopesInitialized = false;
|
||||
EnsureScript();
|
||||
}
|
||||
|
||||
private void EnsureCompiled(string code)
|
||||
{
|
||||
if (_compiledChunk is not null && code == _lastCompiledCode) return;
|
||||
|
||||
DynValue chunk;
|
||||
try
|
||||
{
|
||||
chunk = _script!.LoadString(code, null, "LuaScript");
|
||||
}
|
||||
catch (SyntaxErrorException ex)
|
||||
{
|
||||
throw new LuaScriptCompilationException(ex.DecoratedMessage ?? ex.Message, ex);
|
||||
}
|
||||
|
||||
_compiledChunk = chunk;
|
||||
_lastCompiledCode = code;
|
||||
}
|
||||
|
||||
private void SetupGlobals(AviUtlScriptContext ctx)
|
||||
{
|
||||
var script = _script!;
|
||||
bool isFirstSetup = !_scopesInitialized;
|
||||
|
||||
_options.Clear();
|
||||
_pixelOptions.Clear();
|
||||
_fontState.Reset();
|
||||
|
||||
if (isFirstSetup)
|
||||
{
|
||||
foreach (var scope in _scopes)
|
||||
scope.Create(script);
|
||||
_scopesInitialized = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var scope in _scopes)
|
||||
scope.Reconcile(script);
|
||||
foreach (var scope in _scopes)
|
||||
scope.ResetUserKeys();
|
||||
}
|
||||
|
||||
foreach (var scope in _scopes)
|
||||
scope.Update(ctx);
|
||||
|
||||
if (isFirstSetup)
|
||||
{
|
||||
foreach (var scope in _scopes)
|
||||
scope.CaptureSnapshot();
|
||||
}
|
||||
|
||||
script.Call(
|
||||
script.Globals.Get("math").Table.Get("randomseed"),
|
||||
DynValue.NewNumber(ctx.Frame));
|
||||
}
|
||||
|
||||
private double CurrentTimeRatio() =>
|
||||
_activeContext is { TotalTime: > 0d } context ? context.Time / context.TotalTime : 0d;
|
||||
|
||||
private void RegisterSceneCallbacks(Table scene)
|
||||
{
|
||||
_sceneRegistrar = new SceneTableRegistrar(GetSceneValue, SetSceneValue);
|
||||
_sceneRegistrar.RegisterLuaMembers(scene);
|
||||
}
|
||||
|
||||
private SceneValue GetSceneValue(string name)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
return _activeContext?.GetSceneValue(name) ?? SceneValue.Nil;
|
||||
}
|
||||
|
||||
private void SetSceneValue(string name, SceneValue value)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
_activeContext?.SetSceneValue(name, value);
|
||||
}
|
||||
|
||||
[LuaVariable("w")]
|
||||
private int W(AviUtlScriptContext ctx) => ctx.ImageWidth;
|
||||
|
||||
[LuaVariable("h")]
|
||||
private int H(AviUtlScriptContext ctx) => ctx.ImageHeight;
|
||||
|
||||
[LuaVariable("hw")]
|
||||
private double Hw(AviUtlScriptContext ctx) => ctx.ImageWidth / 2d;
|
||||
|
||||
[LuaVariable("hh")]
|
||||
private double Hh(AviUtlScriptContext ctx) => ctx.ImageHeight / 2d;
|
||||
|
||||
[LuaVariable("diagonal")]
|
||||
private double Diagonal(AviUtlScriptContext ctx) => Math.Sqrt((double)ctx.ImageWidth * ctx.ImageWidth + (double)ctx.ImageHeight * ctx.ImageHeight);
|
||||
|
||||
[LuaVariable("cx")]
|
||||
private double Cx(AviUtlScriptContext ctx) => ctx.ImageWidth / 2d;
|
||||
|
||||
[LuaVariable("cy")]
|
||||
private double Cy(AviUtlScriptContext ctx) => ctx.ImageHeight / 2d;
|
||||
|
||||
[LuaVariable("cz")]
|
||||
private double Cz(AviUtlScriptContext ctx) => 0d;
|
||||
|
||||
[LuaVariable("x")]
|
||||
private double X(AviUtlScriptContext ctx) => ctx.X;
|
||||
|
||||
[LuaVariable("y")]
|
||||
private double Y(AviUtlScriptContext ctx) => ctx.Y;
|
||||
|
||||
[LuaVariable("z")]
|
||||
private double Z(AviUtlScriptContext ctx) => ctx.Z;
|
||||
|
||||
[LuaVariable("ox")]
|
||||
private double Ox(AviUtlScriptContext ctx) => ctx.Ox;
|
||||
|
||||
[LuaVariable("oy")]
|
||||
private double Oy(AviUtlScriptContext ctx) => ctx.Oy;
|
||||
|
||||
[LuaVariable("oz")]
|
||||
private double Oz(AviUtlScriptContext ctx) => ctx.Oz;
|
||||
|
||||
[LuaVariable("sx")]
|
||||
private double Sx(AviUtlScriptContext ctx) => ctx.Sx;
|
||||
|
||||
[LuaVariable("sy")]
|
||||
private double Sy(AviUtlScriptContext ctx) => ctx.Sy;
|
||||
|
||||
[LuaVariable("sz", InCatalog = false)]
|
||||
private double Sz(AviUtlScriptContext ctx) => 1d;
|
||||
|
||||
[LuaVariable("zoom")]
|
||||
private double Zoom(AviUtlScriptContext ctx) => ctx.Zoom;
|
||||
|
||||
[LuaVariable("alpha")]
|
||||
private double Alpha(AviUtlScriptContext ctx) => ctx.Alpha;
|
||||
|
||||
[LuaVariable("aspect")]
|
||||
private double Aspect(AviUtlScriptContext ctx) => ctx.Aspect;
|
||||
|
||||
[LuaVariable("rx")]
|
||||
private double Rx(AviUtlScriptContext ctx) => ctx.Rx;
|
||||
|
||||
[LuaVariable("ry")]
|
||||
private double Ry(AviUtlScriptContext ctx) => ctx.Ry;
|
||||
|
||||
[LuaVariable("rz")]
|
||||
private double Rz(AviUtlScriptContext ctx) => ctx.Rz;
|
||||
|
||||
[LuaVariable("rxr")]
|
||||
private double Rxr(AviUtlScriptContext ctx) => ctx.RxRad;
|
||||
|
||||
[LuaVariable("ryr")]
|
||||
private double Ryr(AviUtlScriptContext ctx) => ctx.RyRad;
|
||||
|
||||
[LuaVariable("rzr")]
|
||||
private double Rzr(AviUtlScriptContext ctx) => ctx.RzRad;
|
||||
|
||||
[LuaVariable("track0")]
|
||||
private double Track0(AviUtlScriptContext ctx) => ctx.Track0;
|
||||
|
||||
[LuaVariable("track1")]
|
||||
private double Track1(AviUtlScriptContext ctx) => ctx.Track1;
|
||||
|
||||
[LuaVariable("track2")]
|
||||
private double Track2(AviUtlScriptContext ctx) => ctx.Track2;
|
||||
|
||||
[LuaVariable("track3")]
|
||||
private double Track3(AviUtlScriptContext ctx) => ctx.Track3;
|
||||
|
||||
[LuaVariable("slider0")]
|
||||
private double Slider0(AviUtlScriptContext ctx) => ctx.Slider0;
|
||||
|
||||
[LuaVariable("slider1")]
|
||||
private double Slider1(AviUtlScriptContext ctx) => ctx.Slider1;
|
||||
|
||||
[LuaVariable("slider2")]
|
||||
private double Slider2(AviUtlScriptContext ctx) => ctx.Slider2;
|
||||
|
||||
[LuaVariable("slider3")]
|
||||
private double Slider3(AviUtlScriptContext ctx) => ctx.Slider3;
|
||||
|
||||
[LuaVariable("check0")]
|
||||
private bool Check0(AviUtlScriptContext ctx) => ctx.Check0;
|
||||
|
||||
[LuaVariable("check1")]
|
||||
private bool Check1(AviUtlScriptContext ctx) => ctx.Check1;
|
||||
|
||||
[LuaVariable("check2")]
|
||||
private bool Check2(AviUtlScriptContext ctx) => ctx.Check2;
|
||||
|
||||
[LuaVariable("check3")]
|
||||
private bool Check3(AviUtlScriptContext ctx) => ctx.Check3;
|
||||
|
||||
[LuaVariable("text")]
|
||||
private string? Text(AviUtlScriptContext ctx) => ctx.StringParameters.TryGetValue("text", out var value) ? value : null;
|
||||
|
||||
[LuaVariable("font")]
|
||||
private string? Font(AviUtlScriptContext ctx) => ctx.StringParameters.TryGetValue("font", out var value) ? value : null;
|
||||
|
||||
[LuaVariable("dir")]
|
||||
private string? Dir(AviUtlScriptContext ctx) => ctx.StringParameters.TryGetValue("dir", out var value) ? value : null;
|
||||
|
||||
[LuaVariable("file_video")]
|
||||
private string? FileVideo(AviUtlScriptContext ctx) => ctx.StringParameters.TryGetValue("file_video", out var value) ? value : null;
|
||||
|
||||
[LuaVariable("file_audio")]
|
||||
private string? FileAudio(AviUtlScriptContext ctx) => ctx.StringParameters.TryGetValue("file_audio", out var value) ? value : null;
|
||||
|
||||
[LuaVariable("file_image")]
|
||||
private string? FileImage(AviUtlScriptContext ctx) => ctx.StringParameters.TryGetValue("file_image", out var value) ? value : null;
|
||||
|
||||
[LuaVariable("file_project")]
|
||||
private string? FileProject(AviUtlScriptContext ctx) => ctx.StringParameters.TryGetValue("file_project", out var value) ? value : null;
|
||||
|
||||
[LuaVariable("file_mp4")]
|
||||
private string? FileMp4(AviUtlScriptContext ctx) => ctx.StringParameters.TryGetValue("file_mp4", out var value) ? value : null;
|
||||
|
||||
[LuaVariable("file_exo")]
|
||||
private string? FileExo(AviUtlScriptContext ctx) => ctx.StringParameters.TryGetValue("file_exo", out var value) ? value : null;
|
||||
|
||||
[LuaVariable("file_subtitle")]
|
||||
private string? FileSubtitle(AviUtlScriptContext ctx) => ctx.StringParameters.TryGetValue("file_subtitle", out var value) ? value : null;
|
||||
|
||||
[LuaVariable("file_shader")]
|
||||
private string? FileShader(AviUtlScriptContext ctx) => ctx.StringParameters.TryGetValue("file_shader", out var value) ? value : null;
|
||||
|
||||
[LuaVariable("time")]
|
||||
private double Time(AviUtlScriptContext ctx) => ctx.Time;
|
||||
|
||||
[LuaVariable("totaltime")]
|
||||
private double Totaltime(AviUtlScriptContext ctx) => ctx.TotalTime;
|
||||
|
||||
[LuaVariable("t")]
|
||||
private double T(AviUtlScriptContext ctx) => ctx.TotalFrame > 0 ? ctx.Frame / (double)ctx.TotalFrame : 0d;
|
||||
|
||||
[LuaVariable("frame")]
|
||||
private int Frame(AviUtlScriptContext ctx) => ctx.Frame;
|
||||
|
||||
[LuaVariable("totalframe")]
|
||||
private int Totalframe(AviUtlScriptContext ctx) => ctx.TotalFrame;
|
||||
|
||||
[LuaVariable("framerate")]
|
||||
private int Framerate(AviUtlScriptContext ctx) => ctx.Framerate;
|
||||
|
||||
[LuaVariable("layer")]
|
||||
private int Layer(AviUtlScriptContext ctx) => ctx.Layer;
|
||||
|
||||
[LuaVariable("index")]
|
||||
private int Index(AviUtlScriptContext ctx) => ctx.Index;
|
||||
|
||||
[LuaVariable("num")]
|
||||
private int Num(AviUtlScriptContext ctx) => ctx.Num;
|
||||
[LuaFunction("getobject")]
|
||||
private DynValue GetObject(ScriptExecutionContext execCtx, CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count == 0)
|
||||
return DynValue.Nil;
|
||||
var tag = args[0];
|
||||
if (tag.Type != DataType.String)
|
||||
return DynValue.Nil;
|
||||
int frame = _activeContext.TimelineFrame;
|
||||
if (args.Count >= 2)
|
||||
{
|
||||
var frameArg = args[1];
|
||||
if (frameArg.Type != DataType.Number)
|
||||
return DynValue.Nil;
|
||||
frame = (int)frameArg.Number;
|
||||
}
|
||||
if (!_activeContext.ResolveObject(tag.String, frame, out var info))
|
||||
return DynValue.Nil;
|
||||
return BuildObjectTable(execCtx.GetScript(), info);
|
||||
}
|
||||
|
||||
[LuaFunction("getpixel")]
|
||||
private DynValue GetPixel(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null) return DynValue.Nil;
|
||||
int x = (int)(args[0].CastToNumber() ?? 0d);
|
||||
int y = (int)(args[1].CastToNumber() ?? 0d);
|
||||
var (r, g, b, a) = _activeContext.GetPixel(x, y);
|
||||
return DynValue.NewTuple(
|
||||
DynValue.NewNumber(r),
|
||||
DynValue.NewNumber(g),
|
||||
DynValue.NewNumber(b),
|
||||
DynValue.NewNumber(a));
|
||||
}
|
||||
|
||||
[LuaFunction("setpixel")]
|
||||
private DynValue SetPixel(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null) return DynValue.Void;
|
||||
int x = (int)(args[0].CastToNumber() ?? 0d);
|
||||
int y = (int)(args[1].CastToNumber() ?? 0d);
|
||||
double r = args[2].CastToNumber() ?? 0d;
|
||||
double g = args[3].CastToNumber() ?? 0d;
|
||||
double b = args[4].CastToNumber() ?? 0d;
|
||||
double a = args.Count > 5 ? args[5].CastToNumber() ?? 255d : 255d;
|
||||
_activeContext.SetPixel(x, y, r, g, b, a);
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("getpixeldata")]
|
||||
private DynValue GetPixelData()
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null) return DynValue.Nil;
|
||||
_activeContext.EnsurePixelBuffer();
|
||||
return UserData.Create(new PixelDataProxy(_activeContext));
|
||||
}
|
||||
|
||||
[LuaFunction("putpixeldata")]
|
||||
private DynValue PutPixelData() => DynValue.Void;
|
||||
|
||||
[LuaFunction("rand")]
|
||||
private DynValue Rand(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
double frameDefault = _activeContext?.Frame ?? 0d;
|
||||
double a = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
|
||||
double b = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
|
||||
double seed = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
|
||||
double frame = args.Count > 3 ? args[3].CastToNumber() ?? frameDefault : frameDefault;
|
||||
return DynValue.NewNumber(AviUtlRandom.Next(a, b, seed, frame));
|
||||
}
|
||||
|
||||
[LuaFunction("load")]
|
||||
private DynValue Load(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
|
||||
switch (args[0].String)
|
||||
{
|
||||
case "figure" when args.Count >= 4:
|
||||
LoadFigure(
|
||||
args[1].Type == DataType.String ? args[1].String : string.Empty,
|
||||
(int)(args[2].CastToNumber() ?? 0d),
|
||||
args[3].CastToNumber() ?? 0d,
|
||||
args.Count > 4 ? args[4].CastToNumber() ?? 0d : 0d,
|
||||
args.Count > 5 ? Math.Clamp(args[5].CastToNumber() ?? 0d, -1d, 1d) : 0d);
|
||||
break;
|
||||
case "text":
|
||||
LoadText(args.Count > 1 && args[1].Type == DataType.String ? args[1].String : string.Empty);
|
||||
break;
|
||||
case "image" when args.Count > 1 && args[1].Type == DataType.String:
|
||||
LoadImage(args[1].String);
|
||||
break;
|
||||
case "movie" when args.Count > 1 && args[1].Type == DataType.String:
|
||||
LoadMovie(
|
||||
args[1].String,
|
||||
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
|
||||
break;
|
||||
}
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("setfont")]
|
||||
private DynValue SetFont(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
_fontState.Apply(
|
||||
args.Count > 0 ? args[0] : DynValue.Nil,
|
||||
args.Count > 1 ? args[1] : DynValue.Nil,
|
||||
args.Count > 2 ? args[2] : DynValue.Nil,
|
||||
args.Count > 3 ? args[3] : DynValue.Nil);
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("draw")]
|
||||
private DynValue Draw(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null)
|
||||
return DynValue.Void;
|
||||
|
||||
double ox = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
|
||||
double oy = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
|
||||
double oz = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
|
||||
double zoom = args.Count > 3 ? args[3].CastToNumber() ?? 1d : 1d;
|
||||
double alpha = args.Count > 4 ? args[4].CastToNumber() ?? 1d : 1d;
|
||||
double aspect = args.Count > 5 ? args[5].CastToNumber() ?? 0d : 0d;
|
||||
|
||||
_activeContext.SubmitDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, CurrentAntialias(), CurrentBlend()));
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("drawpoly")]
|
||||
private DynValue DrawPoly(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count < 12)
|
||||
return DynValue.Void;
|
||||
|
||||
var poly = new double[DrawPolyMath.Length];
|
||||
for (int i = 0; i < 12; i++)
|
||||
poly[i] = args[i].CastToNumber() ?? 0d;
|
||||
|
||||
if (args.Count >= 20)
|
||||
{
|
||||
for (int i = 0; i < 8; i++)
|
||||
poly[12 + i] = args[12 + i].CastToNumber() ?? 0d;
|
||||
}
|
||||
else
|
||||
{
|
||||
double w = _activeContext.ImageWidth;
|
||||
double h = _activeContext.ImageHeight;
|
||||
poly[12] = 0d; poly[13] = 0d;
|
||||
poly[14] = w; poly[15] = 0d;
|
||||
poly[16] = w; poly[17] = h;
|
||||
poly[18] = 0d; poly[19] = h;
|
||||
}
|
||||
|
||||
poly[20] = args.Count switch
|
||||
{
|
||||
13 => args[12].CastToNumber() ?? 1d,
|
||||
>= 21 => args[20].CastToNumber() ?? 1d,
|
||||
_ => 1d,
|
||||
};
|
||||
|
||||
_activeContext.SubmitDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, CurrentAntialias(), CurrentBlend()));
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("copybuffer")]
|
||||
private DynValue CopyBuffer(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count < 2 ||
|
||||
args[0].Type != DataType.String || args[1].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
|
||||
if (_activeContext.CopyBuffer(args[0].String, args[1].String))
|
||||
RefreshObjDimensions();
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("getvalue")]
|
||||
private DynValue GetValue(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.NewNumber(0d);
|
||||
var value = _objScope.Table.Get(args[0].String);
|
||||
return value.Type == DataType.Number ? value : DynValue.NewNumber(0d);
|
||||
}
|
||||
|
||||
[LuaFunction("setoption")]
|
||||
private DynValue SetOption(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
var name = args[0].String;
|
||||
var value = args.Count > 1 ? args[1] : DynValue.True;
|
||||
_options[name] = value;
|
||||
if (name == "draw_state" && _activeContext is not null)
|
||||
_activeContext.DrawStateOverride = value.Type == DataType.Boolean
|
||||
? value.Boolean
|
||||
: (value.CastToNumber() ?? 0d) != 0d;
|
||||
if (name == "drawtarget" && _activeContext is not null)
|
||||
{
|
||||
if (value.Type == DataType.String && value.String == "tempbuffer")
|
||||
{
|
||||
bool hasSize = args.Count > 3;
|
||||
int w = hasSize ? (int)(args[2].CastToNumber() ?? 0d) : 0;
|
||||
int h = hasSize ? (int)(args[3].CastToNumber() ?? 0d) : 0;
|
||||
_activeContext.SetDrawTarget(true, w, h, hasSize);
|
||||
}
|
||||
else
|
||||
{
|
||||
_activeContext.SetDrawTarget(false, 0, 0, false);
|
||||
}
|
||||
}
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("getoption")]
|
||||
private DynValue GetOption(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.NewNumber(0d);
|
||||
return _options.TryGetValue(args[0].String, out var value) ? value : DynValue.NewNumber(0d);
|
||||
}
|
||||
|
||||
[LuaFunction("pixeloption")]
|
||||
private DynValue PixelOption(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
_pixelOptions[args[0].String] = args.Count > 1 ? args[1] : DynValue.True;
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("setanchor")]
|
||||
private DynValue SetAnchor(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || _script is null || args.Count < 2 || args[0].Type != DataType.String)
|
||||
return DynValue.NewNumber(0d);
|
||||
|
||||
var anchorName = args[0].String;
|
||||
int count = AnchorSupport.ClampCount((int)(args[1].CastToNumber() ?? 0d));
|
||||
if (string.Equals(anchorName, AnchorSupport.TrackGroup, StringComparison.Ordinal))
|
||||
return DynValue.NewNumber(0d);
|
||||
|
||||
var connection = AnchorConnection.None;
|
||||
bool is3D = false;
|
||||
for (int i = 2; i < args.Count; i++)
|
||||
{
|
||||
if (args[i].Type == DataType.String)
|
||||
AnchorSupport.ApplyOption(args[i].String, ref connection, ref is3D);
|
||||
}
|
||||
|
||||
int stride = is3D ? 3 : 2;
|
||||
var table = new Table(_script);
|
||||
var source = _activeContext.AnchorSource;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
AnchorSupport.ResolvePosition(source, anchorName, i, out double x, out double y, out double z);
|
||||
table.Set(i * stride + 1, DynValue.NewNumber(x));
|
||||
table.Set(i * stride + 2, DynValue.NewNumber(y));
|
||||
if (is3D)
|
||||
table.Set(i * stride + 3, DynValue.NewNumber(z));
|
||||
}
|
||||
_script.Globals.Set(anchorName, DynValue.NewTable(table));
|
||||
|
||||
_activeContext.AddAnchorRequest(new AnchorRequestData(anchorName, count, connection, is3D));
|
||||
return DynValue.NewNumber(count);
|
||||
}
|
||||
|
||||
[LuaFunction("effect")]
|
||||
private DynValue Effect(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
|
||||
string name = args[0].String;
|
||||
var arguments = new List<KeyValuePair<string, object>>();
|
||||
for (int i = 1; i + 1 < args.Count; i += 2)
|
||||
{
|
||||
if (args[i].Type != DataType.String)
|
||||
continue;
|
||||
var value = args[i + 1];
|
||||
object boxed = value.Type switch
|
||||
{
|
||||
DataType.Number => value.Number,
|
||||
DataType.Boolean => value.Boolean,
|
||||
DataType.String => value.String,
|
||||
_ => value.CastToNumber() ?? 0d,
|
||||
};
|
||||
arguments.Add(new KeyValuePair<string, object>(args[i].String, boxed));
|
||||
}
|
||||
|
||||
_activeContext.AddEffect(new AviUtlEffectRequest(name, arguments));
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("getinfo")]
|
||||
private DynValue GetInfo(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Nil;
|
||||
|
||||
var ctx = _activeContext;
|
||||
return args[0].String switch
|
||||
{
|
||||
"script_path" => DynValue.NewString(ctx.ScriptPath),
|
||||
"filter" => DynValue.True,
|
||||
"saving" => DynValue.NewBoolean(ctx.IsSaving),
|
||||
"image_max" => DynValue.NewTuple(DynValue.NewNumber(ctx.SceneWidth), DynValue.NewNumber(ctx.SceneHeight)),
|
||||
"bpm" => DynValue.NewTuple(DynValue.NewNumber(ctx.Bpm), DynValue.NewNumber(ctx.BpmBeat), DynValue.NewNumber(ctx.BpmOffset)),
|
||||
"clock" => DynValue.NewNumber(s_clock.Elapsed.TotalSeconds),
|
||||
"script_time" => DynValue.NewNumber(Stopwatch.GetElapsedTime(_scriptStartTimestamp).TotalMilliseconds),
|
||||
"version" => DynValue.NewNumber(ctx.HostVersion),
|
||||
_ => DynValue.Nil,
|
||||
};
|
||||
}
|
||||
|
||||
private double CurrentAntialias() =>
|
||||
_options.TryGetValue("antialias", out var value) && value.Type == DataType.Number
|
||||
? value.Number
|
||||
: 1d;
|
||||
|
||||
private double CurrentBlend() =>
|
||||
_options.TryGetValue("blend", out var value) && value.Type == DataType.Number
|
||||
? value.Number
|
||||
: 0d;
|
||||
|
||||
private void LoadFigure(string name, int color, double size, double line, double aspect)
|
||||
{
|
||||
int boundingSize = Math.Max(1, (int)Math.Round(size));
|
||||
double width = aspect >= 0d ? boundingSize * (1d - aspect) : boundingSize;
|
||||
double height = aspect <= 0d ? boundingSize * (1d + aspect) : boundingSize;
|
||||
int w = Math.Max(1, (int)Math.Round(width));
|
||||
int h = Math.Max(1, (int)Math.Round(height));
|
||||
|
||||
var buffer = FigureRenderer.Render(name, w, h, color, line);
|
||||
_activeContext!.ReplaceBuffer(buffer, w, h);
|
||||
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void LoadText(string text)
|
||||
{
|
||||
_mediaLoader ??= _mediaLoaderFactory();
|
||||
var buffer = _mediaLoader.RenderText(
|
||||
text, _fontState.Family, _fontState.Size, _fontState.Bold, _fontState.Italic, _fontState.Color,
|
||||
out int w, out int h);
|
||||
_activeContext!.ReplaceBuffer(buffer, w, h);
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void LoadImage(string path)
|
||||
{
|
||||
_mediaLoader ??= _mediaLoaderFactory();
|
||||
var buffer = _mediaLoader.DecodeImage(path, out int w, out int h);
|
||||
_activeContext!.ReplaceBuffer(buffer, w, h);
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void LoadMovie(string path, double time)
|
||||
{
|
||||
_mediaLoader ??= _mediaLoaderFactory();
|
||||
var buffer = _mediaLoader.DecodeMovie(path, time, out int w, out int h);
|
||||
_activeContext!.ReplaceBuffer(buffer, w, h);
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void RefreshObjDimensions()
|
||||
{
|
||||
int w = _activeContext!.ImageWidth;
|
||||
int h = _activeContext.ImageHeight;
|
||||
var obj = _objScope.Table;
|
||||
obj["w"] = w;
|
||||
obj["h"] = h;
|
||||
obj["hw"] = w / 2d;
|
||||
obj["hh"] = h / 2d;
|
||||
obj["cx"] = w / 2d;
|
||||
obj["cy"] = h / 2d;
|
||||
obj["cz"] = 0d;
|
||||
obj["diagonal"] = Math.Sqrt((double)w * w + (double)h * h);
|
||||
}
|
||||
|
||||
private static DynValue BuildObjectTable(Script script, SceneObjectInfo info)
|
||||
{
|
||||
var table = new Table(script)
|
||||
{
|
||||
["exist"] = info.Exist,
|
||||
["x"] = info.X,
|
||||
["y"] = info.Y,
|
||||
["z"] = info.Z,
|
||||
["zoom"] = info.Zoom,
|
||||
["sx"] = info.Zoom,
|
||||
["sy"] = info.Zoom,
|
||||
["rx"] = 0d,
|
||||
["ry"] = 0d,
|
||||
["rz"] = info.Rz,
|
||||
["rxr"] = 0d,
|
||||
["ryr"] = 0d,
|
||||
["rzr"] = info.Rz * Math.PI / 180d,
|
||||
["alpha"] = info.Alpha,
|
||||
["layer"] = info.Layer,
|
||||
};
|
||||
return DynValue.NewTable(table);
|
||||
}
|
||||
|
||||
private void ReadBackGlobals(AviUtlScriptContext ctx)
|
||||
{
|
||||
if (!_scopesInitialized) return;
|
||||
|
||||
var obj = _objScope.Table;
|
||||
ctx.X = obj.Get("x").CastToNumber() ?? ctx.X;
|
||||
ctx.Y = obj.Get("y").CastToNumber() ?? ctx.Y;
|
||||
ctx.Z = obj.Get("z").CastToNumber() ?? ctx.Z;
|
||||
ctx.Ox = obj.Get("ox").CastToNumber() ?? ctx.Ox;
|
||||
ctx.Oy = obj.Get("oy").CastToNumber() ?? ctx.Oy;
|
||||
ctx.Oz = obj.Get("oz").CastToNumber() ?? ctx.Oz;
|
||||
ctx.Alpha = obj.Get("alpha").CastToNumber() ?? ctx.Alpha;
|
||||
|
||||
ctx.ApplyWriteBack(
|
||||
obj.Get("sx").CastToNumber() ?? ctx.Sx,
|
||||
obj.Get("sy").CastToNumber() ?? ctx.Sy,
|
||||
obj.Get("zoom").CastToNumber() ?? ctx.Zoom,
|
||||
obj.Get("aspect").CastToNumber() ?? ctx.Aspect,
|
||||
obj.Get("rx").CastToNumber() ?? ctx.Rx,
|
||||
obj.Get("ry").CastToNumber() ?? ctx.Ry,
|
||||
obj.Get("rz").CastToNumber() ?? ctx.Rz,
|
||||
obj.Get("rxr").CastToNumber() ?? ctx.RxRad,
|
||||
obj.Get("ryr").CastToNumber() ?? ctx.RyRad,
|
||||
obj.Get("rzr").CastToNumber() ?? ctx.RzRad);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_disposeRequested = true;
|
||||
_workSignal.Release();
|
||||
_thread.Join();
|
||||
_mediaLoader?.Dispose();
|
||||
_cts.Cancel();
|
||||
_cts.Dispose();
|
||||
_workSignal.Dispose();
|
||||
_doneSignal.Dispose();
|
||||
}
|
||||
|
||||
internal void AbandonAsync()
|
||||
{
|
||||
_disposeRequested = true;
|
||||
_workSignal.Release();
|
||||
ThreadPool.QueueUserWorkItem(_ =>
|
||||
{
|
||||
_thread.Join();
|
||||
_mediaLoader?.Dispose();
|
||||
_cts.Dispose();
|
||||
_workSignal.Dispose();
|
||||
_doneSignal.Dispose();
|
||||
});
|
||||
}
|
||||
|
||||
private sealed class DisabledFileScriptLoader : ScriptLoaderBase
|
||||
{
|
||||
public override object LoadFile(string file, Table globalContext)
|
||||
=> throw new NotSupportedException(
|
||||
"File access is not allowed in Lua script effects.");
|
||||
|
||||
public override bool ScriptFileExists(string name) => false;
|
||||
}
|
||||
}
|
||||
|
||||
private const int ExecutionTimeoutMilliseconds = 5000;
|
||||
|
||||
static LuaScriptEngine()
|
||||
{
|
||||
UserData.RegisterType<PixelDataProxy>();
|
||||
}
|
||||
|
||||
private readonly Func<IMediaSourceLoader> _mediaLoaderFactory;
|
||||
private ExecutionThread _executionThread;
|
||||
private bool _disposed;
|
||||
|
||||
internal LuaScriptEngine(Func<IMediaSourceLoader> mediaLoaderFactory)
|
||||
{
|
||||
_mediaLoaderFactory = mediaLoaderFactory;
|
||||
_executionThread = new ExecutionThread(mediaLoaderFactory);
|
||||
}
|
||||
|
||||
public void Execute(string code, AviUtlScriptContext ctx)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
|
||||
var result = _executionThread.TryExecute(code, ctx, ExecutionTimeoutMilliseconds);
|
||||
|
||||
if (result.TimedOut)
|
||||
{
|
||||
var stale = _executionThread;
|
||||
_executionThread = new ExecutionThread(_mediaLoaderFactory);
|
||||
stale.AbandonAsync();
|
||||
throw new LuaScriptTimeoutException(
|
||||
$"Script execution timed out after {ExecutionTimeoutMilliseconds} ms.");
|
||||
}
|
||||
|
||||
if (result.Exception is not null)
|
||||
throw result.Exception;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_executionThread.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript.Engine
|
||||
{
|
||||
internal delegate void PixelRegionAccess(nint address, long capacity);
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="LuaScript" />
|
||||
<InternalsVisibleTo Include="LuaScript.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\LuaScript.Kernel\LuaScript.Kernel.csproj" />
|
||||
<ProjectReference Include="..\LuaScript.Compat\LuaScript.Compat.csproj" />
|
||||
<ProjectReference Include="..\LuaScript.Generator\LuaScript.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MoonSharp" Version="2.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal interface ISceneObjectResolver
|
||||
{
|
||||
bool TryResolve(string tag, int timelineFrame, out SceneObjectInfo info);
|
||||
}
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class SceneSharedValues
|
||||
{
|
||||
public const int MaxNameBytes = 4095;
|
||||
public const int MaxTextBytes = 4095;
|
||||
public const int MaxEntries = 4096;
|
||||
public const long MaxHistoryCostBytes = 16 * 1024 * 1024;
|
||||
|
||||
private const long VersionBaseCost = 64;
|
||||
|
||||
private readonly record struct SceneVersion(long Frame, int Layer, SceneValue Value);
|
||||
|
||||
private static readonly ConditionalWeakTable<object, ConcurrentDictionary<string, SceneSharedValues>> s_scopes = new();
|
||||
|
||||
private readonly Dictionary<string, List<SceneVersion>> _names = new(StringComparer.Ordinal);
|
||||
private readonly object _gate = new();
|
||||
private long _historyCost;
|
||||
|
||||
public static SceneSharedValues ForScene(object scope, string sceneId) =>
|
||||
s_scopes.GetOrCreateValue(scope).GetOrAdd(sceneId, static _ => new SceneSharedValues());
|
||||
|
||||
public SceneValue Read(long generation, string name)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_names.TryGetValue(name, out var versions))
|
||||
return SceneValue.Nil;
|
||||
int index = LatestBefore(versions, generation);
|
||||
return index >= 0 ? versions[index].Value : SceneValue.Nil;
|
||||
}
|
||||
}
|
||||
|
||||
public void Publish(long generation, int layer, Dictionary<string, SceneValue> writes)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
foreach (var pair in writes)
|
||||
Upsert(generation, layer, pair.Key, pair.Value);
|
||||
EnforceHistoryBudget();
|
||||
}
|
||||
}
|
||||
|
||||
private void Upsert(long generation, int layer, string name, SceneValue value)
|
||||
{
|
||||
if (!_names.TryGetValue(name, out var versions))
|
||||
{
|
||||
if (_names.Count >= MaxEntries)
|
||||
return;
|
||||
if (value == SceneValue.Nil)
|
||||
return;
|
||||
_names[name] = [new SceneVersion(generation, layer, value)];
|
||||
return;
|
||||
}
|
||||
|
||||
int index = LatestBefore(versions, generation + 1);
|
||||
if (index >= 0 && versions[index].Frame == generation)
|
||||
{
|
||||
if (layer < versions[index].Layer)
|
||||
return;
|
||||
if (index < versions.Count - 1)
|
||||
_historyCost += CostOf(value) - CostOf(versions[index].Value);
|
||||
versions[index] = new SceneVersion(generation, layer, value);
|
||||
return;
|
||||
}
|
||||
|
||||
var previous = index >= 0 ? versions[index].Value : SceneValue.Nil;
|
||||
if (value == previous)
|
||||
return;
|
||||
|
||||
versions.Insert(index + 1, new SceneVersion(generation, layer, value));
|
||||
if (index + 1 < versions.Count - 1)
|
||||
_historyCost += CostOf(value);
|
||||
else if (versions.Count > 1)
|
||||
_historyCost += CostOf(versions[^2].Value);
|
||||
}
|
||||
|
||||
private void EnforceHistoryBudget()
|
||||
{
|
||||
while (_historyCost > MaxHistoryCostBytes)
|
||||
{
|
||||
List<SceneVersion>? oldest = null;
|
||||
string oldestName = string.Empty;
|
||||
foreach (var pair in _names)
|
||||
{
|
||||
var versions = pair.Value;
|
||||
if (versions.Count < 2)
|
||||
continue;
|
||||
if (oldest is null ||
|
||||
versions[0].Frame < oldest[0].Frame ||
|
||||
(versions[0].Frame == oldest[0].Frame && string.CompareOrdinal(pair.Key, oldestName) < 0))
|
||||
{
|
||||
oldest = versions;
|
||||
oldestName = pair.Key;
|
||||
}
|
||||
}
|
||||
if (oldest is null)
|
||||
return;
|
||||
_historyCost -= CostOf(oldest[0].Value);
|
||||
oldest.RemoveAt(0);
|
||||
}
|
||||
}
|
||||
|
||||
private static long CostOf(SceneValue value) =>
|
||||
VersionBaseCost + (value.Text is null ? 0 : value.Text.Length * 2L);
|
||||
|
||||
private static int LatestBefore(List<SceneVersion> versions, long generation)
|
||||
{
|
||||
int low = 0;
|
||||
int high = versions.Count - 1;
|
||||
int result = -1;
|
||||
while (low <= high)
|
||||
{
|
||||
int mid = (low + high) >> 1;
|
||||
if (versions[mid].Frame < generation)
|
||||
{
|
||||
result = mid;
|
||||
low = mid + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
high = mid - 1;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static string NormalizeName(string name) => TruncateUtf8(name, MaxNameBytes);
|
||||
|
||||
public static SceneValue NormalizeValue(SceneValue value) =>
|
||||
value.Kind == SceneValueKind.String
|
||||
? SceneValue.FromString(TruncateUtf8(value.Text ?? string.Empty, MaxTextBytes))
|
||||
: value;
|
||||
|
||||
private static string TruncateUtf8(string text, int maxBytes)
|
||||
{
|
||||
if (text.Length <= maxBytes / 3 || Encoding.UTF8.GetByteCount(text) <= maxBytes)
|
||||
return text;
|
||||
|
||||
int bytes = 0;
|
||||
int length = 0;
|
||||
while (length < text.Length)
|
||||
{
|
||||
char c = text[length];
|
||||
int size;
|
||||
int step = 1;
|
||||
if (char.IsHighSurrogate(c) && length + 1 < text.Length && char.IsLowSurrogate(text[length + 1]))
|
||||
{
|
||||
size = 4;
|
||||
step = 2;
|
||||
}
|
||||
else if (c < 0x80)
|
||||
{
|
||||
size = 1;
|
||||
}
|
||||
else if (c < 0x800)
|
||||
{
|
||||
size = 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
size = 3;
|
||||
}
|
||||
if (bytes + size > maxBytes)
|
||||
break;
|
||||
bytes += size;
|
||||
length += step;
|
||||
}
|
||||
return text[..length];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal readonly record struct SceneValue(SceneValueKind Kind, double Number, string? Text)
|
||||
{
|
||||
public static readonly SceneValue Nil = new(SceneValueKind.Nil, 0d, null);
|
||||
|
||||
public static SceneValue FromNumber(double value) => new(SceneValueKind.Number, value, null);
|
||||
|
||||
public static SceneValue FromBoolean(bool value) => new(SceneValueKind.Boolean, value ? 1d : 0d, null);
|
||||
|
||||
public static SceneValue FromString(string value) => new(SceneValueKind.String, 0d, value);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal enum SceneValueKind
|
||||
{
|
||||
Nil = 0,
|
||||
Number = 1,
|
||||
String = 2,
|
||||
Boolean = 3,
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal readonly record struct SceneValueQuery(string Name, SceneValue Result);
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class SceneValueSession
|
||||
{
|
||||
private readonly Dictionary<string, SceneValue> _writes = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, SceneValue> _reads = new(StringComparer.Ordinal);
|
||||
private readonly List<SceneValueQuery> _queries = [];
|
||||
|
||||
private SceneSharedValues? _store;
|
||||
private object _scope = new();
|
||||
private string _sceneId = string.Empty;
|
||||
private long _generation;
|
||||
private int _layer;
|
||||
|
||||
public bool HasWrites => _writes.Count > 0;
|
||||
|
||||
public IReadOnlyList<SceneValueQuery> Queries => _queries;
|
||||
|
||||
public void Begin(object scope, string sceneId, long generation, int layer)
|
||||
{
|
||||
if (!ReferenceEquals(_scope, scope) || !string.Equals(_sceneId, sceneId, StringComparison.Ordinal))
|
||||
{
|
||||
_store = null;
|
||||
_scope = scope;
|
||||
_sceneId = sceneId;
|
||||
}
|
||||
_generation = generation;
|
||||
_layer = layer;
|
||||
_writes.Clear();
|
||||
_reads.Clear();
|
||||
_queries.Clear();
|
||||
}
|
||||
|
||||
public SceneValue Get(string name)
|
||||
{
|
||||
name = SceneSharedValues.NormalizeName(name);
|
||||
if (_writes.TryGetValue(name, out var written))
|
||||
return written;
|
||||
if (_reads.TryGetValue(name, out var cached))
|
||||
return cached;
|
||||
var value = Store.Read(_generation, name);
|
||||
_reads[name] = value;
|
||||
_queries.Add(new SceneValueQuery(name, value));
|
||||
return value;
|
||||
}
|
||||
|
||||
public void Set(string name, SceneValue value)
|
||||
{
|
||||
name = SceneSharedValues.NormalizeName(name);
|
||||
value = SceneSharedValues.NormalizeValue(value);
|
||||
if (value.Kind != SceneValueKind.Nil &&
|
||||
!_writes.ContainsKey(name) &&
|
||||
_writes.Count >= SceneSharedValues.MaxEntries)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_writes[name] = value;
|
||||
}
|
||||
|
||||
public void Publish()
|
||||
{
|
||||
if (_writes.Count == 0)
|
||||
return;
|
||||
Store.Publish(_generation, _layer, _writes);
|
||||
}
|
||||
|
||||
private SceneSharedValues Store => _store ??= SceneSharedValues.ForScene(_scope, _sceneId);
|
||||
}
|
||||
}
|
||||
222ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。
さらに表示
新しいイシューから参照
ユーザーをブロックする