コミットを比較

..
37 コミット
作成者 SHA1 メッセージ 日付
routersys 1f421dd158 バージョンをv1.20.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.20.1 のコミットから作成しました
2026-07-05 18:45:22 +09:00
routersys e56a2d85d7 CHANGELOGをv1.20.1の内容へ更新 2026-07-05 18:45:22 +09:00
routersys 969cf52299 READMEを自動GPU委譲の仕様へ更新 2026-07-05 18:24:08 +09:00
routersys 01785267fc サイトを自動GPU委譲の仕様へ更新 2026-07-05 18:24:08 +09:00
routersys 206001888c 全言語ドキュメントを自動GPU委譲の仕様へ更新 2026-07-05 18:24:07 +09:00
routersys 7c8776dd05 MoonSharpの画像加工を自動GPU委譲へ統一 2026-07-05 18:24:07 +09:00
routersys d6756ad3c8 ワーカーの画像加工を自動GPU委譲へ統一 2026-07-05 18:24:07 +09:00
routersys 57c3b346d8 バージョンをv1.20.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.20.0 のコミットから作成しました
2026-07-05 17:44:48 +09:00
routersys 55dde273ae CHANGELOGをv1.20.0の内容へ全置換 2026-07-05 17:43:02 +09:00
routersys a6a9963c85 補完候補へ構文拡張キーワードfastを登録 2026-07-05 17:26:28 +09:00
routersys fb7614d6fb 構文規則属性にIsCatalogとKeywordを追加 2026-07-05 17:26:28 +09:00
routersys a7a8c6b117 ハードウェアデバイス再生成に予算制限を適用 2026-07-05 17:12:16 +09:00
routersys 8b59897992 ホストコールバック時間をネイティブタイムアウトから除外 2026-07-05 17:12:15 +09:00
routersys 0d8f1e5102 [fast]の記載例を単独行形式へ統一 2026-07-05 16:37:10 +09:00
routersys e6165ca5a3 [fast]の診断を英語化し単独行形式をテスト 2026-07-05 16:37:10 +09:00
routersys 2bd54674c1 READMEへ[fast]高速化マーカーを追記 2026-07-05 16:13:11 +09:00
routersys 9a733807e8 [fast]をサイト構文ドキュメントへ追記 2026-07-05 16:13:08 +09:00
routersys f14c689353 [fast]を全言語ドキュメントへ追記 2026-07-05 16:13:05 +09:00
routersys d4443a1eef [fast]と高速化経路のテストを追加 2026-07-05 16:12:51 +09:00
routersys b618a3093b [fast]マーカーの書き換え規則を追加 2026-07-05 16:12:47 +09:00
routersys a03ba45f2a 拡張構文の書き換え診断を全経路へ通す 2026-07-05 16:12:44 +09:00
routersys 56c38b2891 エンジンに__fast_*プリミティブを配線 2026-07-05 16:12:31 +09:00
routersys 68b730e6d2 ワーカーに[fast]高速化プリミティブを追加 2026-07-05 16:12:28 +09:00
routersys ce7b15121c 画像加工にGPU委譲の明示フラグを追加 2026-07-05 16:12:26 +09:00
routersys 50b20e3060 GPU生成器の増分キャッシュをEquatableArray化 2026-07-05 13:52:30 +09:00
routersys c1f4fa2dc5 生成器をLua/Gpuへ整理し型を1ファイル1クラス化 2026-07-05 13:36:03 +09:00
routersys af9c5af173 GPU内部シェーダーをビルド時DXBC化 2026-07-05 13:22:06 +09:00
routersys 406a4c1a1b LuaJIT画像処理をGPU委譲 2026-07-05 11:19:28 +09:00
routersys b732dd1b90 畳み込みHLSLの予約語衝突を修正 2026-07-05 10:49:56 +09:00
routersys 1e93df21ef MoonSharp画像処理をGPU委譲 2026-07-05 10:44:17 +09:00
routersys 3bd6133bef GPUシェーダー管理を属性生成化 2026-07-05 10:40:33 +09:00
routersys 0c05fe2198 GPU画像処理をHW実行へ限定 2026-07-05 10:22:19 +09:00
routersys 775791d1e1 画像処理CPU基準を共有化 2026-07-05 10:16:12 +09:00
routersys a291d66567 画像処理のGPU委譲契約を追加 2026-07-05 10:11:26 +09:00
routersys 31d26c0a70 GPU基盤を専用プロジェクトへ分離 2026-07-05 10:05:41 +09:00
routersys 88b95cc09a 構文規則モデルを専用ファイルへ分離 2026-07-05 09:08:25 +09:00
routersys 9ff328d03a API生成器の型宣言を1ファイル1型へ分離 2026-07-05 09:08:19 +09:00
76個のファイルの変更、2550行の追加、263行の削除

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

