コミットを比較

...
59 コミット
作成者 SHA1 メッセージ 日付
routersys bcac943775 バージョンをv1.8.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.8.0 のコミットから作成しました
2026-06-29 18:21:46 +09:00
routersys 3d0ff687e2 drawpolyの座標12個+不透明度形式を全ドキュメントに追記 2026-06-29 17:32:06 +09:00
routersys ce0da92ac8 マージ 2026-06-29 17:25:40 +09:00
routersys 7dbe063ac8 ドキュメントアラビア語をAviUtl互換実装へ更新 2026-06-29 14:52:55 +09:00
routersys 1acaef291c ドキュメントインドネシア語をAviUtl互換実装へ更新 2026-06-29 14:51:18 +09:00
routersys 26c96b302f ドキュメントスペイン語をAviUtl互換実装へ更新 2026-06-29 14:49:51 +09:00
routersys c4011d8eef ドキュメント韓国語をAviUtl互換実装へ更新 2026-06-29 14:48:19 +09:00
routersys 451b017f6f ドキュメント繁体字中国語をAviUtl互換実装へ更新 2026-06-29 14:46:57 +09:00
routersys d6b6e440bf ドキュメント簡体字中国語をAviUtl互換実装へ更新 2026-06-29 14:45:37 +09:00
routersys 7601b77902 ドキュメント英語をAviUtl互換実装へ更新 2026-06-29 14:44:24 +09:00
routersys 0799785cad ドキュメント日本語をAviUtl互換実装へ更新 2026-06-29 14:43:02 +09:00
routersys d607e4ec49 ヘッダー検証付きobj.load(movie)を両エンジンで実装 2026-06-29 14:38:32 +09:00
routersys c7e5b91509 マージ 2026-06-29 10:26:56 +09:00
routersys cf23d184fe ヘッダー検証付きobj.load(image)を両エンジンで実装 2026-06-29 10:08:59 +09:00
routersys d2b518f611 obj.load(text)とsetfontをネイティブエンジンへ対応 2026-06-29 10:01:06 +09:00
routersys c186a6b27d obj.load(text)とsetfontを従来エンジンで実装 2026-06-29 09:55:12 +09:00
routersys 5f411e89ec オプションAPIと描画補間反映を両エンジンで実装 2026-06-29 08:41:21 +09:00
routersys 16ed6336c3 obj.getvalueで現在のobj値取得を両エンジンで実装 2026-06-29 08:34:50 +09:00
routersys 6d2a5cbe24 obj.copybufferのバッファ保存復元を両エンジンで実装 2026-06-29 08:31:53 +09:00
routersys 94f7ad4f50 obj.drawpolyのアフィン四角形描画を両エンジンで実装 2026-06-29 08:26:00 +09:00
routersys 3ba77aab18 obj.drawをネイティブエンジンへ対応 2026-06-29 08:16:51 +09:00
routersys 90fe288f66 obj.drawの蓄積描画合成を従来エンジンで実装 2026-06-29 08:11:26 +09:00
routersys 6b2b5d879f Create CNAME 2026-06-29 07:26:46 +09:00
routersys d01d5d6df5 Delete CNAME 2026-06-29 07:26:40 +09:00
routersys a093c458a2 バージョンをv1.7.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.7.1 のコミットから作成しました
2026-06-28 22:47:30 +09:00
routersys 0e65bf1883 ネイティブ環境でのobj.load及びobj.effect対応 2026-06-28 22:39:09 +09:00
routersys d8f728b3f9 Direct2Dピクセル管理の責務分離 2026-06-28 16:17:19 +09:00
routersys 244e75a238 Transform書き戻し処理の共通化 2026-06-28 16:16:54 +09:00
routersys 75cc4bd62e トークン解析処理の共通化と抽出 2026-06-28 16:16:35 +09:00
routersys 6385dbeb6d ScriptDirectiveクラスの抽出分離 2026-06-28 16:16:02 +09:00
routersys bc395a0181 SceneObjectQueryを個別ファイルへ分離 2026-06-28 16:15:37 +09:00
routersys a0dec019fe 例外クラス群を個別ファイルへ分離 2026-06-28 16:15:02 +09:00
routersys c8350161db バージョンをv1.7.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.7.0 のコミットから作成しました
2026-06-28 14:35:28 +09:00
routersys 679cab03b5 LuaScriptEffectProcessorにobj.effectチェーン適用を統合し、失敗時は元画像へフォールバック 2026-06-28 14:35:14 +09:00
routersys 6783146231 YMM4映像エフェクトを名前/別名で解決し適用するVideoEffectChainを追加 2026-06-28 14:35:08 +09:00
routersys df303ee154 LuaScriptEngineにobj.effectコールバックを追加し要求を記録 2026-06-28 14:34:57 +09:00
routersys f49bd740a0 AviUtlScriptContextにobj.effect要求の記録/クリアを追加 2026-06-28 14:34:50 +09:00
routersys 80d1b75227 obj.effectの要求を表すAviUtlEffectRequest型を追加 2026-06-28 14:34:42 +09:00
routersys d7f981c38a バージョンをv1.6.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.6.0 のコミットから作成しました
2026-06-28 10:49:58 +09:00
routersys df0c63a270 --check/--colorが展開されないことを検証するテストへ更新 2026-06-28 10:43:26 +09:00
routersys 7766b116dc AviUtlParameterLayoutの解析テストを追加 2026-06-28 10:43:21 +09:00
routersys eb8f4e8055 トラック値のディレクティブ範囲クランプとcheck/color反映を追加 2026-06-28 10:43:03 +09:00
routersys 04563a7242 --track/--check/--colorに応じた動的UIをLuaScriptEffectに実装 2026-06-28 10:42:57 +09:00
routersys 875d954520 --check/--colorの擬似展開を廃止しUI値を唯一のソースに変更 2026-06-28 10:42:48 +09:00
routersys bd7f2ae691 ネイティブ(LuaJIT)実行へcheck0〜3/colorフィールドを配線 2026-06-28 10:42:32 +09:00
routersys 36b3c880fe obj.check0〜3とcolorをスクリプトへ引き渡す処理を追加 2026-06-28 10:42:12 +09:00
routersys 230e6f010c チェック/色の動的パラメータ用ラベルを多言語リソースへ追加 2026-06-28 10:41:50 +09:00
routersys ef16ae64fb AviUtlヘッダ(--track/--check/--color)の解析クラスを追加 2026-06-28 10:41:37 +09:00
routersys 0204d480e2 バージョンをv1.5.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.5.0 のコミットから作成しました
2026-06-28 02:27:37 +09:00
routersys 7e1f2c1d7c obj.load("figure")による図形描画を各ドキュメントへ追記 2026-06-28 02:27:17 +09:00
routersys bab81d27e5 obj.load("figure")による図形描画を実装 2026-06-28 02:15:44 +09:00
routersys a3efd55ce6 SDFベースの図形ラスタライザを追加 2026-06-28 02:14:07 +09:00
routersys 4f2389702a バージョンをv1.4.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.4.0 のコミットから作成しました
2026-06-28 01:29:44 +09:00
routersys 247bb83230 AviUtl部分互換とobj.randを全ドキュメントへ追記 2026-06-28 01:28:32 +09:00
routersys 1d495039f0 AviUtlスクリプトのヘッダ・セクションを解釈する前処理層を追加 2026-06-28 01:28:15 +09:00
routersys 56d7937be1 AviUtlスクリプトのヘッダ・セクションを解釈する前処理層を追加 2026-06-28 01:27:31 +09:00
routersys cade7e8a8f バージョンをv1.3.4へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.3.4 のコミットから作成しました
2026-06-27 19:51:21 +09:00
routersys 9e8e024db9 obj.getobjectのキャッシュ動作をREADMEに追記 2026-06-27 19:50:41 +09:00
routersys 69881878e4 obj.getobjectの同一タグ・同一フレーム問い合わせをキャッシュし往復を削減 2026-06-27 19:50:28 +09:00
62個のファイルの変更、5368行の追加、421行の削除

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

