70 コミット
作成者 SHA1 メッセージ 日付
routersys 420edde566 バージョンをv2.0.0へ更新する 2026-10-01 14:18:35 +09:00
routersys f37e36fe35 Plugin_ReadmeをComputeWeave系の構成で書き直す 2026-10-01 14:18:24 +09:00
routersys fba34baa18 READMEをComputeWeave系の構成で書き直す 2026-10-01 14:18:12 +09:00
routersys b9a60aa6fa 開口がふさがる間は素通しになる試験を追加する 2026-09-30 19:18:20 +09:00
routersys 02b43f9da8 光の通る標本が無い開口の試験を追加する 2026-09-30 19:18:19 +09:00
routersys 2bec5d056b 開口に光の通る標本が無いときは効果を適用しない
・開口をほとんどふさぐ設定で例外が起きる不具合を修正-F
2026-09-30 19:17:13 +09:00
routersys cdbfc60672 一様な領域の明るさが保たれる試験を追加する 2026-09-30 19:11:23 +09:00
routersys 7b314acfad インパルスの試験の期待値を正規化した重みに合わせる 2026-09-30 19:11:22 +09:00
routersys 71084fa9b9 分離した重みの和の試験を追加する 2026-09-30 19:10:16 +09:00
routersys ab1722b1e0 ハーネスの基準値を重みの和の正規化に合わせる 2026-09-30 19:06:16 +09:00
routersys f24dabd2d5 分離した重みの和を1にそろえる 2026-09-30 19:05:45 +09:00
routersys 653323bccb デフォーカスの説明文の単位を波長単位と書く
・デフォーカスの説明文で単位を波数と書いていた誤りを修正-F
2026-09-30 13:17:16 +09:00
routersys 799aa5077e コマ収差のインパルスが点像そのものに広がる試験を追加する 2026-09-30 13:17:16 +09:00
routersys 69dd1fa432 収差のある点像が残差の基準に収まる試験を追加する 2026-09-30 13:17:16 +09:00
routersys 9756e46973 ハーネスの基準値を分離の項数の上限に合わせる 2026-09-30 13:17:16 +09:00
routersys ebfd783d36 分離可能な近似の項数の上限をカーネルの幅にする 2026-09-30 13:17:16 +09:00
routersys 62081f8d66 テレメトリーを変異試験の対象から外す 2026-09-30 13:17:16 +09:00
routersys 18f2b0c69e WPFアプリケーションの外でテレメトリーを送らない試験を追加する 2026-09-30 13:17:15 +09:00
routersys f2be0c4caf 更新確認で例外を握り潰さず報告する 2026-09-30 13:17:15 +09:00
routersys b23e19e9e7 ホストとDirect2Dからの呼び出し口で例外を報告する 2026-09-30 13:17:15 +09:00
routersys 49f92bd04b WaveOpticsTelemetryを追加する
・想定していない例外を開発者へ自動で報告する機能を追加-A
2026-09-30 13:17:15 +09:00
routersys ae95c982d8 Telemetryをコンパイルに含める 2026-09-30 13:17:15 +09:00
routersys e9ea7a75e3 YMM4-Telemetryサブモジュールを追加する 2026-09-30 13:17:15 +09:00
routersys 8e2008de5e WPFアプリケーションの外での挙動の試験を追加する 2026-09-30 13:17:15 +09:00
routersys 2d869f44e1 更新確認を変異試験の対象から外す 2026-09-30 13:17:15 +09:00
routersys 13063805b2 更新の文言の試験を追加する 2026-09-30 13:17:15 +09:00
routersys d7fadec397 言語ごとに文言を引く処理を1か所にまとめる 2026-09-30 13:17:15 +09:00
routersys 5b6753f94c 更新の通知を追加する
・新しい正式版が公開されたときに通知する機能を追加-A
2026-09-30 13:17:15 +09:00
routersys c7c1823b70 YMM4-GitHubUpdateNotifierサブモジュールを追加する 2026-09-30 13:17:14 +09:00
routersys d59bef2e0b 処理器の試験を追加する 2026-09-30 13:17:14 +09:00
routersys af2160e932 適用量が0のときの出力範囲の試験を追加する 2026-09-30 13:17:14 +09:00
routersys 75611dd793 適用量が0のときは元の画像の範囲だけを出力する 2026-09-30 13:17:14 +09:00
routersys eba665280d 相互運用の試験を追加する 2026-09-30 13:17:14 +09:00
routersys f5350538c4 パイプラインの試験を追加する 2026-09-30 13:17:14 +09:00
routersys f7819c57de 設定値の試験を追加する 2026-09-30 13:17:14 +09:00
routersys 349e431bba カスタムエフェクトの試験を追加する 2026-09-30 13:17:14 +09:00
routersys d8808fff1f 文言の試験を追加する 2026-09-30 13:17:14 +09:00
routersys bb59aef5df パラメータの試験を追加する 2026-09-30 13:17:14 +09:00
routersys 8917f43c01 エフェクトのフィールドを既存群の書き方に揃える 2026-09-30 13:17:14 +09:00
routersys ffb1581cc1 文言のキーを既存群の命名に揃える 2026-09-30 13:17:14 +09:00
routersys a02d3fb184 試験の土台を追加する 2026-09-30 13:17:13 +09:00
routersys 9db005ec89 テストプロジェクトの設定を既存群に揃える 2026-09-30 13:17:13 +09:00
routersys f8f97ea516 Stryker.NETで変異試験を行う 2026-09-30 13:17:13 +09:00
routersys 89e5abf1f9 試験の依存関係を最新にする 2026-09-30 13:17:13 +09:00
routersys d9f1a4164d ソリューションのビルドでは本体を配置しない 2026-09-30 13:17:13 +09:00
routersys 5e77119a6a Generatorを本体のプラットフォームに依らず組む 2026-09-30 13:17:13 +09:00
routersys 1ae02a0b8e ソリューションの構成を既存群に揃える 2026-09-30 13:17:13 +09:00
routersys 2b5d061aa0 使われなくなったFxcPathの設定を取り除く 2026-09-30 13:17:13 +09:00
routersys 6f58900e99 リリースワークフローを既存群と同一の構成にする 2026-09-30 13:17:13 +09:00
routersys 96e6dff673 ComputeWeaveのライセンス表示を同梱する 2026-09-30 13:17:13 +09:00
routersys c5e307ec60 畳み込みを1スレッドで8画素ずつ計算して読み出しを減らす
・元映像や設定が変わるときの畳み込みを高速化-M
2026-09-30 13:17:13 +09:00
routersys d0b83ae33d ハーネスへ畳み込みの内訳計測を統合する 2026-09-30 13:17:12 +09:00
routersys 2bd390d65a ハーネスの基準値を計算シェーダーの描画に合わせる 2026-09-30 13:17:12 +09:00
routersys 4615d21d8f 畳み込みを計算シェーダーへ移す
・元映像と設定が変わらないフレームの描画を高速化-M
・利得が100%を超え適用量が100%未満のとき、元映像と混ぜる前に明るさを打ち切るよう変更-M
・長辺が8160画素を超える素材には効果を適用しないよう変更-M
・Direct3D 12や共有テクスチャを使えない環境では効果を適用せず入力映像を表示するよう変更-M
2026-09-30 13:17:12 +09:00
routersys 37f6b55d06 シェーダーの生成をWaveOptics.Shaderへ切り出す 2026-09-30 13:17:12 +09:00
routersys 170aac3247 Direct3D 11と共有するテクスチャの相互運用を追加する 2026-09-30 13:17:12 +09:00
routersys 24b7706056 計算シェーダーで畳み込むパイプラインを追加する 2026-09-30 13:17:12 +09:00
routersys 3bd102f907 ComputeWeaveをILRepackでプラグインのDLLへ統合する 2026-09-30 13:17:12 +09:00
routersys 5b90d5b12a 使われていないComputeSharpの参照を外す 2026-09-30 13:17:12 +09:00
routersys 04e7311be3 実機描画で検証するハーネスを追加する 2026-09-30 13:17:11 +09:00
routersys b326d5da2d 本体のフォルダーをWaveOpticsへ改名する 2026-09-30 13:17:11 +09:00
routersys e04ef2c60e エディターのコード規則を追加する 2026-09-30 13:17:11 +09:00
routersys 92ea407e23 プルリクエストのテンプレートを追加する 2026-09-30 13:17:11 +09:00
routersys 5327df5954 Issueのテンプレートを追加する 2026-09-30 13:17:11 +09:00
routersys f624be38fd スポンサーの設定を追加する 2026-09-30 13:17:11 +09:00
routersys 16308d7d0d 貢献の手引きを追加する 2026-09-30 13:17:11 +09:00
routersys a8177bbf00 セキュリティポリシーを追加する 2026-09-30 13:17:11 +09:00
routersys 2d14865acf 行動規範を追加する 2026-09-30 13:17:11 +09:00
routersys ef78373bef 直接畳み込みをSVD分離可能多パスGPU畳み込みへ置換し描画負荷を軽減
・畳み込みを横と縦の1次元の畳み込みに分けて高速化-M
2026-09-30 13:17:11 +09:00
routersys c9b3ef87d6 PSF生成とFFTをSoA・SIMD化し畳み込みを実半径ループへ最適化して描画負荷を軽減
・点像分布関数の計算を高速化-M
2026-09-30 13:17:10 +09:00
87個のファイルの変更、7877行の追加、1409行の削除

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

+13
ファイルの表示
@@ -0,0 +1,13 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-stryker": {
"version": "5.0.0",
"commands": [
"dotnet-stryker"
],
"rollForward": false
}
}
}
+77
ファイルの表示
@@ -0,0 +1,77 @@
root = true
[*]
indent_style = space
indent_size = 4
tab_width = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.{json,yml,yaml}]
indent_size = 2
[*.{csproj,props,targets,vcxproj,filters,slnx,resx,xml}]
charset = unset
indent_style = unset
indent_size = unset
[*.md]
trim_trailing_whitespace = false
[*.cs]
dotnet_separate_import_directive_groups = false
dotnet_sort_system_directives_first = true
dotnet_style_qualification_for_field = false:error
dotnet_style_qualification_for_property = false:error
dotnet_style_qualification_for_method = false:error
dotnet_style_qualification_for_event = false:error
dotnet_style_predefined_type_for_locals_parameters_members = true:error
dotnet_style_predefined_type_for_member_access = true:error
dotnet_style_readonly_field = true:warning
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning
dotnet_style_operator_placement_when_wrapping = beginning_of_line
dotnet_code_quality_unused_parameters = all:warning
csharp_style_namespace_declarations = file_scoped:error
csharp_using_directive_placement = outside_namespace:error
csharp_prefer_braces = when_multiline:silent
csharp_style_var_for_built_in_types = true:silent
csharp_style_var_when_type_is_apparent = true:silent
csharp_style_var_elsewhere = true:silent
csharp_style_expression_bodied_methods = when_on_single_line:silent
csharp_style_expression_bodied_properties = true:silent
csharp_style_expression_bodied_accessors = true:silent
csharp_style_prefer_pattern_matching = true:suggestion
csharp_style_prefer_not_pattern = true:suggestion
csharp_style_prefer_switch_expression = true:suggestion
csharp_style_prefer_readonly_struct = true:warning
csharp_style_prefer_readonly_struct_member = true:warning
csharp_prefer_static_local_function = true:warning
csharp_style_prefer_primary_constructors = true:silent
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
dotnet_diagnostic.IDE0005.severity = warning
dotnet_diagnostic.IDE0055.severity = warning
dotnet_diagnostic.IDE0161.severity = error
[{YMM4-GitHubUpdateNotifier,YMM4-Telemetry,YukkuriMovieMaker.Generator}/**]
dotnet_diagnostic.IDE0005.severity = none
dotnet_diagnostic.IDE0055.severity = none
dotnet_diagnostic.IDE0161.severity = none
[*.{g.cs,designer.cs}]
generated_code = true
dotnet_diagnostic.IDE0005.severity = none
dotnet_diagnostic.IDE0055.severity = none
dotnet_diagnostic.IDE0161.severity = none
-430
ファイルの表示
@@ -1,430 +0,0 @@
# v1.0.0 - 波動光学 for YMM4
YukkuriMovieMaker4 向けの波動光学エフェクトプラグインの初回リリースです。
フラウンホーファー回折理論に基づいて点像分布関数(PSF)を計算し、Direct2D カスタムシェーダーで
映像を畳み込む映像エフェクトプラグインです。
波長・F値・画素ピッチ・開口形状・ゼルニケ波面収差係数をパラメータとして持ち、
円形開口・正多角形開口・中央遮蔽・6 種類の波面収差項に対応します。
8 言語対応 UI を備えます。
---
## 新機能
### 1. 公開コントラクト(WaveOptics.Abstractions)
`WaveOptics.Abstractions` は主プラグインから独立したライブラリとして提供されます。
#### ApertureShape
開口形状を表す列挙体です。
| 値 | 意味 |
|---|---|
| `Circular` | 円形開口 |
| `RegularPolygon` | 正多角形開口 |
#### OpticalApiVersion
`readonly record struct OpticalApiVersion(int Major, int Minor)` で宣言されます。
`Current` 静的プロパティは `new(1, 0)` を返却します。
#### OpticalCapabilities
PSF 生成器の対応機能を表す `[Flags]` 列挙体です。
| 値 | 意味 |
|---|---|
| `None` | 0 |
| `MonochromaticPsf` | 単色 PSF 生成 |
| `CircularAperture` | 円形開口 |
| `RegularPolygonAperture` | 正多角形開口 |
| `CentralObstruction` | 中央遮蔽 |
| `ZernikeAberration` | ゼルニケ収差 |
| `DirectConvolution` | 直接畳み込み |
#### WavefrontAberration
8 つの収差係数を保持する `readonly struct` で、`IEquatable<WavefrontAberration>` を実装します。
| フィールド | 説明 |
|---|---|
| `DefocusWaves` | デフォーカス係数(-10〜10 waves) |
| `AstigmatismVerticalWaves` | 縦横非点収差係数 |
| `AstigmatismObliqueWaves` | 斜め非点収差係数 |
| `ComaHorizontalWaves` | 水平コマ収差係数 |
| `ComaVerticalWaves` | 垂直コマ収差係数 |
| `TrefoilHorizontalWaves` | 水平トレフォイル係数 |
| `TrefoilVerticalWaves` | 垂直トレフォイル係数 |
| `SphericalWaves` | 球面収差係数 |
コンストラクターは各係数を `ValidateFiniteRange(-10, 10)` で検証します。
`==`・`!=` 演算子および `GetHashCode` を実装します。
#### PsfDescriptor
PSF 計算パラメータを保持する `sealed` クラスで、`IEquatable<PsfDescriptor>` を実装します。
コンストラクターが受け取るパラメータと検証条件は以下のとおりです。
| パラメータ | 型 | 検証条件 |
|---|---|---|
| `pupilGridSize` | `int` | 64〜2048、かつ 2 の冪 |
| `pupilDiameterSamples` | `int` | 16〜`pupilGridSize / 2` |
| `kernelSize` | `int` | 3〜255、かつ奇数 |
| `wavelengthNanometers` | `double` | 有限値、380〜780 |
| `fNumber` | `double` | 有限値、0.5〜64 |
| `sensorPixelPitchMicrometers` | `double` | 有限値、0.25〜100 |
| `apertureShape` | `ApertureShape` | 定義済み列挙値 |
| `bladeCount` | `int` | 3〜32 |
| `bladeRotationDegrees` | `double` | 有限値、-360〜360 |
| `centralObstructionRatio` | `double` | 有限値、0〜0.95 |
| `aberration` | `WavefrontAberration` | — |
`Equals` はすべてのフィールドの完全一致で判定します。`GetHashCode` は `HashCode.Combine` を 2 段に分けて計算します。
#### PsfKernel
PSF カーネルデータを保持する `sealed` クラスです。
コンストラクターは `size`(奇数正整数)と `values`(`size × size` 長、全要素非負有限)を受け取り、
合計値が正であることを検証してから値の総和で正規化します。入力配列は内部にコピーします。
`Sum` メソッドはカハン補償加算でエラー累積を抑えた合計値を返却します。
| メンバー | 説明 |
|---|---|
| `Size` | カーネルの一辺の画素数 |
| `Values` | 正規化済み値の `ReadOnlyMemory<double>` |
| `this[int x, int y]` | 範囲検証付きインデクサー |
| `ToArray()` | 内部配列のクローン |
#### PsfDiagnostics
`readonly record struct PsfDiagnostics` で以下の診断値を保持します。
| フィールド | 説明 |
|---|---|
| `OpenPupilSampleCount` | 開口内の有効サンプル数 |
| `FocalPlaneSamplePitchMicrometers` | 焦点面サンプル間隔(μm) |
| `UnnormalizedKernelEnergy` | 正規化前のカーネルエネルギー |
| `PeakIntensity` | カーネルの最大強度値 |
#### PsfGenerationResult
`sealed record PsfGenerationResult(PsfKernel Kernel, PsfDiagnostics Diagnostics)` で宣言されます。
#### IPsfGenerator
```csharp
public interface IPsfGenerator
{
OpticalApiVersion ApiVersion { get; }
OpticalCapabilities Capabilities { get; }
PsfGenerationResult Generate(PsfDescriptor descriptor);
}
```
---
### 2. 高速フーリエ変換(FastFourierTransform)
`internal static class FastFourierTransform` は 1 次元および 2 次元の FFT・逆 FFT を提供します。
| メソッド | 説明 |
|---|---|
| `Forward(Span<Complex>)` | 1 次元前進 FFT |
| `Inverse(Span<Complex>)` | 1 次元逆 FFT(1/N スケール適用) |
| `Forward2D(Complex[], int, int)` | 2 次元前進 FFT(行→列の順) |
| `Inverse2D(Complex[], int, int)` | 2 次元逆 FFT |
1 次元実装はクーリー・テューキーアルゴリズムに基づく入力サイズ 2 の冪専用の再帰なし実装です。ビット反転置換を前処理として行い、以降を長さ倍増ループで処理します。逆変換では最後に `1/count` を乗算します。
2 次元実装は各行・各列に独立して 1 次元変換を適用します。列方向の処理には作業用配列 `new Complex[height]` を確保します。
---
### 3. ゼルニケ波面評価(ZernikeWavefront)
`internal static class ZernikeWavefront` は正規化ゼルニケ多項式による波面位相を評価します。
`Evaluate(double x, double y, WavefrontAberration aberration)` は以下の項の線形結合を返却します。
| 項 | 式 |
|---|---|
| デフォーカス | `√3 × (2ρ² − 1)` |
| 縦横非点収差 | `√6 × (x² − y²)` |
| 斜め非点収差 | `2√6 × xy` |
| 水平コマ収差 | `√8 × (3ρ² − 2) × x` |
| 垂直コマ収差 | `√8 × (3ρ² − 2) × y` |
| 水平トレフォイル | `√8 × x × (x² − 3y²)` |
| 垂直トレフォイル | `√8 × y × (3x² − y²)` |
| 球面収差 | `√5 × (6ρ⁴ − 6ρ² + 1)` |
`WavefrontAberration` の `TrefoilHorizontalWaves`・`TrefoilVerticalWaves` は`WaveOpticsEffect` の UI には公開されておらず、常に 0 として扱われます。
---
### 4. フラウンホーファーPSF生成器(FraunhoferPsfGenerator)
`public sealed class FraunhoferPsfGenerator : IPsfGenerator` を実装します。
`Capabilities` は以下のフラグを返却します。
`MonochromaticPsf | CircularAperture | RegularPolygonAperture | CentralObstruction | ZernikeAberration | DirectConvolution`
#### Generate メソッド
1. `gridSize × gridSize` の `Complex[]` 配列を確保します。
2. グリッド中心を基準に各サンプル `(x, y)` を正規化座標 `(normalizedX, normalizedY)` に変換し、
`IsInsideAperture` で開口内を判定します。
3. 開口内のサンプルに対して `ZernikeWavefront.Evaluate` で波面位相 `φ` を計算し、
`Complex.FromPolarCoordinates(1d, 2π × φ)` を瞳関数値として設定します。
4. `FastFourierTransform.Forward2D` を適用します。
5. 変換後の値の二乗絶対値(強度)を計算し、FFT のゼロ周波数が中心に来るよう DC シフトして
`double[]` 配列に格納します。全強度の和で正規化します。
6. 焦点面サンプルピッチ `λ × F × D / N`(μm)を計算し、カーネルの各画素に対応する
焦点面座標を求めて `SampleBilinear` で強度を取得します。
7. `new PsfKernel(kernelSize, kernel)` を生成して返却します。
#### IsInsideAperture メソッド
- 正規化半径の二乗が 1 超 → 開口外。
- 正規化半径の二乗が `obstructionRatio²` 未満 → 遮蔽領域。
- 円形開口の場合は上記を満たせば開口内。
- 正多角形の場合:`Math.Atan2(y, x) - rotation` を `2π / bladeCount` で折り畳み、境界距離
`cos(π / bladeCount) / cos(folded)` と半径を比較します。
#### SampleBilinear メソッド
双線形補間でグリッド外を 0 として返却します。
---
### 5. PSFビットマップ生成(PsfBitmapFactory)
`internal static class PsfBitmapFactory` の `Create(ID2D1DeviceContext, PsfKernel)` は
PSF カーネルの各値を RGBA 4 チャンネルの `float[]` に展開(R=G=B=値, A=1)し、
ピン留めポインタを使って `ID2D1DeviceContext1.CreateBitmap` を呼び出します。
ピクセルフォーマットは `Format.R32G32B32A32_Float` / `AlphaMode.Ignore` / 96 DPI です。
---
### 6. カスタムシェーダーエフェクト(WaveOpticsConvolutionEffect)
`internal sealed class WaveOpticsConvolutionEffect : D2D1CustomShaderEffectBase` は
`[CustomEffect(2)]` の 2 入力エフェクトとして宣言されます(入力 0: ソース画像、入力 1: PSF ビットマップ)。
定数は以下のとおりです。
| 定数 | 値 |
|---|---|
| `MaximumKernelSize` | `31` |
公開プロパティは `GetIntValue`・`GetFloatValue`・`SetValue` を介して `EffectImpl` へ転送します。
| プロパティ | 型 | 説明 |
|---|---|---|
| `KernelSize` | `int` | カーネルサイズ(奇数にクランプ、最大 31) |
| `Amount` | `float` | 適用量(0〜1) |
| `Gain` | `float` | 利得(0〜4) |
`SetSource(ID2D1Image?)` は入力 0 を設定します。`SetKernel(ID2D1Image?)` は入力 1 を設定します。
#### EffectImpl(内部 sealed クラス)
`ConstantBuffer` 構造体(`LayoutKind.Sequential`)のレイアウトは以下のとおりです。
| フィールド | 型 | 説明 |
|---|---|---|
| `KernelSize` | `int` | カーネルサイズ |
| `Amount` | `float` | 適用量 |
| `Gain` | `float` | 利得 |
| `Padding` | `float` | アライメント用 |
| `InputBounds` | `Vector4` | 入力矩形(Left, Top, Right, Bottom) |
コンストラクターは `constants.KernelSize = 1`・`constants.Gain = 1` を初期値として設定します。
`MapInputRectsToOutputRect` は `inputRect` と `inputBounds` を更新した後、
`Inflate(inputRect, GetRadius())` を出力矩形に設定します。
`GetRadius` は `Amount > 0` かつ `KernelSize > 1` のとき `KernelSize / 2` を、それ以外は `0` を返却します。
#### HLSLシェーダー(WaveOpticsConvolution.hlsl)
`t0`(ソース画像)・`t1`(PSF ビットマップ)・`b0`(定数バッファー)を持つピクセルシェーダーです。
- `amount <= 0` または `kernelSize <= 1` の場合はソースをそのまま返却します。
- ループ範囲は固定 `-MaximumRadius`〜`MaximumRadius`(= -15〜15)で、
`abs(x) > radius` または `abs(y) > radius` のサンプルは `continue` でスキップします。
- PSF の重みは `KernelTexture.Load(int3(x + radius, y + radius, 0)).r` で取得します。
- 入力矩形外のサンプルは黒として扱います。
- `lerp(source, convolved * gain, amount)` で出力します。
---
### 7. エフェクト定義(WaveOpticsEffect)
`public sealed class WaveOpticsEffect : VideoEffectBase` を継承します。
`[VideoEffect]` 属性は以下のパラメーターで宣言されます。
- 表示名:`Texts.EffectName`(ローカライズキー)
- カテゴリー:`VideoEffectCategories.Filtering`
- 検索タグ:`TagDiffraction`・`TagLens`・`TagPsf`・`TagOptics`(「回折」・「レンズ」・「点像分布関数」・「光学」)
- `IsAviUtlSupported = false` により AviUtl 向け EXO 出力は非対応
- `ResourceType = typeof(Texts)` でローカライズリソースを指定
`Label` プロパティは `Texts.EffectName` を返却します。
公開プロパティは以下のとおりです。
**出力グループ**
| プロパティ | 型 | デフォルト | 内部範囲 |
|---|---|---|---|
| `Amount` | `Animation` | 100 | 0〜100 |
| `Gain` | `Animation` | 100 | 0〜400 |
**光学系グループ**
| プロパティ | 型 | デフォルト | 内部範囲 |
|---|---|---|---|
| `Wavelength` | `Animation` | 550 | 380〜780 |
| `FNumber` | `Animation` | 8 | 0.5〜64 |
| `PixelPitch` | `Animation` | 4 | 0.25〜100 |
| `KernelRadius` | `int` | 15 | 1〜15 |
| `Quality` | `WaveOpticsQuality` | `Standard` | — |
**開口グループ**
| プロパティ | 型 | デフォルト | 内部範囲 |
|---|---|---|---|
| `ApertureShape` | `WaveOpticsApertureShape` | `Circular` | — |
| `BladeCount` | `int` | 6 | 3〜32 |
| `BladeRotation` | `Animation` | 0 | -360〜360 |
| `Obstruction` | `Animation` | 0 | 0〜95 |
**波面収差グループ**
| プロパティ | 型 | デフォルト | 内部範囲 |
|---|---|---|---|
| `Defocus` | `Animation` | 0 | -10〜10 |
| `AstigmatismVertical` | `Animation` | 0 | -10〜10 |
| `AstigmatismOblique` | `Animation` | 0 | -10〜10 |
| `ComaHorizontal` | `Animation` | 0 | -10〜10 |
| `ComaVertical` | `Animation` | 0 | -10〜10 |
| `Spherical` | `Animation` | 0 | -10〜10 |
`GetAnimatables` は `Amount`・`Gain`・`Wavelength`・`FNumber`・`PixelPitch`・`BladeRotation`・
`Obstruction`・`Defocus`・`AstigmatismVertical`・`AstigmatismOblique`・`ComaHorizontal`・
`ComaVertical`・`Spherical` を yield します。
---
### 8. エフェクトプロセッサー(WaveOpticsEffectProcessor)
`internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase` を継承します。
#### Update メソッド
`IsPassThroughEffect || effect is null` の場合は `effectDescription.DrawDescription` をそのまま返却します。
各フレームで以下の値を計算します。
| パラメーター | クランプ範囲 | フォールバック |
|---|---|---|
| `amount` | 0〜1 | 0 |
| `gain` | 0〜4 | 1 |
| `wavelength` | 380〜780 | 550 |
| `fNumber` | 0.5〜64 | 8 |
| `pixelPitch` | 0.25〜100 | 4 |
| `obstruction / 100` | 0〜0.95 | 0 |
| 各収差係数 | -10〜10 | 0 |
`Parameters` レコードとして前フレームの値と比較し、変化があった場合のみ `UpdateKernel` を呼び出します。
`Amount`・`Gain` も同様に差分検出して `effect` のプロパティを更新します。
#### UpdateKernel メソッド
`WavefrontAberration` と `PsfDescriptor` を構築して `FraunhoferPsfGenerator.Generate` を呼び出します。
品質から FFT 格子サイズへの変換は以下のとおりです。
| `WaveOpticsQuality` | FFT 格子サイズ |
|---|---|
| `Draft` | 128 |
| `High` | 512 |
| その他(`Standard`) | 256 |
`PsfDescriptor` の `pupilDiameterSamples` は `gridSize / 4` に固定されます。
`kernelSize` は `KernelRadius * 2 + 1` です。
`PsfBitmapFactory.Create` で新しいビットマップを作成し、`disposer.RemoveAndDispose` で旧ビットマップを破棄してから新ビットマップを `effect` に設定します。
#### CreateEffect / setInput / ClearEffectChain
`CreateEffect` は `WaveOpticsConvolutionEffect` を生成し、`IsEnabled` が false の場合は破棄して
`null` を返却します。有効な場合は `disposer` に収集し、`Output` を取得して返却します。
`setInput` は `effect?.SetSource(input)` を呼び出します。
`ClearEffectChain` は `effect?.SetSource(null)`・`effect?.SetKernel(null)` を呼び出し、
`currentParameters = null`・`isFirst = true` にリセットします。
---
### 9. 公開API(WaveOpticsApi)
`public static class WaveOpticsApi` を提供します。
| メンバー | 説明 |
|---|---|
| `Version` | `OpticalApiVersion.Current` を返却します |
| `CreatePsfGenerator()` | `new FraunhoferPsfGenerator()` を返却します |
---
### 10. ローカライズ(Texts)
`Texts` クラスは `[AutoGenLocalizer]` 属性を持つ `partial` クラスとして宣言されます。
`YukkuriMovieMaker.Generator` のソースジェネレーターが `Texts.csv` を処理し、
各ロケールのリソースファイルを自動生成します。
対応言語:日本語(`ja-jp`)・英語(`en-us`)・中国語簡体字(`zh-cn`)・中国語繁体字(`zh-tw`)・
韓国語(`ko-kr`)・スペイン語(`es-es`)・アラビア語(`ar-sa`)・インドネシア語(`id-id`)
ローカライズキーの一覧は以下のとおりです。
| キー | ja-jp |
|---|---|
| `EffectName` | 波動光学 |
| `OutputGroup` | 出力 |
| `OpticsGroup` | 光学系 |
| `ApertureGroup` | 開口 |
| `AberrationGroup` | 波面収差 |
| `AmountName` | 適用量 |
| `GainName` | 利得 |
| `WavelengthName` | 波長 |
| `FNumberName` | F値 |
| `PixelPitchName` | 画素ピッチ |
| `KernelRadiusName` | カーネル半径 |
| `QualityName` | 品質 |
| `QualityDraft` | 高速 |
| `QualityStandard` | 標準 |
| `QualityHigh` | 高精度 |
| `ApertureShapeName` | 開口形状 |
| `CircularAperture` | 円形 |
| `RegularPolygonAperture` | 正多角形 |
| `BladeCountName` | 羽根枚数 |
| `BladeRotationName` | 開口回転 |
| `ObstructionName` | 中央遮蔽 |
| `DefocusName` | デフォーカス |
| `AstigmatismVerticalName` | 縦横非点収差 |
| `AstigmatismObliqueName` | 斜め非点収差 |
| `ComaHorizontalName` | 水平コマ収差 |
| `ComaVerticalName` | 垂直コマ収差 |
| `SphericalName` | 球面収差 |
| `TagDiffraction` | 回折 |
| `TagLens` | レンズ |
| `TagPsf` | 点像分布関数 |
| `TagOptics` | 光学 |
+1
ファイルの表示
@@ -0,0 +1 @@
github: routersys
+102
ファイルの表示
@@ -0,0 +1,102 @@
name: 不具合の報告
description: エラーが出る、強制終了する、出力が乱れる、README と違う動きをする、といった不具合を報告します。
title: "[Bug] "
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
脆弱性はここに書かず、リポジトリのセキュリティポリシーに従って非公開で報告してください。
README と実際の動きが違い、文書のほうが誤りだと考えるときは、文書の不備を使ってください。
- type: input
id: plugin-version
attributes:
label: プラグインのバージョン
description: GitHub のリリースか、配布パッケージの Readme.txt の見出しで確かめられます。
placeholder: v1.0.0
validations:
required: true
- type: input
id: ymm4-version
attributes:
label: YukkuriMovieMaker4 のバージョン
description: YukkuriMovieMaker4 のメインウィンドウのタイトルに表示されるバージョンを、そのまま書いてください。
placeholder: v4.56.1.0 Lite
validations:
required: true
- type: input
id: os
attributes:
label: Windows のバージョン
description: winver を実行し、ビルド番号まで書いてください。
placeholder: Windows 11 24H2, 26100.2605
validations:
required: true
- type: input
id: gpu
attributes:
label: GPU とドライバー
description: 描画や GPU に関わる不具合では必ず書いてください。デバイスマネージャーか dxdiag に表示される GPU の名前と、ドライバーのバージョンです。
- type: textarea
id: expected
attributes:
label: 期待した動き
description: 何が起きると考えたか。README に根拠があれば、その箇所も書いてください。
validations:
required: true
- type: textarea
id: actual
attributes:
label: 実際の動き
description: 実際に起きたこと。エラー画面が出たときは、その内容を省略せずに貼ってください。
validations:
required: true
- type: textarea
id: steps
attributes:
label: 再現の手順
description: |
新しいプロジェクトから不具合が起きるまでの操作を、番号を付けて書いてください。変えた設定の項目と値も書いてください。
プロジェクトファイルや素材は、zip に圧縮して添付できます。添付したファイルは誰でも見られます。プロジェクトファイルには素材を置いたフォルダーのパスが記録されるので、公開できない情報が無いかを確かめてください。
placeholder: |
1. 新しいプロジェクトを作る
2. アイテムを置き、本プラグインを使う
3. 設定を変える
4. 不具合が起きる
validations:
required: true
- type: dropdown
id: frequency
attributes:
label: 起きる頻度
description: ときどき起きるときは、何回試して何回起きたかを、下の「その他」の欄に書いてください。
options:
- 毎回起きる
- ときどき起きる
- 一度だけ起きた
validations:
required: true
- type: textarea
id: context
attributes:
label: その他
description: 一緒に使っているほかのプラグインや、関係すると思われることを書いてください。
- type: checkboxes
id: checks
attributes:
label: 報告の前に
options:
- label: 最新のリリースを使っています。
required: true
- label: 既存の Issue を検索し、同じ報告が無いことを確かめました。
required: true
+5
ファイルの表示
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: YukkuriMovieMaker4 本体の不具合
url: https://manjubox.net/contact/
about: 本体に原因がある不具合は、YukkuriMovieMaker4 の「ヘルプ」の「フィードバックを送信」か、公式サイトのお問い合わせから報告してください。
+63
ファイルの表示
@@ -0,0 +1,63 @@
name: 文書の不備
description: 誤り、書き漏れ、実際の動きとの食い違いがある文書を報告します。
title: "[Docs] "
labels: ["documentation"]
body:
- type: markdown
attributes:
value: |
実際の動きと文書が食い違うときは、ここで報告して構いません。動きのほうが誤りだと考えるときは、不具合の報告を使ってください。
- type: dropdown
id: location
attributes:
label: 文書
options:
- README
- 配布パッケージの Readme.txt
- 設定の項目の名前や説明
- 貢献の手引き、セキュリティポリシー、行動規範
- その他
validations:
required: true
- type: input
id: reference
attributes:
label: 文書の中の位置
description: 見出し、行番号、設定の項目の名前のどれかを書いてください。
placeholder: README の「制限事項」の 2 つ目の項目
validations:
required: true
- type: textarea
id: says
attributes:
label: 今の記述
description: そのまま引用してください。元の文書を開かずに検討できるようにするためです。
validations:
required: true
- type: textarea
id: problem
attributes:
label: どこが問題か
description: |
誤り、書き漏れ、曖昧さのどれに当たるかを書いてください。それによって読む人が何を取り違えるかも書いてください。
実際の動きと食い違っているときは、文書と動きのどちらを直すべきと考えるかも書いてください。
validations:
required: true
- type: textarea
id: suggestion
attributes:
label: 提案する文面
description: 具体的な文面があると、早く直せます。
- type: checkboxes
id: checks
attributes:
label: 報告の前に
options:
- label: 最新のリリースか、既定のブランチの最新の文書で確かめました。
required: true
+42
ファイルの表示
@@ -0,0 +1,42 @@
name: 機能の提案
description: 新しい機能や設定の項目、既存の動きの変更を提案します。
title: "[Proposal] "
labels: ["enhancement"]
body:
- type: textarea
id: problem
attributes:
label: 困っていること
description: 今のプラグインでできないことや、手間がかかることを、利用者の立場で書いてください。
validations:
required: true
- type: textarea
id: workaround
attributes:
label: 今はどうしているか
description: 今の回避策と、それにかかる手間を書いてください。回避策が無ければ、その旨を書いてください。
validations:
required: true
- type: textarea
id: proposal
attributes:
label: 提案する動き
description: どう動いてほしいかを書いてください。設定の項目を増やす提案では、項目の名前、範囲、既定値の案も書いてください。
- type: textarea
id: alternatives
attributes:
label: 検討したほかの方法
description: ほかに考えた方法があれば、それでは足りない理由と一緒に書いてください。
- type: checkboxes
id: checks
attributes:
label: 提案の前に
options:
- label: 既存の Issue を検索し、同じ提案が無いことを確かめました。
required: true
- label: 最新のリリースに同じ機能が無いことを確かめました。
required: true
+49
ファイルの表示
@@ -0,0 +1,49 @@
name: 使い方の質問
description: 使い方や、実際の動きが仕様どおりかを尋ねます。
title: "[Question] "
labels: ["question"]
body:
- type: markdown
attributes:
value: |
プラグインの不具合だと分かっているときは、不具合の報告を使ってください。
- type: textarea
id: question
attributes:
label: 質問
description: 背景を書く前に、質問を 1 文か 2 文で書いてください。
validations:
required: true
- type: textarea
id: goal
attributes:
label: 何をしようとしているか
description: つまずいている操作だけでなく、最終的に何を作りたいかを書いてください。
validations:
required: true
- type: textarea
id: tried
attributes:
label: 試したこと
description: 試した設定と、そのとき実際に起きたことを書いてください。
- type: input
id: plugin-version
attributes:
label: プラグインのバージョン
placeholder: v1.0.0
validations:
required: true
- type: checkboxes
id: checks
attributes:
label: 質問の前に
options:
- label: README の該当する節を読みました。
required: true
- label: 既存の Issue を検索し、同じ質問が無いことを確かめました。
required: true
+21
ファイルの表示
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Sergio Pedri
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+144 -23
ファイルの表示
@@ -1,49 +1,170 @@
========================================
波動光学 for YMM4 v1.0.0
波動光学 for YMM4 v2.0.0
========================================
YukkuriMovieMaker4(YMM4)上で動作する、フラウンホーファー回折理論に基づいて計算した
点像分布関数(PSF)で映像を畳み込む映像エフェクトプラグインです。
波長・F値・画素ピッチ・開口形状・ゼルニケ波面収差係数をパラメータとして設定でき、
円形開口・正多角形開口・中央遮蔽・6 種類の波面収差項に対応します。
各パラメータはアニメーションに対応しています。
YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想の像とみなし、
レンズの開口と波面収差から求めた点像分布関数で畳み込んで、
回折と収差によるにじみを描画する映像エフェクトプラグインです。
点像分布関数は、1点から出た光が撮像面でどう広がるかを表す関数です。
瞳関数は、開口の各点を通る光の振幅と位相を表す関数です。
振幅は波の揺れの大きさ、位相は波の進み具合です。
本プラグインは、瞳関数のフラウンホーファー回折を高速フーリエ変換で解いて
点像分布関数を求めます。
履歴フレーム、参照画像、深度情報、学習済みモデルは使用しません。
にじみの形は光学系と収差の設定から決定論的に決まり、同じ設定では常に
同じ形になります。
適用量、利得、波長、F値、画素ピッチ、開口回転、中央遮蔽、デフォーカス、
縦横非点収差、斜め非点収差、水平コマ収差、垂直コマ収差、球面収差の
13項目はアニメーションに対応しています。
エフェクトの種類一覧では「波動光学」として表示されます。
--------------------------------------------------------------------------------
■ 動作要件
--------------------------------------------------------------------------------
- OS : Windows 10 バージョン 2004 (ビルド 19041) 以降 / Windows 11 (64bit)
- YMM4 : YukkuriMovieMaker4(最新版を推奨)
- OS : Windows 10 バージョン2004(ビルド19041)以降、または
64ビット版のWindows 11
- YMM4 : YukkuriMovieMaker4の最新版を推奨します
- ランタイム : .NET 10.0
- GPU : Direct3D 12とDirect3D 11・12間の共有テクスチャおよび
共有フェンスを利用できるGPU
--------------------------------------------------------------------------------
■ 注意事項
--------------------------------------------------------------------------------
- AviUtl 非対応: 本プラグインは AviUtl 形式(.exo)への出力に対応していません。
- AviUtl非対応: 本プラグインはAviUtl向けのEXO出力に対応していません。
- 品質と計算負荷: 品質「高精度」では FFT 格子サイズが 512 になるため、パラメータ変更
時の計算負荷が増加します。リアルタイムプレビュー中にパラメータを頻繁に変更する
場合は「高速」への切り替えを検討してください。
- GPU非対応時: Direct3D 12デバイスを取得できない場合と、YMM4が使う
Direct3D 11デバイスが相互運用に必要なインターフェースを持たない場合は、
エフェクトを適用せず入力映像を表示します。GPUメモリが足りず
共有テクスチャを確保できない場合も同じです。
- カーネル半径と出力サイズ: 適用量が 0% より大きい場合、出力矩形は入力矩形よりも
カーネル半径分だけ拡張されます。
- 処理対象: 畳み込みには現在のフレームの色と不透明度だけを使用します。
履歴フレーム、外部画像、深度情報、学習済みモデルは使用しません。
素材に透明でない画素が無いときは、エフェクトを適用せず入力映像を
表示します。
- 適用量が 0% の場合: 畳み込みは実行されず、入力がそのまま出力されます。
- 計算モデル: 計算は単色のフラウンホーファー回折に限ります。白色光の
ように波長の混ざった光は扱いません。点像分布関数は画面のどこでも同じで、
像の位置や素材の奥行きで変わるにじみは扱いません。畳み込みは、画素の値を
そのまま重み付けして足し合わせます。画素の値を光の強さに比例する値へ
直してから畳み込む処理はしません。
- 計算モデルの制限: 計算は単色のフラウンホーファー回折に限定されます。
白色光や多色光のシミュレーションには対応していません。
- 計算領域: 透明な部分も含む素材全体の矩形の上下左右に16画素の余白を
加えた大きさを計算領域とし、長辺は8192画素が上限です。素材の長辺が
8160画素を超える場合は、エフェクトを適用せず入力映像を表示します。
- カーネル半径の範囲: カーネル半径は 1 〜 15 px の範囲で指定できます
(カーネルサイズ最大 31×31)。
- カーネル半径: 1〜15画素です。カーネルは、畳み込みの重みを正方形に
並べたものです。正方形は、中心から上下左右にカーネル半径の画素数まで
広がります。正方形の外に届く光は捨て、カーネルの値の和が1になるように
正規化します。
- 本プラグインを使用する前に、YMM4 プロジェクトファイルのバックアップを
作成することを推奨します。
- 品質と収差: 品質は、瞳関数を置く格子の大きさを切り替えます。格子は
瞳関数の値を縦横に並べた表で、1つ1つの値を標本と呼びます。格子が粗いと、
大きな波面収差で位相が急に変わる所を表しきれず、点像分布関数の形が
崩れます。波面収差を大きくするときは、品質を上げてください。
- 中央遮蔽: 中央遮蔽で開口をほとんどふさぎ、瞳関数の格子に光の通る標本が
1つも無くなる設定では、エフェクトを適用せず入力映像を表示します。
品質を上げると起きにくくなります。
- 処理負荷: GPUメモリ使用量は、計算領域の大きさに応じて増えます。
作業用のバッファーとして、計算領域の1画素につき32バイトをGPUに
確保します。処理量は、素材全体の大きさと畳み込む範囲の大きさに応じて
増えます。畳み込む範囲は、透明でない画素をすべて囲む最小の矩形を
カーネル半径だけ広げ、外側へ4画素単位にそろえた範囲です。畳み込みは、
横方向と縦方向の1次元の重みを1組とした、何組かの和で近似して行います。
収差を入れると組の数が増えて、計算が重くなります。品質を上げると、
点像分布関数の計算が重くなります。
- キャッシュ: 素材の大きさと色と不透明度が変わらず、「利得」と「適用量」
以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。
利得だけを変えたフレームでは、再利用した畳み込みに利得を掛け直します。
適用量だけを変えたフレームでは、混ぜる割合だけを変えます。動画や口パクの
ように素材の内容が変わるフレームと、「利得」と「適用量」以外の項目を
アニメーションで変えたフレームでは、毎回計算し直すので処理が重く
なります。素材が変わったかどうかを調べる計算は、再利用するフレームでも
毎フレーム行います。
- 適用量0%: 適用量は、入力映像と、利得を掛けた結果を混ぜる割合です。
適用量が0%のときは入力を変更せず、畳み込みの計算も行いません。
- 利得: 利得は、畳み込んだ結果に掛ける倍率です。100%で画素の値の総和を
保ちます。利得を掛けた結果は、入力映像と混ぜる前に、各成分が表せる
最大の値で打ち切ります。
- 再現性: 計算は決定論的で、時間値や乱数を使用しません。同じGPUと
ドライバーでは、同じ素材と同じ設定から常に同じ結果になります。
- 透明部分: 畳み込みは不透明度にも掛かるので、素材の縁の外にも半透明の
にじみが広がります。出力の範囲は、素材の範囲と畳み込む範囲を合わせた
ものです。適用量が0%のときは、素材の範囲のままです。
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ
新しい正式版を確認します。更新情報を取得できない場合は通知せず、
そのまま動作します。プレリリースは通知の対象に含めません。
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを
作成することを推奨します。
--------------------------------------------------------------------------------
■ 不具合の報告
--------------------------------------------------------------------------------
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で
送信します。同意は求めず、常に送信します。
送信する情報は次のとおりです。
例外 : 型の完全名、メッセージ、スタックトレース
発生位置 : モジュール名、関数名、ファイル名、行番号
プラグイン : アセンブリ名、バージョン
実行環境 : OSの名前とバージョン、.NETのバージョン、
CPUのアーキテクチャ、論理プロセッサ数
識別子 : YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する
識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値に
なります。メッセージとファイル名に含まれる利用者名などの文字列は、送信の
前に置き換えます。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
送信するのは想定していない例外だけです。YMM4が本プラグインのエフェクトを
作るとき、フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、
Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後は
YMM4へそのまま渡します。更新の確認では、更新情報の取得と比較で起きた例外は
報告しません。通知の文を組み立てて表示するときに起きた例外は報告し、
YMM4へは渡しません。画面の操作やバックグラウンドの処理で未処理になった
例外も報告しますが、本プラグインのコードが関わる例外に限ります。
本プラグインの外で起きた例外は送信しません。
次の失敗は送信しません。
効果をかけないだけで済ませるもの : Direct3D 12デバイスを取得できない、
YMM4のDirect3D 11デバイスが
相互運用に必要なインターフェースを
持たない、GPUメモリが足りず
共有テクスチャを確保できない、
素材の長辺が8160画素を超える、
開口に光の通る標本が無いときに、
エフェクトを適用せず入力映像を
表示したとき
更新の確認の通信の失敗 : manjubox.netとGitHubのどちらへも
接続できない
送信できなかった報告はYMM4のユーザーフォルダーへ退避します。
次にYMM4を起動したあと、本プラグインのエフェクトを生成するか、
同じくYMM4-Telemetryで報告する別のプラグインが動き始めると、
退避した報告を1回の起動で10件まで送り直します。
送信も再送も非同期に行うため、通信を待って起動と描画が遅くなることは
ありません。
--------------------------------------------------------------------------------
■ 免責事項
--------------------------------------------------------------------------------
本プラグインは MIT ライセンスのもとで公開されています。
本ソフトウェアは「現状のまま」提供されており、明示・黙示を問わず、
本プラグインはMITライセンスのもとで公開されています。
本ソフトウェアは「現状のまま」提供されており、明示または黙示を問わず、
商品性、特定目的への適合性、および権利非侵害に関する保証を含む、
いかなる種類の保証も行いません。
作者は、本プラグインの使用または使用不能に起因するいかなる損害についても、
一切の責任を負いません。
ご利用は自己責任でお願いします。
--------------------------------------------------------------------------------
■ サードパーティライセンス
--------------------------------------------------------------------------------
本プラグインはComputeWeave(MIT License)を同梱しています。
ライセンスの全文は同梱のLICENSEフォルダー(ComputeWeave.txt)に収録しています。
ComputeWeave : Copyright (c) 2024 Sergio Pedri
--------------------------------------------------------------------------------
■ ライセンス
--------------------------------------------------------------------------------
+87
ファイルの表示
@@ -0,0 +1,87 @@
<!--
当てはまらない節は消してください。「関連する Issue」と「動きの変更」の節は残し、該当しないときは「なし」と書いてください。
-->
## 概要
<!--
何をどう変えたか。なぜその変更が必要か。
-->
## 関連する Issue
<!--
新しい機能、設定の項目や既定値の変更、大きめの不具合の修正、意図して出力を変える変更、互換性を損なう変更、コードの構成を大きく変える変更は、先に Issue で合意してください。
Issue が無い変更では、下の行を「なし」に書き換えてください。
-->
Closes #
## 変更の種類
<!-- 当てはまるものを残してください。 -->
- 不具合の修正
- 機能の追加
- 動きの変更
- 性能の改善
- テストの追加
- 依存関係の更新
- 文書
- ビルド、リリース
## 動きの変更
<!--
利用者から見て何が変わるか。設定の項目、既定値、出力の結果、エラーの出方の変化も含みます。
保存済みのプロジェクトの結果が変わるなら、必ず書いてください。
-->
## 検証
<!--
手元で実際に確かめた結果を書いてください。
- ビルドの結果と、テストのプロジェクトがあればテストの結果
- YukkuriMovieMaker4 で実際に動かして確かめたこと
- 実行できなかったテストと、その理由
実際に動かして観察したこと、コードを読んで判断したこと、推測したことを分けて書いてください。
-->
使った YukkuriMovieMaker4 のバージョン:
GPU に関わる変更では、使った GPU とドライバー:
## 確認
<!-- テストのプロジェクトが無いリポジトリでは、実装とテストを分ける項目を消してください。 -->
- [ ] 1 つの目的の変更だけを含み、関係の無い整理や整形を含めていない。
- [ ] どのコミットも、それ単独でビルドが通る。
- [ ] 実装の変更と、それを確かめるテストを、別のコミットに分けた。
- [ ] コミットの件名は日本語で書き、50 文字以内に収め、「〜する」の形で終えた。日本語で書けない場合は、その旨を「レビューで見てほしい点」に書いた。
- [ ] コミットの本文は、リリースノートでの変更の分類を指定する行を求められたときだけ書いた。
- [ ] 変更する箇所で既に使われている実装のパターンに従った。
- [ ] 新しく書いたコードにコメントを入れず、コメントアウトしたコードも残していない。既存のコメントとドキュメントコメントは残した。
- [ ] 自分の変更で増えたビルドの警告を直した。
- [ ] 出力を変えるつもりの無い変更では、変更前と変更後で出力が一致することを確かめた。
- [ ] この変更と関係の無い依存関係の更新を含めていない。
- [ ] 動きを変えた場合、README を直した。`.github/Plugin_Readme.txt` があるリポジトリでは、それも直した。
- [ ] バージョンを上げる変更を含めていない。
## 性能の改善を主張する場合
<!-- それ以外の場合は、この節ごと消してください。 -->
- [ ] 同じ機材、ドライバー、設定、電源の条件で、変更前と変更後のビルドを交互に繰り返し測った。
- [ ] 測定の間を空け、ほかのプロセスが GPU を使っていない状態で測った。
- [ ] 正しさの確認と性能の測定を、別々に実行した。
<!--
測定の条件と、測定値。
-->
## レビューで見てほしい点
<!--
判断に迷った点、意見を聞きたい点、意図して外した部分とその理由。
-->
+306 -33
ファイルの表示
@@ -14,29 +14,18 @@ jobs:
steps:
- name: ソースコードのチェックアウト
uses: actions/checkout@v4
uses: actions/checkout@v7
with:
submodules: recursive
fetch-depth: 0
- name: .NET SDK のセットアップ
uses: actions/setup-dotnet@v4
uses: actions/setup-dotnet@v6
with:
dotnet-version: '10.0.x'
- name: fxc.exe の検索
id: fxc
shell: pwsh
run: |
$fxc = Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\bin" -Recurse -Filter "fxc.exe" |
Where-Object { $_.FullName -like "*x64*" } |
Sort-Object FullName -Descending |
Select-Object -First 1
if (-not $fxc) {
Write-Error "fxc.exe が見つかりませんでした。"
exit 1
}
Write-Host "fxc.exe の場所: $($fxc.FullName)"
echo "FXC_PATH=$($fxc.FullName)" >> $env:GITHUB_OUTPUT
- name: MSBuild のセットアップ
uses: microsoft/setup-msbuild@v3
- name: YMM4 最新リリースの取得と解凍
id: ymm4
@@ -64,25 +53,53 @@ jobs:
echo "TAG=$tag" >> $env:GITHUB_OUTPUT
echo "VERSION=$($tag.TrimStart('v'))" >> $env:GITHUB_OUTPUT
- name: resx ファイルの生成(初回ビルド)
- name: バージョン記載の照合
shell: pwsh
run: |
$proj = "Wave Optics/WaveOptics.csproj"
dotnet build "$proj" `
-c Release `
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
-p:FxcPath="${{ steps.fxc.outputs.FXC_PATH }}" `
-p:Platform=x64 `
-p:SkipPluginDeploy=true
$tag = "${{ steps.version.outputs.TAG }}"
$version = "${{ steps.version.outputs.VERSION }}"
$problems = @()
$csprojPath = "WaveOptics/WaveOptics.csproj"
$csproj = Get-Content $csprojPath -Raw
if (-not $csproj.Contains("<Version>$version</Version>")) {
$current = if ($csproj -match '<Version>([^<]*)</Version>') { $Matches[1] } else { "記載なし" }
$problems += "$csprojPath の <Version> が $current です。$version にしてください。"
}
$readmePath = ".github/Plugin_Readme.txt"
$readme = Get-Content $readmePath -Raw
if (-not $readme.Contains(" 波動光学 for YMM4 $tag")) {
$current = if ($readme -match '(?m)^ 波動光学 for YMM4 (\S+)') { $Matches[1] } else { "記載なし" }
$problems += "$readmePath の見出しが $current です。$tag にしてください。"
}
if ($problems.Count -eq 0) {
Write-Host "バージョン記載は $tag と一致しています"
exit 0
}
foreach ($problem in $problems) {
Write-Host "::error::$problem"
}
Write-Host "::error::リリースの対象は $tag が指すコミットです。タグを付けた後で main へ訂正を積んでも、その訂正はリリースに入りません。タグを削除し、記載を直したコミットを積んでから付け直してください。"
exit 1
- name: シェーダーのビルド
shell: pwsh
run: |
msbuild WaveOptics.Shader/WaveOptics.Shader.vcxproj `
/p:Configuration=Release `
/p:Platform=Win32 `
/nologo
- name: プロジェクトのビルド
shell: pwsh
run: |
$proj = "Wave Optics/WaveOptics.csproj"
$proj = "WaveOptics/WaveOptics.csproj"
dotnet build "$proj" `
-c Release `
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
-p:FxcPath="${{ steps.fxc.outputs.FXC_PATH }}" `
-p:Platform=x64 `
-p:SkipPluginDeploy=true
@@ -92,8 +109,8 @@ jobs:
dotnet build WaveOptics.Tests/WaveOptics.Tests.csproj `
-c Release `
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
-p:FxcPath="${{ steps.fxc.outputs.FXC_PATH }}" `
-p:Platform=x64 `
-p:SkipPluginDeploy=true `
-maxcpucount:1
- name: テストの実行
@@ -101,22 +118,30 @@ jobs:
run: |
dotnet test WaveOptics.Tests/WaveOptics.Tests.csproj `
--no-build `
--no-restore `
-c Release `
-p:Platform=x64
-p:Platform=x64 `
-p:SkipPluginDeploy=true
- name: パッケージの作成
id: package
shell: pwsh
run: |
$version = "${{ steps.version.outputs.TAG }}"
$outDir = "Wave Optics/bin/x64/Release/net10.0-windows10.0.19041.0"
$outDir = "WaveOptics/bin/x64/Release/net10.0-windows10.0.19041.0"
$stageRoot = "stage/WaveOptics"
$pkgName = "WaveOptics_$version.ymme"
New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
Copy-Item "$outDir/WaveOptics.dll" "$stageRoot/"
Copy-Item "$outDir/WaveOptics.Abstractions.dll" "$stageRoot/"
foreach ($dll in @("$outDir/plugin/WaveOptics.dll", "$outDir/WaveOptics.Abstractions.dll")) {
if (-not (Test-Path $dll)) {
Write-Error "ビルド結果に $(Split-Path $dll -Leaf) が見つかりませんでした: $dll"
exit 1
}
Copy-Item $dll "$stageRoot/"
}
foreach ($lang in @("ar-sa", "en-us", "es-es", "id-id", "ko-kr", "zh-cn", "zh-tw")) {
$src = "$outDir/$lang"
@@ -126,16 +151,264 @@ jobs:
}
}
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
$readme = Get-Content "$stageRoot/Readme.txt" -Raw
if (-not $readme.Contains(" 波動光学 for YMM4 $version")) {
Write-Error "同梱する Readme.txt の見出しが $version と一致しません"
exit 1
}
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
echo "PKG_NAME=$pkgName" >> $env:GITHUB_OUTPUT
- name: 変更履歴の作成
id: changelog
shell: pwsh
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.version.outputs.TAG }}
REPOSITORY: ${{ github.repository }}
SERVER_URL: ${{ github.server_url }}
PACKAGE: ${{ steps.package.outputs.PKG_NAME }}
run: |
$tag = $env:TAG
$repository = $env:REPOSITORY
$server = $env:SERVER_URL
$code = [char]0x60
$fence = [string]::new($code, 3)
$unit = [char]0x1f
$record = [char]0x1e
$previous = ""
$candidates = @(git tag --list "v*" --merged $tag --sort=-creatordate | Where-Object { $_ -ne $tag })
if ($candidates.Count -gt 0) {
$previous = $candidates[0]
}
Write-Host "直前のタグ: $previous"
$range = if ($previous) { "$previous..$tag" } else { $tag }
$log = (@(git log "--format=%H%x1f%s%x1f%an%x1f%ad%x1f%b%x1e" --date=short $range) -join "`n") -split $record
$commits = @()
foreach ($entry in $log) {
if (-not $entry.Trim()) { continue }
$fields = $entry.TrimStart("`n") -split $unit
if ($fields.Count -lt 5) { continue }
$commits += [pscustomobject]@{
Sha = $fields[0]
Subject = $fields[1]
Name = $fields[2]
Date = $fields[3]
Body = $fields[4]
Login = ""
Avatar = ""
}
}
Write-Host "コミット数: $($commits.Count)"
$categories = [ordered]@{
A = @{ Title = "追加"; Symbol = "+"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
M = @{ Title = "変更"; Symbol = "~"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
D = @{ Title = "削除"; Symbol = "-"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
F = @{ Title = "修正"; Symbol = "!"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
}
foreach ($commit in $commits) {
if (-not $commit.Body) { continue }
foreach ($bodyLine in ($commit.Body -split "`n")) {
$trimmed = $bodyLine.Trim()
if ($trimmed -notmatch '^・(.+)-([AMDF])$') { continue }
$categories[$Matches[2]].Items.Add([pscustomobject]@{ Text = $Matches[1]; Sha = $commit.Sha })
}
}
$pending = [System.Collections.Generic.HashSet[string]]::new()
foreach ($commit in $commits) {
[void]$pending.Add($commit.Sha)
}
$accounts = @{}
$page = 1
while ($pending.Count -gt 0 -and $page -le 20) {
$rows = @()
try {
$rows = @(gh api "repos/$repository/commits?sha=$tag&per_page=100&page=$page" --jq '.[] | [.sha, (.author.login // ""), (.author.avatar_url // "")] | @tsv')
}
catch {
Write-Host "コミットの作者を取得できませんでした: $($_.Exception.Message)"
break
}
if ($LASTEXITCODE -ne 0 -or $rows.Count -eq 0) { break }
foreach ($row in $rows) {
$fields = $row -split "`t"
if ($fields.Count -lt 3) { continue }
if ($pending.Remove($fields[0])) {
$accounts[$fields[0]] = @{ Login = $fields[1]; Avatar = $fields[2] }
}
}
if ($rows.Count -lt 100) { break }
$page++
}
foreach ($commit in $commits) {
if ($accounts.ContainsKey($commit.Sha)) {
$commit.Login = $accounts[$commit.Sha].Login
$commit.Avatar = $accounts[$commit.Sha].Avatar
}
}
$emptyTree = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
$base = if ($previous) { $previous } else { $emptyTree }
$shortstat = (@(git diff --shortstat $base $tag) -join " ")
$changedFiles = 0
$insertions = 0
$deletions = 0
if ($shortstat -match "(\d+) file") { $changedFiles = [int]$Matches[1] }
if ($shortstat -match "(\d+) insertion") { $insertions = [int]$Matches[1] }
if ($shortstat -match "(\d+) deletion") { $deletions = [int]$Matches[1] }
$diffStat = @(git diff --stat $base $tag)
$tagDate = (git log -1 "--format=%ad" --date=short $tag)
$contributors = @($commits |
Group-Object -Property { if ($_.Login) { $_.Login } else { $_.Name } } |
Sort-Object -Property Count -Descending)
function Get-Icon($avatar, $login, $size) {
if (-not $avatar) { return "" }
$sized = if ($avatar.Contains("?")) { "$avatar&s=$($size * 2)" } else { "$avatar" + "?s=$($size * 2)" }
return "<img src=""$sized"" width=""$size"" height=""$size"" alt=""$login""> "
}
$package = Get-Item $env:PACKAGE
$size = [math]::Round($package.Length / 1MB, 2)
$body = [System.Collections.Generic.List[string]]::new()
$body.Add("## 概要")
$body.Add("")
$body.Add("| 項目 | 内容 |")
$body.Add("|---|---|")
$body.Add("| タグ | [$tag]($server/$repository/tree/$tag) |")
$body.Add("| 公開日 | $tagDate |")
if ($previous) {
$body.Add("| 直前のリリース | [$previous]($server/$repository/releases/tag/$previous) |")
}
$body.Add("| コミット数 | $($commits.Count) |")
$body.Add("| 貢献者 | $($contributors.Count) 名 |")
$body.Add("| 変更されたファイル | $changedFiles |")
$body.Add("| 追加された行 | $insertions |")
$body.Add("| 削除された行 | $deletions |")
$hasHighlights = ($categories.Values | ForEach-Object { $_.Items.Count } | Measure-Object -Sum).Sum -gt 0
if ($hasHighlights) {
$body.Add("")
$body.Add("## 主な変更")
foreach ($key in $categories.Keys) {
$category = $categories[$key]
if ($category.Items.Count -eq 0) { continue }
$body.Add("")
$body.Add("### [$($category.Symbol)] $($category.Title)")
$body.Add("")
foreach ($item in $category.Items) {
$short = $item.Sha.Substring(0, 7)
$body.Add("- $($item.Text) ([$code$short$code]($server/$repository/commit/$($item.Sha)))")
}
}
}
$body.Add("")
$body.Add("## ダウンロード")
$body.Add("")
$body.Add("| ファイル | サイズ |")
$body.Add("|---|---|")
$body.Add("| $($package.Name) | $size MB |")
$body.Add("")
$body.Add("## 貢献者")
$body.Add("")
$body.Add("| 貢献者 | コミット数 |")
$body.Add("|---|---|")
foreach ($contributor in $contributors) {
$first = $contributor.Group[0]
if ($first.Login) {
$name = (Get-Icon $first.Avatar $first.Login 40) + "[@$($first.Login)]($server/$($first.Login))"
}
else {
$name = $first.Name
}
$body.Add("| $name | $($contributor.Count) |")
}
$body.Add("")
$body.Add("## 変更履歴")
$body.Add("")
$body.Add("| コミット | 内容 | 貢献者 | 日付 |")
$body.Add("|---|---|---|---|")
$maximumCommits = 300
$listed = 0
foreach ($commit in $commits) {
if ($listed -ge $maximumCommits) { break }
$short = $commit.Sha.Substring(0, 7)
$subject = $commit.Subject -replace '\|', '\|'
if ($commit.Login) {
$author = (Get-Icon $commit.Avatar $commit.Login 20) + "[@$($commit.Login)]($server/$($commit.Login))"
}
else {
$author = $commit.Name
}
$body.Add("| [$code$short$code]($server/$repository/commit/$($commit.Sha)) | $subject | $author | $($commit.Date) |")
$listed++
}
if ($commits.Count -gt $maximumCommits) {
$body.Add("")
$body.Add("残り $($commits.Count - $maximumCommits) 件のコミットは省略しました。")
}
if ($diffStat.Count -gt 0) {
$body.Add("")
$body.Add("## 変更されたファイル")
$body.Add("")
$body.Add("<details>")
$body.Add("<summary>差分の統計</summary>")
$body.Add("")
$body.Add($fence)
$maximumStatLines = 200
$shown = 0
foreach ($line in $diffStat) {
if ($shown -ge $maximumStatLines) { break }
$body.Add($line)
$shown++
}
if ($diffStat.Count -gt $maximumStatLines) {
$body.Add("... 残り $($diffStat.Count - $maximumStatLines) 行は省略しました。")
}
$body.Add($fence)
$body.Add("")
$body.Add("</details>")
}
if ($previous) {
$body.Add("")
$body.Add("## 全ての変更")
$body.Add("")
$body.Add("$server/$repository/compare/$previous...$tag")
}
$path = "release-body.md"
Set-Content -Path $path -Value ($body -join "`n") -Encoding utf8NoBOM
if (-not (Test-Path $path)) {
throw "変更履歴を作成できませんでした。"
}
Write-Host "変更履歴の行数: $($body.Count)"
$global:LASTEXITCODE = 0
- name: GitHub リリースの作成
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
with:
name: ${{ steps.version.outputs.TAG }}
body_path: .github/CHANGELOG.md
body_path: release-body.md
files: ${{ steps.package.outputs.PKG_NAME }}
draft: false
prerelease: false
+3 -1
ファイルの表示
@@ -362,4 +362,6 @@ MigrationBackup/
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
FodyWeavers.xsd
# Stryker.NET
StrykerOutput/
+6
ファイルの表示
@@ -1,3 +1,9 @@
[submodule "YukkuriMovieMaker.Generator"]
path = YukkuriMovieMaker.Generator
url = https://github.com/manju-summoner/YukkuriMovieMaker.Generator.git
[submodule "YMM4-GitHubUpdateNotifier"]
path = YMM4-GitHubUpdateNotifier
url = https://github.com/routersys/YMM4-GitHubUpdateNotifier.git
[submodule "YMM4-Telemetry"]
path = YMM4-Telemetry
url = https://github.com/routersys/YMM4-Telemetry.git
+81
ファイルの表示
@@ -0,0 +1,81 @@
# Contributor Covenant 行動規範
## 私たちの約束
メンバー、貢献者、リーダーである私たちは、年齢、体格、目に見える障害と目に見えない障害、民族、性的特徴、性自認と性表現、経験の程度、教育、社会経済的地位、国籍、外見、人種、宗教、性的アイデンティティと性的指向を問わず、コミュニティへの参加を誰にとっても嫌がらせの無いものにすることを誓います。
私たちは、開かれていて誰もが歓迎される、多様で包摂的な、健全なコミュニティを作るように行動し、交流することを誓います。
## 私たちの基準
コミュニティのよい環境を作る行動の例は、次のとおりです。
- ほかの人に共感と思いやりを示す
- 異なる意見、視点、経験を尊重する
- 建設的な意見を伝え、また快く受け入れる
- 自分たちの誤りに責任を持ち、影響を受けた人に謝り、その経験から学ぶ
- 自分個人にとってだけでなく、コミュニティ全体にとって最善のことを考える
受け入れられない行動の例は、次のとおりです。
- 性的な言葉や画像を使うこと、どのような形であれ、相手に性的な関心を向けることや言い寄ること
- 荒らし、侮辱的または軽蔑的な発言、個人攻撃や政治的な攻撃
- 公の場か私的な場かを問わない嫌がらせ
- 住所やメールアドレスなど、ほかの人の個人情報を明示の許可なく公開すること
- 仕事の場で不適切と合理的に考えられるその他の行為
## 執行の責任
コミュニティリーダーは、受け入れられる行動の基準を明確にし、それを守らせる責任を負います。不適切、脅迫的、攻撃的、または有害と判断した行動には、適切で公正な是正措置をとります。
コミュニティリーダーは、この行動規範に沿わないコメント、コミット、コード、Wiki の編集、Issue、その他の貢献を削除、編集、または却下する権利と責任を持ちます。モデレーションの判断については、適切な場合に理由を伝えます。
## 適用範囲
この行動規範は、コミュニティのあらゆる場で適用されます。個人が公の場でコミュニティを公式に代表しているときにも適用されます。コミュニティを代表しているときとは、たとえば、公式のメールアドレスを使うとき、公式のソーシャルメディアのアカウントから投稿するとき、オンラインやオフラインのイベントで任命された代表として行動するときです。
## 執行
虐待的な言動、嫌がらせ、その他の受け入れられない行動は、執行を担当するコミュニティリーダーへ github.routersys@gmail.com で報告できます。コミュニティリーダーは、すべての苦情を速やかかつ公正に確認し、調査します。
すべてのコミュニティリーダーは、事案を報告した人のプライバシーと安全を尊重する義務を負います。
## 執行のガイドライン
コミュニティリーダーは、この行動規範に違反すると判断した行動への処置を決めるとき、次に示すコミュニティへの影響に応じたガイドラインに従います。
### 1. 是正
コミュニティへの影響: 不適切な言葉づかいや、コミュニティの中で、仕事の場にふさわしくない、または歓迎されないと判断されるその他の行動。
処置: コミュニティリーダーが、非公開の書面による警告を送ります。違反の内容を明らかにし、その行動がなぜ不適切だったかを説明します。公の場での謝罪を求めることがあります。
### 2. 警告
コミュニティへの影響: 1 回の出来事、または一連の行動による違反。
処置: 行動が続いた場合の処置を示した警告を送ります。警告を受けた人は、定められた期間、関係する人々とやり取りしてはいけません。行動規範を執行する人々へ、求められていないのに接触することも、これに含まれます。コミュニティの場だけでなく、ソーシャルメディアなど外部の場でのやり取りも避けなければなりません。これらの条件に違反すると、一時的または永久的な参加禁止につながることがあります。
### 3. 一時的な参加禁止
コミュニティへの影響: 不適切な行動を続けることを含む、コミュニティの基準への重大な違反。
処置: 定められた期間、コミュニティとのあらゆるやり取りと、コミュニティに向けた公の発信を禁止します。この期間中は、公の場か私的な場かを問わず、関係する人々とのやり取りを認めません。行動規範を執行する人々へ、求められていないのに接触することも、これに含まれます。これらの条件に違反すると、永久的な参加禁止につながることがあります。
### 4. 永久的な参加禁止
コミュニティへの影響: コミュニティの基準に繰り返し違反すること。不適切な行動を続けること、個人への嫌がらせ、特定の属性を持つ人々への攻撃や中傷も、これに当たります。
処置: コミュニティの中でのあらゆる公のやり取りを、永久に禁止します。
## 出典
この行動規範は、[Contributor Covenant][homepage] のバージョン 2.0 を基にしています。原文は https://www.contributor-covenant.org/version/2/0/code_of_conduct.html にあります。日本語の文は、公式の日本語訳 https://www.contributor-covenant.org/ja/version/2/0/code_of_conduct/ を基に、原文と照らし合わせて改めたものです。
Contributor Covenant は、[クリエイティブ・コモンズ 表示 4.0 国際 ライセンス](https://creativecommons.org/licenses/by/4.0/deed.ja)のもとで提供されています。
コミュニティへの影響に応じたガイドラインは、[Mozilla の行動規範の執行の段階](https://github.com/mozilla/diversity)に着想を得ています。
[homepage]: https://www.contributor-covenant.org
この行動規範についてのよくある質問と回答は、https://www.contributor-covenant.org/faq にあります。ほかの言語の訳は、https://www.contributor-covenant.org/translations にあります。
+168
ファイルの表示
@@ -0,0 +1,168 @@
# 貢献の手引き
本プラグインへの貢献に関心を持っていただき、ありがとうございます。この手引きは、Issue の立て方、プルリクエストの作り方、変更の確かめ方、コードとコミットの書き方を定めます。
本プラグインでできることとできないことは、[README](README.md) に書いてあります。まず README を読んでください。
---
## 目次
1. [貢献の進め方](#貢献の進め方)
2. [開発環境](#開発環境)
3. [Issue](#issue)
4. [プルリクエスト](#プルリクエスト)
5. [検証](#検証)
6. [コードの規約](#コードの規約)
7. [コミットの規約](#コミットの規約)
8. [行動規範](#行動規範)
---
## 貢献の進め方
誤字の修正、文書の修正、軽微な不具合の修正は、そのままプルリクエストを送ってください。
新しい機能、設定の項目や既定値の変更、大きめの不具合の修正、意図して出力を変える変更、互換性を損なう変更、コードの構成を大きく変える変更は、先に Issue を立ててください。実装を始める前に、意図する動きと変更の範囲について合意するためです。どちらに当たるか迷ったときも、Issue を立ててください。
脆弱性は Issue に書かず、[セキュリティポリシー](SECURITY.md)に従って非公開で報告してください。
Issue とプルリクエストは、日本語か英語で書いてください。
---
## 開発環境
| 項目 | 要件 |
|---|---|
| OS | Windows 10 バージョン 2004 以降の 64bit 版 |
| SDK | .NET 10 |
| YukkuriMovieMaker4 | ビルドがインストール先の DLL を参照するため、手元に入れておく |
| シェーダーのビルド | HLSL をビルドのときにコンパイルするリポジトリでは Windows SDK が要る。シェーダーを `.vcxproj` でビルドするリポジトリでは、Visual Studio 2026 の「C++ によるデスクトップ開発」も要る |
### 取得
リポジトリをフォークし、自分のフォークをクローンしてください。リポジトリはサブモジュールを含むことがあるので、`--recursive` を付けます。
```console
git clone --recursive https://github.com/<自分のアカウント>/<リポジトリ名>.git
```
`--recursive` を付けずにクローンしたときは、後から次のコマンドでサブモジュールを取得できます。
```console
git submodule update --init --recursive
```
作業は `main` から切ったブランチで行ってください。
### YukkuriMovieMaker4 の場所
YukkuriMovieMaker4 のインストール先は、MSBuild のプロパティ `YMM4DirPath` で渡します。値の末尾には `\` を付けてください。
- コマンドラインでは、`-p:YMM4DirPath="<インストール先>\"` を付けてビルドします。PowerShell 7 以降で実行してください。Windows PowerShell 5.1 と cmd では、末尾の `\"` が正しく渡らないため、末尾を `\\"` と書いてください。
- Visual Studio でビルドするときは、プラグインのプロジェクトのフォルダーか、その上のフォルダーに `Directory.Build.props` があれば、その `YMM4DirPath` を手元で書き換えます。無ければ、環境変数 `YMM4DirPath` を設定します。書き換えた `Directory.Build.props` はコミットに含めないでください。サブモジュールの中にある `Directory.Build.props` は書き換えないでください。
### ビルド
ソリューションを開き、Release でビルドしてください。
シェーダーを `.vcxproj` でビルドするリポジトリでは、コマンドラインのビルドに Visual Studio の MSBuild を使ってください。.NET SDK の `dotnet` コマンドは `.vcxproj` を扱えません。テストは、`dotnet test <名前>.Tests\<名前>.Tests.csproj` のようにテストのプロジェクトのファイルを指定して実行してください。ビルドの手順は、`.github/workflows/release.yml` があればそこに書いてあります。
多くのリポジトリでは、ビルドの後にプラグインが YukkuriMovieMaker4 の `user\plugin` フォルダーへ自動でコピーされます。
- YukkuriMovieMaker4 を起動したままだと、コピーの段階で失敗します。ビルドの前に終了してください。
- 配布版のプラグインを入れているときは、同じ名前のファイルが上書きされます。
- コマンドラインでソリューションをビルドしたときはコピーしないリポジトリがあります。その場合は、プラグインのプロジェクトを指定してビルドしてください。
- `.csproj` に `SkipPluginDeploy` の条件があるリポジトリでは、`-p:SkipPluginDeploy=true` を付けるとコピーせずにビルドできます。
---
## Issue
Issue はテンプレートから立ててください。不具合の報告、文書の不備、機能の提案、使い方の質問の 4 つがあります。
不具合の報告には、次の内容を書いてください。
- 期待した動きと、実際の動き
- 再現の手順。できれば、問題が起きる最小のプロジェクトファイルや素材
- プラグインのバージョン、YukkuriMovieMaker4 のバージョン、Windows のバージョン
- 描画や GPU に関わる不具合では、GPU の名前とドライバーのバージョン
- エラー画面に出た内容。省略せずに貼ってください
ときどきしか起きない不具合も、確実な再現の手順が無いまま報告して構いません。何回試して何回起きたかと、どの操作の後に起きたかを書いてください。
コードを読んで見つけた不具合を報告するときは、実際に再現を確かめたかどうかも書いてください。
Issue に添付したファイルは、誰でも見られます。プロジェクトファイルには、素材を置いたフォルダーのパスが記録されています。パスにユーザー名が含まれることがあるので、公開できない情報が無いかを確かめてから添付してください。
不具合の情報を自動で送信するプラグインでも、Issue での報告には意味があります。自動で送られるのは、例外の内容と実行環境の一部です。そこに至った操作、YukkuriMovieMaker4 のバージョン、GPU、例外を伴わない描画の乱れは届きません。
---
## プルリクエスト
1 つのプルリクエストには、1 つの目的の変更だけを含めてください。関係の無い整理、整形、依存関係の更新を含めないでください。依存関係を更新するのは、必要な機能を使うため、不具合やセキュリティの問題を直すため、互換性を保つためなど、具体的な理由があるときだけにしてください。
特に注意が要るのは、次の箇所です。
- 設定の項目と、その既定値と範囲。保存済みのプロジェクトの結果が変わるおそれがある
- 出力の結果。変えるつもりの無い変更で、映像や音が変わっていないか
- GPU のリソース、ファイル、ハンドルの寿命
- 破棄の処理と、失敗したときの処理
- YukkuriMovieMaker4 の内部に手を入れるプラグインでは、YukkuriMovieMaker4 のバージョンによる違い
動きを変えたときは、同じプルリクエストで README を直してください。`.github/Plugin_Readme.txt` があるリポジトリでは、それも直してください。`Plugin_Readme.txt` は配布パッケージに `Readme.txt` として入り、利用者の手元に残ります。
バージョンを上げる変更は、プルリクエストに含めないでください。バージョンの更新とリリースは、開発者が行います。
レビューを受けて直すときは、コミットを目的ごとのまとまりに保つため、ブランチの履歴を組み直して強制プッシュして構いません。
プルリクエストを送った時点で、その貢献をリポジトリと同じライセンスで提供することに同意したものとみなします。リポジトリのライセンスは、リポジトリの直下にあるライセンスのファイルに書いてあります。
---
## 検証
プルリクエストには、手元で実際に確かめた結果を書いてください。
- ビルドの結果と、テストのプロジェクトがあればテストの結果
- YukkuriMovieMaker4 で実際に動かして確かめたこと。使った YukkuriMovieMaker4 のバージョンを添え、GPU に関わる変更では GPU の名前とドライバーのバージョンも添えてください
- 実行できなかったテストと、その理由
実際に動かして観察したこと、コードを読んで判断したこと、推測したことを分けて書いてください。
出力を変えるつもりの無い変更では、変更前と変更後で出力が一致することを確かめてください。`--golden` と `--verify` を持つハーネスのプロジェクトがあるリポジトリでは、それで描画を比べられます。基準値は、手元の環境で変更前のコミットから作り直し、作り直した基準値はコミットに含めないでください。そのようなハーネスが無いリポジトリでは、変更前と変更後の出力を比べてください。サブモジュールの中にあるハーネスは、この確認には使いません。
性能の改善を主張するときは、1 回の測定で判断しないでください。
- 同じ機材、ドライバー、設定、電源の条件で、変更前と変更後のビルドを交互に繰り返し測ってください。
- GPU と CPU の温度で値が変わるため、測定の間を空けてください。
- ほかのプロセスが GPU を使っていない状態で測ってください。
- 正しさの確認と性能の測定は、別々に実行してください。確認のための処理が、測定値を変えるためです。
---
## コードの規約
変更する箇所で既に使われている実装のパターンと書き方に従ってください。既存の実装どうしが食い違っているときは、どちらかを機械的にまねず、README とテストに照らして意図された動きを確かめ、それに合うほうへ揃えてください。
自分の変更で増えたビルドの警告は、放置せず原因を直してください。
新しく書くコードには、コメントを入れず、コメントアウトしたコードも残さないでください。既存のコードにあるコメントとドキュメントコメントは残してください。
---
## コミットの規約
- 1 つのコミットは、目的ごとのまとまりを保てる範囲で、できるだけ小さくしてください。どのコミットも、それ単独でビルドが通るようにしてください。
- 実装の変更と、それを確かめるテストは、別のコミットに分けてください。
- 件名は日本語で書き、50 文字以内に収め、「〜する」の形で終えてください。「〜を追加する」「〜を直す」はよい例です。「〜の追加」「〜を修正」のように名詞で終える形は使いません。
- 件名を日本語で書けないときは、プルリクエストにその旨を書いてください。
- 本文は書かないでください。例外は、リリースノートでの変更の分類を指定する行だけです。この行が要るときは、書き方をレビューで伝えます。
---
## 行動規範
貢献するすべての人に、[行動規範](CODE_OF_CONDUCT.md)に従うことを求めます。
-10
ファイルの表示
@@ -1,15 +1,5 @@
<Project>
<PropertyGroup>
<YMM4DirPath>C:\Program Files\YukkuriMovieMaker_v4_Lite_Dev\</YMM4DirPath>
<WindowsKitRoot>C:\Program Files (x86)\Windows Kits\10\bin</WindowsKitRoot>
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.26100.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.26100.0\x64\fxc.exe</FxcPath>
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.22621.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.22621.0\x64\fxc.exe</FxcPath>
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.19041.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.19041.0\x64\fxc.exe</FxcPath>
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.18362.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.18362.0\x64\fxc.exe</FxcPath>
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.17763.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.17763.0\x64\fxc.exe</FxcPath>
<FxcPath Condition="'$(FxcPath)' == ''">fxc.exe</FxcPath>
</PropertyGroup>
</Project>
+174 -73
ファイルの表示
@@ -6,9 +6,11 @@
---
YukkuriMovieMaker4(YMM4)上で動作する、**フラウンホーファー回折理論に基づいて計算した点像分布関数(PSF)で映像を畳み込む映像エフェクトプラグイン**です。
波長・F値・画素ピッチ・開口形状・ゼルニケ波面収差係数をパラメータとして設定でき、円形開口・正多角形開口・中央遮蔽・6 種類の波面収差項に対応します。
PSF の計算品質は FFT 格子サイズで切り替え可能で、各パラメータはアニメーションに対応しています。
YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もない理想の像とみなし、レンズの開口と波面収差から求めた点像分布関数で畳み込んで、回折と収差によるにじみを描画する映像エフェクトプラグインです。
点像分布関数は、瞳関数のフラウンホーファー回折を高速フーリエ変換で解いて求めます。
履歴フレーム、参照画像、学習済みモデルを使わず、入力された一枚の映像だけを処理します。
にじみの形は光学系と収差の設定から決定論的に決まり、同じ設定では常に同じ形になります。
適用量、利得、波長、F値、画素ピッチ、開口回転、中央遮蔽、デフォーカス、縦横非点収差、斜め非点収差、水平コマ収差、垂直コマ収差、球面収差の13項目はアニメーションに対応しています。
---
@@ -18,10 +20,13 @@ PSF の計算品質は FFT 格子サイズで切り替え可能で、各パラ
2. [動作要件](#動作要件)
3. [インストール方法](#インストール方法)
4. [主な機能](#主な機能)
- [1. フラウンホーファー回折によるPSF計算](#1-フラウンホーファー回折によるpsf計算)
- [2. ゼルニケ多項式による波面収差](#2-ゼルニケ多項式による波面収差)
- [3. D2D1カスタムシェーダーによる畳み込み](#3-d2d1カスタムシェーダーによる畳み込み)
- [4. アニメーション対応パラメータ](#4-アニメーション対応パラメータ)
- [1. 点像分布関数の計算](#1-点像分布関数の計算)
- [2. 光学系の項目とにじみの大きさ](#2-光学系の項目とにじみの大きさ)
- [3. 開口の形と中央遮蔽](#3-開口の形と中央遮蔽)
- [4. ゼルニケ多項式による波面収差](#4-ゼルニケ多項式による波面収差)
- [5. 分離可能な畳み込み](#5-分離可能な畳み込み)
- [6. 利得と適用量](#6-利得と適用量)
- [7. 品質の選択](#7-品質の選択)
5. [パラメータ一覧](#パラメータ一覧)
- [出力グループ](#出力グループ)
- [光学系グループ](#光学系グループ)
@@ -29,20 +34,26 @@ PSF の計算品質は FFT 格子サイズで切り替え可能で、各パラ
- [波面収差グループ](#波面収差グループ)
6. [制限事項](#制限事項)
7. [注意事項](#注意事項)
8. [免責事項](#免責事項)
9. [ライセンス](#ライセンス)
8. [不具合の報告](#不具合の報告)
9. [免責事項](#免責事項)
10. [サードパーティライセンス](#サードパーティライセンス)
11. [ライセンス](#ライセンス)
---
## 概要
本プラグインは YMM4 の「映像エフェクト」として動作し、エフェクトの種類一覧では「波動光学」として表示されます。
本プラグインはYMM4の映像エフェクトとして動作し、エフェクトの種類一覧では「波動光学」として表示されます。カテゴリは加工です。
瞳関数を FFT で変換して強度分布(PSF)を計算し、得られた PSF カーネルを Direct2D カスタムピクセルシェーダーで映像に畳み込むことで、回折・収差による像のにじみを物理的に再現します。PSF はエネルギーが保存されるよう正規化され、「利得」パラメータで表示輝度を調整できます。
レンズで撮った写真では、1点から出た光が1点に写らず、わずかに広がって写ります。この広がり方を表す関数を、点像分布関数と呼びます。光が広がる原因の1つは回折です。回折は、光が開口の縁を回り込んで広がる現象で、開口はレンズの中で光が通る穴です。もう1つの原因は波面収差です。光の波の山をつないだ面を波面と呼び、波面が理想の形からずれることを波面収差と呼びます。本プラグインは、素材の各画素の光を点像分布関数の形に広げて足し合わせます。この計算を畳み込みと呼びます。
PSF の計算には単色のフラウンホーファー回折を仮定します。白色光や多色光のシミュレーションには対応していません。
畳み込んだ結果は、「利得」を掛けてから、「適用量」の割合で入力映像と混ぜ合わせて出力します。
このエフェクトは AviUtl 向けの EXO 出力(`.exo`)には対応していません。
畳み込みの計算はComputeWeaveの計算シェーダーがDirect3D 12で実行します。点像分布関数と畳み込みの重みは、CPUで求めます。YMM4のDirect3D 11側とComputeWeaveのDirect3D 12側は、素材と畳み込んだ結果を共有テクスチャと共有フェンスで受け渡します。通常のフレーム処理では、CPUへの画素の読み戻しを行わず、7個の整数だけを読み戻します。7個の整数は、素材の色と不透明度から作る2個のハッシュと、透明でない画素の数と、外接矩形の位置を表す4個の値です。外接矩形は、透明でない画素をすべて囲む最小の矩形です。ハッシュは素材が変わったかどうかの判定に、外接矩形は畳み込む範囲を決めるのに使います。畳み込む範囲は、外接矩形を「カーネル半径」の画素数だけ広げ、外側へ4画素単位にそろえた範囲です。「カーネル半径」は、にじみが上下左右に届く画素数の上限です。
素材が変わらず、「利得」と「適用量」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。
このエフェクトはAviUtl向けのEXO出力には対応していません。
---
@@ -50,61 +61,98 @@ PSF の計算には単色のフラウンホーファー回折を仮定します
| 項目 | 要件 |
|---|---|
| OS | Windows 10 バージョン 2004(ビルド 19041)以降 / Windows 11(64bit) |
| OS | Windows 10 バージョン2004(ビルド19041)以降 / Windows 11(64bit) |
| YukkuriMovieMaker4 | 最新版を推奨 |
| ランタイム | .NET 10.0 |
| GPU | Direct3D 12とDirect3D 11・12間の共有テクスチャおよび共有フェンスを利用できるGPU |
---
## インストール方法
1. [Releases](https://github.com/routersys/YMM4-WaveOptics/releases/latest) ページから最新のプラグインファイル(`.ymme`)をダウンロードしてください。
2. YMM4 が起動していないことを確認し、ダウンロードしたファイルを実行(ダブルクリック)してインストールします。
3. YMM4 を起動し、タイムライン上のアイテムに映像エフェクトを追加します。
4. 映像エフェクトの種類として **「波動光学」** を選択してください。
1. [Releases](https://github.com/routersys/YMM4-WaveOptics/releases/latest)ページから最新のプラグインファイル(`.ymme`)をダウンロードしてください。
2. YMM4が起動していないことを確認し、ダウンロードしたファイルを実行してインストールします。
3. YMM4を起動し、タイムライン上のアイテムに映像エフェクトを追加します。
4. 映像エフェクトの種類として「波動光学」を選択してください。
---
## 主な機能
### 1. フラウンホーファー回折によるPSF計算
### 1. 点像分布関数の計算
瞳関数のグリッド上の各サンプルに対してゼルニケ収差で変調した位相を与え、FFT を適用して焦点面の強度分布(PSF)を計算します。PSF は双線形補間でカーネルにサンプリングされ、エネルギーが保存されるよう正規化されます。
点像分布関数は、瞳関数から求めます。瞳関数は、開口の各点を通る光の振幅と位相を表す関数です。振幅は波の揺れの大きさ、位相は波の進み具合です。開口の内側では振幅を1、外側では0とし、位相には波面収差を与えます。瞳関数の高速フーリエ変換を求め、その絶対値の2乗を点像分布関数とします。開口から十分に遠い面や、レンズの焦点面で見る回折を、フラウンホーファー回折と呼びます。この計算は、フラウンホーファー回折の式に当たります。
計算品質は「品質」パラメータの FFT 格子サイズで切り替えられます。
畳み込みの重みは、点像分布関数から値を取り出して作ります。取り出すのは、中心から上下左右に「カーネル半径」の画素数までの正方形の範囲です。重みをこの正方形に並べたものを、カーネルと呼びます。カーネルの各画素の値は、画素の中心の位置で点像分布関数を補間した値で、画素の面積にわたる平均ではありません。カーネルの値の和は1になるように正規化します。カーネルの外に届く光は捨てるため、正規化によってカーネルの値がその分だけ大きくなります。
| 品質 | FFT 格子サイズ |
|---|---|
| 高速 | 128 × 128 |
| 標準 | 256 × 256 |
| 高精度 | 512 × 512 |
点像分布関数とカーネルは、「利得」と「適用量」以外のどれかの項目が変わったフレームでだけ、CPUで作り直します。
瞳関数の直径は FFT 格子サイズの 1/4 です。開口形状は円形と正多角形から選択でき、正多角形では羽根枚数(3〜32)と回転角を設定できます。中央遮蔽(開口半径に対する割合 0〜95%)にも対応します。
### 2. 光学系の項目とにじみの大きさ
### 2. ゼルニケ多項式による波面収差
円形の開口で収差がないときの点像分布関数は、エアリーパターンと呼ばれる、明るい円盤と周りの薄い輪の形になります。明るい円盤の半径は、波長とF値の積の1.22倍です。デフォルトの波長550nm、F値8、画素ピッチ4μmでは、明るい円盤の半径は約5.4μmで、約1.3画素です。そのため、デフォルトの設定では、映像はわずかにやわらぐだけです。にじみを大きくするには、F値か波長を上げるか、画素ピッチを下げます。
以下の 6 種類のゼルニケ収差係数を独立して設定できます。各係数の単位は波数(waves)で、設定範囲は -10〜+10 waves です。
「波長」は、単色光として計算する光の波長です。長いほど回折による広がりが大きくなります。赤、緑、青の成分と不透明度は同じ点像分布関数で畳み込むので、波長を変えても映像の色は変わりません。
| 収差項 | 方向 |
|---|---|
| デフォーカス | — |
| 縦横非点収差 | 0 度 |
| 斜め非点収差 | 45 度 |
| 水平コマ収差 | 水平方向 |
| 垂直コマ収差 | 垂直方向 |
| 球面収差 | — |
「F値」は、開口の直径に対する焦点距離の比です。大きいほど開口が小さくなり、回折による広がりが大きくなります。
### 3. D2D1カスタムシェーダーによる畳み込み
「画素ピッチ」は、撮像面での1画素の間隔です。小さいほど、同じ広がりが多くの画素にまたがります。にじみの大きさは素材の画素を単位に決まるため、画素数の多い素材ほど、映像の全体に対するにじみは小さく見えます。
PSF カーネルを R32G32B32A32_Float 形式のビットマップとして Direct2D デバイスコンテキストへ渡し、HLSL ピクセルシェーダーで畳み込みを行います。カーネル最大サイズは 31×31(半径 15 px)です。
「カーネル半径」は、カーネルの正方形が中心から上下左右に何画素まで広がるかを決めます。設定できるのは1〜15画素です。点像分布関数がカーネルの正方形の外まで広がる設定では、外側の輪やにじみが切り取られます。
適用量が 0% の場合、または出力矩形の計算で半径が 0 になる場合は畳み込みを省略してパススルーとなります。畳み込み後に「利得」を乗算することでピーク輝度を調整できます。
### 3. 開口の形と中央遮蔽
### 4. アニメーション対応パラメータ
「開口形状」は、円形と正多角形から選びます。正多角形は、カメラの絞りの羽根が作る開口をまねた形で、頂点は円形の開口と同じ直径の円の上にあります。正多角形の開口では、頂点までの距離を開口の半径とします。辺の数は「羽根枚数」で、向きは「開口回転」で決めます。正多角形の開口では、点像分布関数が辺と垂直な向きへ伸びます。「羽根枚数」と「開口回転」は、開口形状が正多角形のときだけ働きます。
適用量・利得・波長・F値・画素ピッチ・開口回転・中央遮蔽・6 種類の収差係数はすべてアニメーション対応であり、キーフレームを設定することで時間に応じて値を変化させることができます。
「中央遮蔽」は、反射望遠鏡の副鏡のように開口の中央をふさぐ円の大きさで、開口の半径に対する割合です。値を上げると中心の明るさが下がり、周りの輪へ光が移ります。中央遮蔽は、どちらの開口形状でも円でふさぎます。
パラメータの変更を検出した場合のみ PSF を再計算します。
### 4. ゼルニケ多項式による波面収差
波面収差グループの6項目は、ゼルニケ多項式の6つの項の係数です。ゼルニケ多項式は、円形の開口の上の波面収差を、互いに直交する基本の形の和で表す多項式です。係数の単位はwavesで、波長を1とした量です。本プラグインの各項は、開口と同じ半径の円の内側全体で、二乗平均平方根が1になるように正規化しています。二乗平均平方根は、値の2乗を円の内側全体で平均して平方根を取ったもので、波面収差の大きさの目安です。円形で中央遮蔽の無い開口では、係数1 wavesの項による波面収差は、二乗平均平方根で波長1つ分です。正多角形の開口と中央遮蔽のある開口では、光の通る部分だけで測ると、この値からずれます。
表のρは開口の半径を1とした中心からの距離、θは水平方向から測った角度です。
| 項目 | 多項式 | 意味 |
|---|---|---|
| デフォーカス | √3(2ρ²-1) | 焦点の位置のずれ |
| 縦横非点収差 | √6ρ²cos2θ | 水平方向と垂直方向で焦点の位置が違うずれ |
| 斜め非点収差 | √6ρ²sin2θ | 45度傾いた2つの方向で焦点の位置が違うずれ |
| 水平コマ収差 | √8(3ρ³-2ρ)cosθ | 像が水平方向の片側へ尾を引くずれ |
| 垂直コマ収差 | √8(3ρ³-2ρ)sinθ | 像が垂直方向の片側へ尾を引くずれ |
| 球面収差 | √5(6ρ⁴-6ρ²+1) | 開口の中心と縁で焦点の位置が違うずれ |
### 5. 分離可能な畳み込み
本プラグインは、カーネルを何組かの和で近似して畳み込みます。1組は、横方向の1次元の重みと縦方向の1次元の重みの対です。組ごとに横と縦の1次元の畳み込みを行い、足し合わせます。カーネルは一辺が「カーネル半径」の2倍に1を足した画素数の正方形で、カーネル半径が15画素なら31×31画素です。この大きさの畳み込みをそのまま計算すると、1画素ごとに961回の掛け算が要ります。1組の畳み込みは、1画素ごとに横31回と縦31回の掛け算で済むので、組の数が15以下なら掛け算は961回より少なくなります。
組は特異値分解で求めます。特異値分解は、行列を縦と横の重みの組の和に分け、寄与の大きい順に並べる計算です。組の和と元のカーネルとの差の値の2乗の和が、カーネル全体の値の2乗の和の0.01%以下になるまで組を増やします。組の数の上限は、カーネルの一辺の画素数です。組の和は元のカーネルとわずかに違うため、その値の和も1から少しずれます。そこで、組の和をその値の和で割り、値の和を1にそろえます。そのため、利得が100%のときの畳み込みは、画素の値の総和を保ちます。
組の数は点像分布関数の形で決まります。カーネル半径15画素、品質「標準」で23通りの設定を測りました。組の数は、収差がないときは1〜6組、収差を入れると5〜16組でした。組が増えるほど、畳み込みの計算は重くなります。
計算時間は、試験用に作った1920×1080の画像を使い、Intel Iris Xe Graphicsで測りました。素材が変わって畳み込みを計算し直すフレームでは、収差がないときに約11ミリ秒、デフォーカスを1 wavesにすると約34ミリ秒、水平コマ収差を1 wavesにすると約50ミリ秒でした。素材と設定が変わらず、畳み込みを再利用するフレームでは約1.3ミリ秒でした。
### 6. 利得と適用量
「利得」は、畳み込んだ結果に掛ける倍率です。100%で画素の値の総和を保ち、上げるほど明るく、下げるほど暗くなります。利得を掛けた結果は、色と不透明度の各成分が表せる最大の値で打ち切り、さらに色の成分が不透明度を超えないように抑えます。
「適用量」は、入力映像と、利得を掛けた結果を混ぜる割合です。0%では入力を変更せず、100%では利得を掛けた結果だけを出力します。
### 7. 品質の選択
「品質」は、瞳関数を置く格子の大きさを切り替えます。格子は瞳関数の値を縦横に並べた表で、1つ1つの値を標本と呼びます。開口の直径は格子の一辺の4分の1です。格子が大きいほど、開口の縁と波面収差の位相を細かく表せます。
点像分布関数の標本の間隔は、波長とF値の積の4分の1で、品質によらず同じです。格子が大きいほど点像分布関数を求める範囲が広がります。カーネルのうち、この範囲の外になる画素は0になります。
| 品質 | 瞳関数の格子 | 開口の直径 | 点像分布関数を求める範囲 |
|---|---:|---:|---:|
| 高速 | 128×128 | 32標本 | 中心から上下左右に約70μm |
| 標準 | 256×256 | 64標本 | 中心から上下左右に約141μm |
| 高精度 | 512×512 | 128標本 | 中心から上下左右に約282μm |
表の範囲は波長550nm、F値8のときの値で、波長とF値の積に比例します。
格子が粗いと、大きな波面収差で位相が急に変わる所を表しきれず、点像分布関数の形が崩れます。水平コマ収差を2 wavesにし、品質ごとに求めたカーネルを、格子が2048×2048のときのカーネルと比べました。ほかの項目はデフォルトです。カーネルの各画素の値の差の絶対値を全画素で足すと、高速で約0.87、標準で約0.38、高精度で約0.03でした。カーネルの値の和は1です。波面収差を大きくするときは、品質を上げてください。
品質を上げると、点像分布関数の計算が重くなります。「利得」と「適用量」以外の項目をアニメーションで変えるときは、フレームごとに点像分布関数を計算し直すので、品質を下げると処理が軽くなります。
---
@@ -114,68 +162,121 @@ PSF カーネルを R32G32B32A32_Float 形式のビットマップとして Dire
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|---|---|---|---|---|---|
| 適用量 | 数値 | 100% | 0 〜 100% | ✔ | 波動光学処理の適用量を調整します。0% では入力を変更しません。 |
| 利得 | 数値 | 100% | 0 〜 400% | ✔ | エネルギー保存された畳み込み結果へ乗算する表示用利得です。 |
| 適用量 | 数値 | 100% | 0〜100% | 対応 | 入力映像と、利得を掛けた結果を混ぜる割合です。0%では入力を変更しません。 |
| 利得 | 数値 | 100% | 0〜400% | 対応 | 畳み込んだ結果に掛ける倍率です。100%で画素の値の総和を保ちます。 |
### 光学系グループ
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|---|---|---|---|---|---|
| 波長 | 数値 | 550 nm | 380 〜 780 nm | ✔ | 単色光として計算する真空中の波長を指定します。設定範囲は 380 〜 780 nm です。 |
| F値 | 数値 | 8 | 0.5 〜 32 | ✔ | 開口径に対する焦点距離の比を指定します。設定範囲は 0.5 〜 64 です。 |
| 画素ピッチ | 数値 | 4 μm | 0.5 〜 20 μm | ✔ | 撮像面上の 1 画素の物理的な間隔を指定します。設定範囲は 0.25 〜 100 μm です。 |
| カーネル半径 | 整数 | 15 px | 1 〜 15 px | ✗ | PSF を畳み込む画素半径を指定します。カーネルサイズは 2×半径+1 です。 |
| 品質 | 列挙 | 標準 | — | ✗ | 瞳関数と PSF を計算する FFT 格子の大きさを指定します。 |
| 波長 | 数値 | 550nm | 380〜780nm | 対応 | 単色光として計算する真空中の波長です。 |
| F値 | 数値 | 8 | 0.5〜32 | 対応 | 開口の直径に対する焦点距離の比です。直接入力では64まで指定できます。 |
| 画素ピッチ | 数値 | 4μm | 0.5〜20μm | 対応 | 撮像面での1画素の間隔です。直接入力では0.25〜100μmを指定できます。 |
| カーネル半径 | 整数 | 15px | 1〜15px | 非対応 | カーネルが中心から上下左右に広がる画素数です。カーネルの外に届く光は捨てます。 |
| 品質 | 列挙 | 標準 | 高速 / 標準 / 高精度 | 非対応 | 瞳関数を置く格子の大きさを選択します。 |
### 開口グループ
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|---|---|---|---|---|---|
| 開口形状 | 列挙 | 円形 | — | ✗ | 瞳関数の外周形状を指定します。 |
| 羽根枚数 | 整数 | 6 | 3 〜 16 | ✗ | 正多角形開口の辺数を指定します。設定範囲は 3 〜 32 です。 |
| 開口回転 | 数値 | 0° | -180 〜 180° | ✔ | 正多角形開口の回転角を指定します。設定範囲は -360 〜 360° です。 |
| 中央遮蔽 | 数値 | 0% | 0 〜 95% | ✔ | 開口半径に対する中央遮蔽半径の割合を指定します。 |
| 開口形状 | 列挙 | 円形 | 円形 / 正多角形 | 非対応 | 開口の外周の形です。 |
| 羽根枚数 | 整数 | 6 | 3〜16 | 非対応 | 正多角形の開口の辺の数です。直接入力では32まで指定できます。 |
| 開口回転 | 数値 | 0° | -180〜180° | 対応 | 正多角形の開口の回転角です。直接入力では-360〜360°を指定できます。 |
| 中央遮蔽 | 数値 | 0% | 0〜95% | 対応 | 開口の中央をふさぐ円の半径で、開口の半径に対する割合です。 |
### 波面収差グループ
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|---|---|---|---|---|---|
| デフォーカス | 数値 | 0 waves | -3 〜 3 waves | ✔ | 正規化 Zernike デフォーカス係数を波数で指定します。設定範囲は -10 〜 10 waves です。 |
| 縦横非点収差 | 数値 | 0 waves | -3 〜 3 waves | ✔ | 0 度方向の正規化 Zernike 非点収差係数を指定します。 |
| 斜め非点収差 | 数値 | 0 waves | -3 〜 3 waves | ✔ | 45 度方向の正規化 Zernike 非点収差係数を指定します。 |
| 水平コマ収差 | 数値 | 0 waves | -3 〜 3 waves | ✔ | 水平方向の正規化 Zernike コマ収差係数を指定します。 |
| 垂直コマ収差 | 数値 | 0 waves | -3 〜 3 waves | ✔ | 垂直方向の正規化 Zernike コマ収差係数を指定します。 |
| 球面収差 | 数値 | 0 waves | -3 〜 3 waves | ✔ | 正規化 Zernike 球面収差係数を指定します。設定範囲は -10 〜 10 waves です。 |
| デフォーカス | 数値 | 0 waves | -3〜3 waves | 対応 | 焦点の位置のずれの係数です。 |
| 縦横非点収差 | 数値 | 0 waves | -3〜3 waves | 対応 | 水平方向と垂直方向で焦点の位置が違うずれの係数です。 |
| 斜め非点収差 | 数値 | 0 waves | -3〜3 waves | 対応 | 45度傾いた2つの方向で焦点の位置が違うずれの係数です。 |
| 水平コマ収差 | 数値 | 0 waves | -3〜3 waves | 対応 | 像が水平方向の片側へ尾を引くずれの係数です。 |
| 垂直コマ収差 | 数値 | 0 waves | -3〜3 waves | 対応 | 像が垂直方向の片側へ尾を引くずれの係数です。 |
| 球面収差 | 数値 | 0 waves | -3〜3 waves | 対応 | 開口の中心と縁で焦点の位置が違うずれの係数です。 |
波面収差グループの6項目は、どれも直接入力では-10〜10 wavesまで指定できます。
---
## 制限事項
- カーネル半径は 1 〜 15 px の範囲で指定できます(カーネルサイズ最大 31×31)。
- 波長の設定範囲は 380 〜 780 nm(可視光域)です。
- 計算は単色のフラウンホーファー回折に限定されます。白色光や多色光には対応していません。
- AviUtl 向けの EXO 出力(`.exo`)には対応していません。
- AviUtl向けのEXO出力には対応していません。
- Direct3D 12デバイスを取得できない場合と、YMM4が使うDirect3D 11デバイスが相互運用に必要なインターフェースを持たない場合は、エフェクトを適用せず入力映像を表示します。GPUメモリが足りず共有テクスチャを確保できない場合も同じです。
- 畳み込みには現在のフレームの色と不透明度だけを使用します。履歴フレーム、外部画像、学習済みモデルは使用しません。素材に透明でない画素が無いときは、エフェクトを適用せず入力映像を表示します。
- 計算は単色のフラウンホーファー回折に限ります。白色光のように波長の混ざった光は扱いません。点像分布関数は画面のどこでも同じで、像の位置や素材の奥行きで変わるにじみは扱いません。
- 畳み込みは、画素の値をそのまま重み付けして足し合わせます。画素の値を光の強さに比例する値へ直してから畳み込む処理はしません。
- カーネル半径は1〜15画素です。
- 中央遮蔽で開口をほとんどふさぎ、瞳関数の格子に光の通る標本が1つも無くなる設定では、エフェクトを適用せず入力映像を表示します。品質を上げると起きにくくなります。
- 計算領域は、透明な部分も含む素材全体の矩形の上下左右に16画素の余白を加えた大きさで、長辺は8192画素が上限です。素材の長辺が8160画素を超える場合は、エフェクトを適用せず入力映像を表示します。
- GPUメモリ使用量は、計算領域の大きさに応じて増えます。作業用のバッファーとして、計算領域の1画素につき32バイトをGPUに確保します。処理量は、素材全体の大きさと畳み込む範囲の大きさに応じて増えます。
---
## 注意事項
- **品質と計算負荷**: 品質「高精度」では FFT 格子サイズが 512 になるため、パラメータ変更時の計算負荷が増加します。リアルタイムプレビュー中にパラメータを頻繁に変更する場合は「高速」への切り替えを検討してください。
- **カーネル半径と出力サイズ**: 適用量が 0% より大きい場合、出力矩形は入力矩形よりもカーネル半径分だけ拡張されます。
- **適用量が 0% の場合**: 畳み込みは実行されず、入力がそのまま出力されます。
- **AviUtl 非対応**: 本プラグインは AviUtl 向けの EXO 出力(`.exo`)に対応していません。
- **本プラグインを使用する前に、YMM4 プロジェクトファイルのバックアップを作成することを推奨します。**
- 処理負荷: 収差を入れると、畳み込みに使う組の数が増えて計算が重くなります。時間の目安は「分離可能な畳み込み」にあります。品質を上げると、点像分布関数の計算が重くなります。
- 品質と収差: 波面収差を大きくするときは、品質を上げてください。格子が粗いと点像分布関数の形が崩れます。崩れ方の目安は「品質の選択」にあります。
- キャッシュ: 素材の大きさと色と不透明度が変わらず、「利得」と「適用量」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。利得だけを変えたフレームでは、再利用した畳み込みに利得を掛け直します。適用量だけを変えたフレームでは、混ぜる割合だけを変えます。動画や口パクのように素材の内容が変わるフレームと、「利得」と「適用量」以外の項目をアニメーションで変えたフレームでは、毎回計算し直すので処理が重くなります。素材が変わったかどうかを調べる計算は、再利用するフレームでも毎フレーム行います。
- 適用量0%: 適用量が0%のときは入力を変更せず、畳み込みの計算も行いません。
- 再現性: 計算は決定論的で、時間値や乱数を使用しません。同じGPUとドライバーでは、同じ素材と同じ設定から常に同じ結果になります。
- 透明部分: 畳み込みは不透明度にも掛かるので、素材の縁の外にも半透明のにじみが広がります。出力の範囲は、素材の範囲と畳み込む範囲を合わせたものです。適用量が0%のときは、素材の範囲のままです。
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ新しい正式版を確認します。更新情報を取得できない場合は通知せず、そのまま動作します。プレリリースは通知の対象に含めません。
- 不具合の自動送信: 想定していない例外が起きたときは、その内容を開発者へ自動で送信します。内容は「不具合の報告」に書いています。
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを作成することを推奨します。
---
## 不具合の報告
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で送信します。同意は求めず、常に送信します。
送信する情報は次のとおりです。
| 種類 | 内容 |
|---|---|
| 例外 | 型の完全名、メッセージ、スタックトレース |
| 発生位置 | モジュール名、関数名、ファイル名、行番号 |
| プラグイン | アセンブリ名、バージョン |
| 実行環境 | OSの名前とバージョン、.NETのバージョン、CPUのアーキテクチャ、論理プロセッサ数 |
| 識別子 | YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子 |
メッセージとファイル名は、送信の前に置き換えを通します。置き換えるのは、Windowsのユーザー名、ユーザーフォルダー、AppDataのパス、マシン名、ドメイン名、メールアドレス、IPv4アドレスです。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値になります。
送信するのは想定していない例外だけです。YMM4が本プラグインのエフェクトを作るとき、フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後はYMM4へそのまま渡します。更新の確認では、更新情報の取得と比較で起きた例外は報告しません。通知の文を組み立てて表示するときに起きた例外は報告し、YMM4へは渡しません。画面の操作やバックグラウンドの処理で未処理になった例外も報告しますが、本プラグインのコードが関わる例外に限ります。本プラグインの外で起きた例外は送信しません。
次の失敗は送信しません。
| 種類 | 例 |
|---|---|
| 効果をかけないだけで済ませるもの | Direct3D 12デバイスを取得できない、YMM4のDirect3D 11デバイスが相互運用に必要なインターフェースを持たない、GPUメモリが足りず共有テクスチャを確保できない、素材の長辺が8160画素を超える、開口に光の通る標本が無いときに、エフェクトを適用せず入力映像を表示したとき |
| 更新の確認の通信の失敗 | manjubox.netとGitHubのどちらへも接続できない |
送信できなかった報告はYMM4のユーザーフォルダーへ退避します。次にYMM4を起動したあと、本プラグインのエフェクトを生成するか、同じくYMM4-Telemetryで報告する別のプラグインが動き始めると、退避した報告を1回の起動で10件まで送り直します。送信も再送も非同期に行うため、通信を待って起動と描画が遅くなることはありません。
実装は [YMM4-Telemetry](https://github.com/routersys/YMM4-Telemetry) をサブモジュールとして取り込んでいます。
---
## 免責事項
本プラグインは MIT ライセンスのもとで公開されています。
本プラグインはMITライセンスのもとで公開されています。
**本ソフトウェアは「現状のまま」提供されており、明示・黙示を問わず、商品性、特定目的への適合性、および権利非侵害に関する保証を含む、いかなる種類の保証も行いません。**
本ソフトウェアは「現状のまま」提供されており、明示または黙示を問わず、商品性、特定目的への適合性、および権利非侵害に関する保証を含む、いかなる種類の保証も行いません。
作者は、本プラグインの使用または使用不能に起因するいかなる損害についても、一切の責任を負いません。
ご利用は自己責任でお願いします。
作者は、本プラグインの使用または使用不能に起因するいかなる損害についても、一切の責任を負いません。ご利用は自己責任でお願いします。
---
## サードパーティライセンス
本プラグインは以下のサードパーティソフトウェアを同梱・使用しています。ライセンスの全文は、リポジトリの [`.github/LICENSE/ComputeWeave.txt`](.github/LICENSE/ComputeWeave.txt) と、配布パッケージの `LICENSE` フォルダーに収録しています。
| ソフトウェア | 用途 | ライセンス | 著作権表示 |
|---|---|---|---|
| [ComputeWeave](https://github.com/routersys/ComputeWeave) | Direct3D 12計算シェーダーとDirect3D 11・12共有処理 | MIT License | Copyright (c) 2024 Sergio Pedri |
---
+46
ファイルの表示
@@ -0,0 +1,46 @@
# セキュリティポリシー
## サポートするバージョン
セキュリティの修正は、最新のリリースだけを対象にします。
| バージョン | サポート |
|---|---|
| 最新のリリース | 対象 |
| それより前のリリース | 対象外 |
修正は、最新のリリースの次のバージョンとして公開します。報告する前に、最新のリリースでも問題が起きるかを確かめてください。
## 対象とする問題
本プラグインのコードと配布パッケージに原因がある問題を対象にします。たとえば次のようなものです。
- 細工したプロジェクトファイルや素材を開くと、意図しない処理が実行される
- 更新の確認などで行う通信の内容を、第三者が書き換えられる
- 不具合の情報を自動で送信するプラグインで、個人を特定できる情報が伏せられないまま送信される
配布パッケージに同梱したライブラリの脆弱性は、本プラグインを通じて悪用できる場合に対象にします。
YukkuriMovieMaker4 本体や、ほかのプラグインに原因がある問題は対象外です。それぞれの開発者へ報告してください。
## 報告の方法
脆弱性は、公開の Issue に書かないでください。修正を公開する前に悪用されるおそれがあります。
1. リポジトリの URL の末尾に `/security` を付けたページを開き、「Report a vulnerability」から非公開で報告してください。報告の内容を見られるのは、開発者と報告した人、開発者が招いた人だけです。
2. この方法が使えないときは、github.routersys@gmail.com へメールで報告してください。
報告には、次の内容を書いてください。分からない項目は書かなくて構いません。
| 項目 | 内容 |
|---|---|
| バージョン | 問題を確かめたプラグインのバージョンと、YukkuriMovieMaker4 のバージョン |
| 再現の手順 | 問題を起こす操作と、使ったプロジェクトファイルや素材 |
| 影響 | 問題によって何ができてしまうか |
| 回避策 | 分かっていれば、修正までの間に被害を避ける方法 |
## 報告の後
開発者は、報告を受け取ったら内容を確かめ、修正の見込みを返信します。
報告した人は、修正を含むバージョンが出るまで、報告の内容を明かさないでください。問題の詳細は、修正版の公開後に開発者が公表します。
-49
ファイルの表示
@@ -1,49 +0,0 @@
Key,Parameter,ja-jp,en-us,zh-cn,zh-tw,ko-kr,es-es,ar-sa,id-id
EffectName,,波動光学,Wave Optics,波动光学,波動光學,파동 광학,Óptica de ondas,البصريات الموجية,Optik Gelombang
OutputGroup,,出力,Output,输出,輸出,출력,Salida,الإخراج,Keluaran
OpticsGroup,,光学系,Optical System,光学系统,光學系統,광학 시스템,Sistema óptico,النظام البصري,Sistem Optik
ApertureGroup,,開口,Aperture,光圈,光圈,조리개,Apertura,الفتحة,Apertur
AberrationGroup,,波面収差,Wavefront Aberration,波前像差,波前像差,파면 수차,Aberración de frente de onda,انحراف جبهة الموجة,Aberasi Muka Gelombang
AmountName,,適用量,Amount,适用量,適用量,적용량,Cantidad,الكمية,Jumlah
AmountDesc,,波動光学処理の適用量を調整します。0%では入力を変更しません。,Adjusts the amount of wave optics processing. The input is unchanged at 0%.,调整波动光学处理的适用量。0%时输入不变。,調整波動光學處理的適用量。0%時輸入不變。,파동 광학 처리의 적용량을 조정합니다. 0%에서는 입력이 변경되지 않습니다.,Ajusta la cantidad de procesamiento de óptica de ondas. La entrada no cambia al 0%.,يضبط مقدار معالجة البصريات الموجية. يبقى الإدخال دون تغيير عند 0%.,Menyesuaikan jumlah pemrosesan optik gelombang. Input tidak berubah pada 0%.
GainName,,利得,Gain,增益,增益,이득,Ganancia,الكسب,Penguatan
GainDesc,,エネルギー保存された畳み込み結果へ乗算する表示用利得です。,Sets the display gain applied after the energy preserving convolution.,设置能量守恒卷积后应用的显示增益。,設定能量守恆卷積後應用的顯示增益。,에너지 보존 컨볼루션 후 적용되는 표시 이득을 설정합니다.,Establece la ganancia de visualización aplicada tras la convolución de conservación de energía.,يضبط كسب العرض المطبق بعد الالتفاف الحافظ للطاقة.,Mengatur penguatan tampilan yang diterapkan setelah konvolusi pelestarian energi.
WavelengthName,,波長,Wavelength,波长,波長,파장,Longitud de onda,الطول الموجي,Panjang Gelombang
WavelengthDesc,,単色光として計算する真空中の波長を指定します。,Sets the vacuum wavelength used for the monochromatic calculation.,设置单色光计算使用的真空波长。,設定單色光計算使用的真空波長。,단색광 계산에 사용되는 진공 파장을 설정합니다.,Establece la longitud de onda en el vacío utilizada para el cálculo monocromático.,يضبط الطول الموجي في الفراغ المستخدم للحساب أحادي اللون.,Mengatur panjang gelombang vakum yang digunakan untuk perhitungan monokromatik.
FNumberName,,F値,F-number,F值,F值,F값,Número F,رقم F,Angka F
FNumberDesc,,開口径に対する焦点距離の比を指定します。,Sets the ratio of focal length to aperture diameter.,设置焦距与光圈直径的比值。,設定焦距與光圈直徑的比值。,초점 거리와 조리개 직경의 비율을 설정합니다.,Establece la relación entre la longitud focal y el diámetro de la apertura.,يضبط نسبة البعد البؤري إلى قطر الفتحة.,Mengatur rasio panjang fokus terhadap diameter apertur.
PixelPitchName,,画素ピッチ,Pixel Pitch,像素间距,像素間距,픽셀 피치,Paso de píxel,خطوة البكسل,Jarak Piksel
PixelPitchDesc,,撮像面上の1画素の物理的な間隔を指定します。,Sets the physical spacing of one pixel on the image plane.,设置图像平面上一个像素的物理间距。,設定影像平面上一個像素的物理間距。,이미지 평면의 픽셀 하나의 물리적 간격을 설정합니다.,Establece el espaciado físico de un píxel en el plano de imagen.,يضبط التباعد المادي لبكسل واحد على مستوى الصورة.,Mengatur jarak fisik satu piksel pada bidang gambar.
KernelRadiusName,,カーネル半径,Kernel Radius,核半径,核半徑,커널 반지름,Radio de kernel,نصف قطر النواة,Radius Kernel
KernelRadiusDesc,,PSFを畳み込む画素半径を指定します。,Sets the pixel radius used to convolve the PSF.,设置用于卷积PSF的像素半径。,設定用於卷積PSF的像素半徑。,PSF를 컨볼루션하는 픽셀 반지름을 설정합니다.,Establece el radio de píxel utilizado para convolucionar la PSF.,يضبط نصف قطر البكسل المستخدم لالتفاف PSF.,Mengatur radius piksel yang digunakan untuk mengkonvolusikan PSF.
QualityName,,品質,Quality,质量,品質,품질,Calidad,الجودة,Kualitas
QualityDesc,,瞳関数とPSFを計算するFFT格子の大きさを指定します。,Sets the FFT grid size used to calculate the pupil function and PSF.,设置用于计算瞳孔函数和PSF的FFT格点大小。,設定用於計算瞳孔函數和PSF的FFT格點大小。,동공 함수와 PSF를 계산하는 FFT 격자 크기를 설정합니다.,Establece el tamaño de la cuadrícula FFT utilizada para calcular la función pupilar y la PSF.,يضبط حجم شبكة FFT المستخدمة لحساب دالة الحدقة وPSF.,Mengatur ukuran kisi FFT yang digunakan untuk menghitung fungsi pupil dan PSF.
QualityDraft,,高速,Draft,草稿,草稿,초안,Borrador,مسودة,Draf
QualityStandard,,標準,Standard,标准,標準,표준,Estándar,قياسي,Standar
QualityHigh,,高精度,High,高精度,高精度,높음,Alto,مرتفع,Tinggi
ApertureShapeName,,開口形状,Aperture Shape,光圈形状,光圈形狀,조리개 형태,Forma de apertura,شكل الفتحة,Bentuk Apertur
ApertureShapeDesc,,瞳関数の外周形状を指定します。,Sets the outer shape of the pupil function.,设置瞳孔函数的外部形状。,設定瞳孔函數的外部形狀。,동공 함수의 외부 형태를 설정합니다.,Establece la forma exterior de la función pupilar.,يضبط الشكل الخارجي لدالة الحدقة.,Mengatur bentuk luar fungsi pupil.
CircularAperture,,円形,Circular,圆形,圓形,원형,Circular,دائري,Melingkar
RegularPolygonAperture,,正多角形,Regular Polygon,正多边形,正多邊形,정다각형,Polígono regular,مضلع منتظم,Poligon Beraturan
BladeCountName,,羽根枚数,Blade Count,叶片数,葉片數,날개 수,Número de láminas,عدد الشفرات,Jumlah Bilah
BladeCountDesc,,正多角形開口の辺数を指定します。,Sets the number of sides in the regular polygon aperture.,设置正多边形光圈的边数。,設定正多邊形光圈的邊數。,정다각형 조리개의 변의 수를 설정합니다.,Establece el número de lados en la apertura de polígono regular.,يضبط عدد أضلاع فتحة المضلع المنتظم.,Mengatur jumlah sisi pada apertur poligon beraturan.
BladeRotationName,,開口回転,Aperture Rotation,光圈旋转,光圈旋轉,조리개 회전,Rotación de apertura,دوران الفتحة,Rotasi Apertur
BladeRotationDesc,,正多角形開口の回転角を指定します。,Sets the rotation angle of the regular polygon aperture.,设置正多边形光圈的旋转角度。,設定正多邊形光圈的旋轉角度。,정다각형 조리개의 회전 각도를 설정합니다.,Establece el ángulo de rotación de la apertura de polígono regular.,يضبط زاوية دوران فتحة المضلع المنتظم.,Mengatur sudut rotasi apertur poligon beraturan.
ObstructionName,,中央遮蔽,Central Obstruction,中央遮蔽,中央遮蔽,중앙 차폐,Obstrucción central,الحجب المركزي,Obstruksi Tengah
ObstructionDesc,,開口半径に対する中央遮蔽半径の割合を指定します。,Sets the central obstruction radius relative to the aperture radius.,设置中央遮蔽半径相对于光圈半径的比例。,設定中央遮蔽半徑相對於光圈半徑的比例。,조리개 반지름에 대한 중앙 차폐 반지름의 비율을 설정합니다.,Establece el radio de obstrucción central en relación al radio de apertura.,يضبط نصف قطر الحجب المركزي بالنسبة لنصف قطر الفتحة.,Mengatur radius obstruksi tengah relatif terhadap radius apertur.
DefocusName,,デフォーカス,Defocus,离焦,離焦,디포커스,Desenfoque,إزالة التركيز,Defokus
DefocusDesc,,正規化Zernikeデフォーカス係数を波数で指定します。,Sets the normalized Zernike defocus coefficient in waves.,以波数为单位设置归一化Zernike离焦系数。,以波數為單位設定歸一化Zernike離焦係數。,파수 단위로 정규화된 Zernike 디포커스 계수를 설정합니다.,Establece el coeficiente de desenfoque de Zernike normalizado en ondas.,يضبط معامل إزالة التركيز لـZernike المعياري بالأمواج.,Mengatur koefisien defokus Zernike ternormalisasi dalam satuan gelombang.
AstigmatismVerticalName,,縦横非点収差,Vertical Astigmatism,垂直散光,垂直散光,수직 난시,Astigmatismo vertical,الاستجماتيزم الرأسي,Astigmatisme Vertikal
AstigmatismVerticalDesc,,0度方向の正規化Zernike非点収差係数を指定します。,Sets the normalized Zernike astigmatism coefficient at zero degrees.,设置0度方向的归一化Zernike散光系数。,設定0度方向的歸一化Zernike散光係數。,0도 방향의 정규화된 Zernike 난시 계수를 설정합니다.,Establece el coeficiente de astigmatismo de Zernike normalizado en cero grados.,يضبط معامل الاستجماتيزم لـZernike المعياري عند صفر درجة.,Mengatur koefisien astigmatisme Zernike ternormalisasi pada nol derajat.
AstigmatismObliqueName,,斜め非点収差,Oblique Astigmatism,斜向散光,斜向散光,사선 난시,Astigmatismo oblicuo,الاستجماتيزم المائل,Astigmatisme Miring
AstigmatismObliqueDesc,,45度方向の正規化Zernike非点収差係数を指定します。,Sets the normalized Zernike astigmatism coefficient at 45 degrees.,设置45度方向的归一化Zernike散光系数。,設定45度方向的歸一化Zernike散光係數。,45도 방향의 정규화된 Zernike 난시 계수를 설정합니다.,Establece el coeficiente de astigmatismo de Zernike normalizado en 45 grados.,يضبط معامل الاستجماتيزم لـZernike المعياري عند 45 درجة.,Mengatur koefisien astigmatisme Zernike ternormalisasi pada 45 derajat.
ComaHorizontalName,,水平コマ収差,Horizontal Coma,水平彗差,水平彗差,수평 코마,Coma horizontal,الكوما الأفقية,Koma Horizontal
ComaHorizontalDesc,,水平方向の正規化Zernikeコマ収差係数を指定します。,Sets the normalized horizontal Zernike coma coefficient.,设置归一化水平Zernike彗差系数。,設定歸一化水平Zernike彗差係數。,정규화된 수평 Zernike 코마 계수를 설정합니다.,Establece el coeficiente de coma de Zernike horizontal normalizado.,يضبط معامل الكوما الأفقي لـZernike المعياري.,Mengatur koefisien koma Zernike horizontal ternormalisasi.
ComaVerticalName,,垂直コマ収差,Vertical Coma,垂直彗差,垂直彗差,수직 코마,Coma vertical,الكوما الرأسية,Koma Vertikal
ComaVerticalDesc,,垂直方向の正規化Zernikeコマ収差係数を指定します。,Sets the normalized vertical Zernike coma coefficient.,设置归一化垂直Zernike彗差系数。,設定歸一化垂直Zernike彗差係數。,정규화된 수직 Zernike 코마 계수를 설정합니다.,Establece el coeficiente de coma de Zernike vertical normalizado.,يضبط معامل الكوما الرأسي لـZernike المعياري.,Mengatur koefisien koma Zernike vertikal ternormalisasi.
SphericalName,,球面収差,Spherical Aberration,球面像差,球面像差,구면 수차,Aberración esférica,الانحراف الكروي,Aberasi Sferis
SphericalDesc,,正規化Zernike球面収差係数を指定します。,Sets the normalized Zernike spherical aberration coefficient.,设置归一化Zernike球面像差系数。,設定歸一化Zernike球面像差係數。,정규화된 Zernike 구면 수차 계수를 설정합니다.,Establece el coeficiente de aberración esférica de Zernike normalizado.,يضبط معامل الانحراف الكروي لـZernike المعياري.,Mengatur koefisien aberasi sferis Zernike ternormalisasi.
TagDiffraction,,回折,diffraction,衍射,衍射,회절,difracción,الحيود,difraksi
TagLens,,レンズ,lens,镜头,鏡頭,렌즈,lente,العدسة,lensa
TagPsf,,点像分布関数,point spread function,点扩散函数,點擴散函數,점 확산 함수,función de dispersión puntual,دالة انتشار النقطة,fungsi penyebaran titik
TagOptics,,光学,optics,光学,光學,광학,óptica,البصريات,optik
1 Key Parameter ja-jp en-us zh-cn zh-tw ko-kr es-es ar-sa id-id
2 EffectName 波動光学 Wave Optics 波动光学 波動光學 파동 광학 Óptica de ondas البصريات الموجية Optik Gelombang
3 OutputGroup 出力 Output 输出 輸出 출력 Salida الإخراج Keluaran
4 OpticsGroup 光学系 Optical System 光学系统 光學系統 광학 시스템 Sistema óptico النظام البصري Sistem Optik
5 ApertureGroup 開口 Aperture 光圈 光圈 조리개 Apertura الفتحة Apertur
6 AberrationGroup 波面収差 Wavefront Aberration 波前像差 波前像差 파면 수차 Aberración de frente de onda انحراف جبهة الموجة Aberasi Muka Gelombang
7 AmountName 適用量 Amount 适用量 適用量 적용량 Cantidad الكمية Jumlah
8 AmountDesc 波動光学処理の適用量を調整します。0%では入力を変更しません。 Adjusts the amount of wave optics processing. The input is unchanged at 0%. 调整波动光学处理的适用量。0%时输入不变。 調整波動光學處理的適用量。0%時輸入不變。 파동 광학 처리의 적용량을 조정합니다. 0%에서는 입력이 변경되지 않습니다. Ajusta la cantidad de procesamiento de óptica de ondas. La entrada no cambia al 0%. يضبط مقدار معالجة البصريات الموجية. يبقى الإدخال دون تغيير عند 0%. Menyesuaikan jumlah pemrosesan optik gelombang. Input tidak berubah pada 0%.
9 GainName 利得 Gain 增益 增益 이득 Ganancia الكسب Penguatan
10 GainDesc エネルギー保存された畳み込み結果へ乗算する表示用利得です。 Sets the display gain applied after the energy preserving convolution. 设置能量守恒卷积后应用的显示增益。 設定能量守恆卷積後應用的顯示增益。 에너지 보존 컨볼루션 후 적용되는 표시 이득을 설정합니다. Establece la ganancia de visualización aplicada tras la convolución de conservación de energía. يضبط كسب العرض المطبق بعد الالتفاف الحافظ للطاقة. Mengatur penguatan tampilan yang diterapkan setelah konvolusi pelestarian energi.
11 WavelengthName 波長 Wavelength 波长 波長 파장 Longitud de onda الطول الموجي Panjang Gelombang
12 WavelengthDesc 単色光として計算する真空中の波長を指定します。 Sets the vacuum wavelength used for the monochromatic calculation. 设置单色光计算使用的真空波长。 設定單色光計算使用的真空波長。 단색광 계산에 사용되는 진공 파장을 설정합니다. Establece la longitud de onda en el vacío utilizada para el cálculo monocromático. يضبط الطول الموجي في الفراغ المستخدم للحساب أحادي اللون. Mengatur panjang gelombang vakum yang digunakan untuk perhitungan monokromatik.
13 FNumberName F値 F-number F值 F值 F값 Número F رقم F Angka F
14 FNumberDesc 開口径に対する焦点距離の比を指定します。 Sets the ratio of focal length to aperture diameter. 设置焦距与光圈直径的比值。 設定焦距與光圈直徑的比值。 초점 거리와 조리개 직경의 비율을 설정합니다. Establece la relación entre la longitud focal y el diámetro de la apertura. يضبط نسبة البعد البؤري إلى قطر الفتحة. Mengatur rasio panjang fokus terhadap diameter apertur.
15 PixelPitchName 画素ピッチ Pixel Pitch 像素间距 像素間距 픽셀 피치 Paso de píxel خطوة البكسل Jarak Piksel
16 PixelPitchDesc 撮像面上の1画素の物理的な間隔を指定します。 Sets the physical spacing of one pixel on the image plane. 设置图像平面上一个像素的物理间距。 設定影像平面上一個像素的物理間距。 이미지 평면의 픽셀 하나의 물리적 간격을 설정합니다. Establece el espaciado físico de un píxel en el plano de imagen. يضبط التباعد المادي لبكسل واحد على مستوى الصورة. Mengatur jarak fisik satu piksel pada bidang gambar.
17 KernelRadiusName カーネル半径 Kernel Radius 核半径 核半徑 커널 반지름 Radio de kernel نصف قطر النواة Radius Kernel
18 KernelRadiusDesc PSFを畳み込む画素半径を指定します。 Sets the pixel radius used to convolve the PSF. 设置用于卷积PSF的像素半径。 設定用於卷積PSF的像素半徑。 PSF를 컨볼루션하는 픽셀 반지름을 설정합니다. Establece el radio de píxel utilizado para convolucionar la PSF. يضبط نصف قطر البكسل المستخدم لالتفاف PSF. Mengatur radius piksel yang digunakan untuk mengkonvolusikan PSF.
19 QualityName 品質 Quality 质量 品質 품질 Calidad الجودة Kualitas
20 QualityDesc 瞳関数とPSFを計算するFFT格子の大きさを指定します。 Sets the FFT grid size used to calculate the pupil function and PSF. 设置用于计算瞳孔函数和PSF的FFT格点大小。 設定用於計算瞳孔函數和PSF的FFT格點大小。 동공 함수와 PSF를 계산하는 FFT 격자 크기를 설정합니다. Establece el tamaño de la cuadrícula FFT utilizada para calcular la función pupilar y la PSF. يضبط حجم شبكة FFT المستخدمة لحساب دالة الحدقة وPSF. Mengatur ukuran kisi FFT yang digunakan untuk menghitung fungsi pupil dan PSF.
21 QualityDraft 高速 Draft 草稿 草稿 초안 Borrador مسودة Draf
22 QualityStandard 標準 Standard 标准 標準 표준 Estándar قياسي Standar
23 QualityHigh 高精度 High 高精度 高精度 높음 Alto مرتفع Tinggi
24 ApertureShapeName 開口形状 Aperture Shape 光圈形状 光圈形狀 조리개 형태 Forma de apertura شكل الفتحة Bentuk Apertur
25 ApertureShapeDesc 瞳関数の外周形状を指定します。 Sets the outer shape of the pupil function. 设置瞳孔函数的外部形状。 設定瞳孔函數的外部形狀。 동공 함수의 외부 형태를 설정합니다. Establece la forma exterior de la función pupilar. يضبط الشكل الخارجي لدالة الحدقة. Mengatur bentuk luar fungsi pupil.
26 CircularAperture 円形 Circular 圆形 圓形 원형 Circular دائري Melingkar
27 RegularPolygonAperture 正多角形 Regular Polygon 正多边形 正多邊形 정다각형 Polígono regular مضلع منتظم Poligon Beraturan
28 BladeCountName 羽根枚数 Blade Count 叶片数 葉片數 날개 수 Número de láminas عدد الشفرات Jumlah Bilah
29 BladeCountDesc 正多角形開口の辺数を指定します。 Sets the number of sides in the regular polygon aperture. 设置正多边形光圈的边数。 設定正多邊形光圈的邊數。 정다각형 조리개의 변의 수를 설정합니다. Establece el número de lados en la apertura de polígono regular. يضبط عدد أضلاع فتحة المضلع المنتظم. Mengatur jumlah sisi pada apertur poligon beraturan.
30 BladeRotationName 開口回転 Aperture Rotation 光圈旋转 光圈旋轉 조리개 회전 Rotación de apertura دوران الفتحة Rotasi Apertur
31 BladeRotationDesc 正多角形開口の回転角を指定します。 Sets the rotation angle of the regular polygon aperture. 设置正多边形光圈的旋转角度。 設定正多邊形光圈的旋轉角度。 정다각형 조리개의 회전 각도를 설정합니다. Establece el ángulo de rotación de la apertura de polígono regular. يضبط زاوية دوران فتحة المضلع المنتظم. Mengatur sudut rotasi apertur poligon beraturan.
32 ObstructionName 中央遮蔽 Central Obstruction 中央遮蔽 中央遮蔽 중앙 차폐 Obstrucción central الحجب المركزي Obstruksi Tengah
33 ObstructionDesc 開口半径に対する中央遮蔽半径の割合を指定します。 Sets the central obstruction radius relative to the aperture radius. 设置中央遮蔽半径相对于光圈半径的比例。 設定中央遮蔽半徑相對於光圈半徑的比例。 조리개 반지름에 대한 중앙 차폐 반지름의 비율을 설정합니다. Establece el radio de obstrucción central en relación al radio de apertura. يضبط نصف قطر الحجب المركزي بالنسبة لنصف قطر الفتحة. Mengatur radius obstruksi tengah relatif terhadap radius apertur.
34 DefocusName デフォーカス Defocus 离焦 離焦 디포커스 Desenfoque إزالة التركيز Defokus
35 DefocusDesc 正規化Zernikeデフォーカス係数を波数で指定します。 Sets the normalized Zernike defocus coefficient in waves. 以波数为单位设置归一化Zernike离焦系数。 以波數為單位設定歸一化Zernike離焦係數。 파수 단위로 정규화된 Zernike 디포커스 계수를 설정합니다. Establece el coeficiente de desenfoque de Zernike normalizado en ondas. يضبط معامل إزالة التركيز لـZernike المعياري بالأمواج. Mengatur koefisien defokus Zernike ternormalisasi dalam satuan gelombang.
36 AstigmatismVerticalName 縦横非点収差 Vertical Astigmatism 垂直散光 垂直散光 수직 난시 Astigmatismo vertical الاستجماتيزم الرأسي Astigmatisme Vertikal
37 AstigmatismVerticalDesc 0度方向の正規化Zernike非点収差係数を指定します。 Sets the normalized Zernike astigmatism coefficient at zero degrees. 设置0度方向的归一化Zernike散光系数。 設定0度方向的歸一化Zernike散光係數。 0도 방향의 정규화된 Zernike 난시 계수를 설정합니다. Establece el coeficiente de astigmatismo de Zernike normalizado en cero grados. يضبط معامل الاستجماتيزم لـZernike المعياري عند صفر درجة. Mengatur koefisien astigmatisme Zernike ternormalisasi pada nol derajat.
38 AstigmatismObliqueName 斜め非点収差 Oblique Astigmatism 斜向散光 斜向散光 사선 난시 Astigmatismo oblicuo الاستجماتيزم المائل Astigmatisme Miring
39 AstigmatismObliqueDesc 45度方向の正規化Zernike非点収差係数を指定します。 Sets the normalized Zernike astigmatism coefficient at 45 degrees. 设置45度方向的归一化Zernike散光系数。 設定45度方向的歸一化Zernike散光係數。 45도 방향의 정규화된 Zernike 난시 계수를 설정합니다. Establece el coeficiente de astigmatismo de Zernike normalizado en 45 grados. يضبط معامل الاستجماتيزم لـZernike المعياري عند 45 درجة. Mengatur koefisien astigmatisme Zernike ternormalisasi pada 45 derajat.
40 ComaHorizontalName 水平コマ収差 Horizontal Coma 水平彗差 水平彗差 수평 코마 Coma horizontal الكوما الأفقية Koma Horizontal
41 ComaHorizontalDesc 水平方向の正規化Zernikeコマ収差係数を指定します。 Sets the normalized horizontal Zernike coma coefficient. 设置归一化水平Zernike彗差系数。 設定歸一化水平Zernike彗差係數。 정규화된 수평 Zernike 코마 계수를 설정합니다. Establece el coeficiente de coma de Zernike horizontal normalizado. يضبط معامل الكوما الأفقي لـZernike المعياري. Mengatur koefisien koma Zernike horizontal ternormalisasi.
42 ComaVerticalName 垂直コマ収差 Vertical Coma 垂直彗差 垂直彗差 수직 코마 Coma vertical الكوما الرأسية Koma Vertikal
43 ComaVerticalDesc 垂直方向の正規化Zernikeコマ収差係数を指定します。 Sets the normalized vertical Zernike coma coefficient. 设置归一化垂直Zernike彗差系数。 設定歸一化垂直Zernike彗差係數。 정규화된 수직 Zernike 코마 계수를 설정합니다. Establece el coeficiente de coma de Zernike vertical normalizado. يضبط معامل الكوما الرأسي لـZernike المعياري. Mengatur koefisien koma Zernike vertikal ternormalisasi.
44 SphericalName 球面収差 Spherical Aberration 球面像差 球面像差 구면 수차 Aberración esférica الانحراف الكروي Aberasi Sferis
45 SphericalDesc 正規化Zernike球面収差係数を指定します。 Sets the normalized Zernike spherical aberration coefficient. 设置归一化Zernike球面像差系数。 設定歸一化Zernike球面像差係數。 정규화된 Zernike 구면 수차 계수를 설정합니다. Establece el coeficiente de aberración esférica de Zernike normalizado. يضبط معامل الانحراف الكروي لـZernike المعياري. Mengatur koefisien aberasi sferis Zernike ternormalisasi.
46 TagDiffraction 回折 diffraction 衍射 衍射 회절 difracción الحيود difraksi
47 TagLens レンズ lens 镜头 鏡頭 렌즈 lente العدسة lensa
48 TagPsf 点像分布関数 point spread function 点扩散函数 點擴散函數 점 확산 함수 función de dispersión puntual دالة انتشار النقطة fungsi penyebaran titik
49 TagOptics 光学 optics 光学 光學 광학 óptica البصريات optik
-112
ファイルの表示
@@ -1,112 +0,0 @@
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Controls;
using YukkuriMovieMaker.Exo;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Plugin.Effects;
namespace WaveOptics.Effects;
[VideoEffect(nameof(Texts.EffectName), [VideoEffectCategories.Filtering], [nameof(Texts.TagDiffraction), nameof(Texts.TagLens), nameof(Texts.TagPsf), nameof(Texts.TagOptics)], IsAviUtlSupported = false, ResourceType = typeof(Texts))]
public sealed class WaveOpticsEffect : VideoEffectBase
{
public override string Label => Texts.EffectName;
[Display(GroupName = nameof(Texts.OutputGroup), Name = nameof(Texts.AmountName), Description = nameof(Texts.AmountDesc), Order = 0, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "%", 0, 100)]
public Animation Amount { get; } = new(100, 0, 100);
[Display(GroupName = nameof(Texts.OutputGroup), Name = nameof(Texts.GainName), Description = nameof(Texts.GainDesc), Order = 1, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "%", 0, 400)]
public Animation Gain { get; } = new(100, 0, 400);
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.WavelengthName), Description = nameof(Texts.WavelengthDesc), Order = 10, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "nm", 380, 780)]
public Animation Wavelength { get; } = new(550, 380, 780);
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.FNumberName), Description = nameof(Texts.FNumberDesc), Order = 11, ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", 0.5, 32)]
public Animation FNumber { get; } = new(8, 0.5, 64);
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.PixelPitchName), Description = nameof(Texts.PixelPitchDesc), Order = 12, ResourceType = typeof(Texts))]
[AnimationSlider("F2", "μm", 0.5, 20)]
public Animation PixelPitch { get; } = new(4, 0.25, 100);
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.KernelRadiusName), Description = nameof(Texts.KernelRadiusDesc), Order = 13, ResourceType = typeof(Texts))]
[TextBoxSlider("F0", "px", 1, 15)]
[Range(1, 15)]
[DefaultValue(15)]
public int KernelRadius { get => kernelRadius; set => Set(ref kernelRadius, Math.Clamp(value, 1, 15)); }
int kernelRadius = 15;
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.QualityName), Description = nameof(Texts.QualityDesc), Order = 14, ResourceType = typeof(Texts))]
[EnumComboBox]
public WaveOpticsQuality Quality { get => quality; set => Set(ref quality, value); }
WaveOpticsQuality quality = WaveOpticsQuality.Standard;
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.ApertureShapeName), Description = nameof(Texts.ApertureShapeDesc), Order = 20, ResourceType = typeof(Texts))]
[EnumComboBox]
public WaveOpticsApertureShape ApertureShape { get => apertureShape; set => Set(ref apertureShape, value); }
WaveOpticsApertureShape apertureShape;
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.BladeCountName), Description = nameof(Texts.BladeCountDesc), Order = 21, ResourceType = typeof(Texts))]
[TextBoxSlider("F0", "", 3, 16)]
[Range(3, 32)]
[DefaultValue(6)]
public int BladeCount { get => bladeCount; set => Set(ref bladeCount, Math.Clamp(value, 3, 32)); }
int bladeCount = 6;
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.BladeRotationName), Description = nameof(Texts.BladeRotationDesc), Order = 22, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "°", -180, 180)]
public Animation BladeRotation { get; } = new(0, -360, 360);
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.ObstructionName), Description = nameof(Texts.ObstructionDesc), Order = 23, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "%", 0, 95)]
public Animation Obstruction { get; } = new(0, 0, 95);
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.DefocusName), Description = nameof(Texts.DefocusDesc), Order = 30, ResourceType = typeof(Texts))]
[AnimationSlider("F3", "waves", -3, 3)]
public Animation Defocus { get; } = new(0, -10, 10);
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.AstigmatismVerticalName), Description = nameof(Texts.AstigmatismVerticalDesc), Order = 31, ResourceType = typeof(Texts))]
[AnimationSlider("F3", "waves", -3, 3)]
public Animation AstigmatismVertical { get; } = new(0, -10, 10);
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.AstigmatismObliqueName), Description = nameof(Texts.AstigmatismObliqueDesc), Order = 32, ResourceType = typeof(Texts))]
[AnimationSlider("F3", "waves", -3, 3)]
public Animation AstigmatismOblique { get; } = new(0, -10, 10);
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.ComaHorizontalName), Description = nameof(Texts.ComaHorizontalDesc), Order = 33, ResourceType = typeof(Texts))]
[AnimationSlider("F3", "waves", -3, 3)]
public Animation ComaHorizontal { get; } = new(0, -10, 10);
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.ComaVerticalName), Description = nameof(Texts.ComaVerticalDesc), Order = 34, ResourceType = typeof(Texts))]
[AnimationSlider("F3", "waves", -3, 3)]
public Animation ComaVertical { get; } = new(0, -10, 10);
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.SphericalName), Description = nameof(Texts.SphericalDesc), Order = 35, ResourceType = typeof(Texts))]
[AnimationSlider("F3", "waves", -3, 3)]
public Animation Spherical { get; } = new(0, -10, 10);
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices) => new WaveOpticsEffectProcessor(devices, this);
protected override IEnumerable<IAnimatable> GetAnimatables()
{
yield return Amount;
yield return Gain;
yield return Wavelength;
yield return FNumber;
yield return PixelPitch;
yield return BladeRotation;
yield return Obstruction;
yield return Defocus;
yield return AstigmatismVertical;
yield return AstigmatismOblique;
yield return ComaHorizontal;
yield return ComaVertical;
yield return Spherical;
}
}
-162
ファイルの表示
@@ -1,162 +0,0 @@
using Vortice.Direct2D1;
using WaveOptics.Abstractions;
using WaveOptics.Optics;
using WaveOptics.Rendering;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Player.Video.Effects;
namespace WaveOptics.Effects;
internal sealed class WaveOpticsEffectProcessor(IGraphicsDevicesAndContext devices, WaveOpticsEffect item) : VideoEffectProcessorBase(devices)
{
readonly IGraphicsDevicesAndContext devices = devices;
readonly WaveOpticsEffect item = item;
readonly FraunhoferPsfGenerator generator = new();
WaveOpticsConvolutionEffect? effect;
ID2D1Bitmap? kernelBitmap;
Parameters? currentParameters;
float amount;
float gain;
bool isFirst = true;
public override DrawDescription Update(EffectDescription effectDescription)
{
if (IsPassThroughEffect || effect is null)
return effectDescription.DrawDescription;
var frame = effectDescription.ItemPosition.Frame;
var length = effectDescription.ItemDuration.Frame;
var fps = effectDescription.FPS;
var amount = Sanitize(item.Amount.GetValue(frame, length, fps) / 100d, 0, 1, 0);
var gain = Sanitize(item.Gain.GetValue(frame, length, fps) / 100d, 0, 4, 1);
var parameters = new Parameters(
GetGridSize(item.Quality),
item.KernelRadius * 2 + 1,
Sanitize(item.Wavelength.GetValue(frame, length, fps), 380, 780, 550),
Sanitize(item.FNumber.GetValue(frame, length, fps), 0.5, 64, 8),
Sanitize(item.PixelPitch.GetValue(frame, length, fps), 0.25, 100, 4),
item.ApertureShape,
Math.Clamp(item.BladeCount, 3, 32),
Sanitize(item.BladeRotation.GetValue(frame, length, fps), -360, 360, 0),
Sanitize(item.Obstruction.GetValue(frame, length, fps) / 100d, 0, 0.95, 0),
Sanitize(item.Defocus.GetValue(frame, length, fps), -10, 10, 0),
Sanitize(item.AstigmatismVertical.GetValue(frame, length, fps), -10, 10, 0),
Sanitize(item.AstigmatismOblique.GetValue(frame, length, fps), -10, 10, 0),
Sanitize(item.ComaHorizontal.GetValue(frame, length, fps), -10, 10, 0),
Sanitize(item.ComaVertical.GetValue(frame, length, fps), -10, 10, 0),
Sanitize(item.Spherical.GetValue(frame, length, fps), -10, 10, 0));
if (currentParameters != parameters)
UpdateKernel(parameters);
if (isFirst || this.amount != amount)
effect.Amount = amount;
if (isFirst || this.gain != gain)
effect.Gain = gain;
isFirst = false;
this.amount = amount;
this.gain = gain;
currentParameters = parameters;
return effectDescription.DrawDescription;
}
void UpdateKernel(Parameters parameters)
{
if (effect is null)
return;
var aberration = new WavefrontAberration(
defocusWaves: parameters.Defocus,
astigmatismVerticalWaves: parameters.AstigmatismVertical,
astigmatismObliqueWaves: parameters.AstigmatismOblique,
comaHorizontalWaves: parameters.ComaHorizontal,
comaVerticalWaves: parameters.ComaVertical,
sphericalWaves: parameters.Spherical);
var descriptor = new PsfDescriptor(
parameters.GridSize,
parameters.GridSize / 4,
parameters.KernelSize,
parameters.Wavelength,
parameters.FNumber,
parameters.PixelPitch,
parameters.ApertureShape == WaveOpticsApertureShape.Circular ? ApertureShape.Circular : ApertureShape.RegularPolygon,
parameters.BladeCount,
parameters.BladeRotation,
parameters.Obstruction,
aberration);
var result = generator.Generate(descriptor);
var nextBitmap = PsfBitmapFactory.Create(devices.DeviceContext, result.Kernel);
effect.SetKernel(null);
disposer.RemoveAndDispose(ref kernelBitmap);
kernelBitmap = nextBitmap;
disposer.Collect(kernelBitmap);
effect.KernelSize = result.Kernel.Size;
effect.SetKernel(kernelBitmap);
}
static int GetGridSize(WaveOpticsQuality quality)
{
return quality switch
{
WaveOpticsQuality.Draft => 128,
WaveOpticsQuality.High => 512,
_ => 256,
};
}
static float Sanitize(double value, double minimum, double maximum, double fallback)
{
if (!double.IsFinite(value))
return (float)fallback;
return (float)Math.Clamp(value, minimum, maximum);
}
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
{
effect = new WaveOpticsConvolutionEffect(devices);
if (!effect.IsEnabled)
{
effect.Dispose();
effect = null;
return null;
}
disposer.Collect(effect);
var output = effect.Output;
disposer.Collect(output);
return output;
}
protected override void setInput(ID2D1Image? input)
{
effect?.SetSource(input);
}
protected override void ClearEffectChain()
{
effect?.SetSource(null);
effect?.SetKernel(null);
currentParameters = null;
isFirst = true;
}
readonly record struct Parameters(
int GridSize,
int KernelSize,
float Wavelength,
float FNumber,
float PixelPitch,
WaveOpticsApertureShape ApertureShape,
int BladeCount,
float BladeRotation,
float Obstruction,
float Defocus,
float AstigmatismVertical,
float AstigmatismOblique,
float ComaHorizontal,
float ComaVertical,
float Spherical);
}
-92
ファイルの表示
@@ -1,92 +0,0 @@
using System.Numerics;
namespace WaveOptics.Fourier;
internal static class FastFourierTransform
{
public static void Forward(Span<Complex> values) => Transform(values, false);
public static void Inverse(Span<Complex> values) => Transform(values, true);
public static void Forward2D(Complex[] values, int width, int height) => Transform2D(values, width, height, false);
public static void Inverse2D(Complex[] values, int width, int height) => Transform2D(values, width, height, true);
static void Transform(Span<Complex> values, bool inverse)
{
var count = values.Length;
if (count == 0 || !BitOperations.IsPow2((uint)count))
throw new ArgumentException(nameof(values));
var target = 0;
for (var source = 1; source < count; source++)
{
var bit = count >> 1;
while ((target & bit) != 0)
{
target ^= bit;
bit >>= 1;
}
target ^= bit;
if (source < target)
(values[source], values[target]) = (values[target], values[source]);
}
for (var length = 2; length <= count; length <<= 1)
{
var angle = (inverse ? 2d : -2d) * Math.PI / length;
var step = Complex.FromPolarCoordinates(1d, angle);
var half = length >> 1;
for (var offset = 0; offset < count; offset += length)
{
var factor = Complex.One;
for (var index = 0; index < half; index++)
{
var even = values[offset + index];
var odd = values[offset + index + half] * factor;
values[offset + index] = even + odd;
values[offset + index + half] = even - odd;
factor *= step;
}
}
}
if (!inverse)
return;
var scale = 1d / count;
for (var index = 0; index < count; index++)
values[index] *= scale;
}
static void Transform2D(Complex[] values, int width, int height, bool inverse)
{
ArgumentNullException.ThrowIfNull(values);
if (values.Length != width * height)
throw new ArgumentException(nameof(values));
if (!BitOperations.IsPow2((uint)width) || !BitOperations.IsPow2((uint)height))
throw new ArgumentException(nameof(width));
for (var y = 0; y < height; y++)
{
var row = values.AsSpan(y * width, width);
if (inverse)
Inverse(row);
else
Forward(row);
}
var column = new Complex[height];
for (var x = 0; x < width; x++)
{
for (var y = 0; y < height; y++)
column[y] = values[y * width + x];
if (inverse)
Inverse(column);
else
Forward(column);
for (var y = 0; y < height; y++)
values[y * width + x] = column[y];
}
}
}
-139
ファイルの表示
@@ -1,139 +0,0 @@
using System.Numerics;
using WaveOptics.Abstractions;
using WaveOptics.Fourier;
namespace WaveOptics.Optics;
public sealed class FraunhoferPsfGenerator : IPsfGenerator
{
const double TwoPi = 2 * Math.PI;
public OpticalApiVersion ApiVersion => OpticalApiVersion.Current;
public OpticalCapabilities Capabilities => OpticalCapabilities.MonochromaticPsf
| OpticalCapabilities.CircularAperture
| OpticalCapabilities.RegularPolygonAperture
| OpticalCapabilities.CentralObstruction
| OpticalCapabilities.ZernikeAberration
| OpticalCapabilities.DirectConvolution;
public PsfGenerationResult Generate(PsfDescriptor descriptor)
{
ArgumentNullException.ThrowIfNull(descriptor);
var gridSize = descriptor.PupilGridSize;
var pupilDiameter = descriptor.PupilDiameterSamples;
var pupil = new Complex[gridSize * gridSize];
var center = gridSize / 2;
var pupilRadius = pupilDiameter / 2d;
var rotation = descriptor.BladeRotationDegrees * Math.PI / 180d;
var openSampleCount = 0;
for (var y = 0; y < gridSize; y++)
{
var normalizedY = (y - center) / pupilRadius;
for (var x = 0; x < gridSize; x++)
{
var normalizedX = (x - center) / pupilRadius;
if (!IsInsideAperture(normalizedX, normalizedY, descriptor, rotation))
continue;
var waves = ZernikeWavefront.Evaluate(normalizedX, normalizedY, descriptor.Aberration);
pupil[y * gridSize + x] = Complex.FromPolarCoordinates(1d, TwoPi * waves);
openSampleCount++;
}
}
if (openSampleCount == 0)
throw new InvalidOperationException();
FastFourierTransform.Forward2D(pupil, gridSize, gridSize);
var intensity = new double[pupil.Length];
var fullEnergy = 0d;
for (var y = 0; y < gridSize; y++)
{
var sourceY = (y + center) % gridSize;
for (var x = 0; x < gridSize; x++)
{
var sourceX = (x + center) % gridSize;
var value = pupil[sourceY * gridSize + sourceX].Magnitude;
value *= value;
intensity[y * gridSize + x] = value;
fullEnergy += value;
}
}
if (!double.IsFinite(fullEnergy) || fullEnergy <= 0)
throw new InvalidOperationException();
var inverseEnergy = 1d / fullEnergy;
for (var index = 0; index < intensity.Length; index++)
intensity[index] *= inverseEnergy;
var wavelengthMicrometers = descriptor.WavelengthNanometers / 1000d;
var focalPlaneSamplePitch = wavelengthMicrometers * descriptor.FNumber * pupilDiameter / gridSize;
var kernel = new double[descriptor.KernelSize * descriptor.KernelSize];
var kernelRadius = descriptor.KernelSize / 2;
var unnormalizedKernelEnergy = 0d;
for (var y = 0; y < descriptor.KernelSize; y++)
{
var physicalY = (y - kernelRadius) * descriptor.SensorPixelPitchMicrometers;
var sampleY = center + physicalY / focalPlaneSamplePitch;
for (var x = 0; x < descriptor.KernelSize; x++)
{
var physicalX = (x - kernelRadius) * descriptor.SensorPixelPitchMicrometers;
var sampleX = center + physicalX / focalPlaneSamplePitch;
var value = SampleBilinear(intensity, gridSize, sampleX, sampleY);
kernel[y * descriptor.KernelSize + x] = value;
unnormalizedKernelEnergy += value;
}
}
if (!double.IsFinite(unnormalizedKernelEnergy) || unnormalizedKernelEnergy <= 0)
throw new InvalidOperationException();
var psfKernel = new PsfKernel(descriptor.KernelSize, kernel);
var diagnostics = new PsfDiagnostics(
openSampleCount,
focalPlaneSamplePitch,
unnormalizedKernelEnergy,
psfKernel.Values.Span.ToArray().Max());
return new PsfGenerationResult(psfKernel, diagnostics);
}
static bool IsInsideAperture(double x, double y, PsfDescriptor descriptor, double rotation)
{
var radiusSquared = x * x + y * y;
var obstructionSquared = descriptor.CentralObstructionRatio * descriptor.CentralObstructionRatio;
if (radiusSquared > 1d || radiusSquared < obstructionSquared)
return false;
if (descriptor.ApertureShape == ApertureShape.Circular)
return true;
var radius = Math.Sqrt(radiusSquared);
if (radius == 0)
return descriptor.CentralObstructionRatio == 0;
var sector = TwoPi / descriptor.BladeCount;
var angle = Math.Atan2(y, x) - rotation;
var folded = angle - sector * Math.Round(angle / sector);
var boundary = Math.Cos(Math.PI / descriptor.BladeCount) / Math.Cos(folded);
return radius <= boundary;
}
static double SampleBilinear(double[] values, int size, double x, double y)
{
if (x < 0 || y < 0 || x > size - 1 || y > size - 1)
return 0;
var x0 = (int)Math.Floor(x);
var y0 = (int)Math.Floor(y);
var x1 = Math.Min(x0 + 1, size - 1);
var y1 = Math.Min(y0 + 1, size - 1);
var tx = x - x0;
var ty = y - y0;
var top = values[y0 * size + x0] * (1 - tx) + values[y0 * size + x1] * tx;
var bottom = values[y1 * size + x0] * (1 - tx) + values[y1 * size + x1] * tx;
return top * (1 - ty) + bottom * ty;
}
}
-45
ファイルの表示
@@ -1,45 +0,0 @@
using System.Runtime.InteropServices;
using Vortice.DCommon;
using Vortice.Direct2D1;
using Vortice.DXGI;
using Vortice.Mathematics;
using WaveOptics.Abstractions;
namespace WaveOptics.Rendering;
internal static class PsfBitmapFactory
{
public static ID2D1Bitmap Create(ID2D1DeviceContext deviceContext, PsfKernel kernel)
{
var values = kernel.Values.Span;
var pixels = new float[values.Length * 4];
for (var index = 0; index < values.Length; index++)
{
var value = (float)values[index];
var offset = index * 4;
pixels[offset] = value;
pixels[offset + 1] = value;
pixels[offset + 2] = value;
pixels[offset + 3] = 1;
}
var handle = GCHandle.Alloc(pixels, GCHandleType.Pinned);
try
{
var properties = new BitmapProperties1(
new PixelFormat(Format.R32G32B32A32_Float, Vortice.DCommon.AlphaMode.Ignore),
96,
96,
BitmapOptions.None);
return ((ID2D1DeviceContext1)deviceContext).CreateBitmap(
new SizeI(kernel.Size, kernel.Size),
handle.AddrOfPinnedObject(),
kernel.Size * 4 * sizeof(float),
properties);
}
finally
{
handle.Free();
}
}
}
-133
ファイルの表示
@@ -1,133 +0,0 @@
using System.Numerics;
using System.Runtime.InteropServices;
using Vortice;
using Vortice.Direct2D1;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Player.Video;
namespace WaveOptics.Rendering;
internal sealed class WaveOpticsConvolutionEffect(IGraphicsDevicesAndContext devices)
: D2D1CustomShaderEffectBase(Create<EffectImpl>(devices))
{
public const int MaximumKernelSize = 31;
public int KernelSize
{
get => GetIntValue((int)EffectImpl.Properties.KernelSize);
set => SetValue((int)EffectImpl.Properties.KernelSize, value);
}
public float Amount
{
get => GetFloatValue((int)EffectImpl.Properties.Amount);
set => SetValue((int)EffectImpl.Properties.Amount, value);
}
public float Gain
{
get => GetFloatValue((int)EffectImpl.Properties.Gain);
set => SetValue((int)EffectImpl.Properties.Gain, value);
}
public void SetSource(ID2D1Image? image) => SetInput(0, image, true);
public void SetKernel(ID2D1Image? image) => SetInput(1, image, true);
[CustomEffect(2)]
sealed class EffectImpl : D2D1CustomShaderEffectImplBase<EffectImpl>
{
ConstantBuffer constants;
RawRect kernelRect;
[CustomEffectProperty(PropertyType.Int32, (int)Properties.KernelSize)]
public int KernelSize
{
get => constants.KernelSize;
set
{
var clamped = Math.Clamp(value, 1, MaximumKernelSize);
constants.KernelSize = (clamped & 1) == 0 ? clamped - 1 : clamped;
UpdateConstants();
}
}
[CustomEffectProperty(PropertyType.Float, (int)Properties.Amount)]
public float Amount
{
get => constants.Amount;
set
{
constants.Amount = float.IsFinite(value) ? Math.Clamp(value, 0, 1) : 0;
UpdateConstants();
}
}
[CustomEffectProperty(PropertyType.Float, (int)Properties.Gain)]
public float Gain
{
get => constants.Gain;
set
{
constants.Gain = float.IsFinite(value) ? Math.Clamp(value, 0, 4) : 1;
UpdateConstants();
}
}
public EffectImpl() : base(ShaderResourceUri.Get("WaveOpticsConvolution"))
{
constants.KernelSize = 1;
constants.Gain = 1;
}
protected override void UpdateConstants()
{
drawInformation?.SetPixelShaderConstantBuffer(constants);
}
public override void MapInputRectsToOutputRect(RawRect[] inputRects, RawRect[] inputOpaqueSubRects, out RawRect outputRect, out RawRect outputOpaqueSubRect)
{
inputRect = inputRects[0];
kernelRect = inputRects[1];
constants.InputBounds = new Vector4(inputRect.Left, inputRect.Top, inputRect.Right, inputRect.Bottom);
UpdateConstants();
outputRect = Inflate(inputRect, GetRadius());
outputOpaqueSubRect = default;
}
public override void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects)
{
inputRects[0] = Inflate(outputRect, GetRadius());
inputRects[1] = kernelRect;
}
int GetRadius() => constants.Amount > 0 ? constants.KernelSize / 2 : 0;
static RawRect Inflate(RawRect rect, int radius)
{
return new RawRect(
Saturate((long)rect.Left - radius),
Saturate((long)rect.Top - radius),
Saturate((long)rect.Right + radius),
Saturate((long)rect.Bottom + radius));
}
static int Saturate(long value) => (int)Math.Clamp(value, int.MinValue, int.MaxValue);
[StructLayout(LayoutKind.Sequential)]
struct ConstantBuffer
{
public int KernelSize;
public float Amount;
public float Gain;
public float Padding;
public Vector4 InputBounds;
}
public enum Properties
{
KernelSize,
Amount,
Gain,
}
}
}
-55
ファイルの表示
@@ -1,55 +0,0 @@
Texture2D InputTexture : register(t0);
Texture2D KernelTexture : register(t1);
SamplerState InputSampler : register(s0);
static const int MaximumRadius = 15;
cbuffer Constants : register(b0)
{
int kernelSize : packoffset(c0.x);
float amount : packoffset(c0.y);
float gain : packoffset(c0.z);
float4 inputBounds : packoffset(c1);
};
float4 SampleInput(float2 uv, float2 scenePosition)
{
if (scenePosition.x < inputBounds.x || scenePosition.y < inputBounds.y ||
scenePosition.x >= inputBounds.z || scenePosition.y >= inputBounds.w)
return (float4)0;
return InputTexture.SampleLevel(InputSampler, uv, 0);
}
float4 main(
float4 position : SV_POSITION,
float4 scenePosition : SCENE_POSITION,
float4 uv0 : TEXCOORD0,
float4 uv1 : TEXCOORD1
) : SV_TARGET
{
float4 source = SampleInput(uv0.xy, scenePosition.xy);
if (amount <= 0.0f || kernelSize <= 1)
return source;
int radius = clamp(kernelSize / 2, 0, MaximumRadius);
float4 convolved = (float4)0;
[loop]
for (int y = -MaximumRadius; y <= MaximumRadius; y++)
{
if (abs(y) > radius)
continue;
[loop]
for (int x = -MaximumRadius; x <= MaximumRadius; x++)
{
if (abs(x) > radius)
continue;
float weight = KernelTexture.Load(int3(x + radius, y + radius, 0)).r;
float2 offset = float2(x, y);
convolved += SampleInput(uv0.xy + offset * uv0.zw, scenePosition.xy + offset) * weight;
}
}
convolved *= gain;
return lerp(source, convolved, amount);
}
+55
ファイルの表示
@@ -0,0 +1,55 @@
using System.IO;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Json;
namespace WaveOptics.Harness;
internal sealed record GoldenCase(string Name, IReadOnlyList<int> Frames, string Hash);
internal sealed record Golden(string Adapter, string Driver, string Input, string Canvas, IReadOnlyList<GoldenCase> Cases)
{
const string FileName = "golden.json";
const string DirectoryKey = "HarnessDirectory";
static readonly JsonSerializerOptions Options = new()
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
NewLine = "\n",
};
public static string PathFor(HarnessImage image)
=> Path.Combine(ReadDirectory(), image.Key is null ? FileName : $"golden-{image.Key}.json");
public static Golden Load(string path)
{
if (!File.Exists(path))
throw new HarnessException($"基準値がありません。先に --golden で書いてください。{path}");
Golden? golden;
try
{
golden = JsonSerializer.Deserialize<Golden>(File.ReadAllBytes(path), Options);
}
catch (JsonException exception)
{
throw new HarnessException($"基準値を読めません。{path} {exception.Message}");
}
if (golden is not { Adapter: not null, Driver: not null, Input: not null, Canvas: not null, Cases: not null }
|| golden.Cases.Any(item => item is not { Name: not null, Frames: not null, Hash: not null }))
throw new HarnessException($"基準値の項目が足りません。{path}");
if (golden.Cases.Select(item => item.Name).Distinct(StringComparer.Ordinal).Count() != golden.Cases.Count)
throw new HarnessException($"基準値のケース名が重複しています。{path}");
return golden;
}
public void Save(string path) => File.WriteAllBytes(path, JsonSerializer.SerializeToUtf8Bytes(this, Options));
static string ReadDirectory()
=> typeof(Golden).Assembly
.GetCustomAttributes<AssemblyMetadataAttribute>()
.FirstOrDefault(attribute => string.Equals(attribute.Key, DirectoryKey, StringComparison.Ordinal))
?.Value ?? throw new HarnessException($"アセンブリに {DirectoryKey} がありません。");
}
+63
ファイルの表示
@@ -0,0 +1,63 @@
using System.Diagnostics;
using Vortice.Direct3D11;
namespace WaveOptics.Harness;
internal sealed class GpuTimer : IDisposable
{
static readonly TimeSpan ResolveTimeout = TimeSpan.FromSeconds(5);
readonly ID3D11DeviceContext context;
readonly ID3D11Query disjoint;
readonly ID3D11Query start;
readonly ID3D11Query stop;
public GpuTimer(ID3D11Device device, ID3D11DeviceContext context)
{
this.context = context;
disjoint = device.CreateQuery(new QueryDescription(QueryType.TimestampDisjoint, QueryFlags.None));
start = device.CreateQuery(new QueryDescription(QueryType.Timestamp, QueryFlags.None));
stop = device.CreateQuery(new QueryDescription(QueryType.Timestamp, QueryFlags.None));
}
public void Begin()
{
context.Begin(disjoint);
context.End(start);
}
public void End()
{
context.End(stop);
context.End(disjoint);
}
public TimeSpan? Resolve()
{
if (!Wait<QueryDataTimestampDisjoint>(disjoint, out var timing) || timing.Disjoint || timing.Frequency == 0UL)
return null;
if (!Wait<ulong>(start, out var began) || !Wait<ulong>(stop, out var ended) || ended < began)
return null;
return TimeSpan.FromSeconds((ended - began) / (double)timing.Frequency);
}
bool Wait<T>(ID3D11Query query, out T value) where T : unmanaged
{
var elapsed = Stopwatch.StartNew();
while (!context.GetData(query, out value))
{
if (elapsed.Elapsed > ResolveTimeout)
return false;
Thread.Yield();
}
return true;
}
public void Dispose()
{
stop.Dispose();
start.Dispose();
disjoint.Dispose();
}
}
+93
ファイルの表示
@@ -0,0 +1,93 @@
namespace WaveOptics.Harness;
internal sealed class HarnessException(string message) : Exception(message);
internal enum HarnessMode
{
Render,
Golden,
Verify,
Transition,
Compare,
Benchmark,
Convolution,
}
internal sealed record HarnessArguments(HarnessMode Mode, string? Input, string? OutputDirectory, string? Before, string? After)
{
public const string Usage = """
使い方:
[<出力先>] [--input <画像>] ケースを描き、PNG とハッシュを出します
--golden [--input <画像>] 基準値を golden.json に書きます
--verify [--input <画像>] 基準値と照合します
--transition [<出力先>] [--input <画像>] 設定を変えた後とフレームを進めた後の描画を、作り直した描画と照合します
--compare <前> <後> 2 つの出力先の PNG を画素ごとに比べます
--benchmark [--input <画像>] 描画を計測します
--convolution [--input <画像>] 畳み込みの計算し直しに掛かる時間を、変えた値ごとに計測します
""";
public static HarnessArguments Parse(string[] arguments)
{
HarnessMode? mode = null;
string? input = null;
var positionals = new List<string>();
for (var index = 0; index < arguments.Length; index++)
{
var argument = arguments[index];
switch (argument)
{
case "--golden":
mode = Select(mode, HarnessMode.Golden);
break;
case "--verify":
mode = Select(mode, HarnessMode.Verify);
break;
case "--transition":
mode = Select(mode, HarnessMode.Transition);
break;
case "--compare":
mode = Select(mode, HarnessMode.Compare);
break;
case "--benchmark":
mode = Select(mode, HarnessMode.Benchmark);
break;
case "--convolution":
mode = Select(mode, HarnessMode.Convolution);
break;
case "--input":
if (index + 1 >= arguments.Length)
throw new HarnessException("--input には画像のパスを続けてください。");
input = arguments[++index];
break;
default:
if (argument.StartsWith('-'))
throw new HarnessException($"不明なオプションです。{argument}");
positionals.Add(argument);
break;
}
}
var selected = mode ?? HarnessMode.Render;
switch (selected)
{
case HarnessMode.Compare:
if (positionals.Count != 2)
throw new HarnessException("--compare には前と後の出力先を続けてください。");
if (input is not null)
throw new HarnessException("--compare に --input は使えません。");
return new HarnessArguments(HarnessMode.Compare, null, null, positionals[0], positionals[1]);
case HarnessMode.Render:
case HarnessMode.Transition:
if (positionals.Count > 1)
throw new HarnessException($"余分な引数です。{positionals[1]}");
return new HarnessArguments(selected, input, positionals.FirstOrDefault(), null, null);
default:
if (positionals.Count > 0)
throw new HarnessException($"余分な引数です。{positionals[0]}");
return new HarnessArguments(selected, input, null, null, null);
}
}
static HarnessMode Select(HarnessMode? current, HarnessMode next)
=> current is null ? next : throw new HarnessException("モードは 1 つだけ指定してください。");
}
+100
ファイルの表示
@@ -0,0 +1,100 @@
using System.Globalization;
using WaveOptics.Effects;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Json;
namespace WaveOptics.Harness;
internal static class HarnessCases
{
public static IEnumerable<(string Name, WaveOpticsEffect Effect, IReadOnlyList<int> Frames)> All()
{
yield return ("default", Create(), [0]);
yield return ("default-frames-0-8", Create(), Enumerable.Range(0, 9).ToArray());
yield return ("amount-0", Create(effect => effect.Amount.Values[0].Value = 0), [0]);
yield return ("amount-50", Create(effect => effect.Amount.Values[0].Value = 50), [0]);
yield return ("gain-50", Create(effect => effect.Gain.Values[0].Value = 50), [0]);
yield return ("gain-400", Create(effect => effect.Gain.Values[0].Value = 400), [0]);
yield return ("gain-400-amount-50", Create(effect =>
{
effect.Gain.Values[0].Value = 400;
effect.Amount.Values[0].Value = 50;
}), [0]);
yield return ("wavelength-380", Create(effect => effect.Wavelength.Values[0].Value = 380), [0]);
yield return ("wavelength-780", Create(effect => effect.Wavelength.Values[0].Value = 780), [0]);
yield return ("f-number-4", Create(effect => effect.FNumber.Values[0].Value = 4), [0]);
yield return ("f-number-64", Create(effect => effect.FNumber.Values[0].Value = 64), [0]);
yield return ("pixel-pitch-0.25", Create(effect => effect.PixelPitch.Values[0].Value = 0.25), [0]);
yield return ("pixel-pitch-2", Create(effect => effect.PixelPitch.Values[0].Value = 2), [0]);
yield return ("kernel-radius-1", Create(effect => effect.KernelRadius = 1), [0]);
yield return ("kernel-radius-5", Create(effect => effect.KernelRadius = 5), [0]);
yield return ("quality-draft", Create(effect => effect.Quality = WaveOpticsQuality.Draft), [0]);
yield return ("quality-high", Create(effect => effect.Quality = WaveOpticsQuality.High), [0]);
yield return ("aperture-polygon", Create(effect => effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon), [0]);
yield return ("blade-count-3", Create(effect =>
{
effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon;
effect.BladeCount = 3;
}), [0]);
yield return ("blade-count-32", Create(effect =>
{
effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon;
effect.BladeCount = 32;
}), [0]);
yield return ("blade-rotation-30", Create(effect =>
{
effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon;
effect.BladeRotation.Values[0].Value = 30;
}), [0]);
yield return ("obstruction-50", Create(effect => effect.Obstruction.Values[0].Value = 50), [0]);
yield return ("defocus-1", Create(effect => effect.Defocus.Values[0].Value = 1), [0]);
yield return ("astigmatism-vertical-1", Create(effect => effect.AstigmatismVertical.Values[0].Value = 1), [0]);
yield return ("astigmatism-oblique-1", Create(effect => effect.AstigmatismOblique.Values[0].Value = 1), [0]);
yield return ("coma-horizontal-1", Create(effect => effect.ComaHorizontal.Values[0].Value = 1), [0]);
yield return ("coma-vertical-1", Create(effect => effect.ComaVertical.Values[0].Value = 1), [0]);
yield return ("spherical-1", Create(effect => effect.Spherical.Values[0].Value = 1), [0]);
yield return ("defocus-animated-frames-0-8", Create(effect => effect.Defocus.CopyFrom(Linear(0d, 3d))), Enumerable.Range(0, 9).ToArray());
}
public static IEnumerable<(string Name, Func<WaveOpticsEffect> Create, Action<WaveOpticsEffect> Change, int Frame)> Transitions()
{
yield return ("amount-100-to-50", () => Create(), effect => effect.Amount.Values[0].Value = 50, 0);
yield return ("gain-100-to-400", () => Create(), effect => effect.Gain.Values[0].Value = 400, 0);
yield return ("wavelength-550-to-780", () => Create(), effect => effect.Wavelength.Values[0].Value = 780, 0);
yield return ("f-number-8-to-32", () => Create(), effect => effect.FNumber.Values[0].Value = 32, 0);
yield return ("pixel-pitch-4-to-2", () => Create(), effect => effect.PixelPitch.Values[0].Value = 2, 0);
yield return ("kernel-radius-15-to-5", () => Create(), effect => effect.KernelRadius = 5, 0);
yield return ("quality-standard-to-high", () => Create(), effect => effect.Quality = WaveOpticsQuality.High, 0);
yield return ("aperture-circular-to-polygon", () => Create(), effect => effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon, 0);
yield return ("blade-count-6-to-5", () => Create(effect => effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon), effect => effect.BladeCount = 5, 0);
yield return ("blade-rotation-0-to-30", () => Create(effect => effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon), effect => effect.BladeRotation.Values[0].Value = 30, 0);
yield return ("obstruction-0-to-50", () => Create(), effect => effect.Obstruction.Values[0].Value = 50, 0);
yield return ("defocus-0-to-1", () => Create(), effect => effect.Defocus.Values[0].Value = 1, 0);
yield return ("astigmatism-vertical-0-to-1", () => Create(), effect => effect.AstigmatismVertical.Values[0].Value = 1, 0);
yield return ("astigmatism-oblique-0-to-1", () => Create(), effect => effect.AstigmatismOblique.Values[0].Value = 1, 0);
yield return ("coma-horizontal-0-to-1", () => Create(), effect => effect.ComaHorizontal.Values[0].Value = 1, 0);
yield return ("coma-vertical-0-to-1", () => Create(), effect => effect.ComaVertical.Values[0].Value = 1, 0);
yield return ("spherical-0-to-1", () => Create(), effect => effect.Spherical.Values[0].Value = 1, 0);
yield return ("amount-100-to-0", () => Create(), effect => effect.Amount.Values[0].Value = 0, 0);
}
public static IEnumerable<(string Name, WaveOpticsEffect Effect)> Benchmarks()
{
yield return ("quality-draft", Create(effect => effect.Quality = WaveOpticsQuality.Draft));
yield return ("default", Create());
yield return ("quality-high", Create(effect => effect.Quality = WaveOpticsQuality.High));
yield return ("kernel-radius-5", Create(effect => effect.KernelRadius = 5));
yield return ("defocus-animated", Create(effect => effect.Defocus.CopyFrom(Linear(0d, 3d))));
yield return ("amount-0", Create(effect => effect.Amount.Values[0].Value = 0));
}
static Animation Linear(double from, double to)
=> Json.LoadFromText<Animation>(string.Create(CultureInfo.InvariantCulture, $$"""{"AnimationType":"直線移動","Values":[{"Value":{{from}}},{"Value":{{to}}}]}""")) ?? throw new HarnessException("アニメーションを読み込めません。");
public static WaveOpticsEffect Create(Action<WaveOpticsEffect>? configure = null)
{
var effect = new WaveOpticsEffect();
configure?.Invoke(effect);
return effect;
}
}
+59
ファイルの表示
@@ -0,0 +1,59 @@
using System.IO;
using System.Security.Cryptography;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace WaveOptics.Harness;
internal sealed record HarnessImage(int Width, int Height, byte[] Pixels, string Identity, string? Key)
{
public const int BytesPerPixel = 4;
const int KeyLength = 16;
public static HarnessImage Synthetic(int width, int height)
{
var pixels = SyntheticImage.Create(width, height);
return new HarnessImage(width, height, pixels, $"synthetic {width}x{height} {Convert.ToHexString(SHA256.HashData(pixels))[..KeyLength]}", null);
}
public static HarnessImage Load(string path)
{
if (!File.Exists(path))
throw new HarnessException($"入力の画像がありません。{path}");
var bytes = File.ReadAllBytes(path);
var (width, height, pixels) = Decode(bytes, path);
var hash = Convert.ToHexString(SHA256.HashData(bytes));
return new HarnessImage(width, height, pixels, $"{hash} {width}x{height}", hash[..KeyLength]);
}
public static (int Width, int Height, byte[] Pixels) LoadPremultiplied(string path) => Decode(File.ReadAllBytes(path), path);
public static void Save(string path, byte[] pixels, int width, int height)
{
var source = BitmapSource.Create(width, height, 96, 96, PixelFormats.Pbgra32, null, pixels, width * BytesPerPixel);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(source));
using var stream = File.Create(path);
encoder.Save(stream);
}
static (int Width, int Height, byte[] Pixels) Decode(byte[] bytes, string path)
{
using var stream = new MemoryStream(bytes);
BitmapDecoder decoder;
try
{
decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
}
catch (Exception exception) when (exception is NotSupportedException or FileFormatException)
{
throw new HarnessException($"画像として読めません。{path}");
}
var converted = new FormatConvertedBitmap(decoder.Frames[0], PixelFormats.Pbgra32, null, 0d);
var pixels = new byte[converted.PixelWidth * converted.PixelHeight * BytesPerPixel];
converted.CopyPixels(pixels, converted.PixelWidth * BytesPerPixel, 0);
return (converted.PixelWidth, converted.PixelHeight, pixels);
}
}
+262
ファイルの表示
@@ -0,0 +1,262 @@
using System.Diagnostics;
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;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Plugin.Effects;
namespace WaveOptics.Harness;
internal sealed class HarnessRenderer : IDisposable
{
const int Fps = 30;
const int Length = 300;
const int WarmupUpdates = 2000;
const int UpdateRepeats = 20;
const float Dpi = 96f;
static readonly PixelFormat PixelFormat = new(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
readonly GraphicsDevices devices;
readonly IGraphicsDevicesAndContext context;
readonly ID2D1Bitmap1 image;
readonly ID2D1Bitmap1 target;
readonly ID2D1Bitmap1 readback;
readonly ID2D1Bitmap1 sync;
readonly GpuTimer timer;
readonly AffineTransform2D placement;
readonly ID2D1Image centered;
public HarnessRenderer(int canvasWidth, int canvasHeight, HarnessImage source)
{
CanvasWidth = canvasWidth;
CanvasHeight = canvasHeight;
devices = new GraphicsDevices();
context = devices.CreateContext();
var deviceContext = context.DeviceContext;
var adapter = devices.DXGI.Adapter;
Adapter = adapter.Description.Description;
Driver = adapter.CheckInterfaceSupport<IDXGIDevice>(out var version) ? FormatDriverVersion(version) : "不明";
image = CreateBitmap(deviceContext, source.Width, source.Height, BitmapOptions.None);
image.CopyFromMemory(source.Pixels, source.Width * HarnessImage.BytesPerPixel);
target = CreateBitmap(deviceContext, canvasWidth, canvasHeight, BitmapOptions.Target);
readback = CreateBitmap(deviceContext, canvasWidth, canvasHeight, BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
sync = CreateBitmap(deviceContext, 1, 1, BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
timer = new GpuTimer(devices.D3D.Device, devices.D3D.DeviceContext);
placement = new AffineTransform2D(deviceContext)
{
TransformMatrix = Matrix3x2.CreateTranslation(-source.Width * 0.5f, -source.Height * 0.5f),
};
placement.SetInput(0, image, true);
centered = placement.Output;
}
public int CanvasWidth { get; }
public int CanvasHeight { get; }
public string Adapter { get; }
public string Driver { get; }
public byte[][] Render(IVideoEffect effect, IReadOnlyList<int> frames)
{
if (frames.Count == 0)
throw new ArgumentException("フレームを 1 つ以上指定してください。", nameof(frames));
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(centered);
try
{
var rendered = new byte[frames.Count][];
for (var index = 0; index < frames.Count; index++)
{
processor.Update(Describe(frames[index]));
rendered[index] = Capture(processor.Output);
}
return rendered;
}
finally
{
processor.ClearInput();
}
}
public (byte[] Direct, byte[] Transitioned) RenderTransition<TEffect>(Func<TEffect> create, Action<TEffect> change, int frame)
where TEffect : IVideoEffect
{
var settled = create();
change(settled);
var direct = Render(settled, [frame])[0];
var live = create();
using var processor = live.CreateVideoEffect(context);
processor.SetInput(centered);
try
{
processor.Update(Describe(frame));
_ = Capture(processor.Output);
change(live);
processor.Update(Describe(frame));
return (direct, Capture(processor.Output));
}
finally
{
processor.ClearInput();
}
}
public Measurement Measure(IVideoEffect effect, int frames, bool moving)
{
var descriptions = new EffectDescription[frames];
for (var frame = 0; frame < frames; frame++)
descriptions[frame] = Describe(moving ? frame : 0);
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(centered);
var output = processor.Output;
try
{
for (var index = 0; index < WarmupUpdates; index++)
processor.Update(descriptions[index % frames]);
for (var frame = 0; frame < frames; frame++)
{
processor.Update(descriptions[frame]);
Submit(output);
}
Synchronize();
var cpu = TimeSpan.MaxValue;
for (var frame = 0; frame < frames; frame++)
{
var elapsed = Stopwatch.StartNew();
processor.Update(descriptions[frame]);
Submit(output);
elapsed.Stop();
cpu = elapsed.Elapsed < cpu ? elapsed.Elapsed : cpu;
}
Synchronize();
TimeSpan? gpu = null;
for (var frame = 0; frame < frames; frame++)
{
processor.Update(descriptions[frame]);
timer.Begin();
Submit(output);
timer.End();
if (timer.Resolve() is { } resolved && (gpu is null || resolved < gpu))
gpu = resolved;
}
Synchronize();
var repeats = frames * UpdateRepeats;
var updates = Stopwatch.StartNew();
for (var index = 0; index < repeats; index++)
processor.Update(descriptions[index % frames]);
updates.Stop();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var before = GC.GetAllocatedBytesForCurrentThread();
var collections = GC.CollectionCount(0);
for (var frame = 0; frame < frames; frame++)
processor.Update(descriptions[frame]);
var allocated = (GC.GetAllocatedBytesForCurrentThread() - before) / frames;
var gen0 = GC.CollectionCount(0) - collections;
return new Measurement(gpu, cpu, updates.Elapsed / repeats, allocated, gen0);
}
finally
{
processor.ClearInput();
}
}
byte[] Capture(ID2D1Image output)
{
Submit(output);
readback.CopyFromBitmap(target);
var stride = CanvasWidth * HarnessImage.BytesPerPixel;
var pixels = new byte[stride * CanvasHeight];
var mapped = readback.Map(MapOptions.Read);
try
{
for (var y = 0; y < CanvasHeight; y++)
Marshal.Copy(mapped.Bits + y * (int)mapped.Pitch, pixels, y * stride, stride);
}
finally
{
readback.Unmap();
}
return pixels;
}
void Submit(ID2D1Image output)
{
var deviceContext = context.DeviceContext;
deviceContext.Target = target;
deviceContext.BeginDraw();
deviceContext.Clear(new Color4(0f, 0f, 0f, 0f));
deviceContext.DrawImage(output, new Vector2(CanvasWidth * 0.5f, CanvasHeight * 0.5f), null, InterpolationMode.NearestNeighbor, CompositeMode.SourceOver);
deviceContext.EndDraw();
deviceContext.Target = null;
}
void Synchronize()
{
sync.CopyFromBitmap(Int2.Zero, target, new RectI(0, 0, 1, 1));
_ = sync.Map(MapOptions.Read);
sync.Unmap();
}
EffectDescription Describe(int frame)
{
var timeline = new TimelineSourceDescription(
new System.Drawing.Size(CanvasWidth, CanvasHeight),
new YukkuriMovieMaker.Player.Video.FrameTime(frame, Fps),
new YukkuriMovieMaker.Player.Video.FrameTime(Length, Fps),
Fps,
TimelineSourceUsage.Playing,
Guid.Empty,
[]);
var item = new TimelineItemSourceDescription(timeline, frame, Length, 0);
var draw = new DrawDescription(Vector3.Zero, Vector2.Zero, Vector2.One, Vector3.Zero, Matrix4x4.Identity, InterpolationMode.Linear, 1d, false, []);
return new EffectDescription(item, draw, 0, 1, 0, 1);
}
static ID2D1Bitmap1 CreateBitmap(ID2D1DeviceContext6 deviceContext, int width, int height, BitmapOptions options)
=> deviceContext.CreateBitmap(
new SizeI(width, height), nint.Zero, width * HarnessImage.BytesPerPixel,
new BitmapProperties1(PixelFormat, Dpi, Dpi, options));
static string FormatDriverVersion(long version)
=> $"{(version >> 48) & 0xFFFF}.{(version >> 32) & 0xFFFF}.{(version >> 16) & 0xFFFF}.{version & 0xFFFF}";
public void Dispose()
{
placement.SetInput(0, null, true);
centered.Dispose();
placement.Dispose();
timer.Dispose();
sync.Dispose();
readback.Dispose();
target.Dispose();
image.Dispose();
context.Dispose();
devices.Dispose();
}
public readonly record struct Measurement(TimeSpan? Gpu, TimeSpan Cpu, TimeSpan Update, long Allocated, int Gen0);
}
+37
ファイルの表示
@@ -0,0 +1,37 @@
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace WaveOptics.Harness;
internal static class HostAssemblyResolver
{
const string MetadataKey = "HostDirectory";
const string AssemblyExtension = ".dll";
public static string Directory { get; } = ReadDirectory();
public static bool IsConfigured => Directory.Length != 0 && System.IO.Directory.Exists(Directory);
[ModuleInitializer]
internal static void Initialize()
{
if (!IsConfigured)
return;
AppDomain.CurrentDomain.AssemblyResolve += (_, arguments) =>
{
var name = new AssemblyName(arguments.Name).Name;
if (name is null)
return null;
var candidate = Path.Combine(Directory, name + AssemblyExtension);
return File.Exists(candidate) ? Assembly.LoadFrom(candidate) : null;
};
}
static string ReadDirectory() => typeof(HostAssemblyResolver).Assembly
.GetCustomAttributes<AssemblyMetadataAttribute>()
.FirstOrDefault(attribute => string.Equals(attribute.Key, MetadataKey, StringComparison.Ordinal))
?.Value ?? string.Empty;
}
+46
ファイルの表示
@@ -0,0 +1,46 @@
namespace WaveOptics.Harness;
internal readonly record struct ImageDifference(int Differing, int MaxDelta, int Left, int Top, int Right, int Bottom)
{
public bool IsEmpty => Differing == 0;
public override string ToString()
=> IsEmpty ? "一致" : $"differing={Differing} maxDelta={MaxDelta} box=({Left},{Top})-({Right},{Bottom})";
}
internal static class ImageComparison
{
public static ImageDifference Of(byte[] first, byte[] second, int width, int height)
{
if (first.Length != second.Length || first.Length != width * height * HarnessImage.BytesPerPixel)
throw new ArgumentException("画像の寸法が一致しません。");
var differing = 0;
var maxDelta = 0;
var left = width;
var top = height;
var right = -1;
var bottom = -1;
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var offset = (y * width + x) * HarnessImage.BytesPerPixel;
var delta = 0;
for (var channel = 0; channel < HarnessImage.BytesPerPixel; channel++)
delta = Math.Max(delta, Math.Abs(first[offset + channel] - second[offset + channel]));
if (delta == 0)
continue;
differing++;
maxDelta = Math.Max(maxDelta, delta);
left = Math.Min(left, x);
top = Math.Min(top, y);
right = Math.Max(right, x);
bottom = Math.Max(bottom, y);
}
}
return differing == 0 ? default : new ImageDifference(differing, maxDelta, left, top, right, bottom);
}
}
+437
ファイルの表示
@@ -0,0 +1,437 @@
using System.Diagnostics;
using System.IO;
using System.IO.Packaging;
using System.Security.Cryptography;
using ComputeWeave;
using WaveOptics.Effects;
using WaveOptics.Harness;
using WaveOptics.Rendering;
using SharpGen.Runtime;
const int CanvasWidth = 1280;
const int CanvasHeight = 720;
const int ImageWidth = 640;
const int ImageHeight = 480;
const int FullHdWidth = 1920;
const int FullHdHeight = 1080;
_ = PackUriHelper.UriSchemePack;
HarnessArguments arguments;
try
{
arguments = HarnessArguments.Parse(args);
}
catch (HarnessException exception)
{
Console.Error.WriteLine(exception.Message);
Console.Error.WriteLine(HarnessArguments.Usage);
return 2;
}
try
{
if (arguments.Mode == HarnessMode.Compare)
return Compare(arguments.Before!, arguments.After!);
if (arguments.Mode == HarnessMode.Convolution)
{
var convolutionImage = arguments.Input is { } convolutionInput ? HarnessImage.Load(convolutionInput) : HarnessImage.Synthetic(FullHdWidth, FullHdHeight);
return Convolution(convolutionImage);
}
var outputDirectory = arguments.OutputDirectory ?? Path.Combine(AppContext.BaseDirectory, "harness-output");
if (arguments.Mode == HarnessMode.Benchmark)
{
if (arguments.Input is { } benchmarkInput)
{
Benchmark(HarnessImage.Load(benchmarkInput));
}
else
{
Benchmark(HarnessImage.Synthetic(CanvasWidth, CanvasHeight));
Benchmark(HarnessImage.Synthetic(FullHdWidth, FullHdHeight));
}
return 0;
}
var image = arguments.Input is { } input ? HarnessImage.Load(input) : HarnessImage.Synthetic(ImageWidth, ImageHeight);
using var renderer = new HarnessRenderer(CanvasWidth, CanvasHeight, image);
return arguments.Mode switch
{
HarnessMode.Golden => WriteGolden(renderer, image),
HarnessMode.Verify => Verify(renderer, image),
HarnessMode.Transition => Transition(renderer, outputDirectory),
_ => Render(renderer, outputDirectory),
};
}
catch (Exception exception) when (exception is HarnessException or SharpGenException)
{
Console.Error.WriteLine(exception.Message);
return 2;
}
static int Render(HarnessRenderer renderer, string outputDirectory)
{
Directory.CreateDirectory(outputDirectory);
var failures = 0;
var cases = Evaluate(renderer, (golden, files, frames) =>
{
Console.WriteLine($"{golden.Name}: {golden.Hash}");
for (var index = 0; index < files.Length; index++)
{
HarnessImage.Save(Path.Combine(outputDirectory, files[index]), frames[index], renderer.CanvasWidth, renderer.CanvasHeight);
var opaque = CountOpaque(frames[index]);
Console.WriteLine($" {files[index]} opaque={opaque}");
if (opaque == 0)
{
Console.Error.WriteLine($"{files[index]}: 出力が完全に透明です。");
failures++;
}
}
});
Console.WriteLine($"-> {outputDirectory}");
return failures + CountDuplicates(cases) == 0 ? 0 : 1;
}
static int WriteGolden(HarnessRenderer renderer, HarnessImage image)
{
var cases = Evaluate(renderer, null);
if (CountDuplicates(cases) != 0)
return 1;
if (cases.Count == 0)
Console.Error.WriteLine("ケースがありません。HarnessCases に書き足してください。");
var golden = new Golden(renderer.Adapter, renderer.Driver, image.Identity, $"{renderer.CanvasWidth}x{renderer.CanvasHeight}", cases);
var path = Golden.PathFor(image);
golden.Save(path);
Console.WriteLine($"adapter: {golden.Adapter} (driver {golden.Driver})");
Console.WriteLine($"input: {golden.Input}");
foreach (var (name, _, hash) in cases)
Console.WriteLine($"{name}: {hash}");
Console.WriteLine($"-> {path}");
return 0;
}
static int Verify(HarnessRenderer renderer, HarnessImage image)
{
var golden = Golden.Load(Golden.PathFor(image));
var canvas = $"{renderer.CanvasWidth}x{renderer.CanvasHeight}";
if (golden.Input != image.Identity || golden.Canvas != canvas)
{
Console.Error.WriteLine($"基準値は入力 {golden.Input} とキャンバス {golden.Canvas} で書かれています。今回は入力 {image.Identity} とキャンバス {canvas} です。");
return 1;
}
if (golden.Adapter != renderer.Adapter || golden.Driver != renderer.Driver)
Console.Error.WriteLine($"基準値は {golden.Adapter} (driver {golden.Driver}) で書かれています。今回は {renderer.Adapter} (driver {renderer.Driver}) です。画素の差はこの違いから来ることがあります。");
var failures = 0;
var current = Evaluate(renderer, null).ToDictionary(item => item.Name, StringComparer.Ordinal);
if (golden.Cases.Count == 0 && current.Count == 0)
Console.Error.WriteLine("ケースがありません。HarnessCases に書き足してください。");
foreach (var (name, frames, hash) in golden.Cases)
{
if (!current.Remove(name, out var actual))
{
Console.Error.WriteLine($"{name}: ケースがありません。基準値を書き直してください。");
failures++;
}
else if (!actual.Frames.SequenceEqual(frames))
{
Console.Error.WriteLine($"{name}: フレームが違います。基準値 [{string.Join(", ", frames)}]、今回 [{string.Join(", ", actual.Frames)}]。基準値を書き直してください。");
failures++;
}
else if (actual.Hash != hash)
{
Console.Error.WriteLine($"{name}: 一致しません。基準値 {hash}、今回 {actual.Hash}");
failures++;
}
else
{
Console.WriteLine($"{name}: 一致");
}
}
foreach (var name in current.Keys)
{
Console.Error.WriteLine($"{name}: 基準値にありません。基準値を書き直してください。");
failures++;
}
return failures == 0 ? 0 : 1;
}
static int Transition(HarnessRenderer renderer, string outputDirectory)
{
var failures = 0;
foreach (var (name, create, change, frame) in HarnessCases.Transitions())
{
var (direct, transitioned) = renderer.RenderTransition(create, change, frame);
var difference = ImageComparison.Of(direct, transitioned, renderer.CanvasWidth, renderer.CanvasHeight);
if (difference.IsEmpty)
{
Console.WriteLine($"{name}: 一致");
continue;
}
failures++;
Directory.CreateDirectory(outputDirectory);
HarnessImage.Save(Path.Combine(outputDirectory, name + "-direct.png"), direct, renderer.CanvasWidth, renderer.CanvasHeight);
HarnessImage.Save(Path.Combine(outputDirectory, name + "-transitioned.png"), transitioned, renderer.CanvasWidth, renderer.CanvasHeight);
Console.Error.WriteLine($"{name}: {difference}。設定を変えた後の描画が作り直した場合と違います。-> {outputDirectory}");
}
if (!HarnessCases.Transitions().Any() && !HarnessCases.All().Any(item => item.Frames.Count > 1))
Console.Error.WriteLine("ケースがありません。HarnessCases に書き足してください。");
foreach (var (name, effect, frames) in HarnessCases.All())
{
if (frames.Count < 2)
continue;
var sequential = renderer.Render(effect, frames);
for (var index = 0; index < frames.Count; index++)
{
var fresh = renderer.Render(effect, [frames[index]])[0];
var difference = ImageComparison.Of(fresh, sequential[index], renderer.CanvasWidth, renderer.CanvasHeight);
var label = $"{name}-f{frames[index]:D3}";
if (difference.IsEmpty)
{
Console.WriteLine($"{label}: 一致");
continue;
}
failures++;
Directory.CreateDirectory(outputDirectory);
HarnessImage.Save(Path.Combine(outputDirectory, label + "-direct.png"), fresh, renderer.CanvasWidth, renderer.CanvasHeight);
HarnessImage.Save(Path.Combine(outputDirectory, label + "-transitioned.png"), sequential[index], renderer.CanvasWidth, renderer.CanvasHeight);
Console.Error.WriteLine($"{label}: {difference}。前のフレームから進めた描画が作り直した場合と違います。-> {outputDirectory}");
}
}
return failures == 0 ? 0 : 1;
}
static int Convolution(HarnessImage image)
{
const int Rounds = 12;
const int Seed = 17;
using var pipeline = WaveOpticsPipeline.TryCreate();
if (pipeline is null)
throw new HarnessException("Direct3D 12を利用できません。");
var device = GraphicsDevice.GetDefault();
using var original = device.AllocateReadWriteTexture2D<Bgra32, Float4>(image.Width, image.Height);
using var mirrored = device.AllocateReadWriteTexture2D<Bgra32, Float4>(image.Width, image.Height);
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(image.Width, image.Height);
original.CopyFrom(ToPixels(image, false));
mirrored.CopyFrom(ToPixels(image, true));
var parameters = new WaveOpticsPipeline.Parameters(1f, new WaveOpticsPipeline.PsfParameters(
WaveOpticsQuality.Standard, 15, 550f, 8f, 4f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f));
var variants = new (string Name, Func<bool, (ReadWriteTexture2D<Bgra32, Float4> Source, WaveOpticsPipeline.Parameters Parameters)> Make)[]
{
("cached", _ => (original, parameters)),
("gain", flip => (original, parameters with { Gain = flip ? 1.5f : 1f })),
("source", flip => (flip ? mirrored : original, parameters)),
("defocus", flip => (original, parameters with { Psf = parameters.Psf with { Defocus = flip ? 0.1f : 0f } })),
("quality-high", flip => (original, parameters with { Psf = parameters.Psf with { Quality = flip ? WaveOpticsQuality.High : WaveOpticsQuality.Standard } })),
};
var renderedGain = float.NaN;
void Frame(ReadWriteTexture2D<Bgra32, Float4> source, in WaveOpticsPipeline.Parameters frameParameters)
{
var changed = pipeline.Simulate(source, image.Width, image.Height, 0, 0, image.Width, image.Height, in frameParameters);
if ((changed || renderedGain != frameParameters.Gain) && pipeline.TryGetVisibleBounds(image.Width, image.Height, in frameParameters, out var rect))
{
pipeline.RenderVisible(output, rect, in frameParameters);
renderedGain = frameParameters.Gain;
}
pipeline.WaitForCompletion();
}
var samples = new List<double>[variants.Length];
for (var index = 0; index < samples.Length; index++)
samples[index] = new List<double>(Rounds);
foreach (var (_, make) in variants)
{
var (warmupSource, warmupParameters) = make(true);
Frame(warmupSource, in warmupParameters);
}
var stopwatch = new Stopwatch();
var order = Enumerable.Range(0, variants.Length).ToArray();
var random = new Random(Seed);
for (var round = 0; round < Rounds; round++)
{
for (var index = order.Length - 1; index > 0; index--)
{
var swap = random.Next(index + 1);
(order[index], order[swap]) = (order[swap], order[index]);
}
foreach (var index in order)
{
var (settledSource, settledParameters) = variants[index].Make(false);
Frame(settledSource, in settledParameters);
var (measuredSource, measuredParameters) = variants[index].Make(true);
stopwatch.Restart();
Frame(measuredSource, in measuredParameters);
stopwatch.Stop();
samples[index].Add(stopwatch.Elapsed.TotalMilliseconds);
}
}
Console.WriteLine($"convolution recompute at {image.Width}x{image.Height} over {Rounds} interleaved rounds (ms)");
for (var index = 0; index < variants.Length; index++)
{
var sorted = samples[index].OrderBy(static value => value).ToArray();
var median = sorted[sorted.Length / 2];
Console.WriteLine($" {variants[index].Name,-12} min={sorted[0],7:F2} median={median,7:F2} max={sorted[^1],7:F2}");
}
return 0;
}
static Bgra32[] ToPixels(HarnessImage image, bool mirror)
{
var pixels = new Bgra32[image.Width * image.Height];
for (var y = 0; y < image.Height; y++)
{
for (var x = 0; x < image.Width; x++)
{
var offset = (y * image.Width + (mirror ? image.Width - 1 - x : x)) * HarnessImage.BytesPerPixel;
pixels[y * image.Width + x] = new Bgra32(image.Pixels[offset + 2], image.Pixels[offset + 1], image.Pixels[offset], image.Pixels[offset + 3]);
}
}
return pixels;
}
static int Compare(string beforeDirectory, string afterDirectory)
{
if (!Directory.Exists(beforeDirectory) || !Directory.Exists(afterDirectory))
throw new HarnessException("比べる出力先がありません。");
var failures = 0;
var names = Directory.EnumerateFiles(beforeDirectory, "*.png")
.Concat(Directory.EnumerateFiles(afterDirectory, "*.png"))
.Select(path => Path.GetFileName(path))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Order(StringComparer.OrdinalIgnoreCase)
.ToArray();
if (names.Length == 0)
throw new HarnessException("比べる PNG がありません。");
foreach (var name in names)
{
var before = Path.Combine(beforeDirectory, name);
var after = Path.Combine(afterDirectory, name);
if (!File.Exists(before) || !File.Exists(after))
{
Console.Error.WriteLine($"{name}: {(File.Exists(before) ? "後" : "前")}にありません。");
failures++;
continue;
}
var (beforeWidth, beforeHeight, beforePixels) = HarnessImage.LoadPremultiplied(before);
var (afterWidth, afterHeight, afterPixels) = HarnessImage.LoadPremultiplied(after);
if (beforeWidth != afterWidth || beforeHeight != afterHeight)
{
Console.Error.WriteLine($"{name}: 寸法が違います。前 {beforeWidth}x{beforeHeight}、後 {afterWidth}x{afterHeight}");
failures++;
continue;
}
var difference = ImageComparison.Of(beforePixels, afterPixels, beforeWidth, beforeHeight);
Console.WriteLine($"{name}: {difference}");
if (!difference.IsEmpty)
failures++;
}
return failures == 0 ? 0 : 1;
}
static void Benchmark(HarnessImage image)
{
const int Frames = 60;
using var renderer = new HarnessRenderer(image.Width, image.Height, image);
Console.WriteLine($"adapter: {renderer.Adapter} (driver {renderer.Driver})");
foreach (var (name, effect) in HarnessCases.Benchmarks())
{
Report(image, name, "still", renderer.Measure(effect, Frames, moving: false));
Report(image, name, "moving", renderer.Measure(effect, Frames, moving: true));
}
}
static void Report(HarnessImage image, string name, string motion, HarnessRenderer.Measurement measurement)
=> Console.WriteLine(
$"{image.Width}x{image.Height} {name,-15} {motion,-6} " +
$"gpu={(measurement.Gpu is { } gpu ? gpu.TotalMilliseconds.ToString("F3") : "n/a"),7} " +
$"cpu={measurement.Cpu.TotalMilliseconds,7:F3} " +
$"update={measurement.Update.TotalMilliseconds,6:F3} " +
$"alloc={measurement.Allocated,6} gen0={measurement.Gen0}");
static List<GoldenCase> Evaluate(HarnessRenderer renderer, Action<GoldenCase, string[], byte[][]>? report)
{
var cases = new List<GoldenCase>();
var names = new HashSet<string>(StringComparer.Ordinal);
foreach (var (name, effect, frames) in HarnessCases.All())
{
if (!names.Add(name))
throw new HarnessException($"ケース名が重複しています。{name}");
var rendered = renderer.Render(effect, frames);
var files = new string[frames.Count];
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
for (var index = 0; index < frames.Count; index++)
{
hash.AppendData(rendered[index]);
files[index] = frames.Count == 1 ? name + ".png" : $"{name}-f{frames[index]:D3}.png";
}
var golden = new GoldenCase(name, frames, Convert.ToHexString(hash.GetHashAndReset()));
cases.Add(golden);
report?.Invoke(golden, files, rendered);
}
return cases;
}
static int CountDuplicates(IReadOnlyList<GoldenCase> cases)
{
var duplicates = 0;
var seen = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var (name, _, hash) in cases)
{
if (seen.TryGetValue(hash, out var first))
{
Console.Error.WriteLine($"{name}: {first} と出力が一致します。設定がシェーダーへ届いていません。");
duplicates++;
}
else
{
seen.Add(hash, name);
}
}
return duplicates;
}
static int CountOpaque(byte[] pixels)
{
var count = 0;
for (var offset = HarnessImage.BytesPerPixel - 1; offset < pixels.Length; offset += HarnessImage.BytesPerPixel)
{
if (pixels[offset] != 0)
count++;
}
return count;
}
+51
ファイルの表示
@@ -0,0 +1,51 @@
namespace WaveOptics.Harness;
internal static class SyntheticImage
{
const int GridPitch = 32;
public static byte[] Create(int width, int height)
{
var pixels = new byte[width * height * HarnessImage.BytesPerPixel];
var plateLeft = width * 0.10f;
var plateRight = width * 0.56f;
var plateTop = height * 0.14f;
var plateBottom = height * 0.86f;
var discCenterX = width * 0.70f;
var discCenterY = height * 0.50f;
var discRadius = MathF.Min(width, height) * 0.28f;
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var positionX = x + 0.5f;
var positionY = y + 0.5f;
var plateInset = MathF.Min(MathF.Min(positionX - plateLeft, plateRight - positionX), MathF.Min(positionY - plateTop, plateBottom - positionY));
var plateCoverage = Math.Clamp(plateInset + 0.5f, 0f, 1f);
var distance = MathF.Sqrt((positionX - discCenterX) * (positionX - discCenterX) + (positionY - discCenterY) * (positionY - discCenterY));
var discCoverage = Math.Clamp(discRadius - distance + 0.5f, 0f, 1f);
if (plateCoverage == 0f && discCoverage == 0f)
continue;
var onGrid = x % GridPitch == 0 || y % GridPitch == 0;
var plateWeight = plateCoverage * (1f - discCoverage);
var shade = 1f - distance / discRadius * 0.5f;
var red = (onGrid ? 0.25f : 0.82f) * plateWeight + 0.90f * shade * discCoverage;
var green = (onGrid ? 0.30f : 0.86f) * plateWeight + 0.45f * shade * discCoverage;
var blue = (onGrid ? 0.40f : 0.90f) * plateWeight + 0.30f * shade * discCoverage;
var alpha = plateWeight + discCoverage;
var offset = (y * width + x) * HarnessImage.BytesPerPixel;
pixels[offset] = ToByte(blue);
pixels[offset + 1] = ToByte(green);
pixels[offset + 2] = ToByte(red);
pixels[offset + 3] = ToByte(alpha);
}
}
return pixels;
}
static byte ToByte(float premultiplied) => (byte)MathF.Round(Math.Clamp(premultiplied, 0f, 1f) * byte.MaxValue);
}
+62
ファイルの表示
@@ -0,0 +1,62 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<AssemblyName>WaveOptics.Harness</AssemblyName>
<RootNamespace>WaveOptics.Harness</RootNamespace>
<PlatformTarget>x64</PlatformTarget>
<TieredCompilation>false</TieredCompilation>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\WaveOptics\WaveOptics.csproj" SetConfiguration="Configuration=$(Configuration)" SetPlatform="Platform=x64">
<AdditionalProperties Condition="'$(BuildingSolutionFile)' != 'true'">SkipPluginDeploy=true</AdditionalProperties>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<AssemblyMetadata Include="HostDirectory" Value="$(YMM4DirPath)" />
<AssemblyMetadata Include="HarnessDirectory" Value="$(MSBuildProjectDirectory)" />
</ItemGroup>
<ItemGroup>
<Reference Include="SharpGen.Runtime">
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.Direct2D1">
<HintPath>$(YMM4DirPath)Vortice.Direct2D1.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.Direct3D11">
<HintPath>$(YMM4DirPath)Vortice.Direct3D11.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.DirectX">
<HintPath>$(YMM4DirPath)Vortice.DirectX.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.DXGI">
<HintPath>$(YMM4DirPath)Vortice.DXGI.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.Mathematics">
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="YukkuriMovieMaker.Controls">
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Controls.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="YukkuriMovieMaker.Plugin">
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Plugin.dll</HintPath>
<Private>false</Private>
</Reference>
</ItemGroup>
</Project>
+227
ファイルの表示
@@ -0,0 +1,227 @@
{
"adapter": "Intel(R) Iris(R) Xe Graphics",
"driver": "32.0.101.7085",
"input": "synthetic 640x480 89838D8976198E40",
"canvas": "1280x720",
"cases": [
{
"name": "default",
"frames": [
0
],
"hash": "9B93219016A028453BF7CCAB7FBC7E3658B363FC51850286BE23B7A388C368BF"
},
{
"name": "default-frames-0-8",
"frames": [
0,
1,
2,
3,
4,
5,
6,
7,
8
],
"hash": "A77359A34F3A6C78E616953C1D66DF1CD05595E662E3DE38E68EB2FC81D11AE4"
},
{
"name": "amount-0",
"frames": [
0
],
"hash": "0A700F76CEDDBAD7C4B6A2C19D46939C1A93940E86C6EFEF1E5A53DB48D2A020"
},
{
"name": "amount-50",
"frames": [
0
],
"hash": "E854AFBFE739475EE665D3D4C672BEF9A631A1479E094E339B87D18C38BA50B0"
},
{
"name": "gain-50",
"frames": [
0
],
"hash": "9032893550EE7D03B58762F9BD8BE6608929D45DA0BFD474E5AF410A1C4C3328"
},
{
"name": "gain-400",
"frames": [
0
],
"hash": "95886976629306C5E0A2BB93208B5E627E3C78A9CFCD6263202248E0E363A2A7"
},
{
"name": "gain-400-amount-50",
"frames": [
0
],
"hash": "C579D45C3F216492D6219DA8C5CDF1C9B2357B51AA1376C53A6CBE051C3F6F1A"
},
{
"name": "wavelength-380",
"frames": [
0
],
"hash": "A5B889290FAB95A7BB5B00922B36B504AFA660DDF0F7E3EF3F4829D4E4AA8C75"
},
{
"name": "wavelength-780",
"frames": [
0
],
"hash": "7F8CB99C84EEED6C7ADF4E138085B08A53C3454160EF08A135405F1018B4272D"
},
{
"name": "f-number-4",
"frames": [
0
],
"hash": "9526105CC4F77E47D4174A86A7FB6E50A270CDBDCB5C59C14615A2751AB10AD7"
},
{
"name": "f-number-64",
"frames": [
0
],
"hash": "28CD10EE5F789E7D99BBD48E2A2967636E33BF4A4A57253E8F62A0FCD4668733"
},
{
"name": "pixel-pitch-0.25",
"frames": [
0
],
"hash": "0A35D27FBC8670D8C1F9E75581CE5AA7FC23466D5E64141D5E78AFF3631CB0BF"
},
{
"name": "pixel-pitch-2",
"frames": [
0
],
"hash": "39B4E14378BAABB03A364D7824BC0C999E1C7D9FD292090A2A8995D6C0890D8E"
},
{
"name": "kernel-radius-1",
"frames": [
0
],
"hash": "7873F5E5B2AC64FC73E65746900E0C249E6335A533DFD17E0FE97A4EFE9C36A2"
},
{
"name": "kernel-radius-5",
"frames": [
0
],
"hash": "34B3BCEC95C18658E45A8832AEB2BE00F0716E2FD78CE45CBA36F644DA5945B9"
},
{
"name": "quality-draft",
"frames": [
0
],
"hash": "0E16A02AE2360DBAB4FD57C28A95E51C61C2C33B81D46076D6D6E4FF81636A22"
},
{
"name": "quality-high",
"frames": [
0
],
"hash": "B28685A19BA25205B8F2716831687D3D63958AE24C65311E39D5F585D1750D82"
},
{
"name": "aperture-polygon",
"frames": [
0
],
"hash": "876C1DD8767A405F4C24ED6EE289513CFE155FA811E6D6F15A8C0E8F21624948"
},
{
"name": "blade-count-3",
"frames": [
0
],
"hash": "3EC07AD240914F5CD7C0AAA8F0BEF5C76772922E932853B39AD38FC290C493E8"
},
{
"name": "blade-count-32",
"frames": [
0
],
"hash": "7D5D5A10503525D51000E4CE2BF538E88878E77893D885B9B195C7FFCBDBCB50"
},
{
"name": "blade-rotation-30",
"frames": [
0
],
"hash": "7DF481B8A4E5263100A7C30EF3070BC55D497A9F39CF09FEA1E56E4058D19658"
},
{
"name": "obstruction-50",
"frames": [
0
],
"hash": "D1F583FF2F287987F3D97D48B5C3D0B80A647EECCF0F08C15387C745AFA41069"
},
{
"name": "defocus-1",
"frames": [
0
],
"hash": "7B699943FCC55D026212D9D842F2BFE436F992AD1010B23B41A54A9C643120EC"
},
{
"name": "astigmatism-vertical-1",
"frames": [
0
],
"hash": "AB5FACB67EC980806B6FFEE0627161CBE3EEE0F288194C1819072F6C108E372B"
},
{
"name": "astigmatism-oblique-1",
"frames": [
0
],
"hash": "FE7398B928F43E7C3E9722D12F0B2550EA275DF9EB26E02E990DFCF21ECC98AE"
},
{
"name": "coma-horizontal-1",
"frames": [
0
],
"hash": "EB2235CF182171F8D07EE8651D111D8A7483DFFAF934F51CC855E2A595FCAB5D"
},
{
"name": "coma-vertical-1",
"frames": [
0
],
"hash": "AA3FFDF4A62272DC0BD0E7A0EF8A4E4ECE03B27C90C665F71A991C2B65F72CC6"
},
{
"name": "spherical-1",
"frames": [
0
],
"hash": "91CF9F66CC46831C357D898E0367814285FE4D62959AB717B54146F8E8CE0D6F"
},
{
"name": "defocus-animated-frames-0-8",
"frames": [
0,
1,
2,
3,
4,
5,
6,
7,
8
],
"hash": "B0D6919D7AD63BBFC378CD8578033D0F6322EF479EA564385A4E6F50C4905F14"
}
]
}
+157
ファイルの表示
@@ -0,0 +1,157 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{E48EC0C8-23EC-46AC-9EC1-E1457E919BB0}</ProjectGuid>
<RootNamespace>WaveOpticsShader</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v145</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v145</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v145</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v145</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<OutDir>$(MSBuildThisFileDirectory)..\Release\</OutDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
<FxCompile>
<ShaderModel>4.1</ShaderModel>
</FxCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
<FxCompile>
<ShaderModel>4.1</ShaderModel>
<CompileD2DCustomEffect>
</CompileD2DCustomEffect>
</FxCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
<FxCompile>
<ShaderModel>4.1</ShaderModel>
</FxCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
<FxCompile>
<ShaderModel>4.1</ShaderModel>
</FxCompile>
</ItemDefinitionGroup>
<ItemGroup>
<FxCompile Include="WaveOptics.hlsl">
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Pixel</ShaderType>
</FxCompile>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
+22
ファイルの表示
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="ソース ファイル">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="ヘッダー ファイル">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="リソース ファイル">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<FxCompile Include="WaveOptics.hlsl">
<Filter>ソース ファイル</Filter>
</FxCompile>
</ItemGroup>
</Project>
+28
ファイルの表示
@@ -0,0 +1,28 @@
Texture2D SourceTexture : register(t0);
SamplerState SourceSampler : register(s0);
Texture2D ConvolvedTexture : register(t1);
SamplerState ConvolvedSampler : register(s1);
cbuffer Constants : register(b0)
{
float amount : packoffset(c0.x);
float pad0 : packoffset(c0.y);
float pad1 : packoffset(c0.z);
float pad2 : packoffset(c0.w);
};
float4 main(
float4 position : SV_POSITION,
float4 scenePosition : SCENE_POSITION,
float4 uv0 : TEXCOORD0,
float4 uv1 : TEXCOORD1
) : SV_TARGET
{
float4 source = SourceTexture.SampleLevel(SourceSampler, uv0.xy, 0);
if (amount <= 0.0)
return source;
float4 convolved = ConvolvedTexture.SampleLevel(ConvolvedSampler, uv1.xy, 0);
convolved.rgb = min(convolved.rgb, convolved.a.xxx);
return lerp(source, convolved, amount);
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace WaveOptics.Tests;
internal readonly record struct Bgra(byte Blue, byte Green, byte Red, byte Alpha)
{
public static Bgra Transparent => default;
public static Bgra Opaque(byte blue, byte green, byte red) => new(blue, green, red, byte.MaxValue);
public Bgra Premultiplied() => new(Premultiply(Blue), Premultiply(Green), Premultiply(Red), Alpha);
byte Premultiply(byte value) => (byte)Math.Round(value * (double)Alpha / byte.MaxValue, MidpointRounding.AwayFromZero);
}
+28
ファイルの表示
@@ -0,0 +1,28 @@
using System.Drawing;
using System.Numerics;
using Vortice.Direct2D1;
using YukkuriMovieMaker.Player.Video;
namespace WaveOptics.Tests;
internal static class EffectDescriptions
{
public const int Fps = 30;
static readonly Size ScreenSize = new(1920, 1080);
public static EffectDescription At(int frame, int length)
{
var timeline = new TimelineSourceDescription(
ScreenSize,
new FrameTime(frame, Fps),
new FrameTime(length, Fps),
Fps,
TimelineSourceUsage.Playing,
Guid.Empty,
[]);
var item = new TimelineItemSourceDescription(timeline, frame, length, 0);
var draw = new DrawDescription(Vector3.Zero, Vector2.Zero, Vector2.One, Vector3.Zero, Matrix4x4.Identity, InterpolationMode.Linear, 1d, false, []);
return new EffectDescription(item, draw, 0, 1, 0, 1);
}
}
+41 -23
ファイルの表示
@@ -1,4 +1,3 @@
using System.Numerics;
using WaveOptics.Fourier;
namespace WaveOptics.Tests.Fourier;
@@ -8,50 +7,69 @@ public sealed class FastFourierTransformTests
[Fact]
public void ForwardOfImpulseIsConstant()
{
var values = new Complex[16];
values[0] = Complex.One;
var real = new double[16];
var imaginary = new double[16];
real[0] = 1;
FastFourierTransform.Forward(values);
FastFourierTransform.Forward(real, imaginary);
foreach (var value in values)
Assert.True(Complex.Abs(value - Complex.One) < 1e-12);
for (var index = 0; index < real.Length; index++)
{
Assert.True(Math.Abs(real[index] - 1) < 1e-12);
Assert.True(Math.Abs(imaginary[index]) < 1e-12);
}
}
[Fact]
public void OneDimensionalRoundTripRestoresInput()
{
var random = new Random(12345);
var values = Enumerable.Range(0, 256)
.Select(_ => new Complex(random.NextDouble() * 2 - 1, random.NextDouble() * 2 - 1))
.ToArray();
var expected = (Complex[])values.Clone();
var real = new double[256];
var imaginary = new double[256];
for (var index = 0; index < real.Length; index++)
{
real[index] = random.NextDouble() * 2 - 1;
imaginary[index] = random.NextDouble() * 2 - 1;
}
var expectedReal = (double[])real.Clone();
var expectedImaginary = (double[])imaginary.Clone();
FastFourierTransform.Forward(values);
FastFourierTransform.Inverse(values);
FastFourierTransform.Forward(real, imaginary);
FastFourierTransform.Inverse(real, imaginary);
AssertMaximumError(expected, values, 1e-11);
AssertMaximumError(expectedReal, expectedImaginary, real, imaginary, 1e-11);
}
[Fact]
public void TwoDimensionalRoundTripRestoresInput()
{
var random = new Random(67890);
var values = Enumerable.Range(0, 64 * 32)
.Select(_ => new Complex(random.NextDouble(), random.NextDouble()))
.ToArray();
var expected = (Complex[])values.Clone();
var length = 64 * 32;
var real = new double[length];
var imaginary = new double[length];
for (var index = 0; index < length; index++)
{
real[index] = random.NextDouble();
imaginary[index] = random.NextDouble();
}
var expectedReal = (double[])real.Clone();
var expectedImaginary = (double[])imaginary.Clone();
FastFourierTransform.Forward2D(values, 64, 32);
FastFourierTransform.Inverse2D(values, 64, 32);
FastFourierTransform.Forward2D(real, imaginary, 64, 32);
FastFourierTransform.Inverse2D(real, imaginary, 64, 32);
AssertMaximumError(expected, values, 1e-10);
AssertMaximumError(expectedReal, expectedImaginary, real, imaginary, 1e-10);
}
static void AssertMaximumError(Complex[] expected, Complex[] actual, double tolerance)
static void AssertMaximumError(double[] expectedReal, double[] expectedImaginary, double[] actualReal, double[] actualImaginary, double tolerance)
{
var maximum = 0d;
for (var index = 0; index < expected.Length; index++)
maximum = Math.Max(maximum, Complex.Abs(expected[index] - actual[index]));
for (var index = 0; index < expectedReal.Length; index++)
{
var realError = Math.Abs(expectedReal[index] - actualReal[index]);
var imaginaryError = Math.Abs(expectedImaginary[index] - actualImaginary[index]);
maximum = Math.Max(maximum, Math.Max(realError, imaginaryError));
}
Assert.True(maximum <= tolerance, $"{maximum:R}");
}
}
+22
ファイルの表示
@@ -81,6 +81,25 @@ public sealed class FraunhoferPsfGeneratorTests
Assert.True(obstructed[center, center] < unobstructed[center, center]);
}
[Fact]
public void AnApertureWithoutAnOpenSampleYieldsNoPsf()
{
var descriptor = CreateBlockedDescriptor();
var generated = generator.TryGenerate(descriptor, out var result);
Assert.False(generated);
Assert.Null(result);
}
[Fact]
public void GeneratingFromAnApertureWithoutAnOpenSampleStillThrows()
{
var descriptor = CreateBlockedDescriptor();
Assert.Throws<InvalidOperationException>(() => generator.Generate(descriptor));
}
static int FindFirstMinimum(PsfKernel kernel, int center)
{
for (var radius = 1; radius < center - 1; radius++)
@@ -94,6 +113,9 @@ public sealed class FraunhoferPsfGeneratorTests
throw new InvalidOperationException();
}
static PsfDescriptor CreateBlockedDescriptor()
=> new(128, 32, 31, 550, 8, 4, ApertureShape.RegularPolygon, 4, -357.5, 0.95, default);
static PsfDescriptor CreateDescriptor(
double wavelengthNanometers = 550,
double fNumber = 8,
+37
ファイルの表示
@@ -0,0 +1,37 @@
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace WaveOptics.Tests;
internal static class HostAssemblyResolver
{
const string MetadataKey = "HostDirectory";
const string AssemblyExtension = ".dll";
public static string Directory { get; } = ReadDirectory();
public static bool IsConfigured => Directory.Length != 0 && System.IO.Directory.Exists(Directory);
[ModuleInitializer]
internal static void Initialize()
{
if (!IsConfigured)
return;
AppDomain.CurrentDomain.AssemblyResolve += (_, arguments) =>
{
var name = new AssemblyName(arguments.Name).Name;
if (name is null)
return null;
var candidate = Path.Combine(Directory, name + AssemblyExtension);
return File.Exists(candidate) ? Assembly.LoadFrom(candidate) : null;
};
}
static string ReadDirectory() => typeof(HostAssemblyResolver).Assembly
.GetCustomAttributes<AssemblyMetadataAttribute>()
.FirstOrDefault(attribute => string.Equals(attribute.Key, MetadataKey, StringComparison.Ordinal))
?.Value ?? string.Empty;
}
+31
ファイルの表示
@@ -0,0 +1,31 @@
using System.Windows;
using Telemetry;
using WaveOptics.Effects;
namespace WaveOptics.Tests;
public sealed class HostIntegrationTests
{
[Fact]
public void OutsideAWpfApplicationNoTelemetryIsStartedOrSent()
{
Assert.Null(Application.Current);
WaveOpticsTelemetry.EnsureStartedOnce();
WaveOpticsTelemetry.Report(new InvalidOperationException());
Assert.Null(ProcessState.Read("DrainClaimed"));
Assert.Null(ProcessState.Read("SentCount"));
}
[Fact]
public void OutsideAWpfApplicationTheEffectCanStillBeCreated()
{
Assert.Null(Application.Current);
var effect = new WaveOpticsEffect();
Assert.Equal(Texts.WaveOptics, effect.Label);
Assert.Null(ProcessState.Read("DrainClaimed"));
}
}
+10
ファイルの表示
@@ -0,0 +1,10 @@
using System.IO.Packaging;
using System.Runtime.CompilerServices;
namespace WaveOptics.Tests;
internal static class PackUriScheme
{
[ModuleInitializer]
internal static void Register() => _ = PackUriHelper.UriSchemePack;
}
+95
ファイルの表示
@@ -0,0 +1,95 @@
using System.Numerics;
using System.Runtime.InteropServices;
using Vortice.Direct2D1;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
namespace WaveOptics.Tests;
internal sealed class Rendering
{
readonly byte[] pixels;
public int Left { get; }
public int Top { get; }
public int Width { get; }
public int Height { get; }
public int Right => Left + Width;
public int Bottom => Top + Height;
Rendering(int left, int top, int width, int height, byte[] pixels)
{
Left = left;
Top = top;
Width = width;
Height = height;
this.pixels = pixels;
}
public static Rendering Capture(IGraphicsDevicesAndContext devices, ID2D1Image image)
{
var context = devices.DeviceContext;
var bounds = context.GetImageLocalBounds(image);
var left = (int)Math.Floor(bounds.Left);
var top = (int)Math.Floor(bounds.Top);
var width = (int)Math.Ceiling(bounds.Right) - left;
var height = (int)Math.Ceiling(bounds.Bottom) - top;
var stride = width * SourceImage.BytesPerPixel;
var size = new SizeI(width, height);
using var target = context.CreateBitmap(size, nint.Zero, stride,
new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.Target));
using var readback = context.CreateBitmap(size, nint.Zero, stride,
new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.CpuRead | BitmapOptions.CannotDraw));
context.Target = target;
context.BeginDraw();
context.Clear(new Color4(0f, 0f, 0f, 0f));
context.DrawImage(image, new Vector2(-left, -top), null, InterpolationMode.NearestNeighbor, CompositeMode.SourceCopy);
context.EndDraw();
context.Target = null;
readback.CopyFromBitmap(target);
var pixels = new byte[stride * height];
var mapped = readback.Map(MapOptions.Read);
try
{
for (var y = 0; y < height; y++)
Marshal.Copy(mapped.Bits + y * (int)mapped.Pitch, pixels, y * stride, stride);
}
finally
{
readback.Unmap();
}
return new Rendering(left, top, width, height, pixels);
}
public Bgra this[int x, int y]
{
get
{
var offset = ((y - Top) * Width + (x - Left)) * SourceImage.BytesPerPixel;
return new Bgra(pixels[offset], pixels[offset + 1], pixels[offset + 2], pixels[offset + 3]);
}
}
public bool Contains(int x, int y) => x >= Left && y >= Top && x < Right && y < Bottom;
public bool SamePixelsAs(Rendering other)
=> Left == other.Left && Top == other.Top && Width == other.Width && Height == other.Height && pixels.AsSpan().SequenceEqual(other.pixels);
public IEnumerable<(int X, int Y)> Coordinates()
{
for (var y = Top; y < Bottom; y++)
{
for (var x = Left; x < Right; x++)
yield return (x, y);
}
}
}
+132
ファイルの表示
@@ -0,0 +1,132 @@
using WaveOptics.Optics;
namespace WaveOptics.Tests.Optics;
public sealed class SeparableKernelTests
{
[Fact]
public void FullRankReconstructionMatchesOriginal()
{
const int size = 15;
var random = new Random(2024);
var kernel = new double[size * size];
for (var index = 0; index < kernel.Length; index++)
kernel[index] = random.NextDouble();
var separable = SeparableKernel.Decompose(kernel, size, 0d, size);
var maximumError = ReconstructionError(separable, kernel);
Assert.Equal(size, separable.Rank);
Assert.True(maximumError < 1e-5, $"{maximumError:R}");
}
[Fact]
public void OuterProductKernelIsRankOne()
{
const int size = 11;
var vertical = new double[size];
var horizontal = new double[size];
for (var i = 0; i < size; i++)
{
vertical[i] = Math.Exp(-0.2 * (i - 5) * (i - 5));
horizontal[i] = Math.Exp(-0.35 * (i - 5) * (i - 5));
}
var kernel = new double[size * size];
for (var y = 0; y < size; y++)
{
for (var x = 0; x < size; x++)
kernel[y * size + x] = vertical[y] * horizontal[x];
}
var separable = SeparableKernel.Decompose(kernel, size, 1e-6, size);
var maximumError = ReconstructionError(separable, kernel);
Assert.Equal(1, separable.Rank);
Assert.True(maximumError < 1e-5, $"{maximumError:R}");
}
[Fact]
public void LowRankApproximationHonorsResidualBudget()
{
const int size = 21;
var center = size / 2;
var kernel = new double[size * size];
var sum = 0d;
for (var y = 0; y < size; y++)
{
for (var x = 0; x < size; x++)
{
var radiusSquared = (x - center) * (x - center) + (y - center) * (y - center);
var value = Math.Exp(-0.12 * radiusSquared);
kernel[y * size + x] = value;
sum += value;
}
}
for (var index = 0; index < kernel.Length; index++)
kernel[index] /= sum;
var separable = SeparableKernel.Decompose(kernel, size, 1e-4, size);
var energy = 0d;
var residual = 0d;
for (var y = 0; y < size; y++)
{
for (var x = 0; x < size; x++)
{
var original = kernel[y * size + x];
var approximation = Reconstruct(separable, x, y);
energy += original * original;
residual += (original - approximation) * (original - approximation);
}
}
Assert.True(separable.Rank < size);
Assert.True(residual <= 1e-4 * energy, $"{residual / energy:R}");
}
[Fact]
public void SumIsTheSumOfTheApproximation()
{
const int size = 21;
var center = size / 2;
var kernel = new double[size * size];
for (var y = 0; y < size; y++)
{
for (var x = 0; x < size; x++)
kernel[y * size + x] = Math.Exp(-0.3 * Math.Sqrt((x - center) * (x - center) + (y - center) * (y - center)));
}
var separable = SeparableKernel.Decompose(kernel, size, 1e-4, 2);
var sum = 0d;
for (var y = 0; y < size; y++)
{
for (var x = 0; x < size; x++)
sum += Reconstruct(separable, x, y);
}
Assert.Equal(sum, separable.Sum, 5);
}
static double Reconstruct(SeparableKernel separable, int x, int y)
{
var size = separable.Size;
var value = 0d;
for (var term = 0; term < separable.Rank; term++)
value += separable.Vertical[term * size + y] * separable.Horizontal[term * size + x];
return value;
}
static double ReconstructionError(SeparableKernel separable, double[] kernel)
{
var size = separable.Size;
var maximumError = 0d;
for (var y = 0; y < size; y++)
{
for (var x = 0; x < size; x++)
{
var error = Math.Abs(kernel[y * size + x] - Reconstruct(separable, x, y));
maximumError = Math.Max(maximumError, error);
}
}
return maximumError;
}
}
+59
ファイルの表示
@@ -0,0 +1,59 @@
using Vortice.DCommon;
using Vortice.Direct2D1;
using Vortice.DXGI;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
namespace WaveOptics.Tests;
internal sealed class SourceImage : IDisposable
{
public const float Dpi = 96f;
public const int BytesPerPixel = 4;
public static readonly PixelFormat PixelFormat = new(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
readonly Func<int, int, Bgra> pixelOf;
public int Width { get; }
public int Height { get; }
public ID2D1Bitmap1 Bitmap { get; }
public SourceImage(IGraphicsDevicesAndContext devices, int width, int height, Func<int, int, Bgra> pixelOf)
{
this.pixelOf = pixelOf;
Width = width;
Height = height;
var stride = width * BytesPerPixel;
var pixels = new byte[stride * height];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var (blue, green, red, alpha) = pixelOf(x, y).Premultiplied();
var offset = y * stride + x * BytesPerPixel;
pixels[offset] = blue;
pixels[offset + 1] = green;
pixels[offset + 2] = red;
pixels[offset + 3] = alpha;
}
}
Bitmap = devices.DeviceContext.CreateBitmap(
new SizeI(width, height), nint.Zero, stride,
new BitmapProperties1(PixelFormat, Dpi, Dpi, BitmapOptions.None));
Bitmap.CopyFromMemory(pixels, stride);
}
public static SourceImage Solid(IGraphicsDevicesAndContext devices, int width, int height, Bgra color)
=> new(devices, width, height, (_, _) => color);
public Bgra this[int x, int y] => pixelOf(x, y).Premultiplied();
public bool Contains(int x, int y) => x >= 0 && y >= 0 && x < Width && y < Height;
public void Dispose() => Bitmap.Dispose();
}
+68
ファイルの表示
@@ -0,0 +1,68 @@
using System.Collections;
using System.Globalization;
using System.Reflection;
using System.Resources;
using WaveOptics.Effects;
namespace WaveOptics.Tests;
public sealed class TextsTests
{
const string NeutralCulture = "ja-JP";
public static readonly TheoryData<string> Cultures = [NeutralCulture, "en-US", "zh-CN", "zh-TW", "ko-KR", "es-ES", "ar-SA", "id-ID"];
static readonly string[] Keys = typeof(Texts)
.GetProperties(BindingFlags.Public | BindingFlags.Static)
.Where(property => property.PropertyType == typeof(string) && property.Name != nameof(Texts.CurrentCulture))
.Select(property => property.Name)
.ToArray();
static ResourceSet ResourcesOf(string culture)
=> Texts.ResourceManager.GetResourceSet(culture == NeutralCulture ? CultureInfo.InvariantCulture : CultureInfo.GetCultureInfo(culture), true, false)!;
[Fact]
public void EveryLocalizedKeyHasAProperty()
{
var resources = Texts.ResourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, false)!;
var keys = resources.Cast<DictionaryEntry>().Select(entry => (string)entry.Key).Where(key => key != nameof(Texts.CurrentCulture));
Assert.Equal(keys.Order(), Keys.Order());
}
[Theory]
[MemberData(nameof(Cultures))]
public void EveryKeyIsTranslated(string culture)
{
var resources = ResourcesOf(culture);
Assert.All(Keys, key => Assert.False(string.IsNullOrWhiteSpace(resources.GetString(key)), key));
}
[Theory]
[MemberData(nameof(Cultures))]
public void EveryCultureCarriesItsOwnTranslations(string culture)
{
var cultureInfo = CultureInfo.GetCultureInfo(culture);
Assert.Equal(culture.ToLowerInvariant(), Texts.ResourceManager.GetString(nameof(Texts.CurrentCulture), cultureInfo));
}
[Fact]
public void JapaneseIsTheNeutralLanguage()
{
var neutral = Texts.ResourceManager.GetString(nameof(Texts.WaveOptics), CultureInfo.InvariantCulture);
Assert.Equal("波動光学", neutral);
Assert.Equal(neutral, Texts.ResourceManager.GetString(nameof(Texts.WaveOptics), CultureInfo.GetCultureInfo(NeutralCulture)));
}
[Theory]
[MemberData(nameof(Cultures))]
public void TheUpdateMessageEmbedsTheVersion(string culture)
{
var message = string.Format(CultureInfo.InvariantCulture, ResourcesOf(culture).GetString(nameof(Texts.UpdateAvailableMessage))!, "v1.2.3");
Assert.Contains("v1.2.3", message);
}
}
+57 -7
ファイルの表示
@@ -2,6 +2,7 @@
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
@@ -12,20 +13,69 @@
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="10.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.6.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="xunit.v3" Version="3.2.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.10.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="xunit.v3" Version="4.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WaveOptics.Abstractions\WaveOptics.Abstractions.csproj" />
<ProjectReference Include="..\Wave Optics\WaveOptics.csproj" AdditionalProperties="SkipPluginDeploy=true" />
<ProjectReference Include="..\WaveOptics\WaveOptics.csproj" SetConfiguration="Configuration=$(Configuration)">
<AdditionalProperties Condition="'$(BuildingSolutionFile)' != 'true'">SkipPluginDeploy=true</AdditionalProperties>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<AssemblyMetadata Include="HostDirectory" Value="$(YMM4DirPath)" />
</ItemGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json">
<HintPath>$(YMM4DirPath)Newtonsoft.Json.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="SharpGen.Runtime">
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="SharpGen.Runtime.COM">
<HintPath>$(YMM4DirPath)SharpGen.Runtime.COM.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.Direct2D1">
<HintPath>$(YMM4DirPath)Vortice.Direct2D1.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.Direct3D11">
<HintPath>$(YMM4DirPath)Vortice.Direct3D11.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.DirectX">
<HintPath>$(YMM4DirPath)Vortice.DirectX.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.DXGI">
<HintPath>$(YMM4DirPath)Vortice.DXGI.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.Mathematics">
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="YukkuriMovieMaker.Controls">
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Controls.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="YukkuriMovieMaker.Plugin">
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Plugin.dll</HintPath>
<Private>false</Private>
</Reference>
</ItemGroup>
<ItemGroup>
+215
ファイルの表示
@@ -0,0 +1,215 @@
using System.Numerics;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using Vortice.Mathematics;
using WaveOptics.Rendering;
using YukkuriMovieMaker.Commons;
namespace WaveOptics.Tests;
[Collection("Direct2D")]
public sealed class WaveOpticsCustomEffectTests
{
const int AmountIndex = 0;
const int Width = 40;
const int Height = 24;
static readonly Bgra Blue = Bgra.Opaque(255, 0, 0);
static readonly Bgra HalfConvolved = new(0, 0, 0, 128);
static Rendering Render(IGraphicsDevicesAndContext devices, ID2D1Image source, ID2D1Image convolved, float amount)
{
using var effect = new WaveOpticsCustomEffect(devices);
effect.SetInput(0, source, true);
effect.SetInput(1, convolved, true);
effect.Amount = amount;
using var output = effect.Output;
return Rendering.Capture(devices, output);
}
static AffineTransform2D Translate(IGraphicsDevicesAndContext devices, ID2D1Image image, float dx, float dy)
{
var transform = new AffineTransform2D(devices.DeviceContext)
{
InterPolationMode = AffineTransform2DInterpolationMode.NearestNeighbor,
BorderMode = BorderMode.Hard,
TransformMatrix = Matrix3x2.CreateTranslation(dx, dy),
};
transform.SetInput(0, image, true);
return transform;
}
static ID2D1Bitmap1 RawBitmap(IGraphicsDevicesAndContext devices, int width, int height, Bgra premultiplied)
{
var stride = width * SourceImage.BytesPerPixel;
var pixels = new byte[stride * height];
for (var offset = 0; offset < pixels.Length; offset += SourceImage.BytesPerPixel)
{
pixels[offset] = premultiplied.Blue;
pixels[offset + 1] = premultiplied.Green;
pixels[offset + 2] = premultiplied.Red;
pixels[offset + 3] = premultiplied.Alpha;
}
var bitmap = devices.DeviceContext.CreateBitmap(
new SizeI(width, height), nint.Zero, stride,
new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.None));
bitmap.CopyFromMemory(pixels, stride);
return bitmap;
}
static bool WithinRounding(Bgra expected, Bgra actual)
=> Math.Abs(expected.Blue - actual.Blue) <= 1 && Math.Abs(expected.Green - actual.Green) <= 1 && Math.Abs(expected.Red - actual.Red) <= 1 && Math.Abs(expected.Alpha - actual.Alpha) <= 1;
static Bgra Mix(Bgra convolved, Bgra source, float amount)
{
byte Channel(byte convolvedValue, byte sourceValue) => (byte)Math.Round(convolvedValue * amount + sourceValue * (1d - amount), MidpointRounding.AwayFromZero);
return new Bgra(Channel(convolved.Blue, source.Blue), Channel(convolved.Green, source.Green), Channel(convolved.Red, source.Red), Channel(convolved.Alpha, source.Alpha));
}
[Fact]
public void TheEffectIsEnabledOnceCreated()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var effect = new WaveOpticsCustomEffect(context);
Assert.True(effect.IsEnabled);
}
[Fact]
public void TheAmountStartsFromZero()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var effect = new WaveOpticsCustomEffect(context);
Assert.Equal(0f, effect.GetFloatValue(AmountIndex));
}
[Theory]
[InlineData(-0.5f, 0f)]
[InlineData(0f, 0f)]
[InlineData(0.4f, 0.4f)]
[InlineData(1f, 1f)]
[InlineData(1.5f, 1f)]
[InlineData(float.MaxValue, 1f)]
public void TheAmountIsClampedToTheUnitRange(float value, float expected)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var effect = new WaveOpticsCustomEffect(context);
effect.Amount = value;
Assert.Equal(expected, effect.GetFloatValue(AmountIndex));
}
[Fact]
public void TheOutputBoundsCoverTheSourceAndTheConvolution()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Blue);
using var convolved = SourceImage.Solid(context, 8, 8, HalfConvolved);
using var moved = Translate(context, convolved.Bitmap, 50f, -6f);
using var movedOutput = moved.Output;
using var effect = new WaveOpticsCustomEffect(context);
effect.SetInput(0, source.Bitmap, true);
effect.SetInput(1, movedOutput, true);
effect.Amount = 1f;
using var output = effect.Output;
var bounds = context.DeviceContext.GetImageLocalBounds(output);
Assert.Equal(0f, bounds.Left);
Assert.Equal(-6f, bounds.Top);
Assert.Equal(58f, bounds.Right);
Assert.Equal((float)Height, bounds.Bottom);
}
[Fact]
public void WithoutAmountTheOutputBoundsAreThoseOfTheSource()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Blue);
using var convolved = SourceImage.Solid(context, 8, 8, HalfConvolved);
using var moved = Translate(context, convolved.Bitmap, 50f, -6f);
using var movedOutput = moved.Output;
using var effect = new WaveOpticsCustomEffect(context);
effect.SetInput(0, source.Bitmap, true);
effect.SetInput(1, movedOutput, true);
effect.Amount = 1f;
using var output = effect.Output;
context.DeviceContext.GetImageLocalBounds(output);
effect.Amount = 0f;
var bounds = context.DeviceContext.GetImageLocalBounds(output);
Assert.Equal((0f, 0f, (float)Width, (float)Height), (bounds.Left, bounds.Top, bounds.Right, bounds.Bottom));
}
[Theory]
[InlineData(0f)]
[InlineData(-1f)]
public void WithoutAmountTheSourcePassesThroughUntouched(float amount)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Blue);
using var convolved = SourceImage.Solid(context, Width, Height, HalfConvolved);
var rendering = Render(context, source.Bitmap, convolved.Bitmap, amount);
Assert.All(rendering.Coordinates(), point => Assert.Equal(source[point.X, point.Y], rendering[point.X, point.Y]));
}
[Theory]
[InlineData(1f)]
[InlineData(0.5f)]
[InlineData(0.25f)]
public void TheSourceGivesWayToTheConvolutionByTheAmount(float amount)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Blue);
using var convolved = SourceImage.Solid(context, Width, Height, HalfConvolved);
var expected = Mix(HalfConvolved.Premultiplied(), Blue.Premultiplied(), amount);
var rendering = Render(context, source.Bitmap, convolved.Bitmap, amount);
Assert.All(rendering.Coordinates(), point => Assert.True(WithinRounding(expected, rendering[point.X, point.Y]), $"({point.X}, {point.Y}) {rendering[point.X, point.Y]}"));
}
[Fact]
public void AtTheFullAmountOnlyTheConvolutionIsDrawn()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Blue);
using var convolved = SourceImage.Solid(context, 8, 8, HalfConvolved);
using var moved = Translate(context, convolved.Bitmap, 50f, 4f);
using var movedOutput = moved.Output;
var expected = Mix(HalfConvolved.Premultiplied(), Bgra.Transparent, 1f);
var rendering = Render(context, source.Bitmap, movedOutput, 1f);
Assert.True(WithinRounding(expected, rendering[53, 7]), $"{rendering[53, 7]}");
Assert.Equal(Bgra.Transparent, rendering[10, 10]);
Assert.Equal(Bgra.Transparent, rendering[45, 10]);
}
[Fact]
public void AConvolvedColorAboveItsAlphaIsCappedAtTheAlpha()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Bgra.Transparent);
using var convolved = RawBitmap(context, Width, Height, new Bgra(200, 160, 120, 100));
var rendering = Render(context, source.Bitmap, convolved, 1f);
Assert.All(rendering.Coordinates(), point => Assert.True(WithinRounding(new Bgra(100, 100, 100, 100), rendering[point.X, point.Y]), $"({point.X}, {point.Y}) {rendering[point.X, point.Y]}"));
}
}
+435
ファイルの表示
@@ -0,0 +1,435 @@
using System.Globalization;
using System.Numerics;
using ComputeWeave;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using WaveOptics.Effects;
using WaveOptics.Rendering;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Json;
using YukkuriMovieMaker.Player.Video;
namespace WaveOptics.Tests;
[Collection("Direct2D")]
public sealed class WaveOpticsEffectProcessorTests
{
const int Size = 64;
const int Length = 30;
const int Start = 16;
const int End = 48;
static readonly Bgra Gray = Bgra.Opaque(192, 192, 192);
static Bgra CenteredSquare(int x, int y) => x is >= Start and < End && y is >= Start and < End ? Gray : Bgra.Transparent;
static void RequireInterop(IGraphicsDevicesAndContext devices)
{
using var scheduler = ComputeExternalQueueScheduler.Create();
using var provider = WaveOpticsInteropProvider.TryCreate(devices, scheduler, out var device);
if (provider is null || device is null)
Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable.");
}
static Animation Linear(double from, double to)
=> Json.LoadFromText<Animation>(string.Create(CultureInfo.InvariantCulture, $$"""{"AnimationType":"直線移動","Values":[{"Value":{{from}}},{"Value":{{to}}}]}"""))!;
static Rendering RenderFrame(IGraphicsDevicesAndContext devices, IVideoEffectProcessor processor, int frame)
{
processor.Update(EffectDescriptions.At(frame, Length));
return Rendering.Capture(devices, processor.Output);
}
static void AssertSameAsSource(Rendering rendering, SourceImage source)
{
Assert.Equal((0, 0, source.Width, source.Height), (rendering.Left, rendering.Top, rendering.Width, rendering.Height));
Assert.All(rendering.Coordinates(), point => Assert.Equal(source[point.X, point.Y], rendering[point.X, point.Y]));
}
static Bgra PixelAt(Rendering rendering, int x, int y) => rendering.Contains(x, y) ? rendering[x, y] : Bgra.Transparent;
static bool HasLightOutside(Rendering rendering, SourceImage source)
=> rendering.Coordinates().Any(point => (!source.Contains(point.X, point.Y) || source[point.X, point.Y].Alpha == 0) && rendering[point.X, point.Y].Alpha > 0);
static int DistanceFromSquare(int x, int y)
=> Math.Max(Math.Max(Math.Max(Start - x, x - (End - 1)), Math.Max(Start - y, y - (End - 1))), 0);
static bool WithinRounding(Bgra expected, Bgra actual)
=> Math.Abs(expected.Blue - actual.Blue) <= 1 && Math.Abs(expected.Green - actual.Green) <= 1 && Math.Abs(expected.Red - actual.Red) <= 1 && Math.Abs(expected.Alpha - actual.Alpha) <= 1;
[Fact]
public void TheProcessorHandsTheDrawDescriptionBackUnchanged()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, Size, Size, CenteredSquare);
using var processor = new WaveOpticsEffect().CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var description = EffectDescriptions.At(0, Length);
var draw = processor.Update(description);
Assert.Same(description.DrawDescription, draw);
}
[Fact]
public void TheBlurSpreadsOutToTheKernelRadius()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new WaveOpticsEffect { KernelRadius = 4 };
effect.FNumber.Values[0].Value = 32d;
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var rendering = RenderFrame(context, processor, 0);
Assert.Contains(rendering.Coordinates(), point => DistanceFromSquare(point.X, point.Y) == effect.KernelRadius && rendering[point.X, point.Y].Alpha > 0);
Assert.All(rendering.Coordinates(), point =>
{
var pixel = rendering[point.X, point.Y];
Assert.InRange(pixel.Blue, 0, pixel.Alpha);
Assert.InRange(pixel.Green, 0, pixel.Alpha);
Assert.InRange(pixel.Red, 0, pixel.Alpha);
if (DistanceFromSquare(point.X, point.Y) > effect.KernelRadius)
Assert.Equal(Bgra.Transparent, pixel);
});
}
[Fact]
public void TheBlurIsCenteredOnTheSource()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
using var processor = new WaveOpticsEffect().CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var rendering = RenderFrame(context, processor, 0);
Assert.True(HasLightOutside(rendering, source));
Assert.All(rendering.Coordinates(), point =>
{
var pixel = rendering[point.X, point.Y];
Assert.True(WithinRounding(pixel, PixelAt(rendering, Size - 1 - point.X, point.Y)), $"({point.X}, {point.Y}) {pixel}");
Assert.True(WithinRounding(pixel, PixelAt(rendering, point.X, Size - 1 - point.Y)), $"({point.X}, {point.Y}) {pixel}");
});
}
[Theory]
[InlineData(100, 50)]
[InlineData(-37, 21)]
public void TheBlurTravelsWithTheImage(int dx, int dy)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
using var moved = new AffineTransform2D(context.DeviceContext)
{
InterPolationMode = AffineTransform2DInterpolationMode.NearestNeighbor,
BorderMode = BorderMode.Hard,
TransformMatrix = Matrix3x2.CreateTranslation(dx, dy),
};
moved.SetInput(0, source.Bitmap, true);
using var movedOutput = moved.Output;
using var inPlaceProcessor = new WaveOpticsEffect().CreateVideoEffect(context);
inPlaceProcessor.SetInput(source.Bitmap);
var inPlace = RenderFrame(context, inPlaceProcessor, 0);
using var travelledProcessor = new WaveOpticsEffect().CreateVideoEffect(context);
travelledProcessor.SetInput(movedOutput);
var travelled = RenderFrame(context, travelledProcessor, 0);
Assert.Equal((inPlace.Left + dx, inPlace.Top + dy, inPlace.Width, inPlace.Height), (travelled.Left, travelled.Top, travelled.Width, travelled.Height));
Assert.All(inPlace.Coordinates(), point => Assert.True(inPlace[point.X, point.Y] == travelled[point.X + dx, point.Y + dy], $"({point.X}, {point.Y})"));
}
[Fact]
public void AZeroAmountPassesTheImageThrough()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new WaveOpticsEffect();
effect.Amount.Values[0].Value = 0d;
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var rendering = RenderFrame(context, processor, 0);
AssertSameAsSource(rendering, source);
}
[Fact]
public void AZeroAmountAfterABlurredFramePassesTheImageThrough()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = SourceImage.Solid(context, Size, Size, Gray);
var effect = new WaveOpticsEffect();
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var blurred = RenderFrame(context, processor, 0);
effect.Amount.Values[0].Value = 0d;
var passed = RenderFrame(context, processor, 0);
Assert.True(HasLightOutside(blurred, source));
AssertSameAsSource(passed, source);
}
[Theory]
[InlineData(WaveOpticsSettings.MaximumCanvasSize - WaveOpticsSettings.CanvasMargin * 2, true)]
[InlineData(WaveOpticsSettings.MaximumCanvasSize - WaveOpticsSettings.CanvasMargin * 2 + 1, false)]
public void OnlyAnImageThatLeavesRoomForTheMarginIsBlurred(int width, bool blurred)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
if (blurred)
RequireInterop(context);
using var source = SourceImage.Solid(context, width, 8, Gray);
using var processor = new WaveOpticsEffect().CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var rendering = RenderFrame(context, processor, 0);
if (blurred)
Assert.True(HasLightOutside(rendering, source));
else
AssertSameAsSource(rendering, source);
}
public static readonly TheoryData<string, Action<WaveOpticsEffect>> Animations = new()
{
{ nameof(WaveOpticsEffect.Amount), effect => effect.Amount.CopyFrom(Linear(20d, 100d)) },
{ nameof(WaveOpticsEffect.Gain), effect => effect.Gain.CopyFrom(Linear(50d, 150d)) },
{ nameof(WaveOpticsEffect.Defocus), effect => effect.Defocus.CopyFrom(Linear(0d, 2d)) },
};
[Theory]
[MemberData(nameof(Animations))]
public void ReturningToAFrameReproducesItExactly(string setting, Action<WaveOpticsEffect> animate)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new WaveOpticsEffect();
animate(effect);
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var first = RenderFrame(context, processor, 4);
var other = RenderFrame(context, processor, 24);
var again = RenderFrame(context, processor, 4);
Assert.False(first.SamePixelsAs(other), setting);
Assert.True(first.SamePixelsAs(again), setting);
}
[Fact]
public void ANewProcessorDrawsTheSameBlur()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new WaveOpticsEffect { ApertureShape = WaveOpticsApertureShape.RegularPolygon };
effect.Defocus.Values[0].Value = 0.5d;
using var firstProcessor = effect.CreateVideoEffect(context);
firstProcessor.SetInput(source.Bitmap);
var first = RenderFrame(context, firstProcessor, 0);
using var secondProcessor = effect.CreateVideoEffect(context);
secondProcessor.SetInput(source.Bitmap);
var second = RenderFrame(context, secondProcessor, 0);
Assert.True(first.SamePixelsAs(second));
}
[Fact]
public void AnimatedAmountIsReadAtEachFrame()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new WaveOpticsEffect();
effect.Amount.CopyFrom(Linear(0d, 100d));
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var start = RenderFrame(context, processor, 0);
var end = RenderFrame(context, processor, Length - 1);
AssertSameAsSource(start, source);
Assert.True(HasLightOutside(end, source));
}
[Theory]
[InlineData(15, 3)]
[InlineData(3, 15)]
public void AProcessorThatDrewAnotherRadiusDrawsLikeAFreshOne(int firstRadius, int secondRadius)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new WaveOpticsEffect { KernelRadius = firstRadius };
effect.FNumber.Values[0].Value = 32d;
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
RenderFrame(context, processor, 0);
effect.KernelRadius = secondRadius;
using var fresh = effect.CreateVideoEffect(context);
fresh.SetInput(source.Bitmap);
var expected = RenderFrame(context, fresh, 0);
var reused = RenderFrame(context, processor, 0);
Assert.True(reused.SamePixelsAs(expected));
}
public static readonly TheoryData<string, Action<WaveOpticsEffect>> LaterChanges = new()
{
{ nameof(WaveOpticsEffect.Amount), effect => effect.Amount.Values[0].Value = 50d },
{ nameof(WaveOpticsEffect.Gain), effect => effect.Gain.Values[0].Value = 50d },
{ nameof(WaveOpticsEffect.Wavelength), effect => effect.Wavelength.Values[0].Value = 700d },
{ nameof(WaveOpticsEffect.FNumber), effect => effect.FNumber.Values[0].Value = 16d },
{ nameof(WaveOpticsEffect.PixelPitch), effect => effect.PixelPitch.Values[0].Value = 2d },
{ nameof(WaveOpticsEffect.KernelRadius), effect => effect.KernelRadius = 2 },
{ nameof(WaveOpticsEffect.Quality), effect => effect.Quality = WaveOpticsQuality.Draft },
{ nameof(WaveOpticsEffect.ApertureShape), effect => effect.ApertureShape = WaveOpticsApertureShape.Circular },
{ nameof(WaveOpticsEffect.BladeCount), effect => effect.BladeCount = 3 },
{ nameof(WaveOpticsEffect.BladeRotation), effect => effect.BladeRotation.Values[0].Value = 30d },
{ nameof(WaveOpticsEffect.Obstruction), effect => effect.Obstruction.Values[0].Value = 50d },
{ nameof(WaveOpticsEffect.Defocus), effect => effect.Defocus.Values[0].Value = 1d },
{ nameof(WaveOpticsEffect.AstigmatismVertical), effect => effect.AstigmatismVertical.Values[0].Value = 1d },
{ nameof(WaveOpticsEffect.AstigmatismOblique), effect => effect.AstigmatismOblique.Values[0].Value = 1d },
{ nameof(WaveOpticsEffect.ComaHorizontal), effect => effect.ComaHorizontal.Values[0].Value = 1d },
{ nameof(WaveOpticsEffect.ComaVertical), effect => effect.ComaVertical.Values[0].Value = 1d },
{ nameof(WaveOpticsEffect.Spherical), effect => effect.Spherical.Values[0].Value = 1d },
};
[Theory]
[MemberData(nameof(LaterChanges))]
public void EverySettingChangedAfterTheFirstFrameReachesTheEffect(string setting, Action<WaveOpticsEffect> change)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new WaveOpticsEffect { ApertureShape = WaveOpticsApertureShape.RegularPolygon };
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var before = RenderFrame(context, processor, 0);
change(effect);
var after = RenderFrame(context, processor, 0);
Assert.False(before.SamePixelsAs(after), setting);
}
[Theory]
[InlineData(32, 128)]
[InlineData(128, 32)]
public void AResizedSourceKeepsBeingBlurred(int firstSize, int secondSize)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var first = SourceImage.Solid(context, firstSize, firstSize, Gray);
using var second = SourceImage.Solid(context, secondSize, secondSize, Gray);
using var processor = new WaveOpticsEffect().CreateVideoEffect(context);
processor.SetInput(first.Bitmap);
var before = RenderFrame(context, processor, 0);
processor.SetInput(second.Bitmap);
var after = RenderFrame(context, processor, 0);
Assert.True(HasLightOutside(before, first));
Assert.True(HasLightOutside(after, second));
Assert.Equal(secondSize > firstSize, after.Width > before.Width);
}
[Fact]
public void TheBlurAppearsOnceATransparentSourceTakesShape()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var empty = SourceImage.Solid(context, Size, Size, Bgra.Transparent);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
using var processor = new WaveOpticsEffect().CreateVideoEffect(context);
processor.SetInput(empty.Bitmap);
var before = RenderFrame(context, processor, 0);
processor.SetInput(source.Bitmap);
var after = RenderFrame(context, processor, 0);
AssertSameAsSource(before, empty);
Assert.True(HasLightOutside(after, source));
}
[Theory]
[InlineData(Size, Size, false)]
[InlineData(WaveOpticsSettings.MaximumCanvasSize - WaveOpticsSettings.CanvasMargin * 2 + 1, 8, true)]
public void TheBlurReturnsAfterAnImageThatPassedThrough(int width, int height, bool opaque)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
using var passing = SourceImage.Solid(context, width, height, opaque ? Gray : Bgra.Transparent);
using var processor = new WaveOpticsEffect().CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var before = RenderFrame(context, processor, 0);
processor.SetInput(passing.Bitmap);
var between = RenderFrame(context, processor, 0);
processor.SetInput(source.Bitmap);
var after = RenderFrame(context, processor, 0);
Assert.True(HasLightOutside(before, source));
AssertSameAsSource(between, passing);
Assert.True(after.SamePixelsAs(before));
}
[Fact]
public void AnApertureWithoutAnOpenSamplePassesTheImageThroughUntilItOpens()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new WaveOpticsEffect { Quality = WaveOpticsQuality.Draft, ApertureShape = WaveOpticsApertureShape.RegularPolygon, BladeCount = 4 };
effect.BladeRotation.Values[0].Value = -357.5d;
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var open = RenderFrame(context, processor, 0);
effect.Obstruction.Values[0].Value = 95d;
var blocked = RenderFrame(context, processor, 0);
effect.Obstruction.Values[0].Value = 0d;
var reopened = RenderFrame(context, processor, 0);
Assert.True(HasLightOutside(open, source));
AssertSameAsSource(blocked, source);
Assert.True(reopened.SamePixelsAs(open));
}
[Fact]
public void AFailureWhileUpdatingIsNotSwallowed()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var processor = new WaveOpticsEffect().CreateVideoEffect(context);
Assert.ThrowsAny<Exception>(() => processor.Update(null!));
}
}
+305
ファイルの表示
@@ -0,0 +1,305 @@
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using WaveOptics.Effects;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Controls;
using YukkuriMovieMaker.Exo;
using YukkuriMovieMaker.Json;
using YukkuriMovieMaker.Plugin.Effects;
using YukkuriMovieMaker.Project;
namespace WaveOptics.Tests;
public sealed class WaveOpticsEffectTests
{
static PropertyInfo Property(string name) => typeof(WaveOpticsEffect).GetProperty(name)!;
static T Attribute<T>(string property) where T : Attribute => Property(property).GetCustomAttribute<T>()!;
static Animation[] Animations(WaveOpticsEffect effect)
=> [effect.Amount, effect.Gain, effect.Wavelength, effect.FNumber, effect.PixelPitch, effect.BladeRotation, effect.Obstruction, effect.Defocus, effect.AstigmatismVertical, effect.AstigmatismOblique, effect.ComaHorizontal, effect.ComaVertical, effect.Spherical];
[Theory]
[InlineData(nameof(WaveOpticsEffect.Amount), 100d, 0d, 100d)]
[InlineData(nameof(WaveOpticsEffect.Gain), 100d, 0d, 400d)]
[InlineData(nameof(WaveOpticsEffect.Wavelength), 550d, 380d, 780d)]
[InlineData(nameof(WaveOpticsEffect.FNumber), 8d, 0.5d, 64d)]
[InlineData(nameof(WaveOpticsEffect.PixelPitch), 4d, 0.25d, 100d)]
[InlineData(nameof(WaveOpticsEffect.BladeRotation), 0d, -360d, 360d)]
[InlineData(nameof(WaveOpticsEffect.Obstruction), 0d, 0d, 95d)]
[InlineData(nameof(WaveOpticsEffect.Defocus), 0d, -10d, 10d)]
[InlineData(nameof(WaveOpticsEffect.AstigmatismVertical), 0d, -10d, 10d)]
[InlineData(nameof(WaveOpticsEffect.AstigmatismOblique), 0d, -10d, 10d)]
[InlineData(nameof(WaveOpticsEffect.ComaHorizontal), 0d, -10d, 10d)]
[InlineData(nameof(WaveOpticsEffect.ComaVertical), 0d, -10d, 10d)]
[InlineData(nameof(WaveOpticsEffect.Spherical), 0d, -10d, 10d)]
public void AnimatedParametersStartFromTheirDefaultsWithinTheirRange(string name, double defaultValue, double minimum, double maximum)
{
var effect = new WaveOpticsEffect();
var animation = (Animation)Property(name).GetValue(effect)!;
Assert.Equal(defaultValue, animation.DefaultValue);
Assert.Equal(minimum, animation.MinValue);
Assert.Equal(maximum, animation.MaxValue);
Assert.Equal(defaultValue, animation.GetValue(0, 1, EffectDescriptions.Fps));
}
[Fact]
public void KernelRadiusQualityApertureAndBladesStartFromTheirDefaults()
{
var effect = new WaveOpticsEffect();
Assert.Equal(15, effect.KernelRadius);
Assert.Equal(WaveOpticsQuality.Standard, effect.Quality);
Assert.Equal(WaveOpticsApertureShape.Circular, effect.ApertureShape);
Assert.Equal(6, effect.BladeCount);
}
[Theory]
[InlineData(int.MinValue, 1)]
[InlineData(0, 1)]
[InlineData(1, 1)]
[InlineData(7, 7)]
[InlineData(15, 15)]
[InlineData(16, 15)]
[InlineData(int.MaxValue, 15)]
public void KernelRadiusStaysBetweenOneAndFifteenPixels(int value, int expected)
{
var effect = new WaveOpticsEffect { KernelRadius = 8 };
effect.KernelRadius = value;
Assert.Equal(expected, effect.KernelRadius);
Assert.False(effect.HasErrors);
}
[Theory]
[InlineData(int.MinValue, 3)]
[InlineData(2, 3)]
[InlineData(3, 3)]
[InlineData(12, 12)]
[InlineData(32, 32)]
[InlineData(33, 32)]
[InlineData(int.MaxValue, 32)]
public void BladeCountStaysBetweenThreeAndThirtyTwo(int value, int expected)
{
var effect = new WaveOpticsEffect { BladeCount = 5 };
effect.BladeCount = value;
Assert.Equal(expected, effect.BladeCount);
Assert.False(effect.HasErrors);
}
[Fact]
public void ChangingTheSettingsThatDoNotAnimateNotifiesTheEditor()
{
var effect = new WaveOpticsEffect();
var changed = new List<string?>();
effect.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
effect.KernelRadius = 7;
effect.Quality = WaveOpticsQuality.High;
effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon;
effect.BladeCount = 9;
Assert.Equal([nameof(WaveOpticsEffect.KernelRadius), nameof(WaveOpticsEffect.Quality), nameof(WaveOpticsEffect.ApertureShape), nameof(WaveOpticsEffect.BladeCount)], changed);
}
[Fact]
public void AssigningAnUnchangedOrClampedValueDoesNotNotify()
{
var effect = new WaveOpticsEffect();
var changed = new List<string?>();
effect.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
effect.KernelRadius = 15;
effect.KernelRadius = 16;
effect.Quality = WaveOpticsQuality.Standard;
effect.ApertureShape = WaveOpticsApertureShape.Circular;
effect.BladeCount = 6;
Assert.Empty(changed);
}
[Fact]
public void TheLabelIsTheLocalizedEffectName()
{
var effect = new WaveOpticsEffect();
Assert.Equal(Texts.WaveOptics, effect.Label);
}
[Fact]
public void TheThirteenNumericParametersReceiveTheAnimationParameters()
{
var effect = new WaveOpticsEffect();
effect.SetAnimationParameters(120, EffectDescriptions.Fps);
Assert.All(Animations(effect), animation => Assert.Equal(120, animation.Length));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(int.MaxValue)]
public void NoExoFilterIsWrittenForAviUtl(int keyFrameIndex)
{
var effect = new WaveOpticsEffect();
var description = new ExoOutputDescription(new VideoInfo(), string.Empty, new AviUtlDirectories(string.Empty, string.Empty));
Assert.Empty(effect.CreateExoVideoFilters(keyFrameIndex, description));
}
[Fact]
public void TheEffectIsRegisteredForFilteringWithoutAviUtlSupport()
{
var attribute = typeof(WaveOpticsEffect).GetCustomAttribute<VideoEffectAttribute>()!;
Assert.Equal(nameof(Texts.WaveOptics), attribute.Name);
Assert.Equal([VideoEffectCategories.Filtering], attribute.Categories);
Assert.Equal([nameof(Texts.TagDiffraction), nameof(Texts.TagLens), nameof(Texts.TagPsf), nameof(Texts.TagOptics)], attribute.Keywords);
Assert.False(attribute.IsAviUtlSupported);
Assert.True(attribute.IsEffectItemSupported);
Assert.Equal(typeof(Texts), attribute.ResourceType);
Assert.Equal(Texts.WaveOptics, attribute.GetName());
}
[Theory]
[InlineData(nameof(WaveOpticsEffect.Amount), nameof(Texts.OutputGroup), nameof(Texts.Amount), nameof(Texts.AmountDescription), 0)]
[InlineData(nameof(WaveOpticsEffect.Gain), nameof(Texts.OutputGroup), nameof(Texts.Gain), nameof(Texts.GainDescription), 1)]
[InlineData(nameof(WaveOpticsEffect.Wavelength), nameof(Texts.OpticsGroup), nameof(Texts.Wavelength), nameof(Texts.WavelengthDescription), 10)]
[InlineData(nameof(WaveOpticsEffect.FNumber), nameof(Texts.OpticsGroup), nameof(Texts.FNumber), nameof(Texts.FNumberDescription), 11)]
[InlineData(nameof(WaveOpticsEffect.PixelPitch), nameof(Texts.OpticsGroup), nameof(Texts.PixelPitch), nameof(Texts.PixelPitchDescription), 12)]
[InlineData(nameof(WaveOpticsEffect.KernelRadius), nameof(Texts.OpticsGroup), nameof(Texts.KernelRadius), nameof(Texts.KernelRadiusDescription), 13)]
[InlineData(nameof(WaveOpticsEffect.Quality), nameof(Texts.OpticsGroup), nameof(Texts.Quality), nameof(Texts.QualityDescription), 14)]
[InlineData(nameof(WaveOpticsEffect.ApertureShape), nameof(Texts.ApertureGroup), nameof(Texts.ApertureShape), nameof(Texts.ApertureShapeDescription), 20)]
[InlineData(nameof(WaveOpticsEffect.BladeCount), nameof(Texts.ApertureGroup), nameof(Texts.BladeCount), nameof(Texts.BladeCountDescription), 21)]
[InlineData(nameof(WaveOpticsEffect.BladeRotation), nameof(Texts.ApertureGroup), nameof(Texts.BladeRotation), nameof(Texts.BladeRotationDescription), 22)]
[InlineData(nameof(WaveOpticsEffect.Obstruction), nameof(Texts.ApertureGroup), nameof(Texts.Obstruction), nameof(Texts.ObstructionDescription), 23)]
[InlineData(nameof(WaveOpticsEffect.Defocus), nameof(Texts.AberrationGroup), nameof(Texts.Defocus), nameof(Texts.DefocusDescription), 30)]
[InlineData(nameof(WaveOpticsEffect.AstigmatismVertical), nameof(Texts.AberrationGroup), nameof(Texts.AstigmatismVertical), nameof(Texts.AstigmatismVerticalDescription), 31)]
[InlineData(nameof(WaveOpticsEffect.AstigmatismOblique), nameof(Texts.AberrationGroup), nameof(Texts.AstigmatismOblique), nameof(Texts.AstigmatismObliqueDescription), 32)]
[InlineData(nameof(WaveOpticsEffect.ComaHorizontal), nameof(Texts.AberrationGroup), nameof(Texts.ComaHorizontal), nameof(Texts.ComaHorizontalDescription), 33)]
[InlineData(nameof(WaveOpticsEffect.ComaVertical), nameof(Texts.AberrationGroup), nameof(Texts.ComaVertical), nameof(Texts.ComaVerticalDescription), 34)]
[InlineData(nameof(WaveOpticsEffect.Spherical), nameof(Texts.AberrationGroup), nameof(Texts.Spherical), nameof(Texts.SphericalDescription), 35)]
public void EveryParameterIsDisplayedInItsGroupInOrder(string property, string group, string name, string description, int order)
{
var display = Attribute<DisplayAttribute>(property);
Assert.Equal(group, display.GroupName);
Assert.Equal(name, display.Name);
Assert.Equal(description, display.Description);
Assert.Equal(order, display.Order);
Assert.Equal(typeof(Texts), display.ResourceType);
}
[Theory]
[InlineData(nameof(WaveOpticsEffect.Amount), "F1", "%", 0d, 100d)]
[InlineData(nameof(WaveOpticsEffect.Gain), "F1", "%", 0d, 400d)]
[InlineData(nameof(WaveOpticsEffect.Wavelength), "F1", "nm", 380d, 780d)]
[InlineData(nameof(WaveOpticsEffect.FNumber), "F2", "", 0.5d, 32d)]
[InlineData(nameof(WaveOpticsEffect.PixelPitch), "F2", "μm", 0.5d, 20d)]
[InlineData(nameof(WaveOpticsEffect.BladeRotation), "F1", "°", -180d, 180d)]
[InlineData(nameof(WaveOpticsEffect.Obstruction), "F1", "%", 0d, 95d)]
[InlineData(nameof(WaveOpticsEffect.Defocus), "F3", "waves", -3d, 3d)]
[InlineData(nameof(WaveOpticsEffect.AstigmatismVertical), "F3", "waves", -3d, 3d)]
[InlineData(nameof(WaveOpticsEffect.AstigmatismOblique), "F3", "waves", -3d, 3d)]
[InlineData(nameof(WaveOpticsEffect.ComaHorizontal), "F3", "waves", -3d, 3d)]
[InlineData(nameof(WaveOpticsEffect.ComaVertical), "F3", "waves", -3d, 3d)]
[InlineData(nameof(WaveOpticsEffect.Spherical), "F3", "waves", -3d, 3d)]
public void AnimatedParametersAreEditedWithAnimationSliders(string property, string format, string unit, double minimum, double maximum)
{
var slider = Attribute<AnimationSliderAttribute>(property);
Assert.Equal(format, slider.StringFormat);
Assert.Equal(unit, slider.UnitText);
Assert.Equal(minimum, slider.DefaultMin);
Assert.Equal(maximum, slider.DefaultMax);
}
[Theory]
[InlineData(nameof(WaveOpticsEffect.KernelRadius), "px", 1d, 15d, 1, 15, 15)]
[InlineData(nameof(WaveOpticsEffect.BladeCount), "", 3d, 16d, 3, 32, 6)]
public void WholeNumberParametersAreEditedWithTextBoxSliders(string property, string unit, double sliderMinimum, double sliderMaximum, int minimum, int maximum, int defaultValue)
{
var slider = Attribute<TextBoxSliderAttribute>(property);
var range = Attribute<RangeAttribute>(property);
Assert.Equal("F0", slider.StringFormat);
Assert.Equal(unit, slider.UnitText);
Assert.Equal(sliderMinimum, slider.DefaultMin);
Assert.Equal(sliderMaximum, slider.DefaultMax);
Assert.Equal(minimum, range.Minimum);
Assert.Equal(maximum, range.Maximum);
Assert.Equal(defaultValue, Attribute<DefaultValueAttribute>(property).Value);
}
[Fact]
public void TheQualityAndTheApertureShapeAreChosenFromCombos()
{
Assert.NotNull(Attribute<EnumComboBoxAttribute>(nameof(WaveOpticsEffect.Quality)));
Assert.NotNull(Attribute<EnumComboBoxAttribute>(nameof(WaveOpticsEffect.ApertureShape)));
Assert.Equal([WaveOpticsQuality.Draft, WaveOpticsQuality.Standard, WaveOpticsQuality.High], Enum.GetValues<WaveOpticsQuality>());
Assert.Equal([WaveOpticsApertureShape.Circular, WaveOpticsApertureShape.RegularPolygon], Enum.GetValues<WaveOpticsApertureShape>());
}
[Theory]
[InlineData(typeof(WaveOpticsQuality), nameof(WaveOpticsQuality.Draft), nameof(Texts.QualityDraft))]
[InlineData(typeof(WaveOpticsQuality), nameof(WaveOpticsQuality.Standard), nameof(Texts.QualityStandard))]
[InlineData(typeof(WaveOpticsQuality), nameof(WaveOpticsQuality.High), nameof(Texts.QualityHigh))]
[InlineData(typeof(WaveOpticsApertureShape), nameof(WaveOpticsApertureShape.Circular), nameof(Texts.CircularAperture))]
[InlineData(typeof(WaveOpticsApertureShape), nameof(WaveOpticsApertureShape.RegularPolygon), nameof(Texts.RegularPolygonAperture))]
public void EveryChoiceIsDisplayedWithItsLocalizedName(Type type, string value, string name)
{
var display = type.GetField(value)!.GetCustomAttribute<DisplayAttribute>()!;
Assert.Equal(name, display.Name);
Assert.Equal(typeof(Texts), display.ResourceType);
}
[Fact]
public void EverySettingSurvivesAProjectRoundTrip()
{
var effect = new WaveOpticsEffect { KernelRadius = 7, Quality = WaveOpticsQuality.High, ApertureShape = WaveOpticsApertureShape.RegularPolygon, BladeCount = 9 };
var values = new[] { 55d, 150d, 620d, 5.6d, 2.5d, 30d, 40d, 1.5d, -0.5d, 0.25d, -1d, 0.75d, 2d };
foreach (var (animation, value) in Animations(effect).Zip(values))
animation.Values[0].Value = value;
var clone = Json.GetClone(effect)!;
Assert.NotSame(effect, clone);
Assert.Equal(7, clone.KernelRadius);
Assert.Equal(WaveOpticsQuality.High, clone.Quality);
Assert.Equal(WaveOpticsApertureShape.RegularPolygon, clone.ApertureShape);
Assert.Equal(9, clone.BladeCount);
Assert.Equal(values, Animations(clone).Select(animation => animation.GetValue(0, 1, EffectDescriptions.Fps)));
}
[Fact]
public void ProjectsSavedWithTheSettingNamesStillLoad()
{
const string saved = """{"KernelRadius":7,"Quality":"High","ApertureShape":"RegularPolygon","BladeCount":9,"Defocus":{"Values":[{"Value":1.5}]}}""";
var effect = Json.LoadFromText<WaveOpticsEffect>(saved)!;
Assert.Equal(7, effect.KernelRadius);
Assert.Equal(WaveOpticsQuality.High, effect.Quality);
Assert.Equal(WaveOpticsApertureShape.RegularPolygon, effect.ApertureShape);
Assert.Equal(9, effect.BladeCount);
Assert.Equal(1.5d, effect.Defocus.GetValue(0, 1, EffectDescriptions.Fps));
}
[Fact]
public void TheEffectKeepsTheTypeNameThatProjectsStore()
{
var type = typeof(WaveOpticsEffect);
Assert.Equal("WaveOptics.Effects.WaveOpticsEffect", type.FullName);
Assert.Equal("WaveOptics", type.Assembly.GetName().Name);
}
}
+168
ファイルの表示
@@ -0,0 +1,168 @@
using System.Numerics;
using ComputeWeave;
using Vortice.Direct2D1;
using WaveOptics.Effects;
using WaveOptics.Rendering;
using YukkuriMovieMaker.Commons;
namespace WaveOptics.Tests;
[Collection("Direct2D")]
public sealed class WaveOpticsInteropTests
{
static readonly Bgra Gray = Bgra.Opaque(192, 192, 192);
static WaveOpticsPipeline.Parameters Parameters()
=> new(1f, new WaveOpticsPipeline.PsfParameters(
WaveOpticsQuality.Standard, 15, 550f, 8f, 4f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f));
static Func<int, int, Bgra> CenteredSquare(int size, int square)
{
var start = (size - square) / 2;
return (x, y) => x >= start && x < start + square && y >= start && y < start + square ? Gray : Bgra.Transparent;
}
sealed class Interop : IDisposable
{
readonly ComputeExternalQueueScheduler scheduler;
readonly WaveOpticsInteropProvider provider;
readonly ComputeInteropDomain domain;
public WaveOpticsResourceSet Resources { get; }
public WaveOpticsPipeline Pipeline { get; }
Interop(ComputeExternalQueueScheduler scheduler, WaveOpticsInteropProvider provider, GraphicsDevice device)
{
this.scheduler = scheduler;
this.provider = provider;
domain = device.RegisterExternalDomain(provider);
Resources = WaveOpticsResourceSet.Create(device, domain);
Pipeline = WaveOpticsPipeline.TryCreate(device)!;
}
public static Interop Create(IGraphicsDevicesAndContext devices)
{
var scheduler = ComputeExternalQueueScheduler.Create();
var provider = WaveOpticsInteropProvider.TryCreate(devices, scheduler, out var device);
if (provider is null || device is null)
{
scheduler.Dispose();
Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable.");
}
return new Interop(scheduler, provider, device);
}
public void Draw(ID2D1Image image)
{
var context = provider.RenderContext;
using var borrow = Resources.BeginSourceExternalOperation();
var previousTarget = context.Target;
using var target = new ID2D1Bitmap1(borrow.DangerousGetView().AddRefBitmap());
context.Target = target;
context.BeginDraw();
context.Clear(null);
context.DrawImage(image, Vector2.Zero, null, InterpolationMode.NearestNeighbor, CompositeMode.SourceCopy);
context.EndDraw();
context.Target = previousTarget;
}
public Rendering CaptureOutput(IGraphicsDevicesAndContext devices, out int width, out int height)
{
using var lease = Resources.AcquireOutputExternalViewLease();
width = lease.Width;
height = lease.Height;
using var bitmap = new ID2D1Bitmap1(lease.DangerousGetView().AddRefBitmap());
return Rendering.Capture(devices, bitmap);
}
public void Dispose()
{
Pipeline.Dispose();
Resources.Dispose();
Resources.WaitForDisposal();
domain.Dispose();
domain.WaitForDisposal();
provider.Dispose();
scheduler.Dispose();
}
}
static int LitPixels(Rendering rendering, WaveOpticsPipeline.PixelRect visible)
{
var lit = 0;
for (var y = 0; y < visible.Height; y++)
{
for (var x = 0; x < visible.Width; x++)
{
var pixel = rendering[x, y];
Assert.InRange(pixel.Blue, 0, pixel.Alpha);
Assert.InRange(pixel.Green, 0, pixel.Alpha);
Assert.InRange(pixel.Red, 0, pixel.Alpha);
if (pixel.Alpha > 0)
lit++;
}
}
return lit;
}
[Fact]
public void TheBlurIsDrawnAfterTheOutputGrowsToFullHd()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var interop = Interop.Create(context);
using var source = new SourceImage(context, 96, 96, CenteredSquare(96, 32));
var parameters = Parameters();
Assert.True(interop.Resources.TryEnsureSource(96, 96, out _));
WaveOpticsPipeline.PixelRect RenderInto(Func<WaveOpticsPipeline.PixelRect, (int Width, int Height)> outputSize)
{
interop.Draw(source.Bitmap);
interop.Pipeline.Simulate(interop.Resources.GetSourceComputeBinding(), 96, 96, 0, 0, 96, 96, in parameters);
Assert.True(interop.Pipeline.TryGetVisibleBounds(96, 96, in parameters, out var visible));
var (width, height) = outputSize(visible);
Assert.True(interop.Resources.TryEnsureOutput(width, height, out _));
interop.Pipeline.RenderVisible(interop.Resources.GetOutputComputeBinding(), visible, in parameters);
return visible;
}
var first = RenderInto(visible => (visible.Width, visible.Height));
interop.CaptureOutput(context, out var firstWidth, out var firstHeight);
var second = RenderInto(_ => (1920, 1080));
var output = interop.CaptureOutput(context, out var secondWidth, out var secondHeight);
Assert.Equal((first.Width, first.Height), (firstWidth, firstHeight));
Assert.Equal((1920, 1080), (secondWidth, secondHeight));
Assert.True(LitPixels(output, second) > 0);
}
[Fact]
public void TheBlurIsDrawnAfterTheSourceIsReplacedByALargerOne()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var interop = Interop.Create(context);
var parameters = Parameters();
var previous = default(WaveOpticsPipeline.PixelRect);
foreach (var (size, square) in new[] { (96, 32), (128, 64) })
{
using var source = new SourceImage(context, size, size, CenteredSquare(size, square));
Assert.True(interop.Resources.TryEnsureSource(size, size, out var sourceChanged));
interop.Draw(source.Bitmap);
Assert.True(interop.Pipeline.Simulate(interop.Resources.GetSourceComputeBinding(), size, size, 0, 0, size, size, in parameters));
Assert.True(interop.Pipeline.TryGetVisibleBounds(size, size, in parameters, out var visible));
Assert.True(interop.Resources.TryEnsureOutput(visible.Width, visible.Height, out _));
interop.Pipeline.RenderVisible(interop.Resources.GetOutputComputeBinding(), visible, in parameters);
var output = interop.CaptureOutput(context, out var width, out var height);
Assert.True(sourceChanged);
Assert.True(visible.Width > previous.Width && visible.Height > previous.Height);
Assert.Equal((visible.Width, visible.Height), (width, height));
Assert.True(LitPixels(output, visible) > square * square);
previous = visible;
}
}
}
+486
ファイルの表示
@@ -0,0 +1,486 @@
using ComputeWeave;
using ComputeWeave.Interop;
using WaveOptics.Abstractions;
using WaveOptics.Effects;
using WaveOptics.Optics;
using WaveOptics.Rendering;
namespace WaveOptics.Tests;
[Collection("Direct3D12")]
public sealed class WaveOpticsPipelineTests
{
const int Opaque = unchecked((int)0xFFC0C0C0);
const int White = unchecked((int)0xFFFFFFFF);
static readonly bool Direct3D12IsAvailable = GraphicsDevice.EnumerateDevices().Any();
static WaveOpticsPipeline CreatePipeline()
{
if (!Direct3D12IsAvailable)
Assert.Skip("Direct3D 12 is unavailable.");
var pipeline = WaveOpticsPipeline.TryCreate();
Assert.NotNull(pipeline);
return pipeline;
}
static WaveOpticsPipeline.Parameters Parameters(
float gain = 1f,
WaveOpticsQuality quality = WaveOpticsQuality.Standard,
int kernelRadius = 15,
float fNumber = 8f,
float pixelPitch = 4f,
float obstruction = 0f,
float defocus = 0f,
float comaHorizontal = 0f)
=> new(gain, new WaveOpticsPipeline.PsfParameters(
quality, kernelRadius, 550f, fNumber, pixelPitch, WaveOpticsApertureShape.Circular, 6, 0f, obstruction,
defocus, 0f, 0f, comaHorizontal, 0f, 0f));
static int[] Square(int width, int height, int left, int top, int squareWidth, int squareHeight, int color = Opaque)
{
var pixels = new int[width * height];
for (var y = Math.Max(top, 0); y < Math.Min(top + squareHeight, height); y++)
{
for (var x = Math.Max(left, 0); x < Math.Min(left + squareWidth, width); x++)
pixels[y * width + x] = color;
}
return pixels;
}
static int Alpha(int pixel) => (pixel >> 24) & 255;
static int Channel(int pixel, int shift) => (pixel >> shift) & 255;
static (int Left, int Top, int Right, int Bottom) LitBounds(int[] pixels, int width)
{
var (left, top, right, bottom) = (int.MaxValue, int.MaxValue, int.MinValue, int.MinValue);
for (var index = 0; index < pixels.Length; index++)
{
if (pixels[index] == 0)
continue;
left = Math.Min(left, index % width);
top = Math.Min(top, index / width);
right = Math.Max(right, index % width + 1);
bottom = Math.Max(bottom, index / width + 1);
}
return (left, top, right, bottom);
}
static void Upload(ReadWriteTexture2D<Bgra32, Float4> texture, int[] pixels)
=> texture.CopyFrom(pixels.Select(pixel => new Bgra32 { PackedValue = unchecked((uint)pixel) }).ToArray());
static int[] Render(WaveOpticsPipeline pipeline, int[] source, int width, int height, WaveOpticsPipeline.Parameters parameters)
{
var destination = new int[source.Length];
pipeline.Process(source, destination, width, height, in parameters);
return destination;
}
static int[] RenderSplit(WaveOpticsPipeline pipeline, ReadWriteTexture2D<Bgra32, Float4> source, int width, int height, WaveOpticsPipeline.Parameters parameters)
{
var device = GraphicsDevice.GetDefault();
var pixels = new int[width * height];
pipeline.Simulate(source, width, height, 0, 0, width, height, in parameters);
if (!pipeline.TryGetVisibleBounds(width, height, in parameters, out var rect))
return pixels;
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
pipeline.RenderVisible(output, rect, in parameters);
var visible = new Bgra32[rect.Width * rect.Height];
output.CopyTo(visible);
for (var y = 0; y < rect.Height; y++)
{
for (var x = 0; x < rect.Width; x++)
pixels[(rect.Y + y) * width + rect.X + x] = unchecked((int)visible[y * rect.Width + x].PackedValue);
}
return pixels;
}
static PsfKernel Kernel(WaveOpticsPipeline.PsfParameters psf)
{
var gridSize = WaveOpticsSettings.GetPupilGridSize(psf.Quality);
var descriptor = new PsfDescriptor(
gridSize,
WaveOpticsSettings.GetPupilDiameterSamples(gridSize),
WaveOpticsSettings.GetKernelSize(psf.KernelRadius),
psf.Wavelength,
psf.FNumber,
psf.PixelPitch,
ApertureShape.Circular,
psf.BladeCount,
psf.BladeRotation,
psf.Obstruction,
new WavefrontAberration(defocusWaves: psf.Defocus, comaHorizontalWaves: psf.ComaHorizontal));
return new FraunhoferPsfGenerator().Generate(descriptor).Kernel;
}
static SeparableKernel Decompose(WaveOpticsPipeline.PsfParameters psf)
{
var kernel = Kernel(psf);
return SeparableKernel.Decompose(kernel.Values.Span, kernel.Size, WaveOpticsSettings.SeparableResidualRatio, WaveOpticsSettings.MaximumRank);
}
[Fact]
public void ATransparentSourceStaysTransparent()
{
using var pipeline = CreatePipeline();
var destination = Enumerable.Repeat(-1, 64 * 64).ToArray();
var parameters = Parameters();
pipeline.Process(new int[64 * 64], destination, 64, 64, in parameters);
Assert.All(destination, pixel => Assert.Equal(0, pixel));
}
[Fact]
public void AZeroGainLeavesNothing()
{
using var pipeline = CreatePipeline();
var destination = Enumerable.Repeat(-1, 96 * 96).ToArray();
var parameters = Parameters(gain: 0f);
pipeline.Process(Square(96, 96, 32, 32, 32, 32), destination, 96, 96, in parameters);
Assert.All(destination, pixel => Assert.Equal(0, pixel));
}
[Theory]
[InlineData(16, 16)]
[InlineData(0, 0)]
[InlineData(32, 32)]
[InlineData(3, 29)]
public void AnImpulseSpreadsIntoTheSeparableKernel(int impulseX, int impulseY)
{
using var pipeline = CreatePipeline();
var parameters = Parameters(kernelRadius: 6, pixelPitch: 1.5f, comaHorizontal: 0.4f);
var separable = Decompose(parameters.Psf);
var radius = separable.Size / 2;
var source = Square(33, 33, impulseX, impulseY, 1, 1, White);
var rendering = Render(pipeline, source, 33, 33, parameters);
for (var y = 0; y < 33; y++)
{
for (var x = 0; x < 33; x++)
{
var expected = 0f;
var row = impulseY - y + radius;
var column = impulseX - x + radius;
if (row >= 0 && row < separable.Size && column >= 0 && column < separable.Size)
{
for (var term = 0; term < separable.Rank; term++)
expected += separable.Horizontal[term * separable.Size + column] * separable.Vertical[term * separable.Size + row];
}
var value = (int)Math.Round(Math.Clamp(expected / separable.Sum, 0d, 1d) * 255d, MidpointRounding.ToEven);
Assert.InRange(Alpha(rendering[y * 33 + x]), value - 1, value + 1);
}
}
}
[Fact]
public void AnImpulseSpreadsIntoAComaticPsfItself()
{
const int Size = 47;
const int Center = Size / 2;
const float Gain = 4f;
using var pipeline = CreatePipeline();
var parameters = Parameters(gain: Gain, comaHorizontal: 3f);
var kernel = Kernel(parameters.Psf);
var radius = kernel.Size / 2;
var source = Square(Size, Size, Center, Center, 1, 1, White);
var rendering = Render(pipeline, source, Size, Size, parameters);
for (var y = 0; y < Size; y++)
{
for (var x = 0; x < Size; x++)
{
var column = Center - x + radius;
var row = Center - y + radius;
var expected = column >= 0 && column < kernel.Size && row >= 0 && row < kernel.Size ? kernel[column, row] : 0d;
var value = (int)Math.Round(Math.Clamp(expected * Gain, 0d, 1d) * 255d, MidpointRounding.ToEven);
Assert.InRange(Alpha(rendering[y * Size + x]), value - 1, value + 1);
}
}
}
[Fact]
public void TheBlurKeepsTheLightOfTheSource()
{
using var pipeline = CreatePipeline();
var source = Square(128, 128, 48, 48, 32, 32);
var rendering = Render(pipeline, source, 128, 128, Parameters(defocus: 1f));
var before = source.Sum(pixel => (long)Alpha(pixel));
var after = rendering.Sum(pixel => (long)Alpha(pixel));
Assert.InRange(after / (double)before, 0.99, 1.01);
}
[Fact]
public void AUniformAreaKeepsItsBrightness()
{
using var pipeline = CreatePipeline();
var source = Square(96, 96, 16, 16, 64, 64);
var rendering = Render(pipeline, source, 96, 96, Parameters(fNumber: 16f, pixelPitch: 10f, obstruction: 0.5f));
var center = rendering[48 * 96 + 48];
Assert.InRange(Alpha(center), 254, 255);
Assert.InRange(Channel(center, 16), 191, 193);
}
[Fact]
public void TheBlurReachesNoFurtherThanTheKernelRadius()
{
using var pipeline = CreatePipeline();
var source = Square(96, 96, 40, 40, 16, 16);
var bounds = LitBounds(Render(pipeline, source, 96, 96, Parameters(kernelRadius: 5, pixelPitch: 0.25f)), 96);
Assert.Equal((40 - 5, 40 - 5, 56 + 5, 56 + 5), bounds);
}
[Fact]
public void TheGainScalesTheBlurredImage()
{
using var pipeline = CreatePipeline();
var source = Square(96, 96, 32, 32, 32, 32);
var full = Render(pipeline, source, 96, 96, Parameters(defocus: 1f));
var half = Render(pipeline, source, 96, 96, Parameters(gain: 0.5f, defocus: 1f));
Assert.All(full.Zip(half), pair =>
{
foreach (var shift in new[] { 0, 8, 16, 24 })
Assert.InRange(Channel(pair.Second, shift), Channel(pair.First, shift) / 2 - 1, Channel(pair.First, shift) / 2 + 1);
});
}
[Fact]
public void TheSameSettingsAlwaysProduceTheSameImage()
{
using var pipeline = CreatePipeline();
var source = Square(128, 128, 48, 48, 32, 32);
var first = Render(pipeline, source, 128, 128, Parameters(defocus: 0.5f));
var second = Render(pipeline, source, 128, 128, Parameters(defocus: 0.5f));
Assert.Equal(first, second);
}
[Fact]
public void DifferentOpticsBlurDifferently()
{
using var pipeline = CreatePipeline();
var source = Square(128, 128, 48, 48, 32, 32);
var sharp = Render(pipeline, source, 128, 128, Parameters());
var defocused = Render(pipeline, source, 128, 128, Parameters(defocus: 1f));
Assert.NotEqual(sharp, defocused);
}
[Fact]
public void AWarmPipelineAllocatesNoManagedMemory()
{
using var pipeline = CreatePipeline();
var source = Square(64, 64, 24, 24, 16, 16);
var destination = new int[source.Length];
var parameters = Parameters();
for (var iteration = 0; iteration < 4; iteration++)
pipeline.Process(source, destination, 64, 64, in parameters);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var minimum = long.MaxValue;
for (var iteration = 0; iteration < 16; iteration++)
{
var before = GC.GetAllocatedBytesForCurrentThread();
pipeline.Process(source, destination, 64, 64, in parameters);
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
}
Assert.Equal(0, minimum);
}
[Fact]
public void SharedTexturesProduceTheSameImageAsPackedBuffers()
{
using var pipeline = CreatePipeline();
var source = Square(96, 96, 32, 32, 32, 32);
var parameters = Parameters(defocus: 0.7f);
var expected = Render(pipeline, source, 96, 96, parameters);
var device = GraphicsDevice.GetDefault();
using var sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 96, 96);
using var outputTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 96, 96);
Upload(sourceTexture, source);
pipeline.ProcessSharedAndWait(sourceTexture, outputTexture, 96, 96, in parameters);
var result = new Bgra32[source.Length];
outputTexture.CopyTo(result);
Assert.Equal(expected.Select(pixel => unchecked((uint)pixel)), result.Select(pixel => pixel.PackedValue));
}
[Fact]
public void RepeatedSharedTextureSubmissionsAllocateNoManagedMemory()
{
using var pipeline = CreatePipeline();
var device = GraphicsDevice.GetDefault();
using var source = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 64, 64);
using var destination = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 64, 64);
var parameters = Parameters();
for (var iteration = 0; iteration < 4; iteration++)
pipeline.Process(source, destination, 64, 64, in parameters);
pipeline.WaitForCompletion();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var minimum = long.MaxValue;
for (var iteration = 0; iteration < 16; iteration++)
{
var before = GC.GetAllocatedBytesForCurrentThread();
pipeline.Process(source, destination, 64, 64, in parameters);
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
}
pipeline.WaitForCompletion();
Assert.Equal(0, minimum);
}
[Theory]
[InlineData(15, 0f)]
[InlineData(5, 1f)]
[InlineData(1, 0f)]
public void TheVisibleBoundsHoldTheWholeBlurAndRenderTheSameImage(int kernelRadius, float defocus)
{
using var pipeline = CreatePipeline();
var source = Square(160, 144, 60, 52, 32, 24);
var parameters = Parameters(kernelRadius: kernelRadius, defocus: defocus);
var full = Render(pipeline, source, 160, 144, parameters);
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(160, 144);
Upload(sourceTexture, source);
var split = RenderSplit(pipeline, sourceTexture, 160, 144, parameters);
Assert.Equal(full, split);
}
[Fact]
public void TheVisibleBoundsHugTheSourceOnAFourPixelGrid()
{
using var pipeline = CreatePipeline();
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(160, 160);
Upload(sourceTexture, Square(160, 160, 62, 59, 30, 21));
var parameters = Parameters(kernelRadius: 9);
pipeline.Simulate(sourceTexture, 160, 160, 0, 0, 160, 160, in parameters);
Assert.True(pipeline.TryGetVisibleBounds(160, 160, in parameters, out var rect));
Assert.Equal((0, 0, 0, 0), (rect.X % 4, rect.Y % 4, rect.Width % 4, rect.Height % 4));
Assert.InRange(62 - 9 - rect.X, 0, 3);
Assert.InRange(59 - 9 - rect.Y, 0, 3);
Assert.InRange(rect.X + rect.Width - (62 + 30 + 9), 0, 3);
Assert.InRange(rect.Y + rect.Height - (59 + 21 + 9), 0, 3);
}
[Fact]
public void ASmallerKernelRadiusNarrowsTheVisibleBounds()
{
using var pipeline = CreatePipeline();
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(160, 160);
Upload(sourceTexture, Square(160, 160, 64, 64, 32, 32));
var wide = Parameters(kernelRadius: 15);
var narrow = Parameters(kernelRadius: 3);
pipeline.Simulate(sourceTexture, 160, 160, 0, 0, 160, 160, in wide);
Assert.True(pipeline.TryGetVisibleBounds(160, 160, in wide, out var wideRect));
Assert.True(pipeline.TryGetVisibleBounds(160, 160, in narrow, out var narrowRect));
Assert.True(narrowRect.X > wideRect.X && narrowRect.Y > wideRect.Y);
Assert.True(narrowRect.X + narrowRect.Width < wideRect.X + wideRect.Width && narrowRect.Y + narrowRect.Height < wideRect.Y + wideRect.Height);
}
[Fact]
public void NothingIsVisibleForATransparentSource()
{
using var pipeline = CreatePipeline();
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(128, 128);
Upload(sourceTexture, new int[128 * 128]);
var parameters = Parameters();
pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters);
Assert.False(pipeline.TryGetVisibleBounds(128, 128, in parameters, out _));
}
[Fact]
public void APipelineUsedAtAnotherSizeDrawsLikeAFreshOne()
{
using var pipeline = CreatePipeline();
using var fresh = CreatePipeline();
var parameters = Parameters(defocus: 0.5f);
Render(pipeline, Square(128, 64, 48, 16, 32, 32), 128, 64, parameters);
var source = Square(64, 64, 16, 16, 32, 32);
var reused = Render(pipeline, source, 64, 64, parameters);
var expected = Render(fresh, source, 64, 64, parameters);
Assert.Equal(expected, reused);
}
[Fact]
public void ARunOfTheWholePipelineIsNotMistakenForTheCachedConvolution()
{
using var pipeline = CreatePipeline();
using var fresh = CreatePipeline();
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(96, 96);
using var freshTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(96, 96);
var source = Square(96, 96, 32, 32, 32, 32);
Upload(sourceTexture, source);
Upload(freshTexture, source);
var parameters = Parameters(defocus: 1f);
pipeline.Simulate(sourceTexture, 96, 96, 0, 0, 96, 96, in parameters);
Render(pipeline, Square(96, 96, 8, 8, 16, 16), 96, 96, parameters);
var reused = RenderSplit(pipeline, sourceTexture, 96, 96, parameters);
var expected = RenderSplit(fresh, freshTexture, 96, 96, parameters);
Assert.Equal(expected, reused);
}
[Fact]
public void TheConvolutionIsRecomputedOnlyWhenTheSourceOrTheOpticsChange()
{
using var pipeline = CreatePipeline();
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(128, 128);
Upload(sourceTexture, Square(128, 128, 48, 48, 32, 32));
var parameters = Parameters();
Assert.True(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters));
Assert.False(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters));
var gainChanged = parameters with { Gain = 2f };
Assert.False(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in gainChanged));
var opticsChanged = parameters with { Psf = parameters.Psf with { Defocus = 0.5f } };
Assert.True(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in opticsChanged));
Upload(sourceTexture, Square(128, 128, 32, 32, 32, 32));
Assert.True(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in opticsChanged));
}
}
+98
ファイルの表示
@@ -0,0 +1,98 @@
using WaveOptics.Abstractions;
using WaveOptics.Effects;
using WaveOptics.Optics;
namespace WaveOptics.Tests;
public sealed class WaveOpticsSettingsTests
{
[Theory]
[InlineData(WaveOpticsQuality.Draft, 128)]
[InlineData(WaveOpticsQuality.Standard, 256)]
[InlineData(WaveOpticsQuality.High, 512)]
public void EveryQualityChoosesItsPupilGrid(WaveOpticsQuality quality, int gridSize)
=> Assert.Equal(gridSize, WaveOpticsSettings.GetPupilGridSize(quality));
[Theory]
[InlineData(128, 32)]
[InlineData(256, 64)]
[InlineData(512, 128)]
public void ThePupilSpansAQuarterOfTheGrid(int gridSize, int diameter)
=> Assert.Equal(diameter, WaveOpticsSettings.GetPupilDiameterSamples(gridSize));
[Theory]
[InlineData(1, 3)]
[InlineData(7, 15)]
[InlineData(15, 31)]
public void TheKernelSpansTheRadiusOnBothSidesOfTheCenter(int radius, int size)
=> Assert.Equal(size, WaveOpticsSettings.GetKernelSize(radius));
[Fact]
public void TheLargestKernelFitsInEveryWeightSlot()
=> Assert.Equal(WaveOpticsSettings.MaximumKernelSize, WaveOpticsSettings.GetKernelSize(WaveOpticsSettings.MaximumKernelRadius));
[Fact]
public void EveryTermAndAxisOwnsItsOwnWeightSlot()
{
var offsets = Enumerable.Range(0, WaveOpticsSettings.MaximumRank)
.SelectMany(term => new[] { WaveOpticsSettings.GetWeightOffset(term, 0), WaveOpticsSettings.GetWeightOffset(term, 1) })
.Order()
.ToArray();
Assert.Equal(WaveOpticsSettings.MaximumRank * 2, offsets.Distinct().Count());
Assert.Equal(0, offsets[0]);
Assert.All(offsets.Zip(offsets.Skip(1)), pair => Assert.Equal(WaveOpticsSettings.MaximumKernelSize, pair.Second - pair.First));
Assert.Equal(WaveOpticsSettings.WeightsLength, offsets[^1] + WaveOpticsSettings.MaximumKernelSize);
}
public static readonly TheoryData<string, WavefrontAberration> Aberrations = new()
{
{ "defocus", new WavefrontAberration(defocusWaves: 1) },
{ "astigmatism", new WavefrontAberration(astigmatismObliqueWaves: 1) },
{ "coma", new WavefrontAberration(comaHorizontalWaves: 3) },
{ "spherical", new WavefrontAberration(sphericalWaves: 1) },
{ "every term at the limit", new WavefrontAberration(defocusWaves: 10, astigmatismVerticalWaves: 10, astigmatismObliqueWaves: 10, comaHorizontalWaves: 10, comaVerticalWaves: 10, sphericalWaves: 10) },
};
[Theory]
[MemberData(nameof(Aberrations))]
public void TheRankLimitKeepsEveryAberrationWithinTheResidualBudget(string aberrationName, WavefrontAberration aberration)
{
var gridSize = WaveOpticsSettings.GetPupilGridSize(WaveOpticsQuality.Standard);
var descriptor = new PsfDescriptor(
gridSize,
WaveOpticsSettings.GetPupilDiameterSamples(gridSize),
WaveOpticsSettings.MaximumKernelSize,
550, 8, 4, ApertureShape.Circular, 6, 0, 0, aberration);
var kernel = new FraunhoferPsfGenerator().Generate(descriptor).Kernel;
var separable = SeparableKernel.Decompose(kernel.Values.Span, kernel.Size, WaveOpticsSettings.SeparableResidualRatio, WaveOpticsSettings.MaximumRank);
Assert.True(separable.ResidualEnergyRatio <= WaveOpticsSettings.SeparableResidualRatio, $"{aberrationName}: {separable.ResidualEnergyRatio}");
}
[Fact]
public void TheCanvasMarginHoldsTheWidestBlurOnAFourPixelGrid()
{
Assert.True(WaveOpticsSettings.CanvasMargin >= WaveOpticsSettings.MaximumKernelRadius);
Assert.Equal(0, WaveOpticsSettings.CanvasMargin % 4);
}
[Fact]
public void EveryScratchValueHasItsOwnSlot()
{
int[] slots =
[
WaveOpticsSettings.ScratchLitCount,
WaveOpticsSettings.ScratchBoundsMinX,
WaveOpticsSettings.ScratchBoundsMinY,
WaveOpticsSettings.ScratchBoundsMaxX,
WaveOpticsSettings.ScratchBoundsMaxY,
WaveOpticsSettings.ScratchHashSum,
WaveOpticsSettings.ScratchHashMix,
];
Assert.Equal(slots.Length, slots.Distinct().Count());
Assert.All(slots, slot => Assert.InRange(slot, 0, WaveOpticsSettings.ScratchLength - 1));
}
}
+26
ファイルの表示
@@ -0,0 +1,26 @@
{
"stryker-config": {
"project": "WaveOptics.csproj",
"test-runner": "mtp",
"coverage-analysis": "off",
"concurrency": 4,
"additional-timeout": 30000,
"mutate": [
"**/*.cs",
"!**/YMM4-GitHubUpdateNotifier/**",
"!**/YMM4-Telemetry/**",
"!**/WaveOpticsTelemetry.cs",
"!**/WaveOpticsUpdateNotifier.cs"
],
"reporters": [
"progress",
"cleartext",
"html"
],
"thresholds": {
"high": 80,
"low": 60,
"break": 60
}
}
}
+16 -1
ファイルの表示
@@ -3,10 +3,25 @@
<Platform Name="Any CPU" />
<Platform Name="x64" />
</Configurations>
<Project Path="Wave Optics/WaveOptics.csproj">
<Folder Name="/Solution Items/">
<File Path=".editorconfig" />
<File Path=".gitattributes" />
<File Path=".gitignore" />
<File Path=".gitmodules" />
<File Path="Directory.Build.props" />
<File Path="LICENSE.txt" />
<File Path="README.md" />
</Folder>
<Project Path="WaveOptics/WaveOptics.csproj">
<Platform Solution="*|x64" Project="x64" />
<BuildDependency Project="WaveOptics.Shader/WaveOptics.Shader.vcxproj" />
</Project>
<Project Path="WaveOptics.Abstractions/WaveOptics.Abstractions.csproj" />
<Project Path="WaveOptics.Tests/WaveOptics.Tests.csproj" />
<Project Path="WaveOptics.Harness/WaveOptics.Harness.csproj" />
<Project Path="WaveOptics.Shader/WaveOptics.Shader.vcxproj">
<BuildType Solution="*|*" Project="Release" />
<Platform Solution="*|*" Project="Win32" />
</Project>
<Project Path="YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator.csproj" />
</Solution>
ファイルの表示
差分なしでファイル名を変更。
+50
ファイルの表示
@@ -0,0 +1,50 @@
Key,Parameter,ja-jp,en-us,zh-cn,zh-tw,ko-kr,es-es,ar-sa,id-id
WaveOptics,,波動光学,Wave Optics,波动光学,波動光學,파동 광학,Óptica de ondas,البصريات الموجية,Optik Gelombang
OutputGroup,,出力,Output,输出,輸出,출력,Salida,الإخراج,Keluaran
OpticsGroup,,光学系,Optical System,光学系统,光學系統,광학 시스템,Sistema óptico,النظام البصري,Sistem Optik
ApertureGroup,,開口,Aperture,光圈,光圈,조리개,Apertura,الفتحة,Apertur
AberrationGroup,,波面収差,Wavefront Aberration,波前像差,波前像差,파면 수차,Aberración de frente de onda,انحراف جبهة الموجة,Aberasi Muka Gelombang
Amount,,適用量,Amount,适用量,適用量,적용량,Cantidad,الكمية,Jumlah
AmountDescription,,波動光学処理の適用量を調整します。0%では入力を変更しません。,Adjusts the amount of wave optics processing. The input is unchanged at 0%.,调整波动光学处理的适用量。0%时输入不变。,調整波動光學處理的適用量。0%時輸入不變。,파동 광학 처리의 적용량을 조정합니다. 0%에서는 입력이 변경되지 않습니다.,Ajusta la cantidad de procesamiento de óptica de ondas. La entrada no cambia al 0%.,يضبط مقدار معالجة البصريات الموجية. يبقى الإدخال دون تغيير عند 0%.,Menyesuaikan jumlah pemrosesan optik gelombang. Input tidak berubah pada 0%.
Gain,,利得,Gain,增益,增益,이득,Ganancia,الكسب,Penguatan
GainDescription,,エネルギー保存された畳み込み結果へ乗算する表示用利得です。,Sets the display gain applied after the energy preserving convolution.,设置能量守恒卷积后应用的显示增益。,設定能量守恆卷積後應用的顯示增益。,에너지 보존 컨볼루션 후 적용되는 표시 이득을 설정합니다.,Establece la ganancia de visualización aplicada tras la convolución de conservación de energía.,يضبط كسب العرض المطبق بعد الالتفاف الحافظ للطاقة.,Mengatur penguatan tampilan yang diterapkan setelah konvolusi pelestarian energi.
Wavelength,,波長,Wavelength,波长,波長,파장,Longitud de onda,الطول الموجي,Panjang Gelombang
WavelengthDescription,,単色光として計算する真空中の波長を指定します。,Sets the vacuum wavelength used for the monochromatic calculation.,设置单色光计算使用的真空波长。,設定單色光計算使用的真空波長。,단색광 계산에 사용되는 진공 파장을 설정합니다.,Establece la longitud de onda en el vacío utilizada para el cálculo monocromático.,يضبط الطول الموجي في الفراغ المستخدم للحساب أحادي اللون.,Mengatur panjang gelombang vakum yang digunakan untuk perhitungan monokromatik.
FNumber,,F値,F-number,F值,F值,F값,Número F,رقم F,Angka F
FNumberDescription,,開口径に対する焦点距離の比を指定します。,Sets the ratio of focal length to aperture diameter.,设置焦距与光圈直径的比值。,設定焦距與光圈直徑的比值。,초점 거리와 조리개 직경의 비율을 설정합니다.,Establece la relación entre la longitud focal y el diámetro de la apertura.,يضبط نسبة البعد البؤري إلى قطر الفتحة.,Mengatur rasio panjang fokus terhadap diameter apertur.
PixelPitch,,画素ピッチ,Pixel Pitch,像素间距,像素間距,픽셀 피치,Paso de píxel,خطوة البكسل,Jarak Piksel
PixelPitchDescription,,撮像面上の1画素の物理的な間隔を指定します。,Sets the physical spacing of one pixel on the image plane.,设置图像平面上一个像素的物理间距。,設定影像平面上一個像素的物理間距。,이미지 평면의 픽셀 하나의 물리적 간격을 설정합니다.,Establece el espaciado físico de un píxel en el plano de imagen.,يضبط التباعد المادي لبكسل واحد على مستوى الصورة.,Mengatur jarak fisik satu piksel pada bidang gambar.
KernelRadius,,カーネル半径,Kernel Radius,核半径,核半徑,커널 반지름,Radio de kernel,نصف قطر النواة,Radius Kernel
KernelRadiusDescription,,PSFを畳み込む画素半径を指定します。,Sets the pixel radius used to convolve the PSF.,设置用于卷积PSF的像素半径。,設定用於卷積PSF的像素半徑。,PSF를 컨볼루션하는 픽셀 반지름을 설정합니다.,Establece el radio de píxel utilizado para convolucionar la PSF.,يضبط نصف قطر البكسل المستخدم لالتفاف PSF.,Mengatur radius piksel yang digunakan untuk mengkonvolusikan PSF.
Quality,,品質,Quality,质量,品質,품질,Calidad,الجودة,Kualitas
QualityDescription,,瞳関数とPSFを計算するFFT格子の大きさを指定します。,Sets the FFT grid size used to calculate the pupil function and PSF.,设置用于计算瞳孔函数和PSF的FFT格点大小。,設定用於計算瞳孔函數和PSF的FFT格點大小。,동공 함수와 PSF를 계산하는 FFT 격자 크기를 설정합니다.,Establece el tamaño de la cuadrícula FFT utilizada para calcular la función pupilar y la PSF.,يضبط حجم شبكة FFT المستخدمة لحساب دالة الحدقة وPSF.,Mengatur ukuran kisi FFT yang digunakan untuk menghitung fungsi pupil dan PSF.
QualityDraft,,高速,Draft,草稿,草稿,초안,Borrador,مسودة,Draf
QualityStandard,,標準,Standard,标准,標準,표준,Estándar,قياسي,Standar
QualityHigh,,高精度,High,高精度,高精度,높음,Alto,مرتفع,Tinggi
ApertureShape,,開口形状,Aperture Shape,光圈形状,光圈形狀,조리개 형태,Forma de apertura,شكل الفتحة,Bentuk Apertur
ApertureShapeDescription,,瞳関数の外周形状を指定します。,Sets the outer shape of the pupil function.,设置瞳孔函数的外部形状。,設定瞳孔函數的外部形狀。,동공 함수의 외부 형태를 설정합니다.,Establece la forma exterior de la función pupilar.,يضبط الشكل الخارجي لدالة الحدقة.,Mengatur bentuk luar fungsi pupil.
CircularAperture,,円形,Circular,圆形,圓形,원형,Circular,دائري,Melingkar
RegularPolygonAperture,,正多角形,Regular Polygon,正多边形,正多邊形,정다각형,Polígono regular,مضلع منتظم,Poligon Beraturan
BladeCount,,羽根枚数,Blade Count,叶片数,葉片數,날개 수,Número de láminas,عدد الشفرات,Jumlah Bilah
BladeCountDescription,,正多角形開口の辺数を指定します。,Sets the number of sides in the regular polygon aperture.,设置正多边形光圈的边数。,設定正多邊形光圈的邊數。,정다각형 조리개의 변의 수를 설정합니다.,Establece el número de lados en la apertura de polígono regular.,يضبط عدد أضلاع فتحة المضلع المنتظم.,Mengatur jumlah sisi pada apertur poligon beraturan.
BladeRotation,,開口回転,Aperture Rotation,光圈旋转,光圈旋轉,조리개 회전,Rotación de apertura,دوران الفتحة,Rotasi Apertur
BladeRotationDescription,,正多角形開口の回転角を指定します。,Sets the rotation angle of the regular polygon aperture.,设置正多边形光圈的旋转角度。,設定正多邊形光圈的旋轉角度。,정다각형 조리개의 회전 각도를 설정합니다.,Establece el ángulo de rotación de la apertura de polígono regular.,يضبط زاوية دوران فتحة المضلع المنتظم.,Mengatur sudut rotasi apertur poligon beraturan.
Obstruction,,中央遮蔽,Central Obstruction,中央遮蔽,中央遮蔽,중앙 차폐,Obstrucción central,الحجب المركزي,Obstruksi Tengah
ObstructionDescription,,開口半径に対する中央遮蔽半径の割合を指定します。,Sets the central obstruction radius relative to the aperture radius.,设置中央遮蔽半径相对于光圈半径的比例。,設定中央遮蔽半徑相對於光圈半徑的比例。,조리개 반지름에 대한 중앙 차폐 반지름의 비율을 설정합니다.,Establece el radio de obstrucción central en relación al radio de apertura.,يضبط نصف قطر الحجب المركزي بالنسبة لنصف قطر الفتحة.,Mengatur radius obstruksi tengah relatif terhadap radius apertur.
Defocus,,デフォーカス,Defocus,离焦,離焦,디포커스,Desenfoque,إزالة التركيز,Defokus
DefocusDescription,,正規化Zernikeデフォーカス係数を波長単位で指定します。,Sets the normalized Zernike defocus coefficient in waves.,以波长为单位设置归一化Zernike离焦系数。,以波長為單位設定歸一化Zernike離焦係數。,파장 단위로 정규화된 Zernike 디포커스 계수를 설정합니다.,Establece el coeficiente de desenfoque de Zernike normalizado en ondas.,يضبط معامل إزالة التركيز لـZernike المعياري بالأمواج.,Mengatur koefisien defokus Zernike ternormalisasi dalam satuan gelombang.
AstigmatismVertical,,縦横非点収差,Vertical Astigmatism,垂直散光,垂直散光,수직 난시,Astigmatismo vertical,الاستجماتيزم الرأسي,Astigmatisme Vertikal
AstigmatismVerticalDescription,,0度方向の正規化Zernike非点収差係数を指定します。,Sets the normalized Zernike astigmatism coefficient at zero degrees.,设置0度方向的归一化Zernike散光系数。,設定0度方向的歸一化Zernike散光係數。,0도 방향의 정규화된 Zernike 난시 계수를 설정합니다.,Establece el coeficiente de astigmatismo de Zernike normalizado en cero grados.,يضبط معامل الاستجماتيزم لـZernike المعياري عند صفر درجة.,Mengatur koefisien astigmatisme Zernike ternormalisasi pada nol derajat.
AstigmatismOblique,,斜め非点収差,Oblique Astigmatism,斜向散光,斜向散光,사선 난시,Astigmatismo oblicuo,الاستجماتيزم المائل,Astigmatisme Miring
AstigmatismObliqueDescription,,45度方向の正規化Zernike非点収差係数を指定します。,Sets the normalized Zernike astigmatism coefficient at 45 degrees.,设置45度方向的归一化Zernike散光系数。,設定45度方向的歸一化Zernike散光係數。,45도 방향의 정규화된 Zernike 난시 계수를 설정합니다.,Establece el coeficiente de astigmatismo de Zernike normalizado en 45 grados.,يضبط معامل الاستجماتيزم لـZernike المعياري عند 45 درجة.,Mengatur koefisien astigmatisme Zernike ternormalisasi pada 45 derajat.
ComaHorizontal,,水平コマ収差,Horizontal Coma,水平彗差,水平彗差,수평 코마,Coma horizontal,الكوما الأفقية,Koma Horizontal
ComaHorizontalDescription,,水平方向の正規化Zernikeコマ収差係数を指定します。,Sets the normalized horizontal Zernike coma coefficient.,设置归一化水平Zernike彗差系数。,設定歸一化水平Zernike彗差係數。,정규화된 수평 Zernike 코마 계수를 설정합니다.,Establece el coeficiente de coma de Zernike horizontal normalizado.,يضبط معامل الكوما الأفقي لـZernike المعياري.,Mengatur koefisien koma Zernike horizontal ternormalisasi.
ComaVertical,,垂直コマ収差,Vertical Coma,垂直彗差,垂直彗差,수직 코마,Coma vertical,الكوما الرأسية,Koma Vertikal
ComaVerticalDescription,,垂直方向の正規化Zernikeコマ収差係数を指定します。,Sets the normalized vertical Zernike coma coefficient.,设置归一化垂直Zernike彗差系数。,設定歸一化垂直Zernike彗差係數。,정규화된 수직 Zernike 코마 계수를 설정합니다.,Establece el coeficiente de coma de Zernike vertical normalizado.,يضبط معامل الكوما الرأسي لـZernike المعياري.,Mengatur koefisien koma Zernike vertikal ternormalisasi.
Spherical,,球面収差,Spherical Aberration,球面像差,球面像差,구면 수차,Aberración esférica,الانحراف الكروي,Aberasi Sferis
SphericalDescription,,正規化Zernike球面収差係数を指定します。,Sets the normalized Zernike spherical aberration coefficient.,设置归一化Zernike球面像差系数。,設定歸一化Zernike球面像差係數。,정규화된 Zernike 구면 수차 계수를 설정합니다.,Establece el coeficiente de aberración esférica de Zernike normalizado.,يضبط معامل الانحراف الكروي لـZernike المعياري.,Mengatur koefisien aberasi sferis Zernike ternormalisasi.
TagDiffraction,,回折,diffraction,衍射,衍射,회절,difracción,الحيود,difraksi
TagLens,,レンズ,lens,镜头,鏡頭,렌즈,lente,العدسة,lensa
TagPsf,,点像分布関数,point spread function,点扩散函数,點擴散函數,점 확산 함수,función de dispersión puntual,دالة انتشار النقطة,fungsi penyebaran titik
TagOptics,,光学,optics,光学,光學,광학,óptica,البصريات,optik
UpdateAvailableMessage,,新しいバージョン {0} が公開されています。,A new version {0} is available.,新版本 {0} 已发布。,新版本 {0} 已發布。,새 버전 {0}이(가) 공개되었습니다.,La nueva versión {0} ya está disponible.,تم إصدار نسخة جديدة {0}.,Versi baru {0} telah dirilis.
1 Key Parameter ja-jp en-us zh-cn zh-tw ko-kr es-es ar-sa id-id
2 WaveOptics 波動光学 Wave Optics 波动光学 波動光學 파동 광학 Óptica de ondas البصريات الموجية Optik Gelombang
3 OutputGroup 出力 Output 输出 輸出 출력 Salida الإخراج Keluaran
4 OpticsGroup 光学系 Optical System 光学系统 光學系統 광학 시스템 Sistema óptico النظام البصري Sistem Optik
5 ApertureGroup 開口 Aperture 光圈 光圈 조리개 Apertura الفتحة Apertur
6 AberrationGroup 波面収差 Wavefront Aberration 波前像差 波前像差 파면 수차 Aberración de frente de onda انحراف جبهة الموجة Aberasi Muka Gelombang
7 Amount 適用量 Amount 适用量 適用量 적용량 Cantidad الكمية Jumlah
8 AmountDescription 波動光学処理の適用量を調整します。0%では入力を変更しません。 Adjusts the amount of wave optics processing. The input is unchanged at 0%. 调整波动光学处理的适用量。0%时输入不变。 調整波動光學處理的適用量。0%時輸入不變。 파동 광학 처리의 적용량을 조정합니다. 0%에서는 입력이 변경되지 않습니다. Ajusta la cantidad de procesamiento de óptica de ondas. La entrada no cambia al 0%. يضبط مقدار معالجة البصريات الموجية. يبقى الإدخال دون تغيير عند 0%. Menyesuaikan jumlah pemrosesan optik gelombang. Input tidak berubah pada 0%.
9 Gain 利得 Gain 增益 增益 이득 Ganancia الكسب Penguatan
10 GainDescription エネルギー保存された畳み込み結果へ乗算する表示用利得です。 Sets the display gain applied after the energy preserving convolution. 设置能量守恒卷积后应用的显示增益。 設定能量守恆卷積後應用的顯示增益。 에너지 보존 컨볼루션 후 적용되는 표시 이득을 설정합니다. Establece la ganancia de visualización aplicada tras la convolución de conservación de energía. يضبط كسب العرض المطبق بعد الالتفاف الحافظ للطاقة. Mengatur penguatan tampilan yang diterapkan setelah konvolusi pelestarian energi.
11 Wavelength 波長 Wavelength 波长 波長 파장 Longitud de onda الطول الموجي Panjang Gelombang
12 WavelengthDescription 単色光として計算する真空中の波長を指定します。 Sets the vacuum wavelength used for the monochromatic calculation. 设置单色光计算使用的真空波长。 設定單色光計算使用的真空波長。 단색광 계산에 사용되는 진공 파장을 설정합니다. Establece la longitud de onda en el vacío utilizada para el cálculo monocromático. يضبط الطول الموجي في الفراغ المستخدم للحساب أحادي اللون. Mengatur panjang gelombang vakum yang digunakan untuk perhitungan monokromatik.
13 FNumber F値 F-number F值 F值 F값 Número F رقم F Angka F
14 FNumberDescription 開口径に対する焦点距離の比を指定します。 Sets the ratio of focal length to aperture diameter. 设置焦距与光圈直径的比值。 設定焦距與光圈直徑的比值。 초점 거리와 조리개 직경의 비율을 설정합니다. Establece la relación entre la longitud focal y el diámetro de la apertura. يضبط نسبة البعد البؤري إلى قطر الفتحة. Mengatur rasio panjang fokus terhadap diameter apertur.
15 PixelPitch 画素ピッチ Pixel Pitch 像素间距 像素間距 픽셀 피치 Paso de píxel خطوة البكسل Jarak Piksel
16 PixelPitchDescription 撮像面上の1画素の物理的な間隔を指定します。 Sets the physical spacing of one pixel on the image plane. 设置图像平面上一个像素的物理间距。 設定影像平面上一個像素的物理間距。 이미지 평면의 픽셀 하나의 물리적 간격을 설정합니다. Establece el espaciado físico de un píxel en el plano de imagen. يضبط التباعد المادي لبكسل واحد على مستوى الصورة. Mengatur jarak fisik satu piksel pada bidang gambar.
17 KernelRadius カーネル半径 Kernel Radius 核半径 核半徑 커널 반지름 Radio de kernel نصف قطر النواة Radius Kernel
18 KernelRadiusDescription PSFを畳み込む画素半径を指定します。 Sets the pixel radius used to convolve the PSF. 设置用于卷积PSF的像素半径。 設定用於卷積PSF的像素半徑。 PSF를 컨볼루션하는 픽셀 반지름을 설정합니다. Establece el radio de píxel utilizado para convolucionar la PSF. يضبط نصف قطر البكسل المستخدم لالتفاف PSF. Mengatur radius piksel yang digunakan untuk mengkonvolusikan PSF.
19 Quality 品質 Quality 质量 品質 품질 Calidad الجودة Kualitas
20 QualityDescription 瞳関数とPSFを計算するFFT格子の大きさを指定します。 Sets the FFT grid size used to calculate the pupil function and PSF. 设置用于计算瞳孔函数和PSF的FFT格点大小。 設定用於計算瞳孔函數和PSF的FFT格點大小。 동공 함수와 PSF를 계산하는 FFT 격자 크기를 설정합니다. Establece el tamaño de la cuadrícula FFT utilizada para calcular la función pupilar y la PSF. يضبط حجم شبكة FFT المستخدمة لحساب دالة الحدقة وPSF. Mengatur ukuran kisi FFT yang digunakan untuk menghitung fungsi pupil dan PSF.
21 QualityDraft 高速 Draft 草稿 草稿 초안 Borrador مسودة Draf
22 QualityStandard 標準 Standard 标准 標準 표준 Estándar قياسي Standar
23 QualityHigh 高精度 High 高精度 高精度 높음 Alto مرتفع Tinggi
24 ApertureShape 開口形状 Aperture Shape 光圈形状 光圈形狀 조리개 형태 Forma de apertura شكل الفتحة Bentuk Apertur
25 ApertureShapeDescription 瞳関数の外周形状を指定します。 Sets the outer shape of the pupil function. 设置瞳孔函数的外部形状。 設定瞳孔函數的外部形狀。 동공 함수의 외부 형태를 설정합니다. Establece la forma exterior de la función pupilar. يضبط الشكل الخارجي لدالة الحدقة. Mengatur bentuk luar fungsi pupil.
26 CircularAperture 円形 Circular 圆形 圓形 원형 Circular دائري Melingkar
27 RegularPolygonAperture 正多角形 Regular Polygon 正多边形 正多邊形 정다각형 Polígono regular مضلع منتظم Poligon Beraturan
28 BladeCount 羽根枚数 Blade Count 叶片数 葉片數 날개 수 Número de láminas عدد الشفرات Jumlah Bilah
29 BladeCountDescription 正多角形開口の辺数を指定します。 Sets the number of sides in the regular polygon aperture. 设置正多边形光圈的边数。 設定正多邊形光圈的邊數。 정다각형 조리개의 변의 수를 설정합니다. Establece el número de lados en la apertura de polígono regular. يضبط عدد أضلاع فتحة المضلع المنتظم. Mengatur jumlah sisi pada apertur poligon beraturan.
30 BladeRotation 開口回転 Aperture Rotation 光圈旋转 光圈旋轉 조리개 회전 Rotación de apertura دوران الفتحة Rotasi Apertur
31 BladeRotationDescription 正多角形開口の回転角を指定します。 Sets the rotation angle of the regular polygon aperture. 设置正多边形光圈的旋转角度。 設定正多邊形光圈的旋轉角度。 정다각형 조리개의 회전 각도를 설정합니다. Establece el ángulo de rotación de la apertura de polígono regular. يضبط زاوية دوران فتحة المضلع المنتظم. Mengatur sudut rotasi apertur poligon beraturan.
32 Obstruction 中央遮蔽 Central Obstruction 中央遮蔽 中央遮蔽 중앙 차폐 Obstrucción central الحجب المركزي Obstruksi Tengah
33 ObstructionDescription 開口半径に対する中央遮蔽半径の割合を指定します。 Sets the central obstruction radius relative to the aperture radius. 设置中央遮蔽半径相对于光圈半径的比例。 設定中央遮蔽半徑相對於光圈半徑的比例。 조리개 반지름에 대한 중앙 차폐 반지름의 비율을 설정합니다. Establece el radio de obstrucción central en relación al radio de apertura. يضبط نصف قطر الحجب المركزي بالنسبة لنصف قطر الفتحة. Mengatur radius obstruksi tengah relatif terhadap radius apertur.
34 Defocus デフォーカス Defocus 离焦 離焦 디포커스 Desenfoque إزالة التركيز Defokus
35 DefocusDescription 正規化Zernikeデフォーカス係数を波長単位で指定します。 Sets the normalized Zernike defocus coefficient in waves. 以波长为单位设置归一化Zernike离焦系数。 以波長為單位設定歸一化Zernike離焦係數。 파장 단위로 정규화된 Zernike 디포커스 계수를 설정합니다. Establece el coeficiente de desenfoque de Zernike normalizado en ondas. يضبط معامل إزالة التركيز لـZernike المعياري بالأمواج. Mengatur koefisien defokus Zernike ternormalisasi dalam satuan gelombang.
36 AstigmatismVertical 縦横非点収差 Vertical Astigmatism 垂直散光 垂直散光 수직 난시 Astigmatismo vertical الاستجماتيزم الرأسي Astigmatisme Vertikal
37 AstigmatismVerticalDescription 0度方向の正規化Zernike非点収差係数を指定します。 Sets the normalized Zernike astigmatism coefficient at zero degrees. 设置0度方向的归一化Zernike散光系数。 設定0度方向的歸一化Zernike散光係數。 0도 방향의 정규화된 Zernike 난시 계수를 설정합니다. Establece el coeficiente de astigmatismo de Zernike normalizado en cero grados. يضبط معامل الاستجماتيزم لـZernike المعياري عند صفر درجة. Mengatur koefisien astigmatisme Zernike ternormalisasi pada nol derajat.
38 AstigmatismOblique 斜め非点収差 Oblique Astigmatism 斜向散光 斜向散光 사선 난시 Astigmatismo oblicuo الاستجماتيزم المائل Astigmatisme Miring
39 AstigmatismObliqueDescription 45度方向の正規化Zernike非点収差係数を指定します。 Sets the normalized Zernike astigmatism coefficient at 45 degrees. 设置45度方向的归一化Zernike散光系数。 設定45度方向的歸一化Zernike散光係數。 45도 방향의 정규화된 Zernike 난시 계수를 설정합니다. Establece el coeficiente de astigmatismo de Zernike normalizado en 45 grados. يضبط معامل الاستجماتيزم لـZernike المعياري عند 45 درجة. Mengatur koefisien astigmatisme Zernike ternormalisasi pada 45 derajat.
40 ComaHorizontal 水平コマ収差 Horizontal Coma 水平彗差 水平彗差 수평 코마 Coma horizontal الكوما الأفقية Koma Horizontal
41 ComaHorizontalDescription 水平方向の正規化Zernikeコマ収差係数を指定します。 Sets the normalized horizontal Zernike coma coefficient. 设置归一化水平Zernike彗差系数。 設定歸一化水平Zernike彗差係數。 정규화된 수평 Zernike 코마 계수를 설정합니다. Establece el coeficiente de coma de Zernike horizontal normalizado. يضبط معامل الكوما الأفقي لـZernike المعياري. Mengatur koefisien koma Zernike horizontal ternormalisasi.
42 ComaVertical 垂直コマ収差 Vertical Coma 垂直彗差 垂直彗差 수직 코마 Coma vertical الكوما الرأسية Koma Vertikal
43 ComaVerticalDescription 垂直方向の正規化Zernikeコマ収差係数を指定します。 Sets the normalized vertical Zernike coma coefficient. 设置归一化垂直Zernike彗差系数。 設定歸一化垂直Zernike彗差係數。 정규화된 수직 Zernike 코마 계수를 설정합니다. Establece el coeficiente de coma de Zernike vertical normalizado. يضبط معامل الكوما الرأسي لـZernike المعياري. Mengatur koefisien koma Zernike vertikal ternormalisasi.
44 Spherical 球面収差 Spherical Aberration 球面像差 球面像差 구면 수차 Aberración esférica الانحراف الكروي Aberasi Sferis
45 SphericalDescription 正規化Zernike球面収差係数を指定します。 Sets the normalized Zernike spherical aberration coefficient. 设置归一化Zernike球面像差系数。 設定歸一化Zernike球面像差係數。 정규화된 Zernike 구면 수차 계수를 설정합니다. Establece el coeficiente de aberración esférica de Zernike normalizado. يضبط معامل الانحراف الكروي لـZernike المعياري. Mengatur koefisien aberasi sferis Zernike ternormalisasi.
46 TagDiffraction 回折 diffraction 衍射 衍射 회절 difracción الحيود difraksi
47 TagLens レンズ lens 镜头 鏡頭 렌즈 lente العدسة lensa
48 TagPsf 点像分布関数 point spread function 点扩散函数 點擴散函數 점 확산 함수 función de dispersión puntual دالة انتشار النقطة fungsi penyebaran titik
49 TagOptics 光学 optics 光学 光學 광학 óptica البصريات optik
50 UpdateAvailableMessage 新しいバージョン {0} が公開されています。 A new version {0} is available. 新版本 {0} 已发布。 新版本 {0} 已發布。 새 버전 {0}이(가) 공개되었습니다. La nueva versión {0} ya está disponible. تم إصدار نسخة جديدة {0}. Versi baru {0} telah dirilis.
差分なしでファイル名を変更。
+117
ファイルの表示
@@ -0,0 +1,117 @@
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Controls;
using YukkuriMovieMaker.Exo;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Plugin.Effects;
namespace WaveOptics.Effects;
[VideoEffect(nameof(Texts.WaveOptics), [VideoEffectCategories.Filtering], [nameof(Texts.TagDiffraction), nameof(Texts.TagLens), nameof(Texts.TagPsf), nameof(Texts.TagOptics)], IsAviUtlSupported = false, ResourceType = typeof(Texts))]
public sealed class WaveOpticsEffect : VideoEffectBase
{
public override string Label => Texts.WaveOptics;
public WaveOpticsEffect()
{
WaveOpticsTelemetry.EnsureStartedOnce();
WaveOpticsUpdateNotifier.EnsureCheckedOnce();
}
[Display(GroupName = nameof(Texts.OutputGroup), Name = nameof(Texts.Amount), Description = nameof(Texts.AmountDescription), Order = 0, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "%", 0, 100)]
public Animation Amount { get; } = new(100, 0, 100);
[Display(GroupName = nameof(Texts.OutputGroup), Name = nameof(Texts.Gain), Description = nameof(Texts.GainDescription), Order = 1, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "%", 0, 400)]
public Animation Gain { get; } = new(100, 0, 400);
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.Wavelength), Description = nameof(Texts.WavelengthDescription), Order = 10, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "nm", 380, 780)]
public Animation Wavelength { get; } = new(550, 380, 780);
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.FNumber), Description = nameof(Texts.FNumberDescription), Order = 11, ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", 0.5, 32)]
public Animation FNumber { get; } = new(8, 0.5, 64);
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.PixelPitch), Description = nameof(Texts.PixelPitchDescription), Order = 12, ResourceType = typeof(Texts))]
[AnimationSlider("F2", "μm", 0.5, 20)]
public Animation PixelPitch { get; } = new(4, 0.25, 100);
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.KernelRadius), Description = nameof(Texts.KernelRadiusDescription), Order = 13, ResourceType = typeof(Texts))]
[TextBoxSlider("F0", "px", WaveOpticsSettings.MinimumKernelRadius, WaveOpticsSettings.MaximumKernelRadius)]
[Range(WaveOpticsSettings.MinimumKernelRadius, WaveOpticsSettings.MaximumKernelRadius)]
[DefaultValue(WaveOpticsSettings.MaximumKernelRadius)]
public int KernelRadius { get => _kernelRadius; set => Set(ref _kernelRadius, Math.Clamp(value, WaveOpticsSettings.MinimumKernelRadius, WaveOpticsSettings.MaximumKernelRadius)); }
private int _kernelRadius = WaveOpticsSettings.MaximumKernelRadius;
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.Quality), Description = nameof(Texts.QualityDescription), Order = 14, ResourceType = typeof(Texts))]
[EnumComboBox]
public WaveOpticsQuality Quality { get => _quality; set => Set(ref _quality, value); }
private WaveOpticsQuality _quality = WaveOpticsQuality.Standard;
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.ApertureShape), Description = nameof(Texts.ApertureShapeDescription), Order = 20, ResourceType = typeof(Texts))]
[EnumComboBox]
public WaveOpticsApertureShape ApertureShape { get => _apertureShape; set => Set(ref _apertureShape, value); }
private WaveOpticsApertureShape _apertureShape;
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.BladeCount), Description = nameof(Texts.BladeCountDescription), Order = 21, ResourceType = typeof(Texts))]
[TextBoxSlider("F0", "", 3, 16)]
[Range(3, 32)]
[DefaultValue(6)]
public int BladeCount { get => _bladeCount; set => Set(ref _bladeCount, Math.Clamp(value, 3, 32)); }
private int _bladeCount = 6;
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.BladeRotation), Description = nameof(Texts.BladeRotationDescription), Order = 22, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "°", -180, 180)]
public Animation BladeRotation { get; } = new(0, -360, 360);
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.Obstruction), Description = nameof(Texts.ObstructionDescription), Order = 23, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "%", 0, 95)]
public Animation Obstruction { get; } = new(0, 0, 95);
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.Defocus), Description = nameof(Texts.DefocusDescription), Order = 30, ResourceType = typeof(Texts))]
[AnimationSlider("F3", "waves", -3, 3)]
public Animation Defocus { get; } = new(0, -10, 10);
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.AstigmatismVertical), Description = nameof(Texts.AstigmatismVerticalDescription), Order = 31, ResourceType = typeof(Texts))]
[AnimationSlider("F3", "waves", -3, 3)]
public Animation AstigmatismVertical { get; } = new(0, -10, 10);
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.AstigmatismOblique), Description = nameof(Texts.AstigmatismObliqueDescription), Order = 32, ResourceType = typeof(Texts))]
[AnimationSlider("F3", "waves", -3, 3)]
public Animation AstigmatismOblique { get; } = new(0, -10, 10);
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.ComaHorizontal), Description = nameof(Texts.ComaHorizontalDescription), Order = 33, ResourceType = typeof(Texts))]
[AnimationSlider("F3", "waves", -3, 3)]
public Animation ComaHorizontal { get; } = new(0, -10, 10);
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.ComaVertical), Description = nameof(Texts.ComaVerticalDescription), Order = 34, ResourceType = typeof(Texts))]
[AnimationSlider("F3", "waves", -3, 3)]
public Animation ComaVertical { get; } = new(0, -10, 10);
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.Spherical), Description = nameof(Texts.SphericalDescription), Order = 35, ResourceType = typeof(Texts))]
[AnimationSlider("F3", "waves", -3, 3)]
public Animation Spherical { get; } = new(0, -10, 10);
private IAnimatable[]? _animatables;
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices)
{
try
{
return new WaveOpticsEffectProcessor(devices, this);
}
catch (Exception exception)
{
WaveOpticsTelemetry.Report(exception);
throw;
}
}
protected override IEnumerable<IAnimatable> GetAnimatables()
=> _animatables ??= [Amount, Gain, Wavelength, FNumber, PixelPitch, BladeRotation, Obstruction, Defocus, AstigmatismVertical, AstigmatismOblique, ComaHorizontal, ComaVertical, Spherical];
}
+403
ファイルの表示
@@ -0,0 +1,403 @@
using System.ComponentModel;
using System.Numerics;
using ComputeWeave;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using WaveOptics.Rendering;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Player.Video.Effects;
namespace WaveOptics.Effects;
internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
{
private readonly IGraphicsDevicesAndContext _devices;
private readonly WaveOpticsEffect _item;
private ComputeExternalQueueScheduler? _scheduler;
private WaveOpticsInteropProvider? _interopProvider;
private ComputeInteropDomain? _interopDomain;
private WaveOpticsResourceSet? _resourceSet;
private ExternalTextureLease<ExternalDirect3D11TextureView>? _outputLease;
private WaveOpticsPipeline? _pipeline;
private WaveOpticsCustomEffect? _effect;
private Crop? _outputCrop;
private ID2D1Image? _outputCropOutput;
private AffineTransform2D? _outputTransform;
private ID2D1Image? _outputTransformOutput;
private bool _isFirst = true;
private bool _hasOutput;
private bool _hasOutputOffset;
private bool _hasCropRect;
private bool _hasRenderState;
private Vector2 _outputOffset;
private Vector4 _cropRect;
private float _amount;
private RenderState _renderState;
public WaveOpticsEffectProcessor(IGraphicsDevicesAndContext devices, WaveOpticsEffect item)
: base(devices)
{
_devices = devices;
_item = item;
}
public override DrawDescription Update(EffectDescription effectDescription)
{
try
{
return UpdateCore(effectDescription);
}
catch (Exception exception)
{
WaveOpticsTelemetry.Report(exception);
throw;
}
}
private DrawDescription UpdateCore(EffectDescription effectDescription)
{
if (IsPassThroughEffect || _effect is null || _outputCrop is null || _outputTransform is null || _outputTransformOutput is null || _resourceSet is null || _interopProvider is null || _pipeline is null || input is null)
return effectDescription.DrawDescription;
var frame = effectDescription.ItemPosition.Frame;
var length = effectDescription.ItemDuration.Frame;
var fps = effectDescription.FPS;
var amount = Sanitize(_item.Amount.GetValue(frame, length, fps) / 100d, 0, 1, 0);
var parameters = new WaveOpticsPipeline.Parameters(
Sanitize(_item.Gain.GetValue(frame, length, fps) / 100d, 0, 4, 1),
new WaveOpticsPipeline.PsfParameters(
_item.Quality,
Math.Clamp(_item.KernelRadius, WaveOpticsSettings.MinimumKernelRadius, WaveOpticsSettings.MaximumKernelRadius),
Sanitize(_item.Wavelength.GetValue(frame, length, fps), 380, 780, 550),
Sanitize(_item.FNumber.GetValue(frame, length, fps), 0.5, 64, 8),
Sanitize(_item.PixelPitch.GetValue(frame, length, fps), 0.25, 100, 4),
_item.ApertureShape,
Math.Clamp(_item.BladeCount, 3, 32),
Sanitize(_item.BladeRotation.GetValue(frame, length, fps), -360, 360, 0),
Sanitize(_item.Obstruction.GetValue(frame, length, fps) / 100d, 0, 0.95, 0),
Sanitize(_item.Defocus.GetValue(frame, length, fps), -10, 10, 0),
Sanitize(_item.AstigmatismVertical.GetValue(frame, length, fps), -10, 10, 0),
Sanitize(_item.AstigmatismOblique.GetValue(frame, length, fps), -10, 10, 0),
Sanitize(_item.ComaHorizontal.GetValue(frame, length, fps), -10, 10, 0),
Sanitize(_item.ComaVertical.GetValue(frame, length, fps), -10, 10, 0),
Sanitize(_item.Spherical.GetValue(frame, length, fps), -10, 10, 0)));
if (_isFirst || _amount != amount)
_effect.Amount = amount;
if (amount <= 0f)
{
_effect.Amount = 0f;
_amount = amount;
_isFirst = true;
return effectDescription.DrawDescription;
}
var bounds = _devices.DeviceContext.GetImageLocalBounds(input);
var widthValue = Math.Ceiling((double)bounds.Right - bounds.Left);
var heightValue = Math.Ceiling((double)bounds.Bottom - bounds.Top);
if (!double.IsFinite(widthValue) || !double.IsFinite(heightValue) ||
!float.IsFinite(bounds.Left) || !float.IsFinite(bounds.Top) ||
widthValue <= 0d || heightValue <= 0d)
{
_effect.Amount = 0f;
_isFirst = true;
return effectDescription.DrawDescription;
}
var margin = WaveOpticsSettings.CanvasMargin;
var longSide = Math.Max(widthValue, heightValue);
if ((WaveOpticsSettings.MaximumCanvasSize - longSide) / 2d < margin)
{
_effect.Amount = 0f;
_isFirst = true;
return effectDescription.DrawDescription;
}
var canvasWidth = (int)widthValue + margin * 2;
var canvasHeight = (int)heightValue + margin * 2;
var itemWidth = (int)widthValue;
var itemHeight = (int)heightValue;
if (!EnsureSource(itemWidth, itemHeight))
{
_effect.Amount = 0f;
_isFirst = true;
return effectDescription.DrawDescription;
}
RenderInput(new Vortice.RawRectF(bounds.Left, bounds.Top, bounds.Left + itemWidth, bounds.Top + itemHeight));
var convolutionChanged = _pipeline.Simulate(
_resourceSet.GetSourceComputeBinding(),
canvasWidth,
canvasHeight,
margin,
margin,
itemWidth,
itemHeight,
in parameters);
if (!_pipeline.HasKernel || !_pipeline.TryGetVisibleBounds(canvasWidth, canvasHeight, in parameters, out var rect))
{
_effect.Amount = 0f;
_amount = amount;
_isFirst = true;
_hasRenderState = false;
return effectDescription.DrawDescription;
}
if (!OutputCovers(rect.Width, rect.Height))
_outputCrop.SetInput(0, null, true);
if (!EnsureOutput(rect.Width, rect.Height, out var outputChanged))
{
_effect.Amount = 0f;
_amount = amount;
_isFirst = true;
_hasRenderState = false;
return effectDescription.DrawDescription;
}
var renderState = new RenderState(parameters.Gain, rect);
if (convolutionChanged || outputChanged || !_hasOutput || !_hasRenderState || _renderState != renderState)
{
_pipeline.RenderVisible(_resourceSet.GetOutputComputeBinding(), rect, in parameters);
_renderState = renderState;
_hasRenderState = true;
}
_outputLease ??= _resourceSet.AcquireOutputExternalViewLease();
if (outputChanged || !_hasOutput)
{
using var outputBitmap = new ID2D1Bitmap1(_outputLease.DangerousGetView().AddRefBitmap());
_outputCrop.SetInput(0, outputBitmap, true);
_effect.SetInput(1, _outputTransformOutput, true);
}
var cropRect = new Vector4(0f, 0f, rect.Width, rect.Height);
if (!_hasCropRect || _cropRect != cropRect)
{
_outputCrop.Rectangle = cropRect;
_cropRect = cropRect;
_hasCropRect = true;
}
var outputOffset = new Vector2(bounds.Left - margin + rect.X, bounds.Top - margin + rect.Y);
if (!_hasOutputOffset || _outputOffset != outputOffset)
{
_outputTransform.TransformMatrix = Matrix3x2.CreateTranslation(outputOffset);
_outputOffset = outputOffset;
_hasOutputOffset = true;
}
_hasOutput = true;
_amount = amount;
_isFirst = false;
return effectDescription.DrawDescription;
}
private bool EnsureSource(int width, int height)
{
return _resourceSet!.TryEnsureSource(width, height, out _);
}
private bool OutputCovers(int width, int height)
=> _outputLease is { IsDisposed: false } lease &&
lease.Width >= width &&
lease.Height >= height;
private bool EnsureOutput(int width, int height, out bool changed)
{
changed = false;
if (OutputCovers(width, height))
return true;
_outputLease?.Dispose();
_outputLease = null;
return _resourceSet!.TryEnsureOutput(width, height, out changed);
}
private void RenderInput(Vortice.RawRectF bounds)
{
var renderContext = _interopProvider!.RenderContext;
using var borrow = _resourceSet!.BeginSourceExternalOperation();
var previousTarget = renderContext.Target;
using var sourceBitmap = new ID2D1Bitmap1(borrow.DangerousGetView().AddRefBitmap());
renderContext.Target = sourceBitmap;
renderContext.BeginDraw();
renderContext.Clear(null);
renderContext.DrawImage(
input,
new Vector2(-bounds.Left, -bounds.Top),
null,
InterpolationMode.NearestNeighbor,
CompositeMode.SourceCopy);
renderContext.EndDraw();
renderContext.Target = previousTarget;
}
private static float Sanitize(double value, double minimum, double maximum, double fallback)
{
if (!double.IsFinite(value))
return (float)fallback;
return (float)Math.Clamp(value, minimum, maximum);
}
private void ReleaseInterop()
{
_outputLease?.Dispose();
_outputLease = null;
_pipeline?.Dispose();
_pipeline = null;
_resourceSet?.Dispose();
_resourceSet?.WaitForDisposal();
_resourceSet = null;
_interopDomain?.Dispose();
_interopDomain?.WaitForDisposal();
_interopDomain = null;
_interopProvider?.Dispose();
_interopProvider = null;
_scheduler?.Dispose();
_scheduler = null;
}
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
{
var scheduler = ComputeExternalQueueScheduler.Create();
var interopProvider = WaveOpticsInteropProvider.TryCreate(devices, scheduler, out var interopDevice);
if (interopProvider is null || interopDevice is null)
{
scheduler.Dispose();
return null;
}
_scheduler = scheduler;
try
{
_interopProvider = interopProvider;
_interopDomain = interopDevice.RegisterExternalDomain(interopProvider);
_resourceSet = WaveOpticsResourceSet.Create(interopDevice, _interopDomain);
_pipeline = WaveOpticsPipeline.TryCreate(interopDevice);
}
catch (Win32Exception)
{
ReleaseInterop();
return null;
}
catch
{
ReleaseInterop();
throw;
}
if (_pipeline is null)
{
ReleaseInterop();
return null;
}
WaveOpticsCustomEffect? effect = null;
Crop? outputCrop = null;
ID2D1Image? outputCropOutput = null;
AffineTransform2D? outputTransform = null;
ID2D1Image? outputTransformOutput = null;
ID2D1Image? output = null;
try
{
effect = new WaveOpticsCustomEffect(devices);
if (!effect.IsEnabled)
{
effect.Dispose();
ReleaseInterop();
return null;
}
outputCrop = new Crop(devices.DeviceContext);
outputCropOutput = outputCrop.Output;
outputTransform = new AffineTransform2D(devices.DeviceContext)
{
BorderMode = BorderMode.Hard,
};
outputTransform.SetInput(0, outputCropOutput, true);
outputTransformOutput = outputTransform.Output;
output = effect.Output;
_effect = effect;
_outputCrop = outputCrop;
_outputCropOutput = outputCropOutput;
_outputTransform = outputTransform;
_outputTransformOutput = outputTransformOutput;
disposer.Collect(effect);
disposer.Collect(outputCrop);
disposer.Collect(outputCropOutput);
disposer.Collect(outputTransform);
disposer.Collect(outputTransformOutput);
disposer.Collect(output);
return output;
}
catch
{
output?.Dispose();
outputTransformOutput?.Dispose();
outputTransform?.Dispose();
outputCropOutput?.Dispose();
outputCrop?.Dispose();
effect?.Dispose();
ReleaseInterop();
throw;
}
}
protected override void setInput(ID2D1Image? inputImage)
{
try
{
SetInputCore(inputImage);
}
catch (Exception exception)
{
WaveOpticsTelemetry.Report(exception);
throw;
}
}
private void SetInputCore(ID2D1Image? inputImage)
{
_effect?.SetInput(0, inputImage, true);
if (!_hasOutput)
_effect?.SetInput(1, inputImage, true);
}
protected override void ClearEffectChain()
{
_effect?.SetInput(0, null, true);
_effect?.SetInput(1, null, true);
_outputCrop?.SetInput(0, null, true);
_isFirst = true;
_hasOutput = false;
_hasOutputOffset = false;
_hasCropRect = false;
_hasRenderState = false;
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
ClearEffectChain();
ReleaseInterop();
}
}
catch (Exception exception)
{
WaveOpticsTelemetry.Report(exception);
throw;
}
finally
{
base.Dispose(disposing);
}
}
private readonly record struct RenderState(
float Gain,
WaveOpticsPipeline.PixelRect Rect);
}
差分なしでファイル名を変更。
+210
ファイルの表示
@@ -0,0 +1,210 @@
using System.Buffers;
using System.Collections.Concurrent;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace WaveOptics.Fourier;
internal static class FastFourierTransform
{
static readonly ConcurrentDictionary<long, Twiddles> TwiddleCache = new();
public static void Forward(Span<double> real, Span<double> imaginary) => Transform(real, imaginary, false);
public static void Inverse(Span<double> real, Span<double> imaginary) => Transform(real, imaginary, true);
public static void Forward2D(double[] real, double[] imaginary, int width, int height) => Transform2D(real, imaginary, width, height, false);
public static void Inverse2D(double[] real, double[] imaginary, int width, int height) => Transform2D(real, imaginary, width, height, true);
static void Transform(Span<double> real, Span<double> imaginary, bool inverse)
{
var count = real.Length;
if (count == 0 || imaginary.Length != count || !BitOperations.IsPow2((uint)count))
throw new ArgumentException(nameof(real));
var twiddles = GetTwiddles(count, inverse);
Reorder(real, imaginary);
Butterflies(real, imaginary, twiddles);
if (inverse)
Scale(real, imaginary, 1d / count);
}
static void Transform2D(double[] real, double[] imaginary, int width, int height, bool inverse)
{
ArgumentNullException.ThrowIfNull(real);
ArgumentNullException.ThrowIfNull(imaginary);
var area = width * height;
if (real.Length < area || imaginary.Length < area)
throw new ArgumentException(nameof(real));
if (!BitOperations.IsPow2((uint)width) || !BitOperations.IsPow2((uint)height))
throw new ArgumentException(nameof(width));
for (var y = 0; y < height; y++)
{
var offset = y * width;
Transform(real.AsSpan(offset, width), imaginary.AsSpan(offset, width), inverse);
}
var columnReal = ArrayPool<double>.Shared.Rent(height);
var columnImaginary = ArrayPool<double>.Shared.Rent(height);
try
{
var rowReal = real.AsSpan(0, area);
var rowImaginary = imaginary.AsSpan(0, area);
for (var x = 0; x < width; x++)
{
for (var y = 0; y < height; y++)
{
var index = y * width + x;
columnReal[y] = rowReal[index];
columnImaginary[y] = rowImaginary[index];
}
Transform(columnReal.AsSpan(0, height), columnImaginary.AsSpan(0, height), inverse);
for (var y = 0; y < height; y++)
{
var index = y * width + x;
rowReal[index] = columnReal[y];
rowImaginary[index] = columnImaginary[y];
}
}
}
finally
{
ArrayPool<double>.Shared.Return(columnReal);
ArrayPool<double>.Shared.Return(columnImaginary);
}
}
static void Reorder(Span<double> real, Span<double> imaginary)
{
var count = real.Length;
for (int source = 1, target = 0; source < count; source++)
{
var bit = count >> 1;
for (; (target & bit) != 0; bit >>= 1)
target ^= bit;
target ^= bit;
if (source < target)
{
(real[source], real[target]) = (real[target], real[source]);
(imaginary[source], imaginary[target]) = (imaginary[target], imaginary[source]);
}
}
}
static void Butterflies(Span<double> real, Span<double> imaginary, Twiddles twiddles)
{
var count = real.Length;
ref var realBase = ref MemoryMarshal.GetReference(real);
ref var imaginaryBase = ref MemoryMarshal.GetReference(imaginary);
var width = Vector<double>.Count;
for (int length = 2, stage = 0; length <= count; length <<= 1, stage++)
{
var half = length >> 1;
var cos = twiddles.Cos[stage];
var sin = twiddles.Sin[stage];
ref var cosBase = ref MemoryMarshal.GetArrayDataReference(cos);
ref var sinBase = ref MemoryMarshal.GetArrayDataReference(sin);
var vectorized = Vector.IsHardwareAccelerated && half >= width;
for (var offset = 0; offset < count; offset += length)
{
var index = 0;
if (vectorized)
{
for (; index + width <= half; index += width)
{
var even = offset + index;
var odd = even + half;
var evenReal = Vector.LoadUnsafe(ref Unsafe.Add(ref realBase, even));
var evenImaginary = Vector.LoadUnsafe(ref Unsafe.Add(ref imaginaryBase, even));
var oddReal = Vector.LoadUnsafe(ref Unsafe.Add(ref realBase, odd));
var oddImaginary = Vector.LoadUnsafe(ref Unsafe.Add(ref imaginaryBase, odd));
var weightReal = Vector.LoadUnsafe(ref Unsafe.Add(ref cosBase, index));
var weightImaginary = Vector.LoadUnsafe(ref Unsafe.Add(ref sinBase, index));
var productReal = oddReal * weightReal - oddImaginary * weightImaginary;
var productImaginary = oddReal * weightImaginary + oddImaginary * weightReal;
(evenReal + productReal).StoreUnsafe(ref Unsafe.Add(ref realBase, even));
(evenImaginary + productImaginary).StoreUnsafe(ref Unsafe.Add(ref imaginaryBase, even));
(evenReal - productReal).StoreUnsafe(ref Unsafe.Add(ref realBase, odd));
(evenImaginary - productImaginary).StoreUnsafe(ref Unsafe.Add(ref imaginaryBase, odd));
}
}
for (; index < half; index++)
{
var even = offset + index;
var odd = even + half;
var weightReal = Unsafe.Add(ref cosBase, index);
var weightImaginary = Unsafe.Add(ref sinBase, index);
var oddReal = Unsafe.Add(ref realBase, odd);
var oddImaginary = Unsafe.Add(ref imaginaryBase, odd);
var productReal = oddReal * weightReal - oddImaginary * weightImaginary;
var productImaginary = oddReal * weightImaginary + oddImaginary * weightReal;
var evenReal = Unsafe.Add(ref realBase, even);
var evenImaginary = Unsafe.Add(ref imaginaryBase, even);
Unsafe.Add(ref realBase, even) = evenReal + productReal;
Unsafe.Add(ref imaginaryBase, even) = evenImaginary + productImaginary;
Unsafe.Add(ref realBase, odd) = evenReal - productReal;
Unsafe.Add(ref imaginaryBase, odd) = evenImaginary - productImaginary;
}
}
}
}
static void Scale(Span<double> real, Span<double> imaginary, double factor)
{
var count = real.Length;
ref var realBase = ref MemoryMarshal.GetReference(real);
ref var imaginaryBase = ref MemoryMarshal.GetReference(imaginary);
var index = 0;
if (Vector.IsHardwareAccelerated)
{
var scale = new Vector<double>(factor);
var width = Vector<double>.Count;
for (; index + width <= count; index += width)
{
(Vector.LoadUnsafe(ref Unsafe.Add(ref realBase, index)) * scale).StoreUnsafe(ref Unsafe.Add(ref realBase, index));
(Vector.LoadUnsafe(ref Unsafe.Add(ref imaginaryBase, index)) * scale).StoreUnsafe(ref Unsafe.Add(ref imaginaryBase, index));
}
}
for (; index < count; index++)
{
Unsafe.Add(ref realBase, index) *= factor;
Unsafe.Add(ref imaginaryBase, index) *= factor;
}
}
static Twiddles GetTwiddles(int count, bool inverse) =>
TwiddleCache.GetOrAdd(((long)count << 1) | (inverse ? 1L : 0L), _ => new Twiddles(count, inverse));
sealed class Twiddles
{
public double[][] Cos { get; }
public double[][] Sin { get; }
public Twiddles(int count, bool inverse)
{
var stages = BitOperations.TrailingZeroCount(count);
Cos = new double[stages][];
Sin = new double[stages][];
var sign = inverse ? 1d : -1d;
for (int length = 2, stage = 0; stage < stages; length <<= 1, stage++)
{
var half = length >> 1;
var cos = new double[half];
var sin = new double[half];
for (var index = 0; index < half; index++)
{
var (sinValue, cosValue) = Math.SinCos(sign * 2d * Math.PI * index / length);
cos[index] = cosValue;
sin[index] = sinValue;
}
Cos[stage] = cos;
Sin[stage] = sin;
}
}
}
}
+226
ファイルの表示
@@ -0,0 +1,226 @@
using System.Buffers;
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using WaveOptics.Abstractions;
using WaveOptics.Fourier;
namespace WaveOptics.Optics;
public sealed class FraunhoferPsfGenerator : IPsfGenerator
{
const double TwoPi = 2 * Math.PI;
public OpticalApiVersion ApiVersion => OpticalApiVersion.Current;
public OpticalCapabilities Capabilities => OpticalCapabilities.MonochromaticPsf
| OpticalCapabilities.CircularAperture
| OpticalCapabilities.RegularPolygonAperture
| OpticalCapabilities.CentralObstruction
| OpticalCapabilities.ZernikeAberration
| OpticalCapabilities.DirectConvolution;
public PsfGenerationResult Generate(PsfDescriptor descriptor)
{
if (!TryGenerate(descriptor, out var result))
throw new InvalidOperationException();
return result;
}
public bool TryGenerate(PsfDescriptor descriptor, [NotNullWhen(true)] out PsfGenerationResult? result)
{
ArgumentNullException.ThrowIfNull(descriptor);
result = null;
var gridSize = descriptor.PupilGridSize;
var area = gridSize * gridSize;
var real = ArrayPool<double>.Shared.Rent(area);
var imaginary = ArrayPool<double>.Shared.Rent(area);
var intensity = ArrayPool<double>.Shared.Rent(area);
try
{
var openSampleCount = BuildPupil(descriptor, real, imaginary);
if (openSampleCount == 0)
return false;
FastFourierTransform.Forward2D(real, imaginary, gridSize, gridSize);
var fullEnergy = ComputeShiftedIntensity(real, imaginary, intensity, gridSize);
if (!double.IsFinite(fullEnergy) || fullEnergy <= 0)
return false;
var wavelengthMicrometers = descriptor.WavelengthNanometers / 1000d;
var focalPlaneSamplePitch = wavelengthMicrometers * descriptor.FNumber * descriptor.PupilDiameterSamples / gridSize;
var center = gridSize / 2;
var kernelSize = descriptor.KernelSize;
var kernelRadius = kernelSize / 2;
var kernel = new double[kernelSize * kernelSize];
var rawKernelEnergy = 0d;
for (var y = 0; y < kernelSize; y++)
{
var sampleY = center + (y - kernelRadius) * descriptor.SensorPixelPitchMicrometers / focalPlaneSamplePitch;
for (var x = 0; x < kernelSize; x++)
{
var sampleX = center + (x - kernelRadius) * descriptor.SensorPixelPitchMicrometers / focalPlaneSamplePitch;
var value = SampleBilinear(intensity, gridSize, sampleX, sampleY);
kernel[y * kernelSize + x] = value;
rawKernelEnergy += value;
}
}
if (!double.IsFinite(rawKernelEnergy) || rawKernelEnergy <= 0)
return false;
var psfKernel = new PsfKernel(kernelSize, kernel);
var diagnostics = new PsfDiagnostics(
openSampleCount,
focalPlaneSamplePitch,
rawKernelEnergy / fullEnergy,
Peak(psfKernel.Values.Span));
result = new PsfGenerationResult(psfKernel, diagnostics);
return true;
}
finally
{
ArrayPool<double>.Shared.Return(real);
ArrayPool<double>.Shared.Return(imaginary);
ArrayPool<double>.Shared.Return(intensity);
}
}
static int BuildPupil(PsfDescriptor descriptor, double[] real, double[] imaginary)
{
var gridSize = descriptor.PupilGridSize;
var center = gridSize / 2;
var pupilRadius = descriptor.PupilDiameterSamples / 2d;
var rotation = descriptor.BladeRotationDegrees * Math.PI / 180d;
var openSampleCount = 0;
for (var y = 0; y < gridSize; y++)
{
var normalizedY = (y - center) / pupilRadius;
var row = y * gridSize;
for (var x = 0; x < gridSize; x++)
{
var index = row + x;
var normalizedX = (x - center) / pupilRadius;
if (IsInsideAperture(normalizedX, normalizedY, descriptor, rotation))
{
var waves = ZernikeWavefront.Evaluate(normalizedX, normalizedY, descriptor.Aberration);
var (sin, cos) = Math.SinCos(TwoPi * waves);
real[index] = cos;
imaginary[index] = sin;
openSampleCount++;
}
else
{
real[index] = 0;
imaginary[index] = 0;
}
}
}
return openSampleCount;
}
static double ComputeShiftedIntensity(double[] real, double[] imaginary, double[] intensity, int gridSize)
{
var center = gridSize / 2;
var fullEnergy = 0d;
for (var y = 0; y < gridSize; y++)
{
var sourceRow = ((y + center) % gridSize) * gridSize;
var destinationRow = y * gridSize;
fullEnergy += Power(
real.AsSpan(sourceRow + center, gridSize - center),
imaginary.AsSpan(sourceRow + center, gridSize - center),
intensity.AsSpan(destinationRow, gridSize - center));
fullEnergy += Power(
real.AsSpan(sourceRow, center),
imaginary.AsSpan(sourceRow, center),
intensity.AsSpan(destinationRow + gridSize - center, center));
}
return fullEnergy;
}
static double Power(ReadOnlySpan<double> real, ReadOnlySpan<double> imaginary, Span<double> intensity)
{
var count = real.Length;
ref var realBase = ref MemoryMarshal.GetReference(real);
ref var imaginaryBase = ref MemoryMarshal.GetReference(imaginary);
ref var intensityBase = ref MemoryMarshal.GetReference(intensity);
var sum = 0d;
var index = 0;
if (Vector.IsHardwareAccelerated)
{
var accumulator = Vector<double>.Zero;
var width = Vector<double>.Count;
for (; index + width <= count; index += width)
{
var a = Vector.LoadUnsafe(ref Unsafe.Add(ref realBase, index));
var b = Vector.LoadUnsafe(ref Unsafe.Add(ref imaginaryBase, index));
var power = a * a + b * b;
power.StoreUnsafe(ref Unsafe.Add(ref intensityBase, index));
accumulator += power;
}
sum += Vector.Sum(accumulator);
}
for (; index < count; index++)
{
var a = Unsafe.Add(ref realBase, index);
var b = Unsafe.Add(ref imaginaryBase, index);
var power = a * a + b * b;
Unsafe.Add(ref intensityBase, index) = power;
sum += power;
}
return sum;
}
static double Peak(ReadOnlySpan<double> values)
{
var peak = 0d;
foreach (var value in values)
{
if (value > peak)
peak = value;
}
return peak;
}
static bool IsInsideAperture(double x, double y, PsfDescriptor descriptor, double rotation)
{
var radiusSquared = x * x + y * y;
var obstructionSquared = descriptor.CentralObstructionRatio * descriptor.CentralObstructionRatio;
if (radiusSquared > 1d || radiusSquared < obstructionSquared)
return false;
if (descriptor.ApertureShape == ApertureShape.Circular)
return true;
var radius = Math.Sqrt(radiusSquared);
if (radius == 0)
return descriptor.CentralObstructionRatio == 0;
var sector = TwoPi / descriptor.BladeCount;
var angle = Math.Atan2(y, x) - rotation;
var folded = angle - sector * Math.Round(angle / sector);
var boundary = Math.Cos(Math.PI / descriptor.BladeCount) / Math.Cos(folded);
return radius <= boundary;
}
static double SampleBilinear(double[] values, int size, double x, double y)
{
if (x < 0 || y < 0 || x > size - 1 || y > size - 1)
return 0;
var x0 = (int)Math.Floor(x);
var y0 = (int)Math.Floor(y);
var x1 = Math.Min(x0 + 1, size - 1);
var y1 = Math.Min(y0 + 1, size - 1);
var tx = x - x0;
var ty = y - y0;
var top = values[y0 * size + x0] * (1 - tx) + values[y0 * size + x1] * tx;
var bottom = values[y1 * size + x0] * (1 - tx) + values[y1 * size + x1] * tx;
return top * (1 - ty) + bottom * ty;
}
}
+155
ファイルの表示
@@ -0,0 +1,155 @@
namespace WaveOptics.Optics;
internal readonly struct SeparableKernel
{
public int Size { get; }
public int Rank { get; }
public double ResidualEnergyRatio { get; }
public double Sum { get; }
public float[] Horizontal { get; }
public float[] Vertical { get; }
SeparableKernel(int size, int rank, double residualEnergyRatio, double sum, float[] horizontal, float[] vertical)
{
Size = size;
Rank = rank;
ResidualEnergyRatio = residualEnergyRatio;
Sum = sum;
Horizontal = horizontal;
Vertical = vertical;
}
public static SeparableKernel Decompose(ReadOnlySpan<double> kernel, int size, double residualEnergyRatio, int maximumRank)
{
var work = new double[size * size];
for (var index = 0; index < work.Length; index++)
work[index] = kernel[index];
var basis = new double[size * size];
for (var i = 0; i < size; i++)
basis[i * size + i] = 1d;
OrthogonalizeColumns(work, basis, size);
var singularValues = new double[size];
var order = new int[size];
var totalEnergy = 0d;
for (var column = 0; column < size; column++)
{
var norm = 0d;
for (var row = 0; row < size; row++)
{
var value = work[row * size + column];
norm += value * value;
}
singularValues[column] = Math.Sqrt(norm);
order[column] = column;
totalEnergy += norm;
}
Array.Sort(order, (left, right) => singularValues[right].CompareTo(singularValues[left]));
var largest = singularValues[order[0]];
var significant = 0;
var threshold = largest * 1e-12;
for (var i = 0; i < size && singularValues[order[i]] > threshold; i++)
significant++;
significant = Math.Max(significant, 1);
var rank = significant;
if (residualEnergyRatio > 0 && totalEnergy > 0)
{
var retained = 0d;
var target = (1d - residualEnergyRatio) * totalEnergy;
rank = 0;
for (var i = 0; i < significant; i++)
{
retained += singularValues[order[i]] * singularValues[order[i]];
rank++;
if (retained >= target)
break;
}
}
rank = Math.Clamp(rank, 1, Math.Min(maximumRank, significant));
var retainedEnergy = 0d;
for (var i = 0; i < rank; i++)
retainedEnergy += singularValues[order[i]] * singularValues[order[i]];
var residual = totalEnergy > 0 ? Math.Max(0d, (totalEnergy - retainedEnergy) / totalEnergy) : 0d;
var horizontal = new float[rank * size];
var vertical = new float[rank * size];
var sum = 0d;
for (var term = 0; term < rank; term++)
{
var column = order[term];
var singularValue = singularValues[column];
var inverse = singularValue > 0 ? 1d / singularValue : 0d;
var horizontalBase = term * size;
var horizontalSum = 0d;
var verticalSum = 0d;
for (var k = 0; k < size; k++)
{
horizontal[horizontalBase + k] = (float)(basis[k * size + column]);
vertical[horizontalBase + k] = (float)(work[k * size + column] * inverse * singularValue);
horizontalSum += horizontal[horizontalBase + k];
verticalSum += vertical[horizontalBase + k];
}
sum += horizontalSum * verticalSum;
}
return new SeparableKernel(size, rank, residual, sum, horizontal, vertical);
}
static void OrthogonalizeColumns(double[] work, double[] basis, int size)
{
const int maximumSweeps = 60;
const double tolerance = 1e-15;
for (var sweep = 0; sweep < maximumSweeps; sweep++)
{
var converged = true;
for (var p = 0; p < size - 1; p++)
{
for (var q = p + 1; q < size; q++)
{
var alpha = 0d;
var beta = 0d;
var gamma = 0d;
for (var k = 0; k < size; k++)
{
var wp = work[k * size + p];
var wq = work[k * size + q];
alpha += wp * wp;
beta += wq * wq;
gamma += wp * wq;
}
if (Math.Abs(gamma) <= tolerance * Math.Sqrt(alpha * beta))
continue;
converged = false;
var zeta = (beta - alpha) / (2d * gamma);
var t = Math.Sign(zeta) / (Math.Abs(zeta) + Math.Sqrt(1d + zeta * zeta));
if (zeta == 0d)
t = 1d;
var c = 1d / Math.Sqrt(1d + t * t);
var s = c * t;
for (var k = 0; k < size; k++)
{
var index = k * size;
var wp = work[index + p];
var wq = work[index + q];
work[index + p] = c * wp - s * wq;
work[index + q] = s * wp + c * wq;
var vp = basis[index + p];
var vq = basis[index + q];
basis[index + p] = c * vp - s * vq;
basis[index + q] = s * vp + c * vq;
}
}
}
if (converged)
break;
}
}
}
差分なしでファイル名を変更。
@@ -2,5 +2,5 @@ namespace WaveOptics.Rendering;
internal static class ShaderResourceUri
{
public static Uri Get(string shaderName) => new($"pack://application:,,,/WaveOptics;component/Shaders/{shaderName}.cso", UriKind.Absolute);
public static Uri Get(string shaderName) => new($"pack://application:,,,/WaveOptics;component/Resources/Shader/{shaderName}.cso", UriKind.Absolute);
}
+98
ファイルの表示
@@ -0,0 +1,98 @@
using System.Runtime.InteropServices;
using Vortice;
using Vortice.Direct2D1;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Player.Video;
namespace WaveOptics.Rendering;
internal sealed class WaveOpticsCustomEffect(IGraphicsDevicesAndContext devices)
: D2D1CustomShaderEffectBase(Create<EffectImpl>(devices))
{
public float Amount { set => SetValue((int)EffectImpl.Properties.Amount, value); }
[CustomEffect(2)]
private sealed class EffectImpl : D2D1CustomShaderEffectImplBase<EffectImpl>
{
private ConstantBuffer _cb;
[CustomEffectProperty(PropertyType.Float, (int)Properties.Amount)]
public float Amount
{
get => _cb.Amount;
set
{
_cb.Amount = Math.Clamp(value, 0f, 1f);
UpdateConstants();
}
}
public EffectImpl() : base(ShaderResourceUri.Get("WaveOptics"))
{
}
protected override void UpdateConstants()
{
if (drawInformation is null)
return;
try
{
drawInformation.SetPixelShaderConstantBuffer(_cb);
}
catch (Exception exception)
{
WaveOpticsTelemetry.Report(exception);
throw;
}
}
public override void MapInputRectsToOutputRect(
RawRect[] inputRects,
RawRect[] inputOpaqueSubRects,
out RawRect outputRect,
out RawRect outputOpaqueSubRect)
{
if (inputRects.Length == 0)
{
outputRect = default;
outputOpaqueSubRect = default;
return;
}
var union = inputRects[0];
var inputCount = _cb.Amount <= 0f ? 1 : inputRects.Length;
for (var i = 1; i < inputCount; i++)
{
var rect = inputRects[i];
union = new RawRect(
Math.Min(union.Left, rect.Left),
Math.Min(union.Top, rect.Top),
Math.Max(union.Right, rect.Right),
Math.Max(union.Bottom, rect.Bottom));
}
outputRect = union;
outputOpaqueSubRect = default;
}
public override void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects)
{
for (var i = 0; i < inputRects.Length; i++)
inputRects[i] = outputRect;
}
[StructLayout(LayoutKind.Sequential)]
private struct ConstantBuffer
{
public float Amount;
public float Pad0;
public float Pad1;
public float Pad2;
}
public enum Properties
{
Amount = 0,
}
}
}
+89
ファイルの表示
@@ -0,0 +1,89 @@
using ComputeWeave;
using Vortice.Direct2D1;
using Vortice.Direct3D11;
using YukkuriMovieMaker.Commons;
namespace WaveOptics.Rendering;
internal sealed class WaveOpticsInteropProvider : ComputeExternalDirect3D11Provider
{
private readonly ID2D1DeviceContext6 _renderContext;
private WaveOpticsInteropProvider(
ID3D11Device1 device,
ID3D11DeviceContext4 context,
ID2D1DeviceContext6 renderContext,
ComputeExternalQueueScheduler scheduler)
: base(device.NativePointer, context.NativePointer, renderContext.NativePointer, scheduler)
{
_renderContext = renderContext;
}
public ID2D1DeviceContext6 RenderContext => _renderContext;
public static WaveOpticsInteropProvider? TryCreate(
IGraphicsDevicesAndContext devices,
ComputeExternalQueueScheduler scheduler,
out GraphicsDevice? graphicsDevice)
{
ArgumentNullException.ThrowIfNull(scheduler);
graphicsDevice = null;
ID3D11Device1? device = null;
ID3D11DeviceContext4? context = null;
ID2D1DeviceContext6? renderContext = null;
try
{
if (!GraphicsDevice.TryGetDevice(new ExternalAdapterIdentity(devices.DXGI.Adapter.Description.Luid), out graphicsDevice))
return null;
device = devices.D3D.Device.QueryInterface<ID3D11Device1>();
context = devices.D3D.DeviceContext.QueryInterface<ID3D11DeviceContext4>();
renderContext = devices.D2D.Device.CreateDeviceContext(DeviceContextOptions.EnableMultithreadedOptimizations);
var provider = new WaveOpticsInteropProvider(device, context, renderContext, scheduler);
renderContext = null;
return provider;
}
catch
{
graphicsDevice = null;
return null;
}
finally
{
renderContext?.Dispose();
context?.Dispose();
device?.Dispose();
}
}
protected override void DisposeCore()
{
_renderContext.Dispose();
}
}
[ComputeInteropResourceSet]
internal sealed partial class WaveOpticsResourceSet
{
[ComputeSharedTexture(
ComputeResourceResizePolicy.Exact,
ComputeResourceAccess.ReadWrite,
ExternalResourceAccess.Write,
ExternalTextureUsage.RenderTarget,
ComputeAlphaMode.Premultiplied,
ComputeSharedTextureInitialOwner.External,
ComputeResourceRecovery.RecreateFromHost)]
private readonly SharedTextureSlot<Bgra32, Float4, ExternalDirect3D11TextureView> _source;
[ComputeSharedTexture(
ComputeResourceResizePolicy.GrowOnly,
ComputeResourceAccess.ReadWrite,
ExternalResourceAccess.Read,
ExternalTextureUsage.Sampled,
ComputeAlphaMode.Premultiplied,
ComputeSharedTextureInitialOwner.Compute,
ComputeResourceRecovery.Recompute)]
private readonly SharedTextureSlot<Bgra32, Float4, ExternalDirect3D11TextureView> _output;
}
+326
ファイルの表示
@@ -0,0 +1,326 @@
using ComputeWeave;
namespace WaveOptics.Rendering;
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct FillIntShader(
ReadWriteBuffer<int> values,
int length,
int value) : IComputeShader
{
private readonly ReadWriteBuffer<int> values = values;
private readonly int length = length;
private readonly int value = value;
public void Execute()
{
var index = ThreadIds.X;
if (index >= length)
return;
values[index] = value;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct SourceHashResetShader(
ReadWriteBuffer<int> scratch) : IComputeShader
{
private readonly ReadWriteBuffer<int> scratch = scratch;
public void Execute()
{
if (ThreadIds.X != 0)
return;
scratch[WaveOpticsSettings.ScratchLitCount] = 0;
scratch[WaveOpticsSettings.ScratchBoundsMinX] = 2147483647;
scratch[WaveOpticsSettings.ScratchBoundsMinY] = 2147483647;
scratch[WaveOpticsSettings.ScratchBoundsMaxX] = -2147483648;
scratch[WaveOpticsSettings.ScratchBoundsMaxY] = -2147483648;
scratch[WaveOpticsSettings.ScratchHashSum] = 0;
scratch[WaveOpticsSettings.ScratchHashMix] = 0;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct SourceHashShader(
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteBuffer<int> scratch,
int sourceX,
int sourceY,
int sourceWidth,
int sourceHeight) : IComputeShader
{
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
private readonly ReadWriteBuffer<int> scratch = scratch;
private readonly int sourceX = sourceX;
private readonly int sourceY = sourceY;
private readonly int sourceWidth = sourceWidth;
private readonly int sourceHeight = sourceHeight;
public void Execute()
{
var x = ThreadIds.X;
var y = ThreadIds.Y;
if (x >= sourceWidth || y >= sourceHeight)
return;
var color = source[ThreadIds.XY];
var quantized = ((uint)(color.X * 255f + 0.5f) << 24)
| ((uint)(color.Y * 255f + 0.5f) << 16)
| ((uint)(color.Z * 255f + 0.5f) << 8)
| (uint)(color.W * 255f + 0.5f);
if (quantized == 0u)
return;
var mixed = ((uint)(y * sourceWidth + x) * 0x9E3779B9u) ^ (quantized * 0x85EBCA6Bu);
mixed ^= mixed >> 16;
mixed *= 0x85EBCA6Bu;
mixed ^= mixed >> 13;
Hlsl.InterlockedAdd(ref scratch[WaveOpticsSettings.ScratchHashSum], (int)mixed);
Hlsl.InterlockedXor(ref scratch[WaveOpticsSettings.ScratchHashMix], (int)(mixed * 0xC2B2AE35u));
Hlsl.InterlockedAdd(ref scratch[WaveOpticsSettings.ScratchLitCount], 1);
Hlsl.InterlockedMin(ref scratch[WaveOpticsSettings.ScratchBoundsMinX], sourceX + x);
Hlsl.InterlockedMin(ref scratch[WaveOpticsSettings.ScratchBoundsMinY], sourceY + y);
Hlsl.InterlockedMax(ref scratch[WaveOpticsSettings.ScratchBoundsMaxX], sourceX + x);
Hlsl.InterlockedMax(ref scratch[WaveOpticsSettings.ScratchBoundsMaxY], sourceY + y);
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct HorizontalPassShader(
ReadWriteTexture2D<Bgra32, Float4> source,
ReadOnlyBuffer<float> weights,
ReadWriteBuffer<Float4> horizontal,
int weightOffset,
int radius,
int regionX,
int regionY,
int regionWidth,
int regionHeight,
int canvasWidth,
int sourceX,
int sourceY,
int sourceWidth) : IComputeShader
{
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
private readonly ReadOnlyBuffer<float> weights = weights;
private readonly ReadWriteBuffer<Float4> horizontal = horizontal;
private readonly int weightOffset = weightOffset;
private readonly int radius = radius;
private readonly int regionX = regionX;
private readonly int regionY = regionY;
private readonly int regionWidth = regionWidth;
private readonly int regionHeight = regionHeight;
private readonly int canvasWidth = canvasWidth;
private readonly int sourceX = sourceX;
private readonly int sourceY = sourceY;
private readonly int sourceWidth = sourceWidth;
public void Execute()
{
var offsetX = ThreadIds.X * WaveOpticsSettings.ConvolutionBlock;
if (offsetX >= regionWidth || ThreadIds.Y >= regionHeight)
return;
var x = regionX + offsetX;
var y = regionY + ThreadIds.Y;
var column = x - sourceX;
var row = y - sourceY;
var first = Hlsl.Max(-radius, -column);
var last = Hlsl.Min(radius + WaveOpticsSettings.ConvolutionBlock - 1, sourceWidth - 1 - column);
var weight0 = Weight(first - 1);
var weight1 = Weight(first - 2);
var weight2 = Weight(first - 3);
var weight3 = Weight(first - 4);
var weight4 = Weight(first - 5);
var weight5 = Weight(first - 6);
var weight6 = Weight(first - 7);
var sum0 = new Float4(0f, 0f, 0f, 0f);
var sum1 = sum0;
var sum2 = sum0;
var sum3 = sum0;
var sum4 = sum0;
var sum5 = sum0;
var sum6 = sum0;
var sum7 = sum0;
for (var offset = first; offset <= last; offset++)
{
var weight7 = weight6;
weight6 = weight5;
weight5 = weight4;
weight4 = weight3;
weight3 = weight2;
weight2 = weight1;
weight1 = weight0;
weight0 = Weight(offset);
var texel = source[new Int2(column + offset, row)];
sum0 += texel * weight0;
sum1 += texel * weight1;
sum2 += texel * weight2;
sum3 += texel * weight3;
sum4 += texel * weight4;
sum5 += texel * weight5;
sum6 += texel * weight6;
sum7 += texel * weight7;
}
var index = y * canvasWidth + x;
horizontal[index] = sum0;
if (offsetX + 1 < regionWidth)
horizontal[index + 1] = sum1;
if (offsetX + 2 < regionWidth)
horizontal[index + 2] = sum2;
if (offsetX + 3 < regionWidth)
horizontal[index + 3] = sum3;
if (offsetX + 4 < regionWidth)
horizontal[index + 4] = sum4;
if (offsetX + 5 < regionWidth)
horizontal[index + 5] = sum5;
if (offsetX + 6 < regionWidth)
horizontal[index + 6] = sum6;
if (offsetX + 7 < regionWidth)
horizontal[index + 7] = sum7;
}
private float Weight(int offset)
=> offset >= -radius && offset <= radius ? weights[weightOffset + radius + offset] : 0f;
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct VerticalPassShader(
ReadWriteBuffer<Float4> horizontal,
ReadOnlyBuffer<float> weights,
ReadWriteBuffer<Float4> convolved,
int weightOffset,
int radius,
int rectX,
int rectY,
int rectWidth,
int rectHeight,
int canvasWidth,
int sourceY,
int sourceHeight,
bool accumulate) : IComputeShader
{
private readonly ReadWriteBuffer<Float4> horizontal = horizontal;
private readonly ReadOnlyBuffer<float> weights = weights;
private readonly ReadWriteBuffer<Float4> convolved = convolved;
private readonly int weightOffset = weightOffset;
private readonly int radius = radius;
private readonly int rectX = rectX;
private readonly int rectY = rectY;
private readonly int rectWidth = rectWidth;
private readonly int rectHeight = rectHeight;
private readonly int canvasWidth = canvasWidth;
private readonly int sourceY = sourceY;
private readonly int sourceHeight = sourceHeight;
private readonly bool accumulate = accumulate;
public void Execute()
{
var offsetY = ThreadIds.Y * WaveOpticsSettings.ConvolutionBlock;
if (ThreadIds.X >= rectWidth || offsetY >= rectHeight)
return;
var x = rectX + ThreadIds.X;
var y = rectY + offsetY;
var row = y - sourceY;
var first = Hlsl.Max(-radius, -row);
var last = Hlsl.Min(radius + WaveOpticsSettings.ConvolutionBlock - 1, sourceHeight - 1 - row);
var weight0 = Weight(first - 1);
var weight1 = Weight(first - 2);
var weight2 = Weight(first - 3);
var weight3 = Weight(first - 4);
var weight4 = Weight(first - 5);
var weight5 = Weight(first - 6);
var weight6 = Weight(first - 7);
var sum0 = new Float4(0f, 0f, 0f, 0f);
var sum1 = sum0;
var sum2 = sum0;
var sum3 = sum0;
var sum4 = sum0;
var sum5 = sum0;
var sum6 = sum0;
var sum7 = sum0;
for (var offset = first; offset <= last; offset++)
{
var weight7 = weight6;
weight6 = weight5;
weight5 = weight4;
weight4 = weight3;
weight3 = weight2;
weight2 = weight1;
weight1 = weight0;
weight0 = Weight(offset);
var value = horizontal[(y + offset) * canvasWidth + x];
sum0 += value * weight0;
sum1 += value * weight1;
sum2 += value * weight2;
sum3 += value * weight3;
sum4 += value * weight4;
sum5 += value * weight5;
sum6 += value * weight6;
sum7 += value * weight7;
}
var index = y * canvasWidth + x;
Store(index, sum0);
if (offsetY + 1 < rectHeight)
Store(index + canvasWidth, sum1);
if (offsetY + 2 < rectHeight)
Store(index + canvasWidth * 2, sum2);
if (offsetY + 3 < rectHeight)
Store(index + canvasWidth * 3, sum3);
if (offsetY + 4 < rectHeight)
Store(index + canvasWidth * 4, sum4);
if (offsetY + 5 < rectHeight)
Store(index + canvasWidth * 5, sum5);
if (offsetY + 6 < rectHeight)
Store(index + canvasWidth * 6, sum6);
if (offsetY + 7 < rectHeight)
Store(index + canvasWidth * 7, sum7);
}
private float Weight(int offset)
=> offset >= -radius && offset <= radius ? weights[weightOffset + radius + offset] : 0f;
private void Store(int index, Float4 sum)
{
convolved[index] = accumulate ? convolved[index] + sum : sum;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct RenderShader(
ReadWriteBuffer<Float4> convolved,
ReadWriteTexture2D<Bgra32, Float4> output,
int rectX,
int rectY,
int rectWidth,
int rectHeight,
int canvasWidth,
float gain) : IComputeShader
{
private readonly ReadWriteBuffer<Float4> convolved = convolved;
private readonly ReadWriteTexture2D<Bgra32, Float4> output = output;
private readonly int rectX = rectX;
private readonly int rectY = rectY;
private readonly int rectWidth = rectWidth;
private readonly int rectHeight = rectHeight;
private readonly int canvasWidth = canvasWidth;
private readonly float gain = gain;
public void Execute()
{
if (ThreadIds.X >= rectWidth || ThreadIds.Y >= rectHeight)
return;
output[ThreadIds.XY] = convolved[(rectY + ThreadIds.Y) * canvasWidth + rectX + ThreadIds.X] * gain;
}
}
+367
ファイルの表示
@@ -0,0 +1,367 @@
using System.ComponentModel;
using System.Runtime.InteropServices;
using ComputeWeave;
using WaveOptics.Abstractions;
using WaveOptics.Effects;
using WaveOptics.Optics;
namespace WaveOptics.Rendering;
internal sealed class WaveOpticsPipeline : IDisposable
{
private readonly GraphicsDevice _device;
private readonly WaveOpticsPipelineHost _host;
private readonly ReadWriteBuffer<int> _scratch;
private readonly ReadBackBuffer<int> _scratchReadBack;
private readonly ReadOnlyBuffer<float> _weights;
private readonly float[] _weightValues = new float[WaveOpticsSettings.WeightsLength];
private readonly FraunhoferPsfGenerator _generator = new();
private PsfParameters? _kernelPsf;
private Kernel _kernel;
private ConvolutionKey? _convolutionKey;
private int _cachedLitCount;
private int _cachedBoundsMinX;
private int _cachedBoundsMinY;
private int _cachedBoundsMaxX;
private int _cachedBoundsMaxY;
private int _canvasWidth;
private int _canvasHeight;
private ReadWriteTexture2D<Bgra32, Float4>? _packedSource;
private ReadWriteTexture2D<Bgra32, Float4>? _packedOutput;
private int _packedWidth;
private int _packedHeight;
private WaveOpticsPipeline(GraphicsDevice device, WaveOpticsPipelineHost host)
{
_device = device;
_host = host;
_scratch = device.AllocateReadWriteBuffer<int>(WaveOpticsSettings.ScratchLength);
_scratchReadBack = device.AllocateReadBackBuffer<int>(WaveOpticsSettings.ScratchLength);
_weights = device.AllocateReadOnlyBuffer<float>(WaveOpticsSettings.WeightsLength);
}
public static WaveOpticsPipeline? TryCreate()
{
try
{
return TryCreate(GraphicsDevice.GetDefault());
}
catch
{
return null;
}
}
public static WaveOpticsPipeline? TryCreate(GraphicsDevice device)
{
WaveOpticsPipelineHost? host = null;
try
{
host = WaveOpticsPipelineHost.Create(device, WaveOpticsSettings.MaximumPendingSubmissions);
var pipeline = new WaveOpticsPipeline(device, host);
host = null;
return pipeline;
}
catch (Win32Exception)
{
return null;
}
finally
{
host?.Dispose();
host?.WaitForDisposal();
}
}
internal void WaitForCompletion()
{
_device.For(1, new FillIntShader(_scratch, 0, 0));
}
public void Process(ReadOnlySpan<int> source, Span<int> destination, int width, int height, in Parameters parameters)
{
var pixelCount = checked(width * height);
EnsurePackedTextures(width, height);
var sourceTexture = _packedSource!;
var outputTexture = _packedOutput!;
sourceTexture.CopyFrom(MemoryMarshal.Cast<int, Bgra32>(source[..pixelCount]));
SubmitFullPipeline(sourceTexture, outputTexture, width, height, in parameters).Wait();
outputTexture.CopyTo(MemoryMarshal.Cast<int, Bgra32>(destination[..pixelCount]));
}
public void Process(
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> destination,
int width,
int height,
in Parameters parameters)
{
_ = SubmitFullPipeline(source, destination, width, height, in parameters);
}
internal void ProcessSharedAndWait(
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> destination,
int width,
int height,
in Parameters parameters)
{
SubmitFullPipeline(source, destination, width, height, in parameters).Wait();
}
internal bool Simulate(
ReadWriteTexture2D<Bgra32, Float4> source,
int canvasWidth,
int canvasHeight,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
in Parameters parameters)
{
var sourceRect = BeginSimulate(canvasWidth, canvasHeight, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight);
_host.RecordSourceHash(source, _scratch, in sourceRect).Wait();
if (!TryBeginConvolution(in sourceRect, in parameters, out var rect))
return false;
_host.RecordConvolution(source, _weights, in sourceRect, in rect, _canvasWidth, in _kernel).Wait();
return true;
}
internal bool Simulate(
ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> source,
int canvasWidth,
int canvasHeight,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
in Parameters parameters)
{
var sourceRect = BeginSimulate(canvasWidth, canvasHeight, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight);
_host.RecordSharedSourceHash(source, _scratch, in sourceRect).Wait();
if (!TryBeginConvolution(in sourceRect, in parameters, out var rect))
return false;
_host.RecordSharedConvolution(source, _weights, in sourceRect, in rect, _canvasWidth, in _kernel).Wait();
return true;
}
private PixelRect BeginSimulate(int canvasWidth, int canvasHeight, int sourceOffsetX, int sourceOffsetY, int sourceWidth, int sourceHeight)
{
EnsureCanvas(canvasWidth, canvasHeight);
return new PixelRect(sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight);
}
private bool TryBeginConvolution(in PixelRect sourceRect, in Parameters parameters, out PixelRect rect)
{
_scratchReadBack.CopyFrom(_scratch);
var hashed = _scratchReadBack.Span;
_cachedLitCount = hashed[WaveOpticsSettings.ScratchLitCount];
_cachedBoundsMinX = hashed[WaveOpticsSettings.ScratchBoundsMinX];
_cachedBoundsMinY = hashed[WaveOpticsSettings.ScratchBoundsMinY];
_cachedBoundsMaxX = hashed[WaveOpticsSettings.ScratchBoundsMaxX];
_cachedBoundsMaxY = hashed[WaveOpticsSettings.ScratchBoundsMaxY];
var key = new ConvolutionKey(
hashed[WaveOpticsSettings.ScratchHashSum],
hashed[WaveOpticsSettings.ScratchHashMix],
_canvasWidth,
_canvasHeight,
sourceRect,
parameters.Psf);
if (_convolutionKey == key || !TryGetVisibleBounds(_canvasWidth, _canvasHeight, in parameters, out rect))
{
rect = default;
return false;
}
if (!TryEnsureKernel(parameters.Psf))
{
_convolutionKey = null;
rect = default;
return false;
}
_convolutionKey = key;
return true;
}
internal bool HasKernel => _kernel.Rank > 0;
internal bool TryGetVisibleBounds(int canvasWidth, int canvasHeight, in Parameters parameters, out PixelRect rect)
{
rect = default;
if (_cachedLitCount <= 0 || _cachedBoundsMinX > _cachedBoundsMaxX)
return false;
var radius = parameters.Psf.KernelRadius;
var left = Math.Clamp((_cachedBoundsMinX - radius) & ~3, 0, canvasWidth);
var top = Math.Clamp((_cachedBoundsMinY - radius) & ~3, 0, canvasHeight);
var right = Math.Clamp(_cachedBoundsMaxX + 1 + radius, 0, canvasWidth);
var bottom = Math.Clamp(_cachedBoundsMaxY + 1 + radius, 0, canvasHeight);
var width = Math.Min((right - left + 3) & ~3, canvasWidth - left);
var height = Math.Min((bottom - top + 3) & ~3, canvasHeight - top);
if (width <= 0 || height <= 0)
return false;
rect = new PixelRect(left, top, width, height);
return true;
}
internal void RenderVisible(ReadWriteTexture2D<Bgra32, Float4> output, PixelRect rect, in Parameters parameters)
{
_host.RecordRender(output, in rect, _canvasWidth, parameters.Gain).Wait();
}
internal void RenderVisible(ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> output, PixelRect rect, in Parameters parameters)
{
_host.RecordSharedRender(output, in rect, _canvasWidth, parameters.Gain).Wait();
}
private ComputeSubmission SubmitFullPipeline(
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> output,
int width,
int height,
in Parameters parameters)
{
EnsureCanvas(width, height);
if (!TryEnsureKernel(parameters.Psf))
throw new InvalidOperationException();
_convolutionKey = null;
var sourceRect = new PixelRect(0, 0, width, height);
return _host.RecordFullPipeline(source, output, _weights, in sourceRect, in _kernel, parameters.Gain);
}
private bool TryEnsureKernel(in PsfParameters psf)
{
if (_kernelPsf == psf)
return HasKernel;
var pupilGridSize = WaveOpticsSettings.GetPupilGridSize(psf.Quality);
var aberration = new WavefrontAberration(
defocusWaves: psf.Defocus,
astigmatismVerticalWaves: psf.AstigmatismVertical,
astigmatismObliqueWaves: psf.AstigmatismOblique,
comaHorizontalWaves: psf.ComaHorizontal,
comaVerticalWaves: psf.ComaVertical,
sphericalWaves: psf.Spherical);
var descriptor = new PsfDescriptor(
pupilGridSize,
WaveOpticsSettings.GetPupilDiameterSamples(pupilGridSize),
WaveOpticsSettings.GetKernelSize(psf.KernelRadius),
psf.Wavelength,
psf.FNumber,
psf.PixelPitch,
psf.ApertureShape == WaveOpticsApertureShape.Circular ? ApertureShape.Circular : ApertureShape.RegularPolygon,
psf.BladeCount,
psf.BladeRotation,
psf.Obstruction,
aberration);
if (!_generator.TryGenerate(descriptor, out var result))
{
_kernel = default;
_kernelPsf = psf;
return false;
}
var separable = SeparableKernel.Decompose(result.Kernel.Values.Span, result.Kernel.Size, WaveOpticsSettings.SeparableResidualRatio, WaveOpticsSettings.MaximumRank);
var size = separable.Size;
var scale = 1d / separable.Sum;
for (var term = 0; term < separable.Rank; term++)
{
separable.Horizontal.AsSpan(term * size, size).CopyTo(_weightValues.AsSpan(WaveOpticsSettings.GetWeightOffset(term, 0)));
var verticalOffset = WaveOpticsSettings.GetWeightOffset(term, 1);
for (var k = 0; k < size; k++)
_weightValues[verticalOffset + k] = (float)(separable.Vertical[term * size + k] * scale);
}
_weights.CopyFrom(_weightValues);
_kernel = new Kernel(separable.Rank, size / 2);
_kernelPsf = psf;
return true;
}
private void EnsureCanvas(int canvasWidth, int canvasHeight)
{
if (_canvasWidth == canvasWidth && _canvasHeight == canvasHeight)
return;
var canvasLength = canvasWidth * canvasHeight;
if (!_host.TryEnsureCanvas(new WaveOpticsCanvasResources.Plan(canvasLength, canvasLength), out _))
throw new InvalidOperationException();
_cachedLitCount = 0;
_cachedBoundsMinX = int.MaxValue;
_cachedBoundsMinY = int.MaxValue;
_cachedBoundsMaxX = int.MinValue;
_cachedBoundsMaxY = int.MinValue;
_convolutionKey = null;
_canvasWidth = canvasWidth;
_canvasHeight = canvasHeight;
}
private void EnsurePackedTextures(int width, int height)
{
if (_packedWidth == width && _packedHeight == height)
return;
_packedSource?.Dispose();
_packedOutput?.Dispose();
_packedSource = _device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
_packedOutput = _device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
_packedWidth = width;
_packedHeight = height;
}
public void Dispose()
{
_host.Dispose();
_host.WaitForDisposal();
_packedSource?.Dispose();
_packedOutput?.Dispose();
_packedSource = null;
_packedOutput = null;
_packedWidth = 0;
_packedHeight = 0;
_kernelPsf = null;
_convolutionKey = null;
_canvasWidth = 0;
_canvasHeight = 0;
_weights.Dispose();
_scratchReadBack.Dispose();
_scratch.Dispose();
}
internal readonly record struct PixelRect(int X, int Y, int Width, int Height);
internal readonly record struct Kernel(int Rank, int Radius);
private readonly record struct ConvolutionKey(
int HashSum,
int HashMix,
int CanvasWidth,
int CanvasHeight,
PixelRect Source,
PsfParameters Psf);
internal readonly record struct PsfParameters(
WaveOpticsQuality Quality,
int KernelRadius,
float Wavelength,
float FNumber,
float PixelPitch,
WaveOpticsApertureShape ApertureShape,
int BladeCount,
float BladeRotation,
float Obstruction,
float Defocus,
float AstigmatismVertical,
float AstigmatismOblique,
float ComaHorizontal,
float ComaVertical,
float Spherical);
internal readonly record struct Parameters(float Gain, PsfParameters Psf);
}
+184
ファイルの表示
@@ -0,0 +1,184 @@
using ComputeWeave;
namespace WaveOptics.Rendering;
[ComputeResourceGroup]
internal sealed partial class WaveOpticsCanvasResources
{
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<Float4> Horizontal { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<Float4> Convolved { get; }
}
[ComputePipelineHost("_device", 1)]
internal sealed partial class WaveOpticsPipelineHost
{
private readonly GraphicsDevice _device;
[ComputePipelineResource(ComputeResourceAccess.ReadWrite, ComputeResourceRecovery.Recompute)]
private readonly ComputeResourceGroupSlot<WaveOpticsCanvasResources> _canvas = new();
[ComputePipeline]
private void RecordFullPipeline(
in ComputeContext context,
[ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> output,
[ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer<float> weights,
in WaveOpticsPipeline.PixelRect sourceRect,
in WaveOpticsPipeline.Kernel kernel,
float gain)
{
_ = _device;
RecordConvolutionStage(in context, canvas, source, weights, in sourceRect, in sourceRect, sourceRect.Width, in kernel);
RecordRenderStage(in context, canvas, output, in sourceRect, sourceRect.Width, gain);
}
[ComputePipeline]
private void RecordSourceHash(
in ComputeContext context,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
in WaveOpticsPipeline.PixelRect sourceRect)
{
_ = _device;
RecordSourceHashStage(in context, source, scratch, in sourceRect);
}
[ComputePipeline]
[ComputeInterop]
private void RecordSharedSourceHash(
in ComputeContext context,
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
in WaveOpticsPipeline.PixelRect sourceRect)
{
_ = _device;
RecordSourceHashStage(in context, source, scratch, in sourceRect);
}
[ComputePipeline]
private void RecordConvolution(
in ComputeContext context,
[ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer<float> weights,
in WaveOpticsPipeline.PixelRect sourceRect,
in WaveOpticsPipeline.PixelRect rect,
int canvasWidth,
in WaveOpticsPipeline.Kernel kernel)
{
_ = _device;
RecordConvolutionStage(in context, canvas, source, weights, in sourceRect, in rect, canvasWidth, in kernel);
}
[ComputePipeline]
[ComputeInterop]
private void RecordSharedConvolution(
in ComputeContext context,
[ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas,
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer<float> weights,
in WaveOpticsPipeline.PixelRect sourceRect,
in WaveOpticsPipeline.PixelRect rect,
int canvasWidth,
in WaveOpticsPipeline.Kernel kernel)
{
_ = _device;
RecordConvolutionStage(in context, canvas, source, weights, in sourceRect, in rect, canvasWidth, in kernel);
}
[ComputePipeline]
private void RecordRender(
in ComputeContext context,
[ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> output,
in WaveOpticsPipeline.PixelRect rect,
int canvasWidth,
float gain)
{
_ = _device;
RecordRenderStage(in context, canvas, output, in rect, canvasWidth, gain);
}
[ComputePipeline]
[ComputeInterop]
private void RecordSharedRender(
in ComputeContext context,
[ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas,
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> output,
in WaveOpticsPipeline.PixelRect rect,
int canvasWidth,
float gain)
{
_ = _device;
RecordRenderStage(in context, canvas, output, in rect, canvasWidth, gain);
}
private static void RecordSourceHashStage(
in ComputeContext context,
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteBuffer<int> scratch,
in WaveOpticsPipeline.PixelRect sourceRect)
{
context.For(1, new SourceHashResetShader(scratch));
context.Barrier(scratch);
context.For(sourceRect.Width, sourceRect.Height, new SourceHashShader(
source, scratch, sourceRect.X, sourceRect.Y, sourceRect.Width, sourceRect.Height));
context.Barrier(scratch);
}
private static void RecordConvolutionStage(
in ComputeContext context,
WaveOpticsCanvasResources canvas,
ReadWriteTexture2D<Bgra32, Float4> source,
ReadOnlyBuffer<float> weights,
in WaveOpticsPipeline.PixelRect sourceRect,
in WaveOpticsPipeline.PixelRect rect,
int canvasWidth,
in WaveOpticsPipeline.Kernel kernel)
{
var top = Math.Max(rect.Y - kernel.Radius, sourceRect.Y);
var bottom = Math.Min(rect.Y + rect.Height + kernel.Radius, sourceRect.Y + sourceRect.Height);
for (var term = 0; term < kernel.Rank; term++)
{
context.For(GetBlockCount(rect.Width), bottom - top, new HorizontalPassShader(
source, weights, canvas.Horizontal,
WaveOpticsSettings.GetWeightOffset(term, 0), kernel.Radius,
rect.X, top, rect.Width, bottom - top, canvasWidth,
sourceRect.X, sourceRect.Y, sourceRect.Width));
context.Barrier(canvas.Horizontal);
context.For(rect.Width, GetBlockCount(rect.Height), new VerticalPassShader(
canvas.Horizontal, weights, canvas.Convolved,
WaveOpticsSettings.GetWeightOffset(term, 1), kernel.Radius,
rect.X, rect.Y, rect.Width, rect.Height, canvasWidth,
sourceRect.Y, sourceRect.Height, term > 0));
context.Barrier(canvas.Horizontal);
context.Barrier(canvas.Convolved);
}
}
private static int GetBlockCount(int length)
=> (length + WaveOpticsSettings.ConvolutionBlock - 1) / WaveOpticsSettings.ConvolutionBlock;
private static void RecordRenderStage(
in ComputeContext context,
WaveOpticsCanvasResources canvas,
ReadWriteTexture2D<Bgra32, Float4> output,
in WaveOpticsPipeline.PixelRect rect,
int canvasWidth,
float gain)
{
context.For(rect.Width, rect.Height, new RenderShader(
canvas.Convolved, output, rect.X, rect.Y, rect.Width, rect.Height, canvasWidth, gain));
}
}
+22 -20
ファイルの表示
@@ -7,32 +7,18 @@
<Nullable>enable</Nullable>
<AssemblyName>WaveOptics</AssemblyName>
<RootNamespace>WaveOptics</RootNamespace>
<Version>1.0.0</Version>
<Version>2.0.0</Version>
<Platforms>AnyCPU;x64</Platforms>
<PlatformTarget>x64</PlatformTarget>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<ShaderDirPath>..\Release\</ShaderDirPath>
</PropertyGroup>
<ItemGroup>
<HlslShader Include="Shaders\**\*.hlsl" />
<Resource Include="@(HlslShader->'%(RelativeDir)%(Filename).cso')" />
<Resource Include="$(ShaderDirPath)WaveOptics.cso" Link="Resources\Shader\WaveOptics.cso" />
</ItemGroup>
<ItemDefinitionGroup>
<HlslShader>
<ShaderType>ps_5_0</ShaderType>
<EntryPoint>main</EntryPoint>
<ObjectFileOutput>%(RelativeDir)%(Filename).cso</ObjectFileOutput>
</HlslShader>
</ItemDefinitionGroup>
<Target Name="CompileHLSLShaders" BeforeTargets="BeforeBuild" Inputs="@(HlslShader)" Outputs="@(HlslShader->'%(ObjectFileOutput)')">
<Message Text="Compiling HLSL Shader: %(HlslShader.Identity) [Type: %(HlslShader.ShaderType), Entry: %(HlslShader.EntryPoint)]" Importance="high" />
<Error Text="fxc.exe not found at path: $(FxcPath)" Condition="!Exists('$(FxcPath)') AND '$(FxcPath)' != 'fxc.exe'" />
<Exec Command="&quot;$(FxcPath)&quot; /nologo /T %(HlslShader.ShaderType) /E %(HlslShader.EntryPoint) /Fo &quot;%(HlslShader.ObjectFileOutput)&quot; &quot;%(HlslShader.FullPath)&quot;" Condition="Exists('%(HlslShader.FullPath)')" />
</Target>
<ItemGroup>
<Reference Include="SharpGen.Runtime">
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
@@ -81,12 +67,20 @@
</ItemGroup>
<ItemGroup>
<Compile Include="..\YMM4-GitHubUpdateNotifier\GitHubUpdateNotifier\*.cs" LinkBase="GitHubUpdateNotifier" />
</ItemGroup>
<Import Project="..\YMM4-Telemetry\Telemetry.props" />
<ItemGroup>
<PackageReference Include="ComputeWeave" Version="2.6.0" />
<PackageReference Include="ILRepack" Version="2.0.48" PrivateAssets="all" ExcludeAssets="all" GeneratePathProperty="true" />
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.142" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WaveOptics.Abstractions\WaveOptics.Abstractions.csproj" />
<ProjectReference Include="..\YukkuriMovieMaker.Generator\YukkuriMovieMaker.Generator\YukkuriMovieMaker.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<ProjectReference Include="..\YukkuriMovieMaker.Generator\YukkuriMovieMaker.Generator\YukkuriMovieMaker.Generator.csproj" SetConfiguration="Configuration=$(Configuration)" SetPlatform="Platform=AnyCPU" GlobalPropertiesToRemove="SkipPluginDeploy" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<AdditionalFiles Include="**\*.csv" />
</ItemGroup>
@@ -94,10 +88,18 @@
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
<_Parameter1>WaveOptics.Tests</_Parameter1>
</AssemblyAttribute>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
<_Parameter1>WaveOptics.Harness</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(SkipPluginDeploy)' != 'true'">
<Exec Command="mkdir &quot;$(YMM4DirPath)user\plugin\$(ProjectName)&quot; &gt; NUL 2&gt;&amp;1&#xD;&#xA;copy &quot;$(TargetPath)&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;&#xD;&#xA;copy &quot;$(TargetDir)WaveOptics.Abstractions.dll&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;" />
<Target Name="MergePluginAssembly" AfterTargets="PostBuildEvent" Inputs="$(TargetPath);$(TargetDir)ComputeWeave.dll;$(TargetDir)ComputeWeave.Core.dll" Outputs="$(TargetDir)plugin\$(TargetFileName)">
<MakeDir Directories="$(TargetDir)plugin" />
<Exec Command="&quot;$(PkgILRepack)\tools\ILRepack.exe&quot; /out:&quot;$(TargetDir)plugin\$(TargetFileName)&quot; /lib:&quot;$([System.IO.Path]::GetDirectoryName('$(TargetPath)'))&quot; /lib:&quot;$([System.IO.Path]::GetDirectoryName('$(YMM4DirPath)'))&quot; /internalize &quot;$(TargetPath)&quot; &quot;$(TargetDir)ComputeWeave.dll&quot; &quot;$(TargetDir)ComputeWeave.Core.dll&quot;" />
</Target>
<Target Name="PostBuild" AfterTargets="MergePluginAssembly" Condition="'$(SkipPluginDeploy)' != 'true' AND '$(BuildingSolutionFile)' != 'true'">
<Exec Command="mkdir &quot;$(YMM4DirPath)user\plugin\$(ProjectName)&quot; &gt; NUL 2&gt;&amp;1&#xD;&#xA;copy &quot;$(TargetDir)WaveOptics.Abstractions.dll&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot; &amp;&amp; copy &quot;$(TargetDir)plugin\$(TargetFileName)&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;" />
</Target>
</Project>
ファイルの表示
差分なしでファイル名を変更。
+39
ファイルの表示
@@ -0,0 +1,39 @@
using WaveOptics.Effects;
namespace WaveOptics;
internal static class WaveOpticsSettings
{
public const int MinimumKernelRadius = 1;
public const int MaximumKernelRadius = 15;
public const int MaximumKernelSize = MaximumKernelRadius * 2 + 1;
public const int MaximumRank = MaximumKernelSize;
public const double SeparableResidualRatio = 1e-4;
public const int WeightsLength = MaximumRank * 2 * MaximumKernelSize;
public const int ConvolutionBlock = 8;
public const int CanvasMargin = (MaximumKernelRadius + 3) & ~3;
public const int MaximumCanvasSize = 8192;
public const int ScratchLength = 7;
public const int ScratchLitCount = 0;
public const int ScratchBoundsMinX = 1;
public const int ScratchBoundsMinY = 2;
public const int ScratchBoundsMaxX = 3;
public const int ScratchBoundsMaxY = 4;
public const int ScratchHashSum = 5;
public const int ScratchHashMix = 6;
public const int MaximumPendingSubmissions = 32;
public static int GetPupilGridSize(WaveOpticsQuality quality)
=> quality switch
{
WaveOpticsQuality.Draft => 128,
WaveOpticsQuality.High => 512,
_ => 256,
};
public static int GetPupilDiameterSamples(int pupilGridSize) => pupilGridSize / 4;
public static int GetKernelSize(int kernelRadius) => kernelRadius * 2 + 1;
public static int GetWeightOffset(int term, int axis) => (term * 2 + axis) * MaximumKernelSize;
}
+102
ファイルの表示
@@ -0,0 +1,102 @@
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using System.Windows.Threading;
using Telemetry;
namespace WaveOptics;
internal static class WaveOpticsTelemetry
{
private const int MaxChainLength = 5;
private const int MaxFrames = 100;
private static readonly Assembly Own = typeof(WaveOpticsTelemetry).Assembly;
private static int _started;
public static void EnsureStartedOnce()
{
var application = Application.Current;
if (application is null || Interlocked.Exchange(ref _started, 1) != 0)
return;
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
application.DispatcherUnhandledException += OnDispatcherUnhandledException;
TelemetryReporter.Start();
}
public static void Report(Exception exception)
{
if (Volatile.Read(ref _started) != 0)
TelemetryReporter.Report(exception);
}
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
=> ReportOwn(e.ExceptionObject as Exception);
private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
=> ReportOwn(e.Exception);
private static void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
=> ReportOwn(e.Exception);
private static void ReportOwn(Exception? exception)
{
if (exception is not null && IsOwn(exception))
TelemetryReporter.Report(exception);
}
private static bool IsOwn(Exception exception)
{
var current = exception;
for (var depth = 0; current is not null && depth < MaxChainLength; depth++)
{
if (HasOwnFrame(current))
return true;
current = current is AggregateException aggregate && aggregate.InnerExceptions.Count > 0
? aggregate.InnerExceptions[0]
: current.InnerException;
}
return false;
}
private static bool HasOwnFrame(Exception exception)
{
StackFrame[]? frames;
try
{
frames = new StackTrace(exception, false).GetFrames();
}
catch (Exception)
{
return false;
}
if (frames is null)
return false;
for (var index = 0; index < Math.Min(frames.Length, MaxFrames); index++)
{
MethodBase? method;
try
{
method = frames[index].GetMethod();
}
catch (Exception)
{
continue;
}
if (method?.DeclaringType is { } declaringType && ReferenceEquals(declaringType.Assembly, Own))
return true;
}
return false;
}
}
+53
ファイルの表示
@@ -0,0 +1,53 @@
using System.Windows;
using GitHubUpdateNotifier;
using WaveOptics.Effects;
using YukkuriMovieMaker.Plugin.Update;
using Notifier = GitHubUpdateNotifier.GitHubUpdateNotifier;
namespace WaveOptics;
internal static class WaveOpticsUpdateNotifier
{
private const string Owner = "routersys";
private const string Repository = "YMM4-WaveOptics";
private static int _started;
public static void EnsureCheckedOnce()
{
if (Application.Current is null || Interlocked.Exchange(ref _started, 1) != 0)
return;
_ = RunAsync();
}
private static async Task RunAsync()
{
try
{
var options = new UpdateNotifierOptions
{
CurrentVersion = PluginVersion.FromAssemblyInformationalVersion(typeof(WaveOpticsUpdateNotifier)),
IncludePrerelease = false,
MessageFormatter = FormatMessage,
NotificationHandler = ShowNotificationAsync,
};
await new Notifier(Owner, Repository, options).NotifyAsync().ConfigureAwait(false);
}
catch (Exception exception)
{
if (exception is not UpdateCheckException)
WaveOpticsTelemetry.Report(exception);
}
}
private static string FormatMessage(UpdateInfo update)
=> string.Format(Texts.UpdateAvailableMessage, update.TagName) + Environment.NewLine + update.ReleaseUrl;
private static Task ShowNotificationAsync(UpdateNotification notification, CancellationToken cancellationToken)
{
var application = Application.Current;
if (application is null)
return Task.CompletedTask;
return application.Dispatcher.InvokeAsync(() =>
MessageBox.Show(notification.Message, Texts.WaveOptics, MessageBoxButton.OK, MessageBoxImage.Information)).Task;
}
}
サブモジュール
+1
サブモジュール YMM4-GitHubUpdateNotifier が ca66e0f21d で追加されました。
サブモジュール
+1
サブモジュール YMM4-Telemetry が 04010903ca で追加されました。
+5
ファイルの表示
@@ -0,0 +1,5 @@
{
"test": {
"runner": "Microsoft.Testing.Platform"
}
}