コミットを比較

...
46 コミット
作成者 SHA1 メッセージ 日付
routersys 1d8705c7ee バージョンをv1.11.4へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.11.4 のコミットから作成しました
2026-07-02 13:58:38 +09:00
routersys 14683c7909 HlslKernelEmitterの座標原点と出力の切り捨てを検証するテストを追加 2026-07-02 13:58:23 +09:00
routersys 42b123ebc3 検証に通ったGpuKernelのみ採用しカーネルの自動GPU選択を有効化 2026-07-02 13:58:14 +09:00
routersys b0114abdb7 GpuKernelへCpuKernelとの出力一致を実機で確かめるVerifyを追加 2026-07-02 13:58:06 +09:00
routersys c21de5b3eb GpuKernelの座標原点と出力の丸めをCpuKernelへ合わせて修正 2026-07-02 13:57:49 +09:00
routersys bd891d9a1e バージョンをv1.11.3へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.11.3 のコミットから作成しました
2026-07-02 13:19:45 +09:00
routersys d2bef10085 SoftwareCompositorのテストをTryComposeとInstanceへ更新 2026-07-02 13:19:30 +09:00
routersys 3eafcdc70e FallbackCompositorへ引き受け拒否経路のテストを追加しTryComposeへ更新 2026-07-02 13:19:10 +09:00
routersys 6f26fc95fa SynchronizedCompositorのユニットテストを追加 2026-07-02 13:18:55 +09:00
routersys 88ce786d05 GpuKernelで効果のOutputを生成時に一度だけ取得してキャッシュ 2026-07-02 13:18:39 +09:00
routersys d69ae5f06e PixelBufferManagerで変換のOutputをキャッシュし取得したTargetを破棄 2026-07-02 13:18:29 +09:00
routersys d42d8a6764 DrawCompositorでplacementのOutputをキャッシュし取得したTargetを破棄 2026-07-02 13:18:17 +09:00
routersys 8f9ace2dc8 HardwareCompositorをSynchronizedCompositorで包みピクセル読み出しと直列化 2026-07-02 13:18:07 +09:00
routersys c416e955a4 tempbuffer合成をSoftwareCompositor.InstanceのTryCompose呼び出しへ変更 2026-07-02 13:17:57 +09:00
routersys 7362e70ab8 GPU合成をセマフォで直列化するSynchronizedCompositorを追加 2026-07-02 13:17:46 +09:00
routersys c9741836a5 HardwareCompositorへ寸法上限8192を設け取得したTargetを破棄 2026-07-02 13:17:35 +09:00
routersys afd57d758d FallbackCompositorで引き受け拒否を降格扱いせず次段へ委譲 2026-07-02 13:17:24 +09:00
routersys c56432dbd6 SoftwareCompositorを共有インスタンス化しTryComposeで常に処理を引き受け 2026-07-02 13:17:14 +09:00
routersys 9493aef779 IBufferCompositorのComposeを委譲可否を返すTryComposeへ変更 2026-07-02 13:17:04 +09:00
routersys 5d55f2c083 バージョンをv1.11.2へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.11.2 のコミットから作成しました
2026-07-02 12:54:31 +09:00
routersys 09918c2858 READMEへtempbuffer合成のGPU実行を追記 2026-07-02 12:54:27 +09:00
routersys a687bba0ff サイトへtempbuffer合成のGPU実行を追記 2026-07-02 12:54:18 +09:00
routersys bb591b6fef 全言語ドキュメントへtempbuffer合成のGPU実行を追記 2026-07-02 12:54:10 +09:00
routersys 27d7294290 SoftwareCompositorのComposeディスパッチのテストを追加 2026-07-02 12:54:01 +09:00
routersys 8d1cf91499 FallbackCompositorのユニットテストを追加 2026-07-02 12:53:44 +09:00
routersys b2a1900616 DrawTransformのユニットテストを追加 2026-07-02 12:53:35 +09:00
routersys f786250866 tempbuffer合成へGPU優先のFallbackCompositorを配線 2026-07-02 12:53:19 +09:00
routersys 20dfba6e7e DrawCompositorの変換行列構築をDrawTransformへ集約 2026-07-02 12:53:13 +09:00
routersys 5e40f45910 tempbuffer合成を注入された合成器経由へ変更 2026-07-02 12:52:56 +09:00
routersys ea4f096bc4 Direct2DでGPU合成を行うHardwareCompositorを追加 2026-07-02 12:52:48 +09:00
routersys d7812f39dc SoftwareCompositorをIBufferCompositorの実装へ変更 2026-07-02 12:52:29 +09:00
routersys 77fdf60ec9 合成失敗時にCPUへ降格するFallbackCompositorを追加 2026-07-02 12:52:11 +09:00
routersys bcb9925953 描画コマンドから変換行列を求めるDrawTransformを追加 2026-07-02 12:52:00 +09:00
routersys ec7d8a1da4 バッファ合成の契約IBufferCompositorを追加 2026-07-02 12:51:51 +09:00
routersys 098d6e498b バージョンをv1.11.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.11.1 のコミットから作成しました
2026-07-02 08:43:27 +09:00
routersys ccf37dd1d3 サイトを既定エンジンのnative化に合わせて更新 2026-07-02 08:42:43 +09:00
routersys 2ce3068d54 READMEを既定エンジンのnative化に合わせて更新 2026-07-02 08:36:04 +09:00
routersys c2a1990501 全言語ドキュメントを既定エンジンのnative化に合わせて更新 2026-07-02 08:35:27 +09:00
routersys 4ac25584b9 既定エンジンのnative化に合わせてルーティング期待値を更新 2026-07-02 08:01:52 +09:00
routersys 5e40f30124 自動ルーティングの既定エンジンをnativeへ変更 2026-07-02 08:01:46 +09:00
routersys 9d541e06b9 遅延転送・ワーカー永続性・グローバルパリティのテストを追加 2026-07-02 08:01:18 +09:00
routersys bca7b5707e nativeレーンの入力ピクセルをメモ化付き遅延読み込みへ変更 2026-07-02 08:01:12 +09:00
routersys a17289a2da ピクセル転送を遅延化し再起動判定をgrow-only容量ベースへ変更 2026-07-02 08:00:59 +09:00
routersys 71e6b71056 ワーカーのピクセル遅延要求と裸グローバル・環境リセットのパリティを実装 2026-07-02 08:00:34 +09:00
routersys 13a0602adb ピクセル要求コールバック種別をネイティブプロトコルへ追加 2026-07-02 08:00:28 +09:00
routersys 6a0c993755 Updateホットパスのフレーム毎アロケーションを削減 2026-07-02 07:33:08 +09:00
40個のファイルの変更、1362行の追加、340行の削除

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