+70 -25
ファイルの表示
@@ -1,39 +1,84 @@
# v1.3.3 - Lua スクリプト for YMM4
# v1.8.0 - Lua スクリプト for YMM4
これまでネイティブ実行では使用できなかった **`obj.getobject` がネイティブ実行でも
利用可能**になったリリースです。ピクセル操作と他オブジェクトの参照を 1 つの
スクリプトで併用できるようになりました。
AviUtl 互換の描画合成・メディア読み込み・値/オプション API を新たに実装し、
従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の両方で対称に動作させた
リリースです。あわせて全 8 言語のドキュメントを実装状況へ同期しました。
---
## 新機能・改善
## 新機能・機能改善
### 1. `obj.getobject` をネイティブ実行でも利用可能に
### 1. 描画合成 obj.draw / obj.drawpoly
ピクセル操作を含むスクリプトはネイティブ実行へ振り分けられますが、これまでは
ネイティブ実行中の `obj.getobject` が常に `nil` を返していました。本リリースでは、
ネイティブ実行中に `obj.getobject` を呼び出すと**本体プロセスへ同期的に問い合わせて
シーンオブジェクトを解決**するようにしました。従来エンジンと同じ描画情報を返すため、
ピクセル操作と他オブジェクトの参照を 1 つのスクリプトで併用できます。
`--!moonsharp` を明示してエンジンを切り替える必要はなくなりました。
オブジェクト画像を蓄積バッファへ重ねて合成する描画 API に対応しました。
残像・パーティクル・敷き詰めなど、複数回の描画を伴う表現が利用できます。
- `obj.draw([ox, oy, oz [, 拡大率 [, 不透明度 [, アスペクト]]]])` で、現在の
オブジェクト画像を任意のオフセット・拡大率・不透明度で合成します。複数回
呼び出すと重ね描画されます。
- `obj.drawpoly(...)` で 4 頂点へオブジェクト画像をテクスチャ描画します。UV
指定による部分描画、UV を省略した不透明度のみ指定(座標 12 個 + 不透明度)に
対応します。アフィン変換で写像します。
- `obj.setoption("antialias", ...)` の指定が描画時の補間(最近傍/線形)へ
反映されます。
- いずれかの描画 API を呼び出すと標準描画は抑制され、合成結果が出力されます。
### 2. メディア読み込み obj.load("text" / "image" / "movie") と obj.setfont
`obj.load` の対象を図形("figure")のみから、テキスト・画像ファイル・動画
ファイルへ拡張しました。
- `obj.load("text", 文字列)`:`obj.setfont` で指定したフォント・サイズ・
スタイル・色で文字列を描画します(DirectWrite)。
- `obj.load("image", パス)`:画像ファイルを読み込みます(WIC)。
- `obj.load("movie", パス [, 時間])`:動画の指定時間のフレームを読み込みます
(Media Foundation)。
- 読み込み後は `obj.w` / `obj.h` 等が生成サイズへ更新され、`obj.load` 直後の
`getpixel` でも参照できます。
### 3. バッファ操作 obj.copybuffer
バッファ間で画像をコピーする `obj.copybuffer(コピー先, コピー元)` に対応しま
した。`"obj"`(オブジェクト画像)・`"tmp"`(一時バッファ)・`"cache:名前"`
(フレーム間で保持する名前付きキャッシュ)を識別子の先頭文字で判定します。
### 4. 値・オプション API
スクリプトから現在値やオプションを扱う API を追加しました。
- `obj.getvalue(対象)`:`obj.x` や `obj.track0` 等の現在値を取得します。
- `obj.setoption(名前, 値)` / `obj.getoption(名前)`:オプションを設定・取得
します。未対応の項目も受理してスクリプトを停止させません。
- `obj.pixeloption(名前, 値)`:ピクセル操作のオプションを状態として保持します。
---
## 注意事項
## セキュリティ / 安全性
- ネイティブ実行中の `obj.getobject` は、呼び出しごとに本体プロセスへの往復が
発生します。1 フレーム内で多数のオブジェクトを参照する場合は、結果を変数へ
保持して呼び出し回数を抑えることを推奨します。
- `obj.getobject` を含むスクリプトの実行時間も、従来どおり 5 秒のタイムアウトの
対象です。問い合わせを含めた総実行時間が 5 秒を超えると強制終了されます。
- `obj.load("image" / "movie")` は、ファイルの先頭ヘッダー(マジックバイト)を
検証し、真正なメディアと確認できたファイルのみを読み込みます。対応形式は
画像が PNG / JPEG / GIF / BMP / TIFF / WebP、動画が MP4 / MOV / MKV / WebM /
AVI / FLV / ASF です。
- スクリプトへ生のファイルアクセス(`require` / `io` / `dofile`)は引き続き
公開せず、サンドボックスを維持したままメディア読み込みを実現しました。
---
## 内部実装
## 内部実装の最適化(リファクタリング)
- ネイティブ実行の共有メモリプロトコルに同期コールバックを追加しました。ワーカーは
`obj.getobject` の呼び出し時にタグとフレームを共有メモリへ書き込み、本体側が
シーンオブジェクトを解決して結果を書き戻します。解決したオブジェクトは
描画キャッシュの検証対象に含めるため、フレーム間のキャッシュ整合性は保たれます。
- コールバックを含む実行全体に対して単一の実行期限を適用し、`obj.getobject` を
繰り返し呼び出すスクリプトでもタイムアウトが必ず機能するようにしました。
新機能を両エンジンで対称に提供するため、設計の一貫性を重視した実装を行いました。
- **描画・メディア生成パイプライン**
- 描画合成は専用の蓄積描画ターゲットで処理し、複数回の `obj.draw` を破綻なく
重ね合わせます。
- テキスト・画像・動画はスレッド非依存の CPU 生成(DirectWrite / WIC /
Media Foundation)で実体化し、既存の図形即時反映パスへ合流させることで、
`obj.load` 直後のピクセル参照を両エンジンで成立させました。
- **ネイティブ通信プロトコルの拡張**
- 高速ランタイムからホストへの描画・読み込みコールバックを拡充し、図形・
テキスト・画像・動画の生成と描画合成をネイティブ環境でも同一仕様で動作
させました。
- **ドキュメントの同期**
- 日本語・英語・簡体字中国語・繁体字中国語・韓国語・スペイン語・インドネシア
語・アラビア語の全 8 言語について、新 API・対応状況・制限事項を実装に合わせて
更新しました。
+1 -1
ファイルの表示
@@ -1,5 +1,5 @@
========================================
Luaスクリプト for YMM4 v1.3.3
Luaスクリプト for YMM4 v1.8.0
========================================
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
ピクセルを直接制御できるプラグインです。
+120
ファイルの表示
@@ -0,0 +1,120 @@
using LuaScript.Compat;
namespace LuaScript.Tests
{
public class AviUtlParameterLayoutTests
{
[Fact]
public void NoDirectives_HasAnyIsFalse()
{
var layout = AviUtlParameterLayout.Parse("obj.x = 1\nobj.y = 2");
Assert.False(layout.HasAny);
Assert.False(layout.HasTrack(0));
Assert.False(layout.HasColor);
}
[Fact]
public void Track_ParsesNameRangeDefaultStep()
{
var layout = AviUtlParameterLayout.Parse("--track0:Amp,0,100,10,0.5\nobj.ox = obj.track0");
Assert.True(layout.HasAny);
var t = layout.GetTrack(0);
Assert.NotNull(t);
Assert.Equal("Amp", t!.Value.Name);
Assert.Equal(0d, t.Value.Min);
Assert.Equal(100d, t.Value.Max);
Assert.Equal(10d, t.Value.Default);
Assert.Equal(0.5d, t.Value.Step);
}
[Fact]
public void Track_DefaultIsClampedIntoRange()
{
var layout = AviUtlParameterLayout.Parse("--track1:V,0,10,999");
var t = layout.GetTrack(1);
Assert.Equal(10d, t!.Value.Default);
}
[Fact]
public void Track_SwapsInvertedMinMax()
{
var layout = AviUtlParameterLayout.Parse("--track0:V,100,0,50");
var t = layout.GetTrack(0);
Assert.Equal(0d, t!.Value.Min);
Assert.Equal(100d, t.Value.Max);
}
[Fact]
public void Track_NegativeRangeParses()
{
var layout = AviUtlParameterLayout.Parse("--track2:Off,-100,100,-25");
var t = layout.GetTrack(2);
Assert.Equal(-100d, t!.Value.Min);
Assert.Equal(-25d, t.Value.Default);
}
[Fact]
public void Track_IndexBeyondThreeIsIgnored()
{
var layout = AviUtlParameterLayout.Parse("--track4:V,0,10,5");
Assert.False(layout.HasAny);
}
[Fact]
public void Check_ParsesDefaultAsBool()
{
var layout = AviUtlParameterLayout.Parse("--check0:On,1\n--check1:Off,0");
Assert.True(layout.GetCheck(0)!.Value.Default);
Assert.False(layout.GetCheck(1)!.Value.Default);
Assert.Equal("On", layout.GetCheck(0)!.Value.Name);
}
[Fact]
public void Color_ParsesHexLiteral()
{
var layout = AviUtlParameterLayout.Parse("--color:0xff8800");
Assert.True(layout.HasColor);
Assert.Equal(0xff8800, layout.Color!.Value.Default);
}
[Fact]
public void Color_ParsesDecimalLiteral()
{
var layout = AviUtlParameterLayout.Parse("--color:255");
Assert.Equal(255, layout.Color!.Value.Default);
}
[Fact]
public void Combined_TrackCheckColorAllDetected()
{
const string src =
"--track0:Amp,0,100,10\n" +
"--track1:Spd,0,50,5\n" +
"--check0:Enable,1\n" +
"--color:0x112233\n" +
"obj.ox = obj.track0";
var layout = AviUtlParameterLayout.Parse(src);
Assert.True(layout.HasTrack(0));
Assert.True(layout.HasTrack(1));
Assert.False(layout.HasTrack(2));
Assert.True(layout.HasCheck(0));
Assert.True(layout.HasColor);
}
[Fact]
public void Section_OnlyFirstSectionHeaderIsScanned()
{
const string src = "@First\n--track0:A,0,10,3\n@Second\n--track1:B,0,10,4";
var layout = AviUtlParameterLayout.Parse(src);
Assert.True(layout.HasTrack(0));
Assert.False(layout.HasTrack(1));
}
[Fact]
public void EngineDirective_IsNotMistakenForParameter()
{
var layout = AviUtlParameterLayout.Parse("--!native\nobj.x = 1");
Assert.False(layout.HasAny);
}
}
}
+71
ファイルの表示
@@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using LuaScript.Compat;
namespace LuaScript.Tests
{
public class AviUtlRandomEquivalenceTests
{
[Fact]
public void Rand_StaysWithinRequestedRange()
{
for (int seed = 0; seed < 64; seed++)
{
double value = AviUtlRandom.Next(-3, 7, seed, seed * 3 + 1);
Assert.InRange(value, -3d, 7d);
Assert.Equal(Math.Floor(value), value);
}
}
[Fact]
public void Rand_IsDeterministicForSameInputs()
{
Assert.Equal(
AviUtlRandom.Next(0, 100, 5, 12),
AviUtlRandom.Next(0, 100, 5, 12));
}
[Fact]
public void Rand_MatchesBetweenMoonSharpAndLuaJit()
{
var lane = new LuaJitLane();
Assert.True(lane.Available, "native/luajit.exe must be present");
var cases = new List<(double A, double B, double Seed, double Frame)>();
for (int seed = 0; seed < 16; seed++)
for (int frame = 0; frame < 4; frame++)
{
cases.Add((0d, 100d, seed, frame));
cases.Add((-50d, 50d, seed + 1, frame * 7));
cases.Add((1d, 6d, seed * 13, frame));
cases.Add((-3.5d, 3.5d, seed, frame + 1000));
}
var exprs = new List<string>(cases.Count);
foreach (var c in cases)
exprs.Add($"aviutl_rand({L(c.A)},{L(c.B)},{L(c.Seed)},{L(c.Frame)})");
string[] lines = lane.Eval(exprs);
Assert.Equal(exprs.Count, lines.Length);
var failures = new List<string>();
for (int i = 0; i < cases.Count; i++)
{
double expected = AviUtlRandom.Next(cases[i].A, cases[i].B, cases[i].Seed, cases[i].Frame);
if (!double.TryParse(lines[i], NumberStyles.Float, CultureInfo.InvariantCulture, out var got))
{
failures.Add($"{exprs[i]} => luajit '{lines[i]}' (not a number), expected {expected}");
continue;
}
if (got != expected)
failures.Add($"{exprs[i]} => luajit {got}, moonsharp {expected}");
}
Assert.True(failures.Count == 0,
$"{failures.Count}/{cases.Count} mismatches:\n" + string.Join("\n", failures.GetRange(0, Math.Min(25, failures.Count))));
}
private static string L(double value) => value.ToString("R", CultureInfo.InvariantCulture);
}
}
+137
ファイルの表示
@@ -0,0 +1,137 @@
using LuaScript.Compat;
using MoonSharp.Interpreter;
namespace LuaScript.Tests
{
public class AviUtlScriptTests
{
private static Script NewScript()
{
var script = new Script(
CoreModules.Basic |
CoreModules.Math |
CoreModules.String |
CoreModules.Table |
CoreModules.Bit32 |
CoreModules.TableIterators |
CoreModules.Metatables |
CoreModules.ErrorHandling);
script.Globals["obj"] = new Table(script);
return script;
}
private static double RunNumber(string transformed, string global = "result")
{
var script = NewScript();
script.DoString(transformed);
return script.Globals.Get(global).Number;
}
[Fact]
public void PlainScript_IsReturnedUnchanged()
{
const string source = "obj.x = 1\nobj.y = 2";
Assert.Equal(source, AviUtlScript.Transform(source));
}
[Fact]
public void TrackOnlyHeader_IsReturnedUnchanged()
{
const string source = "--track0:Amp,0,100,10\nobj.ox = obj.track0";
Assert.Equal(source, AviUtlScript.Transform(source));
}
[Fact]
public void DirectiveComment_IsNotConfusedWithDirective()
{
const string source = "-- color reference note\nobj.x = 1";
Assert.Equal(source, AviUtlScript.Transform(source));
}
[Fact]
public void EngineDirective_IsPreserved()
{
const string source = "--!native\n--dialog:V,local v=3;\nresult = v";
string transformed = AviUtlScript.Transform(source);
Assert.Contains("--!native", transformed);
Assert.Equal(3d, RunNumber(transformed));
}
[Fact]
public void Dialog_InjectsDefaultDeclarations()
{
const string source = "--dialog:Angle,local angle=45;Dist,local dist=100;\nresult = dist";
double result = RunNumber(AviUtlScript.Transform(source));
Assert.Equal(100d, result);
}
[Fact]
public void Color_IsNotInjected_SurfacedAsUiParameter()
{
const string source = "--color:0x010203\nresult = color";
Assert.Equal(source, AviUtlScript.Transform(source));
}
[Fact]
public void Check_IsNotInjected_SurfacedAsUiParameter()
{
const string source = "--check0:Enable,1\nresult = obj.check0";
Assert.Equal(source, AviUtlScript.Transform(source));
}
[Fact]
public void Param_InjectsRawLua()
{
const string source = "--param:result = 7\nlocal x = 1";
double result = RunNumber(AviUtlScript.Transform(source));
Assert.Equal(7d, result);
}
[Fact]
public void Section_FirstSectionIsSelected()
{
const string source = "@First\n--dialog:A,local a=5;\nresult = a\n@Second\nresult = 999";
double result = RunNumber(AviUtlScript.Transform(source));
Assert.Equal(5d, result);
}
[Fact]
public void Section_PreambleBeforeFirstHeaderIsDiscarded()
{
const string source = "result = 111\n@Only\nresult = 222";
double result = RunNumber(AviUtlScript.Transform(source));
Assert.Equal(222d, result);
}
[Fact]
public void ClassicTransformScript_RunsAndMovesObject()
{
const string source =
"--track0:Range,0,2000,10\n" +
"--dialog:Seed,local seed=3;\n" +
"obj.ox = obj.ox + obj.track0 * obj.rand(-100,100,seed,obj.time) / 100";
var script = NewScript();
var obj = script.Globals.Get("obj").Table;
obj["ox"] = 0d;
obj["track0"] = 500d;
obj["time"] = 2d;
obj["frame"] = 4d;
obj["rand"] = DynValue.NewCallback((_, args) =>
{
double frameDefault = obj.Get("frame").CastToNumber() ?? 0d;
double a = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
double b = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
double seed = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
double frame = args.Count > 3 ? args[3].CastToNumber() ?? frameDefault : frameDefault;
return DynValue.NewNumber(AviUtlRandom.Next(a, b, seed, frame));
});
script.DoString(AviUtlScript.Transform(source));
double moved = obj.Get("ox").Number;
double expectedRand = AviUtlRandom.Next(-100, 100, 3, 2);
Assert.Equal(500d * expectedRand / 100d, moved);
}
}
}
+63
ファイルの表示
@@ -0,0 +1,63 @@
using System.Numerics;
using LuaScript;
namespace LuaScript.Tests
{
public class DrawPolyMathTests
{
private static double[] Quad(
double x0, double y0, double x1, double y1,
double x2, double y2, double x3, double y3,
double u0, double v0, double u1, double v1,
double u2, double v2, double u3, double v3,
double alpha)
=> [x0, y0, 0, x1, y1, 0, x2, y2, 0, x3, y3, 0, u0, v0, u1, v1, u2, v2, u3, v3, alpha];
[Fact]
public void TrySolveAffine_MapsUvCornersToQuad()
{
var poly = Quad(
10, 20, 18, 20, 18, 32, 10, 32,
0, 0, 4, 0, 4, 4, 0, 4, 1);
Assert.True(DrawPolyMath.TrySolveAffine(poly, out var m));
AssertMaps(m, 0, 0, 10, 20);
AssertMaps(m, 4, 0, 18, 20);
AssertMaps(m, 4, 4, 18, 32);
AssertMaps(m, 0, 4, 10, 32);
AssertMaps(m, 2, 2, 14, 26);
}
[Fact]
public void TrySolveAffine_HandlesRotatedQuad()
{
var poly = Quad(
0, 0, 0, 10, -10, 10, -10, 0,
0, 0, 10, 0, 10, 10, 0, 10, 1);
Assert.True(DrawPolyMath.TrySolveAffine(poly, out var m));
AssertMaps(m, 0, 0, 0, 0);
AssertMaps(m, 10, 0, 0, 10);
AssertMaps(m, 0, 10, -10, 0);
}
[Fact]
public void TrySolveAffine_ReturnsFalse_OnDegenerateUv()
{
var poly = Quad(
0, 0, 10, 0, 10, 10, 0, 10,
0, 0, 0, 0, 0, 0, 0, 0, 1);
Assert.False(DrawPolyMath.TrySolveAffine(poly, out _));
}
private static void AssertMaps(Matrix3x2 m, float u, float v, float x, float y)
{
var p = Vector2.Transform(new Vector2(u, v), m);
Assert.Equal(x, p.X, 3);
Assert.Equal(y, p.Y, 3);
}
}
}
+95
ファイルの表示
@@ -0,0 +1,95 @@
using LuaScript.Compat;
namespace LuaScript.Tests
{
public class FigureRendererTests
{
private static (int B, int G, int R, int A) Pixel(byte[] buffer, int width, int x, int y)
{
int i = (y * width + x) * 4;
return (buffer[i], buffer[i + 1], buffer[i + 2], buffer[i + 3]);
}
[Fact]
public void Render_ProducesBufferOfRequestedSize()
{
var buffer = FigureRenderer.Render("円", 64, 48, 0xFFFFFF, 0d);
Assert.Equal(64 * 48 * 4, buffer.Length);
}
[Fact]
public void FilledCircle_CenterIsOpaqueAndColored()
{
int w = 100, h = 100;
var buffer = FigureRenderer.Render("円", w, h, 0xFF0000, 0d);
var (b, g, r, a) = Pixel(buffer, w, w / 2, h / 2);
Assert.Equal(255, a);
Assert.Equal(255, r);
Assert.Equal(0, g);
Assert.Equal(0, b);
}
[Fact]
public void FilledCircle_CornerIsTransparent()
{
int w = 100, h = 100;
var buffer = FigureRenderer.Render("円", w, h, 0xFF0000, 0d);
var (_, _, _, a) = Pixel(buffer, w, 0, 0);
Assert.Equal(0, a);
}
[Fact]
public void Color_IsStoredPremultipliedAtHalfCoverageBoundary()
{
int w = 100, h = 100;
var buffer = FigureRenderer.Render("四角形", w, h, 0x102030, 0d);
var (b, g, r, a) = Pixel(buffer, w, w / 2, h / 2);
Assert.Equal(255, a);
Assert.Equal(0x10, r);
Assert.Equal(0x20, g);
Assert.Equal(0x30, b);
}
[Fact]
public void FilledRectangle_CornerIsOpaque()
{
int w = 80, h = 80;
var buffer = FigureRenderer.Render("四角形", w, h, 0xFFFFFF, 0d);
var (_, _, _, a) = Pixel(buffer, w, 1, 1);
Assert.Equal(255, a);
}
[Fact]
public void OutlinedCircle_IsHollowAtCenterButSolidNearEdge()
{
int w = 100, h = 100;
var buffer = FigureRenderer.Render("円", w, h, 0xFFFFFF, 8d);
var (_, _, _, center) = Pixel(buffer, w, w / 2, h / 2);
var (_, _, _, nearEdge) = Pixel(buffer, w, w / 2 + 46, h / 2);
Assert.Equal(0, center);
Assert.Equal(255, nearEdge);
}
[Fact]
public void Triangle_CornersEmptyCentroidFilled()
{
int w = 100, h = 100;
var buffer = FigureRenderer.Render("三角形", w, h, 0xFFFFFF, 0d);
var (_, _, _, topLeft) = Pixel(buffer, w, 2, 2);
var (_, _, _, topRight) = Pixel(buffer, w, w - 3, 2);
var (_, _, _, centroid) = Pixel(buffer, w, w / 2, h / 2);
Assert.Equal(0, topLeft);
Assert.Equal(0, topRight);
Assert.Equal(255, centroid);
}
[Fact]
public void UnknownName_FallsBackToRectangle()
{
int w = 40, h = 40;
var buffer = FigureRenderer.Render("unknown", w, h, 0xFFFFFF, 0d);
var (_, _, _, corner) = Pixel(buffer, w, 1, 1);
Assert.Equal(255, corner);
}
}
}
+9
ファイルの表示
@@ -27,11 +27,20 @@
<Compile Include="..\LuaScript\Compat\MoonSharpBit32.cs" Link="Linked\MoonSharpBit32.cs" />
<Compile Include="..\LuaScript\Compat\Bit32.cs" Link="Linked\Bit32.cs" />
<Compile Include="..\LuaScript\Engine\ScriptEngineKind.cs" Link="Linked\ScriptEngineKind.cs" />
<Compile Include="..\LuaScript\Engine\ScriptDirective.cs" Link="Linked\ScriptDirective.cs" />
<Compile Include="..\LuaScript\Engine\NativeProtocol.cs" Link="Linked\NativeProtocol.cs" />
<Compile Include="..\LuaScript\Engine\ProcessJobObject.cs" Link="Linked\ProcessJobObject.cs" />
<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\SceneObjectInfo.cs" Link="Linked\SceneObjectInfo.cs" />
<Compile Include="..\LuaScript\SceneObjectQuery.cs" Link="Linked\SceneObjectQuery.cs" />
<Compile Include="..\LuaScript\AnimTableRegistrar.cs" Link="Linked\AnimTableRegistrar.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlScript.cs" Link="Linked\AviUtlScript.cs" />
<Compile Include="..\LuaScript\Compat\ScriptParserHelper.cs" Link="Linked\ScriptParserHelper.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlParameterLayout.cs" Link="Linked\AviUtlParameterLayout.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlRandom.cs" Link="Linked\AviUtlRandom.cs" />
<Compile Include="..\LuaScript\Compat\FigureRenderer.cs" Link="Linked\FigureRenderer.cs" />
</ItemGroup>
</Project>
+337 -10
ファイルの表示
@@ -9,6 +9,12 @@ namespace LuaScript.Tests
private static string NativeDir => Path.Combine(AppContext.BaseDirectory, "native");
private static readonly Func<string, int, SceneObjectInfo?> NoResolver = (_, _) => null;
private static readonly Func<string, int, double, double, double, (byte[] buffer, int w, int h)> NoLoadFigure = (_, _, _, _, _) => ([], 1, 1);
private static readonly Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> NoLoadText = (_, _, _, _, _, _) => ([], 1, 1);
private static readonly Func<string, (byte[] buffer, int w, int h)> NoLoadImage = _ => ([], 1, 1);
private static readonly Func<string, double, (byte[] buffer, int w, int h)> NoLoadMovie = (_, _) => ([], 1, 1);
private static readonly Action<string, System.Collections.Generic.IReadOnlyList<System.Collections.Generic.KeyValuePair<string, object>>> NoAddEffect = (_, _) => { };
private static readonly Action<DrawCommand> NoAddDraw = _ => { };
private readonly LuaJitWorker _worker = new(NativeDir);
@@ -34,7 +40,7 @@ namespace LuaScript.Tests
bool ok = _worker.Execute(
"obj.rz = obj.time * 90\nobj.alpha = 128",
fields, pixels, 4, 4, 5000, NoResolver, out bool dirty, out string? error);
fields, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.False(dirty);
@@ -69,7 +75,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, pixels, w, h, 5000, NoResolver, out bool dirty, out string? error);
bool ok = _worker.Execute(script, fields, pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
@@ -104,7 +110,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, pixels, w, h, 5000, NoResolver, out bool dirty, out string? error);
bool ok = _worker.Execute(script, fields, pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
@@ -140,7 +146,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, pixels, 2, 2, 5000, NoResolver, out _, out string? error);
bool ok = _worker.Execute("obj.x = obj.time * 10", fields, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(k * 10d, fields[NativeProtocol.X]);
}
@@ -155,12 +161,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, pixels, 2, 2, 1500, NoResolver, out _, out string? error);
"local x=0 while true do x=x+1 end", fields, pixels, 2, 2, 1500, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, 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, pixels, 2, 2, 5000, NoResolver, out _, out error);
bool ok = _worker.Execute("obj.x = obj.time", fields2, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error);
Assert.Equal(3d, fields2[NativeProtocol.X]);
}
@@ -182,7 +188,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, pixels, 2, 2, 5000, resolver, out _, out string? error);
bool ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(12d, fields[NativeProtocol.X]);
@@ -195,6 +201,37 @@ namespace LuaScript.Tests
Assert.Equal(90d * Math.PI / 180d, fields[NativeProtocol.Rzr]);
}
[Fact]
public void GetObject_CachesRepeatedQueryAndResetsEachRun()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
int calls = 0;
double x = 10d;
Func<string, int, SceneObjectInfo?> resolver = (tag, frame) =>
{
calls++;
return tag == "a" ? new SceneObjectInfo("a", true, x, 0, 0, 1, 0, 255, 0) : null;
};
const string script =
"local a = obj.getobject(\"a\") " +
"local b = obj.getobject(\"a\") " +
"obj.x = a.x + b.x";
bool ok = _worker.Execute(script, Fields(2, 2, 0d), pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, 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, pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error);
Assert.Equal(2, calls);
Assert.Equal(40d, fields[NativeProtocol.X]);
}
[Fact]
public void GetObject_ReturnsNil_WhenUnresolved()
{
@@ -206,12 +243,302 @@ 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, pixels, 2, 2, 5000, NoResolver, out _, out string? error);
bool ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(1d, fields[NativeProtocol.X]);
}
[Fact]
public void Draw_RecordsCommandsThroughCallback()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute(
"obj.draw() obj.draw(10, 20, 30, 2, 0.5, 0.25)",
fields, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(2, commands.Count);
Assert.Equal(new DrawCommand(0d, 0d, 0d, 1d, 1d, 0d), commands[0]);
Assert.Equal(new DrawCommand(10d, 20d, 30d, 2d, 0.5d, 0.25d), commands[1]);
}
[Fact]
public void DrawPoly_RecordsDefaultUvAndAlpha()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d);
var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute(
"obj.drawpoly(0,0,0, 10,0,0, 10,10,0, 0,10,0)",
fields, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Single(commands);
var poly = commands[0].Poly;
Assert.NotNull(poly);
Assert.Equal(new double[] { 0, 0, 0, 10, 0, 0, 10, 10, 0, 0, 10, 0, 0, 0, 4, 0, 4, 4, 0, 4, 1 }, poly);
}
[Fact]
public void DrawPoly_RecordsExplicitUvAndAlpha()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d);
var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add;
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, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Single(commands);
var poly = commands[0].Poly;
Assert.NotNull(poly);
Assert.Equal(new double[] { 0, 0, 0, 8, 0, 0, 8, 8, 0, 0, 8, 0, 1, 1, 3, 1, 3, 3, 1, 3, 0.5 }, poly);
Assert.Equal(0.5d, commands[0].Alpha);
}
[Fact]
public void SetOption_GetOption_RoundTrips()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
bool ok = _worker.Execute(
"obj.setoption('antialias', 0) obj.x = obj.getoption('antialias') obj.y = obj.getoption('unset')",
fields, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(0d, fields[NativeProtocol.X]);
Assert.Equal(0d, fields[NativeProtocol.Y]);
}
[Fact]
public void Draw_CarriesAntialiasFromOption()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute(
"obj.draw() obj.setoption('antialias', 0) obj.draw()",
Fields(2, 2, 0d), pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(2, commands.Count);
Assert.Equal(1d, commands[0].Antialias);
Assert.Equal(0d, commands[1].Antialias);
}
[Fact]
public void LoadText_RoundTripsThroughCallback()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int tw = 3, th = 2;
var rendered = new byte[tw * th * 4];
for (int i = 0; i < rendered.Length; i++)
rendered[i] = (byte)((i * 17 + 5) & 0xFF);
string? capturedFamily = null;
string? capturedText = null;
double capturedSize = 0;
bool capturedBold = false, capturedItalic = false;
int capturedColor = 0;
Func<string, string, double, bool, bool, int, (byte[], int, int)> loadText =
(family, text, size, bold, italic, color) =>
{
capturedFamily = family; capturedText = text; capturedSize = size;
capturedBold = bold; capturedItalic = italic; capturedColor = color;
return (rendered, tw, th);
};
var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d);
bool ok = _worker.Execute(
"obj.setfont('Meiryo', 40, 3, 0x112233) obj.load('text', 'Hi')",
fields, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, loadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
Assert.True(ok, error);
Assert.Equal("Meiryo", capturedFamily);
Assert.Equal("Hi", capturedText);
Assert.Equal(40d, capturedSize);
Assert.True(capturedBold);
Assert.True(capturedItalic);
Assert.Equal(0x112233, capturedColor);
Assert.True(dirty);
Assert.True(bufferReplaced);
Assert.Equal(tw, rw);
Assert.Equal(th, rh);
Assert.NotNull(newPixels);
Assert.Equal(rendered, newPixels!.AsSpan(0, rendered.Length).ToArray());
}
[Fact]
public void LoadImage_RoundTripsThroughCallback()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int iw = 2, ih = 2;
var decoded = new byte[iw * ih * 4];
for (int i = 0; i < decoded.Length; i++)
decoded[i] = (byte)((i * 23 + 9) & 0xFF);
string? capturedPath = null;
Func<string, (byte[], int, int)> loadImage = path =>
{
capturedPath = path;
return (decoded, iw, ih);
};
var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d);
bool ok = _worker.Execute(
"obj.load('image', 'C:/sample.png')",
fields, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, loadImage, NoLoadMovie, NoAddEffect, NoAddDraw,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
Assert.True(ok, error);
Assert.Equal("C:/sample.png", capturedPath);
Assert.True(dirty);
Assert.True(bufferReplaced);
Assert.Equal(iw, rw);
Assert.Equal(ih, rh);
Assert.NotNull(newPixels);
Assert.Equal(decoded, newPixels!.AsSpan(0, decoded.Length).ToArray());
}
[Fact]
public void LoadMovie_RoundTripsPathAndTime()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int mw = 2, mh = 2;
var frame = new byte[mw * mh * 4];
for (int i = 0; i < frame.Length; i++)
frame[i] = (byte)((i * 31 + 3) & 0xFF);
string? capturedPath = null;
double capturedTime = -1;
Func<string, double, (byte[], int, int)> loadMovie = (path, time) =>
{
capturedPath = path;
capturedTime = time;
return (frame, mw, mh);
};
var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d);
bool ok = _worker.Execute(
"obj.load('movie', 'C:/clip.mp4', 1.5)",
fields, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, loadMovie, NoAddEffect, NoAddDraw,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
Assert.True(ok, error);
Assert.Equal("C:/clip.mp4", capturedPath);
Assert.Equal(1.5d, capturedTime);
Assert.True(dirty);
Assert.True(bufferReplaced);
Assert.Equal(mw, rw);
Assert.Equal(mh, rh);
Assert.NotNull(newPixels);
Assert.Equal(frame, newPixels!.AsSpan(0, frame.Length).ToArray());
}
[Fact]
public void GetValue_ReturnsObjFields()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
fields[NativeProtocol.Track0] = 42d;
bool ok = _worker.Execute(
"obj.x = obj.getvalue('track0') obj.y = obj.getvalue('alpha') obj.z = obj.getvalue('unknown')",
fields, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(42d, fields[NativeProtocol.X]);
Assert.Equal(255d, fields[NativeProtocol.Y]);
Assert.Equal(0d, fields[NativeProtocol.Z]);
}
[Fact]
public void CopyBuffer_TmpSaveRestore_RoundTripsPixels()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
for (int i = 0; i < pixels.Length; i++)
pixels[i] = (byte)((i * 37 + 11) & 0xFF);
pixels[3] = 255; pixels[7] = 255; pixels[11] = 255; pixels[15] = 255;
var original = (byte[])pixels.Clone();
var fields = Fields(w, h, 0d);
const string script =
"obj.copybuffer('tmp','obj') " +
"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, pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(original, pixels);
}
[Fact]
public void CopyBuffer_CachePersistsAcrossRuns()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var stored = new byte[w * h * 4];
for (int i = 0; i < stored.Length; i++)
stored[i] = (byte)((i * 53 + 7) & 0xFF);
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), save, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, 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), blank, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out bool dirty, out _, out _, out _, out _, out error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(stored, blank);
}
[Fact]
public void RuntimeError_IsReported_AndWorkerSurvives()
{
@@ -220,12 +547,12 @@ namespace LuaScript.Tests
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
bool ok = _worker.Execute("obj.x = missing.value", fields, pixels, 2, 2, 5000, NoResolver, out _, out string? error);
bool ok = _worker.Execute("obj.x = missing.value", fields, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, 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, pixels, 2, 2, 5000, NoResolver, out _, out error);
bool ok2 = _worker.Execute("obj.x = obj.time", fields2, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out error);
Assert.True(ok2, error);
Assert.Equal(7d, fields2[NativeProtocol.X]);
}
+5
ファイルの表示
@@ -37,6 +37,11 @@ namespace LuaScript.Tests
[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)
{
Assert.Equal(expected, ScriptDirective.ResolveAuto(script).ToString());
+17
ファイルの表示
@@ -0,0 +1,17 @@
using System.Collections.Generic;
namespace LuaScript
{
internal sealed class AviUtlEffectRequest
{
public string Name { get; }
public IReadOnlyList<KeyValuePair<string, object>> Arguments { get; }
public AviUtlEffectRequest(string name, IReadOnlyList<KeyValuePair<string, object>> arguments)
{
Name = name;
Arguments = arguments;
}
}
}
+161
ファイルの表示
@@ -29,6 +29,14 @@ namespace LuaScript
public double Track2 { get; set; }
public double Track3 { get; set; }
public bool Check0 { get; set; }
public bool Check1 { get; set; }
public bool Check2 { get; set; }
public bool Check3 { get; set; }
public bool HasColor { get; set; }
public double ColorValue { get; set; }
public double Time { get; set; }
public int Frame { get; set; }
public int TotalFrame { get; set; }
@@ -44,10 +52,102 @@ namespace LuaScript
public Func<SceneObjectResolver>? ResolverProvider { get; set; }
private const double Epsilon = 1e-10;
private readonly List<SceneObjectQuery> _objectQueries = [];
public IReadOnlyList<SceneObjectQuery> ObjectQueries => _objectQueries;
private readonly List<AviUtlEffectRequest> _effectRequests = [];
public IReadOnlyList<AviUtlEffectRequest> EffectRequests => _effectRequests;
internal void AddEffect(AviUtlEffectRequest request) => _effectRequests.Add(request);
internal void ClearEffects() => _effectRequests.Clear();
private readonly List<DrawCommand> _drawCommands = [];
public IReadOnlyList<DrawCommand> DrawCommands => _drawCommands;
internal void AddDraw(DrawCommand command) => _drawCommands.Add(command);
internal void ClearDraws() => _drawCommands.Clear();
private readonly Dictionary<string, (byte[] Data, int Width, int Height)> _buffers = new(StringComparer.Ordinal);
internal bool CopyBuffer(string dst, string src)
{
if (!TryReadBuffer(src, out var data, out int w, out int h))
return false;
return TryWriteBuffer(dst, data, w, h);
}
private bool TryReadBuffer(string id, out byte[] data, out int width, out int height)
{
data = [];
width = 0;
height = 0;
switch (BufferKind(id, out string key))
{
case 'o':
EnsurePixelBuffer();
if (_pixelBuffer is null)
return false;
data = _pixelBuffer;
width = ImageWidth;
height = ImageHeight;
return true;
case 't':
case 'c':
if (_buffers.TryGetValue(key, out var stored))
{
data = stored.Data;
width = stored.Width;
height = stored.Height;
return true;
}
return false;
default:
return false;
}
}
private bool TryWriteBuffer(string id, byte[] data, int width, int height)
{
switch (BufferKind(id, out string key))
{
case 'o':
ReplaceBuffer((byte[])data.Clone(), width, height);
return true;
case 't':
case 'c':
_buffers[key] = ((byte[])data.Clone(), width, height);
return false;
default:
return false;
}
}
private static char BufferKind(string id, out string key)
{
key = string.Empty;
int i = 0;
while (i < id.Length && (id[i] == ' ' || id[i] == '\t'))
i++;
if (i >= id.Length)
return '\0';
char kind = char.ToLowerInvariant(id[i]);
if (kind == 't')
key = "t";
else if (kind == 'c')
{
int colon = id.IndexOf(':', i);
key = colon >= 0 ? "c:" + id[(colon + 1)..].Trim() : "c";
}
return kind;
}
public double RxRad => Rx * Math.PI / 180d;
public double RyRad => Ry * Math.PI / 180d;
public double RzRad => Rz * Math.PI / 180d;
@@ -63,8 +163,10 @@ namespace LuaScript
private byte[]? _pixelBuffer;
private bool _pixelBufferLoaded;
private bool _isPixelsDirty;
private bool _bufferReplaced;
public bool IsPixelsDirty => _isPixelsDirty;
public bool BufferReplaced => _bufferReplaced;
internal int TotalChannels => ImageWidth * ImageHeight * 4;
@@ -76,6 +178,17 @@ namespace LuaScript
_pixelBuffer = null;
_pixelBufferLoaded = false;
_isPixelsDirty = false;
_bufferReplaced = false;
}
internal void ReplaceBuffer(byte[] buffer, int width, int height)
{
_pixelBuffer = buffer;
_pixelBufferLoaded = true;
_isPixelsDirty = true;
_bufferReplaced = true;
ImageWidth = width;
ImageHeight = height;
}
internal void EnsurePixelBuffer()
@@ -85,6 +198,14 @@ namespace LuaScript
_pixelBufferLoaded = true;
}
internal void SetResolvedBuffer(byte[] buffer, int width, int height)
{
_pixelBuffer = buffer;
_pixelBufferLoaded = true;
ImageWidth = width;
ImageHeight = height;
}
internal byte[]? GetPixelBuffer() => _pixelBuffer;
internal void MarkPixelsDirty() => _isPixelsDirty = true;
@@ -104,6 +225,46 @@ namespace LuaScript
return false;
}
public void ApplyWriteBack(
double newSx, double newSy, double newZoom, double newAspect,
double newRx, double newRy, double newRz,
double newRxr, double newRyr, double newRzr)
{
double initialSx = Sx;
double initialSy = Sy;
double initialZoom = Zoom;
double initialAspect = Aspect;
Sx = newSx;
Sy = newSy;
Zoom = newZoom;
Aspect = newAspect;
bool sxsyChanged = Math.Abs(Sx - initialSx) > Epsilon || Math.Abs(Sy - initialSy) > Epsilon;
bool zoomAspectChanged = Math.Abs(Zoom - initialZoom) > Epsilon || Math.Abs(Aspect - initialAspect) > Epsilon;
if (zoomAspectChanged && !sxsyChanged)
{
Sx = Zoom * (1.0 + Aspect);
Sy = Zoom * (1.0 - Aspect);
}
double initialRxr = RxRad;
Rx = Math.Abs(newRxr - initialRxr) > Epsilon
? newRxr * (180d / Math.PI)
: newRx;
double initialRyr = RyRad;
Ry = Math.Abs(newRyr - initialRyr) > Epsilon
? newRyr * (180d / Math.PI)
: newRy;
double initialRzr = RzRad;
Rz = Math.Abs(newRzr - initialRzr) > Epsilon
? newRzr * (180d / Math.PI)
: newRz;
}
public unsafe (double r, double g, double b, double a) GetPixel(int x, int y)
{
EnsurePixelBuffer();
+184
ファイルの表示
@@ -0,0 +1,184 @@
using System;
using System.Globalization;
namespace LuaScript.Compat
{
internal sealed class AviUtlParameterLayout
{
public const int MaxTracks = 4;
public const int MaxChecks = 4;
public readonly record struct TrackParam(int Index, string Name, double Min, double Max, double Default, double Step);
public readonly record struct CheckParam(int Index, string Name, bool Default);
public readonly record struct ColorParam(int Default);
private readonly TrackParam?[] _tracks = new TrackParam?[MaxTracks];
private readonly CheckParam?[] _checks = new CheckParam?[MaxChecks];
public static readonly AviUtlParameterLayout Empty = new();
public TrackParam? GetTrack(int index) => (uint)index < MaxTracks ? _tracks[index] : null;
public CheckParam? GetCheck(int index) => (uint)index < MaxChecks ? _checks[index] : null;
public ColorParam? Color { get; private set; }
public bool HasTrack(int index) => GetTrack(index).HasValue;
public bool HasCheck(int index) => GetCheck(index).HasValue;
public bool HasColor => Color.HasValue;
public bool HasAny
{
get
{
for (int i = 0; i < MaxTracks; i++)
if (_tracks[i].HasValue) return true;
for (int i = 0; i < MaxChecks; i++)
if (_checks[i].HasValue) return true;
return HasColor;
}
}
public static AviUtlParameterLayout Parse(string? source)
{
var layout = new AviUtlParameterLayout();
if (string.IsNullOrEmpty(source))
return layout;
var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
int sectionStart = 0;
int sectionEnd = lines.Length;
for (int i = 0; i < lines.Length; i++)
{
if (!ScriptParserHelper.IsSectionHeader(lines[i]))
continue;
sectionStart = i + 1;
sectionEnd = lines.Length;
for (int j = sectionStart; j < lines.Length; j++)
{
if (ScriptParserHelper.IsSectionHeader(lines[j]))
{
sectionEnd = j;
break;
}
}
break;
}
for (int i = sectionStart; i < sectionEnd; i++)
layout.ParseLine(lines[i]);
return layout;
}
private void ParseLine(string line)
{
int i = ScriptParserHelper.SkipSpaces(line, 0);
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
return;
i += 2;
if (i < line.Length && line[i] == '!')
return;
int nameStart = i;
while (i < line.Length && ScriptParserHelper.IsNameChar(line[i]))
i++;
if (i >= line.Length || line[i] != ':')
return;
string name = line.Substring(nameStart, i - nameStart);
string content = line.Substring(i + 1);
if (name.StartsWith("track", StringComparison.OrdinalIgnoreCase) &&
TryGetIndex(name, 5, MaxTracks, out int trackIndex))
{
ParseTrack(trackIndex, content);
}
else if (name.StartsWith("check", StringComparison.OrdinalIgnoreCase) &&
TryGetIndex(name, 5, MaxChecks, out int checkIndex))
{
ParseCheck(checkIndex, content);
}
else if (name.Equals("color", StringComparison.OrdinalIgnoreCase))
{
ParseColor(content);
}
}
private void ParseTrack(int index, string content)
{
var parts = content.Split(',');
string trackName = parts.Length > 0 ? parts[0].Trim() : string.Empty;
double min = ParseNumber(parts, 1, 0d);
double max = ParseNumber(parts, 2, 100d);
double def = ParseNumber(parts, 3, min);
double step = ParseNumber(parts, 4, 0d);
if (max < min)
(min, max) = (max, min);
def = Math.Clamp(def, min, max);
_tracks[index] = new TrackParam(index, trackName, min, max, def, step);
}
private void ParseCheck(int index, string content)
{
var parts = content.Split(',');
string checkName = parts.Length > 0 ? parts[0].Trim() : string.Empty;
double def = ParseNumber(parts, 1, 0d);
_checks[index] = new CheckParam(index, checkName, def != 0d);
}
private void ParseColor(string content)
{
string token = FirstToken(content);
if (TryParseColorLiteral(token, out int rgb))
Color = new ColorParam(rgb);
}
private static bool TryGetIndex(string name, int start, int max, out int index)
{
index = -1;
if (name.Length != start + 1)
return false;
char c = name[start];
if (c < '0' || c > '9')
return false;
int value = c - '0';
if (value >= max)
return false;
index = value;
return true;
}
private static double ParseNumber(string[] parts, int idx, double fallback)
{
if (idx >= parts.Length)
return fallback;
string token = parts[idx].Trim();
return double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out double value)
? value
: fallback;
}
private static bool TryParseColorLiteral(string token, out int rgb)
{
rgb = 0;
if (token.Length == 0)
return false;
if (token.StartsWith("0x", StringComparison.OrdinalIgnoreCase) || token.StartsWith("0X", StringComparison.Ordinal))
{
if (token.Length <= 2)
return false;
return int.TryParse(token.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out rgb);
}
return int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out rgb);
}
private static string FirstToken(string content)
{
int start = ScriptParserHelper.SkipSpaces(content, 0);
int i = start;
while (i < content.Length && content[i] != ',' && content[i] != ' ' && content[i] != '\t')
i++;
return content.Substring(start, i - start);
}
}
}
+30
ファイルの表示
@@ -0,0 +1,30 @@
using System;
namespace LuaScript.Compat
{
internal static class AviUtlRandom
{
public static double Next(double a, double b, double seed, double frame)
{
long seedBits = BitConverter.DoubleToInt64Bits(seed);
long frameBits = BitConverter.DoubleToInt64Bits(frame);
uint s = (uint)(seedBits ^ (seedBits >> 32));
uint f = (uint)(frameBits ^ (frameBits >> 32));
uint h = s * 374761393u + f * 668265263u;
h = (h ^ (h >> 13)) * 1274126177u;
h ^= h >> 16;
double r = h / 4294967295.0;
long lo = (long)Math.Floor(Math.Min(a, b));
long hi = (long)Math.Floor(Math.Max(a, b));
long span = hi - lo + 1L;
if (span <= 1L)
return lo;
long value = lo + (long)(r * span);
return value > hi ? hi : value;
}
}
}
+123
ファイルの表示
@@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace LuaScript.Compat
{
internal static class AviUtlScript
{
private enum DirectiveKind
{
None,
Dialog,
Param,
}
public static string Transform(string source)
{
if (string.IsNullOrEmpty(source))
return source;
var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
int sectionStart = 0;
int sectionEnd = lines.Length;
bool hasSection = false;
for (int i = 0; i < lines.Length; i++)
{
if (!ScriptParserHelper.IsSectionHeader(lines[i]))
continue;
hasSection = true;
sectionStart = i + 1;
sectionEnd = lines.Length;
for (int j = sectionStart; j < lines.Length; j++)
{
if (ScriptParserHelper.IsSectionHeader(lines[j]))
{
sectionEnd = j;
break;
}
}
break;
}
var prelude = new List<string>();
for (int i = sectionStart; i < sectionEnd; i++)
AppendDeclarations(lines[i], prelude);
if (!hasSection && prelude.Count == 0)
return source;
var builder = new StringBuilder(source.Length + 64);
foreach (var declaration in prelude)
builder.Append(declaration).Append('\n');
for (int i = sectionStart; i < sectionEnd; i++)
builder.Append(lines[i]).Append('\n');
return builder.ToString();
}
private static void AppendDeclarations(string line, List<string> prelude)
{
int i = ScriptParserHelper.SkipSpaces(line, 0);
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
return;
i += 2;
if (i < line.Length && line[i] == '!')
return;
int nameStart = i;
while (i < line.Length && ScriptParserHelper.IsNameChar(line[i]))
i++;
if (i >= line.Length || line[i] != ':')
return;
string name = line.Substring(nameStart, i - nameStart);
string content = line.Substring(i + 1);
switch (Classify(name))
{
case DirectiveKind.Dialog:
AppendDialog(content, prelude);
break;
case DirectiveKind.Param:
AppendParam(content, prelude);
break;
}
}
private static DirectiveKind Classify(string name)
{
if (name.Equals("dialog", StringComparison.OrdinalIgnoreCase))
return DirectiveKind.Dialog;
if (name.Equals("param", StringComparison.OrdinalIgnoreCase))
return DirectiveKind.Param;
return DirectiveKind.None;
}
private static void AppendDialog(string content, List<string> prelude)
{
foreach (var segment in content.Split(';'))
{
string trimmed = segment.Trim();
if (trimmed.Length == 0)
continue;
int comma = trimmed.IndexOf(',');
if (comma < 0)
continue;
string declaration = trimmed.Substring(comma + 1).Trim();
if (declaration.Length != 0)
prelude.Add(declaration);
}
}
private static void AppendParam(string content, List<string> prelude)
{
string trimmed = content.Trim();
if (trimmed.Length != 0)
prelude.Add(trimmed);
}
}
}
+193
ファイルの表示
@@ -0,0 +1,193 @@
using System;
namespace LuaScript.Compat
{
internal static class FigureRenderer
{
private enum Shape
{
Ellipse,
Rectangle,
Triangle,
Pentagon,
Hexagon,
Star,
}
public static byte[] Render(string name, int width, int height, int colorRgb, double lineWidth)
{
width = Math.Max(1, width);
height = Math.Max(1, height);
var buffer = new byte[width * height * 4];
Shape shape = Resolve(name);
double hx = width / 2d;
double hy = height / 2d;
double r = (colorRgb >> 16) & 0xFF;
double g = (colorRgb >> 8) & 0xFF;
double b = colorRgb & 0xFF;
(double X, double Y)[]? polygon = shape switch
{
Shape.Triangle => RegularPolygon(3, hx, hy),
Shape.Pentagon => RegularPolygon(5, hx, hy),
Shape.Hexagon => RegularPolygon(6, hx, hy),
Shape.Star => StarPolygon(hx, hy),
_ => null,
};
bool filled = lineWidth <= 0d;
for (int y = 0; y < height; y++)
{
double py = y + 0.5 - hy;
int row = y * width * 4;
for (int x = 0; x < width; x++)
{
double px = x + 0.5 - hx;
double d = shape switch
{
Shape.Ellipse => EllipseSdf(px, py, hx, hy),
Shape.Rectangle => BoxSdf(px, py, hx, hy),
_ => PolygonSdf(px, py, polygon!),
};
if (!filled)
d = Math.Max(d, -d - lineWidth);
double coverage = 0.5 - d;
if (coverage <= 0d)
continue;
if (coverage > 1d)
coverage = 1d;
int i = row + x * 4;
buffer[i] = ToByte(b * coverage);
buffer[i + 1] = ToByte(g * coverage);
buffer[i + 2] = ToByte(r * coverage);
buffer[i + 3] = ToByte(255d * coverage);
}
}
return buffer;
}
private static Shape Resolve(string name)
{
switch (name.Trim())
{
case "円":
case "楕円":
case "circle":
case "ellipse":
return Shape.Ellipse;
case "三角形":
case "triangle":
return Shape.Triangle;
case "五角形":
case "pentagon":
return Shape.Pentagon;
case "六角形":
case "hexagon":
return Shape.Hexagon;
case "星形":
case "star":
return Shape.Star;
default:
return Shape.Rectangle;
}
}
private static (double X, double Y)[] RegularPolygon(int sides, double hx, double hy)
{
var vertices = new (double X, double Y)[sides];
for (int k = 0; k < sides; k++)
{
double angle = -Math.PI / 2d + 2d * Math.PI * k / sides;
vertices[k] = (Math.Cos(angle) * hx, Math.Sin(angle) * hy);
}
return vertices;
}
private static (double X, double Y)[] StarPolygon(double hx, double hy)
{
const double innerRatio = 0.38196601125010515d;
var vertices = new (double X, double Y)[10];
for (int k = 0; k < 10; k++)
{
double angle = -Math.PI / 2d + Math.PI * k / 5d;
double radius = (k & 1) == 0 ? 1d : innerRatio;
vertices[k] = (Math.Cos(angle) * hx * radius, Math.Sin(angle) * hy * radius);
}
return vertices;
}
private static double EllipseSdf(double px, double py, double ax, double ay)
{
if (ax <= 0d || ay <= 0d)
return double.MaxValue;
double kx = px / ax;
double ky = py / ay;
double k1 = Math.Sqrt(kx * kx + ky * ky);
if (k1 == 0d)
return -Math.Min(ax, ay);
double nx = kx / ax;
double ny = ky / ay;
double k2 = Math.Sqrt(nx * nx + ny * ny);
return k1 * (k1 - 1d) / k2;
}
private static double BoxSdf(double px, double py, double hx, double hy)
{
double qx = Math.Abs(px) - hx;
double qy = Math.Abs(py) - hy;
double ox = Math.Max(qx, 0d);
double oy = Math.Max(qy, 0d);
return Math.Sqrt(ox * ox + oy * oy) + Math.Min(Math.Max(qx, qy), 0d);
}
private static double PolygonSdf(double px, double py, (double X, double Y)[] v)
{
int n = v.Length;
double dx = px - v[0].X;
double dy = py - v[0].Y;
double d = dx * dx + dy * dy;
double s = 1d;
for (int i = 0, j = n - 1; i < n; j = i, i++)
{
double ex = v[j].X - v[i].X;
double ey = v[j].Y - v[i].Y;
double wx = px - v[i].X;
double wy = py - v[i].Y;
double t = Clamp((wx * ex + wy * ey) / (ex * ex + ey * ey), 0d, 1d);
double bx = wx - ex * t;
double by = wy - ey * t;
d = Math.Min(d, bx * bx + by * by);
bool c1 = py >= v[i].Y;
bool c2 = py < v[j].Y;
bool c3 = ex * wy > ey * wx;
if ((c1 && c2 && c3) || (!c1 && !c2 && !c3))
s = -s;
}
return s * Math.Sqrt(d);
}
private static double Clamp(double v, double lo, double hi)
{
if (v < lo) return lo;
if (v > hi) return hi;
return v;
}
private static byte ToByte(double v)
{
int i = (int)(v + 0.5d);
if (i < 0) return 0;
if (i > 255) return 255;
return (byte)i;
}
}
}
+21
ファイルの表示
@@ -0,0 +1,21 @@
namespace LuaScript.Compat
{
internal static class ScriptParserHelper
{
public static bool IsSectionHeader(string line)
{
int i = SkipSpaces(line, 0);
return i < line.Length && line[i] == '@';
}
public static int SkipSpaces(string text, int index)
{
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
index++;
return index;
}
public static bool IsNameChar(char c) =>
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
}
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace LuaScript
{
internal readonly record struct DrawCommand(
double Ox,
double Oy,
double Oz,
double Zoom,
double Alpha,
double Aspect,
double[]? Poly = null,
double Antialias = 1d);
}
+149
ファイルの表示
@@ -0,0 +1,149 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using YukkuriMovieMaker.Commons;
namespace LuaScript
{
internal sealed class DrawCompositor : IDisposable
{
private const int MaxDimension = 8192;
private readonly GraphicsDevicesAndContext _ctx;
private ID2D1Bitmap1? _source;
private ID2D1Bitmap1? _target;
private AffineTransform2D? _placement;
private int _sourceWidth;
private int _sourceHeight;
private int _targetWidth;
private int _targetHeight;
public DrawCompositor(GraphicsDevicesAndContext ctx)
{
_ctx = ctx;
}
public unsafe ID2D1Image Compose(byte[] pixels, int width, int height, IReadOnlyList<DrawCommand> commands)
{
EnsureSource(width, height);
fixed (byte* ptr = pixels)
_source!.CopyFromMemory(new nint(ptr), width * 4);
double minX = double.MaxValue, minY = double.MaxValue;
double maxX = double.MinValue, maxY = double.MinValue;
for (int i = 0; i < commands.Count; i++)
{
var cmd = commands[i];
if (cmd.Poly is { } poly)
{
DrawPolyMath.Bounds(poly, out double pMinX, out double pMinY, out double pMaxX, out double pMaxY);
minX = Math.Min(minX, pMinX);
maxX = Math.Max(maxX, pMaxX);
minY = Math.Min(minY, pMinY);
maxY = Math.Max(maxY, pMaxY);
continue;
}
double aspect = Math.Clamp(cmd.Aspect, -1d, 1d);
double zx = cmd.Zoom * (1d + aspect);
double zy = cmd.Zoom * (1d - aspect);
double halfW = width * 0.5 * zx;
double halfH = height * 0.5 * zy;
minX = Math.Min(minX, cmd.Ox - halfW);
maxX = Math.Max(maxX, cmd.Ox + halfW);
minY = Math.Min(minY, cmd.Oy - halfH);
maxY = Math.Max(maxY, cmd.Oy + halfH);
}
int originX = (int)Math.Floor(minX);
int originY = (int)Math.Floor(minY);
int targetW = Math.Clamp((int)Math.Ceiling(maxX) - originX, 1, MaxDimension);
int targetH = Math.Clamp((int)Math.Ceiling(maxY) - originY, 1, MaxDimension);
EnsureTarget(targetW, targetH);
var dc = _ctx.DeviceContext;
var rt = (ID2D1RenderTarget)dc;
var savedTarget = dc.Target;
dc.Target = _target;
dc.BeginDraw();
dc.Clear(null);
var toTarget = Matrix3x2.CreateTranslation(-originX, -originY);
for (int i = 0; i < commands.Count; i++)
{
var cmd = commands[i];
var interpolation = cmd.Antialias != 0d
? BitmapInterpolationMode.Linear
: BitmapInterpolationMode.NearestNeighbor;
if (cmd.Poly is { } poly)
{
if (!DrawPolyMath.TrySolveAffine(poly, out var affine))
continue;
rt.Transform = affine * toTarget;
rt.DrawBitmap(_source, (float)Math.Clamp(poly[20], 0d, 1d), interpolation);
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;
rt.DrawBitmap(_source, opacity, interpolation);
}
rt.Transform = Matrix3x2.Identity;
dc.EndDraw();
dc.Target = savedTarget;
_placement!.TransformMatrix = Matrix3x2.CreateTranslation(originX, originY);
return _placement.Output;
}
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;
_placement?.Dispose();
_target?.Dispose();
_placement = null;
_target = _ctx.DeviceContext.CreateEmptyBitmap(width, height, BitmapOptions.Target);
_targetWidth = width;
_targetHeight = height;
_placement = new AffineTransform2D(_ctx.DeviceContext);
_placement.SetInput(0, _target, true);
}
public void Dispose()
{
_placement?.Dispose();
_source?.Dispose();
_target?.Dispose();
_placement = null;
_source = null;
_target = null;
}
}
}
+53
ファイルの表示
@@ -0,0 +1,53 @@
using System;
using System.Numerics;
namespace LuaScript
{
internal static class DrawPolyMath
{
public const int Length = 21;
public static bool TrySolveAffine(double[] poly, out Matrix3x2 matrix)
{
double x0 = poly[0], y0 = poly[1];
double x1 = poly[3], y1 = poly[4];
double x3 = poly[9], y3 = poly[10];
double u0 = poly[12], v0 = poly[13];
double u1 = poly[14], v1 = poly[15];
double u3 = poly[18], v3 = poly[19];
double det = u0 * (v1 - v3) - v0 * (u1 - u3) + (u1 * v3 - v1 * u3);
if (Math.Abs(det) < 1e-9)
{
matrix = Matrix3x2.Identity;
return false;
}
double inv = 1d / det;
double a = (x0 * (v1 - v3) - v0 * (x1 - x3) + (x1 * v3 - v1 * x3)) * inv;
double b = (u0 * (x1 - x3) - x0 * (u1 - u3) + (u1 * x3 - x1 * u3)) * inv;
double c = (u0 * (v1 * x3 - x1 * v3) - v0 * (u1 * x3 - x1 * u3) + x0 * (u1 * v3 - v1 * u3)) * inv;
double d = (y0 * (v1 - v3) - v0 * (y1 - y3) + (y1 * v3 - v1 * y3)) * inv;
double e = (u0 * (y1 - y3) - y0 * (u1 - u3) + (u1 * y3 - y1 * u3)) * inv;
double f = (u0 * (v1 * y3 - y1 * v3) - v0 * (u1 * y3 - y1 * u3) + y0 * (u1 * v3 - v1 * u3)) * inv;
matrix = new Matrix3x2((float)a, (float)d, (float)b, (float)e, (float)c, (float)f);
return true;
}
public static void Bounds(double[] poly, out double minX, out double minY, out double maxX, out double maxY)
{
minX = minY = double.MaxValue;
maxX = maxY = double.MinValue;
for (int i = 0; i < 4; i++)
{
double x = poly[i * 3];
double y = poly[i * 3 + 1];
if (x < minX) minX = x;
if (x > maxX) maxX = x;
if (y < minY) minY = y;
if (y > maxY) maxY = y;
}
}
}
}
+274 -6
ファイルの表示
@@ -23,6 +23,12 @@ namespace LuaScript.Engine
private int _height;
private bool _alive;
private readonly byte[] _callbackTag = new byte[NativeProtocol.CallbackTagMax];
private readonly byte[] _lastCallbackTag = new byte[NativeProtocol.CallbackTagMax];
private int _lastCallbackTagLength = -1;
private string _lastCallbackTagText = string.Empty;
private byte[]? _resultBuffer;
public LuaJitWorker(string nativeDir)
{
_nativeDir = nativeDir;
@@ -42,10 +48,24 @@ namespace LuaScript.Engine
int height,
int timeoutMs,
Func<string, int, SceneObjectInfo?> resolveObject,
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure,
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
Func<string, (byte[] buffer, int w, int h)> loadImage,
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
Action<DrawCommand> addDraw,
out bool pixelsDirty,
out bool bufferReplaced,
out byte[]? newPixels,
out int resultWidth,
out int resultHeight,
out string? error)
{
pixelsDirty = false;
bufferReplaced = false;
newPixels = null;
resultWidth = width;
resultHeight = height;
error = null;
byte[] scriptBytes = Encoding.UTF8.GetBytes(script);
@@ -87,7 +107,7 @@ namespace LuaScript.Engine
if (status != NativeProtocol.StatusCallback)
break;
ResolveCallback(view, resolveObject);
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, addDraw);
_workEvent.Set();
}
@@ -103,20 +123,104 @@ namespace LuaScript.Engine
for (int i = NativeProtocol.FirstWritableField; i <= NativeProtocol.LastWritableField; i++)
fields[i] = view.ReadDouble(NativeProtocol.FieldsOffset + i * 8);
resultWidth = view.ReadInt32(NativeProtocol.OffWidth);
resultHeight = view.ReadInt32(NativeProtocol.OffHeight);
bufferReplaced = resultWidth != width || resultHeight != height;
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
if (pixelsDirty)
view.ReadArray(NativeProtocol.PixelOffset, pixels, 0, pixels.Length);
{
if (bufferReplaced)
{
int pixelSize = resultWidth * resultHeight * 4;
if (_resultBuffer == null || _resultBuffer.Length < pixelSize)
_resultBuffer = new byte[pixelSize];
view.ReadArray(NativeProtocol.PixelOffset, _resultBuffer, 0, pixelSize);
newPixels = _resultBuffer;
}
else
{
view.ReadArray(NativeProtocol.PixelOffset, pixels, 0, pixels.Length);
}
}
return true;
}
private void ResolveCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject)
private void DispatchCallback(
MemoryMappedViewAccessor view,
Func<string, int, SceneObjectInfo?> resolveObject,
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure,
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
Func<string, (byte[] buffer, int w, int h)> loadImage,
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
Action<DrawCommand> addDraw)
{
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
switch (kind)
{
case NativeProtocol.CbKindGetObject:
ResolveGetObjectCallback(view, resolveObject);
break;
case NativeProtocol.CbKindLoadFigure:
ResolveLoadFigureCallback(view, loadFigure);
break;
case NativeProtocol.CbKindLoadText:
ResolveLoadTextCallback(view, loadText);
break;
case NativeProtocol.CbKindLoadImage:
ResolveLoadImageCallback(view, loadImage);
break;
case NativeProtocol.CbKindLoadMovie:
ResolveLoadMovieCallback(view, loadMovie);
break;
case NativeProtocol.CbKindEffect:
ResolveEffectCallback(view, addEffect);
break;
case NativeProtocol.CbKindDraw:
ResolveDrawCallback(view, addDraw);
break;
case NativeProtocol.CbKindDrawPoly:
ResolveDrawPolyCallback(view, addDraw);
break;
}
}
private static void ResolveDrawCallback(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
{
long rOff = NativeProtocol.CallbackResultOffset;
double ox = view.ReadDouble(rOff + 0 * 8);
double oy = view.ReadDouble(rOff + 1 * 8);
double oz = view.ReadDouble(rOff + 2 * 8);
double zoom = view.ReadDouble(rOff + 3 * 8);
double alpha = view.ReadDouble(rOff + 4 * 8);
double aspect = view.ReadDouble(rOff + 5 * 8);
double antialias = view.ReadDouble(rOff + 6 * 8);
try { addDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, antialias)); }
catch { }
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private static void ResolveDrawPolyCallback(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
{
var poly = new double[DrawPolyMath.Length];
for (int i = 0; i < DrawPolyMath.Length; i++)
poly[i] = view.ReadDouble(NativeProtocol.CallbackTagOffset + i * 8);
double antialias = view.ReadDouble(NativeProtocol.CallbackTagOffset + DrawPolyMath.Length * 8);
try { addDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, antialias)); }
catch { }
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveGetObjectCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject)
{
int frame = view.ReadInt32(NativeProtocol.OffCallbackFrame);
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
var tagBytes = new byte[tagLen];
view.ReadArray(NativeProtocol.CallbackTagOffset, tagBytes, 0, tagLen);
string tag = Encoding.UTF8.GetString(tagBytes);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string tag = ResolveTag(tagLen);
SceneObjectInfo? info;
try { info = resolveObject(tag, frame); }
@@ -141,6 +245,170 @@ namespace LuaScript.Engine
}
}
private void ResolveLoadFigureCallback(
MemoryMappedViewAccessor view,
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string name = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
long rOff = NativeProtocol.CallbackResultOffset;
int color = (int)view.ReadDouble(rOff + 0 * 8);
double size = view.ReadDouble(rOff + 1 * 8);
double lineWidth = view.ReadDouble(rOff + 2 * 8);
double aspect = view.ReadDouble(rOff + 3 * 8);
(byte[] buffer, int w, int h) result;
try { result = loadFigure(name, color, size, lineWidth, aspect); }
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - NativeProtocol.PixelOffset;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
pixelSize = 4;
}
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
view.WriteArray(NativeProtocol.PixelOffset, result.buffer, 0, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveLoadTextCallback(
MemoryMappedViewAccessor view,
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string payload = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
int separator = payload.IndexOf('\0');
string family = separator >= 0 ? payload[..separator] : string.Empty;
string text = separator >= 0 ? payload[(separator + 1)..] : payload;
long rOff = NativeProtocol.CallbackResultOffset;
double size = view.ReadDouble(rOff + 0 * 8);
bool bold = view.ReadDouble(rOff + 1 * 8) != 0;
bool italic = view.ReadDouble(rOff + 2 * 8) != 0;
int color = (int)view.ReadDouble(rOff + 3 * 8);
(byte[] buffer, int w, int h) result;
try { result = loadText(family, text, size, bold, italic, color); }
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - NativeProtocol.PixelOffset;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
pixelSize = 4;
}
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
view.WriteArray(NativeProtocol.PixelOffset, result.buffer, 0, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveLoadImageCallback(
MemoryMappedViewAccessor view,
Func<string, (byte[] buffer, int w, int h)> loadImage)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string path = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
(byte[] buffer, int w, int h) result;
try { result = loadImage(path); }
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - NativeProtocol.PixelOffset;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
pixelSize = 4;
}
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
view.WriteArray(NativeProtocol.PixelOffset, result.buffer, 0, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveLoadMovieCallback(
MemoryMappedViewAccessor view,
Func<string, double, (byte[] buffer, int w, int h)> loadMovie)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string path = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
double time = view.ReadDouble(NativeProtocol.CallbackResultOffset);
(byte[] buffer, int w, int h) result;
try { result = loadMovie(path, time); }
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - NativeProtocol.PixelOffset;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
pixelSize = 4;
}
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
view.WriteArray(NativeProtocol.PixelOffset, result.buffer, 0, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveEffectCallback(MemoryMappedViewAccessor view, Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
var segments = Encoding.UTF8.GetString(_callbackTag, 0, tagLen).Split('\0');
if (segments.Length == 0)
return;
string effectName = segments[0];
var arguments = new List<KeyValuePair<string, object>>();
for (int i = 1; i + 1 < segments.Length; i += 2)
{
string key = segments[i];
string raw = segments[i + 1];
object value;
if (raw.Length > 0 && raw[0] == 'n')
value = double.TryParse(raw.AsSpan(1), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var d) ? d : 0d;
else if (raw.Length > 0 && raw[0] == 'b')
value = raw.Length > 1 && raw[1] == '1';
else if (raw.Length > 0 && raw[0] == 's')
value = raw.Substring(1);
else
value = raw;
arguments.Add(new KeyValuePair<string, object>(key, value));
}
try { addEffect(effectName, arguments); }
catch { }
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private string ResolveTag(int tagLen)
{
if (tagLen == _lastCallbackTagLength &&
_callbackTag.AsSpan(0, tagLen).SequenceEqual(_lastCallbackTag.AsSpan(0, tagLen)))
return _lastCallbackTagText;
_lastCallbackTagText = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
_callbackTag.AsSpan(0, tagLen).CopyTo(_lastCallbackTag);
_lastCallbackTagLength = tagLen;
return _lastCallbackTagText;
}
private void EnsureWorker(int width, int height)
{
if (_alive && _process is { HasExited: false } && _width == width && _height == height)
+16 -36
ファイルの表示
@@ -38,6 +38,11 @@ namespace LuaScript.Engine
f[NativeProtocol.Track1] = ctx.Track1;
f[NativeProtocol.Track2] = ctx.Track2;
f[NativeProtocol.Track3] = ctx.Track3;
f[NativeProtocol.Check0] = ctx.Check0 ? 1d : 0d;
f[NativeProtocol.Check1] = ctx.Check1 ? 1d : 0d;
f[NativeProtocol.Check2] = ctx.Check2 ? 1d : 0d;
f[NativeProtocol.Check3] = ctx.Check3 ? 1d : 0d;
f[NativeProtocol.Color] = ctx.HasColor ? ctx.ColorValue : -1d;
f[NativeProtocol.Time] = ctx.Time;
f[NativeProtocol.Frame] = ctx.Frame;
f[NativeProtocol.TotalFrame] = ctx.TotalFrame;
@@ -73,42 +78,17 @@ namespace LuaScript.Engine
ctx.Oz = f[NativeProtocol.Oz];
ctx.Alpha = f[NativeProtocol.Alpha];
double initialSx = ctx.Sx;
double initialSy = ctx.Sy;
double initialZoom = ctx.Zoom;
double initialAspect = ctx.Aspect;
ctx.Sx = f[NativeProtocol.Sx];
ctx.Sy = f[NativeProtocol.Sy];
ctx.Zoom = f[NativeProtocol.Zoom];
ctx.Aspect = f[NativeProtocol.Aspect];
bool sxsyChanged = Math.Abs(ctx.Sx - initialSx) > Epsilon || Math.Abs(ctx.Sy - initialSy) > Epsilon;
bool zoomAspectChanged = Math.Abs(ctx.Zoom - initialZoom) > Epsilon || Math.Abs(ctx.Aspect - initialAspect) > Epsilon;
if (zoomAspectChanged && !sxsyChanged)
{
ctx.Sx = ctx.Zoom * (1.0 + ctx.Aspect);
ctx.Sy = ctx.Zoom * (1.0 - ctx.Aspect);
}
double initialRxr = ctx.RxRad;
double rxrNew = f[NativeProtocol.Rxr];
ctx.Rx = Math.Abs(rxrNew - initialRxr) > Epsilon
? rxrNew * (180d / Math.PI)
: f[NativeProtocol.Rx];
double initialRyr = ctx.RyRad;
double ryrNew = f[NativeProtocol.Ryr];
ctx.Ry = Math.Abs(ryrNew - initialRyr) > Epsilon
? ryrNew * (180d / Math.PI)
: f[NativeProtocol.Ry];
double initialRzr = ctx.RzRad;
double rzrNew = f[NativeProtocol.Rzr];
ctx.Rz = Math.Abs(rzrNew - initialRzr) > Epsilon
? rzrNew * (180d / Math.PI)
: f[NativeProtocol.Rz];
ctx.ApplyWriteBack(
f[NativeProtocol.Sx],
f[NativeProtocol.Sy],
f[NativeProtocol.Zoom],
f[NativeProtocol.Aspect],
f[NativeProtocol.Rx],
f[NativeProtocol.Ry],
f[NativeProtocol.Rz],
f[NativeProtocol.Rxr],
f[NativeProtocol.Ryr],
f[NativeProtocol.Rzr]);
}
}
}
+21 -2
ファイルの表示
@@ -23,6 +23,9 @@ namespace LuaScript.Engine
public const int OffCallbackFrame = 32;
public const int OffCallbackTagLen = 36;
public const int OffCallbackFound = 40;
public const int OffCallbackKind = 44;
public const int OffLoadResultWidth = 48;
public const int OffLoadResultHeight = 52;
public const int HeaderSize = 64;
@@ -36,10 +39,19 @@ namespace LuaScript.Engine
public const int ErrorMax = 4 * 1024;
public const int CallbackTagOffset = ErrorOffset + ErrorMax;
public const int CallbackTagMax = 256;
public const int CallbackTagMax = 4096;
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
public const int CallbackResultCount = 8;
public const int CbKindGetObject = 0;
public const int CbKindLoadFigure = 1;
public const int CbKindEffect = 2;
public const int CbKindDraw = 3;
public const int CbKindDrawPoly = 4;
public const int CbKindLoadText = 5;
public const int CbKindLoadImage = 6;
public const int CbKindLoadMovie = 7;
public const int CbExist = 0;
public const int CbX = 1;
public const int CbY = 2;
@@ -104,11 +116,18 @@ namespace LuaScript.Engine
public const int IsPaused = 50;
public const int TimelineFrame = 51;
public const int TimelineTime = 52;
public const int Check0 = 53;
public const int Check1 = 54;
public const int Check2 = 55;
public const int Check3 = 56;
public const int Color = 57;
public const int FirstWritableField = X;
public const int LastWritableField = Rzr;
public const int MaxPixelBufferSize = 3840 * 2160 * 4;
public static long BufferSize(int width, int height) =>
PixelOffset + (long)width * height * 4;
PixelOffset + Math.Max((long)width * height * 4, MaxPixelBufferSize);
}
}
+104
ファイルの表示
@@ -0,0 +1,104 @@
using System;
namespace LuaScript.Engine
{
internal static class ScriptDirective
{
public static ScriptEngineKind Resolve(string? script) =>
TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.MoonSharp;
public static ScriptEngineKind ResolveAuto(string? script)
{
if (TryGetDirective(script, out var kind))
return kind;
if (UsesDrawingApi(script))
return ScriptEngineKind.MoonSharp;
return UsesPixelApi(script) ? ScriptEngineKind.Native : ScriptEngineKind.MoonSharp;
}
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);
private static bool TryGetDirective(string? script, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
if (string.IsNullOrEmpty(script))
return false;
int index = 0;
int length = script.Length;
while (index < length)
{
int lineStart = index;
while (index < length && script[index] != '\n')
index++;
int lineEnd = index;
if (lineEnd > lineStart && script[lineEnd - 1] == '\r')
lineEnd--;
if (TryParseDirectiveLine(script, lineStart, lineEnd, out kind))
return true;
index++;
}
return false;
}
private static bool TryParseDirectiveLine(string script, int start, int end, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
int i = start;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
if (i + 3 > end || script[i] != '-' || script[i + 1] != '-' || script[i + 2] != '!')
return false;
i += 3;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
int tokenStart = i;
while (i < end && IsTokenChar(script[i]))
i++;
int tokenEnd = i;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
if (i != end)
return false;
var token = script.AsSpan(tokenStart, tokenEnd - tokenStart);
if (token.Equals("native", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Native;
return true;
}
if (token.Equals("gpu", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Gpu;
return true;
}
if (token.Equals("cpu", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Cpu;
return true;
}
if (token.Equals("moonsharp", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.MoonSharp;
return true;
}
return false;
}
private static bool IsTokenChar(char c) =>
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
}
-94
ファイルの表示
@@ -9,98 +9,4 @@ namespace LuaScript.Engine
Gpu,
Cpu,
}
internal static class ScriptDirective
{
public static ScriptEngineKind Resolve(string? script) =>
TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.MoonSharp;
public static ScriptEngineKind ResolveAuto(string? script)
{
if (TryGetDirective(script, out var kind))
return kind;
return UsesPixelApi(script) ? ScriptEngineKind.Native : ScriptEngineKind.MoonSharp;
}
public static bool UsesPixelApi(string? script) =>
script is not null && (script.Contains("getpixel", StringComparison.Ordinal) || script.Contains("setpixel", StringComparison.Ordinal));
private static bool TryGetDirective(string? script, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
if (string.IsNullOrEmpty(script))
return false;
int index = 0;
int length = script.Length;
while (index < length)
{
int lineStart = index;
while (index < length && script[index] != '\n')
index++;
int lineEnd = index;
if (lineEnd > lineStart && script[lineEnd - 1] == '\r')
lineEnd--;
if (TryParseDirectiveLine(script, lineStart, lineEnd, out kind))
return true;
index++;
}
return false;
}
private static bool TryParseDirectiveLine(string script, int start, int end, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
int i = start;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
if (i + 3 > end || script[i] != '-' || script[i + 1] != '-' || script[i + 2] != '!')
return false;
i += 3;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
int tokenStart = i;
while (i < end && IsTokenChar(script[i]))
i++;
int tokenEnd = i;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
if (i != end)
return false;
var token = script.AsSpan(tokenStart, tokenEnd - tokenStart);
if (token.Equals("native", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Native;
return true;
}
if (token.Equals("gpu", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Gpu;
return true;
}
if (token.Equals("cpu", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Cpu;
return true;
}
if (token.Equals("moonsharp", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.MoonSharp;
return true;
}
return false;
}
private static bool IsTokenChar(char c) =>
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
}
+97
ファイルの表示
@@ -0,0 +1,97 @@
using System;
using System.IO;
using Vortice.Mathematics;
using Vortice.WIC;
namespace LuaScript
{
internal sealed class ImageDecoder : IDisposable
{
private const int MaxDimension = 8192;
private IWICImagingFactory? _factory;
public unsafe byte[] Decode(string path, out int width, out int height)
{
width = 1;
height = 1;
if (string.IsNullOrEmpty(path) || !IsSupportedImage(path))
return new byte[4];
try
{
_factory ??= new IWICImagingFactory();
using var stream = _factory.CreateStream(path, FileAccess.Read);
using var decoder = _factory.CreateDecoderFromStream(stream, DecodeOptions.CacheOnDemand);
using var frame = decoder.GetFrame(0);
using var converter = _factory.CreateFormatConverter();
converter.Initialize(
frame,
Vortice.WIC.PixelFormat.Format32bppPBGRA,
BitmapDitherType.None,
null,
0d,
BitmapPaletteType.Custom);
converter.GetSize(out int w, out int h);
if (w <= 0 || h <= 0 || w > MaxDimension || h > MaxDimension)
return new byte[4];
var buffer = new byte[w * h * 4];
fixed (byte* p = buffer)
converter.CopyPixels(new RectI(0, 0, w, h), w * 4, buffer.Length, (nint)p);
width = w;
height = h;
return buffer;
}
catch
{
width = 1;
height = 1;
return new byte[4];
}
}
private static bool IsSupportedImage(string path)
{
try
{
if (!File.Exists(path))
return false;
Span<byte> head = stackalloc byte[12];
using var stream = File.OpenRead(path);
int read = stream.Read(head);
if (read < 4)
return false;
if (head[0] == 0x89 && head[1] == 0x50 && head[2] == 0x4E && head[3] == 0x47)
return true;
if (head[0] == 0xFF && head[1] == 0xD8 && head[2] == 0xFF)
return true;
if (head[0] == 0x47 && head[1] == 0x49 && head[2] == 0x46 && head[3] == 0x38)
return true;
if (head[0] == 0x42 && head[1] == 0x4D)
return true;
if ((head[0] == 0x49 && head[1] == 0x49 && head[2] == 0x2A && head[3] == 0x00) ||
(head[0] == 0x4D && head[1] == 0x4D && head[2] == 0x00 && head[3] == 0x2A))
return true;
if (read >= 12 &&
head[0] == 0x52 && head[1] == 0x49 && head[2] == 0x46 && head[3] == 0x46 &&
head[8] == 0x57 && head[9] == 0x45 && head[10] == 0x42 && head[11] == 0x50)
return true;
return false;
}
catch
{
return false;
}
}
public void Dispose()
{
_factory?.Dispose();
_factory = null;
}
}
}
+1 -1
ファイルの表示
@@ -42,7 +42,7 @@ namespace LuaScript
"obj.time", "obj.totaltime", "obj.t", "obj.frame", "obj.totalframe",
"obj.framerate", "obj.layer", "obj.index", "obj.num",
"obj.getpixel", "obj.setpixel",
"obj.getpixeldata"
"obj.getpixeldata", "obj.rand", "obj.load"
]),
("math", [
"math.abs", "math.ceil", "math.cos", "math.exp", "math.floor",
+5 -1
ファイルの表示
@@ -4,7 +4,7 @@
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.3.3</Version>
<Version>1.8.0</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
@@ -67,6 +67,10 @@
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.MediaFoundation">
<HintPath>$(YMM4DirPath)Vortice.MediaFoundation.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="YukkuriMovieMaker">
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.dll</HintPath>
<Private>false</Private>
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System;
namespace LuaScript
{
internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+104 -1
ファイルの表示
@@ -1,8 +1,12 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Windows.Media;
using LuaScript.Compat;
using Newtonsoft.Json;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Controls;
using YukkuriMovieMaker.Exo;
using YukkuriMovieMaker.ItemEditor.CustomVisibilityAttributes;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Plugin;
using YukkuriMovieMaker.Plugin.Effects;
@@ -27,27 +31,126 @@ namespace LuaScript
[Display(GroupName = nameof(Texts.ScriptGroup), ResourceType = typeof(Texts))]
[CodeEditor(Language = "pack://application:,,,/LuaScript;component/Resources/SyntaxDefinitions/Lua-{theme}.xshd", FoldingStrategyType = typeof(LuaFoldingStrategy), AutoCompletionStrategyType = typeof(LuaAutoCompletionStrategy), ToolBarStrategyType = typeof(EmptyToolBarStrategy), PropertyEditorSize = PropertyEditorSize.FullWidth)]
public string Script { get => _script; set => Set(ref _script, value); }
public string Script
{
get => _script;
set { if (Set(ref _script, value)) UpdateLayout(); }
}
string _script = DefaultScript;
string IScriptProvider.DefaultScript => DefaultScript;
internal AviUtlParameterLayout Layout { get; private set; } = AviUtlParameterLayout.Parse(DefaultScript);
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track0), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", -100, 100)]
[ShowPropertyEditorWhen(nameof(IsTrack0Visible), true)]
public Animation Track0 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue);
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track1), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", -100, 100)]
[ShowPropertyEditorWhen(nameof(IsTrack1Visible), true)]
public Animation Track1 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue);
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track2), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", -100, 100)]
[ShowPropertyEditorWhen(nameof(IsTrack2Visible), true)]
public Animation Track2 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue);
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track3), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", -100, 100)]
[ShowPropertyEditorWhen(nameof(IsTrack3Visible), true)]
public Animation Track3 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue);
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Check0), Description = nameof(Texts.CheckDesc), ResourceType = typeof(Texts))]
[ToggleSlider]
[ShowPropertyEditorWhen(nameof(IsCheck0Visible), true)]
public bool Check0 { get => _check0; set => Set(ref _check0, value); }
bool _check0;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Check1), Description = nameof(Texts.CheckDesc), ResourceType = typeof(Texts))]
[ToggleSlider]
[ShowPropertyEditorWhen(nameof(IsCheck1Visible), true)]
public bool Check1 { get => _check1; set => Set(ref _check1, value); }
bool _check1;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Check2), Description = nameof(Texts.CheckDesc), ResourceType = typeof(Texts))]
[ToggleSlider]
[ShowPropertyEditorWhen(nameof(IsCheck2Visible), true)]
public bool Check2 { get => _check2; set => Set(ref _check2, value); }
bool _check2;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Check3), Description = nameof(Texts.CheckDesc), ResourceType = typeof(Texts))]
[ToggleSlider]
[ShowPropertyEditorWhen(nameof(IsCheck3Visible), true)]
public bool Check3 { get => _check3; set => Set(ref _check3, value); }
bool _check3;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Color), Description = nameof(Texts.ColorDesc), ResourceType = typeof(Texts))]
[ColorPicker]
[ShowPropertyEditorWhen(nameof(IsColorVisible), true)]
public Color Color { get => _color; set => Set(ref _color, value); }
Color _color = Colors.White;
[JsonIgnore] public bool IsTrack0Visible { get => _isTrack0Visible; private set => Set(ref _isTrack0Visible, value); }
[JsonIgnore] public bool IsTrack1Visible { get => _isTrack1Visible; private set => Set(ref _isTrack1Visible, value); }
[JsonIgnore] public bool IsTrack2Visible { get => _isTrack2Visible; private set => Set(ref _isTrack2Visible, value); }
[JsonIgnore] public bool IsTrack3Visible { get => _isTrack3Visible; private set => Set(ref _isTrack3Visible, value); }
[JsonIgnore] public bool IsCheck0Visible { get => _isCheck0Visible; private set => Set(ref _isCheck0Visible, value); }
[JsonIgnore] public bool IsCheck1Visible { get => _isCheck1Visible; private set => Set(ref _isCheck1Visible, value); }
[JsonIgnore] public bool IsCheck2Visible { get => _isCheck2Visible; private set => Set(ref _isCheck2Visible, value); }
[JsonIgnore] public bool IsCheck3Visible { get => _isCheck3Visible; private set => Set(ref _isCheck3Visible, value); }
[JsonIgnore] public bool IsColorVisible { get => _isColorVisible; private set => Set(ref _isColorVisible, value); }
bool _isTrack0Visible = true;
bool _isTrack1Visible = true;
bool _isTrack2Visible = true;
bool _isTrack3Visible = true;
bool _isCheck0Visible;
bool _isCheck1Visible;
bool _isCheck2Visible;
bool _isCheck3Visible;
bool _isColorVisible;
private void UpdateLayout()
{
var layout = AviUtlParameterLayout.Parse(_script);
Layout = layout;
bool hasAny = layout.HasAny;
IsTrack0Visible = !hasAny || layout.HasTrack(0);
IsTrack1Visible = !hasAny || layout.HasTrack(1);
IsTrack2Visible = !hasAny || layout.HasTrack(2);
IsTrack3Visible = !hasAny || layout.HasTrack(3);
IsCheck0Visible = layout.HasCheck(0);
IsCheck1Visible = layout.HasCheck(1);
IsCheck2Visible = layout.HasCheck(2);
IsCheck3Visible = layout.HasCheck(3);
IsColorVisible = layout.HasColor;
SeedDefaults(layout);
}
private void SeedDefaults(AviUtlParameterLayout layout)
{
if (layout.GetCheck(0) is { Default: true } && !_check0) Check0 = true;
if (layout.GetCheck(1) is { Default: true } && !_check1) Check1 = true;
if (layout.GetCheck(2) is { Default: true } && !_check2) Check2 = true;
if (layout.GetCheck(3) is { Default: true } && !_check3) Check3 = true;
if (layout.Color is { } color && _color == Colors.White)
Color = ToMediaColor(color.Default);
}
private static Color ToMediaColor(int rgb)
{
byte r = (byte)((rgb >> 16) & 0xFF);
byte g = (byte)((rgb >> 8) & 0xFF);
byte b = (byte)(rgb & 0xFF);
return Color.FromRgb(r, g, b);
}
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices)
+182 -132
ファイルの表示
@@ -1,6 +1,7 @@
using System.IO;
using System.Numerics;
using System.Runtime.InteropServices;
using LuaScript.Compat;
using LuaScript.Engine;
using Vortice;
using Vortice.DCommon;
@@ -27,6 +28,12 @@ namespace LuaScript
double Track1,
double Track2,
double Track3,
bool Check0,
bool Check1,
bool Check2,
bool Check3,
bool HasColor,
int Color,
string Script,
TimelineSourceUsage Usage,
Guid SceneId,
@@ -56,6 +63,7 @@ namespace LuaScript
private LuaJitWorker? _nativeWorker;
private double[]? _nativeFields;
private bool _nativeWarned;
private bool _effectChainWarned;
private EffectDescription? _frameDesc;
private SceneObjectResolver? _frameResolver;
@@ -67,26 +75,29 @@ namespace LuaScript
private GraphicsDevicesAndContext? _ownCtx;
private ID2D1Bitmap1? _renderTarget;
private ID2D1Bitmap1? _stagingBitmap;
private ID2D1Bitmap1? _outputBitmap;
private AffineTransform2D? _transformEffect;
private byte[]? _pixelBuffer;
private int _bitmapWidth;
private int _bitmapHeight;
private RawRectF _cachedBounds;
private PixelBufferManager? _pixelManager;
private bool _isFirst = true;
private string _sourceScript = string.Empty;
private string _runnableScript = string.Empty;
private bool _runnableCached;
private ID2D1Image? _cachedInput;
private RenderKey _cachedKey;
private SceneObjectQuery[] _cachedQueries = [];
private DrawDescription? _cachedOutputDesc;
private bool _cachedPixelsModified;
private ID2D1Image? _cachedEffectOutput;
private VideoEffectChain? _effectChain;
private DrawCompositor? _drawCompositor;
private TextRenderer? _nativeTextRenderer;
private ImageDecoder? _nativeImageDecoder;
private MovieDecoder? _nativeMovieDecoder;
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
{
_ownCtx = new GraphicsDevicesAndContext(devices);
disposer.Collect(_ownCtx);
_pixelManager = new PixelBufferManager(_ownCtx);
_context.ResolverProvider = GetFrameResolver;
return null;
}
@@ -112,6 +123,17 @@ namespace LuaScript
return _lastSceneId;
}
private string GetRunnableScript(string source)
{
if (_runnableCached && string.Equals(source, _sourceScript, StringComparison.Ordinal))
return _runnableScript;
_runnableScript = AviUtlScript.Transform(source);
_sourceScript = source;
_runnableCached = true;
return _runnableScript;
}
protected override void setInput(ID2D1Image? input)
{
if (!ReferenceEquals(_cachedInput, input))
@@ -135,16 +157,22 @@ namespace LuaScript
var time = desc.ItemPosition.Time.TotalSeconds;
var script = item.Script ?? string.Empty;
var t0 = item.Track0.GetValue(frame, length, fps);
var t1 = item.Track1.GetValue(frame, length, fps);
var t2 = item.Track2.GetValue(frame, length, fps);
var t3 = item.Track3.GetValue(frame, length, fps);
var layout = item.Layout;
var t0 = ClampTrack(item.Track0.GetValue(frame, length, fps), layout, 0);
var t1 = ClampTrack(item.Track1.GetValue(frame, length, fps), layout, 1);
var t2 = ClampTrack(item.Track2.GetValue(frame, length, fps), layout, 2);
var t3 = ClampTrack(item.Track3.GetValue(frame, length, fps), layout, 3);
bool c0 = item.Check0, c1 = item.Check1, c2 = item.Check2, c3 = item.Check3;
bool hasColor = layout.HasColor;
int colorRgb = hasColor ? (item.Color.R << 16) | (item.Color.G << 8) | item.Color.B : 0;
var inDesc = desc.DrawDescription;
var key = new RenderKey(
frame, time, length, fps,
t0, t1, t2, t3,
c0, c1, c2, c3, hasColor, colorRgb,
script, desc.Usage, desc.SceneId,
desc.TimelinePosition.Frame,
desc.TimelinePosition.Time.TotalSeconds,
@@ -162,7 +190,7 @@ namespace LuaScript
if (!_isFirst && key == _cachedKey &&
(_cachedQueries.Length == 0 || QueriesMatch(_cachedQueries, GetFrameResolver())))
{
effectOutput = _cachedPixelsModified ? _transformEffect?.Output : null;
effectOutput = _cachedEffectOutput;
return _cachedOutputDesc ?? inDesc;
}
@@ -175,30 +203,32 @@ namespace LuaScript
ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH));
DrawDescription outDesc = inDesc;
bool pixelsModified = false;
try
{
bool wantNative = ScriptDirective.ResolveAuto(script) == ScriptEngineKind.Native;
string runnable = GetRunnableScript(script);
bool wantNative = ScriptDirective.ResolveAuto(runnable) == ScriptEngineKind.Native;
bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory);
if (wantNative && !nativeReady)
WarnNativeUnavailableOnce();
if (nativeReady)
{
pixelsModified = ExecuteNative(script, ctx, bounds, imgW, imgH);
ExecuteNative(runnable, ctx, bounds, imgW, imgH);
}
else
{
_engine.Execute(script, ctx);
_engine.Execute(runnable, ctx);
if (ctx.IsPixelsDirty)
{
EnsureBitmaps(imgW, imgH);
WritePixelsToOutput(ctx.GetPixelBuffer()!, imgW);
UpdateTransformEffect(bounds);
effectOutput = _transformEffect!.Output;
pixelsModified = true;
int bufW = ctx.ImageWidth;
int bufH = ctx.ImageHeight;
_pixelManager!.WritePixelsToOutput(ctx.GetPixelBuffer()!, bufW, bufH);
if (ctx.BufferReplaced)
effectOutput = _pixelManager.GetTransformOutput(-bufW / 2f, -bufH / 2f);
else
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
}
else
{
@@ -206,7 +236,32 @@ namespace LuaScript
}
}
if (ctx.DrawCommands.Count > 0)
{
ctx.EnsurePixelBuffer();
var drawBuffer = ctx.GetPixelBuffer();
if (drawBuffer is not null)
{
_drawCompositor ??= new DrawCompositor(_ownCtx);
effectOutput = _drawCompositor.Compose(drawBuffer, ctx.ImageWidth, ctx.ImageHeight, ctx.DrawCommands);
}
}
outDesc = BuildOutputDesc(inDesc, ctx);
if (ctx.EffectRequests.Count > 0)
{
var source = effectOutput ?? input;
try
{
effectOutput = ApplyEffectChain(source, ctx.EffectRequests, desc, ref outDesc);
}
catch (Exception ex)
{
effectOutput = source;
WarnEffectChainFailureOnce(ex);
}
}
}
catch (LuaScriptTimeoutException ex)
{
@@ -232,11 +287,17 @@ namespace LuaScript
_cachedKey = key;
_cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries];
_cachedOutputDesc = outDesc;
_cachedPixelsModified = pixelsModified;
_cachedEffectOutput = effectOutput;
return outDesc;
}
private ID2D1Image ApplyEffectChain(ID2D1Image source, IReadOnlyList<AviUtlEffectRequest> requests, EffectDescription desc, ref DrawDescription drawDescription)
{
_effectChain ??= new VideoEffectChain(_ownCtx!);
return _effectChain.Apply(source, requests, desc, ref drawDescription);
}
private static SceneObjectResolver BuildSceneObjectResolver(EffectDescription desc)
{
var scenes = desc.Scenes;
@@ -293,6 +354,8 @@ namespace LuaScript
: 0d;
ctx.ClearQueries();
ctx.ClearEffects();
ctx.ClearDraws();
ctx.ImageWidth = imgW;
ctx.ImageHeight = imgH;
@@ -314,6 +377,12 @@ namespace LuaScript
ctx.Track1 = key.Track1;
ctx.Track2 = key.Track2;
ctx.Track3 = key.Track3;
ctx.Check0 = key.Check0;
ctx.Check1 = key.Check1;
ctx.Check2 = key.Check2;
ctx.Check3 = key.Check3;
ctx.HasColor = key.HasColor;
ctx.ColorValue = key.Color;
ctx.Time = key.Time;
ctx.Frame = key.Frame;
ctx.TotalFrame = key.Length;
@@ -337,6 +406,11 @@ namespace LuaScript
ctx.TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d;
}
private static double ClampTrack(double value, AviUtlParameterLayout layout, int index)
{
return layout.GetTrack(index) is { } p ? Math.Clamp(value, p.Min, p.Max) : value;
}
private static DrawDescription BuildOutputDesc(DrawDescription inDesc, AviUtlScriptContext ctx)
{
return inDesc with
@@ -356,6 +430,13 @@ namespace LuaScript
Log.Default.Write($"LuaScript: native runtime not found at '{NativeDirectory}'. Falling back to MoonSharp (slow). Deploy the 'native' folder next to the plugin.");
}
private void WarnEffectChainFailureOnce(Exception ex)
{
if (_effectChainWarned) return;
_effectChainWarned = true;
Log.Default.Write("LuaScript: obj.effect chain failed and was skipped for this frame. The source image is passed through unchanged.", ex);
}
private bool ExecuteNative(string script, AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
{
_nativeWorker ??= new LuaJitWorker(NativeDirectory);
@@ -367,7 +448,14 @@ namespace LuaScript
bool ok = _nativeWorker.Execute(
script, _nativeFields, buffer, imgW, imgH, NativeTimeoutMilliseconds,
(tag, frame) => ctx.ResolveObject(tag, frame, out var info) ? info : null,
out bool dirty, out string? error);
NativeLoadFigure,
NativeLoadText,
NativeLoadImage,
NativeLoadMovie,
(name, args) => ctx.AddEffect(new AviUtlEffectRequest(name, args)),
ctx.AddDraw,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels,
out int resultW, out int resultH, out string? error);
if (!ok)
{
@@ -378,61 +466,83 @@ namespace LuaScript
NativeFieldMap.FromFields(_nativeFields, ctx);
bool hasDraws = ctx.DrawCommands.Count > 0;
if (dirty)
{
EnsureBitmaps(imgW, imgH);
WritePixelsToOutput(buffer, imgW);
UpdateTransformEffect(bounds);
effectOutput = _transformEffect!.Output;
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 (hasDraws)
{
ctx.SetResolvedBuffer(outPixels, outW, outH);
return true;
}
_pixelManager!.WritePixelsToOutput(outPixels, outW, outH);
if (bufferReplaced)
effectOutput = _pixelManager.GetTransformOutput(-outW / 2f, -outH / 2f);
else
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
return true;
}
if (hasDraws)
{
ctx.SetResolvedBuffer(buffer, imgW, imgH);
return false;
}
effectOutput = null;
return false;
}
private (byte[] buffer, int w, int h) NativeLoadText(string family, string text, double size, bool bold, bool italic, int color)
{
_nativeTextRenderer ??= new TextRenderer();
var buffer = _nativeTextRenderer.Render(text, family, size, bold, italic, color, out int w, out int h);
return (buffer, w, h);
}
private (byte[] buffer, int w, int h) NativeLoadImage(string path)
{
_nativeImageDecoder ??= new ImageDecoder();
var buffer = _nativeImageDecoder.Decode(path, out int w, out int h);
return (buffer, w, h);
}
private (byte[] buffer, int w, int h) NativeLoadMovie(string path, double time)
{
_nativeMovieDecoder ??= new MovieDecoder();
var buffer = _nativeMovieDecoder.Decode(path, time, out int w, out int h);
return (buffer, w, h);
}
private static (byte[] buffer, int w, int h) NativeLoadFigure(string name, int color, double size, double lineWidth, double aspect)
{
aspect = Math.Clamp(aspect, -1d, 1d);
int boundingSize = Math.Max(1, (int)Math.Round(size));
double w = aspect >= 0d ? boundingSize * (1d - aspect) : boundingSize;
double h = aspect <= 0d ? boundingSize * (1d + aspect) : boundingSize;
int fw = Math.Max(1, (int)Math.Round(w));
int fh = Math.Max(1, (int)Math.Round(h));
var buffer = FigureRenderer.Render(name, fw, fh, color, lineWidth);
return (buffer, fw, fh);
}
private byte[] LoadInputPixels(RawRectF bounds, int width, int height)
{
_pixelLoaderSemaphore.Wait();
try
{
EnsureBitmaps(width, height);
var dc = _ownCtx!.DeviceContext;
var savedTarget = dc.Target;
dc.Target = _renderTarget;
dc.BeginDraw();
dc.Clear(null);
dc.DrawImage(input!, new Vector2(-bounds.Left, -bounds.Top));
dc.EndDraw();
dc.Target = savedTarget;
_stagingBitmap!.CopyFromBitmap(_renderTarget!);
var mapped = _stagingBitmap.Map(MapOptions.Read);
try
{
if (mapped.Pitch == width * 4)
{
Marshal.Copy(mapped.Bits, _pixelBuffer!, 0, width * height * 4);
}
else
{
for (int row = 0; row < height; row++)
Marshal.Copy(
mapped.Bits + mapped.Pitch * row,
_pixelBuffer!,
row * width * 4,
width * 4);
}
}
finally
{
_stagingBitmap.Unmap();
}
return _pixelBuffer!;
return _pixelManager!.LoadInputPixels(input!, bounds, width, height);
}
finally
{
@@ -440,79 +550,19 @@ namespace LuaScript
}
}
private unsafe void WritePixelsToOutput(byte[] pixels, int width)
{
fixed (byte* ptr = pixels)
_outputBitmap!.CopyFromMemory(new nint(ptr), width * 4);
}
private void UpdateTransformEffect(RawRectF bounds)
{
if (_transformEffect is null)
{
_transformEffect = new AffineTransform2D(_ownCtx!.DeviceContext);
_transformEffect.SetInput(0, _outputBitmap, true);
_cachedBounds = default;
}
if (_cachedBounds.Left != bounds.Left || _cachedBounds.Top != bounds.Top)
{
_transformEffect.TransformMatrix = Matrix3x2.CreateTranslation(bounds.Left, bounds.Top);
_cachedBounds = bounds;
}
}
private void EnsureBitmaps(int width, int height)
{
if (_bitmapWidth == width && _bitmapHeight == height) return;
_renderTarget?.Dispose();
_stagingBitmap?.Dispose();
_outputBitmap?.Dispose();
_transformEffect?.Dispose();
_renderTarget = null;
_stagingBitmap = null;
_outputBitmap = null;
_transformEffect = null;
_bitmapWidth = 0;
_bitmapHeight = 0;
var dc = _ownCtx!.DeviceContext;
_renderTarget = 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);
_stagingBitmap = dc.CreateBitmap(
new SizeI(width, height),
nint.Zero,
width * 4,
stagingProps);
_outputBitmap = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
_pixelBuffer = new byte[width * height * 4];
_bitmapWidth = width;
_bitmapHeight = height;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_engine.Dispose();
_nativeWorker?.Dispose();
_effectChain?.Dispose();
_drawCompositor?.Dispose();
_nativeTextRenderer?.Dispose();
_nativeImageDecoder?.Dispose();
_pixelLoaderSemaphore.Dispose();
_renderTarget?.Dispose();
_stagingBitmap?.Dispose();
_outputBitmap?.Dispose();
_transformEffect?.Dispose();
_renderTarget = null;
_stagingBitmap = null;
_outputBitmap = null;
_transformEffect = null;
_pixelManager?.Dispose();
_pixelManager = null;
}
base.Dispose(disposing);
}
+293 -33
ファイルの表示
@@ -1,3 +1,4 @@
using LuaScript.Compat;
using MoonSharp.Interpreter;
using MoonSharp.Interpreter.Debugging;
using MoonSharp.Interpreter.Loaders;
@@ -52,6 +53,18 @@ namespace LuaScript
private readonly List<string> _removalBuffer = [];
private readonly Dictionary<string, DynValue> _options = new(StringComparer.Ordinal);
private readonly Dictionary<string, DynValue> _pixelOptions = new(StringComparer.Ordinal);
private TextRenderer? _textRenderer;
private ImageDecoder? _imageDecoder;
private MovieDecoder? _movieDecoder;
private string _fontFamily = string.Empty;
private double _fontSize = 34d;
private bool _fontBold;
private bool _fontItalic;
private int _fontColor = 0xFFFFFF;
private Script? _script;
private DynValue? _compiledChunk;
private string _lastCompiledCode = string.Empty;
@@ -202,6 +215,14 @@ namespace LuaScript
var script = _script!;
bool isFirstSetup = _objTable is null;
_options.Clear();
_pixelOptions.Clear();
_fontFamily = string.Empty;
_fontSize = 34d;
_fontBold = false;
_fontItalic = false;
_fontColor = 0xFFFFFF;
if (isFirstSetup)
{
var sceneTable = new Table(script);
@@ -312,6 +333,12 @@ namespace LuaScript
_objTable!["track1"] = ctx.Track1;
_objTable!["track2"] = ctx.Track2;
_objTable!["track3"] = ctx.Track3;
_objTable!["check0"] = ctx.Check0;
_objTable!["check1"] = ctx.Check1;
_objTable!["check2"] = ctx.Check2;
_objTable!["check3"] = ctx.Check3;
if (ctx.HasColor)
script.Globals["color"] = ctx.ColorValue;
_objTable!["time"] = ctx.Time;
_objTable!["frame"] = ctx.Frame;
_objTable!["totalframe"] = ctx.TotalFrame;
@@ -451,6 +478,255 @@ namespace LuaScript
});
obj["putpixeldata"] = DynValue.NewCallback((_, _) => DynValue.Void);
obj["rand"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
double frameDefault = _activeContext?.Frame ?? 0d;
double a = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
double b = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
double seed = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
double frame = args.Count > 3 ? args[3].CastToNumber() ?? frameDefault : frameDefault;
return DynValue.NewNumber(AviUtlRandom.Next(a, b, seed, frame));
});
obj["load"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Void;
switch (args[0].String)
{
case "figure" when args.Count >= 4:
LoadFigure(
args[1].Type == DataType.String ? args[1].String : string.Empty,
(int)(args[2].CastToNumber() ?? 0d),
args[3].CastToNumber() ?? 0d,
args.Count > 4 ? args[4].CastToNumber() ?? 0d : 0d,
args.Count > 5 ? Math.Clamp(args[5].CastToNumber() ?? 0d, -1d, 1d) : 0d);
break;
case "text":
LoadText(args.Count > 1 && args[1].Type == DataType.String ? args[1].String : string.Empty);
break;
case "image" when args.Count > 1 && args[1].Type == DataType.String:
LoadImage(args[1].String);
break;
case "movie" when args.Count > 1 && args[1].Type == DataType.String:
LoadMovie(
args[1].String,
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
break;
}
return DynValue.Void;
});
obj["setfont"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (args.Count == 0)
return DynValue.Void;
if (args[0].Type == DataType.String)
_fontFamily = args[0].String;
if (args.Count > 1)
_fontSize = args[1].CastToNumber() ?? _fontSize;
if (args.Count > 2)
{
int type = (int)(args[2].CastToNumber() ?? 0d);
_fontBold = (type & 1) != 0;
_fontItalic = (type & 2) != 0;
}
if (args.Count > 3)
_fontColor = (int)(args[3].CastToNumber() ?? _fontColor);
return DynValue.Void;
});
obj["effect"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Void;
string name = args[0].String;
var arguments = new List<KeyValuePair<string, object>>();
for (int i = 1; i + 1 < args.Count; i += 2)
{
if (args[i].Type != DataType.String)
continue;
var value = args[i + 1];
object boxed = value.Type switch
{
DataType.Number => value.Number,
DataType.Boolean => value.Boolean,
DataType.String => value.String,
_ => value.CastToNumber() ?? 0d,
};
arguments.Add(new KeyValuePair<string, object>(args[i].String, boxed));
}
_activeContext.AddEffect(new AviUtlEffectRequest(name, arguments));
return DynValue.Void;
});
obj["draw"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null)
return DynValue.Void;
double ox = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
double oy = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
double oz = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
double zoom = args.Count > 3 ? args[3].CastToNumber() ?? 1d : 1d;
double alpha = args.Count > 4 ? args[4].CastToNumber() ?? 1d : 1d;
double aspect = args.Count > 5 ? args[5].CastToNumber() ?? 0d : 0d;
_activeContext.AddDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, CurrentAntialias()));
return DynValue.Void;
});
obj["drawpoly"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 12)
return DynValue.Void;
var poly = new double[DrawPolyMath.Length];
for (int i = 0; i < 12; i++)
poly[i] = args[i].CastToNumber() ?? 0d;
if (args.Count >= 20)
{
for (int i = 0; i < 8; i++)
poly[12 + i] = args[12 + i].CastToNumber() ?? 0d;
}
else
{
double w = _activeContext.ImageWidth;
double h = _activeContext.ImageHeight;
poly[12] = 0d; poly[13] = 0d;
poly[14] = w; poly[15] = 0d;
poly[16] = w; poly[17] = h;
poly[18] = 0d; poly[19] = h;
}
poly[20] = args.Count switch
{
13 => args[12].CastToNumber() ?? 1d,
>= 21 => args[20].CastToNumber() ?? 1d,
_ => 1d,
};
_activeContext.AddDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, CurrentAntialias()));
return DynValue.Void;
});
obj["copybuffer"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 2 ||
args[0].Type != DataType.String || args[1].Type != DataType.String)
return DynValue.Void;
if (_activeContext.CopyBuffer(args[0].String, args[1].String))
RefreshObjDimensions();
return DynValue.Void;
});
obj["getvalue"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (args.Count == 0 || args[0].Type != DataType.String)
return DynValue.NewNumber(0d);
var value = _objTable!.Get(args[0].String);
return value.Type == DataType.Number ? value : DynValue.NewNumber(0d);
});
obj["setoption"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Void;
_options[args[0].String] = args.Count > 1 ? args[1] : DynValue.True;
return DynValue.Void;
});
obj["getoption"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (args.Count == 0 || args[0].Type != DataType.String)
return DynValue.NewNumber(0d);
return _options.TryGetValue(args[0].String, out var value) ? value : DynValue.NewNumber(0d);
});
obj["pixeloption"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Void;
_pixelOptions[args[0].String] = args.Count > 1 ? args[1] : DynValue.True;
return DynValue.Void;
});
}
private double CurrentAntialias() =>
_options.TryGetValue("antialias", out var value) && value.Type == DataType.Number
? value.Number
: 1d;
private void LoadFigure(string name, int color, double size, double line, double aspect)
{
int boundingSize = Math.Max(1, (int)Math.Round(size));
double width = aspect >= 0d ? boundingSize * (1d - aspect) : boundingSize;
double height = aspect <= 0d ? boundingSize * (1d + aspect) : boundingSize;
int w = Math.Max(1, (int)Math.Round(width));
int h = Math.Max(1, (int)Math.Round(height));
var buffer = FigureRenderer.Render(name, w, h, color, line);
_activeContext!.ReplaceBuffer(buffer, w, h);
RefreshObjDimensions();
}
private void LoadText(string text)
{
_textRenderer ??= new TextRenderer();
var buffer = _textRenderer.Render(
text, _fontFamily, _fontSize, _fontBold, _fontItalic, _fontColor,
out int w, out int h);
_activeContext!.ReplaceBuffer(buffer, w, h);
RefreshObjDimensions();
}
private void LoadImage(string path)
{
_imageDecoder ??= new ImageDecoder();
var buffer = _imageDecoder.Decode(path, out int w, out int h);
_activeContext!.ReplaceBuffer(buffer, w, h);
RefreshObjDimensions();
}
private void LoadMovie(string path, double time)
{
_movieDecoder ??= new MovieDecoder();
var buffer = _movieDecoder.Decode(path, time, out int w, out int h);
_activeContext!.ReplaceBuffer(buffer, w, h);
RefreshObjDimensions();
}
private void RefreshObjDimensions()
{
int w = _activeContext!.ImageWidth;
int h = _activeContext.ImageHeight;
var obj = _objTable!;
obj["w"] = w;
obj["h"] = h;
obj["hw"] = w / 2d;
obj["hh"] = h / 2d;
obj["cx"] = w / 2d;
obj["cy"] = h / 2d;
obj["cz"] = 0d;
obj["diagonal"] = Math.Sqrt((double)w * w + (double)h * h);
}
private static DynValue BuildObjectTable(Script script, SceneObjectInfo info)
@@ -488,39 +764,17 @@ namespace LuaScript
ctx.Oz = _objTable.Get("oz").CastToNumber() ?? ctx.Oz;
ctx.Alpha = _objTable.Get("alpha").CastToNumber() ?? ctx.Alpha;
double initialSx = ctx.Sx;
double initialSy = ctx.Sy;
double initialZoom = ctx.Zoom;
double initialAspect = ctx.Aspect;
ctx.Sx = _objTable.Get("sx").CastToNumber() ?? ctx.Sx;
ctx.Sy = _objTable.Get("sy").CastToNumber() ?? ctx.Sy;
ctx.Zoom = _objTable.Get("zoom").CastToNumber() ?? ctx.Zoom;
ctx.Aspect = _objTable.Get("aspect").CastToNumber() ?? ctx.Aspect;
bool sxsyChanged = Math.Abs(ctx.Sx - initialSx) > 1e-10 || Math.Abs(ctx.Sy - initialSy) > 1e-10;
bool zoomAspectChanged = Math.Abs(ctx.Zoom - initialZoom) > 1e-10 || Math.Abs(ctx.Aspect - initialAspect) > 1e-10;
if (zoomAspectChanged && !sxsyChanged)
{
ctx.Sx = ctx.Zoom * (1.0 + ctx.Aspect);
ctx.Sy = ctx.Zoom * (1.0 - ctx.Aspect);
}
double rxrNew = _objTable.Get("rxr").CastToNumber() ?? ctx.RxRad;
ctx.Rx = Math.Abs(rxrNew - ctx.RxRad) > 1e-10
? rxrNew * (180d / Math.PI)
: _objTable.Get("rx").CastToNumber() ?? ctx.Rx;
double ryrNew = _objTable.Get("ryr").CastToNumber() ?? ctx.RyRad;
ctx.Ry = Math.Abs(ryrNew - ctx.RyRad) > 1e-10
? ryrNew * (180d / Math.PI)
: _objTable.Get("ry").CastToNumber() ?? ctx.Ry;
double rzrNew = _objTable.Get("rzr").CastToNumber() ?? ctx.RzRad;
ctx.Rz = Math.Abs(rzrNew - ctx.RzRad) > 1e-10
? rzrNew * (180d / Math.PI)
: _objTable.Get("rz").CastToNumber() ?? ctx.Rz;
ctx.ApplyWriteBack(
_objTable.Get("sx").CastToNumber() ?? ctx.Sx,
_objTable.Get("sy").CastToNumber() ?? ctx.Sy,
_objTable.Get("zoom").CastToNumber() ?? ctx.Zoom,
_objTable.Get("aspect").CastToNumber() ?? ctx.Aspect,
_objTable.Get("rx").CastToNumber() ?? ctx.Rx,
_objTable.Get("ry").CastToNumber() ?? ctx.Ry,
_objTable.Get("rz").CastToNumber() ?? ctx.Rz,
_objTable.Get("rxr").CastToNumber() ?? ctx.RxRad,
_objTable.Get("ryr").CastToNumber() ?? ctx.RyRad,
_objTable.Get("rzr").CastToNumber() ?? ctx.RzRad);
}
public void Dispose()
@@ -528,6 +782,9 @@ namespace LuaScript
_disposeRequested = true;
_workSignal.Release();
_thread.Join();
_textRenderer?.Dispose();
_imageDecoder?.Dispose();
_movieDecoder?.Dispose();
_cts.Cancel();
_cts.Dispose();
_workSignal.Dispose();
@@ -541,6 +798,9 @@ namespace LuaScript
ThreadPool.QueueUserWorkItem(_ =>
{
_thread.Join();
_textRenderer?.Dispose();
_imageDecoder?.Dispose();
_movieDecoder?.Dispose();
_cts.Dispose();
_workSignal.Dispose();
_doneSignal.Dispose();
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System;
namespace LuaScript
{
internal abstract class LuaScriptException(string message, Exception? inner = null) : Exception(message, inner);
}
-10
ファイルの表示
@@ -1,10 +0,0 @@
namespace LuaScript
{
internal abstract class LuaScriptException(string message, Exception? inner = null) : Exception(message, inner);
internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner);
internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner);
internal sealed class LuaScriptTimeoutException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System;
namespace LuaScript
{
internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System;
namespace LuaScript
{
internal sealed class LuaScriptTimeoutException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+213
ファイルの表示
@@ -0,0 +1,213 @@
using System;
using System.IO;
using SharpGen.Runtime.Win32;
using Vortice.MediaFoundation;
namespace LuaScript
{
internal sealed class MovieDecoder : IDisposable
{
private const int MaxDimension = 8192;
private const int FirstVideoStream = -4;
private const int AllStreams = -2;
private const int EndOfStreamFlag = 0x2;
private bool _mfStarted;
private string? _path;
private IMFSourceReader? _reader;
private int _width;
private int _height;
private int _stride;
public unsafe byte[] Decode(string path, double timeSeconds, out int width, out int height)
{
width = 1;
height = 1;
if (string.IsNullOrEmpty(path) || !IsSupportedVideo(path))
return new byte[4];
try
{
EnsureReader(path);
if (_reader is null || _width <= 0 || _height <= 0)
return new byte[4];
SetPosition(_reader, (long)(Math.Max(0d, timeSeconds) * 10_000_000d));
using var sample = ReadVideoSample(_reader);
if (sample is null)
return new byte[4];
using var buffer = sample.ConvertToContiguousBuffer();
buffer.Lock(out nint data, out _, out _);
try
{
int w = _width;
int h = _height;
int absStride = Math.Abs(_stride);
bool bottomUp = _stride < 0;
var result = new byte[w * h * 4];
byte* src = (byte*)data;
fixed (byte* dst = result)
{
for (int y = 0; y < h; y++)
{
int sourceRow = bottomUp ? h - 1 - y : y;
byte* s = src + sourceRow * absStride;
byte* d = dst + y * w * 4;
for (int x = 0; x < w; x++)
{
d[0] = s[0];
d[1] = s[1];
d[2] = s[2];
d[3] = 255;
s += 4;
d += 4;
}
}
}
width = w;
height = h;
return result;
}
finally
{
buffer.Unlock();
}
}
catch
{
width = 1;
height = 1;
return new byte[4];
}
}
private void EnsureReader(string path)
{
if (_reader is not null && string.Equals(_path, path, StringComparison.Ordinal))
return;
DisposeReader();
if (!_mfStarted)
{
MediaFactory.MFStartup(false);
_mfStarted = true;
}
using var attributes = MediaFactory.MFCreateAttributes(1);
attributes.Set(SourceReaderAttributeKeys.EnableAdvancedVideoProcessing, 1);
var reader = MediaFactory.MFCreateSourceReaderFromURL(path, attributes);
reader.SetStreamSelection(AllStreams, false);
reader.SetStreamSelection(FirstVideoStream, true);
using (var mediaType = MediaFactory.MFCreateMediaType())
{
mediaType.Set(MediaTypeAttributeKeys.MajorType, MediaTypeGuids.Video);
mediaType.Set(MediaTypeAttributeKeys.Subtype, VideoFormatGuids.Rgb32);
reader.SetCurrentMediaType(FirstVideoStream, mediaType);
}
using var current = reader.GetCurrentMediaType(FirstVideoStream);
var mediaAttributes = (IMFAttributes)current;
ulong frameSize = Convert.ToUInt64(mediaAttributes.Get(MediaTypeAttributeKeys.FrameSize));
int w = (int)(frameSize >> 32);
int h = (int)(frameSize & 0xFFFFFFFF);
int stride;
try { stride = Convert.ToInt32(mediaAttributes.Get(MediaTypeAttributeKeys.DefaultStride)); }
catch { stride = w * 4; }
if (stride == 0)
stride = w * 4;
if (w <= 0 || h <= 0 || w > MaxDimension || h > MaxDimension)
{
reader.Dispose();
return;
}
_reader = reader;
_path = path;
_width = w;
_height = h;
_stride = stride;
}
private static void SetPosition(IMFSourceReader reader, long ticks)
{
var variant = new Variant
{
Value = ticks,
ElementType = (VariantElementType)20,
};
reader.SetCurrentPosition(Guid.Empty, variant);
}
private static IMFSample? ReadVideoSample(IMFSourceReader reader)
{
for (int guard = 0; guard < 256; guard++)
{
reader.ReadSample(FirstVideoStream, 0, out _, out int flags, out _, out IMFSample? sample);
if (sample is not null)
return sample;
if ((flags & EndOfStreamFlag) != 0)
return null;
}
return null;
}
private static bool IsSupportedVideo(string path)
{
try
{
if (!File.Exists(path))
return false;
Span<byte> head = stackalloc byte[16];
using var stream = File.OpenRead(path);
int read = stream.Read(head);
if (read < 12)
return false;
if (head[4] == 0x66 && head[5] == 0x74 && head[6] == 0x79 && head[7] == 0x70)
return true;
if (head[0] == 0x1A && head[1] == 0x45 && head[2] == 0xDF && head[3] == 0xA3)
return true;
if (head[0] == 0x52 && head[1] == 0x49 && head[2] == 0x46 && head[3] == 0x46 &&
head[8] == 0x41 && head[9] == 0x56 && head[10] == 0x49 && head[11] == 0x20)
return true;
if (head[0] == 0x46 && head[1] == 0x4C && head[2] == 0x56)
return true;
if (head[0] == 0x30 && head[1] == 0x26 && head[2] == 0xB2 && head[3] == 0x75)
return true;
return false;
}
catch
{
return false;
}
}
private void DisposeReader()
{
_reader?.Dispose();
_reader = null;
_path = null;
_width = 0;
_height = 0;
_stride = 0;
}
public void Dispose()
{
DisposeReader();
if (_mfStarted)
{
try { MediaFactory.MFShutdown(); }
catch { }
_mfStarted = false;
}
}
}
}
+145
ファイルの表示
@@ -0,0 +1,145 @@
using System;
using Vortice;
using System.Numerics;
using System.Runtime.InteropServices;
using Vortice.DCommon;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using Vortice.DXGI;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
namespace LuaScript
{
internal sealed class PixelBufferManager : IDisposable
{
private readonly GraphicsDevicesAndContext _ctx;
private ID2D1Bitmap1? _renderTarget;
private ID2D1Bitmap1? _stagingBitmap;
private ID2D1Bitmap1? _outputBitmap;
private AffineTransform2D? _transformEffect;
private byte[]? _pixelBuffer;
private int _bitmapWidth;
private int _bitmapHeight;
private RawRectF _cachedBounds;
public PixelBufferManager(GraphicsDevicesAndContext ctx)
{
_ctx = ctx;
}
public byte[] LoadInputPixels(ID2D1Image input, RawRectF bounds, int width, int height)
{
EnsureBitmaps(width, height);
var dc = _ctx.DeviceContext;
var savedTarget = dc.Target;
dc.Target = _renderTarget;
dc.BeginDraw();
dc.Clear(null);
dc.DrawImage(input, new Vector2(-bounds.Left, -bounds.Top));
dc.EndDraw();
dc.Target = savedTarget;
_stagingBitmap!.CopyFromBitmap(_renderTarget!);
var mapped = _stagingBitmap.Map(MapOptions.Read);
try
{
if (mapped.Pitch == width * 4)
{
Marshal.Copy(mapped.Bits, _pixelBuffer!, 0, width * height * 4);
}
else
{
for (int row = 0; row < height; row++)
Marshal.Copy(
mapped.Bits + mapped.Pitch * row,
_pixelBuffer!,
row * width * 4,
width * 4);
}
}
finally
{
_stagingBitmap.Unmap();
}
return _pixelBuffer!;
}
public unsafe void WritePixelsToOutput(byte[] pixels, int width, int height)
{
EnsureBitmaps(width, height);
fixed (byte* ptr = pixels)
_outputBitmap!.CopyFromMemory(new nint(ptr), width * 4);
}
public ID2D1Image GetTransformOutput(float left, float top)
{
if (_transformEffect is null)
{
_transformEffect = new AffineTransform2D(_ctx.DeviceContext);
_transformEffect.SetInput(0, _outputBitmap, true);
_cachedBounds = default;
}
if (_cachedBounds.Left != left || _cachedBounds.Top != top)
{
_transformEffect.TransformMatrix = Matrix3x2.CreateTranslation(left, top);
_cachedBounds = new RawRectF(left, top, left, top);
}
return _transformEffect.Output;
}
private void EnsureBitmaps(int width, int height)
{
if (_bitmapWidth == width && _bitmapHeight == height) return;
_renderTarget?.Dispose();
_stagingBitmap?.Dispose();
_outputBitmap?.Dispose();
_transformEffect?.Dispose();
_renderTarget = null;
_stagingBitmap = null;
_outputBitmap = null;
_transformEffect = null;
_bitmapWidth = 0;
_bitmapHeight = 0;
var dc = _ctx.DeviceContext;
_renderTarget = 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);
_stagingBitmap = dc.CreateBitmap(
new SizeI(width, height),
nint.Zero,
width * 4,
stagingProps);
_outputBitmap = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
_pixelBuffer = new byte[width * height * 4];
_bitmapWidth = width;
_bitmapHeight = height;
}
public void Dispose()
{
_renderTarget?.Dispose();
_stagingBitmap?.Dispose();
_outputBitmap?.Dispose();
_transformEffect?.Dispose();
_renderTarget = null;
_stagingBitmap = null;
_outputBitmap = null;
_transformEffect = null;
}
}
}
-5
ファイルの表示
@@ -10,9 +10,4 @@ namespace LuaScript
double Rz,
double Alpha,
int Layer);
internal readonly record struct SceneObjectQuery(
string Tag,
int Frame,
SceneObjectInfo? Result);
}
+7
ファイルの表示
@@ -0,0 +1,7 @@
namespace LuaScript
{
internal readonly record struct SceneObjectQuery(
string Tag,
int Frame,
SceneObjectInfo? Result);
}
+97
ファイルの表示
@@ -0,0 +1,97 @@
using System;
using System.Numerics;
using Vortice.Direct2D1;
using Vortice.DirectWrite;
using Vortice.Mathematics;
using Vortice.WIC;
namespace LuaScript
{
internal sealed class TextRenderer : IDisposable
{
private const int MaxDimension = 8192;
private const string FallbackFamily = "Yu Gothic UI";
private ID2D1Factory? _d2dFactory;
private IWICImagingFactory? _wicFactory;
private IDWriteFactory? _dwriteFactory;
private void EnsureFactories()
{
_d2dFactory ??= D2D1.D2D1CreateFactory<ID2D1Factory>(
Vortice.Direct2D1.FactoryType.MultiThreaded, DebugLevel.None);
_wicFactory ??= new IWICImagingFactory();
_dwriteFactory ??= DWrite.DWriteCreateFactory<IDWriteFactory>(
Vortice.DirectWrite.FactoryType.Shared);
}
public unsafe byte[] Render(
string text, string fontFamily, double fontSize,
bool bold, bool italic, int colorRgb,
out int width, out int height)
{
width = 1;
height = 1;
if (string.IsNullOrEmpty(text))
return new byte[4];
EnsureFactories();
float size = (float)Math.Clamp(fontSize, 1d, 4096d);
using var format = _dwriteFactory!.CreateTextFormat(
string.IsNullOrWhiteSpace(fontFamily) ? FallbackFamily : fontFamily,
null,
bold ? FontWeight.Bold : FontWeight.Normal,
italic ? FontStyle.Italic : FontStyle.Normal,
FontStretch.Normal,
size,
string.Empty);
using var layout = _dwriteFactory.CreateTextLayout(text, format, MaxDimension, MaxDimension);
var metrics = layout.Metrics;
int w = Math.Clamp((int)Math.Ceiling(metrics.WidthIncludingTrailingWhitespace), 1, MaxDimension);
int h = Math.Clamp((int)Math.Ceiling(metrics.Height), 1, MaxDimension);
using var wic = _wicFactory!.CreateBitmap(
w, h, Vortice.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnLoad);
var properties = new RenderTargetProperties(
RenderTargetType.Default,
new Vortice.DCommon.PixelFormat(Vortice.DXGI.Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
96f, 96f,
RenderTargetUsage.None,
FeatureLevel.Default);
float r = ((colorRgb >> 16) & 0xFF) / 255f;
float g = ((colorRgb >> 8) & 0xFF) / 255f;
float b = (colorRgb & 0xFF) / 255f;
using (var target = _d2dFactory!.CreateWicBitmapRenderTarget(wic, properties))
{
target.BeginDraw();
target.Clear(new Color4(0f, 0f, 0f, 0f));
using (var brush = target.CreateSolidColorBrush(new Color4(r, g, b, 1f)))
target.DrawTextLayout(new Vector2(-metrics.Left, -metrics.Top), layout, brush);
target.EndDraw();
}
var buffer = new byte[w * h * 4];
fixed (byte* p = buffer)
wic.CopyPixels(new RectI(0, 0, w, h), w * 4, buffer.Length, (nint)p);
width = w;
height = h;
return buffer;
}
public void Dispose()
{
_dwriteFactory?.Dispose();
_wicFactory?.Dispose();
_d2dFactory?.Dispose();
_dwriteFactory = null;
_wicFactory = null;
_d2dFactory = null;
}
}
}
+7
ファイルの表示
@@ -69,6 +69,13 @@
<data name="Track2" xml:space="preserve"><value>مسار 2</value></data>
<data name="Track3" xml:space="preserve"><value>مسار 3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>قيمة المنزلق (متوافق مع AviUtl: track0-3)</value></data>
<data name="Check0" xml:space="preserve"><value>خانة 0</value></data>
<data name="Check1" xml:space="preserve"><value>خانة 1</value></data>
<data name="Check2" xml:space="preserve"><value>خانة 2</value></data>
<data name="Check3" xml:space="preserve"><value>خانة 3</value></data>
<data name="CheckDesc" xml:space="preserve"><value>قيمة خانة الاختيار (متوافق مع AviUtl: check0-3)</value></data>
<data name="Color" xml:space="preserve"><value>اللون</value></data>
<data name="ColorDesc" xml:space="preserve"><value>اللون (متوافق مع AviUtl: --color)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>استيراد</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>تصدير</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>مسح</value></data>
+7
ファイルの表示
@@ -9,6 +9,13 @@ Track1,,トラック1,Track 1,轨道1,軌道1,트랙1,Pista 1,مسار 1,Jalur 1
Track2,,トラック2,Track 2,轨道2,軌道2,트랙2,Pista 2,مسار 2,Jalur 2
Track3,,トラック3,Track 3,轨道3,軌道3,트랙3,Pista 3,مسار 3,Jalur 3
TrackDesc,,スライダー値 (AviUtl準拠 track0〜3 に対応),Slider value (AviUtl compatible: track0–3),滑块值(AviUtl兼容: track0~3),滑塊值(AviUtl兼容: track0~3),슬라이더 값 (AviUtl 호환: track0~3),Valor del deslizador (compatible AviUtl: track0-3),قيمة المنزلق (متوافق مع AviUtl: track0-3),Nilai slider (kompatibel AviUtl: track0-3)
Check0,,チェック0,Check 0,复选框0,核取方塊0,체크0,Casilla 0,خانة 0,Centang 0
Check1,,チェック1,Check 1,复选框1,核取方塊1,체크1,Casilla 1,خانة 1,Centang 1
Check2,,チェック2,Check 2,复选框2,核取方塊2,체크2,Casilla 2,خانة 2,Centang 2
Check3,,チェック3,Check 3,复选框3,核取方塊3,체크3,Casilla 3,خانة 3,Centang 3
CheckDesc,,チェックボックス値 (AviUtl準拠 check0〜3 に対応),Checkbox value (AviUtl compatible: check0–3),复选框值(AviUtl兼容: check0~3),核取方塊值(AviUtl兼容: check0~3),체크박스 값 (AviUtl 호환: check0~3),Valor de casilla (compatible AviUtl: check0-3),قيمة خانة الاختيار (متوافق مع AviUtl: check0-3),Nilai kotak centang (kompatibel AviUtl: check0-3)
Color,,色,Color,颜色,顏色,색,Color,اللون,Warna
ColorDesc,,色 (AviUtl準拠 --color に対応),Color (AviUtl compatible: --color),颜色(AviUtl兼容: --color),顏色(AviUtl兼容: --color),색 (AviUtl 호환: --color),Color (compatible AviUtl: --color),اللون (متوافق مع AviUtl: --color),Warna (kompatibel AviUtl: --color)
ToolBarImport,,インポート,Import,导入,導入,가져오기,Importar,استيراد,Impor
ToolBarExport,,エクスポート,Export,导出,導出,내보내기,Exportar,تصدير,Ekspor
ToolBarClear,,クリア,Clear,清除,清除,지우기,Limpiar,مسح,Hapus
1 Key Parameter ja-jp en-us zh-cn zh-tw ko-kr es-es ar-sa id-id
9 Track2 トラック2 Track 2 轨道2 軌道2 트랙2 Pista 2 مسار 2 Jalur 2
10 Track3 トラック3 Track 3 轨道3 軌道3 트랙3 Pista 3 مسار 3 Jalur 3
11 TrackDesc スライダー値 (AviUtl準拠 track0〜3 に対応) Slider value (AviUtl compatible: track0–3) 滑块值(AviUtl兼容: track0~3) 滑塊值(AviUtl兼容: track0~3) 슬라이더 값 (AviUtl 호환: track0~3) Valor del deslizador (compatible AviUtl: track0-3) قيمة المنزلق (متوافق مع AviUtl: track0-3) Nilai slider (kompatibel AviUtl: track0-3)
12 Check0 チェック0 Check 0 复选框0 核取方塊0 체크0 Casilla 0 خانة 0 Centang 0
13 Check1 チェック1 Check 1 复选框1 核取方塊1 체크1 Casilla 1 خانة 1 Centang 1
14 Check2 チェック2 Check 2 复选框2 核取方塊2 체크2 Casilla 2 خانة 2 Centang 2
15 Check3 チェック3 Check 3 复选框3 核取方塊3 체크3 Casilla 3 خانة 3 Centang 3
16 CheckDesc チェックボックス値 (AviUtl準拠 check0〜3 に対応) Checkbox value (AviUtl compatible: check0–3) 复选框值(AviUtl兼容: check0~3) 核取方塊值(AviUtl兼容: check0~3) 체크박스 값 (AviUtl 호환: check0~3) Valor de casilla (compatible AviUtl: check0-3) قيمة خانة الاختيار (متوافق مع AviUtl: check0-3) Nilai kotak centang (kompatibel AviUtl: check0-3)
17 Color 色 Color 颜色 顏色 색 Color اللون Warna
18 ColorDesc 色 (AviUtl準拠 --color に対応) Color (AviUtl compatible: --color) 颜色(AviUtl兼容: --color) 顏色(AviUtl兼容: --color) 색 (AviUtl 호환: --color) Color (compatible AviUtl: --color) اللون (متوافق مع AviUtl: --color) Warna (kompatibel AviUtl: --color)
19 ToolBarImport インポート Import 导入 導入 가져오기 Importar استيراد Impor
20 ToolBarExport エクスポート Export 导出 導出 내보내기 Exportar تصدير Ekspor
21 ToolBarClear クリア Clear 清除 清除 지우기 Limpiar مسح Hapus
+7
ファイルの表示
@@ -69,6 +69,13 @@
<data name="Track2" xml:space="preserve"><value>Track 2</value></data>
<data name="Track3" xml:space="preserve"><value>Track 3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>Slider value (AviUtl compatible: track0–3)</value></data>
<data name="Check0" xml:space="preserve"><value>Check 0</value></data>
<data name="Check1" xml:space="preserve"><value>Check 1</value></data>
<data name="Check2" xml:space="preserve"><value>Check 2</value></data>
<data name="Check3" xml:space="preserve"><value>Check 3</value></data>
<data name="CheckDesc" xml:space="preserve"><value>Checkbox value (AviUtl compatible: check0–3)</value></data>
<data name="Color" xml:space="preserve"><value>Color</value></data>
<data name="ColorDesc" xml:space="preserve"><value>Color (AviUtl compatible: --color)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>Import</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>Export</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>Clear</value></data>
+7
ファイルの表示
@@ -69,6 +69,13 @@
<data name="Track2" xml:space="preserve"><value>Pista 2</value></data>
<data name="Track3" xml:space="preserve"><value>Pista 3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>Valor del deslizador (compatible AviUtl: track0-3)</value></data>
<data name="Check0" xml:space="preserve"><value>Casilla 0</value></data>
<data name="Check1" xml:space="preserve"><value>Casilla 1</value></data>
<data name="Check2" xml:space="preserve"><value>Casilla 2</value></data>
<data name="Check3" xml:space="preserve"><value>Casilla 3</value></data>
<data name="CheckDesc" xml:space="preserve"><value>Valor de casilla (compatible AviUtl: check0-3)</value></data>
<data name="Color" xml:space="preserve"><value>Color</value></data>
<data name="ColorDesc" xml:space="preserve"><value>Color (compatible AviUtl: --color)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>Importar</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>Exportar</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>Limpiar</value></data>
+7
ファイルの表示
@@ -69,6 +69,13 @@
<data name="Track2" xml:space="preserve"><value>Jalur 2</value></data>
<data name="Track3" xml:space="preserve"><value>Jalur 3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>Nilai slider (kompatibel AviUtl: track0-3)</value></data>
<data name="Check0" xml:space="preserve"><value>Centang 0</value></data>
<data name="Check1" xml:space="preserve"><value>Centang 1</value></data>
<data name="Check2" xml:space="preserve"><value>Centang 2</value></data>
<data name="Check3" xml:space="preserve"><value>Centang 3</value></data>
<data name="CheckDesc" xml:space="preserve"><value>Nilai kotak centang (kompatibel AviUtl: check0-3)</value></data>
<data name="Color" xml:space="preserve"><value>Warna</value></data>
<data name="ColorDesc" xml:space="preserve"><value>Warna (kompatibel AviUtl: --color)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>Impor</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>Ekspor</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>Hapus</value></data>
+7
ファイルの表示
@@ -69,6 +69,13 @@
<data name="Track2" xml:space="preserve"><value>트랙2</value></data>
<data name="Track3" xml:space="preserve"><value>트랙3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>슬라이더 값 (AviUtl 호환: track0~3)</value></data>
<data name="Check0" xml:space="preserve"><value>체크0</value></data>
<data name="Check1" xml:space="preserve"><value>체크1</value></data>
<data name="Check2" xml:space="preserve"><value>체크2</value></data>
<data name="Check3" xml:space="preserve"><value>체크3</value></data>
<data name="CheckDesc" xml:space="preserve"><value>체크박스 값 (AviUtl 호환: check0~3)</value></data>
<data name="Color" xml:space="preserve"><value>색</value></data>
<data name="ColorDesc" xml:space="preserve"><value>색 (AviUtl 호환: --color)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>가져오기</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>내보내기</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>지우기</value></data>
+7
ファイルの表示
@@ -69,6 +69,13 @@
<data name="Track2" xml:space="preserve"><value>トラック2</value></data>
<data name="Track3" xml:space="preserve"><value>トラック3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>スライダー値 (AviUtl準拠 track0〜3 に対応)</value></data>
<data name="Check0" xml:space="preserve"><value>チェック0</value></data>
<data name="Check1" xml:space="preserve"><value>チェック1</value></data>
<data name="Check2" xml:space="preserve"><value>チェック2</value></data>
<data name="Check3" xml:space="preserve"><value>チェック3</value></data>
<data name="CheckDesc" xml:space="preserve"><value>チェックボックス値 (AviUtl準拠 check0〜3 に対応)</value></data>
<data name="Color" xml:space="preserve"><value>色</value></data>
<data name="ColorDesc" xml:space="preserve"><value>色 (AviUtl準拠 --color に対応)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>インポート</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>エクスポート</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>クリア</value></data>
+7
ファイルの表示
@@ -69,6 +69,13 @@
<data name="Track2" xml:space="preserve"><value>轨道2</value></data>
<data name="Track3" xml:space="preserve"><value>轨道3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>滑块值(AviUtl兼容: track0~3)</value></data>
<data name="Check0" xml:space="preserve"><value>复选框0</value></data>
<data name="Check1" xml:space="preserve"><value>复选框1</value></data>
<data name="Check2" xml:space="preserve"><value>复选框2</value></data>
<data name="Check3" xml:space="preserve"><value>复选框3</value></data>
<data name="CheckDesc" xml:space="preserve"><value>复选框值(AviUtl兼容: check0~3)</value></data>
<data name="Color" xml:space="preserve"><value>颜色</value></data>
<data name="ColorDesc" xml:space="preserve"><value>颜色(AviUtl兼容: --color)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>导入</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>导出</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>清除</value></data>
+7
ファイルの表示
@@ -69,6 +69,13 @@
<data name="Track2" xml:space="preserve"><value>軌道2</value></data>
<data name="Track3" xml:space="preserve"><value>軌道3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>滑塊值(AviUtl兼容: track0~3)</value></data>
<data name="Check0" xml:space="preserve"><value>核取方塊0</value></data>
<data name="Check1" xml:space="preserve"><value>核取方塊1</value></data>
<data name="Check2" xml:space="preserve"><value>核取方塊2</value></data>
<data name="Check3" xml:space="preserve"><value>核取方塊3</value></data>
<data name="CheckDesc" xml:space="preserve"><value>核取方塊值(AviUtl兼容: check0~3)</value></data>
<data name="Color" xml:space="preserve"><value>顏色</value></data>
<data name="ColorDesc" xml:space="preserve"><value>顏色(AviUtl兼容: --color)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>導入</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>導出</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>清除</value></data>
+297
ファイルの表示
@@ -0,0 +1,297 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Windows.Media;
using Vortice.Direct2D1;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Plugin;
using YukkuriMovieMaker.Plugin.Effects;
namespace LuaScript
{
internal sealed class VideoEffectChain : IDisposable
{
private sealed class Node
{
public required Type Type;
public required IVideoEffect Model;
public required IVideoEffectProcessor Processor;
public required int RequestIndex;
}
private static Dictionary<string, Type>? _registry;
private static readonly Dictionary<Type, Dictionary<string, PropertyInfo>> _propertyCache = [];
private readonly IGraphicsDevicesAndContext _devices;
private readonly List<Node> _nodes = [];
private string[] _signature = [];
public VideoEffectChain(IGraphicsDevicesAndContext devices)
{
_devices = devices;
}
public ID2D1Image Apply(ID2D1Image source, IReadOnlyList<AviUtlEffectRequest> requests, EffectDescription baseDesc, ref DrawDescription drawDescription)
{
try
{
SyncNodes(requests);
}
catch
{
return source;
}
var current = source;
var desc = drawDescription;
foreach (var node in _nodes)
{
try
{
ApplyParameters(node.Model, requests[node.RequestIndex].Arguments);
node.Processor.SetInput(current);
var effectDescription = new EffectDescription(baseDesc, desc, baseDesc.InputIndex, baseDesc.InputCount, baseDesc.GroupIndex, baseDesc.GroupCount);
desc = node.Processor.Update(effectDescription);
current = node.Processor.Output;
}
catch
{
}
}
drawDescription = desc;
return current;
}
private void SyncNodes(IReadOnlyList<AviUtlEffectRequest> requests)
{
if (SignatureMatches(requests))
return;
DisposeNodes();
_signature = new string[requests.Count];
for (int i = 0; i < requests.Count; i++)
_signature[i] = requests[i].Name;
for (int i = 0; i < requests.Count; i++)
{
var type = Resolve(requests[i].Name);
if (type is null)
continue;
IVideoEffect? model = null;
try
{
model = Activator.CreateInstance(type) as IVideoEffect;
}
catch
{
}
if (model is null)
continue;
IVideoEffectProcessor processor;
try
{
processor = model.CreateVideoEffect(_devices);
}
catch
{
continue;
}
_nodes.Add(new Node { Type = type, Model = model, Processor = processor, RequestIndex = i });
}
}
private bool SignatureMatches(IReadOnlyList<AviUtlEffectRequest> requests)
{
if (_signature.Length != requests.Count)
return false;
for (int i = 0; i < requests.Count; i++)
{
if (!string.Equals(_signature[i], requests[i].Name, StringComparison.Ordinal))
return false;
}
return true;
}
private static Type? Resolve(string name)
{
var registry = GetRegistry();
return registry.TryGetValue(Normalize(name), out var type) ? type : null;
}
private static Dictionary<string, Type> GetRegistry()
{
if (_registry is not null)
return _registry;
var map = new Dictionary<string, Type>(StringComparer.Ordinal);
try
{
foreach (var factory in EffectFactories.VideoEffectFactories)
{
try
{
Register(map, factory.Name, factory.EffectType);
foreach (var keyword in factory.Keywords)
Register(map, keyword, factory.EffectType);
}
catch
{
}
}
_registry = map;
}
catch
{
}
return map;
}
private static void Register(Dictionary<string, Type> map, string? key, Type type)
{
if (string.IsNullOrWhiteSpace(key))
return;
map.TryAdd(Normalize(key), type);
}
private static string Normalize(string value) => value.Trim().ToLowerInvariant();
private static void ApplyParameters(IVideoEffect model, IReadOnlyList<KeyValuePair<string, object>> arguments)
{
if (arguments.Count == 0)
return;
var properties = GetProperties(model.GetType());
foreach (var (key, value) in arguments)
{
if (!properties.TryGetValue(Normalize(key), out var property))
continue;
try
{
SetValue(model, property, value);
}
catch
{
}
}
}
private static Dictionary<string, PropertyInfo> GetProperties(Type type)
{
if (_propertyCache.TryGetValue(type, out var cached))
return cached;
var map = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (property.GetIndexParameters().Length != 0)
continue;
bool usable = property.PropertyType == typeof(Animation) || property.GetSetMethod() is not null;
if (!usable)
continue;
map.TryAdd(Normalize(property.Name), property);
try
{
var display = property.GetCustomAttribute<DisplayAttribute>()?.GetName();
if (!string.IsNullOrWhiteSpace(display))
map.TryAdd(Normalize(display), property);
}
catch
{
}
}
_propertyCache[type] = map;
return map;
}
private static void SetValue(IVideoEffect model, PropertyInfo property, object value)
{
var type = property.PropertyType;
if (type == typeof(Animation))
{
if (property.GetValue(model) is Animation animation)
animation.CopyFrom(new Animation(ToDouble(value)));
return;
}
if (type == typeof(bool))
{
property.SetValue(model, ToBool(value));
return;
}
if (type.IsEnum)
{
property.SetValue(model, ToEnum(type, value));
return;
}
if (type == typeof(Color))
{
property.SetValue(model, ToColor(value));
return;
}
if (type == typeof(double) || type == typeof(float) || type == typeof(int) || type == typeof(long) || type == typeof(short))
{
property.SetValue(model, Convert.ChangeType(ToDouble(value), type, CultureInfo.InvariantCulture));
return;
}
if (type == typeof(string))
property.SetValue(model, value?.ToString());
}
private static double ToDouble(object value) => value switch
{
double d => d,
bool b => b ? 1d : 0d,
string s => double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var r) ? r : 0d,
_ => 0d,
};
private static bool ToBool(object value) => value switch
{
bool b => b,
double d => d != 0d,
string s => s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1",
_ => false,
};
private static object ToEnum(Type type, object value)
{
if (value is string s && Enum.TryParse(type, s, true, out var parsed))
return parsed;
return Enum.ToObject(type, (int)ToDouble(value));
}
private static Color ToColor(object value)
{
int rgb = (int)ToDouble(value);
return Color.FromRgb((byte)((rgb >> 16) & 0xFF), (byte)((rgb >> 8) & 0xFF), (byte)(rgb & 0xFF));
}
private void DisposeNodes()
{
foreach (var node in _nodes)
{
try
{
node.Processor.ClearInput();
}
catch
{
}
node.Processor.Dispose();
}
_nodes.Clear();
}
public void Dispose() => DisposeNodes();
}
}
+151 -6
ファイルの表示
@@ -301,6 +301,104 @@
لكن في هذا المكوِّن الإضافي تنعكس التغييرات عبر setpixel/set تلقائياً،
لذا لا داعي لاستدعاء هذه الدالة.
○ obj.rand(st, ed [, seed [, frame]])
تُعيد قيمة عشوائية صحيحة حتمية ضمن النطاق st ~ ed.
* مع نفس seed و frame، تُعيد دائماً القيمة نفسها.
* عند حذف seed يُعتبر 0، وعند حذف frame يُستخدم الإطار الحالي (obj.frame).
* تُعيد القيمة نفسها على محرك MoonSharp وعلى زمن التشغيل LuaJIT.
إذا لزمت قيمة عشوائية عشرية مستقلة عن المحرك، فاستخدم anim.rand.
st : الحد الأدنى للنطاق (يُقتطع إلى عدد صحيح)
ed : الحد الأعلى للنطاق (يُقتطع إلى عدد صحيح)
seed : بذرة العشوائية (اختياري، الافتراضي 0)
frame : الإطار المستخدم للتغيير (اختياري، الافتراضي obj.frame)
النتيجة : عدد صحيح ضمن st ~ ed
مثال: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
○ obj.load(الهدف، ...)
يستبدل مخزن الكائن بمحتوى مُولَّد. تُدعم الأهداف "figure" و"text"
و"image" (ملف صورة) و"movie" (ملف فيديو). بعد التحميل تُحدَّث
obj.w / obj.h وغيرها إلى الحجم المُولَّد، ويمكن قراءتها بـ getpixel
مباشرة بعد التحميل. يعمل على محرك MoonSharp والمحرك السريع (LuaJIT).
obj.load("figure", name, color, size [, line [, aspect]])
يُولّد شكلاً ويستبدل المخزن (متوسَّطاً).
name : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
(وتُقبل الأسماء الإنجليزية circle, rect, triangle,
pentagon, hexagon, star).
color : لون التعبئة 0xRRGGBB.
size : الحجم الأساسي بالبكسل.
line : عرض الحد (اختياري). 0 يملأ الشكل.
aspect : التشويه -1.0 ~ 1.0 (اختياري).
مثال: obj.load("figure", "円", 0xff3366, 200)
obj.load("text", string)
يرسم النص بالخط والحجم واللون المحددة بـ obj.setfont ويستبدل
المخزن (يُرسم بـ DirectWrite).
مثال: obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
obj.load("image", path)
يحمّل ملف صورة ويستبدل المخزن.
※ للأمان يُتحقَّق من الترويسة الأولى، ولا تُحمَّل إلا الصور
الأصلية (PNG / JPEG / GIF / BMP / TIFF / WebP).
مثال: obj.load("image", "C:\\img\\logo.png")
obj.load("movie", path [, time])
يحمّل الإطار عند الزمن المحدد من ملف فيديو ويستبدل المخزن
(يُفكَّك بـ Media Foundation).
time : بالثواني. الافتراضي obj.time عند الحذف.
※ للأمان يُتحقَّق من الترويسة الأولى، ولا تُحمَّل إلا مقاطع
الفيديو الأصلية (MP4 / MOV / MKV / WebM / AVI / FLV / ASF).
مثال: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
○ obj.setfont(font [, size [, style [, color]]])
يحدد الخط المستخدم في obj.load("text").
style : أعلام بِتّية. 1=عريض، 2=مائل، 3=عريض+مائل.
color : 0xRRGGBB.
مثال: obj.setfont("Meiryo", 64, 1, 0xffffff)
○ obj.draw([ox, oy, oz [, zoom [, alpha [, aspect]]]])
يدمج صورة الكائن الحالية في مخزن التراكم ويرسمها.
استدعاؤها عدة مرات يرسم نسخاً متراكبة (صور لاحقة، جزيئات، إلخ).
ox, oy, oz : الإزاحة من المركز (افتراضي 0).
zoom : 1.0 هو الحجم الأصلي (افتراضي 1.0).
alpha : 0.0 ~ 1.0 (افتراضي 1.0).
aspect : -1.0 ~ 1.0 (افتراضي 0).
※ بعد الاستدعاء يُكبَت الرسم القياسي ويُخرَج الناتج المدموج.
○ obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
[, u0,v0, u1,v1, u2,v2, u3,v3 [, alpha]])
يطبّق صورة الكائن كنسيج على رباعي محدد بأربع رؤوس.
ترتيب الرؤوس: أعلى-يسار، أعلى-يمين، أسفل-يمين، أسفل-يسار.
عند حذف UV تُستخدم الصورة كاملة.
※ عند حذف UV وإعطاء المعامل الثالث عشر فقط، يُستخدم كقيمة ألفا
(12 إحداثياً + ألفا).
※ يُسقَط بتحويل أفيني (دقيق لمتوازي الأضلاع، تقريبي لغيره).
○ obj.copybuffer(الوجهة، المصدر)
ينسخ صورة بين المخازن، يُحدَّد بالحرف الأول.
"obj" : مخزن صورة الكائن
"tmp" : مخزن مؤقت
"cache:الاسم" : ذاكرة مخبّأة مُسمّاة (تُحفظ بين الإطارات)
مثال: obj.copybuffer("tmp", "obj") -- حفظ
obj.copybuffer("obj", "tmp") -- استعادة
※ "frm" (مخزن الإطار / الخلفية) لا يمكن الحصول عليه بسبب بنية YMM4.
○ obj.getvalue(الهدف)
يحصل على القيمة الحالية لـ obj (مثل obj.x و obj.track0).
الهدف : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
"alpha","sx","sy","track0"~"track3","time","frame" إلخ.
المُرجَع : رقم (0 لهدف غير معروف).
○ obj.setoption(name, value) / obj.getoption(name)
يضبط / يحصل على خيار. الخيارات غير المدعومة تُقبَل كي لا توقف
النص (getoption يُرجع القيمة المحفوظة، و0 إن لم تُضبط).
الخيارات التي تؤثر على الرسم حالياً:
"antialias" : 0 = أقرب جار، وإلا استيفاء خطّي
(obj.draw / obj.drawpoly).
○ obj.pixeloption(name, value)
يحفظ خياراً لعمليات البكسل كحالة.
- ymm4 Table -
@@ -441,17 +539,64 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- التوافق الجزئي مع نصوص AviUtl -
تتيح طبقة توافق تشغيل الأجزاء الخاصة بالتحويل والشفافية والأرقام العشوائية من
نصوص تأثير الحركة في AviUtl (عائلة *.anm) دون إعادة كتابة. عندما لا يحتوي النص
على صياغة خاصة بـ AviUtl، لا تتدخل هذه الطبقة على الإطلاق (تبقى سلوكيات النصوص
الحالية كما هي تماماً).
○ توجيهات ترويسة النص
تُفسَّر إعلانات المعاملات المكتوبة على هيئة تعليقات، وتُعرَّف المتغيرات التي
يشير إليها جسم النص قبل التنفيذ.
--dialog:التسمية,local var=الافتراضي;...
يوسّع جزء الإعلان لكل عنصر (مثل local var=الافتراضي) إلى بداية الجسم.
في AviUtl تُحرَّر هذه القيم في مربع حوار، وهنا تُستخدم القيم الافتراضية.
--color:0xRRGGBB
يُعرّف المتغير color باللون المحدد.
--check0:التسمية,الافتراضي
يُعرّف obj.check0 (من 0 إلى 3) بالقيمة الافتراضية.
--param:<عبارة Lua>
يوسّع عبارة Lua المكتوبة إلى بداية الجسم.
--track0: إلى --track3:
تُقرأ قيم أشرطة التتبع عبر obj.track0 إلى obj.track3 كما في السابق.
لا تنعكس التسمية والنطاق والقيمة الافتراضية في الترويسة على الواجهة.
○ أقسام متعددة باستخدام @
عندما يُعرّف نص واحد عدة تأثيرات باستخدام @الاسم، يُنفَّذ القسم الأول فقط.
○ obj.rand(st, ed [, seed [, frame]])
دالة أرقام عشوائية صحيحة حتمية متوافقة مع AviUtl. انظر "جدول obj - الدوال"
للتفاصيل.
○ الرسم والتركيب والتحميل
يُدعم الرسم والتركيب عبر obj.draw / obj.drawpoly، وعمليات المخزن
عبر obj.copybuffer، والتوليد والتحميل عبر
obj.load("figure"/"text"/"image"/"movie")، و obj.setfont، و obj.effect،
و obj.getvalue، و obj.setoption / obj.getoption / obj.pixeloption.
انظر "جدول obj - الدوال" للتفاصيل.
الميزات التالية خارج نطاق هذه الطبقة.
النصوص التي تستدعيها لن تعمل كما هو متوقع.
× تحميل الوحدات عبر require، والوصول العشوائي إلى الملفات مثل
io / dofile (تحميل الصور / الفيديو عبر obj.load مدعوم مع التحقق
من الترويسة).
× obj.setanchor، scene.set / scene.get وما شابه.
- الميزات غير المدعومة / القيود -
× obj.effect()، obj.draw()، obj.drawpoly()، obj.load() وما شابه من AviUtl2 غير مدعومة.
× obj.rand()، obj.rand1()، obj.setfont()، obj.mes() وما شابه من AviUtl2 غير مدعومة.
× obj.setoption()، obj.getoption()، obj.getvalue()، obj.setanchor() وما شابه من AviUtl2 غير مدعومة.
× obj.rand1()، obj.mes()، obj.setanchor() وما شابه من AviUtl2 غير مدعومة.
× الدوال مثل scene.set() و scene.get() في جدول scene الخاص بـ AviUtl2 غير مدعومة.
(يمكن قراءة scene.width و scene.height فقط)
× الوصول إلى الملفات (require, dofile, io وما شابه) غير مدعوم.
× الوصول العشوائي إلى الملفات من النصوص (require, dofile, io وما شابه) غير مدعوم.
فقط obj.load("image"/"movie") يحمّل الملفات المؤكَّد أنها وسائط أصلية عبر
التحقق من الترويسة الأولى.
× تعديل obj.z ينعكس في الرسم (مضمَّن في ReadBack)،
لكن دعم الرسم ثلاثي الأبعاد محدود.
× إذا تجاوز النص البرمجي مهلة الانتهاء (5 ثوانٍ)، يُنهى التنفيذ قسراً.
يجب الانتباه في التطبيق لتجنب الحلقات اللانهائية.
× توجيهات الترويسة من AviUtl2 مثل --track@ و --check@ غير مدعومة.
يمكن استخدام Track0 ~ Track3 فقط كمعاملات.
× توجيهات الترويسة من AviUtl2 مدعومة جزئياً فقط. تُفسَّر القيم الافتراضية لـ
--dialog / --color / --check / --param (انظر "التوافق الجزئي مع نصوص AviUtl")،
لكن التسمية والنطاق والقيمة الافتراضية لـ --track@ لا تنعكس على الواجهة،
وتُستخدم القيم عبر Track0 ~ Track3.
+161 -6
ファイルの表示
@@ -307,6 +307,110 @@
but in this plugin changes via setpixel/set are automatically applied,
so calling this function is unnecessary.
o obj.rand(st, ed [, seed [, frame]])
Returns a deterministic integer random value within the range st ~ ed.
* With the same seed and frame, it always returns the same value.
* When seed is omitted it is treated as 0; when frame is omitted the
current frame (obj.frame) is used.
* Returns the same value on both the MoonSharp engine and the LuaJIT
runtime. For an engine-independent floating-point random value, use anim.rand.
st : Lower bound of the range (truncated to an integer)
ed : Upper bound of the range (truncated to an integer)
seed : Random seed (optional, default 0)
frame : Frame used for variation (optional, default obj.frame)
Returns : An integer within st ~ ed
Example: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
o obj.load(target, ...)
Replaces the object buffer with generated content. The targets
"figure", "text", "image" (image file) and "movie" (video file)
are supported. After loading, obj.w / obj.h, etc. are updated to the
generated size and can be read by getpixel right after the load.
Works on both the MoonSharp and the fast (LuaJIT) engine.
obj.load("figure", name, color, size [, line [, aspect]])
Generates a shape and replaces the buffer (centered).
name : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
(English aliases circle, rect, triangle, pentagon,
hexagon, star are also accepted).
color : Fill color 0xRRGGBB.
size : Bounding size in pixels.
line : Outline width (optional). 0 fills the shape.
aspect : Distortion -1.0 ~ 1.0 (optional).
Example: obj.load("figure", "円", 0xff3366, 200)
obj.load("text", string)
Draws the string with the font, size and color set by
obj.setfont and replaces the buffer (rendered with DirectWrite).
Example: obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
obj.load("image", path)
Loads an image file and replaces the buffer.
* For safety the leading header is validated and only genuine
images (PNG / JPEG / GIF / BMP / TIFF / WebP) are loaded.
Example: obj.load("image", "C:\\img\\logo.png")
obj.load("movie", path [, time])
Loads the frame at the given time of a video file and replaces
the buffer (decoded with Media Foundation).
time : Seconds. Defaults to obj.time when omitted.
* For safety the leading header is validated and only genuine
videos (MP4 / MOV / MKV / WebM / AVI / FLV / ASF) are loaded.
Example: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
o obj.setfont(font [, size [, style [, color]]])
Sets the font used by obj.load("text").
style : Bit flags. 1=bold, 2=italic, 3=bold+italic.
color : 0xRRGGBB.
Example: obj.setfont("Meiryo", 64, 1, 0xffffff)
o obj.draw([ox, oy, oz [, zoom [, alpha [, aspect]]]])
Composites the current object image onto the accumulation buffer.
Calling it multiple times draws overlapping copies (afterimages,
particles, etc.).
ox, oy, oz : Offset from the center (default 0).
zoom : 1.0 is original size (default 1.0).
alpha : 0.0 ~ 1.0 (default 1.0).
aspect : -1.0 ~ 1.0 (default 0).
* Once called, the standard draw is suppressed and the composited
result is output.
o obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
[, u0,v0, u1,v1, u2,v2, u3,v3 [, alpha]])
Texture-maps the object image onto a quad given by 4 vertices.
Vertex order is top-left, top-right, bottom-right, bottom-left.
When UVs are omitted the whole image is used.
* If only a 13th argument is given (UVs omitted), it is used as the
alpha (12 coordinates + alpha).
* Mapped with an affine transform (exact for parallelograms,
approximate for non-parallelograms).
o obj.copybuffer(destination, source)
Copies an image between buffers, selected by the first character.
"obj" : Object image buffer
"tmp" : Temporary buffer
"cache:name" : Named cache (kept across frames)
Example: obj.copybuffer("tmp", "obj") -- save
obj.copybuffer("obj", "tmp") -- restore
* "frm" (frame buffer / background) cannot be obtained due to the
structure of YMM4.
o obj.getvalue(target)
Gets the current value of obj (same as obj.x, obj.track0, etc.).
target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
"alpha","sx","sy","track0"~"track3","time","frame", etc.
Returns: a number (0 for an unknown target).
o obj.setoption(name, value) / obj.getoption(name)
Sets / gets an option. Unsupported options are accepted so they do
not stop the script (getoption returns the stored value, 0 if unset).
Options that currently affect drawing:
"antialias" : 0 = nearest neighbor, otherwise linear interpolation
(obj.draw / obj.drawpoly).
o obj.pixeloption(name, value)
Stores an option for pixel operations as state.
- ymm4 Table -
@@ -447,17 +551,68 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- AviUtl Script Compatibility (Partial) -
A compatibility layer lets the transform, opacity and random portions of
AviUtl animation effect scripts (the *.anm family) run without rewriting.
When a script contains no AviUtl-specific notation, this layer does not
intervene at all, and existing scripts behave exactly as before.
o Script header directives
Parameter declarations written as comments are interpreted, and the
variables that the script body references are defined before execution.
--dialog:label,local var=default;...
Expands the declaration part of each item
(such as local var=default) to the top of the body.
In AviUtl these are edited in a dialog; here the default
values are used.
--color:0xRRGGBB
Defines the variable color with the specified color.
--check0:label,default
Defines obj.check0 (0 to 3) with the default value.
--param:<Lua statement>
Expands the written Lua statement to the top of the body.
--track0: to --track3:
Trackbar values are referenced via obj.track0 to obj.track3
as before. The label, range and default written in the header
are not reflected in the UI.
o Multiple sections with @
When a single script defines multiple effects with @name, only the
first section is executed.
o obj.rand(st, ed [, seed [, frame]])
A deterministic integer random function compatible with AviUtl.
See "obj Table - Functions" for details.
o Drawing, compositing and loading
Drawing and compositing with obj.draw / obj.drawpoly, buffer
operations with obj.copybuffer, generation and loading with
obj.load("figure"/"text"/"image"/"movie"), obj.setfont, obj.effect,
obj.getvalue, and obj.setoption / obj.getoption / obj.pixeloption are
supported. See "obj Table - Functions" for details.
The following are out of scope for this layer. Scripts that call them will not
behave as intended.
x Module loading via require, and arbitrary file access such as io /
dofile (image / video loading via obj.load is supported with header
validation).
x obj.setanchor, scene.set / scene.get, etc.
- Unsupported Features / Limitations -
x obj.effect(), obj.draw(), obj.drawpoly(), obj.load(), etc. from AviUtl2 are not supported.
x obj.rand(), obj.rand1(), obj.setfont(), obj.mes(), etc. from AviUtl2 are not supported.
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), etc. from AviUtl2 are not supported.
x obj.rand1(), obj.mes(), obj.setanchor(), etc. from AviUtl2 are not supported.
x Functions such as scene.set() and scene.get() in the AviUtl2 scene table are not supported.
(Only scene.width and scene.height can be read)
x File access (require, dofile, io, etc.) is not supported.
x Arbitrary file access from scripts (require, dofile, io, etc.) is not supported.
Only obj.load("image"/"movie") loads files confirmed to be genuine media by
leading-header validation.
x Modifying obj.z is reflected in rendering (included in ReadBack),
but 3D rendering support is limited.
x If the script timeout (5 seconds) is exceeded, execution is forcibly terminated.
Care must be taken in implementation to prevent infinite loops.
x AviUtl2 header directives such as --track@ and --check@ are not supported.
Only Track0 ~ Track3 can be used as parameters.
x AviUtl2 header directives are only partially supported. The default values of
--dialog / --color / --check / --param are interpreted (see "AviUtl Script
Compatibility (Partial)"), but the label, range and default of --track@ are
not reflected in the UI; values are used via Track0 ~ Track3.
+164 -6
ファイルの表示
@@ -305,6 +305,111 @@
pero en este plugin los cambios mediante setpixel/set se aplican automáticamente,
por lo que no es necesario llamar a esta función.
o obj.rand(st, ed [, seed [, frame]])
Devuelve un valor aleatorio entero determinista dentro del rango st ~ ed.
* Con el mismo seed y frame, siempre devuelve el mismo valor.
* Si se omite seed se trata como 0; si se omite frame se usa el
fotograma actual (obj.frame).
* Devuelve el mismo valor en el motor MoonSharp y en el runtime LuaJIT.
Para un valor aleatorio decimal independiente del motor, use anim.rand.
st : Límite inferior del rango (truncado a entero)
ed : Límite superior del rango (truncado a entero)
seed : Semilla aleatoria (opcional, predeterminado 0)
frame : Fotograma usado para la variación (opcional, predeterminado obj.frame)
Devuelve: Un entero dentro de st ~ ed
Ejemplo: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
o obj.load(target, ...)
Reemplaza el búfer del objeto con contenido generado. Se admiten los
targets "figure", "text", "image" (archivo de imagen) y "movie"
(archivo de vídeo). Tras la carga, obj.w / obj.h, etc. se actualizan al
tamaño generado y pueden leerse con getpixel justo después de la carga.
Funciona en el motor MoonSharp y en el motor rápido (LuaJIT).
obj.load("figure", name, color, size [, line [, aspect]])
Genera una forma y reemplaza el búfer (centrada).
name : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
(también los alias en inglés circle, rect, triangle,
pentagon, hexagon, star).
color : Color de relleno 0xRRGGBB.
size : Tamaño base en píxeles.
line : Grosor del contorno (opcional). 0 rellena la forma.
aspect : Distorsión -1.0 ~ 1.0 (opcional).
Ejemplo: obj.load("figure", "円", 0xff3366, 200)
obj.load("text", cadena)
Dibuja la cadena con la fuente, el tamaño y el color definidos
por obj.setfont y reemplaza el búfer (con DirectWrite).
Ejemplo: obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
obj.load("image", ruta)
Carga un archivo de imagen y reemplaza el búfer.
* Por seguridad se valida la cabecera inicial y solo se cargan
imágenes genuinas (PNG / JPEG / GIF / BMP / TIFF / WebP).
Ejemplo: obj.load("image", "C:\\img\\logo.png")
obj.load("movie", ruta [, tiempo])
Carga el fotograma en el tiempo indicado de un archivo de vídeo
y reemplaza el búfer (decodificado con Media Foundation).
tiempo : Segundos. Por defecto obj.time si se omite.
* Por seguridad se valida la cabecera inicial y solo se cargan
vídeos genuinos (MP4 / MOV / MKV / WebM / AVI / FLV / ASF).
Ejemplo: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
o obj.setfont(fuente [, tamaño [, estilo [, color]]])
Establece la fuente usada por obj.load("text").
estilo : Bits. 1=negrita, 2=cursiva, 3=negrita+cursiva.
color : 0xRRGGBB.
Ejemplo: obj.setfont("Meiryo", 64, 1, 0xffffff)
o obj.draw([ox, oy, oz [, zoom [, alpha [, aspect]]]])
Compone la imagen actual del objeto en el búfer de acumulación.
Llamarla varias veces dibuja copias superpuestas (estelas,
partículas, etc.).
ox, oy, oz : Desplazamiento desde el centro (por defecto 0).
zoom : 1.0 es tamaño original (por defecto 1.0).
alpha : 0.0 ~ 1.0 (por defecto 1.0).
aspect : -1.0 ~ 1.0 (por defecto 0).
* Una vez llamada, se suprime el dibujo estándar y se emite el
resultado compuesto.
o obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
[, u0,v0, u1,v1, u2,v2, u3,v3 [, alpha]])
Aplica la imagen del objeto como textura sobre un cuadrilátero dado por
4 vértices. El orden es superior-izq, superior-der, inferior-der,
inferior-izq. Si se omiten las UV se usa toda la imagen.
* Si solo se da un 13.º argumento (UV omitidas), se usa como alpha
(12 coordenadas + alpha).
* Se mapea con una transformación afín (exacta para paralelogramos,
aproximada para no paralelogramos).
o obj.copybuffer(destino, origen)
Copia una imagen entre búferes, seleccionado por el primer carácter.
"obj" : Búfer de imagen del objeto
"tmp" : Búfer temporal
"cache:nombre" : Caché con nombre (se conserva entre fotogramas)
Ejemplo: obj.copybuffer("tmp", "obj") -- guardar
obj.copybuffer("obj", "tmp") -- restaurar
* "frm" (búfer de fotograma / fondo) no puede obtenerse por la
estructura de YMM4.
o obj.getvalue(target)
Obtiene el valor actual de obj (igual que obj.x, obj.track0, etc.).
target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
"alpha","sx","sy","track0"~"track3","time","frame", etc.
Devuelve: un número (0 para un target desconocido).
o obj.setoption(nombre, valor) / obj.getoption(nombre)
Establece / obtiene una opción. Las opciones no admitidas se aceptan
para no detener el script (getoption devuelve el valor guardado, 0 si
no está establecido).
Opciones que afectan al dibujo actualmente:
"antialias" : 0 = vecino más cercano, en otro caso interpolación
lineal (obj.draw / obj.drawpoly).
o obj.pixeloption(nombre, valor)
Guarda como estado una opción para las operaciones de píxeles.
- ymm4 Table -
@@ -445,17 +550,70 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- Compatibilidad parcial con scripts de AviUtl -
Una capa de compatibilidad permite ejecutar, sin reescritura, las partes de
los scripts de efecto de animación de AviUtl (la familia *.anm) relativas a
transformación, opacidad y números aleatorios. Cuando un script no contiene
notación específica de AviUtl, esta capa no interviene en absoluto (los
scripts existentes se comportan exactamente igual que antes).
o Directivas de encabezado del script
Las declaraciones de parámetros escritas como comentarios se
interpretan, y las variables que el cuerpo del script referencia se
definen antes de la ejecución.
--dialog:etiqueta,local var=predeterminado;...
Expande la parte de declaración de cada elemento
(como local var=predeterminado) al inicio del cuerpo.
En AviUtl se editan en un cuadro de diálogo; aquí se usan
los valores predeterminados.
--color:0xRRGGBB
Define la variable color con el color especificado.
--check0:etiqueta,predeterminado
Define obj.check0 (0 a 3) con el valor predeterminado.
--param:<sentencia Lua>
Expande la sentencia Lua escrita al inicio del cuerpo.
--track0: a --track3:
Los valores de las barras de seguimiento se referencian
mediante obj.track0 a obj.track3 como antes. La etiqueta, el
rango y el valor predeterminado del encabezado no se reflejan en la UI.
o Múltiples secciones con @
Cuando un único script define varios efectos con @nombre, solo se
ejecuta la primera sección.
o obj.rand(st, ed [, seed [, frame]])
Función de número aleatorio entero determinista compatible con AviUtl.
Consulte "Tabla obj - Funciones" para más detalles.
o Dibujo, composición y carga
Se admiten el dibujo y composición con obj.draw / obj.drawpoly, las
operaciones de búfer con obj.copybuffer, la generación y carga con
obj.load("figure"/"text"/"image"/"movie"), obj.setfont, obj.effect,
obj.getvalue y obj.setoption / obj.getoption / obj.pixeloption.
Consulte "Tabla obj - Funciones" para más detalles.
Lo siguiente queda fuera del alcance de esta capa. Los scripts que lo llamen no
se comportarán como se espera.
x Carga de módulos mediante require y acceso arbitrario a archivos como
io / dofile (la carga de imagen / vídeo con obj.load sí se admite con
validación de cabecera).
x obj.setanchor, scene.set / scene.get, etc.
- Funciones no admitidas / Limitaciones -
x obj.effect(), obj.draw(), obj.drawpoly(), obj.load(), etc. de AviUtl2 no son compatibles.
x obj.rand(), obj.rand1(), obj.setfont(), obj.mes(), etc. de AviUtl2 no son compatibles.
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), etc. de AviUtl2 no son compatibles.
x obj.rand1(), obj.mes(), obj.setanchor(), etc. de AviUtl2 no son compatibles.
x Las funciones como scene.set() y scene.get() de la tabla scene de AviUtl2 no son compatibles.
(Solo se pueden leer scene.width y scene.height)
x El acceso a archivos (require, dofile, io, etc.) no es compatible.
x El acceso arbitrario a archivos desde scripts (require, dofile, io, etc.) no es compatible.
Solo obj.load("image"/"movie") carga archivos confirmados como medios genuinos
mediante validación de la cabecera inicial.
x Modificar obj.z se refleja en el renderizado (incluido en ReadBack),
pero el soporte de renderizado 3D es limitado.
x Si se supera el tiempo de espera del script (5 segundos), la ejecución se termina forzosamente.
Se debe tener cuidado en la implementación para evitar bucles infinitos.
x Las directivas de encabezado de AviUtl2 como --track@ y --check@ no son compatibles.
Solo Track0 ~ Track3 pueden usarse como parámetros.
x Las directivas de encabezado de AviUtl2 solo son compatibles parcialmente. Los valores
predeterminados de --dialog / --color / --check / --param se interpretan (consulte
"Compatibilidad parcial con scripts de AviUtl"), pero la etiqueta, el rango y el valor
predeterminado de --track@ no se reflejan en la UI; los valores se usan vía Track0 ~ Track3.
+162 -6
ファイルの表示
@@ -303,6 +303,110 @@
tetapi dalam plugin ini perubahan melalui setpixel/set diterapkan secara otomatis,
sehingga tidak perlu memanggil fungsi ini.
o obj.rand(st, ed [, seed [, frame]])
Mengembalikan nilai acak bilangan bulat deterministik dalam rentang st ~ ed.
* Dengan seed dan frame yang sama, selalu mengembalikan nilai yang sama.
* Jika seed dihilangkan dianggap 0; jika frame dihilangkan digunakan
frame saat ini (obj.frame).
* Mengembalikan nilai yang sama pada mesin MoonSharp maupun runtime LuaJIT.
Untuk nilai acak desimal yang independen dari mesin, gunakan anim.rand.
st : Batas bawah rentang (dipotong menjadi bilangan bulat)
ed : Batas atas rentang (dipotong menjadi bilangan bulat)
seed : Seed acak (opsional, default 0)
frame : Frame yang digunakan untuk variasi (opsional, default obj.frame)
Hasil : Bilangan bulat dalam st ~ ed
Contoh: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
o obj.load(target, ...)
Mengganti buffer objek dengan konten yang dihasilkan. Target "figure",
"text", "image" (berkas gambar) dan "movie" (berkas video) didukung.
Setelah dimuat, obj.w / obj.h, dll. diperbarui ke ukuran yang
dihasilkan dan dapat dibaca oleh getpixel tepat setelah pemuatan.
Berfungsi pada mesin MoonSharp maupun mesin cepat (LuaJIT).
obj.load("figure", name, color, size [, line [, aspect]])
Menghasilkan bentuk dan mengganti buffer (dipusatkan).
name : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
(alias Inggris circle, rect, triangle, pentagon,
hexagon, star juga diterima).
color : Warna isi 0xRRGGBB.
size : Ukuran dasar dalam piksel.
line : Lebar garis tepi (opsional). 0 mengisi bentuk.
aspect : Distorsi -1.0 ~ 1.0 (opsional).
Contoh: obj.load("figure", "円", 0xff3366, 200)
obj.load("text", string)
Menggambar string dengan font, ukuran, dan warna yang diatur
oleh obj.setfont dan mengganti buffer (digambar dengan DirectWrite).
Contoh: obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
obj.load("image", path)
Memuat berkas gambar dan mengganti buffer.
* Demi keamanan, header awal divalidasi dan hanya gambar asli
(PNG / JPEG / GIF / BMP / TIFF / WebP) yang dimuat.
Contoh: obj.load("image", "C:\\img\\logo.png")
obj.load("movie", path [, time])
Memuat frame pada waktu tertentu dari berkas video dan mengganti
buffer (didekode dengan Media Foundation).
time : Detik. Default obj.time jika dihilangkan.
* Demi keamanan, header awal divalidasi dan hanya video asli
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF) yang dimuat.
Contoh: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
o obj.setfont(font [, size [, style [, color]]])
Mengatur font yang digunakan oleh obj.load("text").
style : Flag bit. 1=tebal, 2=miring, 3=tebal+miring.
color : 0xRRGGBB.
Contoh: obj.setfont("Meiryo", 64, 1, 0xffffff)
o obj.draw([ox, oy, oz [, zoom [, alpha [, aspect]]]])
Mengomposit gambar objek saat ini ke buffer akumulasi.
Memanggilnya beberapa kali menggambar salinan bertumpuk (afterimage,
partikel, dll.).
ox, oy, oz : Offset dari pusat (default 0).
zoom : 1.0 adalah ukuran asli (default 1.0).
alpha : 0.0 ~ 1.0 (default 1.0).
aspect : -1.0 ~ 1.0 (default 0).
* Setelah dipanggil, penggambaran standar ditekan dan hasil komposit
dikeluarkan.
o obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
[, u0,v0, u1,v1, u2,v2, u3,v3 [, alpha]])
Memetakan gambar objek sebagai tekstur ke quad dari 4 verteks.
Urutan verteks: kiri-atas, kanan-atas, kanan-bawah, kiri-bawah.
Jika UV dihilangkan, seluruh gambar digunakan.
* Jika hanya argumen ke-13 yang diberikan (UV dihilangkan), nilainya
dipakai sebagai alpha (12 koordinat + alpha).
* Dipetakan dengan transformasi afin (tepat untuk jajaran genjang,
perkiraan untuk non-jajaran genjang).
o obj.copybuffer(tujuan, sumber)
Menyalin gambar antar buffer, dipilih oleh karakter pertama.
"obj" : Buffer gambar objek
"tmp" : Buffer sementara
"cache:nama" : Cache bernama (dipertahankan antar frame)
Contoh: obj.copybuffer("tmp", "obj") -- simpan
obj.copybuffer("obj", "tmp") -- pulihkan
* "frm" (buffer frame / latar) tidak dapat diperoleh karena struktur YMM4.
o obj.getvalue(target)
Mengambil nilai saat ini dari obj (sama dengan obj.x, obj.track0, dll.).
target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
"alpha","sx","sy","track0"~"track3","time","frame", dll.
Mengembalikan: sebuah angka (0 untuk target yang tidak dikenal).
o obj.setoption(name, value) / obj.getoption(name)
Mengatur / mengambil opsi. Opsi yang tidak didukung tetap diterima
sehingga tidak menghentikan skrip (getoption mengembalikan nilai
tersimpan, 0 jika belum diatur).
Opsi yang saat ini memengaruhi penggambaran:
"antialias" : 0 = tetangga terdekat, selain itu interpolasi linear
(obj.draw / obj.drawpoly).
o obj.pixeloption(name, value)
Menyimpan opsi untuk operasi piksel sebagai status.
- ymm4 Table -
@@ -443,17 +547,69 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- Kompatibilitas Parsial Skrip AviUtl -
Lapisan kompatibilitas memungkinkan bagian transformasi, opasitas, dan
bilangan acak dari skrip efek animasi AviUtl (keluarga *.anm) dijalankan
tanpa penulisan ulang. Ketika sebuah skrip tidak mengandung notasi khusus
AviUtl, lapisan ini tidak ikut campur sama sekali (skrip yang ada berperilaku
persis seperti sebelumnya).
o Direktif header skrip
Deklarasi parameter yang ditulis sebagai komentar diinterpretasikan,
dan variabel yang dirujuk oleh badan skrip didefinisikan sebelum eksekusi.
--dialog:label,local var=default;...
Memperluas bagian deklarasi setiap item
(seperti local var=default) ke awal badan skrip.
Di AviUtl nilai ini diedit dalam dialog; di sini digunakan
nilai default.
--color:0xRRGGBB
Mendefinisikan variabel color dengan warna yang ditentukan.
--check0:label,default
Mendefinisikan obj.check0 (0 sampai 3) dengan nilai default.
--param:<pernyataan Lua>
Memperluas pernyataan Lua yang ditulis ke awal badan skrip.
--track0: sampai --track3:
Nilai trackbar dirujuk melalui obj.track0 sampai obj.track3
seperti sebelumnya. Label, rentang, dan default pada header
tidak tercermin di UI.
o Beberapa bagian dengan @
Ketika satu skrip mendefinisikan beberapa efek dengan @nama, hanya
bagian pertama yang dijalankan.
o obj.rand(st, ed [, seed [, frame]])
Fungsi bilangan acak bulat deterministik yang kompatibel dengan AviUtl.
Lihat "Tabel obj - Fungsi" untuk detailnya.
o Penggambaran, komposisi, dan pemuatan
Penggambaran dan komposisi dengan obj.draw / obj.drawpoly, operasi
buffer dengan obj.copybuffer, pembuatan dan pemuatan dengan
obj.load("figure"/"text"/"image"/"movie"), obj.setfont, obj.effect,
obj.getvalue, serta obj.setoption / obj.getoption / obj.pixeloption
didukung. Lihat "Tabel obj - Fungsi" untuk detailnya.
Berikut ini berada di luar cakupan lapisan ini. Skrip yang memanggilnya tidak
akan berperilaku seperti yang diharapkan.
x Pemuatan modul melalui require, dan akses berkas sembarang seperti
io / dofile (pemuatan gambar / video via obj.load didukung dengan
validasi header).
x obj.setanchor, scene.set / scene.get, dll.
- Fitur yang Tidak Didukung / Batasan -
x obj.effect(), obj.draw(), obj.drawpoly(), obj.load(), dll. dari AviUtl2 tidak didukung.
x obj.rand(), obj.rand1(), obj.setfont(), obj.mes(), dll. dari AviUtl2 tidak didukung.
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), dll. dari AviUtl2 tidak didukung.
x obj.rand1(), obj.mes(), obj.setanchor(), dll. dari AviUtl2 tidak didukung.
x Fungsi seperti scene.set() dan scene.get() dalam tabel scene AviUtl2 tidak didukung.
(Hanya scene.width dan scene.height yang dapat dibaca)
x Akses file (require, dofile, io, dll.) tidak didukung.
x Akses berkas sembarang dari skrip (require, dofile, io, dll.) tidak didukung.
Hanya obj.load("image"/"movie") yang memuat berkas yang dipastikan sebagai
media asli melalui validasi header awal.
x Memodifikasi obj.z tercermin dalam render (termasuk dalam ReadBack),
tetapi dukungan render 3D terbatas.
x Jika batas waktu skrip (5 detik) terlampaui, eksekusi dihentikan paksa.
Perhatian harus diberikan dalam implementasi untuk mencegah loop tak terbatas.
x Direktif header AviUtl2 seperti --track@ dan --check@ tidak didukung.
Hanya Track0 ~ Track3 yang dapat digunakan sebagai parameter.
x Direktif header AviUtl2 hanya didukung sebagian. Nilai default dari
--dialog / --color / --check / --param diinterpretasikan (lihat "Kompatibilitas
Parsial Skrip AviUtl"), tetapi label, rentang, dan default dari --track@ tidak
tercermin di UI; nilai digunakan melalui Track0 ~ Track3.
+152 -6
ファイルの表示
@@ -303,6 +303,104 @@
このプラグインでは setpixel/set による変更が自動的に反映されるため、
本関数を呼び出す必要はありません。
○obj.rand(st, ed [, seed [, frame]])
指定範囲 st ~ ed の整数を返す決定論的な乱数です。
※ seed と frame が同じであれば常に同じ値を返します。
※ seed 省略時は 0、frame 省略時は現在のフレーム(obj.frame)を使用します。
※ 従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)で同じ値を返します。
エンジンに依存しない小数の乱数が必要な場合は anim.rand を使用してください。
st : 範囲の下限 (小数は切り捨てて整数化)
ed : 範囲の上限 (小数は切り捨てて整数化)
seed : 乱数シード (省略可, デフォルト 0)
frame : 変化に用いるフレーム (省略可, デフォルト obj.frame)
戻り値 : st ~ ed の整数
例:obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
○obj.load(対象, ...)
オブジェクトのバッファを生成した内容に置き換えます。
対象は "figure"(図形) / "text"(テキスト) / "image"(画像ファイル) /
"movie"(動画ファイル) に対応します。生成後 obj.w / obj.h 等は生成
サイズへ更新され、load 直後の getpixel でも参照できます。
従来エンジン・高速エンジンの両方で動作します。
obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])
図形を生成してバッファを置き換えます(中心に配置)。
名前 : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
(英語名 circle, rect, triangle, pentagon,
hexagon, star も使用可)。
色 : 塗り色 0xRRGGBB。
サイズ : 図形の基準サイズ(ピクセル)。
ライン : 輪郭の太さ(省略可)。0 で塗りつぶし。
アスペクト: 歪曲 -1.0 ~ 1.0(省略可)。
例:obj.load("figure", "円", 0xff3366, 200)
obj.load("text", 文字列)
obj.setfont で指定したフォント・サイズ・色で文字列を
描画してバッファを置き換えます(DirectWrite で描画)。
例:obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
obj.load("image", パス)
画像ファイルを読み込んでバッファを置き換えます。
※ 安全のため先頭ヘッダーを検証し、真正な画像
(PNG / JPEG / GIF / BMP / TIFF / WebP)のみ読み込みます。
例:obj.load("image", "C:\\img\\logo.png")
obj.load("movie", パス [, 時間])
動画ファイルの指定時間のフレームを読み込んでバッファを
置き換えます(Media Foundation で復号)。
時間 : 秒。省略時は obj.time。
※ 安全のため先頭ヘッダーを検証し、真正な動画
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF)のみ
読み込みます。
例:obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
○obj.setfont(フォント名 [, サイズ [, スタイル [, 色]]])
obj.load("text") で使用するフォントを設定します。
スタイル : ビット和。1=太字, 2=斜体, 3=太字+斜体。
色 : 0xRRGGBB。
例:obj.setfont("Meiryo", 64, 1, 0xffffff)
○obj.draw([ox, oy, oz [, 拡大率 [, 不透明度 [, アスペクト]]]])
現在のオブジェクト画像を蓄積バッファへ合成して描画します。
複数回呼ぶと重ねて描画されます(残像・パーティクル等)。
ox, oy, oz : 中心からのオフセット(省略時 0)。
拡大率 : 1.0 で等倍(省略時 1.0)。
不透明度 : 0.0 ~ 1.0(省略時 1.0)。
アスペクト : -1.0 ~ 1.0(省略時 0)。
※ 呼び出すと標準描画は抑制され、合成結果が出力されます。
○obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
[, u0,v0, u1,v1, u2,v2, u3,v3 [, 不透明度]])
4 頂点で指定した四角形へオブジェクト画像をテクスチャ描画します。
頂点は左上→右上→右下→左下の順。UV 省略時は画像全体を使用します。
※ UV を省略し 13 番目の引数のみ与えた場合、その値を不透明度として
使用します(座標 12 個 + 不透明度)。
※ アフィン変換で写像します(平行四辺形は厳密、非平行四辺形は近似)。
○obj.copybuffer(コピー先, コピー元)
バッファ間で画像をコピーします。識別子の先頭文字で判定します。
"obj" : オブジェクト画像バッファ
"tmp" : 一時バッファ
"cache:名前" : 名前付きキャッシュ(フレーム間で保持)
例:obj.copybuffer("tmp", "obj") -- 退避
obj.copybuffer("obj", "tmp") -- 復元
※ "frm"(フレームバッファ/背景)はYMM4の構造上取得できません。
○obj.getvalue(対象)
obj の現在値を取得します(obj.x や obj.track0 等と同値)。
対象 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
"alpha","sx","sy","track0"~"track3","time","frame" 等。
戻り値 : 数値(未知の対象は 0)。
○obj.setoption(名前, 値) / obj.getoption(名前)
オプションを設定 / 取得します。未対応の項目も受理してスクリプトを
停止させません(getoption は設定値を返し、未設定は 0)。
現在描画へ反映される項目:
"antialias" : 0 で最近傍、それ以外で線形補間(obj.draw/drawpoly)。
○obj.pixeloption(名前, 値)
ピクセル操作のオプションを状態として保持します。
- ymm4 テーブル -
@@ -443,17 +541,65 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- AviUtl スクリプトの部分互換 -
AviUtl のアニメーション効果スクリプト(*.anm 系)のうち、座標・拡縮・回転・
不透明度の変形と乱数を用いる範囲を、追加の記述変更なしで実行できる互換層です。
スクリプトに AviUtl 固有の記法が含まれない場合、この互換層は一切介入しません
(従来のスクリプトの挙動は変わりません)。
○スクリプトヘッダの解釈
コメント形式のパラメータ宣言を解釈し、スクリプト本体が参照する変数を
実行前に定義します。
--dialog:項目名,local 変数=既定値;…
各項目の宣言部(local 変数=既定値 など)を本体の先頭へ展開します。
AviUtl では対話ダイアログで編集する値ですが、ここでは既定値で
動作します。
--color:0xRRGGBB
変数 color を指定色で定義します。
--check0:項目名,既定値
obj.check0 (0~3) を既定値で定義します。
--param:任意のLua文
記述した Lua 文をそのまま本体の先頭へ展開します。
--track0: ~ --track3:
トラックバーの値は従来どおり obj.track0 ~ obj.track3 から
参照します。ヘッダーのラベル・範囲・既定値は UI へ反映しません。
○@ による複数セクション
1 つのスクリプトに @名前 で複数の効果が定義されている場合、先頭の
セクションのみを実行します。
○obj.rand(st, ed [, seed [, frame]])
AviUtl 互換の決定論的な整数乱数です。詳細は「obj テーブル - 関数」を
参照してください。
○描画・合成・読み込み
obj.draw / obj.drawpoly による描画合成、obj.copybuffer による
バッファ操作、obj.load("figure"/"text"/"image"/"movie") による生成・
読み込み、obj.setfont、obj.effect、obj.getvalue、obj.setoption /
obj.getoption / obj.pixeloption に対応します。詳細は「obj テーブル -
関数」を参照してください。
次の機能はこの互換層では対象外です。
これらを呼び出すスクリプトは意図どおりには動作しません。
×require によるモジュール読み込み、io / dofile などの任意ファイル
アクセス(obj.load の画像 / 動画はヘッダー検証付きで対応)。
×obj.setanchor、scene.set / scene.get 等。
- 非対応・制限事項 -
×AviUtl2 の obj.effect(), obj.draw(), obj.drawpoly(), obj.load() 等には対応していません。
×AviUtl2 の obj.rand(), obj.rand1(), obj.setfont(), obj.mes() 等には対応していません。
×AviUtl2 の obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor() 等には対応していません。
×AviUtl2 の obj.rand1(), obj.mes(), obj.setanchor() 等には対応していません。
×AviUtl2 の scene テーブルの scene.set(), scene.get() 等の関数には対応していません。
(scene.width と scene.height の読み取りのみ対応)
×ファイルアクセス(require, dofile, io 等)には対応していません。
×スクリプトからの任意ファイルアクセス(require, dofile, io 等)には対応して
いません。obj.load("image"/"movie") のみ、先頭ヘッダー検証で真正なメディアと
確認できたファイルを読み込みます。
×obj.z を変更した場合、描画には反映されます(ReadBack に含まれる)が、
3D 描画のサポートは限定的です。
×スクリプトのタイムアウト(5秒)を超えた場合、実行は強制終了されます。
無限ループが発生しないよう実装上の注意が必要です。
×AviUtl2 の --track@, --check@ 等のヘッダーディレクティブには対応していません。
パラメータは Track0 ~ Track3 のみ使用できます。
×AviUtl2 のヘッダーディレクティブは部分的にのみ対応します。
--dialog / --color / --check / --param の既定値は解釈されますが
(「AviUtl スクリプトの部分互換」を参照)、--track@ のラベル・範囲・
既定値は UI へ反映されず、値は Track0 ~ Track3 を使用します。
+150 -6
ファイルの表示
@@ -299,6 +299,103 @@
이 플러그인에서는 setpixel/set에 의한 변경이 자동으로 반영되므로,
이 함수를 호출할 필요가 없습니다.
○ obj.rand(st, ed [, seed [, frame]])
지정 범위 st ~ ed의 정수를 반환하는 결정론적 난수입니다.
※ seed와 frame이 같으면 항상 같은 값을 반환합니다.
※ seed 생략 시 0으로, frame 생략 시 현재 프레임(obj.frame)을 사용합니다.
※ 기존 엔진(MoonSharp)과 고속 런타임(LuaJIT)에서 같은 값을 반환합니다.
엔진에 의존하지 않는 소수 난수가 필요하면 anim.rand를 사용하세요.
st : 범위 하한 (소수는 버림하여 정수화)
ed : 범위 상한 (소수는 버림하여 정수화)
seed : 난수 시드 (생략 가능, 기본값 0)
frame : 변화에 사용하는 프레임 (생략 가능, 기본값 obj.frame)
반환값 : st ~ ed의 정수
예: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
○ obj.load(대상, ...)
오브젝트 버퍼를 생성한 내용으로 교체합니다. "figure"(도형) /
"text"(텍스트) / "image"(이미지 파일) / "movie"(동영상 파일)를
지원합니다. 로드 후 obj.w / obj.h 등은 생성 크기로 갱신되며, 로드
직후의 getpixel로도 참조할 수 있습니다. 기존 엔진과 고속 엔진
양쪽에서 동작합니다.
obj.load("figure", 이름, 색, 크기 [, 라인 [, 종횡비]])
도형을 생성하여 버퍼를 교체합니다(중심 배치).
이름 : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
(영어 circle, rect, triangle, pentagon, hexagon,
star 도 사용 가능).
색 : 채움 색 0xRRGGBB.
크기 : 기준 크기(픽셀).
라인 : 외곽선 두께(생략 가능). 0이면 채움.
종횡비 : 왜곡 -1.0 ~ 1.0(생략 가능).
예: obj.load("figure", "円", 0xff3366, 200)
obj.load("text", 문자열)
obj.setfont로 지정한 글꼴・크기・색으로 문자열을 그려
버퍼를 교체합니다(DirectWrite로 그림).
예: obj.setfont("Yu Gothic UI", 48); obj.load("text", "자막")
obj.load("image", 경로)
이미지 파일을 읽어 버퍼를 교체합니다.
※ 안전을 위해 선두 헤더를 검증하여 진짜 이미지
(PNG / JPEG / GIF / BMP / TIFF / WebP)만 읽습니다.
예: obj.load("image", "C:\\img\\logo.png")
obj.load("movie", 경로 [, 시간])
동영상 파일의 지정 시간 프레임을 읽어 버퍼를 교체합니다
(Media Foundation으로 디코딩).
시간 : 초. 생략 시 obj.time.
※ 안전을 위해 선두 헤더를 검증하여 진짜 동영상
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF)만 읽습니다.
예: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
○ obj.setfont(글꼴 [, 크기 [, 스타일 [, 색]]])
obj.load("text")에서 사용할 글꼴을 설정합니다.
스타일 : 비트 플래그. 1=굵게, 2=기울임, 3=굵게+기울임.
색 : 0xRRGGBB.
예: obj.setfont("Meiryo", 64, 1, 0xffffff)
○ obj.draw([ox, oy, oz [, 확대율 [, 불투명도 [, 종횡비]]]])
현재 오브젝트 이미지를 누적 버퍼에 합성하여 그립니다.
여러 번 호출하면 겹쳐서 그려집니다(잔상・파티클 등).
ox, oy, oz : 중심으로부터의 오프셋(기본 0).
확대율 : 1.0이 등배(기본 1.0).
불투명도 : 0.0 ~ 1.0(기본 1.0).
종횡비 : -1.0 ~ 1.0(기본 0).
※ 호출하면 표준 그리기가 억제되고 합성 결과가 출력됩니다.
○ obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
[, u0,v0, u1,v1, u2,v2, u3,v3 [, 불투명도]])
4개 정점으로 지정한 사각형에 오브젝트 이미지를 텍스처로 그립니다.
정점 순서는 좌상→우상→우하→좌하. UV 생략 시 전체 이미지를 사용합니다.
※ UV를 생략하고 13번째 인수만 준 경우, 그 값을 불투명도로 사용합니다
(좌표 12개 + 불투명도).
※ 아핀 변환으로 매핑합니다(평행사변형은 정확, 비평행사변형은 근사).
○ obj.copybuffer(대상, 원본)
버퍼 간에 이미지를 복사합니다. 식별자의 첫 글자로 판정합니다.
"obj" : 오브젝트 이미지 버퍼
"tmp" : 임시 버퍼
"cache:이름" : 명명 캐시(프레임 간 유지)
예: obj.copybuffer("tmp", "obj") -- 저장
obj.copybuffer("obj", "tmp") -- 복원
※ "frm"(프레임 버퍼 / 배경)은 YMM4의 구조상 가져올 수 없습니다.
○ obj.getvalue(대상)
obj의 현재 값을 가져옵니다(obj.x, obj.track0 등과 동일).
대상 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
"alpha","sx","sy","track0"~"track3","time","frame" 등.
반환값 : 숫자(알 수 없는 대상은 0).
○ obj.setoption(이름, 값) / obj.getoption(이름)
옵션을 설정 / 가져옵니다. 지원하지 않는 항목도 받아들여
스크립트를 중단시키지 않습니다(getoption은 설정값을 반환, 미설정은 0).
현재 그리기에 반영되는 항목:
"antialias" : 0이면 최근접, 그 외는 선형 보간(obj.draw / obj.drawpoly).
○ obj.pixeloption(이름, 값)
픽셀 조작 옵션을 상태로 보존합니다.
- ymm4 테이블 -
@@ -439,17 +536,64 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- AviUtl 스크립트 부분 호환 -
AviUtl 애니메이션 효과 스크립트(*.anm 계열) 중 좌표·확대축소·회전·
불투명도의 변형과 난수를 사용하는 범위를, 추가 수정 없이 실행할 수 있는
호환 계층입니다. 스크립트에 AviUtl 고유 표기가 포함되지 않은 경우 이
호환 계층은 전혀 개입하지 않습니다(기존 스크립트의 동작은 변하지 않습니다).
○ 스크립트 헤더 디렉티브 해석
주석 형식의 파라미터 선언을 해석하여, 스크립트 본문이 참조하는
변수를 실행 전에 정의합니다.
--dialog:항목명,local 변수=기본값;…
각 항목의 선언부(local 변수=기본값 등)를 본문 앞에 펼칩니다.
AviUtl에서는 대화 상자에서 편집하는 값이지만, 여기서는
기본값으로 동작합니다.
--color:0xRRGGBB
변수 color를 지정한 색으로 정의합니다.
--check0:항목명,기본값
obj.check0 (0~3)을 기본값으로 정의합니다.
--param:임의의 Lua 문
작성한 Lua 문을 그대로 본문 앞에 펼칩니다.
--track0: ~ --track3:
트랙바 값은 기존과 같이 obj.track0 ~ obj.track3에서
참조합니다. 헤더의 라벨·범위·기본값은 UI에 반영되지 않습니다.
○ @를 통한 복수 섹션
하나의 스크립트에 @이름으로 여러 효과가 정의된 경우, 첫 번째
섹션만 실행합니다.
○ obj.rand(st, ed [, seed [, frame]])
AviUtl 호환의 결정론적 정수 난수입니다. 자세한 내용은
"obj 테이블 - 함수"를 참조하세요.
○ 그리기·합성·로드
obj.draw / obj.drawpoly에 의한 그리기 합성, obj.copybuffer에 의한
버퍼 조작, obj.load("figure"/"text"/"image"/"movie")에 의한 생성·로드,
obj.setfont, obj.effect, obj.getvalue, 그리고 obj.setoption /
obj.getoption / obj.pixeloption을 지원합니다. 자세한 내용은
"obj 테이블 - 함수"를 참조하세요.
다음 기능은 이 호환 계층의 범위 밖입니다.
이를 호출하는 스크립트는 의도대로 동작하지 않습니다.
× require에 의한 모듈 로드 및 io / dofile 등의 임의 파일 접근
(obj.load의 이미지 / 동영상 로드는 헤더 검증과 함께 지원).
× obj.setanchor, scene.set / scene.get 등.
- 미지원·제한 사항 -
× AviUtl2의 obj.effect(), obj.draw(), obj.drawpoly(), obj.load() 등은 지원하지 않습니다.
× AviUtl2의 obj.rand(), obj.rand1(), obj.setfont(), obj.mes() 등은 지원하지 않습니다.
× AviUtl2의 obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor() 등은 지원하지 않습니다.
× AviUtl2의 obj.rand1(), obj.mes(), obj.setanchor() 등은 지원하지 않습니다.
× AviUtl2의 scene 테이블의 scene.set(), scene.get() 등의 함수는 지원하지 않습니다.
(scene.width와 scene.height의 읽기만 지원)
× 파일 접근(require, dofile, io 등)은 지원하지 않습니다.
× 스크립트에서의 임의 파일 접근(require, dofile, io 등)은 지원하지 않습니다.
obj.load("image"/"movie")만 선두 헤더 검증으로 진짜 미디어로 확인된 파일을
읽습니다.
× obj.z를 변경하면 렌더링에 반영되지만(ReadBack에 포함),
3D 렌더링 지원은 제한적입니다.
× 스크립트 타임아웃(5초)을 초과하면 실행이 강제 종료됩니다.
무한 루프가 발생하지 않도록 구현 시 주의가 필요합니다.
× AviUtl2의 --track@, --check@ 등의 헤더 디렉티브는 지원하지 않습니다.
파라미터는 Track0 ~ Track3만 사용할 수 있습니다.
× AviUtl2의 헤더 디렉티브는 부분적으로만 지원합니다. --dialog / --color /
--check / --param의 기본값은 해석되지만("AviUtl 스크립트 부분 호환" 참조),
--track@의 라벨·범위·기본값은 UI에 반영되지 않으며 값은 Track0 ~ Track3을 사용합니다.
+140 -6
ファイルの表示
@@ -297,6 +297,100 @@
但本插件中 setpixel/set 的修改会自动反映,
因此无需调用此函数。
○ obj.rand(st, ed [, seed [, frame]])
返回指定范围 st ~ ed 内整数的确定性随机数。
* seed 与 frame 相同时始终返回相同的值。
* 省略 seed 时按 0 处理,省略 frame 时使用当前帧 (obj.frame)。
* 在传统引擎 (MoonSharp) 与高速运行时 (LuaJIT) 上返回相同的值。
若需要不依赖引擎的小数随机数,请使用 anim.rand。
st : 范围下限(小数向下取整为整数)
ed : 范围上限(小数向下取整为整数)
seed : 随机种子(可省略,默认 0)
frame : 用于变化的帧(可省略,默认 obj.frame)
返回值 : st ~ ed 的整数
示例:obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
○ obj.load(目标, ...)
将对象缓冲区替换为生成的内容。支持 "figure"(图形) / "text"(文本) /
"image"(图像文件) / "movie"(视频文件)。加载后 obj.w / obj.h 等会更新为
生成尺寸,紧接着的 getpixel 也可读取。传统引擎与高速引擎均可运行。
obj.load("figure", 名称, 颜色, 大小 [, 线宽 [, 纵横比]])
生成图形并替换缓冲区(居中)。
名称 : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
(也可用英文 circle, rect, triangle, pentagon,
hexagon, star)。
颜色 : 填充色 0xRRGGBB。
大小 : 基准大小(像素)。
线宽 : 轮廓宽度(可省略)。0 为填充。
纵横比 : 变形 -1.0 ~ 1.0(可省略)。
示例:obj.load("figure", "円", 0xff3366, 200)
obj.load("text", 字符串)
以 obj.setfont 指定的字体、大小、颜色绘制字符串并替换缓冲区
(使用 DirectWrite 绘制)。
示例:obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
obj.load("image", 路径)
加载图像文件并替换缓冲区。
※ 为安全起见会校验文件头,仅加载真正的图像
(PNG / JPEG / GIF / BMP / TIFF / WebP)。
示例:obj.load("image", "C:\\img\\logo.png")
obj.load("movie", 路径 [, 时间])
加载视频文件指定时间的帧并替换缓冲区
(使用 Media Foundation 解码)。
时间 : 秒。省略时为 obj.time。
※ 为安全起见会校验文件头,仅加载真正的视频
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF)。
示例:obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
○ obj.setfont(字体 [, 大小 [, 样式 [, 颜色]]])
设置 obj.load("text") 使用的字体。
样式 : 位标志。1=粗体, 2=斜体, 3=粗斜体。
颜色 : 0xRRGGBB。
示例:obj.setfont("Meiryo", 64, 1, 0xffffff)
○ obj.draw([ox, oy, oz [, 缩放 [, 不透明度 [, 纵横比]]]])
将当前对象图像合成到累积缓冲区并绘制。
多次调用会叠加绘制(残像、粒子等)。
ox, oy, oz : 相对中心的偏移(默认 0)。
缩放 : 1.0 为原始大小(默认 1.0)。
不透明度 : 0.0 ~ 1.0(默认 1.0)。
纵横比 : -1.0 ~ 1.0(默认 0)。
※ 调用后将抑制标准绘制,输出合成结果。
○ obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
[, u0,v0, u1,v1, u2,v2, u3,v3 [, 不透明度]])
将对象图像以纹理方式绘制到 4 个顶点指定的四边形。
顶点顺序为左上→右上→右下→左下。省略 UV 时使用整幅图像。
※ 省略 UV 而仅提供第 13 个参数时,将其用作不透明度(12 个坐标 + 不透明度)。
※ 使用仿射变换映射(平行四边形精确,非平行四边形为近似)。
○ obj.copybuffer(目标, 源)
在缓冲区之间复制图像。按标识符首字符判定。
"obj" : 对象图像缓冲区
"tmp" : 临时缓冲区
"cache:名称" : 命名缓存(跨帧保留)
示例:obj.copybuffer("tmp", "obj") -- 保存
obj.copybuffer("obj", "tmp") -- 恢复
※ 由于 YMM4 的结构,无法获取 "frm"(帧缓冲区 / 背景)。
○ obj.getvalue(目标)
获取 obj 的当前值(与 obj.x、obj.track0 等相同)。
目标 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
"alpha","sx","sy","track0"~"track3","time","frame" 等。
返回值 : 数值(未知目标返回 0)。
○ obj.setoption(名称, 值) / obj.getoption(名称)
设置 / 获取选项。未支持的项目也会被接受,不会中断脚本
(getoption 返回设置值,未设置为 0)。
当前会反映到绘制的项目:
"antialias" : 0 为最近邻,其它为线性插值(obj.draw / obj.drawpoly)。
○ obj.pixeloption(名称, 值)
将像素操作的选项作为状态保存。
- ymm4 表 -
@@ -437,17 +531,57 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- AviUtl 脚本的部分兼容 -
提供兼容层,使 AviUtl 动画效果脚本(*.anm 系列)中涉及坐标、缩放、旋转、
不透明度的变形以及随机数的部分,无需额外修改即可运行。当脚本中不包含
AviUtl 专有写法时,此兼容层完全不介入(传统脚本的行为不变)。
○ 脚本头部指令的解释
解释注释形式的参数声明,在执行前定义脚本主体所引用的变量。
--dialog:项目名,local 变量=默认值;…
将各项目的声明部分(如 local 变量=默认值)展开到主体开头。
在 AviUtl 中这些是通过对话框编辑的值,此处以默认值运行。
--color:0xRRGGBB
以指定颜色定义变量 color。
--check0:项目名,默认值
以默认值定义 obj.check0 (0~3)。
--param:任意 Lua 语句
将所写的 Lua 语句原样展开到主体开头。
--track0: ~ --track3:
轨道条的值仍通过 obj.track0 ~ obj.track3 引用。头部的标签、
范围与默认值不会反映到 UI。
○ 通过 @ 的多区段
当一个脚本以 @名称 定义了多个效果时,仅执行第一个区段。
○ obj.rand(st, ed [, seed [, frame]])
与 AviUtl 兼容的确定性整数随机数。详情请参阅“obj 表 - 函数”。
○ 绘制·合成·加载
支持 obj.draw / obj.drawpoly 的绘制合成、obj.copybuffer 的缓冲区操作、
obj.load("figure"/"text"/"image"/"movie") 的生成与加载、obj.setfont、
obj.effect、obj.getvalue 以及 obj.setoption / obj.getoption /
obj.pixeloption。详情请参阅“obj 表 - 函数”。
以下功能不在此兼容层的范围内。
调用它们的脚本不会按预期运行。
× 通过 require 加载模块,以及 io / dofile 等任意文件访问
(obj.load 的图像 / 视频加载已带文件头校验支持)。
× obj.setanchor、scene.set / scene.get 等。
- 不支持项目·限制事项 -
× 不支持 AviUtl2 的 obj.effect()、obj.draw()、obj.drawpoly()、obj.load() 等。
× 不支持 AviUtl2 的 obj.rand()、obj.rand1()、obj.setfont()、obj.mes() 等。
× 不支持 AviUtl2 的 obj.setoption()、obj.getoption()、obj.getvalue()、obj.setanchor() 等。
× 不支持 AviUtl2 的 obj.rand1()、obj.mes()、obj.setanchor() 等。
× 不支持 AviUtl2 scene 表中的 scene.set()、scene.get() 等函数。
(仅支持读取 scene.width 和 scene.height)
× 不支持文件访问(require、dofile、io 等)。
× 不支持脚本进行任意文件访问(require、dofile、io 等)。
仅 obj.load("image"/"movie") 会加载经文件头校验确认为真正媒体的文件。
× 修改 obj.z 会反映到绘制中(包含在 ReadBack 中),
但 3D 绘制支持有限。
× 超过脚本超时时间(5 秒)时,执行将被强制终止。
实现时需注意避免出现无限循环。
× 不支持 AviUtl2 的 --track@、--check@ 等头部指令。
参数仅可使用 Track0 ~ Track3。
× AviUtl2 的头部指令仅部分支持。--dialog / --color / --check / --param 的
默认值会被解释(参阅“AviUtl 脚本的部分兼容”),但 --track@ 的标签、范围
与默认值不会反映到 UI,值通过 Track0 ~ Track3 使用。
+140 -6
ファイルの表示
@@ -297,6 +297,100 @@
但本外掛中 setpixel/set 的修改會自動反映,
因此無需呼叫此函式。
○ obj.rand(st, ed [, seed [, frame]])
回傳指定範圍 st ~ ed 內整數的確定性亂數。
* seed 與 frame 相同時始終回傳相同的值。
* 省略 seed 時以 0 處理,省略 frame 時使用目前影格 (obj.frame)。
* 在傳統引擎 (MoonSharp) 與高速執行階段 (LuaJIT) 上回傳相同的值。
若需要不依賴引擎的小數亂數,請使用 anim.rand。
st : 範圍下限(小數無條件捨去為整數)
ed : 範圍上限(小數無條件捨去為整數)
seed : 亂數種子(可省略,預設 0)
frame : 用於變化的影格(可省略,預設 obj.frame)
回傳值 : st ~ ed 的整數
範例:obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
○ obj.load(目標, ...)
將物件緩衝區替換為產生的內容。支援 "figure"(圖形) / "text"(文字) /
"image"(影像檔) / "movie"(影片檔)。載入後 obj.w / obj.h 等會更新為產生
尺寸,緊接著的 getpixel 亦可讀取。傳統引擎與高速引擎皆可執行。
obj.load("figure", 名稱, 顏色, 大小 [, 線寬 [, 長寬比]])
產生圖形並替換緩衝區(置中)。
名稱 : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
(亦可用英文 circle, rect, triangle, pentagon,
hexagon, star)。
顏色 : 填滿色 0xRRGGBB。
大小 : 基準大小(像素)。
線寬 : 輪廓寬度(可省略)。0 為填滿。
長寬比 : 變形 -1.0 ~ 1.0(可省略)。
範例:obj.load("figure", "円", 0xff3366, 200)
obj.load("text", 字串)
以 obj.setfont 指定的字型、大小、顏色繪製字串並替換緩衝區
(使用 DirectWrite 繪製)。
範例:obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
obj.load("image", 路徑)
載入影像檔並替換緩衝區。
※ 為安全起見會驗證檔頭,僅載入真正的影像
(PNG / JPEG / GIF / BMP / TIFF / WebP)。
範例:obj.load("image", "C:\\img\\logo.png")
obj.load("movie", 路徑 [, 時間])
載入影片檔指定時間的影格並替換緩衝區
(使用 Media Foundation 解碼)。
時間 : 秒。省略時為 obj.time。
※ 為安全起見會驗證檔頭,僅載入真正的影片
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF)。
範例:obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
○ obj.setfont(字型 [, 大小 [, 樣式 [, 顏色]]])
設定 obj.load("text") 使用的字型。
樣式 : 位元旗標。1=粗體, 2=斜體, 3=粗斜體。
顏色 : 0xRRGGBB。
範例:obj.setfont("Meiryo", 64, 1, 0xffffff)
○ obj.draw([ox, oy, oz [, 縮放 [, 不透明度 [, 長寬比]]]])
將目前物件影像合成到累積緩衝區並繪製。
多次呼叫會疊加繪製(殘影、粒子等)。
ox, oy, oz : 相對中心的偏移(預設 0)。
縮放 : 1.0 為原始大小(預設 1.0)。
不透明度 : 0.0 ~ 1.0(預設 1.0)。
長寬比 : -1.0 ~ 1.0(預設 0)。
※ 呼叫後會抑制標準繪製,輸出合成結果。
○ obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
[, u0,v0, u1,v1, u2,v2, u3,v3 [, 不透明度]])
將物件影像以材質方式繪製到 4 個頂點指定的四邊形。
頂點順序為左上→右上→右下→左下。省略 UV 時使用整幅影像。
※ 省略 UV 而僅提供第 13 個引數時,將其作為不透明度(12 個座標 + 不透明度)。
※ 使用仿射變換對應(平行四邊形精確,非平行四邊形為近似)。
○ obj.copybuffer(目標, 來源)
在緩衝區之間複製影像。依識別字首字元判定。
"obj" : 物件影像緩衝區
"tmp" : 暫存緩衝區
"cache:名稱" : 具名快取(跨影格保留)
範例:obj.copybuffer("tmp", "obj") -- 儲存
obj.copybuffer("obj", "tmp") -- 還原
※ 由於 YMM4 的結構,無法取得 "frm"(影格緩衝區 / 背景)。
○ obj.getvalue(目標)
取得 obj 的目前值(與 obj.x、obj.track0 等相同)。
目標 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
"alpha","sx","sy","track0"~"track3","time","frame" 等。
回傳值 : 數值(未知目標回傳 0)。
○ obj.setoption(名稱, 值) / obj.getoption(名稱)
設定 / 取得選項。未支援的項目也會被接受,不會中斷腳本
(getoption 回傳設定值,未設定為 0)。
目前會反映到繪製的項目:
"antialias" : 0 為最近鄰,其它為線性內插(obj.draw / obj.drawpoly)。
○ obj.pixeloption(名稱, 值)
將像素操作的選項作為狀態保存。
- ymm4 表 -
@@ -437,17 +531,57 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- AviUtl 腳本的部分相容 -
提供相容層,使 AviUtl 動畫效果腳本(*.anm 系列)中涉及座標、縮放、旋轉、
不透明度的變形以及亂數的部分,無需額外修改即可執行。當腳本中不包含
AviUtl 專有寫法時,此相容層完全不介入(傳統腳本的行為不變)。
○ 腳本標頭指令的解釋
解釋註解形式的參數宣告,在執行前定義腳本主體所參考的變數。
--dialog:項目名,local 變數=預設值;…
將各項目的宣告部分(如 local 變數=預設值)展開至主體開頭。
在 AviUtl 中這些是透過對話框編輯的值,此處以預設值執行。
--color:0xRRGGBB
以指定顏色定義變數 color。
--check0:項目名,預設值
以預設值定義 obj.check0 (0~3)。
--param:任意 Lua 陳述式
將所寫的 Lua 陳述式原樣展開至主體開頭。
--track0: ~ --track3:
軌道列的值仍透過 obj.track0 ~ obj.track3 參考。標頭的標籤、
範圍與預設值不會反映至 UI。
○ 透過 @ 的多區段
當一個腳本以 @名稱 定義了多個效果時,僅執行第一個區段。
○ obj.rand(st, ed [, seed [, frame]])
與 AviUtl 相容的確定性整數亂數。詳情請參閱「obj 表 - 函式」。
○ 繪製·合成·載入
支援 obj.draw / obj.drawpoly 的繪製合成、obj.copybuffer 的緩衝區操作、
obj.load("figure"/"text"/"image"/"movie") 的產生與載入、obj.setfont、
obj.effect、obj.getvalue 以及 obj.setoption / obj.getoption /
obj.pixeloption。詳情請參閱「obj 表 - 函式」。
以下功能不在此相容層的範圍內。
呼叫它們的腳本不會如預期運作。
× 透過 require 載入模組,以及 io / dofile 等任意檔案存取
(obj.load 的影像 / 影片載入已附檔頭驗證支援)。
× obj.setanchor、scene.set / scene.get 等。
- 不支援項目·限制事項 -
× 不支援 AviUtl2 的 obj.effect()、obj.draw()、obj.drawpoly()、obj.load() 等。
× 不支援 AviUtl2 的 obj.rand()、obj.rand1()、obj.setfont()、obj.mes() 等。
× 不支援 AviUtl2 的 obj.setoption()、obj.getoption()、obj.getvalue()、obj.setanchor() 等。
× 不支援 AviUtl2 的 obj.rand1()、obj.mes()、obj.setanchor() 等。
× 不支援 AviUtl2 scene 表中的 scene.set()、scene.get() 等函式。
(僅支援讀取 scene.width 和 scene.height)
× 不支援檔案存取(require、dofile、io 等)。
× 不支援腳本進行任意檔案存取(require、dofile、io 等)。
僅 obj.load("image"/"movie") 會載入經檔頭驗證確認為真正媒體的檔案。
× 修改 obj.z 會反映至繪製中(包含在 ReadBack 中),
但 3D 繪製支援有限。
× 超過腳本逾時時間(5 秒)時,執行將被強制終止。
實作時需注意避免出現無限迴圈。
× 不支援 AviUtl2 的 --track@、--check@ 等標頭指令。
參數僅可使用 Track0 ~ Track3。
× AviUtl2 的標頭指令僅部分支援。--dialog / --color / --check / --param 的
預設值會被解釋(參閱「AviUtl 腳本的部分相容」),但 --track@ 的標籤、範圍
與預設值不會反映至 UI,值透過 Track0 ~ Track3 使用。
+27 -3
ファイルの表示
@@ -29,6 +29,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
- [6. トラックバー(Track0〜Track3)](#6-トラックバーtrack0track3)
- [7. スクリプトエディタの支援機能](#7-スクリプトエディタの支援機能)
- [8. インポート・エクスポート・クリア](#8-インポートエクスポートクリア)
- [9. AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)
5. [実行モデル](#実行モデル)
- [実行エンジンの自動振り分け](#実行エンジンの自動振り分け)
- [実行スレッドとタイムアウト](#実行スレッドとタイムアウト)
@@ -47,7 +48,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
内部的には MoonSharp(Lua 5.2 互換のスクリプトエンジン)を組み込んでおり、ユーザーが記述した Lua スクリプトをフレームごとに実行します。スクリプト内で `obj.x` や `obj.alpha` といったグローバル変数を書き換えると、その値がオブジェクトの座標・拡縮・回転・不透明度として描画に反映されます。
このエフェクトは AviUtl2 のスクリプト仕様とは異なる独自実装であり、AviUtl 向けの EXO 出力(`.exo`)には対応していません。
このエフェクトは独自のスクリプト実行系を基盤としつつ、AviUtl のアニメーション効果スクリプト(`.anm` 系)の一部に対する互換層を備えています(詳細は[AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。AviUtl 向けの EXO 出力(`.exo`)には対応していません。
---
@@ -187,6 +188,29 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
- **インポート**: `.lua` ファイルを選択して読み込み、選択中のすべてのアイテムのスクリプトを置き換えます。
- **エクスポート**: 現在のスクリプトを `.lua` ファイルとして保存します。複数のアイテムを選択している場合でも、書き出されるのは先頭の 1 件のスクリプトのみです。
- **クリア**: 確認ダイアログの表示後、選択中のすべてのアイテムのスクリプトをデフォルトスクリプト(`obj.alpha = math.min(time * 255, 255)`)に戻します。
### 9. AviUtl スクリプトの部分互換
AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、座標・拡縮・回転・不透明度の変形、乱数、および図形描画について、追加の記述変更なしに実行できる互換層を備えています。スクリプトに AviUtl 固有の記法が含まれない場合、この互換層は一切介入しません(従来のスクリプトの挙動は変わりません)。
対応している内容は次のとおりです。
- **スクリプトヘッダの解釈**: コメント形式のパラメータ宣言を解釈し、スクリプト本体が参照する変数を実行前に定義します。
- `--dialog:項目名,local 変数=既定値;…` … 各項目の宣言部(`local 変数=既定値` など)を本体の先頭に展開します。AviUtl では対話ダイアログで編集される値ですが、本プラグインでは既定値で動作します。
- `--color:0xRRGGBB` … 変数 `color` を指定色で定義します。
- `--check0:項目名,既定値` … `obj.check0`(`0`〜`3`)を既定値で定義します。
- `--param:任意のLua文` … 記述した Lua 文をそのまま本体の先頭に展開します。
- `--track0:`〜`--track3:` … トラックバーの値は従来どおり `obj.track0`〜`obj.track3` から参照します(ラベル・範囲・既定値の UI 反映は行いません)。
- **`@` による複数セクション**: 1 つのスクリプトに `@名前` で複数の効果が定義されている場合、先頭のセクションのみを実行します。
- **`obj.rand(st, ed [, seed [, frame]])`**: 指定範囲(`st`〜`ed`)の整数を返す決定論的な乱数です。`seed` と `frame` が同じであれば常に同じ値を返し、`frame` を省略すると現在のフレームを用います。従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)で同じ値を返します。
- **`obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])`**: 円・四角形・三角形・五角形・六角形・星形を生成し、オブジェクトのバッファを置き換えて描画します(出力は図形サイズに合わせて生成され、中心に配置されます)。`ライン` を省略するか `0` で塗りつぶし、サイズ以上の値でも塗りつぶしになります。`アスペクト`(-1.0〜1.0)で幅・高さを歪曲できます。`figure` 以外の対象は本バージョンでは対象外です。描画系 API を含むスクリプトは従来エンジン(MoonSharp)で実行されます。
次のような機能は、本体の描画パイプラインへの統合を要するため、この互換層では対象外です(呼び出しを含むスクリプトは意図どおりには動作しません)。
- 描画・合成(`obj.draw` / `obj.drawpoly`)、`obj.load` の `"figure"` 以外の対象(画像ファイル・`"text"`・`"movie"` など)、および `obj.setfont`
- フィルタ効果やバッファ操作(`obj.effect` / `obj.copybuffer` / `obj.setoption` など)
- `require` によるモジュール読み込み、`io` などのファイルアクセス
---
## 実行モデル
@@ -205,7 +229,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で受け渡されます。スクリプトが無限ループに陥った場合でも **5 秒のタイムアウトでプロセスを強制終了**するため本体は固まらず、終了後は自動的に復帰します。出力結果は従来エンジンと一致します。
`obj.getobject` はネイティブ実行でも利用できます。呼び出し時に本体プロセスへ同期的に問い合わせてシーンオブジェクトを解決するため、従来エンジンと同じ結果を返します。
`obj.getobject` はネイティブ実行でも利用できます。呼び出し時に本体プロセスへ同期的に問い合わせてシーンオブジェクトを解決するため、従来エンジンと同じ結果を返します。同じタグ・同じフレームへの連続した問い合わせはフレーム内でキャッシュされ、2 回目以降は往復を行いません。
ネイティブ実行には次の制約があります。
@@ -321,7 +345,7 @@ obj.alpha = anim.ease_out(t) * 255
## 注意事項
- **AviUtl 非対応**: 本プラグインは独自のスクリプト実行系であり、AviUtl 向けの EXO 出力(`.exo`)には対応していません。
- **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 へのデータ転送が発生します。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは高速ランタイム(LuaJIT)で自動実行され大幅に高速化されます。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
+20
ファイルの表示
@@ -307,6 +307,26 @@ function anim.rand(...)
return min + r * (max - min)
end
function aviutl_rand(a, b, seed, frame)
local ps = ffi.new("double[1]", seed)
local ws = ffi.cast("uint32_t*", ps)
local s = tou(bit.bxor(ws[0], ws[1]))
local pf = ffi.new("double[1]", frame)
local wf = ffi.cast("uint32_t*", pf)
local f = tou(bit.bxor(wf[0], wf[1]))
local h = tou(umul32(s, 374761393) + umul32(f, 668265263))
h = umul32(tou(bit.bxor(h, bit.rshift(h, 13))), 1274126177)
h = tou(bit.bxor(h, bit.rshift(h, 16)))
local r = h / 4294967295.0
local lo = floor(math.min(a, b))
local hi = floor(math.max(a, b))
local span = hi - lo + 1
if span <= 1 then return lo end
local v = lo + floor(r * span)
if v > hi then return hi end
return v
end
local function noise_hash(x, y, z)
local n = tou(umul32(tou(x), 374761393) + umul32(tou(y), 668265263) + umul32(tou(z), 1013904223))
n = umul32(tou(bit.bxor(n, bit.rshift(n, 13))), 1274126177)
+307 -13
ファイルの表示
@@ -46,15 +46,26 @@ local OFF_ERRORLEN = 7
local OFF_CB_FRAME = 8
local OFF_CB_TAGLEN = 9
local OFF_CB_FOUND = 10
local OFF_CB_KIND = 11
local OFF_LOAD_RESULT_W = 12
local OFF_LOAD_RESULT_H = 13
local SCRIPT_OFFSET = 64 + 64 * 8
local ERROR_OFFSET = SCRIPT_OFFSET + 128 * 1024
local CB_TAG_OFFSET = ERROR_OFFSET + 4 * 1024
local CB_TAG_MAX = 256
local CB_TAG_MAX = 4096
local CB_RESULT_OFFSET = CB_TAG_OFFSET + CB_TAG_MAX
local PIXEL_OFFSET = CB_RESULT_OFFSET + 8 * 8
local FIRST_WRITABLE = 8
local LAST_WRITABLE = 25
local STATUS_CALLBACK = 3
local CB_KIND_GETOBJECT = 0
local CB_KIND_LOADFIGURE = 1
local CB_KIND_EFFECT = 2
local CB_KIND_DRAW = 3
local CB_KIND_DRAWPOLY = 4
local CB_KIND_LOADTEXT = 5
local CB_KIND_LOADIMAGE = 6
local CB_KIND_LOADMOVIE = 7
assert(loadfile(shimPath))()
@@ -67,8 +78,24 @@ end
local width, height = 0, 0
local pixels = ffi.cast("uint8_t*", base + PIXEL_OFFSET)
local cbResult = ffi.cast("double*", base + CB_RESULT_OFFSET)
local cbTagD = ffi.cast("double*", base + CB_TAG_OFFSET)
local pixelCapacity = mapSize - PIXEL_OFFSET
local buffers = {}
local options = {}
local pixeloptions = {}
local dirty = false
local function bufferKind(id)
local c = id:match("^%s*(.)")
if not c then return nil end
c = c:lower()
if c == "c" then
local name = id:match(":%s*(.-)%s*$")
return "c", name and ("c:" .. name) or "c"
end
return c, c
end
local obj = {}
local scene = {}
local ymm4 = {}
@@ -146,28 +173,288 @@ end
function obj.putpixeldata() end
function obj.rand(a, b, seed, frame)
return aviutl_rand(a or 0, b or 0, seed or 0, frame or obj.frame or 0)
end
local font = { family = "", size = 34, bold = false, italic = false, color = 0xFFFFFF }
function obj.setfont(name, size, style, col1)
if name ~= nil then font.family = tostring(name) end
if size ~= nil then font.size = size end
if style ~= nil then
local s = math.floor(style)
font.bold = (s % 2) == 1
font.italic = (math.floor(s / 2) % 2) == 1
end
if col1 ~= nil then font.color = col1 end
end
local function applyLoadResult()
local newW = i32[OFF_LOAD_RESULT_W]
local newH = i32[OFF_LOAD_RESULT_H]
if newW > 0 and newH > 0 then
width = newW
height = newH
i32[OFF_WIDTH] = newW
i32[OFF_HEIGHT] = newH
dirty = true
obj.w = newW; obj.h = newH
obj.hw = newW / 2; obj.hh = newH / 2
obj.cx = newW / 2; obj.cy = newH / 2
obj.cz = 0
obj.diagonal = math.sqrt(newW * newW + newH * newH)
end
end
local function loadFigure(name, color, size, lineWidth, aspect)
local nameBytes = tostring(name or "")
local len = #nameBytes
if len > CB_TAG_MAX then len = CB_TAG_MAX end
ffi.copy(base + CB_TAG_OFFSET, nameBytes, len)
i32[OFF_CB_TAGLEN] = len
i32[OFF_CB_KIND] = CB_KIND_LOADFIGURE
cbResult[0] = color or 0
cbResult[1] = size or 100
cbResult[2] = lineWidth or 0
cbResult[3] = aspect or 0
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
applyLoadResult()
end
local function loadText(str)
local payload = font.family .. "\0" .. tostring(str or "")
local len = #payload
if len > CB_TAG_MAX then len = CB_TAG_MAX end
ffi.copy(base + CB_TAG_OFFSET, payload, len)
i32[OFF_CB_TAGLEN] = len
i32[OFF_CB_KIND] = CB_KIND_LOADTEXT
cbResult[0] = font.size
cbResult[1] = font.bold and 1 or 0
cbResult[2] = font.italic and 1 or 0
cbResult[3] = font.color
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
applyLoadResult()
end
local function loadImage(path)
local payload = tostring(path or "")
local len = #payload
if len > CB_TAG_MAX then len = CB_TAG_MAX end
ffi.copy(base + CB_TAG_OFFSET, payload, len)
i32[OFF_CB_TAGLEN] = len
i32[OFF_CB_KIND] = CB_KIND_LOADIMAGE
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
applyLoadResult()
end
local function loadMovie(path, time)
local payload = tostring(path or "")
local len = #payload
if len > CB_TAG_MAX then len = CB_TAG_MAX end
ffi.copy(base + CB_TAG_OFFSET, payload, len)
i32[OFF_CB_TAGLEN] = len
i32[OFF_CB_KIND] = CB_KIND_LOADMOVIE
cbResult[0] = time or obj.time or 0
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
applyLoadResult()
end
function obj.load(kind, ...)
if kind == "figure" then
loadFigure(...)
elseif kind == "text" then
loadText(...)
elseif kind == "image" then
loadImage(...)
elseif kind == "movie" then
loadMovie(...)
end
end
function obj.effect(name, ...)
if type(name) ~= "string" then return end
local args = { ... }
local n = select("#", ...)
local parts = { name }
local pos = #name + 1
for i = 1, n - 1, 2 do
local k = tostring(args[i])
local v = args[i + 1]
local encoded
local vt = type(v)
if vt == "number" then
encoded = "n" .. string.format("%.17g", v)
elseif vt == "boolean" then
encoded = v and "b1" or "b0"
else
encoded = "s" .. tostring(v)
end
local needed = 2 + #k + #encoded
if pos + needed > CB_TAG_MAX then break end
parts[#parts + 1] = k
parts[#parts + 1] = encoded
pos = pos + needed
end
local payload = table.concat(parts, "\0")
local len = #payload
if len > CB_TAG_MAX then len = CB_TAG_MAX end
ffi.copy(base + CB_TAG_OFFSET, payload, len)
i32[OFF_CB_TAGLEN] = len
i32[OFF_CB_KIND] = CB_KIND_EFFECT
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
end
function obj.draw(ox, oy, oz, zoom, alpha, aspect)
cbResult[0] = ox or 0
cbResult[1] = oy or 0
cbResult[2] = oz or 0
cbResult[3] = zoom or 1
cbResult[4] = alpha or 1
cbResult[5] = aspect or 0
cbResult[6] = options.antialias or 1
i32[OFF_CB_KIND] = CB_KIND_DRAW
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
end
function obj.drawpoly(...)
local n = select("#", ...)
if n < 12 then return end
local a = { ... }
for i = 0, 11 do cbTagD[i] = a[i + 1] or 0 end
if n >= 20 then
for i = 0, 7 do cbTagD[12 + i] = a[13 + i] or 0 end
else
cbTagD[12] = 0; cbTagD[13] = 0
cbTagD[14] = width; cbTagD[15] = 0
cbTagD[16] = width; cbTagD[17] = height
cbTagD[18] = 0; cbTagD[19] = height
end
local alpha = 1
if n == 13 then
alpha = a[13] or 1
elseif n >= 21 then
alpha = a[21] or 1
end
cbTagD[20] = alpha
cbTagD[21] = options.antialias or 1
i32[OFF_CB_KIND] = CB_KIND_DRAWPOLY
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
end
function obj.getvalue(target)
if type(target) ~= "string" then return 0 end
local v = obj[target]
if type(v) == "number" then return v end
return 0
end
function obj.setoption(name, value)
if type(name) ~= "string" then return end
if value == nil then value = true end
options[name] = value
end
function obj.getoption(name)
if type(name) ~= "string" then return 0 end
local v = options[name]
if v == nil then return 0 end
return v
end
function obj.pixeloption(name, value)
if type(name) ~= "string" then return end
if value == nil then value = true end
pixeloptions[name] = value
end
function obj.copybuffer(dst, src)
if type(dst) ~= "string" or type(src) ~= "string" then return end
local sk, skey = bufferKind(src)
local data, w, h
if sk == "o" then
data = ffi.string(pixels, width * height * 4)
w = width; h = height
elseif sk == "t" or sk == "c" then
local b = buffers[skey]
if not b then return end
data, w, h = b.data, b.w, b.h
else
return
end
local dk, dkey = bufferKind(dst)
if dk == "o" then
local need = w * h * 4
if need > pixelCapacity then return end
ffi.copy(pixels, data, need)
width = w; height = h
i32[OFF_WIDTH] = w; i32[OFF_HEIGHT] = h
dirty = true
obj.w = w; obj.h = h
obj.hw = w / 2; obj.hh = h / 2
obj.cx = w / 2; obj.cy = h / 2
obj.cz = 0
obj.diagonal = math.sqrt(w * w + h * h)
elseif dk == "t" or dk == "c" then
buffers[dkey] = { data = data, w = w, h = h }
end
end
local cacheTag, cacheFrame, cacheFound
local cacheExist, cacheX, cacheY, cacheZ, cacheZoom, cacheRz, cacheAlpha, cacheLayer
local function buildObject()
return {
exist = cacheExist,
x = cacheX, y = cacheY, z = cacheZ,
zoom = cacheZoom, sx = cacheZoom, sy = cacheZoom,
rx = 0, ry = 0, rz = cacheRz,
rxr = 0, ryr = 0, rzr = cacheRz * math.pi / 180,
alpha = cacheAlpha, layer = cacheLayer,
}
end
function obj.getobject(tag, frame)
if type(tag) ~= "string" then return nil end
if frame then frame = math.floor(frame) else frame = math.floor(obj.timelineframe or 0) end
if tag == cacheTag and frame == cacheFrame then
if cacheFound then return buildObject() end
return nil
end
local len = #tag
if len > CB_TAG_MAX then len = CB_TAG_MAX end
ffi.copy(base + CB_TAG_OFFSET, tag, len)
i32[OFF_CB_TAGLEN] = len
i32[OFF_CB_FRAME] = frame
i32[OFF_CB_KIND] = CB_KIND_GETOBJECT
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
if i32[OFF_CB_FOUND] == 0 then return nil end
local rz = cbResult[5]
local zoom = cbResult[4]
return {
exist = cbResult[0] ~= 0,
x = cbResult[1], y = cbResult[2], z = cbResult[3],
zoom = zoom, sx = zoom, sy = zoom,
rx = 0, ry = 0, rz = rz,
rxr = 0, ryr = 0, rzr = rz * math.pi / 180,
alpha = cbResult[6], layer = cbResult[7],
}
cacheTag = tag
cacheFrame = frame
if i32[OFF_CB_FOUND] == 0 then
cacheFound = false
return nil
end
cacheFound = true
cacheExist = cbResult[0] ~= 0
cacheX = cbResult[1]; cacheY = cbResult[2]; cacheZ = cbResult[3]
cacheZoom = cbResult[4]; cacheRz = cbResult[5]; cacheAlpha = cbResult[6]; cacheLayer = cbResult[7]
return buildObject()
end
local sandbox = {
@@ -205,6 +492,8 @@ local function loadFields()
ymm4.is_saving = f64[48] ~= 0; ymm4.is_playing = f64[49] ~= 0; ymm4.is_paused = f64[50] ~= 0
ymm4.group_ratio = (f64[44] ~= 0) and (f64[43] / f64[44]) or 0
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
end
local function storeFields()
@@ -245,6 +534,10 @@ while true do
if compiledChunk and code == compiledCode then
loadFields()
cacheTag = nil
for k in pairs(options) do options[k] = nil end
for k in pairs(pixeloptions) do pixeloptions[k] = nil end
font.family = ""; font.size = 34; font.bold = false; font.italic = false; font.color = 0xFFFFFF
math.randomseed(f64[31])
setfenv(compiledChunk, sandbox)
local ok, err = pcall(compiledChunk)
@@ -252,13 +545,14 @@ while true do
storeFields()
i32[OFF_PIXELSDIRTY] = dirty and 1 or 0
i32[OFF_STATUS] = 1
k32.SetEvent(doneEvent)
else
local msg = tostring(err)
ffi.copy(base + ERROR_OFFSET, msg, math.min(#msg, 4096))
i32[OFF_ERRORLEN] = math.min(#msg, 4096)
i32[OFF_STATUS] = 2
k32.SetEvent(doneEvent)
end
k32.SetEvent(doneEvent)
end
end