+27 -15
ファイルの表示
@@ -1,32 +1,44 @@
# v1.19.2 - Lua スクリプト for YMM4
# v1.20.1 - Lua スクリプト for YMM4
従来エンジン(MoonSharp)の毎フレームのグローバル変数更新を高速化したパッチリリースです。スクリプトの書き方と実行結果は一切変わりません。高速ランタイム(LuaJIT)の実装にも変更はありません。
画像加工の GPU 委譲を自動判定へ変更したリリースです。v1.20.0 では obj.fill / obj.convolve / obj.resize は [fast] マーカーを付けたときだけ GPU へ委譲していましたが、本バージョンからは標準の呼び出しでも、処理量がしきい値以上で GPU の結果が CPU と一致すると確認できたとき、自動で GPU へ委譲します。マーカーを知らなくても大きな処理は速くなり、成立しない場合は従来どおり CPU で実行するため結果は変わりません。[fast] は構文・診断ともそのまま残り、委譲の意図を明示する補助マーカーになりました。置いても動作は変わりません。
---
## 改善
## 変更
### 毎フレームのグローバル変数更新のボックス化を除去
### 画像加工の GPU 委譲を自動判定へ
従来エンジンは実行のたびに obj / scene / ymm4 / グローバルの約 70 個の変数をテーブルへ書き込みます。この書き込みが object 型のインデクサ経由で、数値・真偽値のボックス化と型変換のディスパッチを毎回発生させていました。ソースジェネレーターの発行を型付きの Table.Set へ変更し、ボックス化と変換ディスパッチを削除しました。
obj.fill / obj.convolve / obj.resize は書き方を変えることなく、条件が成立したとき自動で GPU へ委譲します。委譲が成立する条件は v1.20.0 の [fast] と同じで、いずれかを満たさない場合は自動で CPU 実行になり、処理は失敗しません。
- 数値は DynValue.NewNumber、文字列は DynValue.NewString の直接生成になります。
- 真偽値は MoonSharp が共有する DynValue の参照になり、割り当てが完全になくなります。
- obj.load / obj.copybuffer / obj.resize の後の寸法更新(obj.w 等の 8 個)も同じ形へ揃えました。
- Direct3D 11 のハードウェアデバイスが利用できること。ソフトウェアラスタライザ(WARP)へは委譲しません。CPU 実装より遅くなるためです。
- 処理量がしきい値以上であること。fill は画像全体で 1,048,576 画素以上、矩形指定では同じ画素数に加えて塗り面積が画像の 3/4 以上、resize は出力が 262,144 画素以上、convolve は画素数×係数の個数が 262,144 以上です。小さな処理は委譲の往復コストが上回るため CPU で実行します。
- convolve のカーネルは 31×31 までです。それを超えるサイズは CPU で実行します。
- 初回に小さな検証画像で GPU の結果を CPU 基準とバイト単位で比較し、一致した組み合わせだけを GPU へ委譲すること。不一致の環境やカーネルでは CPU 実行へ戻ります。
### [fast] マーカーは補助的な明示へ
判定が自動になったため、[fast] は委譲の意図を明示する補助マーカーになりました。
- 構文・置ける位置(単独の行または同じ行)・内部プリミティブへの書き換えは v1.20.0 から変わりません。
- 3 関数以外へ付けたときのエラー表示もそのまま機能します。
- [fast] を付けた呼び出しと付けない呼び出しは同じ判定を通るため、動作の差はありません。既存の [fast] 付きスクリプトはそのまま動きます。
---
## 互換性・後方互換
- すべての変数の名前・型・値に変更はありません。ボックス化と変換ディスパッチの除去のみで、テーブルへ格納される内容は従来と同一です。
- 両エンジンの実行結果はバイト単位まで一致したままです。
- v1.19.1 までの構文拡張と既存の API に変更はありません。
- しきい値未満の小さな処理、GPU が使えない環境、検証に通らないカーネルでは、実行結果は v1.20.0 と同一です。
- GPU 委譲は事前の検証で CPU 基準とバイト単位まで一致した組み合わせに限って行い、成立しない場合は常に CPU 実装が結果を保証します。
- 関数の引数・戻り値・エラーの扱いに変更はありません。スクリプトの書き換えは不要です。
- エンジンの自動振り分け、エンジン指定ディレクティブの仕様と優先順位、カーネル化の対象、v1.20.0 までの構文拡張と既存の API に変更はありません。
---
## 内部実装
- 型付き発行は LuaApiGenerator が担います。更新メソッドの戻り値型(double / int / bool / string とその null 許容)から値種別を判定し、DynValue.NewNumber / NewBoolean / NewString を包んだ Table.Set を発行します。未知の型は従来のインデクサ発行へ残すため、後方互換は構造的に保たれます。
- 発行部 1 箇所の変更で全レジストラ(AviUtlGlobalRegistrar / SceneTableRegistrar / Ymm4TableRegistrar / obj テーブル)に波及します。個別の書き換えはありません。
- 数値の DynValue 生成自体は値が毎フレーム変わるため残ります。共有インスタンスの書き換えはスクリプトが参照を保持しうるため行いません。
- テストは 3366 件のまま全件成功です。ソリューションは x64 で 0 個の警告、0 個のエラーです。
- 3 実行系(MoonSharp・LuaJIT ワーカー・コンテキスト契約)から委譲の明示フラグ accelerate を削除しました。[fast] の書き換え先である __fast_fill / __fast_convolve / __fast_resize は標準の関数と同じ実装の別名になり、マーカーの有無で経路が分かれることは構造的にありません。
- 従来エンジンは AviUtlScriptContext の fill / convolve / resize が常にプロセッサへ照会し、不成立なら CPU 実装へ落ちます。しきい値の判定は GPU 演算側(GpuFillOperation / GpuConvolveOperation / GpuResizeOperation)が持ちます。
- 高速ランタイムは worker.lua がしきい値の成立時のみホストへ往復し、しきい値未満は往復せず Lua 内で完結します。成立し得ない委譲のプロセス間往復コストは発生しません。
- GPU 基盤(専用プロジェクト・事前 DXBC コンパイル・検証キャッシュ・再生成予算)は v1.20.0 のまま変更していません。
- ドキュメントは付属の 8 言語の [fast] の節、サイトの構文拡張と obj の関数のページ、README を自動判定の仕様へ更新しました。
- テストは 3400 件です。v1.20.0 の 3396 件から、標準呼び出しがホストプロセッサへ委譲されることの検証へ両レーンの既定経路テストを反転し、しきい値未満では委譲しないことの検証 3 件と、従来エンジンの委譲と CPU フォールバックの検証 1 件を追加しました。ソリューションは x64 で 0 個の警告、0 個のエラーです。
+1 -1
ファイルの表示
@@ -1,5 +1,5 @@
========================================
Luaスクリプト for YMM4 v1.19.2
Luaスクリプト for YMM4 v1.20.1
========================================
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
ピクセルを直接制御できるプラグインです。
+1
ファイルの表示
@@ -77,6 +77,7 @@ jobs:
Copy-Item "$outDir/LuaScript.Compat.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Media.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Runtime.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Gpu.dll" "$stageRoot/"
Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/"
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
+1 -1
ファイルの表示
@@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.19.2</Version>
<Version>1.20.1</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
</PropertyGroup>
+7 -6
ファイルの表示
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Text;
using LuaScript.Compat.Syntax;
namespace LuaScript.Compat
{
@@ -15,10 +16,10 @@ namespace LuaScript.Compat
public static string Transform(string source) => TransformWithMap(source).Code;
public static (string Code, int[] LineMap, int[] ChangedLines) TransformWithMap(string source)
public static (string Code, int[] LineMap, int[] ChangedLines, LuaRewriteDiagnostic[] Diagnostics) TransformWithMap(string source)
{
if (string.IsNullOrEmpty(source))
return (source, [], []);
return (source, [], [], []);
var lines = ScriptParserHelper.SplitLines(source);
bool hasSection = ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
@@ -29,8 +30,8 @@ namespace LuaScript.Compat
if (!hasSection && prelude.Count == 0)
{
var (code, changed) = LuaSyntaxExtensions.RewriteWithMap(source);
return (code, [], changed);
var (code, changed, preludeless) = LuaSyntaxExtensions.RewriteWithMap(source);
return (code, [], changed, preludeless);
}
var builder = new StringBuilder(source.Length + 64);
@@ -48,8 +49,8 @@ namespace LuaScript.Compat
lineMap[row++] = i;
}
var (rewritten, changedLines) = LuaSyntaxExtensions.RewriteWithMap(builder.ToString());
return (rewritten, lineMap, changedLines);
var (rewritten, changedLines, diagnostics) = LuaSyntaxExtensions.RewriteWithMap(builder.ToString());
return (rewritten, lineMap, changedLines, diagnostics);
}
private static void AppendDeclarations(string line, List<string> prelude)
+4 -3
ファイルの表示
@@ -6,10 +6,10 @@ namespace LuaScript.Compat
{
public static string Rewrite(string source) => RewriteWithMap(source).Code;
public static (string Code, int[] ChangedLines) RewriteWithMap(string source)
public static (string Code, int[] ChangedLines, LuaRewriteDiagnostic[] Diagnostics) RewriteWithMap(string source)
{
if (string.IsNullOrEmpty(source))
return (source, []);
return (source, [], []);
var tokens = LuaSyntaxLexer.Tokenize(source);
var context = new LuaRewriteContext(tokens);
@@ -42,7 +42,8 @@ namespace LuaScript.Compat
}
}
return context.Changed ? (context.Serialize(), context.ChangedLines) : (source, []);
var diagnostics = context.Diagnostics;
return context.Changed ? (context.Serialize(), context.ChangedLines, diagnostics) : (source, [], diagnostics);
}
}
}
+9
ファイルの表示
@@ -8,6 +8,7 @@ namespace LuaScript.Compat.Syntax
private readonly List<LuaSyntaxToken> _input;
private readonly List<LuaSyntaxToken> _output;
private List<int>? _changedLines;
private List<LuaRewriteDiagnostic>? _diagnostics;
private int _line = 1;
private int _lastChangedLine;
private int _temporaries;
@@ -28,6 +29,14 @@ namespace LuaScript.Compat.Syntax
public int[] ChangedLines => _changedLines is null ? [] : _changedLines.ToArray();
public LuaRewriteDiagnostic[] Diagnostics => _diagnostics is null ? [] : _diagnostics.ToArray();
public void AddDiagnostic(string message)
{
(_diagnostics ??= new List<LuaRewriteDiagnostic>()).Add(new LuaRewriteDiagnostic(_line, message));
MarkChanged();
}
public bool AtEnd => Index >= _input.Count;
public LuaSyntaxToken Current => _input[Index];
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Compat.Syntax
{
internal readonly record struct LuaRewriteDiagnostic(int Line, string Message);
}
+4
ファイルの表示
@@ -6,5 +6,9 @@ namespace LuaScript.Compat.Syntax
internal sealed class LuaSyntaxRuleAttribute(int order) : Attribute
{
public int Order { get; } = order;
public bool IsCatalog { get; set; }
public string Keyword { get; set; } = "";
}
}
+76
ファイルの表示
@@ -0,0 +1,76 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(2, IsCatalog = true, Keyword = MarkerKeyword)]
internal sealed class LuaFastRule : ILuaSyntaxRule
{
private const string MarkerKeyword = "fast";
private const string Message = "[fast]: only obj.fill, obj.convolve and obj.resize can be accelerated.";
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("["))
return false;
if (context.TryPreviousOutputSignificantSameLine(out var previous) && LuaSyntaxFacts.IsValueEnd(previous))
return false;
int nameIndex = context.NextSignificant(context.Index + 1);
if (nameIndex < 0 || !context.Input[nameIndex].IsName(MarkerKeyword))
return false;
int closeIndex = context.NextSignificant(nameIndex + 1);
if (closeIndex < 0 || !context.Input[closeIndex].IsOperator("]"))
return false;
int targetIndex = context.NextSignificant(closeIndex + 1);
if (targetIndex < 0 || context.Input[targetIndex].Kind != LuaSyntaxTokenKind.Name)
return false;
if (TryResolveTarget(context, targetIndex, out int funcIndex, out string function))
{
EmitBetween(context, closeIndex + 1, targetIndex);
context.Index = funcIndex + 1;
context.EmitRaw("__fast_" + function);
return true;
}
context.AddDiagnostic(Message);
EmitBetween(context, closeIndex + 1, targetIndex);
context.Index = targetIndex;
return true;
}
private static bool TryResolveTarget(LuaRewriteContext context, int objIndex, out int funcIndex, out string function)
{
funcIndex = -1;
function = string.Empty;
if (!context.Input[objIndex].IsName("obj"))
return false;
int dot = context.NextSignificant(objIndex + 1);
if (dot < 0 || !context.Input[dot].IsOperator("."))
return false;
int name = context.NextSignificant(dot + 1);
if (name < 0)
return false;
string text = context.Input[name].Text;
if (text is not ("fill" or "convolve" or "resize"))
return false;
int paren = context.NextSignificant(name + 1);
if (paren < 0 || !context.Input[paren].IsOperator("("))
return false;
funcIndex = name;
function = text;
return true;
}
private static void EmitBetween(LuaRewriteContext context, int from, int to)
{
for (int i = from; i < to; i++)
context.Emit(context.Input[i]);
}
}
}
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderClass(
string Namespace,
EquatableArray<GpuShaderTypePart> TypeChain,
EquatableArray<GpuShaderMethod> Methods,
EquatableArray<string> Errors);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderFile(string Path, string Source);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderInvocation(string Resources, string Constants, string Target, string Width, string Height);
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderMethod(
string Accessibility,
bool IsStatic,
string ReturnType,
string MethodName,
EquatableArray<GpuShaderParameter> Parameters,
string FileName,
string EntryPoint,
GpuShaderInvocation Invocation);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderMethodSource(GpuShaderMethod Method, string Bytecode);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderParameter(string Prefix, string Type, string Name);
}
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System.Collections.Immutable;
namespace LuaScript.Generator
{
internal sealed record GpuShaderResolution(ImmutableArray<GpuShaderMethodSource> Methods, ImmutableArray<string> Errors);
}
+436
ファイルの表示
@@ -0,0 +1,436 @@
using System.Collections.Immutable;
using System.Globalization;
using System.IO;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace LuaScript.Generator
{
[Generator]
public sealed class GpuShaderSourceGenerator : IIncrementalGenerator
{
private const string AttributeName = "LuaScript.Engine.Processing.GpuPixelOperationShaderAttribute";
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var classes = context.SyntaxProvider
.CreateSyntaxProvider(
static (node, _) => node is ClassDeclarationSyntax { AttributeLists.Count: > 0 },
static (ctx, _) => CreateClass(ctx))
.Where(static model => model is not null)
.Select(static (model, _) => model!);
var files = context.AdditionalTextsProvider
.Where(static file => file.Path.EndsWith(".hlsl", StringComparison.OrdinalIgnoreCase))
.Select(static (file, token) => new GpuShaderFile(Normalize(file.Path), file.GetText(token)?.ToString() ?? string.Empty))
.Collect()
.Select(static (items, _) => new EquatableArray<GpuShaderFile>([.. items]));
context.RegisterSourceOutput(classes.Combine(files), static (context, source) =>
{
var (model, files) = source;
var resolved = Resolve(model, files);
if (resolved.Errors.Length > 0)
{
context.AddSource(ErrorHintName(model), SourceText.From(EmitErrors(resolved.Errors), Encoding.UTF8));
return;
}
context.AddSource(HintName(model), SourceText.From(Emit(model, resolved.Methods), Encoding.UTF8));
});
}
private static GpuShaderClass? CreateClass(GeneratorSyntaxContext context)
{
if (context.Node is not ClassDeclarationSyntax declaration)
return null;
if (context.SemanticModel.GetDeclaredSymbol(declaration) is not INamedTypeSymbol type)
return null;
var attributes = type.GetAttributes()
.Where(static attribute => attribute.AttributeClass?.ToDisplayString() == AttributeName)
.ToArray();
if (attributes.Length == 0)
return null;
var chain = new List<GpuShaderTypePart>();
for (var current = type; current is not null; current = current.ContainingType)
chain.Insert(0, new GpuShaderTypePart(current.Name, current.IsStatic));
var methods = ImmutableArray.CreateBuilder<GpuShaderMethod>();
var errors = ImmutableArray.CreateBuilder<string>();
foreach (var attribute in attributes)
{
if (attribute.ConstructorArguments.Length < 3 ||
attribute.ConstructorArguments[0].Value is not string methodName ||
attribute.ConstructorArguments[1].Value is not string fileName ||
attribute.ConstructorArguments[2].Value is not string entryPoint)
{
errors.Add("GPU shader attribute arguments are invalid");
continue;
}
var candidates = type.GetMembers(methodName).OfType<IMethodSymbol>().ToArray();
if (candidates.Length == 0)
{
errors.Add($"GPU shader method '{methodName}' was not found");
continue;
}
if (candidates.Length > 1)
{
errors.Add($"GPU shader method '{methodName}' is ambiguous");
continue;
}
var method = candidates[0];
string? error = Validate(method, fileName, entryPoint, out var invocation);
if (error is not null)
{
errors.Add($"GPU shader method '{methodName}': {error}");
continue;
}
var parameters = ImmutableArray.CreateBuilder<GpuShaderParameter>();
foreach (var parameter in method.Parameters)
parameters.Add(new GpuShaderParameter(ParameterPrefix(parameter), parameter.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), parameter.Name));
methods.Add(new GpuShaderMethod(
AccessibilityName(method.DeclaredAccessibility),
method.IsStatic,
method.ReturnType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
method.Name,
new EquatableArray<GpuShaderParameter>([.. parameters]),
Normalize(fileName),
entryPoint,
invocation));
}
return new GpuShaderClass(
type.ContainingNamespace.IsGlobalNamespace ? string.Empty : type.ContainingNamespace.ToDisplayString(),
new EquatableArray<GpuShaderTypePart>([.. chain]),
new EquatableArray<GpuShaderMethod>([.. methods]),
new EquatableArray<string>([.. errors]));
}
private static string? Validate(IMethodSymbol method, string fileName, string entryPoint, out GpuShaderInvocation invocation)
{
invocation = new GpuShaderInvocation(string.Empty, string.Empty, string.Empty, string.Empty, string.Empty);
if (string.IsNullOrWhiteSpace(fileName))
return "file name is empty";
if (string.IsNullOrWhiteSpace(entryPoint))
return "entry point is empty";
if (method.ReturnType.SpecialType != SpecialType.System_Boolean)
return "return type must be bool";
var parameters = method.Parameters;
if (parameters.Length == 4 &&
IsReadOnlySpanSingle(parameters[0].Type) &&
IsByteArray(parameters[1].Type) &&
IsInt32(parameters[2].Type) &&
IsInt32(parameters[3].Type))
{
invocation = new GpuShaderInvocation("[]", parameters[0].Name, parameters[1].Name, parameters[2].Name, parameters[3].Name);
return null;
}
if (parameters.Length == 5 &&
IsReadOnlySpanPixelShaderInput(parameters[0].Type) &&
IsReadOnlySpanSingle(parameters[1].Type) &&
IsByteArray(parameters[2].Type) &&
IsInt32(parameters[3].Type) &&
IsInt32(parameters[4].Type))
{
invocation = new GpuShaderInvocation(parameters[0].Name, parameters[1].Name, parameters[2].Name, parameters[3].Name, parameters[4].Name);
return null;
}
return "signature is invalid";
}
private static GpuShaderResolution Resolve(GpuShaderClass model, EquatableArray<GpuShaderFile> files)
{
var methods = ImmutableArray.CreateBuilder<GpuShaderMethodSource>();
var errors = ImmutableArray.CreateBuilder<string>();
errors.AddRange(model.Errors);
foreach (var method in model.Methods)
{
var matched = files.Where(file => Matches(file.Path, method.FileName)).ToArray();
if (matched.Length == 0)
{
errors.Add($"GPU shader file '{method.FileName}' for method '{method.MethodName}' was not found");
continue;
}
if (matched.Length > 1)
{
errors.Add($"GPU shader file '{method.FileName}' for method '{method.MethodName}' matched multiple additional files");
continue;
}
string? failure = ShaderCompiler.Compile(matched[0].Source, method.EntryPoint, out string bytecode);
if (failure is not null)
{
errors.Add($"GPU shader method '{method.MethodName}' failed to compile: {failure}");
continue;
}
methods.Add(new GpuShaderMethodSource(method, bytecode));
}
return new GpuShaderResolution([.. methods], [.. errors]);
}
private static bool Matches(string filePath, string registrationPath)
{
if (string.Equals(filePath, registrationPath, StringComparison.OrdinalIgnoreCase))
return true;
return filePath.EndsWith("/" + registrationPath, StringComparison.OrdinalIgnoreCase);
}
private static bool IsReadOnlySpanSingle(ITypeSymbol type)
{
return type is INamedTypeSymbol named &&
named.OriginalDefinition.ToDisplayString() == "System.ReadOnlySpan<T>" &&
named.TypeArguments.Length == 1 &&
named.TypeArguments[0].SpecialType == SpecialType.System_Single;
}
private static bool IsReadOnlySpanPixelShaderInput(ITypeSymbol type)
{
string display = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
return display.Contains("ReadOnlySpan", StringComparison.Ordinal) &&
display.Contains("PixelShaderInput", StringComparison.Ordinal);
}
private static bool IsByteArray(ITypeSymbol type)
{
return type is IArrayTypeSymbol array &&
array.Rank == 1 &&
array.ElementType.SpecialType == SpecialType.System_Byte;
}
private static bool IsInt32(ITypeSymbol type) => type.SpecialType == SpecialType.System_Int32;
private static string Normalize(string path) => path.Replace(Path.DirectorySeparatorChar, '/').Replace(Path.AltDirectorySeparatorChar, '/');
private static string AccessibilityName(Accessibility accessibility)
{
return accessibility switch
{
Accessibility.Public => "public",
Accessibility.Internal => "internal",
Accessibility.Protected => "protected",
Accessibility.ProtectedAndInternal => "private protected",
Accessibility.ProtectedOrInternal => "protected internal",
_ => "private",
};
}
private static string ParameterPrefix(IParameterSymbol parameter)
{
return parameter.RefKind switch
{
RefKind.In => "in ",
RefKind.Ref => "ref ",
RefKind.Out => "out ",
_ => string.Empty,
};
}
private static string Emit(GpuShaderClass model, ImmutableArray<GpuShaderMethodSource> sources)
{
var builder = new StringBuilder();
builder.AppendLine("#nullable enable");
if (model.Namespace.Length > 0)
{
builder.AppendLine("namespace " + model.Namespace);
builder.AppendLine("{");
}
int indent = model.Namespace.Length > 0 ? 1 : 0;
foreach (var type in model.TypeChain)
{
AppendIndent(builder, indent);
builder.Append(type.IsStatic ? "static partial class " : "partial class ");
builder.AppendLine(type.Name);
AppendIndent(builder, indent);
builder.AppendLine("{");
indent++;
}
for (int i = 0; i < sources.Length; i++)
{
if (i > 0)
builder.AppendLine();
EmitMethod(builder, indent, sources[i]);
}
for (int i = model.TypeChain.Count - 1; i >= 0; i--)
{
indent--;
AppendIndent(builder, indent);
builder.AppendLine("}");
}
if (model.Namespace.Length > 0)
builder.AppendLine("}");
return builder.ToString();
}
private static void EmitMethod(StringBuilder builder, int indent, GpuShaderMethodSource source)
{
var method = source.Method;
string field = "s_shader_" + method.MethodName;
AppendIndent(builder, indent);
builder.Append("private static readonly byte[] ");
builder.Append(field);
builder.Append(" = global::System.Convert.FromBase64String(");
builder.Append(Literal(source.Bytecode));
builder.AppendLine(");");
builder.AppendLine();
AppendIndent(builder, indent);
builder.Append(method.Accessibility);
builder.Append(' ');
if (method.IsStatic)
builder.Append("static ");
builder.Append("partial ");
builder.Append(method.ReturnType);
builder.Append(' ');
builder.Append(method.MethodName);
builder.Append('(');
for (int i = 0; i < method.Parameters.Count; i++)
{
if (i > 0)
builder.Append(", ");
var parameter = method.Parameters[i];
builder.Append(parameter.Prefix);
builder.Append(parameter.Type);
builder.Append(' ');
builder.Append(parameter.Name);
}
builder.AppendLine(")");
AppendIndent(builder, indent);
builder.AppendLine("{");
AppendIndent(builder, indent + 1);
builder.Append("return Run(");
builder.Append(field);
builder.Append(", ");
builder.Append(method.Invocation.Resources);
builder.Append(", ");
builder.Append(method.Invocation.Constants);
builder.Append(", ");
builder.Append(method.Invocation.Target);
builder.Append(", ");
builder.Append(method.Invocation.Width);
builder.Append(", ");
builder.Append(method.Invocation.Height);
builder.AppendLine(");");
AppendIndent(builder, indent);
builder.AppendLine("}");
}
private static void AppendIndent(StringBuilder builder, int indent)
{
for (int i = 0; i < indent; i++)
builder.Append(" ");
}
private static string EmitErrors(ImmutableArray<string> errors)
{
var builder = new StringBuilder();
foreach (var error in errors)
builder.AppendLine("#error " + error);
return builder.ToString();
}
private static string HintName(GpuShaderClass model)
{
var builder = new StringBuilder("GpuPixelOperationShader");
if (model.Namespace.Length > 0)
{
builder.Append('.');
builder.Append(HintPart(model.Namespace));
}
foreach (var type in model.TypeChain)
{
builder.Append('.');
builder.Append(HintPart(type.Name));
}
builder.Append(".g.cs");
return builder.ToString();
}
private static string ErrorHintName(GpuShaderClass model)
{
return Path.ChangeExtension(HintName(model), ".Errors.g.cs");
}
private static string HintPart(string value)
{
var builder = new StringBuilder(value.Length);
foreach (char c in value)
builder.Append(char.IsLetterOrDigit(c) ? c : '_');
return builder.ToString();
}
private static string Literal(string value)
{
var builder = new StringBuilder(value.Length + 2);
builder.Append('"');
foreach (char c in value)
{
switch (c)
{
case '\\':
builder.Append(@"\\");
break;
case '"':
builder.Append("\\\"");
break;
case '\0':
builder.Append(@"\0");
break;
case '\a':
builder.Append(@"\a");
break;
case '\b':
builder.Append(@"\b");
break;
case '\f':
builder.Append(@"\f");
break;
case '\n':
builder.Append(@"\n");
break;
case '\r':
builder.Append(@"\r");
break;
case '\t':
builder.Append(@"\t");
break;
case '\v':
builder.Append(@"\v");
break;
default:
if (char.IsControl(c))
{
builder.Append(@"\u");
builder.Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
}
else
{
builder.Append(c);
}
break;
}
}
builder.Append('"');
return builder.ToString();
}
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderTypePart(string Name, bool IsStatic);
}
+96
ファイルの表示
@@ -0,0 +1,96 @@
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
namespace LuaScript.Generator
{
internal static class ShaderCompiler
{
private const string Profile = "ps_5_0";
public static string? Compile(string source, string entryPoint, out string bytecode)
{
bytecode = string.Empty;
byte[] data = Encoding.UTF8.GetBytes(source);
IntPtr code = IntPtr.Zero;
IntPtr errors = IntPtr.Zero;
try
{
int hr = D3DCompile(data, (IntPtr)data.Length, null, IntPtr.Zero, IntPtr.Zero, entryPoint, Profile, 0u, 0u, out code, out errors);
if (hr < 0 || code == IntPtr.Zero)
return ReadError(errors, hr);
bytecode = Convert.ToBase64String(ReadBlob(code));
return null;
}
catch (DllNotFoundException)
{
return "the Direct3D shader compiler is unavailable on this build host";
}
catch (EntryPointNotFoundException)
{
return "the Direct3D shader compiler is unavailable on this build host";
}
finally
{
Release(errors);
Release(code);
}
}
private static byte[] ReadBlob(IntPtr blob)
{
IntPtr pointer = Invoke<GetBufferPointerDelegate>(blob, 3)(blob);
int size = checked((int)(long)Invoke<GetBufferSizeDelegate>(blob, 4)(blob));
var buffer = new byte[size];
Marshal.Copy(pointer, buffer, 0, size);
return buffer;
}
private static string ReadError(IntPtr blob, int hr)
{
string fallback = "HRESULT 0x" + hr.ToString("X8", CultureInfo.InvariantCulture);
if (blob == IntPtr.Zero)
return fallback;
IntPtr pointer = Invoke<GetBufferPointerDelegate>(blob, 3)(blob);
int size = checked((int)(long)Invoke<GetBufferSizeDelegate>(blob, 4)(blob));
string message = (Marshal.PtrToStringAnsi(pointer, size) ?? string.Empty).Trim();
return message.Length > 0 ? message : fallback;
}
private static void Release(IntPtr unknown)
{
if (unknown != IntPtr.Zero)
Invoke<ReleaseDelegate>(unknown, 2)(unknown);
}
private static T Invoke<T>(IntPtr instance, int slot) where T : Delegate
{
IntPtr table = Marshal.ReadIntPtr(instance);
IntPtr function = Marshal.ReadIntPtr(table, slot * IntPtr.Size);
return (T)Marshal.GetDelegateForFunctionPointer(function, typeof(T));
}
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate IntPtr GetBufferPointerDelegate(IntPtr self);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate IntPtr GetBufferSizeDelegate(IntPtr self);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseDelegate(IntPtr self);
[DllImport("d3dcompiler_47.dll", CallingConvention = CallingConvention.StdCall)]
private static extern int D3DCompile(
byte[] srcData,
IntPtr srcDataSize,
[MarshalAs(UnmanagedType.LPStr)] string? sourceName,
IntPtr defines,
IntPtr include,
[MarshalAs(UnmanagedType.LPStr)] string entryPoint,
[MarshalAs(UnmanagedType.LPStr)] string target,
uint flags1,
uint flags2,
out IntPtr code,
out IntPtr errorMsgs);
}
}
@@ -5,68 +5,6 @@ using Microsoft.CodeAnalysis.Text;
namespace LuaScript.Generator
{
internal enum LuaParameterKind
{
ExecutionContext,
Arguments,
DynValue,
Double,
Int,
Bool,
}
internal enum LuaReturnKind
{
DynValue,
Double,
Void,
}
internal sealed record LuaParameterModel(string Name, LuaParameterKind Kind, string DefaultLiteral);
internal sealed record LuaFunctionModel(
string LuaName,
string MethodName,
LuaReturnKind ReturnKind,
EquatableArray<LuaParameterModel> Parameters);
internal sealed record LuaConstantModel(string LuaName, string MemberName);
internal enum LuaUpdateKind
{
Direct,
OptionalValue,
OptionalReference,
}
internal enum LuaValueKind
{
Number,
Boolean,
String,
Other,
}
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind, LuaValueKind ValueKind);
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
{
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace LuaScript.Generator
{
internal sealed record LuaCatalogEntry(
string Table,
string Name,
bool IsFunction,
EquatableArray<string> Parameters);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record LuaConstantModel(string LuaName, string MemberName);
}
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace LuaScript.Generator
{
internal sealed record LuaFunctionModel(
string LuaName,
string MethodName,
LuaReturnKind ReturnKind,
EquatableArray<LuaParameterModel> Parameters);
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace LuaScript.Generator
{
internal enum LuaParameterKind
{
ExecutionContext,
Arguments,
DynValue,
Double,
Int,
Bool,
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record LuaParameterModel(string Name, LuaParameterKind Kind, string DefaultLiteral);
}
+9
ファイルの表示
@@ -0,0 +1,9 @@
namespace LuaScript.Generator
{
internal enum LuaReturnKind
{
DynValue,
Double,
Void,
}
}
@@ -8,8 +8,6 @@ using Microsoft.CodeAnalysis.Text;
namespace LuaScript.Generator
{
internal sealed record LuaSyntaxRuleModel(string TypeName, int Order);
[Generator]
public sealed class LuaSyntaxRuleGenerator : IIncrementalGenerator
{
@@ -47,7 +45,17 @@ namespace LuaScript.Generator
if (arguments.Length > 0 && arguments[0].Value is int value)
order = value;
return new LuaSyntaxRuleModel(symbol.ToDisplayString(), order);
bool isCatalog = false;
string keyword = string.Empty;
foreach (var argument in context.Attributes[0].NamedArguments)
{
if (argument.Key == "IsCatalog" && argument.Value.Value is bool catalogValue)
isCatalog = catalogValue;
else if (argument.Key == "Keyword" && argument.Value.Value is string keywordValue)
keyword = keywordValue;
}
return new LuaSyntaxRuleModel(symbol.ToDisplayString(), order, isCatalog ? keyword : string.Empty);
}
private static string Emit(ImmutableArray<LuaSyntaxRuleModel> models)
@@ -68,6 +76,24 @@ namespace LuaScript.Generator
foreach (var model in ordered)
builder.AppendLine($" new global::{model.TypeName}(),");
builder.AppendLine(" };");
var keywords = ordered
.Where(static m => m.CatalogKeyword.Length > 0)
.Select(static m => m.CatalogKeyword)
.Distinct()
.ToArray();
if (keywords.Length == 0)
{
builder.AppendLine(" internal static readonly string[] CatalogKeywords = global::System.Array.Empty<string>();");
}
else
{
builder.AppendLine(" internal static readonly string[] CatalogKeywords = new string[]");
builder.AppendLine(" {");
foreach (var keyword in keywords)
builder.AppendLine($" \"{keyword}\",");
builder.AppendLine(" };");
}
builder.AppendLine(" }");
builder.AppendLine("}");
return builder.ToString();
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record LuaSyntaxRuleModel(string TypeName, int Order, string CatalogKeyword);
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace LuaScript.Generator
{
internal sealed record LuaTableModel(
string Namespace,
EquatableArray<LuaTypePart> TypeChain,
string TableName,
string ContextType,
EquatableArray<LuaFunctionModel> Functions,
EquatableArray<LuaConstantModel> Constants,
EquatableArray<LuaUpdateModel> Updates,
EquatableArray<LuaCatalogEntry> Entries);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record LuaTypePart(string Name, bool IsStatic);
}
+9
ファイルの表示
@@ -0,0 +1,9 @@
namespace LuaScript.Generator
{
internal enum LuaUpdateKind
{
Direct,
OptionalValue,
OptionalReference,
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind, LuaValueKind ValueKind);
}
+10
ファイルの表示
@@ -0,0 +1,10 @@
namespace LuaScript.Generator
{
internal enum LuaValueKind
{
Number,
Boolean,
String,
Other,
}
}
+1 -1
ファイルの表示
@@ -5,7 +5,7 @@
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.19.2</Version>
<Version>1.20.1</Version>
<IsRoslynComponent>true</IsRoslynComponent>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
</PropertyGroup>
+134
ファイルの表示
@@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using LuaScript.Engine.Shader;
namespace LuaScript.Engine.Processing
{
[GpuPixelOperationShader(nameof(RunConvolve), "Shaders/convolve.hlsl", "convolve")]
internal sealed partial class GpuConvolveOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
{
private const int ConvolveWorkThreshold = 262144;
private const int MaxConvolveSize = 31;
private const int MaxConvolveValidationCount = 64;
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
private readonly float[] _constants = new float[1024];
private readonly List<ConvolveValidation> _validations = [];
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
{
if (!IsTextureSupported(target, width, height) || !IsSupported(kernel, size, divisor, offset))
return false;
long work = (long)width * height * size * size;
if (work < ConvolveWorkThreshold || !EnsureValidated(target, width, height, kernel, size, divisor, offset))
return false;
SetConstants(width, height, kernel, size, divisor, offset);
_resources[0] = new PixelShaderInput(target, width, height);
return RunConvolve(_resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), target, width, height);
}
private bool EnsureValidated(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
{
for (int i = 0; i < _validations.Count; i++)
{
if (_validations[i].Matches(kernel, size, divisor, offset))
return _validations[i].Valid;
}
if (_validations.Count >= MaxConvolveValidationCount)
_validations.Clear();
bool valid = Validate(target, width, height, kernel, size, divisor, offset);
_validations.Add(new ConvolveValidation(kernel, size, divisor, offset, valid));
return valid;
}
private bool Validate(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
{
int probeWidth = Math.Min(width, 8);
int probeHeight = Math.Min(height, 7);
var probe = CopyProbe(target, width, height, probeWidth, probeHeight);
var cpu = (byte[])probe.Clone();
var gpu = (byte[])probe.Clone();
double[]? scratch = null;
PixelBufferSoftwareProcessor.Convolve(cpu, probeWidth, probeHeight, kernel, size, divisor, offset, ref scratch);
SetConstants(probeWidth, probeHeight, kernel, size, divisor, offset);
_resources[0] = new PixelShaderInput(gpu, probeWidth, probeHeight);
return RunConvolve(_resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), gpu, probeWidth, probeHeight) && Equal(cpu, gpu);
}
private void SetConstants(int width, int height, double[] kernel, int size, double divisor, double offset)
{
_constants[0] = width;
_constants[1] = height;
_constants[2] = (float)divisor;
_constants[3] = (float)offset;
_constants[4] = size;
_constants[5] = size / 2;
_constants[6] = 0f;
_constants[7] = 0f;
int taps = size * size;
for (int i = 0; i < taps; i++)
_constants[i + 8] = (float)kernel[i];
}
private static bool IsSupported(double[] kernel, int size, double divisor, double offset)
{
if (size < 1 || (size & 1) == 0 || size > MaxConvolveSize || divisor == 0d || !IsFloatCompatible(divisor) || !IsFloatCompatible(offset))
return false;
int taps = size * size;
if (kernel.Length < taps || taps + 8 > 1024)
return false;
for (int i = 0; i < taps; i++)
{
if (!IsFloatCompatible(kernel[i]))
return false;
}
return true;
}
private static bool IsFloatCompatible(double value)
{
return double.IsFinite(value) && float.IsFinite((float)value);
}
private partial bool RunConvolve(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
private sealed class ConvolveValidation
{
private readonly double[] _kernel;
private readonly int _size;
private readonly double _divisor;
private readonly double _offset;
public ConvolveValidation(double[] kernel, int size, double divisor, double offset, bool valid)
{
int taps = size * size;
_kernel = new double[taps];
Array.Copy(kernel, _kernel, taps);
_size = size;
_divisor = divisor;
_offset = offset;
Valid = valid;
}
public bool Valid { get; }
public bool Matches(double[] kernel, int size, double divisor, double offset)
{
if (_size != size || BitConverter.DoubleToInt64Bits(_divisor) != BitConverter.DoubleToInt64Bits(divisor) ||
BitConverter.DoubleToInt64Bits(_offset) != BitConverter.DoubleToInt64Bits(offset))
return false;
int taps = size * size;
for (int i = 0; i < taps; i++)
{
if (BitConverter.DoubleToInt64Bits(_kernel[i]) != BitConverter.DoubleToInt64Bits(kernel[i]))
return false;
}
return true;
}
}
}
}
+124
ファイルの表示
@@ -0,0 +1,124 @@
using System;
using LuaScript.Engine.Shader;
namespace LuaScript.Engine.Processing
{
[GpuPixelOperationShader(nameof(RunFillFull), "Shaders/fill.hlsl", "fill_full")]
[GpuPixelOperationShader(nameof(RunFillPartial), "Shaders/fill.hlsl", "fill_partial")]
internal sealed partial class GpuFillOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
{
private const int FillFullThreshold = 1048576;
private const int FillPartialThreshold = 1048576;
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
private readonly float[] _constants = new float[8];
private bool? _fullValidated;
private bool? _partialValidated;
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
{
if (!IsTextureSupported(target, width, height) || !AreFinite(r, g, b, a))
return false;
long pixels = (long)width * height;
bool full = x == 0 && y == 0 && fillWidth == width && fillHeight == height;
if (full)
{
if (pixels < FillFullThreshold || !EnsureFullValidated())
return false;
SetConstants(r, g, b, a);
return RunFillFull(_constants.AsSpan(0, 4), target, width, height);
}
long area = (long)fillWidth * fillHeight;
if (pixels < FillPartialThreshold || area * 4L < pixels * 3L || !EnsurePartialValidated())
return false;
SetConstants(r, g, b, a);
_constants[4] = x;
_constants[5] = y;
_constants[6] = x + fillWidth;
_constants[7] = y + fillHeight;
_resources[0] = new PixelShaderInput(target, width, height);
return RunFillPartial(_resources.AsSpan(0, 1), _constants.AsSpan(0, 8), target, width, height);
}
private bool EnsureFullValidated()
{
if (_fullValidated.HasValue)
return _fullValidated.Value;
const int width = 7;
const int height = 5;
var source = CreateProbe(width, height);
var cpu = (byte[])source.Clone();
var gpu = (byte[])source.Clone();
PixelBufferSoftwareProcessor.Fill(cpu, width, height, 23d, 197d, 89d, 173d, 0, 0, width, height);
SetConstants(23d, 197d, 89d, 173d);
_fullValidated = RunFillFull(_constants.AsSpan(0, 4), gpu, width, height) && Equal(cpu, gpu);
return _fullValidated.Value;
}
private bool EnsurePartialValidated()
{
if (_partialValidated.HasValue)
return _partialValidated.Value;
const int width = 7;
const int height = 5;
var source = CreateProbe(width, height);
var cpu = (byte[])source.Clone();
var gpu = (byte[])source.Clone();
PixelBufferSoftwareProcessor.Fill(cpu, width, height, 23d, 197d, 89d, 173d, 1, 2, 4, 2);
SetConstants(23d, 197d, 89d, 173d);
_constants[4] = 1f;
_constants[5] = 2f;
_constants[6] = 5f;
_constants[7] = 4f;
_resources[0] = new PixelShaderInput(gpu, width, height);
_partialValidated = RunFillPartial(_resources.AsSpan(0, 1), _constants.AsSpan(0, 8), gpu, width, height) && Equal(cpu, gpu);
return _partialValidated.Value;
}
private void SetConstants(double r, double g, double b, double a)
{
double aK = Math.Clamp(a, 0d, 255d) / 255d;
byte pb = (byte)Math.Clamp(b * aK, 0d, 255d);
byte pg = (byte)Math.Clamp(g * aK, 0d, 255d);
byte pr = (byte)Math.Clamp(r * aK, 0d, 255d);
byte pa = (byte)Math.Clamp(a, 0d, 255d);
_constants[0] = pr / 255f;
_constants[1] = pg / 255f;
_constants[2] = pb / 255f;
_constants[3] = pa / 255f;
}
private static bool AreFinite(double r, double g, double b, double a)
{
return double.IsFinite(r) && double.IsFinite(g) && double.IsFinite(b) && double.IsFinite(a);
}
private static byte[] CreateProbe(int width, int height)
{
var data = new byte[width * height * 4];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int index = (y * width + x) * 4;
byte a = (byte)((x * 31 + y * 47) & 255);
data[index] = a == 0 ? (byte)0 : (byte)((x * 17 + y * 29) % (a + 1));
data[index + 1] = a == 0 ? (byte)0 : (byte)((x * 43 + y * 11) % (a + 1));
data[index + 2] = a == 0 ? (byte)0 : (byte)((x * 7 + y * 53) % (a + 1));
data[index + 3] = a;
}
}
return data;
}
private partial bool RunFillFull(ReadOnlySpan<float> constants, byte[] target, int width, int height);
private partial bool RunFillPartial(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
}
}
+30
ファイルの表示
@@ -0,0 +1,30 @@
using LuaScript.Engine.Shader;
namespace LuaScript.Engine.Processing
{
internal sealed class GpuPixelBufferProcessor(PixelShaderRunner runner) : IPixelBufferProcessor
{
private readonly object _gate = new();
private readonly GpuFillOperation _fill = new(runner);
private readonly GpuConvolveOperation _convolve = new(runner);
private readonly GpuResizeOperation _resize = new(runner);
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
{
lock (_gate)
return _fill.TryFill(target, width, height, r, g, b, a, x, y, fillWidth, fillHeight);
}
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
{
lock (_gate)
return _convolve.TryConvolve(target, width, height, kernel, size, divisor, offset);
}
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
{
lock (_gate)
return _resize.TryResize(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target);
}
}
}
+47
ファイルの表示
@@ -0,0 +1,47 @@
using System;
using LuaScript.Engine.Shader;
namespace LuaScript.Engine.Processing
{
internal abstract class GpuPixelOperation(PixelShaderRunner runner)
{
protected const int MaxTextureSize = 16384;
protected bool Run(byte[] bytecode, ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height)
{
return runner.TryRunHardware(
bytecode,
resources,
constants,
PixelShaderBlend.Copy,
PixelShaderSampler.None,
target,
width,
height,
out _) == PixelShaderRunStatus.Success;
}
protected static bool IsTextureSupported(byte[] buffer, int width, int height)
{
return IsTextureSizeSupported(width, height) && (long)buffer.Length >= (long)width * height * 4;
}
protected static bool IsTextureSizeSupported(int width, int height)
{
return width > 0 && height > 0 && width <= MaxTextureSize && height <= MaxTextureSize;
}
protected static bool Equal(byte[] expected, byte[] actual)
{
return expected.AsSpan().SequenceEqual(actual);
}
protected static byte[] CopyProbe(byte[] source, int width, int height, int probeWidth, int probeHeight)
{
var data = new byte[probeWidth * probeHeight * 4];
for (int y = 0; y < probeHeight; y++)
Buffer.BlockCopy(source, y * width * 4, data, y * probeWidth * 4, probeWidth * 4);
return data;
}
}
}
+14
ファイルの表示
@@ -0,0 +1,14 @@
using System;
namespace LuaScript.Engine.Processing
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
internal sealed class GpuPixelOperationShaderAttribute(string methodName, string fileName, string entryPoint) : Attribute
{
public string MethodName { get; } = methodName;
public string FileName { get; } = fileName;
public string EntryPoint { get; } = entryPoint;
}
}
+82
ファイルの表示
@@ -0,0 +1,82 @@
using System;
using LuaScript.Engine.Shader;
namespace LuaScript.Engine.Processing
{
[GpuPixelOperationShader(nameof(RunResizeNearest), "Shaders/resize.hlsl", "resize_nearest")]
[GpuPixelOperationShader(nameof(RunResizeLinear), "Shaders/resize.hlsl", "resize_linear")]
internal sealed partial class GpuResizeOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
{
private const int ResizeThreshold = 262144;
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
private readonly float[] _constants = new float[4];
private byte[] _target = [];
private bool? _nearestValidated;
private bool? _linearValidated;
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
{
target = null;
if (!IsTextureSupported(source, sourceWidth, sourceHeight) || !IsTextureSizeSupported(targetWidth, targetHeight))
return false;
long pixels = (long)targetWidth * targetHeight;
if (pixels < ResizeThreshold || !(linear ? EnsureLinearValidated(source, sourceWidth, sourceHeight) : EnsureNearestValidated(source, sourceWidth, sourceHeight)))
return false;
return RunShader(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target);
}
private bool EnsureNearestValidated(byte[] source, int sourceWidth, int sourceHeight)
{
if (_nearestValidated.HasValue)
return _nearestValidated.Value;
_nearestValidated = Validate(source, sourceWidth, sourceHeight, false);
return _nearestValidated.Value;
}
private bool EnsureLinearValidated(byte[] source, int sourceWidth, int sourceHeight)
{
if (_linearValidated.HasValue)
return _linearValidated.Value;
_linearValidated = Validate(source, sourceWidth, sourceHeight, true);
return _linearValidated.Value;
}
private bool Validate(byte[] source, int sourceWidth, int sourceHeight, bool linear)
{
int probeWidth = Math.Min(sourceWidth, 8);
int probeHeight = Math.Min(sourceHeight, 7);
int targetWidth = Math.Max(1, probeWidth * 2 - 3);
int targetHeight = Math.Max(1, probeHeight * 2 - 5);
var probe = CopyProbe(source, sourceWidth, sourceHeight, probeWidth, probeHeight);
byte[]? sourceScratch = null;
byte[]? targetScratch = null;
var cpu = PixelBufferSoftwareProcessor.Resize(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, ref sourceScratch, ref targetScratch);
return RunShader(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, out var gpu) && gpu is not null && Equal(cpu, gpu);
}
private bool RunShader(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
{
int count = checked(targetWidth * targetHeight * 4);
if (_target.Length != count)
_target = new byte[count];
_constants[0] = sourceWidth;
_constants[1] = sourceHeight;
_constants[2] = targetWidth;
_constants[3] = targetHeight;
_resources[0] = new PixelShaderInput(source, sourceWidth, sourceHeight);
target = _target;
return linear
? RunResizeLinear(_resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _target, targetWidth, targetHeight)
: RunResizeNearest(_resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _target, targetWidth, targetHeight);
}
private partial bool RunResizeNearest(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
private partial bool RunResizeLinear(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
}
}
+50
ファイルの表示
@@ -0,0 +1,50 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.20.1</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="LuaScript" />
<InternalsVisibleTo Include="LuaScript.Tests" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LuaScript.Runtime\LuaScript.Runtime.csproj" />
<ProjectReference Include="..\LuaScript.Generator\LuaScript.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<AdditionalFiles Include="Shaders\*.hlsl" />
</ItemGroup>
<ItemGroup>
<Reference Include="SharpGen.Runtime">
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.Direct3D11">
<HintPath>$(YMM4DirPath)Vortice.Direct3D11.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.DirectX">
<HintPath>$(YMM4DirPath)Vortice.DirectX.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.D3DCompiler.dll">
<HintPath>$(YMM4DirPath)Vortice.D3DCompiler.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.DXGI.dll">
<HintPath>$(YMM4DirPath)Vortice.DXGI.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.Mathematics">
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
<Private>false</Private>
</Reference>
</ItemGroup>
</Project>
+106 -10
ファイルの表示
@@ -7,7 +7,6 @@ using Vortice.Direct3D;
using Vortice.Direct3D11;
using Vortice.DXGI;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
namespace LuaScript.Engine.Shader
{
@@ -43,6 +42,7 @@ namespace LuaScript.Engine.Shader
private readonly Lock _locker = new();
private readonly Dictionary<(string Hlsl, string Entry), CompiledShader> _shaders = [];
private readonly Dictionary<byte[], ID3D11PixelShader> _precompiled = new(ReferenceEqualityComparer.Instance);
private readonly InputSlot[] _inputs = new InputSlot[MaxResources];
private readonly ID3D11ShaderResourceView[] _boundViews = new ID3D11ShaderResourceView[MaxResources];
private readonly ID3D11ShaderResourceView[] _nullViews = new ID3D11ShaderResourceView[MaxResources];
@@ -51,8 +51,11 @@ namespace LuaScript.Engine.Shader
public IBufferCompositor Compositor { get; set; } = SoftwareCompositor.Instance;
public Action<string, Exception?>? Logger { get; set; }
private ID3D11Device? _device;
private ID3D11DeviceContext? _context;
private DriverType _driverType;
private ID3D11VertexShader? _vertexShader;
private ID3D11Buffer? _constantBuffer;
private ID3D11RasterizerState? _rasterizer;
@@ -70,6 +73,7 @@ namespace LuaScript.Engine.Shader
private bool _disposed;
private bool _unavailable;
private bool _hardwareUnavailable;
private bool _failureLogged;
private int _recreateBudget = 3;
@@ -88,9 +92,7 @@ namespace LuaScript.Engine.Shader
error = null;
lock (_locker)
{
if (_disposed || _unavailable)
return PixelShaderRunStatus.Unavailable;
if (targetWidth <= 0 || targetHeight <= 0 || (long)target.Length < (long)targetWidth * targetHeight * 4)
if (!CanRun(target, targetWidth, targetHeight))
return PixelShaderRunStatus.Unavailable;
try
@@ -116,6 +118,46 @@ namespace LuaScript.Engine.Shader
}
}
public PixelShaderRunStatus TryRunHardware(
byte[] bytecode,
ReadOnlySpan<PixelShaderInput> resources,
ReadOnlySpan<float> constants,
PixelShaderBlend blend,
PixelShaderSampler sampler,
byte[] target,
int targetWidth,
int targetHeight,
out string? error)
{
error = null;
lock (_locker)
{
if (!CanRun(target, targetWidth, targetHeight))
return PixelShaderRunStatus.Unavailable;
try
{
if (!EnsureHardwareDevice())
return PixelShaderRunStatus.Unavailable;
Execute(GetOrCreate(bytecode), resources, constants, blend, sampler, target, targetWidth, targetHeight);
return PixelShaderRunStatus.Success;
}
catch (Exception ex)
{
HandleFailure(ex);
return PixelShaderRunStatus.Unavailable;
}
}
}
private bool CanRun(byte[] target, int targetWidth, int targetHeight)
{
return !_disposed && !_unavailable &&
targetWidth > 0 && targetHeight > 0 &&
(long)target.Length >= (long)targetWidth * targetHeight * 4;
}
public void Invalidate()
{
lock (_locker)
@@ -146,19 +188,55 @@ namespace LuaScript.Engine.Shader
}
_recreateBudget--;
if (!TryCreateDevice(DriverType.Hardware, out var device, out var context) &&
!TryCreateDevice(DriverType.Warp, out device, out context))
DriverType driverType;
if (TryCreateDevice(DriverType.Hardware, out var device, out var context))
{
driverType = DriverType.Hardware;
}
else if (TryCreateDevice(DriverType.Warp, out device, out context))
{
driverType = DriverType.Warp;
}
else
{
MarkUnavailable(null);
return false;
}
return InitializeDevice(device, context, driverType, true);
}
private bool EnsureHardwareDevice()
{
if (_device is not null)
return _driverType == DriverType.Hardware;
if (_hardwareUnavailable)
return false;
if (_recreateBudget <= 0)
{
_hardwareUnavailable = true;
return false;
}
_recreateBudget--;
if (!TryCreateDevice(DriverType.Hardware, out var device, out var context))
{
_hardwareUnavailable = true;
return false;
}
return InitializeDevice(device, context, DriverType.Hardware, false);
}
private bool InitializeDevice(ID3D11Device? device, ID3D11DeviceContext? context, DriverType driverType, bool markUnavailable)
{
try
{
var vsBytecode = CompileOrThrow(VertexShaderSource, "vsmain", "vs_4_0");
var vertexShader = device!.CreateVertexShader(vsBytecode);
_device = device;
_context = context;
_driverType = driverType;
_hardwareUnavailable = driverType != DriverType.Hardware && _hardwareUnavailable;
_vertexShader = vertexShader;
_constantBuffer = device.CreateBuffer(new BufferDescription(
ConstantBufferSize, BindFlags.ConstantBuffer, ResourceUsage.Dynamic, CpuAccessFlags.Write));
@@ -178,7 +256,10 @@ namespace LuaScript.Engine.Shader
context?.Dispose();
device?.Dispose();
}
MarkUnavailable(ex);
if (markUnavailable)
MarkUnavailable(ex);
else
_hardwareUnavailable = true;
return false;
}
}
@@ -267,6 +348,16 @@ namespace LuaScript.Engine.Shader
return compiled;
}
private ID3D11PixelShader GetOrCreate(byte[] bytecode)
{
if (_precompiled.TryGetValue(bytecode, out var cached))
return cached;
var shader = _device!.CreatePixelShader(bytecode);
_precompiled[bytecode] = shader;
return shader;
}
private static byte[] CompileOrThrow(string source, string entryPoint, string profile)
{
var result = Compiler.Compile(Encoding.UTF8.GetBytes(source), entryPoint, string.Empty, profile, out var bytecode, out var errors);
@@ -503,7 +594,7 @@ namespace LuaScript.Engine.Shader
if (!_failureLogged)
{
_failureLogged = true;
Log.Default.Write("LuaScript: obj.pixelshader execution failed; the call is skipped.", ex);
WriteLog("LuaScript: obj.pixelshader execution failed; the call is skipped.", ex);
}
ReleaseDeviceObjects();
if (_recreateBudget <= 0)
@@ -517,16 +608,21 @@ namespace LuaScript.Engine.Shader
return;
_failureLogged = true;
if (ex is null)
Log.Default.Write("LuaScript: Direct3D 11 is unavailable; obj.pixelshader is disabled.");
WriteLog("LuaScript: Direct3D 11 is unavailable; obj.pixelshader is disabled.", null);
else
Log.Default.Write("LuaScript: Direct3D 11 initialization failed; obj.pixelshader is disabled.", ex);
WriteLog("LuaScript: Direct3D 11 initialization failed; obj.pixelshader is disabled.", ex);
}
private void WriteLog(string message, Exception? exception) => Logger?.Invoke(message, exception);
private void ReleaseShaders()
{
foreach (var compiled in _shaders.Values)
compiled.Shader?.Dispose();
_shaders.Clear();
foreach (var shader in _precompiled.Values)
shader.Dispose();
_precompiled.Clear();
}
private void ReleaseDeviceObjects()
+58
ファイルの表示
@@ -0,0 +1,58 @@
Texture2D source : register(t0);
cbuffer Parameters : register(b0)
{
float4 values[256];
};
float get_value(uint index)
{
uint row = index >> 2;
uint column = index & 3u;
float4 value = values[row];
if (column == 0u)
return value.x;
if (column == 1u)
return value.y;
if (column == 2u)
return value.z;
return value.w;
}
float convolve_channel(float value)
{
return floor(saturate(value) * 255.0) / 255.0;
}
float4 convolve(float4 pos : SV_Position) : SV_Target
{
uint2 p = (uint2)floor(pos.xy);
int width = (int)get_value(0u);
int height = (int)get_value(1u);
float divisor = get_value(2u);
float offset = get_value(3u) / 255.0;
int kernelSize = (int)get_value(4u);
int radius = (int)get_value(5u);
float4 sum = 0.0;
for (int ky = 0; ky < kernelSize; ky++)
{
int sy = clamp((int)p.y + ky - radius, 0, height - 1);
for (int kx = 0; kx < kernelSize; kx++)
{
int sx = clamp((int)p.x + kx - radius, 0, width - 1);
float kv = get_value((uint)(8 + ky * kernelSize + kx));
float4 sourceValue = source[uint2((uint)sx, (uint)sy)];
float3 rgb = sourceValue.a <= 0.0 ? 0.0 : saturate(sourceValue.rgb / sourceValue.a);
sum += float4(rgb, sourceValue.a) * kv;
}
}
float3 rgbOut = saturate(sum.rgb / divisor + offset);
float alpha = saturate(sum.a / divisor + offset);
return float4(
convolve_channel(rgbOut.r * alpha),
convolve_channel(rgbOut.g * alpha),
convolve_channel(rgbOut.b * alpha),
convolve_channel(alpha));
}
+21
ファイルの表示
@@ -0,0 +1,21 @@
Texture2D source : register(t0);
cbuffer Parameters : register(b0)
{
float4 color;
float4 rect;
};
float4 fill_full(float4 pos : SV_Position) : SV_Target
{
return color;
}
float4 fill_partial(float4 pos : SV_Position) : SV_Target
{
uint2 p = (uint2)floor(pos.xy);
uint4 r = (uint4)rect;
if (p.x >= r.x && p.y >= r.y && p.x < r.z && p.y < r.w)
return color;
return source[p];
}
+56
ファイルの表示
@@ -0,0 +1,56 @@
Texture2D source : register(t0);
cbuffer Parameters : register(b0)
{
float4 size;
};
float channel(float value)
{
return floor(saturate(value) * 255.0) / 255.0;
}
float4 resize_pack(float4 value)
{
return float4(channel(value.r), channel(value.g), channel(value.b), channel(value.a));
}
float4 resize_nearest(float4 pos : SV_Position) : SV_Target
{
uint2 p = (uint2)floor(pos.xy);
uint sourceWidth = (uint)size.x;
uint sourceHeight = (uint)size.y;
uint targetWidth = (uint)size.z;
uint targetHeight = (uint)size.w;
uint sx = min(((p.x * 2u + 1u) * sourceWidth) / (targetWidth * 2u), sourceWidth - 1u);
uint sy = min(((p.y * 2u + 1u) * sourceHeight) / (targetHeight * 2u), sourceHeight - 1u);
return source[uint2(sx, sy)];
}
float4 resize_linear(float4 pos : SV_Position) : SV_Target
{
uint2 p = (uint2)floor(pos.xy);
float sourceWidth = size.x;
float sourceHeight = size.y;
float targetWidth = size.z;
float targetHeight = size.w;
float u = (p.x + 0.5) * sourceWidth / targetWidth - 0.5;
float v = (p.y + 0.5) * sourceHeight / targetHeight - 0.5;
int x0 = (int)floor(u);
int y0 = (int)floor(v);
float tx = u - x0;
float ty = v - y0;
int maxX = (int)sourceWidth - 1;
int maxY = (int)sourceHeight - 1;
uint xA = (uint)clamp(x0, 0, maxX);
uint yA = (uint)clamp(y0, 0, maxY);
uint xB = (uint)clamp(x0 + 1, 0, maxX);
uint yB = (uint)clamp(y0 + 1, 0, maxY);
float4 c00 = source[uint2(xA, yA)];
float4 c10 = source[uint2(xB, yA)];
float4 c01 = source[uint2(xA, yB)];
float4 c11 = source[uint2(xB, yB)];
float4 top = c00 * (1.0 - tx) + c10 * tx;
float4 bottom = c01 * (1.0 - tx) + c11 * tx;
return resize_pack(top * (1.0 - ty) + bottom * ty);
}
+1 -1
ファイルの表示
@@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.19.2</Version>
<Version>1.20.1</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
</PropertyGroup>
+1 -1
ファイルの表示
@@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.19.2</Version>
<Version>1.20.1</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+1
ファイルの表示
@@ -60,6 +60,7 @@ namespace LuaScript.Api
}
var candidates = Keywords
.Concat(LuaScript.Compat.Syntax.LuaSyntaxRuleRegistry.CatalogKeywords)
.Concat(globals)
.Concat(tableMembers.Keys)
.Concat(tableMembers.Values.SelectMany(x => x))
+16 -137
ファイルの表示
@@ -169,6 +169,8 @@ namespace LuaScript
internal IPixelShaderRunner? ShaderRunner { get; set; }
internal IPixelBufferProcessor? PixelProcessor { get; set; }
internal AviUtlPixelShaderLibrary PixelShaders { get; set; } = AviUtlPixelShaderLibrary.Empty;
internal bool TryGetShaderResource(string id, out byte[] data, out int width, out int height) =>
@@ -524,28 +526,14 @@ namespace LuaScript
if (x1 <= x0 || y1 <= y0)
return;
_isPixelsDirty = true;
double aK = Math.Clamp(a, 0d, 255d) / 255d;
byte pb = (byte)Math.Clamp(b * aK, 0d, 255d);
byte pg = (byte)Math.Clamp(g * aK, 0d, 255d);
byte pr = (byte)Math.Clamp(r * aK, 0d, 255d);
byte pa = (byte)Math.Clamp(a, 0d, 255d);
fixed (byte* buf = _pixelBuffer)
if (PixelProcessor?.TryFill(_pixelBuffer, cw, ch, r, g, b, a, x0, y0, x1 - x0, y1 - y0) == true)
{
for (int py = y0; py < y1; py++)
{
byte* p = buf + (py * cw + x0) * 4;
for (int px = x0; px < x1; px++)
{
p[0] = pb;
p[1] = pg;
p[2] = pr;
p[3] = pa;
p += 4;
}
}
_isPixelsDirty = true;
return;
}
_isPixelsDirty = true;
PixelBufferSoftwareProcessor.Fill(_pixelBuffer, cw, ch, r, g, b, a, x0, y0, x1 - x0, y1 - y0);
}
public unsafe void ReadRegion(int x, int y, int w, int h, double[] destination)
@@ -641,72 +629,14 @@ namespace LuaScript
int cw = ImageWidth;
int ch = ImageHeight;
int count = cw * ch * 4;
if (_convolveSource is null || _convolveSource.Length < count)
_convolveSource = new double[count];
var src = _convolveSource;
fixed (byte* buf = _pixelBuffer)
if (PixelProcessor?.TryConvolve(_pixelBuffer, cw, ch, kernel, size, divisor, offset) == true)
{
for (int pi = 0; pi < cw * ch; pi++)
{
byte* p = buf + pi * 4;
int di = pi * 4;
double a = p[3];
src[di + 3] = a;
if (a <= 0d)
{
src[di] = 0d;
src[di + 1] = 0d;
src[di + 2] = 0d;
}
else
{
double s = 255d / a;
src[di] = Math.Clamp(p[2] * s, 0d, 255d);
src[di + 1] = Math.Clamp(p[1] * s, 0d, 255d);
src[di + 2] = Math.Clamp(p[0] * s, 0d, 255d);
}
}
_isPixelsDirty = true;
return;
}
int half = size / 2;
_isPixelsDirty = true;
fixed (byte* buf = _pixelBuffer)
{
for (int y = 0; y < ch; y++)
{
for (int x = 0; x < cw; x++)
{
double sr = 0d, sg = 0d, sb = 0d, sa = 0d;
for (int ky = 0; ky < size; ky++)
{
int sy = Math.Clamp(y + ky - half, 0, ch - 1);
for (int kx = 0; kx < size; kx++)
{
int sx = Math.Clamp(x + kx - half, 0, cw - 1);
double kv = kernel[ky * size + kx];
int si = (sy * cw + sx) * 4;
sr += src[si] * kv;
sg += src[si + 1] * kv;
sb += src[si + 2] * kv;
sa += src[si + 3] * kv;
}
}
double rr = Math.Clamp(sr / divisor + offset, 0d, 255d);
double gg = Math.Clamp(sg / divisor + offset, 0d, 255d);
double bb = Math.Clamp(sb / divisor + offset, 0d, 255d);
double aa = Math.Clamp(sa / divisor + offset, 0d, 255d);
double aK = aa / 255d;
byte* p = buf + (y * cw + x) * 4;
p[0] = (byte)Math.Clamp(bb * aK, 0d, 255d);
p[1] = (byte)Math.Clamp(gg * aK, 0d, 255d);
p[2] = (byte)Math.Clamp(rr * aK, 0d, 255d);
p[3] = (byte)aa;
}
}
}
PixelBufferSoftwareProcessor.Convolve(_pixelBuffer, cw, ch, kernel, size, divisor, offset, ref _convolveSource);
}
public unsafe void Resize(int newWidth, int newHeight, bool linear)
@@ -720,64 +650,13 @@ namespace LuaScript
int cw = ImageWidth;
int ch = ImageHeight;
int srcCount = cw * ch * 4;
if (_resizeSource is null || _resizeSource.Length < srcCount)
_resizeSource = new byte[srcCount];
Buffer.BlockCopy(_pixelBuffer, 0, _resizeSource, 0, srcCount);
int dstCount = newWidth * newHeight * 4;
if (_resizeBuffer is null || _resizeBuffer.Length != dstCount)
_resizeBuffer = new byte[dstCount];
var src = _resizeSource;
var dst = _resizeBuffer;
fixed (byte* s = src)
fixed (byte* d = dst)
if (PixelProcessor?.TryResize(_pixelBuffer, cw, ch, newWidth, newHeight, linear, out var processed) == true && processed is not null)
{
for (int y = 0; y < newHeight; y++)
{
for (int x = 0; x < newWidth; x++)
{
byte* o = d + (y * newWidth + x) * 4;
if (!linear)
{
int sx = Math.Clamp((int)((x + 0.5) * cw / newWidth), 0, cw - 1);
int sy = Math.Clamp((int)((y + 0.5) * ch / newHeight), 0, ch - 1);
byte* p = s + (sy * cw + sx) * 4;
o[0] = p[0];
o[1] = p[1];
o[2] = p[2];
o[3] = p[3];
}
else
{
double u = (x + 0.5) * cw / newWidth - 0.5;
double v = (y + 0.5) * ch / newHeight - 0.5;
int x0 = (int)Math.Floor(u);
int y0 = (int)Math.Floor(v);
double tx = u - x0;
double ty = v - y0;
for (int c = 0; c < 4; c++)
{
double acc = 0d;
for (int j = 0; j < 2; j++)
{
int sy = Math.Clamp(y0 + j, 0, ch - 1);
double wy = j == 0 ? 1d - ty : ty;
for (int i = 0; i < 2; i++)
{
int sx = Math.Clamp(x0 + i, 0, cw - 1);
double wx = i == 0 ? 1d - tx : tx;
acc += s[(sy * cw + sx) * 4 + c] * wy * wx;
}
}
o[c] = (byte)Math.Clamp(acc, 0d, 255d);
}
}
}
}
ReplaceBuffer(processed, newWidth, newHeight);
return;
}
var dst = PixelBufferSoftwareProcessor.Resize(_pixelBuffer, cw, ch, newWidth, newHeight, linear, ref _resizeSource, ref _resizeBuffer);
ReplaceBuffer(dst, newWidth, newHeight);
}
}
+11
ファイルの表示
@@ -0,0 +1,11 @@
namespace LuaScript
{
internal interface IPixelBufferProcessor
{
bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight);
bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset);
bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target);
}
}
+102 -3
ファイルの表示
@@ -44,6 +44,8 @@ namespace LuaScript.Engine
private readonly byte[]?[] _shaderResourceData = new byte[NativeProtocol.ShaderResourcesMax][];
private readonly float[] _shaderConstants = new float[NativeProtocol.ShaderConstantsMax];
private byte[] _shaderTarget = [];
private byte[] _pixelProcessTarget = [];
private double[] _pixelProcessKernel = [];
private long PixelRegionCapacity => _allocatedSize - _pixelOffset - NativeProtocol.ShaderRegionBytes;
@@ -81,6 +83,7 @@ namespace LuaScript.Engine
Action<string, SceneValue> sceneSetValue,
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio,
PixelShaderInvoke? runPixelShader,
IPixelBufferProcessor? pixelProcessor,
out bool pixelsDirty,
out bool bufferReplaced,
out int resultWidth,
@@ -124,16 +127,18 @@ namespace LuaScript.Engine
view.Write(NativeProtocol.OffScriptVersion, _scriptVersion);
view.Write(NativeProtocol.OffPixelsDirty, 0);
view.Write(NativeProtocol.OffErrorLen, 0);
view.Write(NativeProtocol.OffCallbackFound, pixelProcessor is null ? -1 : 1);
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdRun);
_workEvent!.Set();
var stopwatch = Stopwatch.StartNew();
long budget = timeoutMs;
int status;
while (true)
{
long remaining = timeoutMs - stopwatch.ElapsedMilliseconds;
long remaining = budget - stopwatch.ElapsedMilliseconds;
if (remaining <= 0 || !_doneEvent!.WaitOne((int)remaining))
{
KillWorker();
@@ -145,6 +150,7 @@ namespace LuaScript.Engine
if (status != NativeProtocol.StatusCallback)
break;
long callbackStart = stopwatch.ElapsedMilliseconds;
int callbackKind = view.ReadInt32(NativeProtocol.OffCallbackKind);
if (callbackKind == NativeProtocol.CbKindRequestPixels)
{
@@ -164,8 +170,9 @@ namespace LuaScript.Engine
}
else
{
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, loadScene, loadBrush, addEffect, setAnchor, sceneGetValue, sceneSetValue, loadAudio, runPixelShader);
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, loadScene, loadBrush, addEffect, setAnchor, sceneGetValue, sceneSetValue, loadAudio, runPixelShader, pixelProcessor);
}
budget += stopwatch.ElapsedMilliseconds - callbackStart;
_workEvent.Set();
}
@@ -332,7 +339,8 @@ namespace LuaScript.Engine
Func<string, SceneValue> sceneGetValue,
Action<string, SceneValue> sceneSetValue,
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio,
PixelShaderInvoke? runPixelShader)
PixelShaderInvoke? runPixelShader,
IPixelBufferProcessor? pixelProcessor)
{
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
switch (kind)
@@ -382,9 +390,100 @@ namespace LuaScript.Engine
case NativeProtocol.CbKindPixelShaderRun:
ResolveShaderRunCallback(view, runPixelShader);
break;
case NativeProtocol.CbKindPixelProcess:
ResolvePixelProcessCallback(view, pixelProcessor);
break;
}
}
private void ResolvePixelProcessCallback(MemoryMappedViewAccessor view, IPixelBufferProcessor? pixelProcessor)
{
bool processed = false;
if (pixelProcessor is not null)
{
int width = view.ReadInt32(NativeProtocol.OffWidth);
int height = view.ReadInt32(NativeProtocol.OffHeight);
long length = (long)width * height * 4;
if (width > 0 && height > 0 && length <= PixelRegionCapacity && length <= int.MaxValue)
{
int pixelLength = (int)length;
if (_pixelProcessTarget.Length < pixelLength)
_pixelProcessTarget = new byte[pixelLength];
int operation = (int)view.ReadDouble(NativeProtocol.CallbackResultOffset);
processed = operation switch
{
NativeProtocol.PixelProcessFill => TryProcessFill(view, pixelProcessor, width, height, pixelLength),
NativeProtocol.PixelProcessConvolve => TryProcessConvolve(view, pixelProcessor, width, height, pixelLength),
NativeProtocol.PixelProcessResize => TryProcessResize(view, pixelProcessor, pixelLength),
_ => false,
};
}
}
view.Write(NativeProtocol.OffCallbackFound, processed ? 1 : pixelProcessor is null ? -1 : 0);
}
private bool TryProcessFill(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int width, int height, int pixelLength)
{
long offset = NativeProtocol.CallbackResultOffset;
double r = view.ReadDouble(offset + 1 * 8);
double g = view.ReadDouble(offset + 2 * 8);
double b = view.ReadDouble(offset + 3 * 8);
double a = view.ReadDouble(offset + 4 * 8);
int x = (int)view.ReadDouble(offset + 5 * 8);
int y = (int)view.ReadDouble(offset + 6 * 8);
int fillWidth = (int)view.ReadDouble(offset + 7 * 8);
int fillHeight = (int)view.ReadDouble(offset + 8 * 8);
if (x != 0 || y != 0 || fillWidth != width || fillHeight != height)
ReadRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
if (!pixelProcessor.TryFill(_pixelProcessTarget, width, height, r, g, b, a, x, y, fillWidth, fillHeight))
return false;
WriteRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
return true;
}
private bool TryProcessConvolve(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int width, int height, int pixelLength)
{
long offset = NativeProtocol.CallbackResultOffset;
int size = (int)view.ReadDouble(offset + 1 * 8);
double divisor = view.ReadDouble(offset + 2 * 8);
double kernelOffset = view.ReadDouble(offset + 3 * 8);
if (size < 1 || (size & 1) == 0)
return false;
int taps = size * size;
if (taps <= 0 || taps * 8 > Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax))
return false;
if (_pixelProcessKernel.Length < taps)
_pixelProcessKernel = new double[taps];
ReadRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
view.ReadArray(NativeProtocol.CallbackTagOffset, _pixelProcessKernel, 0, taps);
if (!pixelProcessor.TryConvolve(_pixelProcessTarget, width, height, _pixelProcessKernel, size, divisor, kernelOffset))
return false;
WriteRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
return true;
}
private bool TryProcessResize(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int sourceLength)
{
long offset = NativeProtocol.CallbackResultOffset;
int targetWidth = (int)view.ReadDouble(offset + 1 * 8);
int targetHeight = (int)view.ReadDouble(offset + 2 * 8);
bool linear = view.ReadDouble(offset + 3 * 8) != 0d;
long length = (long)targetWidth * targetHeight * 4;
int sourceWidth = view.ReadInt32(NativeProtocol.OffWidth);
int sourceHeight = view.ReadInt32(NativeProtocol.OffHeight);
if (targetWidth <= 0 || targetHeight <= 0 || length > PixelRegionCapacity || length > int.MaxValue)
return false;
ReadRegion(_pixelOffset, _pixelProcessTarget, sourceLength);
if (!pixelProcessor.TryResize(_pixelProcessTarget, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out var target) || target is null)
return false;
WriteRegion(_pixelOffset, target, (int)length);
view.Write(NativeProtocol.OffWidth, targetWidth);
view.Write(NativeProtocol.OffHeight, targetHeight);
return true;
}
private void ResolveShaderStageCallback(MemoryMappedViewAccessor view)
{
long meta = NativeProtocol.ShaderMetaOffset(_allocatedSize);
+17 -3
ファイルの表示
@@ -181,9 +181,17 @@ namespace LuaScript
script.AttachDebugger(_debugger);
_globalRegistrar = new AviUtlGlobalRegistrar(CurrentTimeRatio);
_globalRegistrar.RegisterLuaMembers(script.Globals);
RegisterFastPrimitives(script);
_script = script;
}
private void RegisterFastPrimitives(Script script)
{
script.Globals.Set("__fast_fill", DynValue.NewCallback((_, args) => FillCore(args)));
script.Globals.Set("__fast_convolve", DynValue.NewCallback((_, args) => ConvolveCore(args)));
script.Globals.Set("__fast_resize", DynValue.NewCallback((_, args) => ResizeCore(args)));
}
private void EnsureScriptIntegrity()
{
if (_script is null) return;
@@ -1007,7 +1015,9 @@ namespace LuaScript
}
[LuaFunction("fill")]
private DynValue Fill(CallbackArguments args)
private DynValue Fill(CallbackArguments args) => FillCore(args);
private DynValue FillCore(CallbackArguments args)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null)
@@ -1076,7 +1086,9 @@ namespace LuaScript
}
[LuaFunction("convolve")]
private DynValue Convolve(CallbackArguments args)
private DynValue Convolve(CallbackArguments args) => ConvolveCore(args);
private DynValue ConvolveCore(CallbackArguments args)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 2 || args[0].Type != DataType.Table)
@@ -1108,7 +1120,9 @@ namespace LuaScript
}
[LuaFunction("resize")]
private DynValue Resize(CallbackArguments args)
private DynValue Resize(CallbackArguments args) => ResizeCore(args);
private DynValue ResizeCore(CallbackArguments args)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 2)
+5
ファイルの表示
@@ -67,6 +67,11 @@ namespace LuaScript.Engine
public const int CbKindLoadBrush = 16;
public const int CbKindBrush = 17;
public const int CbKindGetAudio = 18;
public const int CbKindPixelProcess = 19;
public const int PixelProcessFill = 0;
public const int PixelProcessConvolve = 1;
public const int PixelProcessResize = 2;
public const int DrawRingCapacity = 4096;
public const int DrawEntryDoubles = 24;
+166
ファイルの表示
@@ -0,0 +1,166 @@
using System;
namespace LuaScript
{
internal static unsafe class PixelBufferSoftwareProcessor
{
public static void Fill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
{
double aK = Math.Clamp(a, 0d, 255d) / 255d;
byte pb = (byte)Math.Clamp(b * aK, 0d, 255d);
byte pg = (byte)Math.Clamp(g * aK, 0d, 255d);
byte pr = (byte)Math.Clamp(r * aK, 0d, 255d);
byte pa = (byte)Math.Clamp(a, 0d, 255d);
int x1 = x + fillWidth;
int y1 = y + fillHeight;
fixed (byte* buf = target)
{
for (int py = y; py < y1; py++)
{
byte* p = buf + (py * width + x) * 4;
for (int px = x; px < x1; px++)
{
p[0] = pb;
p[1] = pg;
p[2] = pr;
p[3] = pa;
p += 4;
}
}
}
}
public static void Convolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, ref double[]? sourceScratch)
{
int count = width * height * 4;
if (sourceScratch is null || sourceScratch.Length < count)
sourceScratch = new double[count];
var src = sourceScratch;
fixed (byte* buf = target)
{
for (int pi = 0; pi < width * height; pi++)
{
byte* p = buf + pi * 4;
int di = pi * 4;
double a = p[3];
src[di + 3] = a;
if (a <= 0d)
{
src[di] = 0d;
src[di + 1] = 0d;
src[di + 2] = 0d;
}
else
{
double s = 255d / a;
src[di] = Math.Clamp(p[2] * s, 0d, 255d);
src[di + 1] = Math.Clamp(p[1] * s, 0d, 255d);
src[di + 2] = Math.Clamp(p[0] * s, 0d, 255d);
}
}
}
int half = size / 2;
fixed (byte* buf = target)
{
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
double sr = 0d, sg = 0d, sb = 0d, sa = 0d;
for (int ky = 0; ky < size; ky++)
{
int sy = Math.Clamp(y + ky - half, 0, height - 1);
for (int kx = 0; kx < size; kx++)
{
int sx = Math.Clamp(x + kx - half, 0, width - 1);
double kv = kernel[ky * size + kx];
int si = (sy * width + sx) * 4;
sr += src[si] * kv;
sg += src[si + 1] * kv;
sb += src[si + 2] * kv;
sa += src[si + 3] * kv;
}
}
double rr = Math.Clamp(sr / divisor + offset, 0d, 255d);
double gg = Math.Clamp(sg / divisor + offset, 0d, 255d);
double bb = Math.Clamp(sb / divisor + offset, 0d, 255d);
double aa = Math.Clamp(sa / divisor + offset, 0d, 255d);
double aK = aa / 255d;
byte* p = buf + (y * width + x) * 4;
p[0] = (byte)Math.Clamp(bb * aK, 0d, 255d);
p[1] = (byte)Math.Clamp(gg * aK, 0d, 255d);
p[2] = (byte)Math.Clamp(rr * aK, 0d, 255d);
p[3] = (byte)aa;
}
}
}
}
public static byte[] Resize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, ref byte[]? sourceScratch, ref byte[]? targetScratch)
{
int srcCount = sourceWidth * sourceHeight * 4;
if (sourceScratch is null || sourceScratch.Length < srcCount)
sourceScratch = new byte[srcCount];
Buffer.BlockCopy(source, 0, sourceScratch, 0, srcCount);
int dstCount = targetWidth * targetHeight * 4;
if (targetScratch is null || targetScratch.Length != dstCount)
targetScratch = new byte[dstCount];
var src = sourceScratch;
var dst = targetScratch;
fixed (byte* s = src)
fixed (byte* d = dst)
{
for (int y = 0; y < targetHeight; y++)
{
for (int x = 0; x < targetWidth; x++)
{
byte* o = d + (y * targetWidth + x) * 4;
if (!linear)
{
int sx = Math.Clamp((int)((x + 0.5) * sourceWidth / targetWidth), 0, sourceWidth - 1);
int sy = Math.Clamp((int)((y + 0.5) * sourceHeight / targetHeight), 0, sourceHeight - 1);
byte* p = s + (sy * sourceWidth + sx) * 4;
o[0] = p[0];
o[1] = p[1];
o[2] = p[2];
o[3] = p[3];
}
else
{
double u = (x + 0.5) * sourceWidth / targetWidth - 0.5;
double v = (y + 0.5) * sourceHeight / targetHeight - 0.5;
int x0 = (int)Math.Floor(u);
int y0 = (int)Math.Floor(v);
double tx = u - x0;
double ty = v - y0;
for (int c = 0; c < 4; c++)
{
double acc = 0d;
for (int j = 0; j < 2; j++)
{
int sy = Math.Clamp(y0 + j, 0, sourceHeight - 1);
double wy = j == 0 ? 1d - ty : ty;
for (int i = 0; i < 2; i++)
{
int sx = Math.Clamp(x0 + i, 0, sourceWidth - 1);
double wx = i == 0 ? 1d - tx : tx;
acc += s[(sy * sourceWidth + sx) * 4 + c] * wy * wx;
}
}
o[c] = (byte)Math.Clamp(acc, 0d, 255d);
}
}
}
}
}
return dst;
}
}
}
+3 -2
ファイルの表示
@@ -1,15 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.19.2</Version>
<Version>1.20.1</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="LuaScript.Gpu" />
<InternalsVisibleTo Include="LuaScript" />
<InternalsVisibleTo Include="LuaScript.Tests" />
</ItemGroup>
+5 -5
ファイルの表示
@@ -137,35 +137,35 @@ namespace LuaScript.Tests
[Fact]
public void ChangedLines_EmptyWhenNoRewrite()
{
var (_, _, changed) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = 2");
var (_, _, changed, _) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = 2");
Assert.Empty(changed);
}
[Fact]
public void ChangedLines_ReportRewrittenLineInRunnableSpace()
{
var (_, _, changed) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = obj.x != 0\nobj.z = 3");
var (_, _, changed, _) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = obj.x != 0\nobj.z = 3");
Assert.Equal(new[] { 2 }, changed);
}
[Fact]
public void ChangedLines_AreSortedAndCoverEveryRewrittenLine()
{
var (_, _, changed) = AviUtlScript.TransformWithMap("a = x != 0\nb = y\nc = z ?? 5\nw++");
var (_, _, changed, _) = AviUtlScript.TransformWithMap("a = x != 0\nb = y\nc = z ?? 5\nw++");
Assert.Equal(new[] { 1, 3, 4 }, changed);
}
[Fact]
public void ChangedLines_DeduplicateMultipleRewritesOnOneLine()
{
var (_, _, changed) = AviUtlScript.TransformWithMap("a = x != 0 and y != 1 and z != 2");
var (_, _, changed, _) = AviUtlScript.TransformWithMap("a = x != 0 and y != 1 and z != 2");
Assert.Equal(new[] { 1 }, changed);
}
[Fact]
public void ChangedLines_TrackRunnableLineAfterHoistedPrelude()
{
var (_, _, changed) = AviUtlScript.TransformWithMap("--dialog:V,local v=3;\nresult = v != 0");
var (_, _, changed, _) = AviUtlScript.TransformWithMap("--dialog:V,local v=3;\nresult = v != 0");
Assert.NotEmpty(changed);
for (int i = 1; i < changed.Length; i++)
Assert.True(changed[i] > changed[i - 1]);
+3
ファイルの表示
@@ -11,6 +11,8 @@ namespace LuaScript.Tests
"repeat", "return", "then", "true", "until", "while"
];
private static readonly string[] SyntaxKeywords = ["fast"];
private static readonly string[] Globals =
[
"time", "frame", "totalframe", "framerate",
@@ -104,6 +106,7 @@ namespace LuaScript.Tests
private static string[] ExpectedStaticCandidates() =>
Keywords
.Concat(SyntaxKeywords)
.Concat(Globals)
.Concat(Namespaces.SelectMany(n => n.Members))
.Distinct()
+43
ファイルの表示
@@ -52,6 +52,49 @@ namespace LuaScript.Tests
return buffer;
}
private sealed class RecordingProcessor : IPixelBufferProcessor
{
public int FillCalls;
public int ConvolveCalls;
public int ResizeCalls;
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
{
FillCalls++;
return false;
}
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
{
ConvolveCalls++;
return false;
}
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
{
ResizeCalls++;
target = null;
return false;
}
}
[Fact]
public void BufferOps_ConsultPixelProcessorAndFallBackToCpu()
{
using var engine = CreateEngine();
var ctx = NewContext(new byte[2 * 2 * 4], 2, 2);
var processor = new RecordingProcessor();
ctx.PixelProcessor = processor;
engine.Execute("obj.fill(200, 100, 50, 255) obj.convolve({1,1,1,1,1,1,1,1,1}, 3) obj.resize(4, 4)", ctx);
Assert.Equal(1, processor.FillCalls);
Assert.Equal(1, processor.ConvolveCalls);
Assert.Equal(1, processor.ResizeCalls);
Assert.Equal(4, ctx.ImageWidth);
Assert.Equal(4, ctx.ImageHeight);
}
[Fact]
public void Fill_WholeBuffer_WritesPremultipliedColor()
{
+90
ファイルの表示
@@ -578,5 +578,95 @@ namespace LuaScript.Tests
{
Assert.Equal("for i = 0, 10 do end", Rewrite("for i in <0..10> do end"));
}
[Theory]
[InlineData("[fast] obj.fill(0, 0, 0, 255)", " __fast_fill(0, 0, 0, 255)")]
[InlineData("[fast] obj.convolve(k, 3)", " __fast_convolve(k, 3)")]
[InlineData("[fast] obj.resize(100, 100)", " __fast_resize(100, 100)")]
[InlineData("[ fast ] obj.resize(100, 100)", " __fast_resize(100, 100)")]
[InlineData("[fast]obj.fill()", "__fast_fill()")]
[InlineData(" [fast] obj.fill()", " __fast_fill()")]
public void Fast_RewritesAcceleratedPrimitive(string source, string expected)
{
Assert.Equal(expected, Rewrite(source));
}
[Theory]
[InlineData("[fast]\nobj.fill(0, 0, 0, 255)", "\n__fast_fill(0, 0, 0, 255)")]
[InlineData("[fast]\nobj.convolve(k, 3)", "\n__fast_convolve(k, 3)")]
[InlineData("[fast]\nobj.resize(64, 64)", "\n__fast_resize(64, 64)")]
[InlineData("obj.x = 1\n[fast]\nobj.resize(64, 64)", "obj.x = 1\n\n__fast_resize(64, 64)")]
public void Fast_MarkerOnOwnLine_RewritesNextStatement(string source, string expected)
{
Assert.Equal(expected, Rewrite(source));
}
[Fact]
public void Fast_MarkerOnOwnLine_ReportsDiagnosticOnMarkerLine()
{
var (code, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("obj.x = 1\n[fast]\nobj.draw(0)");
Assert.Equal("obj.x = 1\n\nobj.draw(0)", code);
var diagnostic = Assert.Single(diagnostics);
Assert.Equal(2, diagnostic.Line);
}
[Fact]
public void Fast_KeywordIsRegisteredInCatalog()
{
Assert.Contains("fast", LuaScript.Compat.Syntax.LuaSyntaxRuleRegistry.CatalogKeywords);
}
[Fact]
public void Fast_RewritesInsideBlock()
{
Assert.Equal(
"for i = 1, 3 do __fast_fill(i, i, i, 255) end",
Rewrite("for i in <1..3> do [fast] obj.fill(i, i, i, 255) end"));
}
[Theory]
[InlineData("x = t[fast]")]
[InlineData("x = obj.data[fast]")]
[InlineData("x = f()[fast]")]
[InlineData("t = { [fast] = 1 }")]
[InlineData("x = \"[fast] obj.fill()\"")]
[InlineData("-- [fast] obj.fill()")]
public void Fast_DoesNotTouchNonMarkerBrackets(string source)
{
Assert.Equal(source, Rewrite(source));
}
[Fact]
public void Fast_OnUnsupportedTargetStripsMarkerAndReportsDiagnostic()
{
var (code, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("[fast] obj.draw(0)");
Assert.Equal(" obj.draw(0)", code);
var diagnostic = Assert.Single(diagnostics);
Assert.Equal(1, diagnostic.Line);
Assert.Contains("fast", diagnostic.Message);
}
[Fact]
public void Fast_OnNonObjTargetReportsDiagnostic()
{
var (code, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("[fast] local x = 1");
Assert.Equal(" local x = 1", code);
Assert.Single(diagnostics);
}
[Fact]
public void Fast_SupportedTargetEmitsNoDiagnostic()
{
var (_, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("[fast] obj.fill(0, 0, 0, 255)");
Assert.Empty(diagnostics);
}
[Fact]
public void Fast_ReportsDiagnosticLineWithinBlock()
{
var (_, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("obj.x = 1\n[fast] obj.draw(0)");
var diagnostic = Assert.Single(diagnostics);
Assert.Equal(2, diagnostic.Line);
}
}
}
+284
ファイルの表示
@@ -28,6 +28,7 @@ namespace LuaScript.Tests
private Action<string, SceneValue> _sceneSet = (_, _) => { };
private Func<string, string, int, (int Count, int Rate, double[] Data)> _loadAudio = (_, _, _) => (0, 0, []);
private PixelShaderInvoke? _runPixelShader;
private IPixelBufferProcessor? _pixelProcessor;
public void Dispose() => _worker.Dispose();
@@ -77,6 +78,7 @@ namespace LuaScript.Tests
_sceneGet, _sceneSet,
_loadAudio,
_runPixelShader,
_pixelProcessor,
out pixelsDirty, out bufferReplaced, out resultWidth, out resultHeight, out error);
resultPixels = null;
@@ -114,6 +116,7 @@ namespace LuaScript.Tests
_sceneGet, _sceneSet,
_loadAudio,
_runPixelShader,
null,
out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
@@ -1905,6 +1908,234 @@ namespace LuaScript.Tests
Assert.Equal(7d, fields2[NativeProtocol.X]);
}
[Fact]
public void PixelProcess_Fill_UsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 1024, h = 1024;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { FillResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"__fast_fill(10, 20, 30, 40, 0, 0, 1024, 1024)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(1, processor.FillCalls);
Assert.Equal(0x41, pixels[0]);
Assert.Equal(0x41, pixels[^1]);
}
[Fact]
public void PixelProcess_Convolve_PassesKernelToHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 200, h = 200;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ConvolveResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"__fast_convolve({1, 2, 3, 4, 5, 6, 7, 8, 9}, 3, 45, 6)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(1, processor.ConvolveCalls);
Assert.Equal(3, processor.Size);
Assert.Equal(45d, processor.Divisor);
Assert.Equal(6d, processor.Offset);
Assert.Equal(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, processor.Kernel);
Assert.Equal(0x42, pixels[0]);
Assert.Equal(0x42, pixels[^1]);
}
[Fact]
public void PixelProcess_Resize_ReplacesBufferWithHostResult()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ResizeResult = true };
_pixelProcessor = processor;
var fields = Fields(w, h, 0d);
bool ok = RunWorker(
"__fast_resize(512, 512, 'nearest') obj.x = obj.w obj.y = obj.h",
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out bool replaced, out byte[]? result, out int rw, out int rh, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.True(replaced);
Assert.Equal(512, rw);
Assert.Equal(512, rh);
Assert.Equal(512d, processor.TargetWidth);
Assert.Equal(512d, processor.TargetHeight);
Assert.False(processor.Linear);
Assert.Equal(512d, fields[NativeProtocol.X]);
Assert.Equal(512d, fields[NativeProtocol.Y]);
Assert.NotNull(result);
Assert.Equal(0x43, result![0]);
Assert.Equal(0x43, result[^1]);
}
[Fact]
public void PixelProcess_DefaultFill_UsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 1024, h = 1024;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { FillResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.fill(10, 20, 30, 40, 0, 0, 1024, 1024)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(1, processor.FillCalls);
Assert.Equal(0x41, pixels[0]);
Assert.Equal(0x41, pixels[^1]);
}
[Fact]
public void PixelProcess_DefaultConvolve_UsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 200, h = 200;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ConvolveResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.convolve({1, 2, 3, 4, 5, 6, 7, 8, 9}, 3, 45, 6)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(1, processor.ConvolveCalls);
Assert.Equal(3, processor.Size);
Assert.Equal(45d, processor.Divisor);
Assert.Equal(6d, processor.Offset);
Assert.Equal(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, processor.Kernel);
}
[Fact]
public void PixelProcess_DefaultResize_UsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ResizeResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.resize(512, 512, 'nearest')",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out bool replaced, out _, out int rw, out int rh, out string? error);
Assert.True(ok, error);
Assert.True(replaced);
Assert.Equal(1, processor.ResizeCalls);
Assert.Equal(512, rw);
Assert.Equal(512, rh);
}
[Fact]
public void PixelProcess_BelowThresholdFill_SkipsHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 64, h = 64;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { FillResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.fill(10, 20, 30, 40)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(0, processor.FillCalls);
}
[Fact]
public void PixelProcess_BelowThresholdConvolve_SkipsHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 8, h = 8;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ConvolveResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(0, processor.ConvolveCalls);
}
[Fact]
public void PixelProcess_BelowThresholdResize_SkipsHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ResizeResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.resize(4, 4, 'nearest')",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(0, processor.ResizeCalls);
}
[Fact]
public void HostCallbackTime_DoesNotConsumeScriptTimeout()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var decoded = new byte[4];
Func<string, (byte[], int, int)> slowLoadImage = _ =>
{
System.Threading.Thread.Sleep(1500);
return (decoded, 1, 1);
};
var pixels = new byte[2 * 2 * 4];
var fields = Fields(2, 2, 0d);
bool ok = RunWorker(
"obj.load('image', 'C:/sample.png') obj.x = 5",
fields, NoStringParams, () => pixels, 2, 2, 1000, NoResolver, NoLoadFigure, NoLoadText, slowLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(5d, fields[NativeProtocol.X]);
}
[Fact]
public void Fill_WritesPremultipliedColor()
{
@@ -2116,5 +2347,58 @@ namespace LuaScript.Tests
Assert.Equal(2d, fields[NativeProtocol.Y]);
Assert.Equal(Math.Sqrt(8d * 8d + 2d * 2d), fields[NativeProtocol.Z]);
}
private sealed class RecordingPixelProcessor : IPixelBufferProcessor
{
public bool FillResult { get; init; }
public bool ConvolveResult { get; init; }
public bool ResizeResult { get; init; }
public int FillCalls { get; private set; }
public int ConvolveCalls { get; private set; }
public int ResizeCalls { get; private set; }
public int Size { get; private set; }
public double Divisor { get; private set; }
public double Offset { get; private set; }
public double[] Kernel { get; private set; } = [];
public int TargetWidth { get; private set; }
public int TargetHeight { get; private set; }
public bool Linear { get; private set; }
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
{
FillCalls++;
if (!FillResult)
return false;
Array.Fill(target, (byte)0x41, 0, width * height * 4);
return true;
}
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
{
ConvolveCalls++;
Size = size;
Divisor = divisor;
Offset = offset;
Kernel = kernel.AsSpan(0, size * size).ToArray();
if (!ConvolveResult)
return false;
Array.Fill(target, (byte)0x42, 0, width * height * 4);
return true;
}
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
{
ResizeCalls++;
TargetWidth = targetWidth;
TargetHeight = targetHeight;
Linear = linear;
target = null;
if (!ResizeResult)
return false;
target = new byte[targetWidth * targetHeight * 4];
Array.Fill(target, (byte)0x43);
return true;
}
}
}
}
+3
ファイルの表示
@@ -16,6 +16,9 @@
<Project Path="LuaScript.Runtime/LuaScript.Runtime.csproj">
<Platform Solution="*|x64" Project="Any CPU" />
</Project>
<Project Path="LuaScript.Gpu/LuaScript.Gpu.csproj">
<Platform Solution="*|x64" Project="Any CPU" />
</Project>
<Project Path="LuaScript.Tests/LuaScript.Tests.csproj" />
<Project Path="LuaScript/LuaScript.csproj">
<Platform Solution="*|x64" Project="x64" />
+33 -3
ファイルの表示
@@ -7,6 +7,7 @@ using LuaScript.Compat;
using LuaScript.Diagnostics;
using LuaScript.Engine;
using LuaScript.Engine.Kernel;
using LuaScript.Engine.Processing;
using LuaScript.Engine.Shader;
using Vortice;
using Vortice.DCommon;
@@ -158,6 +159,7 @@ namespace LuaScript
private string _runnableScript = string.Empty;
private int[] _runnableLineMap = [];
private int[] _runnableChangedLines = [];
private LuaScriptDiagnostic[] _runnableRewriteDiagnostics = [];
private bool _runnableCached;
private ID2D1Image? _cachedInput;
private RenderKey _cachedKey;
@@ -167,6 +169,7 @@ namespace LuaScript
private ID2D1Image? _cachedEffectOutput;
private PixelShaderRunner? _pixelShaderRunner;
private GpuPixelBufferProcessor? _pixelProcessor;
private AviUtlPixelShaderLibrary _pixelShaderLibrary = AviUtlPixelShaderLibrary.Empty;
private string? _pixelShaderSourceRef;
@@ -187,9 +190,11 @@ namespace LuaScript
new SynchronizedCompositor(new HardwareCompositor(_ownCtx), _pixelLoaderSemaphore),
SoftwareCompositor.Instance,
WarnBufferCompositorDegraded);
_pixelShaderRunner = new PixelShaderRunner { Compositor = _bufferCompositor };
_pixelShaderRunner = new PixelShaderRunner { Compositor = _bufferCompositor, Logger = WriteGpuLog };
_pixelProcessor = new GpuPixelBufferProcessor(_pixelShaderRunner);
_context.ResolverProvider = GetFrameResolver;
_context.Compositor = _bufferCompositor;
_context.PixelProcessor = _pixelProcessor;
_context.SceneImageLoader = _loadSceneImage ??= LoadSceneImage;
_context.BrushImageLoader = _loadBrushImage ??= LoadBrushImage;
_context.AudioLoader = _loadAudio ??= LoadAudio;
@@ -199,11 +204,21 @@ namespace LuaScript
private static void WarnBufferCompositorDegraded(Exception ex) =>
Log.Default.Write("LuaScript: hardware buffer compositing failed; falling back to the software compositor.", ex);
private static void WriteGpuLog(string message, Exception? exception)
{
if (exception is null)
Log.Default.Write(message);
else
Log.Default.Write(message, exception);
}
private AviUtlScriptContext CreateScriptContext()
{
var context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
if (_bufferCompositor is not null)
context.Compositor = _bufferCompositor;
if (_pixelProcessor is not null)
context.PixelProcessor = _pixelProcessor;
context.SceneImageLoader = _loadSceneImage ??= LoadSceneImage;
context.BrushImageLoader = _loadBrushImage ??= LoadBrushImage;
context.AudioLoader = _loadAudio ??= LoadAudio;
@@ -236,15 +251,27 @@ namespace LuaScript
if (_runnableCached && ReferenceEquals(source, _sourceScript))
return _runnableScript;
var (code, lineMap, changedLines) = AviUtlScript.TransformWithMap(source);
var (code, lineMap, changedLines, rewriteDiagnostics) = AviUtlScript.TransformWithMap(source);
_runnableScript = code;
_runnableLineMap = lineMap;
_runnableChangedLines = changedLines;
_sourceScript = source;
_runnableCached = true;
_runnableRewriteDiagnostics = BuildRewriteDiagnostics(rewriteDiagnostics);
return _runnableScript;
}
private LuaScriptDiagnostic[] BuildRewriteDiagnostics(LuaScript.Compat.Syntax.LuaRewriteDiagnostic[] source)
{
if (source.Length == 0)
return [];
var diagnostics = new LuaScriptDiagnostic[source.Length];
for (int i = 0; i < source.Length; i++)
diagnostics[i] = new LuaScriptDiagnostic(LuaScriptDiagnosticKind.Compile, MapRunnableLine(source[i].Line), 0, 0, source[i].Message);
return diagnostics;
}
private AviUtlPixelShaderLibrary GetPixelShaderLibrary(string source)
{
if (!ReferenceEquals(_pixelShaderSourceRef, source))
@@ -480,7 +507,9 @@ namespace LuaScript
_pixelLoaderSemaphore.Release();
}
LuaScriptDiagnostics.Instance.Report(script, diagnostics);
LuaScriptDiagnostics.Instance.Report(script, _runnableRewriteDiagnostics.Length == 0
? diagnostics
: [.. _runnableRewriteDiagnostics, .. diagnostics]);
_isFirst = false;
if (_sceneImageLoaded)
@@ -1065,6 +1094,7 @@ namespace LuaScript
_nativeSceneSet,
_loadAudio,
_nativeRunPixelShader,
_pixelProcessor,
out bool dirty, out bool bufferReplaced,
out int resultW, out int resultH, out string? error);
+3 -2
ファイルの表示
@@ -1,10 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.19.2</Version>
<Version>1.20.1</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
@@ -97,6 +97,7 @@
<ItemGroup>
<ProjectReference Include="..\LuaScript.Kernel\LuaScript.Kernel.csproj" />
<ProjectReference Include="..\LuaScript.Compat\LuaScript.Compat.csproj" />
<ProjectReference Include="..\LuaScript.Gpu\LuaScript.Gpu.csproj" />
<ProjectReference Include="..\LuaScript.Media\LuaScript.Media.csproj" />
<ProjectReference Include="..\LuaScript.Runtime\LuaScript.Runtime.csproj" />
</ItemGroup>
+11
ファイルの表示
@@ -974,6 +974,17 @@
x in <1..5> يفحص 1 <= x and x <= 5.
<1..<5> لا يشمل الحد الأعلى. يُقيَّم الطرف الأيسر مرة واحدة.
○ [fast] (علامة التسريع) * امتداد خاص بـ YMM4
تُفوَّض obj.fill / obj.convolve / obj.resize إلى وحدة معالجة الرسوميات
تلقائيًا عندما يتجاوز حجم المعالجة حدًا معينًا ويتم التحقق من تطابق نتيجة
وحدة معالجة الرسوميات مع نتيجة المعالج. [fast] علامة مساعدة تصرّح
بالنية صراحةً، وإضافتها لا تغيّر السلوك. يمكن وضع العلامة في سطر
مستقل أو في السطر نفسه.
مثال: [fast]
obj.convolve(kernel, 5)
* يظهر خطأ عندما يسبق [fast] أي شيء غير هذه الدوال الثلاث.
* يعمل في محرك MoonSharp والمحرك الأصلي على حد سواء.
- أمثلة على النصوص البرمجية -
+11
ファイルの表示
@@ -1013,6 +1013,17 @@
x in <1..5> tests 1 <= x and x <= 5.
<1..<5> excludes the upper bound. The left side is evaluated once.
o [fast] (acceleration marker) * YMM4 extension
obj.fill / obj.convolve / obj.resize are delegated to the GPU
automatically when the workload exceeds a threshold and the GPU
result is verified to match the CPU. [fast] is an auxiliary marker
that states the intent explicitly; adding it does not change the
behavior. The marker may be on its own line or on the same line.
Example: [fast]
obj.convolve(kernel, 5)
* An error is shown when [fast] precedes anything other than those three functions.
* Works in both the MoonSharp and native engines.
- Script Examples -
+11
ファイルの表示
@@ -1034,6 +1034,17 @@
x in <1..5> comprueba 1 <= x and x <= 5.
<1..<5> excluye el límite superior. El lado izquierdo se evalúa una sola vez.
o [fast] (marcador de aceleración) * extensión de YMM4
obj.fill / obj.convolve / obj.resize se delegan automáticamente a la
GPU cuando la carga supera un umbral y el resultado de la GPU se
verifica como idéntico al de la CPU. [fast] es un marcador auxiliar
que declara la intención de forma explícita; añadirlo no cambia el
comportamiento. El marcador puede ir en su propia línea o en la misma.
Ejemplo: [fast]
obj.convolve(kernel, 5)
* Se muestra un error cuando [fast] precede a algo distinto de esas tres funciones.
* Funciona tanto en el motor MoonSharp como en el nativo.
- Ejemplos de script -
+11
ファイルの表示
@@ -1024,6 +1024,17 @@
x in <1..5> menguji 1 <= x and x <= 5.
<1..<5> tidak menyertakan batas atas. Sisi kiri dievaluasi sekali.
o [fast] (penanda akselerasi) * ekstensi YMM4
obj.fill / obj.convolve / obj.resize didelegasikan ke GPU secara
otomatis ketika beban kerja melebihi ambang batas dan hasil GPU
terverifikasi sama dengan CPU. [fast] adalah penanda tambahan yang
menyatakan niat secara eksplisit; menambahkannya tidak mengubah
perilaku. Penanda boleh di baris tersendiri atau di baris yang sama.
Contoh: [fast]
obj.convolve(kernel, 5)
* Kesalahan ditampilkan jika [fast] mendahului selain ketiga fungsi tersebut.
* Berfungsi pada mesin MoonSharp maupun native.
- Contoh Skrip -
+11
ファイルの表示
@@ -981,6 +981,17 @@
x in <1..5> は 1 <= x and x <= 5 を判定します。
<1..<5> は上限を含みません。左辺は 1 度だけ評価します。
○[fast](高速化マーカー) ※YMM4独自拡張
obj.fill / obj.convolve / obj.resize は、処理量がしきい値以上で
GPU の結果が CPU と一致すると確認できたとき、自動で GPU へ委譲
します。[fast] は委譲の意図を明示する補助マーカーで、置いても
動作は変わりません。マーカーは単独の行に置いても、同じ行に
続けて書いても構いません。
例:[fast]
obj.convolve(kernel, 5)
※ [fast] を付けた対象が上記 3 関数以外のときはエラーを表示します。
※ 従来エンジンと高速ランタイムの両方で動作します。
- スクリプト例 -
+11
ファイルの表示
@@ -970,6 +970,17 @@
x in <1..5>는 1 <= x and x <= 5를 판정합니다.
<1..<5>는 상한을 포함하지 않습니다. 왼쪽 값은 한 번만 평가합니다.
○ [fast] (가속 마커) ※YMM4 고유 확장
obj.fill / obj.convolve / obj.resize는 처리량이 임계값 이상이고
GPU 결과가 CPU와 일치함이 확인되면 자동으로 GPU에 위임합니다.
[fast]는 위임 의도를 명시하는 보조 마커이며, 붙여도 동작은
변하지 않습니다. 마커는 단독 행에 두어도, 같은 행에 이어 써도
됩니다.
예: [fast]
obj.convolve(kernel, 5)
※ [fast]를 붙인 대상이 위 3개 함수가 아니면 오류를 표시합니다.
※ 기존 엔진과 고속 런타임 양쪽에서 동작합니다.
- 스크립트 예 -
+10
ファイルの表示
@@ -928,6 +928,16 @@
x in <1..5> 判断 1 <= x and x <= 5。
<1..<5> 不包含上限。左侧只求值一次。
○ [fast](加速标记) ※YMM4专有扩展
当处理量达到阈值且 GPU 结果经验证与 CPU 一致时,obj.fill /
obj.convolve / obj.resize 会自动委托给 GPU。[fast] 是显式表明
委托意图的辅助标记,加上它不会改变行为。标记可以单独占一行,
也可以写在同一行。
例:[fast]
obj.convolve(kernel, 5)
※ 若 [fast] 修饰的目标不是上述 3 个函数,则显示错误。
※ 在传统引擎和高速运行时上均可运行。
- 脚本示例 -
+10
ファイルの表示
@@ -929,6 +929,16 @@
x in <1..5> 判斷 1 <= x and x <= 5。
<1..<5> 不包含上限。左側只求值一次。
○ [fast](加速標記) ※YMM4專有擴充
當處理量達到閾值且 GPU 結果經驗證與 CPU 一致時,obj.fill /
obj.convolve / obj.resize 會自動委派給 GPU。[fast] 是明示
委派意圖的輔助標記,加上它不會改變行為。標記可以單獨佔一行,
也可以寫在同一行。
例:[fast]
obj.convolve(kernel, 5)
※ 若 [fast] 修飾的目標不是上述 3 個函式,則顯示錯誤。
※ 在傳統引擎與高速執行環境上皆可運行。
- 腳本範例 -
+1
ファイルの表示
@@ -261,6 +261,7 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
- **パイプ**: `x |> f`(`f((x))`。左辺を第 1 引数に渡す)、`x |> clamp(0, 255)`(`clamp((x), 0, 255)`)
- **補間文字列**: `` `x={a}` ``(`("x=" .. tostring(a))`。`{ }` の中に式を書く。拡張構文も使える)
- **範囲判定**: `x in <1..5>`(`1 <= x and x <= 5`)、`<1..<5>`(上限を含まない)
- **高速化マーカー**(YMM4 独自拡張): `obj.fill` / `obj.convolve` / `obj.resize` は処理量がしきい値以上で GPU の結果が CPU と一致すると確認できたとき自動で GPU へ委譲する。`[fast]` は委譲の意図を明示する補助マーカーで、呼び出しの直前(単独行でも同一行でも可)に置ける。動作は変わらない。文の先頭でのみ働くため `t[fast]` のような添字アクセスには影響しない
各記法の詳しい説明と例はドキュメント(`LuaScript/docs`)およびサイトの「構文拡張」を参照してください。
+4
ファイルの表示
@@ -382,6 +382,10 @@ obj.convolve({ -1,-1,-1, -1,8,-1, -1,-1,-1 }, 3, 1, 0) -- 輪郭抽出</code></
<code>obj.resize(w, h [, filter])</code> は作業画像を指定サイズへ拡大縮小し、<code>obj.w</code>・<code>obj.h</code>・<code>obj.cx</code> などの寸法も更新します。<code>filter</code> は <code>"nearest"</code>(最近傍)か、省略で線形補間です。高速ランタイムでは結果が最大画像サイズを超える場合は変更しません。
</p>
<p>
<code>obj.fill</code>・<code>obj.convolve</code>・<code>obj.resize</code> は、処理量がしきい値以上で GPU の結果が CPU と一致すると確認できたとき、自動で GPU へ委譲します。呼び出しの直前(単独行でも同一行でも可)に <code>[fast]</code> を置くと委譲の意図を明示できます(動作は変わりません)。詳細は <a href="syntax.html">拡張構文</a> を参照してください。
</p>
<h3>アンカーポイント</h3>
<p>
+28
ファイルの表示
@@ -249,6 +249,34 @@ end</code></pre>
左辺は 1 度だけ評価する無名関数に展開します。範囲 for の <code>for i in &lt;0..10&gt;</code> とは書く位置が異なるため、for のヘッダーには影響しません。
</div>
<h2>[fast] 高速化マーカー</h2>
<p>
<code>obj.fill</code> <code>obj.convolve</code> <code>obj.resize</code> は、処理量がしきい値以上で GPU の結果が CPU と一致すると確認できたとき、自動で GPU へ委譲します。<code>[fast]</code> は委譲の意図を明示する補助マーカーで、置いても動作は変わりません。<strong>YMM4 独自拡張</strong>です。
</p>
<table>
<tr><th>書き方</th><th>意味</th></tr>
<tr><td><code>[fast]</code> の次の行に <code>obj.convolve(k, 5)</code></td><td>GPU への委譲を明示する(動作は下と同じ)</td></tr>
<tr><td><code>obj.convolve(k, 5)</code></td><td>自動で GPU / CPU を判定する</td></tr>
</table>
<p>
マーカーは単独の行に置いても、同じ行に続けて書いても構いません。処理が小さいときや GPU が使えないときは自動で CPU 実行になります。
</p>
<pre><code>--track@size:Size,1,15,3,2
local n = math.floor(obj.track0)
if n % 2 == 0 then n = n + 1 end
local k = {}
for i = 1, n * n do k[i] = 1 end
[fast]
obj.convolve(k, n)</code></pre>
<div class="note">
文の先頭でのみマーカーとして働くため、<code>t[fast]</code> のような添字アクセスは変換しません。<code>[fast]</code> を付けた対象が上記 3 関数以外のときはエラーを表示します。従来エンジンと高速ランタイムの両方で動作します。
</div>
<div class="pager">
<a href="stdlib.html">← 標準ライブラリ</a>
<a href="globals.html">グローバル変数 →</a>
+92 -4
ファイルの表示
@@ -99,6 +99,14 @@ local CB_KIND_LOADSCENE = 15
local CB_KIND_LOADBRUSH = 16
local CB_KIND_BRUSH = 17
local CB_KIND_GETAUDIO = 18
local CB_KIND_PIXELPROCESS = 19
local PIXEL_PROCESS_FILL = 0
local PIXEL_PROCESS_CONVOLVE = 1
local PIXEL_PROCESS_RESIZE = 2
local PIXEL_PROCESS_FILL_FULL_THRESHOLD = 1048576
local PIXEL_PROCESS_FILL_PARTIAL_THRESHOLD = 1048576
local PIXEL_PROCESS_RESIZE_THRESHOLD = 262144
local PIXEL_PROCESS_CONVOLVE_WORK_THRESHOLD = 262144
local MAX_PIXEL_BUFFER = 3840 * 2160 * 4
local SHADER_META_DOUBLES = 20
local SHADER_CONSTANTS_MAX = 1024
@@ -134,6 +142,7 @@ local drawTarget = "frame"
local pdData, pdCapacity, pdValid, pdDirty = nil, 0, false, false
local convSrcData, convSrcCap = nil, 0
local resizeSrcData, resizeSrcCap = nil, 0
local pixelProcessAvailable = true
local function ensurePixels()
if pixelsValid then return end
@@ -151,6 +160,19 @@ local function flushDraws()
k32.WaitForSingleObject(workEvent, INFINITE)
end
local function tryPixelProcess(kind)
if not pixelProcessAvailable then return false end
cbResult[0] = kind
i32[OFF_CB_FOUND] = 0
i32[OFF_CB_KIND] = CB_KIND_PIXELPROCESS
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
local found = i32[OFF_CB_FOUND]
if found < 0 then pixelProcessAvailable = false end
return found == 1
end
local function ringSlot(kind)
local n = ringD[0]
if n >= DRAW_RING_CAPACITY then
@@ -842,7 +864,7 @@ function obj.copybuffer(dst, src)
end
end
function obj.fill(r, g, b, a, x, y, w, h)
local function fillImpl(r, g, b, a, x, y, w, h)
ensurePixels()
flushPixelData()
r = r or 0; g = g or 0; b = b or 0; a = a or 255
@@ -853,6 +875,29 @@ function obj.fill(r, g, b, a, x, y, w, h)
local x1 = clamp(x + w, 0, width)
local y1 = clamp(y + h, 0, height)
if x1 <= x0 or y1 <= y0 then return end
local imageArea = width * height
local fillArea = (x1 - x0) * (y1 - y0)
local fullFill = x0 == 0 and y0 == 0 and x1 == width and y1 == height
local usePixelProcess = false
if fullFill then
usePixelProcess = imageArea >= PIXEL_PROCESS_FILL_FULL_THRESHOLD
else
usePixelProcess = imageArea >= PIXEL_PROCESS_FILL_PARTIAL_THRESHOLD and fillArea * 4 >= imageArea * 3
end
cbResult[1] = r
cbResult[2] = g
cbResult[3] = b
cbResult[4] = a
cbResult[5] = x0
cbResult[6] = y0
cbResult[7] = x1 - x0
cbResult[8] = y1 - y0
if usePixelProcess and tryPixelProcess(PIXEL_PROCESS_FILL) then
dirty = true
pdValid = false
pdDirty = false
return
end
local aK = clamp(a, 0, 255) / 255
local pb = math.floor(clamp(b * aK, 0, 255))
local pg = math.floor(clamp(g * aK, 0, 255))
@@ -868,6 +913,9 @@ function obj.fill(r, g, b, a, x, y, w, h)
pdValid = false
end
obj.fill = fillImpl
__fast_fill = fillImpl
function obj.getpixelregion(x, y, w, h)
x = math.floor(x or 0); y = math.floor(y or 0)
w = math.floor(w or 0); h = math.floor(h or 0)
@@ -929,7 +977,7 @@ function obj.putpixelregion(x, y, w, h, data)
pdValid = false
end
function obj.convolve(kernel, size, divisor, offset)
local function convolveImpl(kernel, size, divisor, offset)
if type(kernel) ~= "table" then return end
size = math.floor(size or 0)
if size < 1 or size % 2 == 0 then return end
@@ -946,6 +994,21 @@ function obj.convolve(kernel, size, divisor, offset)
local inv = divisor or sum
if inv == 0 then inv = 1 end
offset = offset or 0
if taps * 8 <= CB_TAG_MAX and width * height * taps >= PIXEL_PROCESS_CONVOLVE_WORK_THRESHOLD then
cbResult[1] = size
cbResult[2] = inv
cbResult[3] = offset
for i = 1, taps do
cbTagD[i - 1] = k[i]
end
i32[OFF_CB_TAGLEN] = taps * 8
if tryPixelProcess(PIXEL_PROCESS_CONVOLVE) then
dirty = true
pdValid = false
pdDirty = false
return
end
end
local total = width * height * 4
if not convSrcData or convSrcCap < total then
convSrcData = ffi.new("double[?]", total)
@@ -998,7 +1061,10 @@ function obj.convolve(kernel, size, divisor, offset)
pdValid = false
end
function obj.resize(newW, newH, mode)
obj.convolve = convolveImpl
__fast_convolve = convolveImpl
local function resizeImpl(newW, newH, mode)
newW = math.floor(newW or 0); newH = math.floor(newH or 0)
if newW < 1 then newW = 1 end
if newH < 1 then newH = 1 end
@@ -1007,6 +1073,24 @@ function obj.resize(newW, newH, mode)
ensurePixels()
flushPixelData()
local cw, ch = width, height
local linear = mode ~= "nearest"
cbResult[1] = newW
cbResult[2] = newH
cbResult[3] = linear and 1 or 0
if newW * newH >= PIXEL_PROCESS_RESIZE_THRESHOLD and tryPixelProcess(PIXEL_PROCESS_RESIZE) then
width = newW; height = newH
i32[OFF_WIDTH] = newW; i32[OFF_HEIGHT] = newH
dirty = true
pixelsValid = true
pdValid = false
pdDirty = false
obj.w = newW; obj.h = newH
obj.hw = newW / 2; obj.hh = newH / 2
obj.cx = newW / 2; obj.cy = newH / 2
obj.cz = 0
obj.diagonal = math.sqrt(newW * newW + newH * newH)
return
end
local srcCount = cw * ch * 4
if not resizeSrcData or resizeSrcCap < srcCount then
resizeSrcData = ffi.new("uint8_t[?]", srcCount)
@@ -1014,7 +1098,6 @@ function obj.resize(newW, newH, mode)
end
ffi.copy(resizeSrcData, pixels, srcCount)
local src = resizeSrcData
local linear = mode ~= "nearest"
for y = 0, newH - 1 do
for x = 0, newW - 1 do
local o = pixels + (y * newW + x) * 4
@@ -1059,6 +1142,9 @@ function obj.resize(newW, newH, mode)
obj.diagonal = math.sqrt(newW * newW + newH * newH)
end
obj.resize = resizeImpl
__fast_resize = resizeImpl
local SCENE_VALUE_MAX = 4095
local SCENE_NIL = {}
local sceneReads = {}
@@ -1381,6 +1467,7 @@ sandbox = {
obj = obj, scene = scene, ymm4 = ymm4,
anim = anim, bit32 = bit32, rawlen = rawlen,
RGB = RGB, HSV = HSV, OR = OR, AND = AND, XOR = XOR, SHIFT = SHIFT,
__fast_fill = __fast_fill, __fast_convolve = __fast_convolve, __fast_resize = __fast_resize,
debug_print = debug_print,
math = math, string = string, table = table,
type = type, tostring = tostring, tonumber = tonumber, select = select,
@@ -1477,6 +1564,7 @@ while true do
pixelsValid = false
pdValid = false
pdDirty = false
pixelProcessAvailable = i32[OFF_CB_FOUND] > 0
frameBufferValid = false
ringD[0] = 0
local version = i32[OFF_SCRIPT_VERSION]