+51 -88
ファイルの表示
@@ -1,112 +1,75 @@
# v1.11.0 - Lua スクリプト for YMM4
# v1.11.4 - Lua スクリプト for YMM4
AviUtl 互換の描画 API を拡張したリリースです。`obj.draw` / `obj.drawpoly` の合成モード、
作業画像の出力可否を切り替える `draw_state`、描画先を `tmp` バッファへ切り替える
`drawtarget`、アンカー座標を Lua 変数として扱う `obj.setanchor` を追加しました。
MoonSharp とネイティブの両エンジンで同じ API を使えるようにし、内蔵ドキュメントも
各言語で更新しました。
毎ピクセル処理のスクリプト(カーネル)の実行先を、GPU と CPU から自動で選べるように
したリリースです。これまで GPU カーネルは `--!gpu` を明示したときだけ使っていましたが、
指定が無いときも利用できるかを自動で判断し、利用できる場合は GPU で実行します。正確性を
最優先し、初回に実機の GPU で CPU カーネルとの出力一致を検証し、許容差に収まった
プログラムだけ GPU で実行します。あわせて、GPU カーネルと CPU カーネルで食い違って
いた HLSL の座標原点と出力の丸めを、CPU カーネルに合わせて修正しました。
---
## 新機能・機能改善
## 改善
### 1. obj.setoption("blend", 合成モード)
### 1. カーネルの GPU/CPU 自動選択
`obj.draw` / `obj.drawpoly` の合成モードを `obj.setoption("blend", 番号)` で指定できるように
しました。
これまで毎ピクセル処理のスクリプトは、`--!gpu` を明示したときだけ GPU カーネルで実行し、
指定が無いときは CPU カーネルで実行していました。本リリースでは、指定が無いときも
GPU カーネルを利用できるかを自動で判断し、利用できる場合は GPU で実行します。GPU
カーネルは CPU カーネルが必要とするピクセルの読み戻しとアップロードを伴わないため、
そのぶん高速です。実行先はプログラム単位で一度だけ決まり、フレームや画像サイズによって
切り替わらないため、途中で結果がちらつくことはありません。
- 番号は YMM4 のプロパティパネルにある「合成モード」の並びと同じで、0 から始まります。
- 0 は通常、1 はディザ合成、2 は比較(暗)、3 は乗算、4 は焼き込みカラー、5 は
焼き込み(リニア)、6 は比較(明)、7 はスクリーン、8 は覆い焼きカラー、9 は
覆い焼き(リニア) - 加算、10 は加算、11 はオーバーレイ、12 はソフトライト、13 は
ハードライト、14 はビビッドライト、15 はリニアライト、16 はピンライト、17 は
ハードミックス、18 は差分、19 は除外、20 は減算、21 は除算、22 は色相、23 は彩度、
24 はカラー、25 は輝度、26 はカラー比較(明)、27 は背景、28 はカラー比較(暗)、
29 は削除、30 は背景でクリッピング、31 は重ならない部分のみ、32 は色反転マスクです。
- 範囲外の値や数値ではない値は通常として扱います。
- MoonSharp とネイティブの両エンジンで、`obj.draw` と `obj.drawpoly` の描画コマンドへ
合成モードを渡します。
### 2. 実行時のセルフ検証で正確性を担保
### 2. obj.setoption("draw_state", true / false)
GPU カーネルを初めて構築したとき、固定の 64×64 の検証用画像を実機の GPU で処理し、
その結果を CPU カーネルの結果と比較します。全チャンネルの差が許容範囲に収まった
プログラムだけを GPU で実行し、収まらない場合や検証を実行できない場合は CPU カーネルで
実行します。GPU の出力が CPU カーネルと食い違うことはありません。検証の結果はログに
記録します。
このエフェクトが作業画像を出力するかどうかを、スクリプトから明示できるようにしました。
---
- `true` を指定すると、`setpixel` や `obj.draw` を使わない場合でも作業画像を出力します。
- `false` を指定すると、このエフェクトの作業画像出力を抑制します。
- 未指定の場合は従来どおり、ピクセル変更や描画コマンドの有無に従います。
- MoonSharp とネイティブの両エンジンで動作します。
## 不具合修正
### 3. obj.setoption("drawtarget", "framebuffer" / "tempbuffer")
### GPU カーネルの座標原点のずれを修正
`obj.draw` / `obj.drawpoly` の描画先を切り替えられるようにしました。
GPU カーネルの HLSL は、ピクセル座標を「テクスチャ座標 × 寸法」で求めていました。
テクスチャ座標はピクセルの中心を指すため、求まる座標は CPU カーネルが用いる整数の
添字より 0.5 大きく、ループ変数 `x`・`y` を参照するスクリプトで結果がずれていました。
テクスチャ座標から 0.5 を引くように変更し、CPU カーネルの整数座標と一致させました。
- `"framebuffer"` は既定の描画先です。描画コマンドはフレームバッファへ合成されます。
- `"tempbuffer"` を指定すると、描画コマンドは作業用の `tmp` バッファへその場で合成されます。
- `obj.setoption("drawtarget", "tempbuffer", w, h)` のように幅と高さを渡すと、そのサイズで
`tmp` バッファを用意します。
- `tmp` へ描いた結果は `obj.copybuffer("obj", "tmp")` で作業画像へ戻せます。
- `tempbuffer` への合成は通常のソースオーバーで行い、`blend` はフレームバッファへの描画に
適用します。
- 描画先は毎フレーム既定の `"framebuffer"` へ戻ります。
- MoonSharp とネイティブの両エンジンで動作します。
### GPU カーネルの出力の丸めを修正
### 4. obj.setanchor(name, count [, option, ...])
アンカー座標を Lua 変数へ格納する `obj.setanchor` を追加しました。
- `name` で指定した名前の Lua 変数へ、`{x0, y0, x1, y1, ...}` の配列を作成します。
- `"xyz"` を指定した場合は `{x0, y0, z0, x1, y1, z1, ...}` の 3D 座標になります。
- `count` は 0〜32 に制限され、戻り値は実際に設置した個数です。
- 保存済みの座標がある場合はその値を使い、無い場合は 8 列の既定グリッド座標を使います。
- `"line"` / `"loop"` / `"star"` / `"arm"` の線結び指定と、`"xyz"` の 3D 指定を受け付けます。
- `name` に `"track"` を指定するトラックバー連携は未対応で、0 を返します。
- MoonSharp とネイティブの両エンジンで同じ座標テーブルを受け取れるようにしました。
### 5. 内蔵ドキュメントの更新
同梱される `LuaScript/docs/LuaScript.*.txt` を更新し、`blend`、`draw_state`、
`drawtarget`、`obj.setanchor` の説明を各言語へ追加しました。
Direct2D は出力を四捨五入で 8 ビットへ量子化する一方、CPU カーネルは切り捨てていた
ため、両者に系統的な 1 階調のずれがありました。シェーダ側で各チャンネルを切り捨てて
から量子化するように変更し、丸め方を CPU カーネルへ統一しました。
---
## 互換性・後方互換
- `blend` の既定値は 0 の通常です。指定しない既存スクリプトの合成結果は変わりません。
- `drawtarget` の既定値は `"framebuffer"` です。フレームをまたいで前回の描画先は持ち越しません。
- `draw_state` を指定しない場合は、従来どおりピクセル変更や描画コマンドに応じて出力します。
- `obj.setanchor` を含むスクリプトは、自動判定では描画 API を使うスクリプトとして扱います。
ネイティブで実行する場合は、従来どおり明示ディレクティブを使えます。
- `tempbuffer` への描画は通常合成です。`blend` による合成モード指定は、フレームバッファへの
`obj.draw` / `obj.drawpoly` に適用されます。
- `obj.setanchor("track", ...)` によるトラックバー連携は未対応で、0 を返します。
- スクリプトの書き方と API に変更はありません。
- `--!cpu` は従来どおり CPU カーネルで実行します。`--!gpu` は GPU カーネルで実行しますが、
検証に通らない場合は CPU カーネルへ切り替え、一度だけ警告を記録します。
- 指定の無いカーネルは、検証に通れば GPU、通らなければ CPU で実行します。いずれも
出力は CPU カーネルと許容差の範囲で一致します。
- GPU カーネルは浮動小数点で計算するため、CPU カーネルと 1 階調程度異なることが
あります。この差が許容範囲に収まることを検証で確認したプログラムだけを GPU で
実行します。
- GPU を利用できない環境では、従来どおり CPU カーネルで実行します。
---
## 内部実装
- YMM4 の `Blend` 列挙値へ番号を対応させる `BlendModeMap` を追加し、`DrawCommand` へ
合成モード番号を持たせました。
- `DrawCompositor` は通常以外の合成モードで `DrawImage` / `BlendImage` を使い、Opacity の
出力をキャッシュして毎描画ごとの COM オブジェクト確保を避けるようにしました。
- `SoftwareCompositor` を追加し、MoonSharp 側で最近傍または線形補間による
`obj.draw` / `obj.drawpoly` の `tempbuffer` 合成を行えるようにしました。
- ネイティブワーカー側にも同等のソフトウェア合成処理を追加しました。
- `AviUtlScriptContext` に `DrawStateOverride`、描画先状態、アンカー入力元、アンカー要求一覧を
追加しました。描画先が `tempbuffer` の場合は `DrawCommand` を通常の描画キューへ積まず、
その場で `tmp` バッファへ合成します。
- `LuaAnchorPoint` と `AnchorSupport` を追加し、アンカー数の制限、オプション解析、既定座標、
保存済み座標の解決、ドラッグ後の座標更新を分離しました。
- アンカー要求から生成した `VideoEffectController` を `DrawDescription.Controllers` へ追加し、
YMM4 のプレビュー操作へ渡すようにしました。
- アンカー座標の変更をキャッシュキーへ含めるため、エフェクト側へ `AnchorVersion` を追加しました。
- ネイティブプロトコルへ `draw_state` の書き戻しフィールドと `setanchor` コールバック種別を
追加しました。`LuaJitWorker` は `draw` / `drawpoly` の合成モード、`draw_state`、
`setanchor` の座標解決をワーカーとやり取りします。
- ネイティブワーカーでは `drawtarget` 用の `tmp` バッファ、`obj.setanchor`、
`draw_state` の書き戻しを実装しました。
- ネイティブワーカーの `obj.copybuffer` は、`tmp` や名前付きキャッシュへ書き込むときに
バッファを複製するようにしました。
- `ScriptDirective` は `obj.setanchor` を描画 API として検出します。
- `NativeFieldMap` から未使用の `Epsilon` 定数を削除しました。
- `AnchorSupportTests` と `SoftwareCompositorTests` を追加し、ネイティブ往復テストへ
`blend`、`draw_state`、`setanchor`、`drawtarget` の検証を追加しました。
- `HlslKernelEmitter` の座標を「テクスチャ座標 × 寸法 - 0.5」へ、出力の各チャンネルを
`floor(clamp(...))` へ変更し、CPU カーネルの整数座標と切り捨てへ揃えました。
- `GpuKernel` へ `Verify` を追加しました。検証用画像を効果で描画して読み戻し、
`CpuKernel` の結果と比較します。差が許容範囲に収まらない場合は GPU カーネルを
採用しません。
- `LuaScriptEffectProcessor` の `GetGpuKernel` は検証に通った GPU カーネルだけを返し、
判定をプログラム単位でキャッシュします。`ExecuteKernelLane` は指定が無いときと
`--!gpu` のときに検証済みの GPU カーネルを優先し、無ければ CPU カーネルで実行します。
- テストへ HLSL の座標原点と出力の丸めを検証するケースを追加しました(全 2994 件)。
GPU カーネルの実行と検証は実機の GPU が必要なため、YMM4 上での確認が対象です。
+1 -1
ファイルの表示
@@ -1,5 +1,5 @@
========================================
Luaスクリプト for YMM4 v1.11.0
Luaスクリプト for YMM4 v1.11.4
========================================
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
ピクセルを直接制御できるプラグインです。
+82
ファイルの表示
@@ -0,0 +1,82 @@
using System.Numerics;
namespace LuaScript.Tests
{
public class DrawTransformTests
{
[Fact]
public void TryResolve_Affine_MapsSourceCenterToOffset()
{
var command = new DrawCommand(10d, 20d, 0d, 1d, 1d, 0d);
Assert.True(DrawTransform.TryResolve(command, 4, 6, out var matrix));
var mapped = Vector2.Transform(new Vector2(2f, 3f), matrix);
Assert.Equal(10d, mapped.X, 3);
Assert.Equal(20d, mapped.Y, 3);
}
[Fact]
public void TryResolve_Affine_AppliesZoomAndAspect()
{
var command = new DrawCommand(0d, 0d, 0d, 2d, 1d, 0.5d);
Assert.True(DrawTransform.TryResolve(command, 2, 2, out var matrix));
var mapped = Vector2.Transform(new Vector2(2f, 2f), matrix);
Assert.Equal(3d, mapped.X, 3);
Assert.Equal(1d, mapped.Y, 3);
}
[Fact]
public void TryResolve_Affine_ClampsAspect()
{
var command = new DrawCommand(0d, 0d, 0d, 2d, 1d, -3d);
Assert.False(DrawTransform.TryResolve(command, 2, 2, out _));
}
[Fact]
public void TryResolve_ZeroZoom_Fails()
{
var command = new DrawCommand(0d, 0d, 0d, 0d, 1d, 0d);
Assert.False(DrawTransform.TryResolve(command, 2, 2, out _));
}
[Fact]
public void TryResolve_NegativeZoom_Mirrors()
{
var command = new DrawCommand(0d, 0d, 0d, -1d, 1d, 0d);
Assert.True(DrawTransform.TryResolve(command, 2, 2, out var matrix));
var mapped = Vector2.Transform(new Vector2(2f, 2f), matrix);
Assert.Equal(-1d, mapped.X, 3);
Assert.Equal(-1d, mapped.Y, 3);
}
[Fact]
public void TryResolve_IdentityPoly_YieldsIdentity()
{
double[] poly =
[
0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 2, 0,
0, 0, 2, 0, 2, 2, 0, 2,
1,
];
var command = new DrawCommand(0d, 0d, 0d, 1d, 1d, 0d, poly);
Assert.True(DrawTransform.TryResolve(command, 2, 2, out var matrix));
Assert.Equal(Matrix3x2.Identity, matrix);
}
[Fact]
public void TryResolve_DegeneratePoly_Fails()
{
var command = new DrawCommand(0d, 0d, 0d, 1d, 1d, 0d, new double[DrawPolyMath.Length]);
Assert.False(DrawTransform.TryResolve(command, 2, 2, out _));
}
}
}
+137
ファイルの表示
@@ -0,0 +1,137 @@
using System;
namespace LuaScript.Tests
{
public class FallbackCompositorTests
{
private sealed class RecordingCompositor : IBufferCompositor
{
public int Calls;
public byte[]? LastDst;
public byte[]? LastSrc;
public DrawCommand LastCommand;
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
{
Calls++;
LastDst = dst;
LastSrc = src;
LastCommand = command;
return true;
}
}
private sealed class RejectingCompositor : IBufferCompositor
{
public int Calls;
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
{
Calls++;
return false;
}
}
private sealed class ThrowingCompositor : IBufferCompositor
{
public int Calls;
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
{
Calls++;
throw new InvalidOperationException("device lost");
}
}
private sealed class DisposableCompositor : IBufferCompositor, IDisposable
{
public bool Disposed;
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command) => true;
public void Dispose() => Disposed = true;
}
private static readonly DrawCommand Command = new(1d, 2d, 0d, 1d, 1d, 0d);
[Fact]
public void TryCompose_PrimarySucceeds_FallbackIsNotUsed()
{
var primary = new RecordingCompositor();
var fallback = new RecordingCompositor();
var compositor = new FallbackCompositor(primary, fallback);
Assert.True(compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
Assert.Equal(1, primary.Calls);
Assert.Equal(0, fallback.Calls);
Assert.False(compositor.IsDegraded);
}
[Fact]
public void TryCompose_PrimaryThrows_FallbackReceivesSameArguments()
{
var primary = new ThrowingCompositor();
var fallback = new RecordingCompositor();
Exception? reported = null;
var compositor = new FallbackCompositor(primary, fallback, ex => reported = ex);
var dst = new byte[4];
var src = new byte[4];
Assert.True(compositor.TryCompose(dst, 1, 1, src, 1, 1, Command));
Assert.Equal(1, fallback.Calls);
Assert.Same(dst, fallback.LastDst);
Assert.Same(src, fallback.LastSrc);
Assert.Equal(Command, fallback.LastCommand);
Assert.IsType<InvalidOperationException>(reported);
Assert.True(compositor.IsDegraded);
}
[Fact]
public void TryCompose_AfterFailure_PrimaryIsSkippedAndDegradationReportedOnce()
{
var primary = new ThrowingCompositor();
var fallback = new RecordingCompositor();
int reports = 0;
var compositor = new FallbackCompositor(primary, fallback, _ => reports++);
compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command);
compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command);
Assert.Equal(1, primary.Calls);
Assert.Equal(2, fallback.Calls);
Assert.Equal(1, reports);
}
[Fact]
public void TryCompose_PrimaryRejects_FallbackIsUsedWithoutDegradation()
{
var primary = new RejectingCompositor();
var fallback = new RecordingCompositor();
int reports = 0;
var compositor = new FallbackCompositor(primary, fallback, _ => reports++);
Assert.True(compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
Assert.True(compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
Assert.Equal(2, primary.Calls);
Assert.Equal(2, fallback.Calls);
Assert.Equal(0, reports);
Assert.False(compositor.IsDegraded);
}
[Fact]
public void Dispose_DisposesDisposableLanes()
{
var primary = new DisposableCompositor();
var fallback = new DisposableCompositor();
var compositor = new FallbackCompositor(primary, fallback);
compositor.Dispose();
Assert.True(primary.Disposed);
Assert.True(fallback.Disposed);
}
}
}
+15
ファイルの表示
@@ -31,6 +31,21 @@ namespace LuaScript.Tests
Assert.Contains("inB", hlsl);
}
[Fact]
public void CoordinatesUsePixelCenterOrigin()
{
string hlsl = HlslKernelEmitter.Emit(Extract(Grayscale));
Assert.Contains(" - 0.5;", hlsl);
}
[Fact]
public void OutputTruncatesToMatchCpuKernel()
{
string hlsl = HlslKernelEmitter.Emit(Extract(Grayscale));
Assert.Contains("float oR = floor(clamp((", hlsl);
Assert.Contains("float oA = floor(outA) / 255.0;", hlsl);
}
[Fact]
public void ThresholdEmitsTernary()
{
+5
ファイルの表示
@@ -4,6 +4,7 @@
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPackable>false</IsPackable>
</PropertyGroup>
@@ -33,7 +34,11 @@
<Compile Include="..\LuaScript\Engine\LuaJitWorker.cs" Link="Linked\LuaJitWorker.cs" />
<Compile Include="..\LuaScript\DrawCommand.cs" Link="Linked\DrawCommand.cs" />
<Compile Include="..\LuaScript\DrawPolyMath.cs" Link="Linked\DrawPolyMath.cs" />
<Compile Include="..\LuaScript\DrawTransform.cs" Link="Linked\DrawTransform.cs" />
<Compile Include="..\LuaScript\IBufferCompositor.cs" Link="Linked\IBufferCompositor.cs" />
<Compile Include="..\LuaScript\SoftwareCompositor.cs" Link="Linked\SoftwareCompositor.cs" />
<Compile Include="..\LuaScript\FallbackCompositor.cs" Link="Linked\FallbackCompositor.cs" />
<Compile Include="..\LuaScript\SynchronizedCompositor.cs" Link="Linked\SynchronizedCompositor.cs" />
<Compile Include="..\LuaScript\Anchor\LuaAnchorPoint.cs" Link="Linked\LuaAnchorPoint.cs" />
<Compile Include="..\LuaScript\Anchor\AnchorSupport.cs" Link="Linked\AnchorSupport.cs" />
<Compile Include="..\LuaScript\SceneObjectInfo.cs" Link="Linked\SceneObjectInfo.cs" />
+148 -35
ファイルの表示
@@ -42,7 +42,7 @@ namespace LuaScript.Tests
bool ok = _worker.Execute(
"obj.rz = obj.time * 90\nobj.alpha = 128",
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.False(dirty);
@@ -65,7 +65,7 @@ namespace LuaScript.Tests
bool ok = _worker.Execute(
"obj.x = string.len(obj.text) obj.alpha = string.len(obj.file_image)",
fields, stringParameters, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
fields, stringParameters, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(5d, fields[NativeProtocol.X]);
@@ -84,7 +84,7 @@ namespace LuaScript.Tests
var fieldsLarge = Fields(2, 2, 0d);
bool ok = _worker.Execute(
"obj.x = string.len(obj.text)",
fieldsLarge, large, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
fieldsLarge, large, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(big.Length, fieldsLarge[NativeProtocol.X]);
@@ -92,7 +92,7 @@ namespace LuaScript.Tests
var fieldsSmall = Fields(2, 2, 0d);
ok = _worker.Execute(
"obj.x = string.len(obj.text)",
fieldsSmall, small, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
fieldsSmall, small, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error);
Assert.Equal(2d, fieldsSmall[NativeProtocol.X]);
}
@@ -124,7 +124,7 @@ namespace LuaScript.Tests
"local gray = r*0.299 + g*0.587 + b*0.114 " +
"obj.setpixel(x,y,gray,gray,gray,a) end end";
bool ok = _worker.Execute(script, fields, NoStringParams, pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
bool ok = _worker.Execute(script, fields, 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);
@@ -159,7 +159,7 @@ namespace LuaScript.Tests
"local gray=r*0.299+g*0.587+b*0.114 " +
"pd:set(base+1,gray) pd:set(base+2,gray) pd:set(base+3,gray) end end";
bool ok = _worker.Execute(script, fields, NoStringParams, pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
bool ok = _worker.Execute(script, fields, 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);
@@ -195,7 +195,7 @@ namespace LuaScript.Tests
for (int k = 1; k <= 5; k++)
{
var fields = Fields(2, 2, k);
bool ok = _worker.Execute("obj.x = obj.time * 10", fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
bool ok = _worker.Execute("obj.x = obj.time * 10", fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(k * 10d, fields[NativeProtocol.X]);
}
@@ -210,12 +210,12 @@ namespace LuaScript.Tests
var fields = Fields(2, 2, 0d);
bool timedOut = _worker.Execute(
"local x=0 while true do x=x+1 end", fields, NoStringParams, pixels, 2, 2, 1500, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
"local x=0 while true do x=x+1 end", fields, NoStringParams, () => pixels, 2, 2, 1500, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.False(timedOut);
Assert.Contains("timed out", error);
var fields2 = Fields(2, 2, 3d);
bool ok = _worker.Execute("obj.x = obj.time", fields2, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
bool ok = _worker.Execute("obj.x = obj.time", fields2, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error);
Assert.Equal(3d, fields2[NativeProtocol.X]);
}
@@ -237,7 +237,7 @@ namespace LuaScript.Tests
"obj.zoom = o.zoom obj.rz = o.rz obj.alpha = o.alpha " +
"obj.sx = o.sy obj.rzr = o.rzr";
bool ok = _worker.Execute(script, fields, NoStringParams, pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
bool ok = _worker.Execute(script, fields, NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(12d, fields[NativeProtocol.X]);
@@ -269,13 +269,13 @@ namespace LuaScript.Tests
"local b = obj.getobject(\"a\") " +
"obj.x = a.x + b.x";
bool ok = _worker.Execute(script, Fields(2, 2, 0d), NoStringParams, pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
bool ok = _worker.Execute(script, Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(1, calls);
var fields = Fields(2, 2, 0d);
x = 20d;
ok = _worker.Execute(script, fields, NoStringParams, pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
ok = _worker.Execute(script, fields, NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error);
Assert.Equal(2, calls);
Assert.Equal(40d, fields[NativeProtocol.X]);
@@ -292,7 +292,7 @@ namespace LuaScript.Tests
const string script =
"local o = obj.getobject(\"missing\") obj.x = o == nil and 1 or 0";
bool ok = _worker.Execute(script, fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
bool ok = _worker.Execute(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(1d, fields[NativeProtocol.X]);
@@ -310,7 +310,7 @@ namespace LuaScript.Tests
bool ok = _worker.Execute(
"obj.draw() obj.draw(10, 20, 30, 2, 0.5, 0.25)",
fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
@@ -331,7 +331,7 @@ namespace LuaScript.Tests
bool ok = _worker.Execute(
"obj.drawpoly(0,0,0, 10,0,0, 10,10,0, 0,10,0)",
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
@@ -353,7 +353,7 @@ namespace LuaScript.Tests
bool ok = _worker.Execute(
"obj.drawpoly(0,0,0, 8,0,0, 8,8,0, 0,8,0, 1,1, 3,1, 3,3, 1,3, 0.5)",
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
@@ -374,7 +374,7 @@ namespace LuaScript.Tests
bool ok = _worker.Execute(
"obj.setoption('antialias', 0) obj.x = obj.getoption('antialias') obj.y = obj.getoption('unset')",
fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
@@ -393,7 +393,7 @@ namespace LuaScript.Tests
bool ok = _worker.Execute(
"obj.draw() obj.setoption('antialias', 0) obj.draw()",
Fields(2, 2, 0d), NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
@@ -413,7 +413,7 @@ namespace LuaScript.Tests
bool ok = _worker.Execute(
"obj.draw() obj.setoption('blend', 3) obj.draw()",
Fields(2, 2, 0d), NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
@@ -433,7 +433,7 @@ namespace LuaScript.Tests
bool ok = _worker.Execute(
"obj.setoption('blend', 11) obj.drawpoly(0,0,0, 10,0,0, 10,10,0, 0,10,0)",
Fields(4, 4, 0d), NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
Fields(4, 4, 0d), NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
@@ -451,7 +451,7 @@ namespace LuaScript.Tests
var fTrue = Fields(2, 2, 0d);
bool okTrue = _worker.Execute(
"obj.setoption('draw_state', true)",
fTrue, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
fTrue, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? errorTrue);
Assert.True(okTrue, errorTrue);
Assert.Equal(1d, fTrue[NativeProtocol.DrawState]);
@@ -459,7 +459,7 @@ namespace LuaScript.Tests
var fFalse = Fields(2, 2, 0d);
bool okFalse = _worker.Execute(
"obj.setoption('draw_state', false)",
fFalse, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
fFalse, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? errorFalse);
Assert.True(okFalse, errorFalse);
Assert.Equal(2d, fFalse[NativeProtocol.DrawState]);
@@ -467,7 +467,7 @@ namespace LuaScript.Tests
var fUnset = Fields(2, 2, 0d);
bool okUnset = _worker.Execute(
"obj.x = 1",
fUnset, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
fUnset, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? errorUnset);
Assert.True(okUnset, errorUnset);
Assert.Equal(0d, fUnset[NativeProtocol.DrawState]);
@@ -503,7 +503,7 @@ namespace LuaScript.Tests
"obj.y = pos[1]\n" +
"obj.z = pos[3]";
bool ok = _worker.Execute(script, fields, NoStringParams, pixels, 2, 2, 5000,
bool ok = _worker.Execute(script, fields, NoStringParams, () => pixels, 2, 2, 5000,
NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, setAnchor,
out _, out _, out _, out _, out _, out string? error);
@@ -534,7 +534,7 @@ namespace LuaScript.Tests
"obj.copybuffer('obj','tmp')";
bool ok = _worker.Execute(
script, fields, NoStringParams, pixels, 2, 2, 5000,
script, fields, NoStringParams, () => pixels, 2, 2, 5000,
NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
@@ -581,7 +581,7 @@ namespace LuaScript.Tests
bool ok = _worker.Execute(
"obj.setfont('Meiryo', 40, 3, 0x112233) obj.load('text', 'Hi')",
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, loadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, loadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
Assert.True(ok, error);
@@ -621,7 +621,7 @@ namespace LuaScript.Tests
bool ok = _worker.Execute(
"obj.load('image', 'C:/sample.png')",
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, loadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, loadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
Assert.True(ok, error);
@@ -658,7 +658,7 @@ namespace LuaScript.Tests
bool ok = _worker.Execute(
"obj.load('movie', 'C:/clip.mp4', 1.5)",
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, loadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, loadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
Assert.True(ok, error);
@@ -683,7 +683,7 @@ namespace LuaScript.Tests
bool ok = _worker.Execute(
"obj.x = obj.getvalue('track0') obj.y = obj.getvalue('alpha') obj.z = obj.getvalue('unknown')",
fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
@@ -710,7 +710,7 @@ namespace LuaScript.Tests
"for y=0,obj.h-1 do for x=0,obj.w-1 do obj.setpixel(x,y,0,0,0,0) end end " +
"obj.copybuffer('obj','tmp')";
bool ok = _worker.Execute(script, fields, NoStringParams, pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
bool ok = _worker.Execute(script, fields, 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);
@@ -729,14 +729,127 @@ namespace LuaScript.Tests
stored[3] = 255; stored[7] = 255; stored[11] = 255; stored[15] = 255;
var save = (byte[])stored.Clone();
bool ok = _worker.Execute("obj.copybuffer('cache:foo','obj')", Fields(w, h, 0d), NoStringParams, save, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
bool ok = _worker.Execute("obj.copybuffer('cache:foo','obj')", Fields(w, h, 0d), NoStringParams, () => save, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
var blank = new byte[w * h * 4];
ok = _worker.Execute("obj.copybuffer('obj','cache:foo')", Fields(w, h, 0d), NoStringParams, blank, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out error);
ok = _worker.Execute("obj.copybuffer('obj','cache:foo')", Fields(w, h, 0d), NoStringParams, () => blank, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out byte[]? restored, out _, out _, out error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(stored, blank);
Assert.NotNull(restored);
Assert.Equal(stored, restored!.AsSpan(0, stored.Length).ToArray());
}
[Fact]
public void TransformScript_NeverRequestsPixels()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
int loads = 0;
Func<byte[]> loadPixels = () => { loads++; return pixels; };
var fields = Fields(2, 2, 1d);
bool ok = _worker.Execute(
"obj.x = obj.time * 10 obj.draw()",
fields, NoStringParams, loadPixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.False(dirty);
Assert.Equal(0, loads);
Assert.Equal(10d, fields[NativeProtocol.X]);
}
[Fact]
public void PixelScript_RequestsPixelsExactlyOnce()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
pixels[3] = 255; pixels[7] = 255; pixels[11] = 255; pixels[15] = 255;
int loads = 0;
Func<byte[]> loadPixels = () => { loads++; return pixels; };
bool ok = _worker.Execute(
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a = obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end",
Fields(2, 2, 0d), NoStringParams, loadPixels, 2, 2, 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, loads);
}
[Fact]
public void Worker_SurvivesSizeChanges_PreservingCache()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var stored = new byte[2 * 2 * 4];
for (int i = 0; i < stored.Length; i++)
stored[i] = (byte)((i * 41 + 13) & 0xFF);
stored[3] = 255; stored[7] = 255; stored[11] = 255; stored[15] = 255;
bool ok = _worker.Execute("obj.copybuffer('cache:sz','obj')", Fields(2, 2, 0d), NoStringParams, () => stored, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
var bigger = new byte[4 * 4 * 4];
ok = _worker.Execute("obj.copybuffer('obj','cache:sz')", Fields(4, 4, 0d), NoStringParams, () => bigger, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out bool bufferReplaced, out byte[]? restored, out int rw, out int rh, out error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.True(bufferReplaced);
Assert.Equal(2, rw);
Assert.Equal(2, rh);
Assert.NotNull(restored);
Assert.Equal(stored, restored!.AsSpan(0, stored.Length).ToArray());
}
[Fact]
public void BareGlobals_MirrorObjFields()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 2d);
fields[NativeProtocol.Frame] = 10d;
fields[NativeProtocol.TotalFrame] = 20d;
fields[NativeProtocol.Framerate] = 30d;
fields[NativeProtocol.Layer] = 3d;
fields[NativeProtocol.TimelineFrame] = 100d;
fields[NativeProtocol.TimelineTime] = 4d;
const string script =
"obj.x = time * 10 + frame " +
"obj.y = totalframe + framerate + layer " +
"obj.z = timelineframe + timelinetime";
bool ok = _worker.Execute(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(30d, fields[NativeProtocol.X]);
Assert.Equal(53d, fields[NativeProtocol.Y]);
Assert.Equal(104d, fields[NativeProtocol.Z]);
}
[Fact]
public void UserGlobals_AreResetBetweenRuns()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
bool ok = _worker.Execute(
"leak = 42 obj.leaked = 7 scene.custom = 1 ymm4.custom = 2",
Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
var fields = Fields(2, 2, 0d);
ok = _worker.Execute(
"obj.x = (leak == nil and 1 or 0) + (obj.leaked == nil and 10 or 0) + (scene.custom == nil and 100 or 0) + (ymm4.custom == nil and 1000 or 0)",
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error);
Assert.Equal(1111d, fields[NativeProtocol.X]);
}
[Fact]
@@ -747,12 +860,12 @@ namespace LuaScript.Tests
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
bool ok = _worker.Execute("obj.x = missing.value", fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
bool ok = _worker.Execute("obj.x = missing.value", fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.False(ok);
Assert.False(string.IsNullOrEmpty(error));
var fields2 = Fields(2, 2, 7d);
bool ok2 = _worker.Execute("obj.x = obj.time", fields2, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
bool ok2 = _worker.Execute("obj.x = obj.time", fields2, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
Assert.True(ok2, error);
Assert.Equal(7d, fields2[NativeProtocol.X]);
}
+10 -7
ファイルの表示
@@ -31,18 +31,21 @@ namespace LuaScript.Tests
}
[Theory]
[InlineData("obj.rz = time * 90", "MoonSharp")]
[InlineData(null, "MoonSharp")]
[InlineData("", "MoonSharp")]
[InlineData("obj.rz = time * 90", "Native")]
[InlineData("local r,g,b,a = obj.getpixel(0,0)", "Native")]
[InlineData("obj.setpixel(0,0,255,0,0)", "Native")]
[InlineData("local pd = obj.getpixeldata()", "Native")]
[InlineData("--!moonsharp\nobj.setpixel(0,0,1,1,1)", "MoonSharp")]
[InlineData("--!native\nobj.rz = 1", "Native")]
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)", "MoonSharp")]
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)\nlocal r = obj.getpixel(0,0)", "Native")]
[InlineData("obj.draw()", "MoonSharp")]
[InlineData("obj.draw()\nlocal r = obj.getpixel(0,0)", "Native")]
[InlineData("--!native\nobj.load(\"figure\", \"円\", 0xff0000, 100)", "Native")]
public void ResolveAuto_RoutesPixelScriptsToNative(string script, string expected)
[InlineData("--!gpu\nfunction pixel() end", "Gpu")]
[InlineData("--!cpu\nfunction pixel() end", "Cpu")]
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)", "Native")]
[InlineData("obj.draw()", "Native")]
[InlineData("obj.setoption('blend', 1)", "Native")]
[InlineData("obj.setanchor('pos', 2)", "Native")]
public void ResolveAuto_DefaultsToNative(string? script, string expected)
{
Assert.Equal(expected, ScriptDirective.ResolveAuto(script).ToString());
}
+53
ファイルの表示
@@ -61,6 +61,59 @@ namespace LuaScript.Tests
Assert.Equal(0, value);
}
[Fact]
public void TryCompose_AffineCommand_MatchesDrawInto()
{
var src = Solid(1, 1, 10, 20, 30, 255);
var actual = new byte[3 * 3 * 4];
var expected = new byte[3 * 3 * 4];
var command = new DrawCommand(1.5, 1.5, 0d, 1d, 1d, 0d, Antialias: 0d);
Assert.True(SoftwareCompositor.Instance.TryCompose(actual, 3, 3, src, 1, 1, command));
SoftwareCompositor.DrawInto(expected, 3, 3, src, 1, 1, 1.5, 1.5, 1d, 0d, 1d, linear: false);
Assert.Equal(expected, actual);
}
[Fact]
public void TryCompose_PolyCommand_MatchesDrawPolyInto()
{
var src = Solid(2, 2, 40, 50, 60, 255);
var actual = new byte[2 * 2 * 4];
var expected = new byte[2 * 2 * 4];
double[] poly =
[
0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 2, 0,
0, 0, 2, 0, 2, 2, 0, 2,
1,
];
var command = new DrawCommand(0d, 0d, 0d, 1d, 1d, 0d, poly, Antialias: 0d);
Assert.True(SoftwareCompositor.Instance.TryCompose(actual, 2, 2, src, 2, 2, command));
SoftwareCompositor.DrawPolyInto(expected, 2, 2, src, 2, 2, poly, 1d, linear: false);
Assert.Equal(expected, actual);
}
[Fact]
public void TryCompose_AntialiasCommand_UsesLinearSampling()
{
var src = new byte[2 * 1 * 4];
src[3] = 255;
src[4] = 255;
src[5] = 255;
src[6] = 255;
src[7] = 255;
var actual = new byte[4 * 1 * 4];
var expected = new byte[4 * 1 * 4];
var command = new DrawCommand(2d, 0.5, 0d, 2d, 1d, 0d, Antialias: 1d);
Assert.True(SoftwareCompositor.Instance.TryCompose(actual, 4, 1, src, 2, 1, command));
SoftwareCompositor.DrawInto(expected, 4, 1, src, 2, 1, 2d, 0.5, 2d, 0d, 1d, linear: true);
Assert.Equal(expected, actual);
}
[Fact]
public void DrawPolyInto_IdentityAffine_CopiesSource()
{
+88
ファイルの表示
@@ -0,0 +1,88 @@
using System;
using System.Threading;
namespace LuaScript.Tests
{
public class SynchronizedCompositorTests
{
private sealed class GateObservingCompositor(SemaphoreSlim gate, bool result) : IBufferCompositor
{
public int Calls;
public int GateCountDuringCompose = -1;
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
{
Calls++;
GateCountDuringCompose = gate.CurrentCount;
return result;
}
}
private sealed class ThrowingCompositor : IBufferCompositor
{
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command) =>
throw new InvalidOperationException("device lost");
}
private sealed class DisposableCompositor : IBufferCompositor, IDisposable
{
public bool Disposed;
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command) => true;
public void Dispose() => Disposed = true;
}
private static readonly DrawCommand Command = new(0d, 0d, 0d, 1d, 1d, 0d);
[Fact]
public void TryCompose_HoldsGateDuringComposeAndReleasesAfter()
{
using var gate = new SemaphoreSlim(1, 1);
var inner = new GateObservingCompositor(gate, result: true);
var compositor = new SynchronizedCompositor(inner, gate);
Assert.True(compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
Assert.Equal(1, inner.Calls);
Assert.Equal(0, inner.GateCountDuringCompose);
Assert.Equal(1, gate.CurrentCount);
}
[Fact]
public void TryCompose_PassesRejectionThrough()
{
using var gate = new SemaphoreSlim(1, 1);
var inner = new GateObservingCompositor(gate, result: false);
var compositor = new SynchronizedCompositor(inner, gate);
Assert.False(compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
Assert.Equal(1, gate.CurrentCount);
}
[Fact]
public void TryCompose_ReleasesGateWhenInnerThrows()
{
using var gate = new SemaphoreSlim(1, 1);
var compositor = new SynchronizedCompositor(new ThrowingCompositor(), gate);
Assert.Throws<InvalidOperationException>(() =>
compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
Assert.Equal(1, gate.CurrentCount);
}
[Fact]
public void Dispose_DisposesInnerButNotGate()
{
using var gate = new SemaphoreSlim(1, 1);
var inner = new DisposableCompositor();
var compositor = new SynchronizedCompositor(inner, gate);
compositor.Dispose();
Assert.True(inner.Disposed);
gate.Wait();
gate.Release();
}
}
}
+3 -5
ファイルの表示
@@ -91,6 +91,8 @@ namespace LuaScript
internal void ClearEffects() => _effectRequests.Clear();
internal IBufferCompositor Compositor { get; set; } = SoftwareCompositor.Instance;
private readonly List<DrawCommand> _drawCommands = [];
public IReadOnlyList<DrawCommand> DrawCommands => _drawCommands;
@@ -139,11 +141,7 @@ namespace LuaScript
_buffers["t"] = temp;
}
bool linear = command.Antialias != 0d;
if (command.Poly is { } poly)
SoftwareCompositor.DrawPolyInto(temp.Data, temp.Width, temp.Height, src, ImageWidth, ImageHeight, poly, command.Alpha, linear);
else
SoftwareCompositor.DrawInto(temp.Data, temp.Width, temp.Height, src, ImageWidth, ImageHeight, command.Ox, command.Oy, command.Zoom, command.Aspect, command.Alpha, linear);
Compositor.TryCompose(temp.Data, temp.Width, temp.Height, src, ImageWidth, ImageHeight, command);
}
private readonly Dictionary<string, (byte[] Data, int Width, int Height)> _buffers = new(StringComparer.Ordinal);
+13 -23
ファイルの表示
@@ -18,6 +18,7 @@ namespace LuaScript
private ID2D1Bitmap1? _source;
private ID2D1Bitmap1? _target;
private AffineTransform2D? _placement;
private ID2D1Image? _placementOutput;
private Opacity? _opacityEffect;
private ID2D1Image? _opacityOutput;
private int _sourceWidth;
@@ -70,7 +71,7 @@ namespace LuaScript
var dc = _ctx.DeviceContext;
var rt = (ID2D1RenderTarget)dc;
var savedTarget = dc.Target;
using var savedTarget = dc.Target;
dc.Target = _target;
dc.BeginDraw();
@@ -79,39 +80,23 @@ namespace LuaScript
for (int i = 0; i < commands.Count; i++)
{
var cmd = commands[i];
if (!DrawTransform.TryResolve(cmd, width, height, out var transform))
continue;
var interpolation = cmd.Antialias != 0d
? BitmapInterpolationMode.Linear
: BitmapInterpolationMode.NearestNeighbor;
var blend = BlendModeMap.Resolve(cmd.Blend);
if (cmd.Poly is { } poly)
{
if (!DrawPolyMath.TrySolveAffine(poly, out var affine))
continue;
rt.Transform = affine * toTarget;
DrawSource(rt, (float)Math.Clamp(poly[20], 0d, 1d), interpolation, blend);
continue;
}
double aspect = Math.Clamp(cmd.Aspect, -1d, 1d);
float zx = (float)(cmd.Zoom * (1d + aspect));
float zy = (float)(cmd.Zoom * (1d - aspect));
float opacity = (float)Math.Clamp(cmd.Alpha, 0d, 1d);
var matrix =
Matrix3x2.CreateTranslation(-width * 0.5f, -height * 0.5f) *
Matrix3x2.CreateScale(zx, zy) *
Matrix3x2.CreateTranslation((float)(cmd.Ox - originX), (float)(cmd.Oy - originY));
rt.Transform = matrix;
DrawSource(rt, opacity, interpolation, blend);
rt.Transform = transform * toTarget;
DrawSource(rt, (float)Math.Clamp(cmd.Alpha, 0d, 1d), interpolation, blend);
}
rt.Transform = Matrix3x2.Identity;
dc.EndDraw();
dc.Target = savedTarget;
_placement!.TransformMatrix = Matrix3x2.CreateTranslation(originX, originY);
return _placement.Output;
return _placementOutput!;
}
private void DrawSource(ID2D1RenderTarget rt, float opacity, BitmapInterpolationMode interpolation, Blend blend)
@@ -156,8 +141,10 @@ namespace LuaScript
if (_target is not null && _targetWidth == width && _targetHeight == height)
return;
_placementOutput?.Dispose();
_placement?.Dispose();
_target?.Dispose();
_placementOutput = null;
_placement = null;
_target = _ctx.DeviceContext.CreateEmptyBitmap(width, height, BitmapOptions.Target);
@@ -166,15 +153,18 @@ namespace LuaScript
_placement = new AffineTransform2D(_ctx.DeviceContext);
_placement.SetInput(0, _target, true);
_placementOutput = _placement.Output;
}
public void Dispose()
{
_placementOutput?.Dispose();
_placement?.Dispose();
_opacityOutput?.Dispose();
_opacityEffect?.Dispose();
_source?.Dispose();
_target?.Dispose();
_placementOutput = null;
_placement = null;
_opacityOutput = null;
_opacityEffect = null;
+29
ファイルの表示
@@ -0,0 +1,29 @@
using System;
using System.Numerics;
namespace LuaScript
{
internal static class DrawTransform
{
public static bool TryResolve(in DrawCommand command, int srcW, int srcH, out Matrix3x2 matrix)
{
if (command.Poly is { } poly)
return DrawPolyMath.TrySolveAffine(poly, out matrix);
double aspect = Math.Clamp(command.Aspect, -1d, 1d);
double zx = command.Zoom * (1d + aspect);
double zy = command.Zoom * (1d - aspect);
if (zx == 0d || zy == 0d)
{
matrix = Matrix3x2.Identity;
return false;
}
matrix =
Matrix3x2.CreateTranslation(-srcW * 0.5f, -srcH * 0.5f) *
Matrix3x2.CreateScale((float)zx, (float)zy) *
Matrix3x2.CreateTranslation((float)command.Ox, (float)command.Oy);
return true;
}
}
}
+137 -3
ファイルの表示
@@ -1,17 +1,30 @@
using System;
using System.Numerics;
using System.Runtime.InteropServices;
using Vortice.DCommon;
using Vortice.Direct2D1;
using Vortice.DXGI;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
namespace LuaScript.Engine.Kernel
{
internal sealed class GpuKernel : IDisposable
{
private const int VerifySize = 64;
private const int VerifyTolerance = 2;
private readonly IGraphicsDevicesAndContext _devices;
private readonly GpuKernelEffect _effect;
private readonly float[] _packed = new float[HlslKernelEmitter.ConstantFloatCount];
private readonly byte[] _bytes = new byte[HlslKernelEmitter.ConstantFloatCount * sizeof(float)];
private ID2D1Image? _output;
public GpuKernel(IGraphicsDevicesAndContext devices, KernelProgram program)
=> _effect = new GpuKernelEffect(devices, HlslKernelEmitter.Emit(program));
{
_devices = devices;
_effect = new GpuKernelEffect(devices, HlslKernelEmitter.Emit(program));
}
public bool IsReady => _effect.IsReady;
@@ -21,9 +34,130 @@ namespace LuaScript.Engine.Kernel
Buffer.BlockCopy(_packed, 0, _bytes, 0, _bytes.Length);
_effect.SetConstants(_bytes);
_effect.SetInput(0, input, true);
return _effect.Output;
return _output ??= _effect.Output;
}
public void Dispose() => _effect.Dispose();
public unsafe bool Verify(CpuKernel reference)
{
if (!IsReady)
return false;
var uniforms = KernelUniformBinding.Create();
for (int i = 0; i < uniforms.Length; i++)
uniforms[i] = (i % 7) + 1;
uniforms[(int)KernelUniform.Width] = VerifySize;
uniforms[(int)KernelUniform.Height] = VerifySize;
byte[] probe = BuildProbe(VerifySize);
byte[] expected = (byte[])probe.Clone();
reference.Execute(expected, VerifySize, VerifySize, uniforms);
var dc = (ID2D1DeviceContext)_devices.DeviceContext;
ID2D1Bitmap1? source = null;
ID2D1Bitmap1? target = null;
ID2D1Bitmap1? staging = null;
try
{
source = dc.CreateEmptyBitmap(VerifySize, VerifySize, BitmapOptions.Target);
fixed (byte* ptr = probe)
source.CopyFromMemory(new nint(ptr), VerifySize * 4);
target = dc.CreateEmptyBitmap(VerifySize, VerifySize, BitmapOptions.Target);
var stagingProps = new BitmapProperties1(
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
96f, 96f,
BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
staging = dc.CreateBitmap(new SizeI(VerifySize, VerifySize), nint.Zero, VerifySize * 4, stagingProps);
var output = Apply(source, uniforms);
using var savedTarget = dc.Target;
dc.Target = target;
try
{
dc.BeginDraw();
dc.Clear(null);
dc.DrawImage(output, new Vector2(0f, 0f));
dc.EndDraw();
}
finally
{
dc.Target = savedTarget;
}
staging.CopyFromBitmap(target);
byte[] actual = new byte[VerifySize * VerifySize * 4];
var mapped = staging.Map(MapOptions.Read);
try
{
if (mapped.Pitch == VerifySize * 4)
{
Marshal.Copy(mapped.Bits, actual, 0, actual.Length);
}
else
{
for (int row = 0; row < VerifySize; row++)
Marshal.Copy(mapped.Bits + mapped.Pitch * row, actual, row * VerifySize * 4, VerifySize * 4);
}
}
finally
{
staging.Unmap();
}
return WithinTolerance(expected, actual, VerifyTolerance);
}
catch (Exception ex)
{
Log.Default.Write("LuaScript: GPU kernel verification could not run; using the CPU kernel.", ex);
return false;
}
finally
{
source?.Dispose();
target?.Dispose();
staging?.Dispose();
}
}
private static byte[] BuildProbe(int size)
{
var buffer = new byte[size * size * 4];
ReadOnlySpan<int> alphas = [0, 64, 128, 200, 255];
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
int alpha = alphas[(x + y) % alphas.Length];
int r = x * 255 / (size - 1);
int g = y * 255 / (size - 1);
int b = (x + y) * 255 / (2 * (size - 1));
int p = (y * size + x) * 4;
buffer[p] = (byte)(b * alpha / 255);
buffer[p + 1] = (byte)(g * alpha / 255);
buffer[p + 2] = (byte)(r * alpha / 255);
buffer[p + 3] = (byte)alpha;
}
}
return buffer;
}
private static bool WithinTolerance(byte[] expected, byte[] actual, int tolerance)
{
if (expected.Length != actual.Length)
return false;
for (int i = 0; i < expected.Length; i++)
if (Math.Abs(expected[i] - actual[i]) > tolerance)
return false;
return true;
}
public void Dispose()
{
_output?.Dispose();
_output = null;
_effect.Dispose();
}
}
}
+12 -12
ファイルの表示
@@ -32,8 +32,8 @@ namespace LuaScript.Engine.Kernel
builder.Append(" float inG = clamp(src.g * invA * 255.0, 0.0, 255.0);\n");
builder.Append(" float inB = clamp(src.b * invA * 255.0, 0.0, 255.0);\n");
builder.Append(" float inA = srcA * 255.0;\n");
builder.Append(" float px = uv.x * ").Append(Uniform(KernelUniform.Width)).Append(";\n");
builder.Append(" float py = uv.y * ").Append(Uniform(KernelUniform.Height)).Append(";\n");
builder.Append(" float px = uv.x * ").Append(Uniform(KernelUniform.Width)).Append(" - 0.5;\n");
builder.Append(" float py = uv.y * ").Append(Uniform(KernelUniform.Height)).Append(" - 0.5;\n");
for (int i = 0; i < program.Bindings.Count; i++)
{
@@ -42,21 +42,21 @@ namespace LuaScript.Engine.Kernel
builder.Append(";\n");
}
builder.Append(" float outA = ");
builder.Append(" float outA = clamp(");
EmitExpression(builder, program.OutputA);
builder.Append(";\n");
builder.Append(" float alphaK = clamp(outA, 0.0, 255.0) / 255.0;\n");
builder.Append(", 0.0, 255.0);\n");
builder.Append(" float alphaK = outA / 255.0;\n");
builder.Append(" float oR = clamp((");
builder.Append(" float oR = floor(clamp((");
EmitExpression(builder, program.OutputR);
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
builder.Append(" float oG = clamp((");
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
builder.Append(" float oG = floor(clamp((");
EmitExpression(builder, program.OutputG);
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
builder.Append(" float oB = clamp((");
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
builder.Append(" float oB = floor(clamp((");
EmitExpression(builder, program.OutputB);
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
builder.Append(" float oA = clamp(outA, 0.0, 255.0) / 255.0;\n");
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
builder.Append(" float oA = floor(outA) / 255.0;\n");
builder.Append(" return float4(oR, oG, oB, oA);\n}\n");
return builder.ToString();
+62 -24
ファイルの表示
@@ -19,10 +19,9 @@ namespace LuaScript.Engine
private EventWaitHandle? _workEvent;
private EventWaitHandle? _doneEvent;
private Process? _process;
private int _width;
private int _height;
private int _stringParamsCapacity = NativeProtocol.MinStringParamsCapacity;
private long _pixelOffset = NativeProtocol.PixelOffset(NativeProtocol.MinStringParamsCapacity);
private long _allocatedSize;
private bool _alive;
private readonly byte[] _callbackTag = new byte[NativeProtocol.CallbackTagMax];
@@ -49,7 +48,7 @@ namespace LuaScript.Engine
string script,
double[] fields,
IReadOnlyDictionary<string, string> stringParameters,
byte[] pixels,
Func<byte[]> loadPixels,
int width,
int height,
int timeoutMs,
@@ -63,14 +62,14 @@ namespace LuaScript.Engine
Action<string, int, bool, int, double[]> setAnchor,
out bool pixelsDirty,
out bool bufferReplaced,
out byte[]? newPixels,
out byte[]? resultPixels,
out int resultWidth,
out int resultHeight,
out string? error)
{
pixelsDirty = false;
bufferReplaced = false;
newPixels = null;
resultPixels = null;
resultWidth = width;
resultHeight = height;
error = null;
@@ -92,7 +91,6 @@ namespace LuaScript.Engine
view.Write(NativeProtocol.OffHeight, height);
view.Write(NativeProtocol.OffScriptLen, scriptBytes.Length);
view.WriteArray(NativeProtocol.ScriptOffset, scriptBytes, 0, scriptBytes.Length);
view.WriteArray(_pixelOffset, pixels, 0, pixels.Length);
view.Write(NativeProtocol.OffPixelsDirty, 0);
view.Write(NativeProtocol.OffErrorLen, 0);
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
@@ -100,6 +98,7 @@ namespace LuaScript.Engine
_workEvent!.Set();
byte[]? uploadedPixels = null;
var stopwatch = Stopwatch.StartNew();
int status;
while (true)
@@ -116,7 +115,15 @@ namespace LuaScript.Engine
if (status != NativeProtocol.StatusCallback)
break;
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, addDraw, setAnchor);
if (view.ReadInt32(NativeProtocol.OffCallbackKind) == NativeProtocol.CbKindRequestPixels)
{
uploadedPixels ??= loadPixels();
WritePixelRegion(uploadedPixels, uploadedPixels.Length);
}
else
{
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, addDraw, setAnchor);
}
_workEvent.Set();
}
@@ -141,23 +148,56 @@ namespace LuaScript.Engine
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
if (pixelsDirty)
{
if (bufferReplaced)
int pixelSize = resultWidth * resultHeight * 4;
if (!bufferReplaced && uploadedPixels is not null)
{
int pixelSize = resultWidth * resultHeight * 4;
if (_resultBuffer == null || _resultBuffer.Length < pixelSize)
_resultBuffer = new byte[pixelSize];
view.ReadArray(_pixelOffset, _resultBuffer, 0, pixelSize);
newPixels = _resultBuffer;
ReadPixelRegion(uploadedPixels, pixelSize);
resultPixels = uploadedPixels;
}
else
{
view.ReadArray(_pixelOffset, pixels, 0, pixels.Length);
if (_resultBuffer == null || _resultBuffer.Length < pixelSize)
_resultBuffer = new byte[pixelSize];
ReadPixelRegion(_resultBuffer, pixelSize);
resultPixels = _resultBuffer;
}
}
return true;
}
private unsafe void WritePixelRegion(byte[] source, int length)
{
var handle = _view!.SafeMemoryMappedViewHandle;
byte* ptr = null;
handle.AcquirePointer(ref ptr);
try
{
fixed (byte* src = source)
Buffer.MemoryCopy(src, ptr + _view.PointerOffset + _pixelOffset, handle.ByteLength - (ulong)(_view.PointerOffset + _pixelOffset), (ulong)length);
}
finally
{
handle.ReleasePointer();
}
}
private unsafe void ReadPixelRegion(byte[] destination, int length)
{
var handle = _view!.SafeMemoryMappedViewHandle;
byte* ptr = null;
handle.AcquirePointer(ref ptr);
try
{
fixed (byte* dst = destination)
Buffer.MemoryCopy(ptr + _view.PointerOffset + _pixelOffset, dst, destination.Length, length);
}
finally
{
handle.ReleasePointer();
}
}
private static int MeasureStringParameters(IReadOnlyDictionary<string, string> stringParameters)
{
int total = 4;
@@ -178,8 +218,6 @@ namespace LuaScript.Engine
}
capacity *= 2;
}
while (capacity > NativeProtocol.MinStringParamsCapacity && required <= capacity / 2)
capacity /= 2;
return capacity;
}
@@ -366,7 +404,7 @@ namespace LuaScript.Engine
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
view.WriteArray(_pixelOffset, result.buffer, 0, pixelSize);
WritePixelRegion(result.buffer, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
@@ -401,7 +439,7 @@ namespace LuaScript.Engine
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
view.WriteArray(_pixelOffset, result.buffer, 0, pixelSize);
WritePixelRegion(result.buffer, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
@@ -427,7 +465,7 @@ namespace LuaScript.Engine
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
view.WriteArray(_pixelOffset, result.buffer, 0, pixelSize);
WritePixelRegion(result.buffer, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
@@ -454,7 +492,7 @@ namespace LuaScript.Engine
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
view.WriteArray(_pixelOffset, result.buffer, 0, pixelSize);
WritePixelRegion(result.buffer, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
@@ -504,7 +542,8 @@ namespace LuaScript.Engine
private void EnsureWorker(int width, int height, int stringCapacity)
{
if (_alive && _process is { HasExited: false } && _width == width && _height == height && _stringParamsCapacity == stringCapacity)
long required = NativeProtocol.PixelOffset(stringCapacity) + (long)width * height * 4;
if (_alive && _process is { HasExited: false } && _stringParamsCapacity == stringCapacity && required <= _allocatedSize)
return;
KillWorker();
@@ -513,11 +552,10 @@ namespace LuaScript.Engine
private void StartWorker(int width, int height, int stringCapacity)
{
_width = width;
_height = height;
_stringParamsCapacity = stringCapacity;
_pixelOffset = NativeProtocol.PixelOffset(stringCapacity);
long size = NativeProtocol.BufferSize(width, height, stringCapacity);
long size = Math.Max(NativeProtocol.BufferSize(width, height, stringCapacity), _allocatedSize);
_allocatedSize = size;
string suffix = Guid.NewGuid().ToString("N");
string mapName = "LuaScriptMap_" + suffix;
+1
ファイルの表示
@@ -56,6 +56,7 @@ namespace LuaScript.Engine
public const int CbKindLoadImage = 6;
public const int CbKindLoadMovie = 7;
public const int CbKindSetAnchor = 8;
public const int CbKindRequestPixels = 9;
public const int CbExist = 0;
public const int CbX = 1;
+2 -12
ファイルの表示
@@ -9,24 +9,14 @@ namespace LuaScript.Engine
public static ScriptEngineKind ResolveAuto(string? script)
{
if (TryGetDirective(script, out var kind))
return kind;
if (UsesDrawingApi(script))
if (string.IsNullOrEmpty(script))
return ScriptEngineKind.MoonSharp;
return UsesPixelApi(script) ? ScriptEngineKind.Native : ScriptEngineKind.MoonSharp;
return TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.Native;
}
public static bool TryResolveExplicit(string? script, out ScriptEngineKind kind) =>
TryGetDirective(script, out kind);
public static bool UsesPixelApi(string? script) =>
script is not null && (script.Contains("getpixel", StringComparison.Ordinal) || script.Contains("setpixel", StringComparison.Ordinal));
public static bool UsesDrawingApi(string? script) =>
script is not null &&
(script.Contains("obj.setoption", StringComparison.Ordinal) ||
script.Contains("obj.setanchor", StringComparison.Ordinal));
private static bool TryGetDirective(string? script, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
+38
ファイルの表示
@@ -0,0 +1,38 @@
using System;
namespace LuaScript
{
internal sealed class FallbackCompositor(
IBufferCompositor primary,
IBufferCompositor fallback,
Action<Exception>? onDegraded = null) : IBufferCompositor, IDisposable
{
private bool _degraded;
public bool IsDegraded => _degraded;
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
{
if (!_degraded)
{
try
{
if (primary.TryCompose(dst, dstW, dstH, src, srcW, srcH, command))
return true;
}
catch (Exception ex)
{
_degraded = true;
onDegraded?.Invoke(ex);
}
}
return fallback.TryCompose(dst, dstW, dstH, src, srcW, srcH, command);
}
public void Dispose()
{
(primary as IDisposable)?.Dispose();
(fallback as IDisposable)?.Dispose();
}
}
}
+139
ファイルの表示
@@ -0,0 +1,139 @@
using System;
using System.Numerics;
using System.Runtime.InteropServices;
using Vortice.DCommon;
using Vortice.Direct2D1;
using Vortice.DXGI;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
namespace LuaScript
{
internal sealed class HardwareCompositor : IBufferCompositor, IDisposable
{
private const int MaxDimension = 8192;
private readonly GraphicsDevicesAndContext _ctx;
private ID2D1Bitmap1? _source;
private ID2D1Bitmap1? _target;
private ID2D1Bitmap1? _staging;
private int _sourceWidth;
private int _sourceHeight;
private int _targetWidth;
private int _targetHeight;
public HardwareCompositor(GraphicsDevicesAndContext ctx)
{
_ctx = ctx;
}
public unsafe bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
{
if (srcW <= 0 || srcH <= 0 || dstW <= 0 || dstH <= 0)
return true;
if (srcW > MaxDimension || srcH > MaxDimension || dstW > MaxDimension || dstH > MaxDimension)
return false;
if (src.Length < srcW * srcH * 4 || dst.Length < dstW * dstH * 4)
return false;
if (!DrawTransform.TryResolve(command, srcW, srcH, out var transform))
return true;
float opacity = (float)Math.Clamp(command.Alpha, 0d, 1d);
if (opacity <= 0f)
return true;
EnsureSource(srcW, srcH);
EnsureTarget(dstW, dstH);
fixed (byte* ptr = src)
_source!.CopyFromMemory(new nint(ptr), srcW * 4);
fixed (byte* ptr = dst)
_target!.CopyFromMemory(new nint(ptr), dstW * 4);
var interpolation = command.Antialias != 0d
? BitmapInterpolationMode.Linear
: BitmapInterpolationMode.NearestNeighbor;
var dc = _ctx.DeviceContext;
var rt = (ID2D1RenderTarget)dc;
using var savedTarget = dc.Target;
dc.Target = _target;
try
{
dc.BeginDraw();
rt.Transform = transform;
rt.DrawBitmap(_source!, opacity, interpolation);
rt.Transform = Matrix3x2.Identity;
dc.EndDraw();
}
finally
{
dc.Target = savedTarget;
}
_staging!.CopyFromBitmap(_target!);
var mapped = _staging.Map(MapOptions.Read);
try
{
if (mapped.Pitch == dstW * 4)
{
Marshal.Copy(mapped.Bits, dst, 0, dstW * dstH * 4);
}
else
{
for (int row = 0; row < dstH; row++)
Marshal.Copy(mapped.Bits + mapped.Pitch * row, dst, row * dstW * 4, dstW * 4);
}
}
finally
{
_staging.Unmap();
}
return true;
}
private void EnsureSource(int width, int height)
{
if (_source is not null && _sourceWidth == width && _sourceHeight == height)
return;
_source?.Dispose();
_source = _ctx.DeviceContext.CreateEmptyBitmap(width, height, BitmapOptions.Target);
_sourceWidth = width;
_sourceHeight = height;
}
private void EnsureTarget(int width, int height)
{
if (_target is not null && _targetWidth == width && _targetHeight == height)
return;
_target?.Dispose();
_staging?.Dispose();
_target = null;
_staging = null;
var dc = _ctx.DeviceContext;
_target = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
var stagingProps = new BitmapProperties1(
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
96f, 96f,
BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
_staging = dc.CreateBitmap(new SizeI(width, height), nint.Zero, width * 4, stagingProps);
_targetWidth = width;
_targetHeight = height;
}
public void Dispose()
{
_source?.Dispose();
_target?.Dispose();
_staging?.Dispose();
_source = null;
_target = null;
_staging = null;
}
}
}
+7
ファイルの表示
@@ -0,0 +1,7 @@
namespace LuaScript
{
internal interface IBufferCompositor
{
bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command);
}
}
+1 -1
ファイルの表示
@@ -4,7 +4,7 @@
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.11.0</Version>
<Version>1.11.4</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+101 -31
ファイルの表示
@@ -96,6 +96,28 @@ namespace LuaScript
private PixelBufferManager? _pixelManager;
private RawRectF _pixelBounds;
private int _pixelWidth;
private int _pixelHeight;
private Func<byte[]>? _pixelLoader;
private string _directiveSource = string.Empty;
private bool _directiveCached;
private ScriptEngineKind _autoKind;
private bool _hasExplicitDirective;
private ScriptEngineKind _explicitDirectiveKind;
private byte[]? _nativeInputPixels;
private Func<byte[]>? _nativeLoadInput;
private Func<string, int, SceneObjectInfo?>? _nativeResolveObject;
private Func<string, int, double, double, double, (byte[] buffer, int w, int h)>? _nativeLoadFigure;
private Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)>? _nativeLoadText;
private Func<string, (byte[] buffer, int w, int h)>? _nativeLoadImage;
private Func<string, double, (byte[] buffer, int w, int h)>? _nativeLoadMovie;
private Action<string, IReadOnlyList<KeyValuePair<string, object>>>? _nativeAddEffect;
private Action<DrawCommand>? _nativeAddDraw;
private Action<string, int, bool, int, double[]>? _nativeSetAnchor;
private bool _isFirst = true;
private string _sourceScript = string.Empty;
private string _runnableScript = string.Empty;
@@ -109,6 +131,7 @@ namespace LuaScript
private VideoEffectChain? _effectChain;
private DrawCompositor? _drawCompositor;
private FallbackCompositor? _bufferCompositor;
private TextRenderer? _nativeTextRenderer;
private ImageDecoder? _nativeImageDecoder;
private MovieDecoder? _nativeMovieDecoder;
@@ -118,10 +141,26 @@ namespace LuaScript
_ownCtx = new GraphicsDevicesAndContext(devices);
disposer.Collect(_ownCtx);
_pixelManager = new PixelBufferManager(_ownCtx);
_bufferCompositor = new FallbackCompositor(
new SynchronizedCompositor(new HardwareCompositor(_ownCtx), _pixelLoaderSemaphore),
SoftwareCompositor.Instance,
WarnBufferCompositorDegraded);
_context.ResolverProvider = GetFrameResolver;
_context.Compositor = _bufferCompositor;
return null;
}
private static void WarnBufferCompositorDegraded(Exception ex) =>
Log.Default.Write("LuaScript: hardware buffer compositing failed; falling back to the software compositor.", ex);
private AviUtlScriptContext CreateScriptContext()
{
var context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
if (_bufferCompositor is not null)
context.Compositor = _bufferCompositor;
return context;
}
private SceneObjectResolver GetFrameResolver()
{
if (!_frameResolverBuilt)
@@ -251,7 +290,10 @@ namespace LuaScript
var ctx = _context;
PopulateContext(ctx, in key, imgW, imgH);
ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH));
_pixelBounds = bounds;
_pixelWidth = imgW;
_pixelHeight = imgH;
ctx.SetPixelLoader(_pixelLoader ??= LoadPendingInputPixels);
DrawDescription outDesc = inDesc;
IReadOnlyList<LuaScriptDiagnostic> diagnostics = [];
@@ -260,14 +302,15 @@ namespace LuaScript
{
string runnable = GetRunnableScript(script);
EnsureKernel(runnable);
EnsureDirective(runnable);
if (ExecuteKernelLane(runnable, ctx, bounds, imgW, imgH))
if (ExecuteKernelLane(ctx, bounds, imgW, imgH))
{
outDesc = inDesc;
}
else
{
bool wantNative = ScriptDirective.ResolveAuto(runnable) == ScriptEngineKind.Native;
bool wantNative = _autoKind == ScriptEngineKind.Native;
bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory);
if (wantNative && !nativeReady)
WarnNativeUnavailableOnce();
@@ -331,7 +374,7 @@ namespace LuaScript
catch (LuaScriptTimeoutException ex)
{
effectOutput = null;
_context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
_context = CreateScriptContext();
_isFirst = true;
Log.Default.Write(ex.Message, ex);
LuaScriptDiagnostics.Instance.Report(script, [CreateDiagnostic(LuaScriptDiagnosticKind.Timeout, ex.Message)]);
@@ -699,19 +742,31 @@ namespace LuaScript
_gpuKernelChecked = false;
}
private bool ExecuteKernelLane(string runnable, AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
private void EnsureDirective(string runnable)
{
if (_directiveCached && string.Equals(runnable, _directiveSource, StringComparison.Ordinal))
return;
_directiveSource = runnable;
_directiveCached = true;
_hasExplicitDirective = ScriptDirective.TryResolveExplicit(runnable, out _explicitDirectiveKind);
_autoKind = ScriptDirective.ResolveAuto(runnable);
}
private bool ExecuteKernelLane(AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
{
if (_kernelProgram is null || _cpuKernel is null)
return false;
bool explicitDirective = ScriptDirective.TryResolveExplicit(runnable, out var kind);
bool explicitDirective = _hasExplicitDirective;
var kind = _explicitDirectiveKind;
if (explicitDirective && kind is not (ScriptEngineKind.Gpu or ScriptEngineKind.Cpu))
return false;
_kernelUniforms ??= KernelUniformBinding.Create();
KernelUniformBinding.Fill(ctx, _kernelUniforms);
if (explicitDirective && kind == ScriptEngineKind.Gpu)
if (!explicitDirective || kind == ScriptEngineKind.Gpu)
{
var gpu = GetGpuKernel();
if (gpu is not null)
@@ -719,7 +774,8 @@ namespace LuaScript
effectOutput = gpu.Apply(input!, _kernelUniforms);
return true;
}
WarnGpuUnavailableOnce();
if (explicitDirective)
WarnGpuUnavailableOnce();
}
byte[] buffer = LoadInputPixels(bounds, imgW, imgH);
@@ -735,16 +791,22 @@ namespace LuaScript
return _gpuKernel;
_gpuKernelChecked = true;
if (_kernelProgram is null)
if (_kernelProgram is null || _cpuKernel is null)
return null;
try
{
var kernel = new GpuKernel(_ownCtx!, _kernelProgram);
if (kernel.IsReady)
if (kernel.IsReady && kernel.Verify(_cpuKernel))
{
_gpuKernel = kernel;
}
else
{
if (kernel.IsReady)
Log.Default.Write("LuaScript: GPU kernel output diverges from the CPU kernel beyond tolerance; using the CPU kernel.");
kernel.Dispose();
}
}
catch (Exception ex)
{
@@ -778,21 +840,30 @@ namespace LuaScript
{
_nativeWorker ??= new LuaJitWorker(NativeDirectory);
_nativeFields ??= new double[NativeProtocol.FieldCount];
_nativeLoadInput ??= () => _nativeInputPixels ??= LoadPendingInputPixels();
_nativeResolveObject ??= (tag, frame) => _context.ResolveObject(tag, frame, out var info) ? info : null;
_nativeLoadFigure ??= NativeLoadFigure;
_nativeLoadText ??= NativeLoadText;
_nativeLoadImage ??= NativeLoadImage;
_nativeLoadMovie ??= NativeLoadMovie;
_nativeAddEffect ??= (name, args) => _context.AddEffect(new AviUtlEffectRequest(name, args));
_nativeAddDraw ??= command => _context.AddDraw(command);
_nativeSetAnchor ??= ResolveNativeAnchor;
NativeFieldMap.ToFields(ctx, _nativeFields);
byte[] buffer = LoadInputPixels(bounds, imgW, imgH);
_nativeInputPixels = null;
bool ok = _nativeWorker.Execute(
script, _nativeFields, ctx.StringParameters, buffer, imgW, imgH, NativeTimeoutMilliseconds,
(tag, frame) => ctx.ResolveObject(tag, frame, out var info) ? info : null,
NativeLoadFigure,
NativeLoadText,
NativeLoadImage,
NativeLoadMovie,
(name, args) => ctx.AddEffect(new AviUtlEffectRequest(name, args)),
ctx.AddDraw,
ResolveNativeAnchor,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels,
script, _nativeFields, ctx.StringParameters, _nativeLoadInput, imgW, imgH, NativeTimeoutMilliseconds,
_nativeResolveObject,
_nativeLoadFigure,
_nativeLoadText,
_nativeLoadImage,
_nativeLoadMovie,
_nativeAddEffect,
_nativeAddDraw,
_nativeSetAnchor,
out bool dirty, out bool bufferReplaced, out byte[]? resultPixels,
out int resultW, out int resultH, out string? error);
if (!ok)
@@ -806,25 +877,21 @@ namespace LuaScript
bool hasDraws = ctx.DrawCommands.Count > 0;
if (dirty)
if (dirty && resultPixels is not null)
{
int outW = bufferReplaced ? resultW : imgW;
int outH = bufferReplaced ? resultH : imgH;
byte[] outPixels = buffer;
if (bufferReplaced && newPixels != null)
{
outPixels = newPixels;
ctx.ReplaceBuffer(outPixels, outW, outH);
}
if (bufferReplaced)
ctx.ReplaceBuffer(resultPixels, outW, outH);
if (hasDraws)
{
ctx.SetResolvedBuffer(outPixels, outW, outH);
ctx.SetResolvedBuffer(resultPixels, outW, outH);
return true;
}
_pixelManager!.WritePixelsToOutput(outPixels, outW, outH);
_pixelManager!.WritePixelsToOutput(resultPixels, outW, outH);
if (bufferReplaced)
effectOutput = _pixelManager.GetTransformOutput(-outW / 2f, -outH / 2f);
else
@@ -834,7 +901,7 @@ namespace LuaScript
if (hasDraws)
{
ctx.SetResolvedBuffer(buffer, imgW, imgH);
ctx.SetResolvedBuffer(_nativeLoadInput(), imgW, imgH);
return false;
}
@@ -891,6 +958,8 @@ namespace LuaScript
return (buffer, fw, fh);
}
private byte[] LoadPendingInputPixels() => LoadInputPixels(_pixelBounds, _pixelWidth, _pixelHeight);
private byte[] LoadInputPixels(RawRectF bounds, int width, int height)
{
_pixelLoaderSemaphore.Wait();
@@ -913,6 +982,7 @@ namespace LuaScript
_nativeWorker?.Dispose();
_effectChain?.Dispose();
_drawCompositor?.Dispose();
_bufferCompositor?.Dispose();
_nativeTextRenderer?.Dispose();
_nativeImageDecoder?.Dispose();
_pixelLoaderSemaphore.Dispose();
+8 -2
ファイルの表示
@@ -18,6 +18,7 @@ namespace LuaScript
private ID2D1Bitmap1? _stagingBitmap;
private ID2D1Bitmap1? _outputBitmap;
private AffineTransform2D? _transformEffect;
private ID2D1Image? _transformOutput;
private byte[]? _pixelBuffer;
private int _bitmapWidth;
private int _bitmapHeight;
@@ -33,7 +34,7 @@ namespace LuaScript
EnsureBitmaps(width, height);
var dc = _ctx.DeviceContext;
var savedTarget = dc.Target;
using var savedTarget = dc.Target;
dc.Target = _renderTarget;
dc.BeginDraw();
@@ -82,6 +83,7 @@ namespace LuaScript
{
_transformEffect = new AffineTransform2D(_ctx.DeviceContext);
_transformEffect.SetInput(0, _outputBitmap, true);
_transformOutput = _transformEffect.Output;
_cachedBounds = default;
}
@@ -91,7 +93,7 @@ namespace LuaScript
_cachedBounds = new RawRectF(left, top, left, top);
}
return _transformEffect.Output;
return _transformOutput!;
}
private void EnsureBitmaps(int width, int height)
@@ -101,10 +103,12 @@ namespace LuaScript
_renderTarget?.Dispose();
_stagingBitmap?.Dispose();
_outputBitmap?.Dispose();
_transformOutput?.Dispose();
_transformEffect?.Dispose();
_renderTarget = null;
_stagingBitmap = null;
_outputBitmap = null;
_transformOutput = null;
_transformEffect = null;
_bitmapWidth = 0;
_bitmapHeight = 0;
@@ -135,10 +139,12 @@ namespace LuaScript
_renderTarget?.Dispose();
_stagingBitmap?.Dispose();
_outputBitmap?.Dispose();
_transformOutput?.Dispose();
_transformEffect?.Dispose();
_renderTarget = null;
_stagingBitmap = null;
_outputBitmap = null;
_transformOutput = null;
_transformEffect = null;
}
}
+17 -1
ファイルの表示
@@ -3,8 +3,24 @@ using System.Numerics;
namespace LuaScript
{
internal static class SoftwareCompositor
internal sealed class SoftwareCompositor : IBufferCompositor
{
public static readonly SoftwareCompositor Instance = new();
private SoftwareCompositor()
{
}
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
{
bool linear = command.Antialias != 0d;
if (command.Poly is { } poly)
DrawPolyInto(dst, dstW, dstH, src, srcW, srcH, poly, command.Alpha, linear);
else
DrawInto(dst, dstW, dstH, src, srcW, srcH, command.Ox, command.Oy, command.Zoom, command.Aspect, command.Alpha, linear);
return true;
}
public static void DrawInto(
byte[] dst, int dstW, int dstH,
byte[] src, int srcW, int srcH,
+23
ファイルの表示
@@ -0,0 +1,23 @@
using System;
using System.Threading;
namespace LuaScript
{
internal sealed class SynchronizedCompositor(IBufferCompositor inner, SemaphoreSlim gate) : IBufferCompositor, IDisposable
{
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
{
gate.Wait();
try
{
return inner.TryCompose(dst, dstW, dstH, src, srcW, srcH, command);
}
finally
{
gate.Release();
}
}
public void Dispose() => (inner as IDisposable)?.Dispose();
}
}
+13 -9
ファイルの表示
@@ -2,7 +2,8 @@
يستخدم تأثير الفيديو "نص Lua" في YukkuriMovieMaker4
لغة Lua لكتابة النصوص البرمجية.
يعتمد محرك النصوص على MoonSharp (متوافق مع Lua 5.2).
تُنفَّذ النصوص على بيئة التشغيل السريعة المرفقة (LuaJIT)،
وتعمل على MoonSharp (متوافق مع Lua 5.2) عندما لا تتوفر تلك البيئة.
* هذا التأثير تطبيق مستقل ويختلف عن مواصفات نصوص AviUtl2.
* يختلف في مواصفاته عن ملفات نصوص AviUtl2 (*.anm2 وما شابه).
@@ -11,7 +12,7 @@
- ملاحظات -
○ محرك تنفيذ النصوص هو MoonSharp (متوافق مع Lua 5.2).
○ محركا تنفيذ النصوص هما LuaJIT (الافتراضي) وMoonSharp (متوافق مع Lua 5.2).
○ المكتبات القياسية المتاحة محدودة بما يلي:
table, string, math, bit32
* io, os, debug, ffi, require وغيرها غير متاحة.
@@ -26,16 +27,16 @@
- محركات التنفيذ والتسريع التلقائي -
النصوص التي تحتوي على معالجة بكسل (حلقة getpixel/setpixel متداخلة)
يُحلَّل تركيبها وتُوجَّه تلقائياً إلى محرك أسرع.
أما النصوص العادية (الإحداثيات، الدوران، الشفافية، إلخ) فتظل تعمل على
MoonSharp كما في السابق دون أي تغيير في السلوك.
يُحلَّل تركيب النصوص وتُوجَّه تلقائياً إلى المحرك الأنسب.
النصوص التي لا تحمل توجيهاً تُنفَّذ على بيئة التشغيل السريعة المرفقة
(LuaJIT)، أما تخطيطات البكسل المكتفية بنفسها فتُترجَم إضافةً إلى ذلك
إلى نواة CPU الأسرع. وفي كلتا الحالتين تطابق النتائج MoonSharp.
○ التوجيه التلقائي (عند عدم وجود توجيه)
· تخطيط بكسل مكتفٍ بنفسه (انظر الشروط أدناه)
→ نواة CPU (سريعة ودقيقة)
· عمليات البكسل الأخرى → Native (LuaJIT، فقط عند نشره)
· بلا عمليات بكسل → MoonSharp
· كل ما عدا ذلك → Native (LuaJIT، فقط عند نشره)
· عند عدم نشر native أو كون النص فارغاً → MoonSharp
○ توجيهات المحرك (تعليق في السطر الأول من النص)
--!cpu : نواة CPU. تُترجَم وقت التشغيل إلى شجرة تعابير
@@ -511,7 +512,10 @@
تهيئة مخزن tmp، وحذفهما يُبقيه كما هو. أعِد نتيجة tmp إلى صورة
العمل عبر obj.copybuffer("obj", "tmp"). التركيب في tempbuffer
عادي (source-over)، وblend يُطبَّق على الرسم في framebuffer.
تعمل في المحركين معاً.
تعمل في المحركين معاً. في MoonSharp يُنفَّذ التركيب في tempbuffer
على GPU، ويتحوّل تلقائياً إلى التركيب على CPU عندما تكون GPU
غير متاحة. وبسبب اختلاف التقريب قد تختلف نتيجة التركيب
اختلافاً طفيفاً جداً بين المحركين.
○ obj.pixeloption(name, value)
يحفظ خياراً لعمليات البكسل كحالة.
+13 -9
ファイルの表示
@@ -2,7 +2,8 @@
The "Lua Script" video effect in YukkuriMovieMaker4 uses
the Lua language for scripting.
The scripting engine is MoonSharp (Lua 5.2 compatible).
Scripts run on the bundled fast runtime (LuaJIT), and fall back to
MoonSharp (Lua 5.2 compatible) when the runtime is unavailable.
* This effect is a custom implementation and differs from the AviUtl2 script specification.
* This is a separate specification from AviUtl2 script files (*.anm2, etc.).
@@ -11,7 +12,7 @@
- Notes -
o The script execution engine is MoonSharp (Lua 5.2 compatible).
o The script execution engines are LuaJIT (default) and MoonSharp (Lua 5.2 compatible).
o Available standard libraries are limited to the following:
table, string, math, bit32
* io, os, debug, ffi, require, etc. are not available.
@@ -26,16 +27,16 @@
- Execution Engines and Automatic Acceleration -
Scripts that contain pixel processing (a nested getpixel/setpixel loop)
are analyzed and automatically routed to a faster engine.
Ordinary scripts (coordinate, rotation, opacity changes, etc.) keep
running on MoonSharp as before, with no change in behavior.
Scripts are analyzed and automatically routed to the best engine.
Scripts without a directive run on the bundled fast runtime (LuaJIT),
and self-contained per-pixel maps are further compiled to the even
faster CPU kernel. Either way the results match MoonSharp.
o Automatic routing (when no directive is present)
- A self-contained per-pixel map (see conditions below)
-> CPU kernel (fast, exact)
- Other pixel operations -> Native (LuaJIT, only when deployed)
- No pixel operations -> MoonSharp
- Everything else -> Native (LuaJIT, only when deployed)
- Native not deployed, or an empty script -> MoonSharp
o Engine directives (a comment on the first line of the script)
--!cpu : CPU kernel. Compiled at runtime to an expression
@@ -530,7 +531,10 @@
tmp result back to the working image with
obj.copybuffer("obj", "tmp"). Compositing into tempbuffer is
normal (source-over); blend applies to framebuffer drawing. It
works in both engines.
works in both engines. In MoonSharp the compositing into
tempbuffer runs on the GPU and switches to the CPU compositing
automatically when the GPU is unavailable. Due to rounding, the
composited result may differ very slightly between the engines.
o obj.pixeloption(name, value)
Stores an option for pixel operations as state.
+15 -10
ファイルの表示
@@ -2,7 +2,8 @@
El efecto de video «Script Lua» de YukkuriMovieMaker4 utiliza
el lenguaje Lua para los scripts.
El motor de scripts empleado es MoonSharp (compatible con Lua 5.2).
Los scripts se ejecutan en el runtime rápido incluido (LuaJIT) y,
cuando este no está disponible, en MoonSharp (compatible con Lua 5.2).
* Este efecto es una implementación propia y difiere de la especificación de scripts de AviUtl2.
* Tiene una especificación distinta a los archivos de script de AviUtl2 (*.anm2, etc.).
@@ -11,7 +12,7 @@
- Notas -
o El motor de ejecución de scripts es MoonSharp (compatible con Lua 5.2).
o Los motores de ejecución son LuaJIT (predeterminado) y MoonSharp (compatible con Lua 5.2).
o Las bibliotecas estándar disponibles se limitan a las siguientes:
table, string, math, bit32
* io, os, debug, ffi, require, etc. no están disponibles.
@@ -26,17 +27,17 @@
- Motores de ejecución y aceleración automática -
Los scripts que contienen procesamiento de píxeles (un bucle anidado
getpixel/setpixel) se analizan y se enrutan automáticamente a un motor
más rápido. Los scripts normales (coordenadas, rotación, opacidad, etc.)
siguen ejecutándose en MoonSharp como antes, sin cambios de comportamiento.
Los scripts se analizan y se enrutan automáticamente al mejor motor.
Los scripts sin directiva se ejecutan en el runtime rápido incluido
(LuaJIT), y los mapeos por píxel autocontenidos se compilan además al
núcleo CPU, aún más rápido. En ambos casos los resultados coinciden
con MoonSharp.
o Enrutamiento automático (cuando no hay directiva)
- Un mapeo por píxel autocontenido (ver condiciones abajo)
-> núcleo CPU (rápido, exacto)
- Otras operaciones de píxeles -> Nativo (LuaJIT, solo si está
desplegado)
- Sin operaciones de píxeles -> MoonSharp
- Todo lo demás -> Nativo (LuaJIT, solo si está desplegado)
- Nativo no desplegado, o script vacío -> MoonSharp
o Directivas de motor (un comentario en la primera línea del script)
--!cpu : Núcleo CPU. Compilado en tiempo de ejecución a un
@@ -533,7 +534,11 @@
conservarlo. Recupera el resultado de tmp a la imagen de trabajo
con obj.copybuffer("obj", "tmp"). La composición en tempbuffer es
normal (source-over); blend se aplica al dibujo en framebuffer.
Funciona en ambos motores.
Funciona en ambos motores. En MoonSharp la composición en
tempbuffer se ejecuta en la GPU y cambia automáticamente a la
composición por CPU cuando la GPU no está disponible. Por el
redondeo, el resultado puede diferir muy ligeramente entre los
motores.
o obj.pixeloption(nombre, valor)
Guarda como estado una opción para las operaciones de píxeles.
+15 -9
ファイルの表示
@@ -2,7 +2,9 @@
Efek video "Script Lua" di YukkuriMovieMaker4 menggunakan
bahasa Lua untuk penulisan skrip.
Mesin skrip yang digunakan adalah MoonSharp (kompatibel dengan Lua 5.2).
Skrip dijalankan pada runtime cepat yang disertakan (LuaJIT), dan
berjalan pada MoonSharp (kompatibel dengan Lua 5.2) jika runtime
tersebut tidak tersedia.
* Efek ini adalah implementasi mandiri dan berbeda dari spesifikasi skrip AviUtl2.
* Memiliki spesifikasi yang berbeda dari file skrip AviUtl2 (*.anm2, dll.).
@@ -11,7 +13,7 @@
- Catatan -
o Mesin eksekusi skrip adalah MoonSharp (kompatibel dengan Lua 5.2).
o Mesin eksekusi skrip adalah LuaJIT (bawaan) dan MoonSharp (kompatibel dengan Lua 5.2).
o Pustaka standar yang tersedia terbatas pada berikut ini:
table, string, math, bit32
* io, os, debug, ffi, require, dll. tidak tersedia.
@@ -26,16 +28,17 @@
- Mesin Eksekusi dan Akselerasi Otomatis -
Skrip yang berisi pemrosesan piksel (loop bersarang getpixel/setpixel)
dianalisis sintaksnya dan secara otomatis dialihkan ke mesin yang lebih
cepat. Skrip biasa (koordinat, rotasi, opasitas, dll.) tetap berjalan di
MoonSharp seperti sebelumnya, tanpa perubahan perilaku.
Skrip dianalisis sintaksnya dan secara otomatis dialihkan ke mesin
yang paling sesuai. Skrip tanpa direktif dijalankan pada runtime cepat
yang disertakan (LuaJIT), dan pemetaan per-piksel mandiri dikompilasi
lebih lanjut ke kernel CPU yang lebih cepat lagi. Hasil keduanya sama
dengan MoonSharp.
o Pengalihan otomatis (saat tidak ada direktif)
- Pemetaan per-piksel mandiri (lihat syarat di bawah)
-> kernel CPU (cepat, tepat)
- Operasi piksel lainnya -> Native (LuaJIT, hanya jika di-deploy)
- Tanpa operasi piksel -> MoonSharp
- Selain itu -> Native (LuaJIT, hanya jika di-deploy)
- Native tidak di-deploy, atau skrip kosong -> MoonSharp
o Direktif mesin (komentar pada baris pertama skrip)
--!cpu : Kernel CPU. Dikompilasi saat runtime menjadi pohon
@@ -528,7 +531,10 @@
mempertahankannya. Kembalikan hasil tmp ke citra kerja dengan
obj.copybuffer("obj", "tmp"). Komposit ke tempbuffer bersifat
normal (source-over); blend berlaku untuk gambar ke framebuffer.
Bekerja pada kedua mesin.
Bekerja pada kedua mesin. Pada MoonSharp, komposit ke tempbuffer
dijalankan di GPU dan beralih secara otomatis ke komposit CPU
saat GPU tidak tersedia. Karena pembulatan, hasil komposit dapat
sedikit berbeda antara kedua mesin.
o obj.pixeloption(name, value)
Menyimpan opsi untuk operasi piksel sebagai status.
+13 -8
ファイルの表示
@@ -2,7 +2,8 @@
YukkuriMovieMaker4 の「Luaスクリプト」映像エフェクトで
利用可能なスクリプトには Lua 言語を使用します。
スクリプトエンジンには MoonSharp (Lua 5.2 互換) が採用されています。
スクリプトは同梱の高速ランタイム(LuaJIT)で実行され、
利用できない環境では MoonSharp (Lua 5.2 互換) で実行されます。
※このエフェクトは AviUtl2 のスクリプト仕様とは異なる独自実装です。
※AviUtl2 のスクリプトファイル(*.anm2 等)とは別仕様です。
@@ -11,7 +12,7 @@
- 注意点 -
○スクリプトの実行エンジンは MoonSharp (Lua 5.2 互換) です。
○スクリプトの実行エンジンは LuaJIT(標準)と MoonSharp (Lua 5.2 互換) です。
○利用可能な標準ライブラリは以下に限定されます。
table, string, math, bit32
※io, os, debug, ffi, require 等は使用できません。
@@ -26,15 +27,15 @@
- 実行エンジンと自動高速化 -
ピクセル処理(getpixel/setpixel の二重ループ)を含むスクリプトは、
構文を解析して自動的に高速なエンジンへ振り分けられます。
座標・回転・不透明度などの通常スクリプトは従来どおり MoonSharp で
実行され、挙動は一切変わりません。
スクリプトは構文を解析して自動的に最適なエンジンへ振り分けられます。
ディレクティブ無しのスクリプトは同梱の高速ランタイム(LuaJIT)で
実行され、自ピクセル完結のピクセル写像はさらに高速な CPU カーネルへ
変換されます。いずれの結果も MoonSharp と一致します。
○自動振り分け(ディレクティブ無しのとき)
・自ピクセル完結のピクセル写像(下記条件) → CPU カーネル(高速・厳密)
・上記以外のピクセル操作 → ネイティブ(LuaJIT, 配備時のみ)
・ピクセル操作なし → MoonSharp
・上記以外 → ネイティブ(LuaJIT, 配備時のみ)
・native 未配備または空のスクリプト → MoonSharp
○エンジン指定ディレクティブ(スクリプト先頭行のコメント)
--!cpu : CPU カーネル。式ツリーへ実行時コンパイルして
@@ -515,6 +516,10 @@
tmp へ描いた結果は obj.copybuffer("obj", "tmp") で作業画像へ
戻せます。tempbuffer への合成は通常(ソースオーバー)で、blend は
framebuffer への描画に適用されます。両エンジンで動きます。
MoonSharp では tempbuffer への合成を GPU で実行し、GPU を
利用できない環境では CPU の合成へ自動的に切り替わります。
丸めの違いにより、合成の結果はエンジン間でごく僅かに
異なることがあります。
○obj.pixeloption(名前, 値)
ピクセル操作のオプションを状態として保持します。
+12 -8
ファイルの表示
@@ -2,7 +2,8 @@
YukkuriMovieMaker4의 「Lua 스크립트」 영상 이펙트에서
사용 가능한 스크립트에는 Lua 언어를 사용합니다.
스크립트 엔진으로는 MoonSharp (Lua 5.2 호환)이 채용되어 있습니다.
스크립트는 동봉된 고속 런타임(LuaJIT)으로 실행되며,
사용할 수 없는 환경에서는 MoonSharp (Lua 5.2 호환)으로 실행됩니다.
※ 이 이펙트는 AviUtl2의 스크립트 사양과는 다른 독자적인 구현입니다.
※ AviUtl2의 스크립트 파일(*.anm2 등)과는 별도의 사양입니다.
@@ -11,7 +12,7 @@
- 주의 사항 -
○ 스크립트 실행 엔진은 MoonSharp (Lua 5.2 호환)입니다.
○ 스크립트 실행 엔진은 LuaJIT(표준)과 MoonSharp (Lua 5.2 호환)입니다.
○ 사용 가능한 표준 라이브러리는 다음으로 제한됩니다.
table, string, math, bit32
※ io, os, debug, ffi, require 등은 사용할 수 없습니다.
@@ -26,15 +27,15 @@
- 실행 엔진과 자동 가속 -
픽셀 처리(getpixel/setpixel 이중 루프)를 포함하는 스크립트는
구문을 분석하여 자동으로 더 빠른 엔진으로 분배됩니다.
좌표・회전・불투명도 등 일반 스크립트는 기존과 동일하게 MoonSharp으로
실행되며 동작은 전혀 바뀌지 않습니다.
스크립트는 구문을 분석하여 자동으로 가장 적합한 엔진으로 분배됩니다.
디렉티브가 없는 스크립트는 동봉된 고속 런타임(LuaJIT)으로 실행되며,
자기 픽셀로 완결되는 픽셀 매핑은 더욱 빠른 CPU 커널로 변환됩니다.
어느 쪽이든 결과는 MoonSharp과 일치합니다.
○ 자동 분배(디렉티브가 없을 때)
· 자기 픽셀로 완결되는 픽셀 매핑(아래 조건) → CPU 커널(고속・엄밀)
· 위 이외의 픽셀 조작 → 네이티브(LuaJIT, 배치된 경우에만)
· 픽셀 조작 없음 → MoonSharp
· 위 이외 → 네이티브(LuaJIT, 배치된 경우에만)
· native 미배치 또는 빈 스크립트 → MoonSharp
○ 엔진 지정 디렉티브(스크립트 첫 줄의 주석)
--!cpu : CPU 커널. 식 트리로 런타임 컴파일하여
@@ -508,6 +509,9 @@
그린 결과는 obj.copybuffer("obj", "tmp")로 작업 이미지에 되돌릴
수 있습니다. tempbuffer로의 합성은 보통(소스 오버)이며, blend는
framebuffer 그리기에 적용됩니다. 두 엔진 모두에서 동작합니다.
MoonSharp에서는 tempbuffer로의 합성을 GPU에서 실행하며, GPU를
사용할 수 없는 환경에서는 CPU 합성으로 자동 전환됩니다. 반올림
차이로 인해 합성 결과가 엔진 간에 아주 조금 다를 수 있습니다.
○ obj.pixeloption(이름, 값)
픽셀 조작 옵션을 상태로 보존합니다.
+12 -8
ファイルの表示
@@ -2,7 +2,8 @@
YukkuriMovieMaker4 的"Lua 脚本"视频特效使用
Lua 语言编写脚本。
脚本引擎采用 MoonSharp(兼容 Lua 5.2)。
脚本由随附的高速运行时(LuaJIT)执行,
在其不可用的环境下改由 MoonSharp(兼容 Lua 5.2)执行。
* 本特效为独立实现,与 AviUtl2 的脚本规范不同。
* 与 AviUtl2 的脚本文件(*.anm2 等)为不同规范。
@@ -11,7 +12,7 @@
- 注意事项 -
○ 脚本执行引擎为 MoonSharp(兼容 Lua 5.2)。
○ 脚本执行引擎为 LuaJIT(默认)与 MoonSharp(兼容 Lua 5.2)。
○ 可用的标准库仅限以下内容:
table, string, math, bit32
* io、os、debug、ffi、require 等不可使用。
@@ -26,14 +27,15 @@
- 执行引擎与自动加速 -
包含像素处理(getpixel/setpixel 双重循环)的脚本会被解析语法,
并自动分配到更快的引擎。
坐标、旋转、不透明度等普通脚本仍照旧由 MoonSharp 执行,行为不变。
脚本会被解析语法,并自动分配到最合适的引擎。
未指定指令的脚本由随附的高速运行时(LuaJIT)执行,
自像素完结的像素映射会进一步转换为更快的 CPU 内核。
两者的结果均与 MoonSharp 一致。
○ 自动分配(未指定指令时)
· 自像素完结的像素映射(见下方条件)→ CPU 内核(高速、精确)
· 上述以外的像素操作 → 原生(LuaJIT,仅在已部署时)
· 无像素操作 → MoonSharp
· 上述以外 → 原生(LuaJIT,仅在已部署时)
· 未部署 native 或脚本为空 → MoonSharp
○ 引擎指定指令(脚本首行的注释)
--!cpu :CPU 内核。运行时编译为表达式树,
@@ -495,7 +497,9 @@
中的 w, h 是初始化 tmp 缓冲的尺寸,省略则不初始化。画到 tmp 的
结果可用 obj.copybuffer("obj", "tmp") 取回工作图像。合成到
tempbuffer 使用普通(源覆盖),blend 应用于 framebuffer 的绘制。
两个引擎都可用。
两个引擎都可用。在 MoonSharp 中,合成到 tempbuffer 在 GPU 上
执行,GPU 不可用时会自动切换到 CPU 合成。由于舍入方式不同,
合成结果在引擎之间可能存在极小差异。
○ obj.pixeloption(名称, 值)
将像素操作的选项作为状态保存。
+12 -8
ファイルの表示
@@ -2,7 +2,8 @@
YukkuriMovieMaker4 的「Lua 腳本」視訊特效使用
Lua 語言編寫腳本。
腳本引擎採用 MoonSharp(相容 Lua 5.2)。
腳本由隨附的高速執行環境(LuaJIT)執行,
在其不可用的環境下改由 MoonSharp(相容 Lua 5.2)執行。
* 本特效為獨立實作,與 AviUtl2 的腳本規範不同。
* 與 AviUtl2 的腳本檔案(*.anm2 等)為不同規範。
@@ -11,7 +12,7 @@
- 注意事項 -
○ 腳本執行引擎為 MoonSharp(相容 Lua 5.2)。
○ 腳本執行引擎為 LuaJIT(預設)與 MoonSharp(相容 Lua 5.2)。
○ 可用的標準函式庫僅限以下內容:
table, string, math, bit32
* io、os、debug、ffi、require 等不可使用。
@@ -26,14 +27,15 @@
- 執行引擎與自動加速 -
包含像素處理(getpixel/setpixel 雙重迴圈)的腳本會被解析語法,
並自動分配到更快的引擎。
座標、旋轉、不透明度等一般腳本仍照舊由 MoonSharp 執行,行為不變。
腳本會被解析語法,並自動分配到最合適的引擎。
未指定指令的腳本由隨附的高速執行環境(LuaJIT)執行,
自像素完結的像素映射會進一步轉換為更快的 CPU 核心。
兩者的結果均與 MoonSharp 一致。
○ 自動分配(未指定指令時)
· 自像素完結的像素映射(見下方條件)→ CPU 核心(高速、精確)
· 上述以外的像素操作 → 原生(LuaJIT,僅在已部署時)
· 無像素操作 → MoonSharp
· 上述以外 → 原生(LuaJIT,僅在已部署時)
· 未部署 native 或腳本為空 → MoonSharp
○ 引擎指定指令(腳本首行的註解)
--!cpu :CPU 核心。執行時編譯為運算式樹,
@@ -496,7 +498,9 @@
中的 w, h 是初始化 tmp 緩衝的尺寸,省略則不初始化。畫到 tmp 的
結果可用 obj.copybuffer("obj", "tmp") 取回工作影像。合成到
tempbuffer 使用一般(來源覆蓋),blend 套用於 framebuffer 的繪製。
兩個引擎都可用。
兩個引擎都可用。在 MoonSharp 中,合成到 tempbuffer 在 GPU 上
執行,GPU 無法使用時會自動切換到 CPU 合成。由於捨入方式不同,
合成結果在引擎之間可能存在極小差異。
○ obj.pixeloption(名稱, 值)
將像素操作的選項作為狀態保存。
+13 -13
ファイルの表示
@@ -7,7 +7,7 @@
---
YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブジェクトの座標・拡縮・回転・不透明度・ピクセルを直接制御できる映像エフェクトプラグイン**です。
スクリプトエンジンには MoonSharp(Lua 5.2 互換)が採用されており、`obj.x` や `obj.alpha` といった変数をスクリプトから書き換えることで、AviUtl のスクリプト制御に近い感覚でアニメーションを組み立てられます。
スクリプトは同梱の高速ランタイム(LuaJIT)で実行され、`obj.x` や `obj.alpha` といった変数をスクリプトから書き換えることで、AviUtl のスクリプト制御に近い感覚でアニメーションを組み立てられます。高速ランタイムを利用できない環境では MoonSharp(Lua 5.2 互換)で実行されます。
座標・拡縮・回転・不透明度の制御に加えて、`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` によるピクセル単位の画像加工、アニメーション制作向けの数学ユーティリティ群(`anim` テーブル)、4 系統のトラックバー(Track0〜Track3)によるスクリプトへのパラメータ受け渡しに対応しています。
@@ -46,7 +46,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
本プラグインは YMM4 の「映像エフェクト」として動作し、エフェクトの種類一覧では「Luaスクリプト」として表示されます。
内部的には MoonSharp(Lua 5.2 互換のスクリプトエンジン)を組み込んでおり、ユーザーが記述した Lua スクリプトをフレームごとに実行します。スクリプト内で `obj.x` や `obj.alpha` といったグローバル変数を書き換えると、その値がオブジェクトの座標・拡縮・回転・不透明度として描画に反映されます。
内部的には高速ランタイム(LuaJIT)と MoonSharp(Lua 5.2 互換のスクリプトエンジン)を組み込んでおり、ユーザーが記述した Lua スクリプトをフレームごとに実行します。スクリプト内で `obj.x` や `obj.alpha` といったグローバル変数を書き換えると、その値がオブジェクトの座標・拡縮・回転・不透明度として描画に反映されます。
このエフェクトは独自のスクリプト実行系を基盤としつつ、AviUtl のアニメーション効果スクリプト(`.anm` 系)の一部に対する互換層を備えています(詳細は[AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。AviUtl 向けの EXO 出力(`.exo`)には対応していません。
@@ -60,7 +60,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
| YukkuriMovieMaker4 | 最新版を推奨 |
| ランタイム | .NET 10.0 |
※ スクリプトエンジン(MoonSharp)はプラグインに同梱されており、別途インストールする必要はありません。
※ スクリプトエンジン(LuaJIT・MoonSharp)はプラグインに同梱されており、別途インストールする必要はありません。
---
@@ -76,7 +76,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
### 1. スクリプトエンジン
スクリプトの実行エンジンには MoonSharp(Lua 5.2 互換)を使用しています。加えて、自ピクセル完結のピクセル写像(`obj.getpixel` で読み取り `obj.setpixel` で書き戻す二重ループ)は構文解析で検出して **CPU カーネル(式ツリー)** または **GPU カーネル(Direct2D ピクセルシェーダ)** へ実行時コンパイルして高速化し、それ以外のピクセル操作を含むスクリプトは同梱の高速ランタイム(**LuaJIT**)で自動実行されます(詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照)。いずれのエンジンでも利用可能な標準ライブラリは以下に限定されています。
スクリプトの実行エンジンには、同梱の高速ランタイム(**LuaJIT**)と MoonSharp(Lua 5.2 互換)を使用しています。ディレクティブを書いていないスクリプトは LuaJIT で実行され、自ピクセル完結のピクセル写像(`obj.getpixel` で読み取り `obj.setpixel` で書き戻す二重ループ)は構文解析で検出して **CPU カーネル(式ツリー)** へ実行時コンパイルしてさらに高速化されます。`native` フォルダが配備されていない環境と空のスクリプトは MoonSharp で実行されます(詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照)。いずれのエンジンでも利用可能な標準ライブラリは以下に限定されています。
- `table`、`string`、`math`、`bit32`
- 基本関数: `type`、`tostring`、`tonumber`、`select`、`error`、`assert`、`print`、`ipairs`、`pairs`、`next`、`unpack`、`setmetatable`、`getmetatable`、`rawget`、`rawset`、`rawequal`、`rawlen`、`pcall`、`xpcall`
@@ -113,7 +113,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
- **`obj.putpixeldata()`**: 互換性のために定義された空実装関数です。`setpixel` / `PixelDataProxy:set` による変更は自動的に反映されるため、呼び出す必要はありません。
`getpixel` / `setpixel` / `getpixeldata` のいずれかを最初に呼び出した時点で、GPU 上の画像データを CPU 側へ転送する処理が一度だけ発生します。ピクセル操作を行わないスクリプトではこの転送は発生しません。
これらのピクセル操作を含むスクリプトは自動的に高速化されます。自ピクセル完結のピクセル写像は CPU カーネル(式ツリー)または GPU カーネル(Direct2D ピクセルシェーダ)へ、それ以外は高速ランタイム(LuaJIT)へ自動で振り分けられ、いずれも従来エンジンに比べて大幅(内部計測で数十倍)に高速化されます。CPU カーネルと LuaJIT の出力結果は従来エンジンと一致します(GPU カーネルのみ float32 精度のためごく僅かに異なり得ます)。詳細・制約は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照してください。
これらのピクセル操作を含むスクリプトは自動的に高速化されます。自ピクセル完結のピクセル写像は CPU カーネル(式ツリー)へ、それ以外は高速ランタイム(LuaJIT)へ自動で振り分けられ、いずれも MoonSharp に比べて大幅(内部計測で数十倍)に高速化されます。CPU カーネルと LuaJIT の出力結果は MoonSharp と一致します(明示指定のみで使われる GPU カーネルは float32 精度のためごく僅かに異なり得ます)。詳細・制約は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照してください。
### 4. scene テーブルと ymm4 テーブル
@@ -213,7 +213,7 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
- **`@` による複数セクション**: 1 つのスクリプトに `@名前` で複数の効果が定義されている場合、先頭のセクションのみを実行します。
- **`obj.rand(st, ed [, seed [, frame]])`**: 指定範囲(`st`〜`ed`)の整数を返す決定論的な乱数です。`seed` と `frame` が同じであれば常に同じ値を返し、`frame` を省略すると現在のフレームを用います。従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)で同じ値を返します。
- **`obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])`**: 円・四角形・三角形・五角形・六角形・星形を生成し、オブジェクトのバッファを置き換えて描画します(出力は図形サイズに合わせて生成され、中心に配置されます)。`ライン` を省略するか `0` で塗りつぶし、サイズ以上の値でも塗りつぶしになります。`アスペクト`(-1.0〜1.0)で幅・高さを歪曲できます。
- **描画・メディア・バッファ・オプション API**: `obj.draw` / `obj.drawpoly` による描画合成、`obj.load` の `"text"` / `"image"` / `"movie"`、`obj.setfont`、`obj.copybuffer`、`obj.effect`、`obj.getvalue`、`obj.setoption` / `obj.getoption` / `obj.pixeloption` に対応しています。これらは従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。`obj.setoption` では `antialias` に加えて、`obj.draw` / `obj.drawpoly` の合成モードを YMM4 の並びで指定する `blend`、描画先を `"framebuffer"` / `"tempbuffer"` で切り替える `drawtarget`、作業画像の出力可否を切り替える `draw_state` に対応します。
- **描画・メディア・バッファ・オプション API**: `obj.draw` / `obj.drawpoly` による描画合成、`obj.load` の `"text"` / `"image"` / `"movie"`、`obj.setfont`、`obj.copybuffer`、`obj.effect`、`obj.getvalue`、`obj.setoption` / `obj.getoption` / `obj.pixeloption` に対応しています。これらは従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。`obj.setoption` では `antialias` に加えて、`obj.draw` / `obj.drawpoly` の合成モードを YMM4 の並びで指定する `blend`、描画先を `"framebuffer"` / `"tempbuffer"` で切り替える `drawtarget`、作業画像の出力可否を切り替える `draw_state` に対応します。MoonSharp では `tempbuffer` への合成を GPU で実行し、GPU を利用できない環境では CPU の合成へ自動的に切り替わります。丸めの違いにより、合成の結果はエンジン間でごく僅かに異なることがあります。
- **`obj.setanchor(name, count [, option, ...])`**: プレビュー上にドラッグ可能なアンカーポイントを表示し、その座標を `name` の Lua 変数(`pos={x0,y0,x1,y1,…}`、`"xyz"` 指定時は `{x0,y0,z0,…}`)へ格納します。座標はオブジェクトの中心が原点で、ドラッグで調整した値はプロジェクトへ保存されます。最大 32 個で、`"line"` / `"loop"` / `"star"` / `"arm"` の線結びと `"xyz"` の 3D 指定に対応します。設置数を返し、従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。`name` に `"track"` を指定するトラックバー連携は未対応です。
- **`obj.effect` の AviUtl/AviUtl2 互換マップ**: `obj.effect("エフェクト名", "パラメータ名", 値, …)` はまず互換マップを参照し、AviUtl/AviUtl2 の名前として宣言したエフェクトを、対応する YMM4 の映像エフェクトとプロパティへ変換して適用します。値の倍率とオフセットの変換まで宣言できます。互換マップに宣言が無い名前は、従来どおり YMM4 のエフェクト名・キーワードでそのまま解決するため、既存の呼び出しはそのまま動きます。この互換マップは YMM4 自身が AviUtl の `.exo` へ書き出す変換を逆向きにたどって構築しているため、往復しても結果が一致します。対象のエンジンは指定子 `--!aviutl` または `--!aviutl2` で切り替え、指定子を書かないときは `--!aviutl` として扱います。互換マップが対応するエフェクト名の一覧はドキュメントの「obj の関数」を参照してください。
@@ -231,8 +231,8 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
スクリプトは内容に応じて 4 つのエンジンへ自動的に振り分けられます。
- **自ピクセル完結のピクセル写像**(`for y … for x … obj.getpixel … obj.setpixel … end end` の形)→ **CPU カーネル(式ツリー)** へ実行時コンパイルして実行。
- **上記以外のピクセル操作を含むスクリプト**(`obj.getpixeldata` や近傍参照・別座標書き込みなど)→ 同梱の高速ランタイム **LuaJIT** で実行(ネイティブ実行)。
- **変形のみのスクリプト** → 従来の **MoonSharp** で実行。
- **上記以外のスクリプト** → 同梱の高速ランタイム **LuaJIT** で実行(ネイティブ実行)。
- **`native` フォルダが配備されていない環境と空のスクリプト** → **MoonSharp** で実行。
スクリプトの先頭行に次のディレクティブを書くと、エンジンを明示指定できます。
@@ -245,7 +245,7 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
CPU / GPU カーネルが成立するのは、四則演算・`math.*`・比較・しきい値の「条件 and 値1 or 値2」・`local` 変数のみを使い、処理中の自ピクセル(`obj.getpixel(x, y)`)と `obj` / `scene` / `time` 等の値だけを参照する純粋な写像(色変換・グレースケール・ガンマ・しきい値・チャンネル混合など)の場合です。近傍参照(ぼかし等)・別座標への書き込み・`getpixeldata`・`getobject`・テーブル/文字列操作・`if` 文などを含む場合はカーネル化されず、自動的に LuaJIT または MoonSharp で実行されます。コンパイル済みのカーネルはスクリプト本文をキーにキャッシュされ、初回フレームのみコンパイルコストを払います。
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で受け渡されます。スクリプトが無限ループに陥った場合でも **5 秒のタイムアウトでプロセスを強制終了**するため本体は固まらず、終了後は自動的に復帰します。出力結果は従来エンジンと一致します。
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で受け渡されます。ピクセルの転送はスクリプトがピクセルへ初めてアクセスした時点でのみ行われるため、変形や描画だけのスクリプトでは転送が発生しません。ワーカープロセスは入力画像のサイズが変わっても再起動せず、フレームをまたいで再利用されます。スクリプトが無限ループに陥った場合でも **5 秒のタイムアウトでプロセスを強制終了**するため本体は固まらず、終了後は自動的に復帰します。出力結果は MoonSharp と一致します。
`obj.getobject` はネイティブ実行でも利用できます。呼び出し時に本体プロセスへ同期的に問い合わせてシーンオブジェクトを解決するため、従来エンジンと同じ結果を返します。同じタグ・同じフレームへの連続した問い合わせはフレーム内でキャッシュされ、2 回目以降は往復を行いません。
@@ -272,7 +272,7 @@ CPU / GPU カーネルが成立するのは、四則演算・`math.*`・比較
### グローバル変数のリセットと整合性チェック
内部の Lua 実行環境(Script / Table インスタンス)は性能のためフレームをまたいで再利用されますが、スクリプトが定義したユーザー定義のグローバル変数や、`obj` / `scene` / `anim` / `ymm4` テーブルへスクリプトが追加したキーは、各フレームの実行開始時に初期状態のスナップショットと比較して取り除かれます。これにより、あるフレームでスクリプトが作成した状態が次のフレームへ意図せず持ち越されることを防いでいます。
内部の Lua 実行環境は性能のためフレームをまたいで再利用されますが、スクリプトが定義したユーザー定義のグローバル変数や、`obj` / `scene` / `anim` / `ymm4` テーブルへスクリプトが追加したキーは、各フレームの実行開始時に初期状態のスナップショットと比較して取り除かれます。これにより、あるフレームでスクリプトが作成した状態が次のフレームへ意図せず持ち越されることを防いでいます。このリセットは LuaJIT と MoonSharp のどちらのエンジンでも同じように行われます。
また、実行のたびに組み込みの `math` グローバルがテーブル型のまま残っているかを確認し、スクリプトの誤操作などで破壊されていた場合は Lua 実行環境ごと再構築します。
@@ -374,7 +374,7 @@ obj.alpha = anim.ease_out(t) * 255
- **AviUtl 互換は部分的**: AviUtl のアニメーション効果スクリプトのうち、変形・不透明度・乱数の範囲のみ実行できます([AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。描画・フィルタ・ファイルアクセス系の関数、および AviUtl 向けの EXO 出力(`.exo`)には対応していません。
- **実行タイムアウト**: スクリプトの実行は 5000ms(5秒)でタイムアウトし、超過した場合は強制終了されエラーとして扱われます。無限ループが発生しないよう注意してください。
- **利用可能な標準ライブラリの制限**: `table`、`string`、`math`、`bit32` および基本関数のみ利用できます。`io`、`os`、`debug`、`ffi`、`require` は利用できません。
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します(GPU カーネルはこの転送を行いません)。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは内容に応じて CPU カーネル・GPU カーネル・高速ランタイム(LuaJIT)のいずれかで自動実行され大幅に高速化されます。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します(GPU カーネルはこの転送を行いません)。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは内容に応じて CPU カーネルまたは高速ランタイム(LuaJIT)で自動実行され大幅に高速化されます。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
- **`math.random` はフレームごとの決定論的な乱数**: 毎フレーム `frame` の値でシードし直されるため、同一フレームでは常に同じ値になります。フレームをまたいで変化する乱数的な値が必要な場合は `anim.rand` の利用を検討してください。
- **`obj.oz` は出力に反映されません**: スクリプト実行後にコンテキストへ読み戻されますが、現在の実装では中心点オフセットの出力計算に使用されていません。
- **エクスポートは先頭の1件のみ**: 複数アイテムを選択した状態でも、エクスポートされるスクリプトは先頭のアイテムのもののみです(インポート・クリアは選択中のすべてのアイテムに適用されます)。
@@ -399,8 +399,8 @@ obj.alpha = anim.ease_out(t) * 255
| ソフトウェア | 用途 | ライセンス |
|---|---|---|
| [MoonSharp](https://github.com/moonsharp-devs/moonsharp) | 標準のLua実行エンジン(Lua 5.2 互換) | 3-Clause BSD License |
| [LuaJIT](https://github.com/LuaJIT/LuaJIT) | ピクセル操作向け高速ランタイム(`native/luajit.exe`・`lua51.dll`) | MIT License |
| [MoonSharp](https://github.com/moonsharp-devs/moonsharp) | フォールバック用のLua実行エンジン(Lua 5.2 互換) | 3-Clause BSD License |
| [LuaJIT](https://github.com/LuaJIT/LuaJIT) | 標準の高速ランタイム(`native/luajit.exe`・`lua51.dll`) | MIT License |
### MoonSharp(3-Clause BSD License)
+10 -8
ファイルの表示
@@ -14,17 +14,17 @@
<h1>エンジンと高速化</h1>
<p>
このプラグインには複数の実行エンジンがあります。標準は MoonSharp ですが、重いピクセル処理のために
LuaJIT ネイティブレーンや、CPU / GPU カーネルへ変換するレーンを選べます。
座標などを動かすだけのスクリプトでは MoonSharp で十分速く、エンジンを意識する必要はありません。
このプラグインには複数の実行エンジンがあります。標準は同梱の LuaJIT ネイティブレーンで、
決まった形の重いピクセル処理はさらに CPU カーネルへ変換されます。Lua 5.2 互換の MoonSharp は
フォールバック用の従来エンジンです。指定子を書かなくても、内容に応じて自動で最適なレーンが選ばれます。
</p>
<h2>エンジンの種類</h2>
<table>
<tr><th>エンジン</th><th>指定子</th><th>特徴</th></tr>
<tr><td>MoonSharp</td><td><code>--!moonsharp</code>(既定)</td><td>Lua 5.2 互換。全機能が使える標準エンジン</td></tr>
<tr><td>ネイティブ(LuaJIT)</td><td><code>--!native</code></td><td>別プロセスの LuaJIT で実行。ピクセル処理が大幅に高速</td></tr>
<tr><td>ネイティブ(LuaJIT)</td><td><code>--!native</code>(既定)</td><td>別プロセスの LuaJIT で実行。ピクセル処理が大幅に高速</td></tr>
<tr><td>MoonSharp</td><td><code>--!moonsharp</code></td><td>Lua 5.2 互換。フォールバック用の従来エンジン</td></tr>
<tr><td>CPU カーネル</td><td><code>--!cpu</code></td><td>決まった形のピクセルループを並列実行に変換。MoonSharp と一致する結果</td></tr>
<tr><td>GPU カーネル</td><td><code>--!gpu</code></td><td>ピクセルループを GPU シェーダーに変換。最速だが float32 精度(明示指定のみ)</td></tr>
</table>
@@ -57,9 +57,8 @@ end</code></pre>
<ul>
<li>後述のカーネル条件に当てはまるピクセルループは、CPU カーネルで実行します。結果は MoonSharp と一致します。</li>
<li><code>obj.setoption</code> を使う描画系のスクリプトは、MoonSharp で実行します。</li>
<li>カーネル条件には当てはまらないものの <code>getpixel</code> や <code>setpixel</code> を使うスクリプトは、ネイティブが使えればネイティブで実行します。</li>
<li>それ以外は MoonSharp で実行します。</li>
<li>それ以外のスクリプトは、同梱の LuaJIT ネイティブで実行します。結果は MoonSharp と一致します。</li>
<li><code>native</code> フォルダが配備されていない環境と空のスクリプトは、MoonSharp で実行します。</li>
</ul>
<div class="note">
@@ -113,6 +112,9 @@ end</code></pre>
<li><code>--!gpu</code> を指定しても、GPU カーネルを初期化できない場合は CPU カーネル、さらに MoonSharp の順で
フォールバックします。</li>
<li><code>--!cpu</code> を指定してもカーネル条件に合わないスクリプトは、ほかのエンジンで実行されます。</li>
<li>MoonSharp では <code>tempbuffer</code> への描画合成を GPU で実行し、GPU を利用できない環境では
CPU の合成へ自動的に切り替わります。丸めの違いにより、合成の結果はエンジン間で
ごく僅かに異なることがあります。</li>
</ul>
<div class="warn">
+3 -3
ファイルの表示
@@ -20,9 +20,9 @@ YukkuriMovieMaker4 の映像エフェクト「Lua スクリプト」の公式ド
</p>
<p>
標準のスクリプトエンジンは Lua 5.2 互換の MoonSharp です。
重いピクセル処理のためには、LuaJIT で実行する <code>--!native</code> レーンと、
CPU・GPU カーネルへ変換する <code>--!cpu</code>・<code>--!gpu</code> レーンも用意しています。
標準のスクリプトエンジンは LuaJIT で実行するネイティブレーンで、
決まった形のピクセル処理は <code>--!cpu</code> の CPU カーネルへ変換されます。
Lua 5.2 互換の MoonSharp はフォールバックとして使われ、明示指定の <code>--!gpu</code> レーンも用意しています。
詳しくは<a href="engines.html">エンジンと高速化</a>を参照してください。
</p>
+2
ファイルの表示
@@ -235,6 +235,8 @@ obj.draw()</code></pre>
<p>
<code>tempbuffer</code> への合成は通常(ソースオーバー)で、<code>blend</code> は <code>framebuffer</code> への描画に適用されます。
描画先の切り替えは両エンジンで動きます。
MoonSharp では <code>tempbuffer</code> への合成を GPU で実行し、GPU を利用できない環境では CPU の合成へ自動的に切り替わります。
丸めの違いにより、合成の結果はエンジン間でごく僅かに異なることがあります。
</p>
<pre><code>obj.setoption("drawtarget", "tempbuffer", obj.w, obj.h)
+2 -2
ファイルの表示
@@ -125,8 +125,8 @@ A チャンネル(インデックス <code>base + 4</code>)を変更する
<p>
ピクセル処理は重くなりがちです。このプラグインは <code>getpixel</code> / <code>setpixel</code> を含むスクリプトを
自動的に高速なネイティブレーンへ振り分けます(利用できる場合)。さらに、二重ループで
<code>getpixel</code> → 計算 → <code>setpixel</code> という決まった形のスクリプトは、CPU / GPU カーネルへ
変換されてさらに高速に実行できます。詳しくは <a href="engines.html">エンジンと高速化</a> を参照してください。
<code>getpixel</code> → 計算 → <code>setpixel</code> という決まった形のスクリプトは、CPU カーネルへ
変換されてさらに高速に実行できます。<code>--!gpu</code> を明示すると GPU カーネルも使えます。詳しくは <a href="engines.html">エンジンと高速化</a> を参照してください。
</p>
<div class="pager">
+44
ファイルの表示
@@ -70,6 +70,7 @@ local CB_KIND_LOADTEXT = 5
local CB_KIND_LOADIMAGE = 6
local CB_KIND_LOADMOVIE = 7
local CB_KIND_SETANCHOR = 8
local CB_KIND_REQUESTPIXELS = 9
assert(loadfile(shimPath))()
@@ -88,8 +89,18 @@ local buffers = {}
local options = {}
local pixeloptions = {}
local dirty = false
local pixelsValid = false
local drawTarget = "frame"
local function ensurePixels()
if pixelsValid then return end
i32[OFF_CB_KIND] = CB_KIND_REQUESTPIXELS
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
pixelsValid = true
end
local function sampleSource(src, srcW, srcH, u, v, linear)
if not linear then
local su = clamp(math.floor(u), 0, srcW - 1)
@@ -233,6 +244,7 @@ local ymm4 = {}
function obj.getpixel(x, y)
x = math.floor(x); y = math.floor(y)
if x < 0 or y < 0 or x >= width or y >= height then return 0, 0, 0, 0 end
ensurePixels()
local p = pixels + (y * width + x) * 4
local a = p[3]
if a <= 0 then return 0, 0, 0, 0 end
@@ -243,6 +255,7 @@ end
function obj.setpixel(x, y, r, g, b, a)
x = math.floor(x); y = math.floor(y)
if x < 0 or y < 0 or x >= width or y >= height then return end
ensurePixels()
a = a or 255
dirty = true
local aK = clamp(a, 0, 255) / 255
@@ -254,6 +267,7 @@ function obj.setpixel(x, y, r, g, b, a)
end
function obj.getpixeldata()
ensurePixels()
local total = width * height * 4
local buf = pixels
local pd = { width = width, height = height }
@@ -329,6 +343,7 @@ local function applyLoadResult()
i32[OFF_WIDTH] = newW
i32[OFF_HEIGHT] = newH
dirty = true
pixelsValid = true
obj.w = newW; obj.h = newH
obj.hw = newW / 2; obj.hh = newH / 2
obj.cx = newW / 2; obj.cy = newH / 2
@@ -447,6 +462,7 @@ end
function obj.draw(ox, oy, oz, zoom, alpha, aspect)
if drawTarget == "temp" then
ensurePixels()
local t = ensureTemp()
compositeDrawInto(t.data, t.w, t.h, pixels, width, height,
ox or 0, oy or 0, zoom or 1, aspect or 0, alpha or 1, (options.antialias or 1) ~= 0)
@@ -488,6 +504,7 @@ function obj.drawpoly(...)
end
p[20] = alpha
if drawTarget == "temp" then
ensurePixels()
local t = ensureTemp()
compositeDrawPolyInto(t.data, t.w, t.h, pixels, width, height, p, alpha, (options.antialias or 1) ~= 0)
return
@@ -584,6 +601,7 @@ function obj.copybuffer(dst, src)
local sk, skey = bufferKind(src)
local data, w, h
if sk == "o" then
ensurePixels()
data = pixels
w = width; h = height
elseif sk == "t" or sk == "c" then
@@ -601,6 +619,7 @@ function obj.copybuffer(dst, src)
width = w; height = h
i32[OFF_WIDTH] = w; i32[OFF_HEIGHT] = h
dirty = true
pixelsValid = true
obj.w = w; obj.h = h
obj.hw = w / 2; obj.hh = h / 2
obj.cx = w / 2; obj.cy = h / 2
@@ -669,6 +688,23 @@ sandbox = {
}
sandbox._G = sandbox
local function captureKeys(t)
local keys = {}
for k in pairs(t) do keys[k] = true end
return keys
end
local function resetExtraKeys(t, keys)
for k in pairs(t) do
if not keys[k] then t[k] = nil end
end
end
local sandboxKeys = captureKeys(sandbox)
local objKeys = captureKeys(obj)
local sceneKeys = captureKeys(scene)
local ymm4Keys = captureKeys(ymm4)
local compiledCode, compiledChunk
local function loadFields()
@@ -695,6 +731,9 @@ local function loadFields()
obj.timelineframe = f64[51]; obj.timelinetime = f64[52]
obj.check0 = f64[53] ~= 0; obj.check1 = f64[54] ~= 0; obj.check2 = f64[55] ~= 0; obj.check3 = f64[56] ~= 0
sandbox.color = (f64[57] >= 0) and f64[57] or nil
sandbox.time = f64[30]; sandbox.frame = f64[31]; sandbox.totalframe = f64[32]
sandbox.framerate = f64[35]; sandbox.layer = f64[36]
sandbox.timelineframe = f64[51]; sandbox.timelinetime = f64[52]
end
local function loadStringParams()
@@ -729,6 +768,7 @@ while true do
if i32[OFF_COMMAND] == 1 then break end
dirty = false
pixelsValid = false
local scriptLen = i32[OFF_SCRIPTLEN]
local code = ffi.string(base + SCRIPT_OFFSET, scriptLen)
@@ -748,6 +788,10 @@ while true do
end
if compiledChunk and code == compiledCode then
resetExtraKeys(sandbox, sandboxKeys)
resetExtraKeys(obj, objKeys)
resetExtraKeys(scene, sceneKeys)
resetExtraKeys(ymm4, ymm4Keys)
loadFields()
loadStringParams()
cacheTag = nil