49 コミット
作成者 SHA1 メッセージ 日付
routersys 03f63e5266 gitmodulesの先頭のBOMを取り除く
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.2.0 のコミットから作成しました
・GitHubが認識できなかったサブモジュール定義を修正-F
2026-09-21 16:26:39 +09:00
routersys abcf0c3a2b バージョンをv1.2.0へ更新する 2026-09-21 16:23:09 +09:00
routersys cb449bcae8 リリースノートへ分類の内訳節を加える 2026-09-21 16:10:20 +09:00
routersys df53e08a85 vcxprojファイルへBOMを付ける 2026-09-21 15:44:21 +09:00
routersys c78c5315fe 使われなくなったFxcPathの設定を取り除く 2026-09-21 15:35:21 +09:00
routersys 12d56819b9 ハーネスへ構造再計算の内訳計測を統合する 2026-09-21 15:31:53 +09:00
routersys 6afdd5e63c ハーネスを実機描画によるゴールデン検証基盤にする 2026-09-21 14:56:30 +09:00
routersys 9eee3f6da0 リリースワークフローを既存群と同一の構成にする 2026-09-21 14:35:05 +09:00
routersys 1f64a28b5c Plugin_Readmeの見出しを実際の版へ合わせる
・同梱するReadme.txtの版表記が古いままだった不具合を修正-F
2026-09-21 14:34:20 +09:00
routersys 8728ad1a7b ルートファイルをSolution Itemsへ加える 2026-09-21 14:32:22 +09:00
routersys 92134d27d6 シェーダーの生成をUkiyoe.Shaderへ切り出す 2026-09-21 14:31:35 +09:00
routersys 7c5f566a8b READMEへ不具合の報告を追記する 2026-09-21 14:09:38 +09:00
routersys 4a743b3dc5 更新確認で例外を握り潰さず報告する 2026-09-21 14:09:37 +09:00
routersys 2f8e39c12f 更新確認をWPF起動中に限り行う 2026-09-21 14:08:49 +09:00
routersys 93f15d5839 ホストとDirect2Dからの呼び出し口で例外を報告する
・想定していない例外を開発者へ自動で報告する機能を追加-A
2026-09-21 13:29:07 +09:00
routersys ef5690c3e1 UkiyoeTelemetryを追加する 2026-09-21 13:27:25 +09:00
routersys 29d3e161bb Telemetryをコンパイルに含める 2026-09-21 13:25:44 +09:00
routersys ee96c42dcb YMM4-Telemetryサブモジュールを追加する 2026-09-21 13:24:41 +09:00
routersys ad7d9df207 影の寸法フィールドを資源集合へ委ねる 2026-09-01 15:06:19 +09:00
routersys 7ffb9eaad3 ComputeWeaveを2.3.0へ更新する 2026-09-01 14:24:27 +09:00
routersys 676125b2cb ComputeWeaveを1.8.1へ更新する 2026-08-18 13:41:22 +09:00
routersys 1216404915 Device解決を本体提供のAPIへ替える 2026-08-18 12:15:31 +09:00
routersys be17ba63f1 ComputeWeaveを1.8.0へ更新する 2026-08-18 12:15:31 +09:00
routersys c2e15973b3 ComputeWeaveを1.7.2へ更新する 2026-08-17 23:11:19 +09:00
routersys ee33262486 ComputeWeaveを1.7.1へ更新する 2026-08-17 21:47:31 +09:00
routersys bdd3c2a589 包み方の変更に伴い検証を更新する 2026-08-17 21:15:38 +09:00
routersys 9669a70c26 外部Viewの所有取得でビットマップを包む 2026-08-17 21:15:38 +09:00
routersys f53e354a7e 外部Viewの移行に伴い検証を更新する 2026-08-17 19:54:00 +09:00
routersys 4c348529b6 相互運用Providerを本体提供の基底へ移す 2026-08-17 19:54:00 +09:00
routersys 35ecb2f1ce 構造再計算の内訳を交互測定する 2026-08-17 16:47:43 +09:00
routersys ddb7ebce0c 部分再計算が全再計算と一致することを検証する 2026-08-17 16:47:43 +09:00
routersys 5f410df284 構造の再計算を部分グラフ単位へ分ける 2026-08-17 16:47:35 +09:00
routersys bceb744fee 外部キューSchedulerを本体提供のものへ替える 2026-08-17 15:44:55 +09:00
routersys d222463ca6 ComputeWeaveを1.5.0へ更新する 2026-08-17 15:44:47 +09:00
routersys 736fdf2d42 バージョンをv1.1.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.1.1 のコミットから作成しました
2026-08-11 19:03:00 +09:00
routersys b07d5b8937 ComputeWeaveを1.4.1へ更新する 2026-08-11 18:58:26 +09:00
routersys bfc35b3931 Full HD出力置換直後の描画を検証する 2026-08-11 13:26:16 +09:00
routersys a2531d96e8 出力貸与の確保寸法を再利用判定に使う 2026-08-10 19:03:54 +09:00
routersys 4f54851fc5 ComputeWeaveを配布DLLへ統合し衝突を防ぐ
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.1.0 のコミットから作成しました
2026-08-02 20:47:01 +09:00
routersys fcb5c87637 ComputeWeaveを1.1.4へ更新する 2026-08-02 17:16:36 +09:00
routersys 82ae3e3acd 相互運用を外部提供者と共有テクスチャ集合へ移す 2026-08-02 17:06:01 +09:00
routersys b9e57ffd66 グリッドの資源を生成ホストの所有スロットへ移す 2026-08-02 16:48:38 +09:00
routersys c7415baf1b ComputeWeaveを1.1.3へ更新する 2026-08-02 16:48:38 +09:00
routersys c85592277e ComputeSharpサブモジュールの登録を外す 2026-08-02 13:06:45 +09:00
routersys 0d8e5124a0 ComputeWeaveをNuGet参照へ移行する 2026-08-02 13:06:21 +09:00
routersys 086557db7f ComputeSharpをComputeWeaveへ置き換える 2026-08-02 12:43:13 +09:00
routersys c69f796293 バージョンをv1.0.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.0.1 のコミットから作成しました
2026-07-19 19:04:46 +09:00
routersys 1df66b5c28 ハーネスの測定を最小値方式へ変更 2026-07-19 19:03:24 +09:00
routersys 77fca5223a 平坦化反復をグループ共有メモリのタイル化で高速化 2026-07-19 15:22:52 +09:00
43個のファイルの変更、2834行の追加、1132行の削除

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

-195
ファイルの表示
@@ -1,195 +0,0 @@
# v1.0.0 - 浮世絵 for YMM4
YukkuriMovieMaker4向けの浮世絵エフェクトプラグインの初回リリースです。
素材を多色木版画の原画とみなし、Kang・Lee・Chuiの「Coherent Line Drawing」(NPAR 2007)のエッジ接線流と流れに沿った差分ガウスで輪郭主線を求め、Bi・Han・Yuの「An L1 Image Transform for Edge-Preserving Smoothing and Scene-Level Intrinsic Decomposition」(SIGGRAPH 2015)のL1局所平坦化で地色を均し、Winnemöllerらの「Real-Time Video Abstraction」(SIGGRAPH 2006)の軟量子化で限定パレットへ寄せ、和紙の繊維とばれん目と版ずれを重ねて刷り上げます。
和紙の繊維とばれん目と版ずれの形はシードから決定論的に決まり、同じ設定では常に同じ絵になります。
計算はComputeSharpの計算シェーダーがDirect3D 12で実行し、YMM4のDirect3D 11側とは共有テクスチャおよび共有フェンスで接続します。
8言語のリソース構成のUIを備えます。
---
## 新機能
### 1. 浮世絵の計算パイプライン
`UkiyoePipeline`は、シルエット、構造、描画の3段階の計算シェーダーを`ComputeContext`へ記録して実行します。処理格子のバッファーは計算領域の大きさと品質に応じて確保し、サイズが変わらないフレームでは再利用します。処理の流れは次のとおりです。
1. `SilhouetteShader`が、各格子セルに対応する画素の色とアルファ値の平均を調べ、直色と白地の輝度を記録します。
2. `GradientShader`が、輝度のソーベル勾配から接線場の初期値と勾配強度を求めます。
3. `EtfShader`が、エッジ接線流の非線形ベクトル平滑化を反復します。
4. `FlattenShader`が、L1局所平坦化の反復重み付き最小二乗を反復し、色面を均します。
5. `DogShader`と`FlowAccumulateShader`が、勾配方向の1次元差分ガウスと流線方向の集計で主線の応答を求め、`SuperimposeShader`が黒画素を重ねて反復します。
6. `RenderShader`が、画素ごとに平坦化色を軟量子化し、版ずれ、ばれん目、和紙の繊維、主線を合成して出力します。
| シェーダー | 役割 |
|---|---|
| `SilhouetteShader` | 画素の色とアルファ値から直色と輝度を求める |
| `MaskHashShader` | 素材のハッシュと境界を集計する |
| `GradientShader` | ソーベル勾配と接線場の初期値を求める |
| `EtfShader` | エッジ接線流を平滑化する |
| `FlattenShader` | L1平坦化の1反復を解く |
| `CopyColorShader` | 平坦化の反復初期値を用意する |
| `DogShader` | 勾配方向の差分ガウスを求める |
| `FlowAccumulateShader` | 流線に沿って応答を集計する |
| `SuperimposeShader` | 主線を輝度へ重ねて反復する |
| `RenderShader` | 版画を描画する |
### 2. エッジ接線流と流れに沿った差分ガウス
輪郭主線は、Kang・Lee・Chuiの論文「Coherent Line Drawing」(NPAR 2007)に基づきます。
- エッジ接線流は、論文の式1〜5の核関数に基づく非線形ベクトル平滑化です。空間重みは半径5セルの円盤、強度重みは`(1 + tanh(ĝ(y) − ĝ(x))) / 2`、方向重みは`|t(x)・t(y)|`で、逆向きの接線は符号を反転してから加えます。勾配強度が最大値の2%を下回るセルは方向なしとして扱い、近傍の有意な接線の構造テンソルの主固有ベクトルで充填します。この充填により、素材の内部に境界と直交する緩い勾配があっても、シルエット境界の1〜2セル内側の接線が境界へ沿い、輪郭主線が途切れません。
- 差分ガウスは論文の式6〜9を2パスへ分離して求めます。第1パスは各セルの勾配方向へ1次元の`G_σc − 0.99・G_σs`(`σs = 1.6σc`)を畳み込み、第2パスは接線流の流線を両方向へ`⌈2σm⌉`ステップ辿り、`G_σm`の重みで応答を集計します。この分離は流線上の各点の応答を再利用する近似で、Kyprianidisらが実時間実装で用いた構成です。
- 二値化は式10の`1 + tanh(gain・H) < τ`で行い、描画では同じ式の連続値を幅0.1の軟しきい値として使い、主線の縁を滑らかにします。
- 論文3.2節の反復適用を行い、前回の主線の黒画素を輝度へ重ねてから再度差分ガウスを適用します。エッジ接線流は反復中に更新しません。
線の太さは中心ガウスの幅`σc`を0.6〜3.0画素、線の流れは流線ガウスの幅`σm`を1〜6セル、線の量はしきい値`τ`を0.1〜0.95へ割り当てます。
### 3. L1局所平坦化による地色の色面
地色は、Bi・Han・Yuの論文「An L1 Image Transform for Edge-Preserving Smoothing and Scene-Level Intrinsic Decomposition」(SIGGRAPH 2015)の局所平坦化項(式2)と画像近似項(式7)のエネルギーを最小化して均します。親和度は平滑化用の式9に従い、輝度を0.3倍へ抑えた色特徴の距離と、隣接セルの勾配の最大値の`η = 0.4`倍の大きいほうを使います。大域疎性項は論文の平滑化の節の記述どおり使用しません。
論文のSplit-Bregman法による大域の疎行列解法の代わりに、L1項を反復重み付き最小二乗として前向きに解きます。各反復は、近傍24セルについて重み`w_ij / max(|x_i − x_j|_1, ε)`を現在の反復値から求め、`x_i = (β・in_i + Σ w・x_j) / (β + Σ w)`のヤコビ更新を2枚のバッファーで交互に行います。更新は順序に依存しないため、GPU上で決定論的です。分解や推定を伴わない前向きの区分平坦化であり、常に均質な色面が得られます。平坦化のパラメータはデータ項の重み`β`を10⁵〜1の対数尺度で割り当てます。
### 4. 限定パレットと版ずれ・ばれん目・和紙
描画は`RenderShader`が画素ごとに行います。
- 階調化は、Winnemöllerらの「Real-Time Video Abstraction」(SIGGRAPH 2006)の輝度の軟量子化に基づきます。プラトーが階調の中心に来るように正規化した遷移幅0.18の軟階段で、暗さを色数の段数へ量子化します。彩度は平坦化とスケール0.9で整え、量子化しません。
- 版ずれは、階調の層ごとにシードから決めた方向へ最大10画素まで刷り位置をずらします。各画素で自身より暗い層のずらした標本を調べ、最も暗い層の色を採用するため、階調の境界に多色刷りの見当ずれの色縁が出ます。
- ばれん目は、セルごとに中心をずらした同心円模様を低周波の斑と掛け合わせ、中間調の暗さをわずかに明るくします。
- 和紙は、3オクターブの値ノイズの繊維場で暗さと主線を削り、かすれを作ります。
すべての模様はシードと画素位置のハッシュから決定論的に生成し、乱数と時間値を使用しません。出力はプリマルチプライドアルファで、各チャンネルをアルファ以下へクランプします。
### 5. 可視範囲への出力矩形の最小化
シルエットの集計時に、アルファ値を持つセルの境界を`InterlockedMin`と`InterlockedMax`で求め、8個の整数の読み戻しに含めます。表示矩形は素材の境界に主線の到達範囲と版ずれと余白を加えた大きさで、4画素境界へそろえます。出力テクスチャは矩形の大きさで確保し、Direct2Dの`Crop`と`AffineTransform2D`で元の位置へ合成します。画素の読み戻しは行いません。
### 6. 構造キャッシュ
輪郭と色面を決める入力が変わらないフレームでは、構造の計算を再利用します。
- 素材は、セル位置と量子化した色とアルファ値のハッシュの総和とXORの2値へ集約し、8個の整数の読み戻しで前フレームと比較します。
- 素材のハッシュ、計算領域の大きさ、品質、線の太さ、線の流れ、線の量、平坦化が一致する場合は、構造段階を実行しません。
- 構造が同じで、色数、版ずれ、ばれん目、和紙、線の濃さ、主線色、シード、出力矩形も変わらないフレームでは、描画段階も実行せず、前フレームの出力テクスチャを使用します。
### 7. Direct3D 11・Direct3D 12相互運用
`UkiyoeGpuInterop`は、YMM4のDirect3D 11・Direct2D側と、ComputeSharpのDirect3D 12側を接続します。ComputeSharpの`GraphicsDevice`は、YMM4が使うDXGIアダプターのLUIDと一致するものを選びます。
入力と出力は、ComputeSharpで確保した共有テクスチャをDirect3D 11のテクスチャとして開き、Direct2Dのビットマップとして扱います。両デバイスの同期は、Direct3D 12のフェンスを共有フェンスとしてDirect3D 11側で開いて行います。`BeginCompute`は、Direct3D 11のコマンドを送出したうえでDirect3D 12側を待機させ、`EndCompute`は、Direct3D 12側の完了をDirect3D 11側で待ちます。
Direct3D 12デバイスの取得や共有リソースの作成に失敗した場合は、`TryCreate`が`null`を返し、エフェクトを適用せず入力映像を表示します。
### 8. カスタムシェーダーによる合成
`UkiyoeCustomEffect`は、`[CustomEffect(2)]`の2入力エフェクトです。入力0は元映像、入力1は描画した版画です。ピクセルシェーダー`Ukiyoe.hlsl`の`main`は、`amount`が0以下のとき元映像をそのまま返し、そうでないときは版画のRGBをアルファでクランプし、`lerp(source, print, amount)`で元映像と混合します。版画の濃淡と模様は描画段階で画素へ焼き込むため、合成は単純な混合です。
定数バッファーは`Amount`と3つの詰め物で16バイトです。`MapInputRectsToOutputRect`は2つの入力矩形の和集合を出力矩形とします。主線と版ずれは素材の外側へわずかに広がるため、出力範囲は素材より大きくなります。
シェーダーリソース: `pack://application:,,,/Ukiyoe;component/Shaders/Ukiyoe.cso`(ps_5_0、`ShaderResourceUri.Get`が生成)
### 9. エフェクト定義とパラメータ
`UkiyoeEffect`は、YMM4の映像エフェクトとして宣言されます。
`[VideoEffect]`属性は以下のパラメーターで宣言されます。
- 表示名: `Texts.Ukiyoe`(ローカライズキー、日本語では「浮世絵」)
- カテゴリー: `VideoEffectCategories.Filtering`・`VideoEffectCategories.Decoration`
- 検索タグ: `TagWoodblock`・`TagPrint`・`TagJapanese`
- `IsAviUtlSupported = false`によりAviUtl向けEXO出力は非対応
- `ResourceType = typeof(Texts)`でローカライズリソースを指定
公開プロパティは以下のとおりです。基本項目は「基本」グループ、主線項目は「主線」グループ、色面項目は「色面」グループ、意匠項目は「意匠」グループに属します。
| プロパティ | 型 | デフォルト | 内部範囲 | アニメーション |
|---|---|---|---|---|
| `Amount` | `Animation` | 100 | 0〜100 | あり |
| `Quality` | `UkiyoeQuality` | `High` | — | なし |
| `LineWidth` | `Animation` | 50 | 0〜100 | あり |
| `Coherence` | `Animation` | 50 | 0〜100 | あり |
| `LineDetail` | `Animation` | 50 | 0〜100 | あり |
| `LineStrength` | `Animation` | 85 | 0〜100 | あり |
| `LineColor` | `Color` | #FF1E1A18 | — | なし |
| `Flatten` | `Animation` | 60 | 0〜100 | あり |
| `PaletteLevels` | `int` | 6 | 2〜16 | なし |
| `Misregistration` | `Animation` | 30 | 0〜100 | あり |
| `Baren` | `Animation` | 40 | 0〜100 | あり |
| `Paper` | `Animation` | 50 | 0〜100 | あり |
| `Seed` | `int` | 0 | 0〜int.MaxValue | なし |
`GetAnimatables`は`Amount`・`LineWidth`・`Coherence`・`LineDetail`・`LineStrength`・`Flatten`・`Misregistration`・`Baren`・`Paper`を返します。`Seed`は負値を代入すると0へ丸め、`PaletteLevels`は2〜16へ丸めます。
`CreateExoVideoFilters`は空のシーケンスを返します(EXO非対応)。`CreateVideoEffect`は映像処理用のインスタンスを生成します。エフェクトを最初に生成したときに、更新確認を一度だけ開始します。
### 10. フレームごとの更新
各フレームでYMM4の`EffectDescription`からフレーム位置、アイテム長、FPSを取得し、アニメーション値を評価します。値をパイプラインが前提とする範囲へ制限してから転送します。
| パラメータ | 変換 |
|---|---|
| `Amount` | `value / 100` をカスタムシェーダーの`Amount`へ |
| `LineWidth` | `value / 100` を0〜1へクランプし、中心ガウスの幅0.6〜3.0画素へ |
| `Coherence` | `value / 100` を0〜1へクランプし、流線ガウスの幅1〜6セルへ |
| `LineDetail` | `value / 100` を0〜1へクランプし、二値化のしきい値0.1〜0.95へ |
| `LineStrength` | `value / 100` を0〜1へクランプ |
| `Flatten` | `value / 100` を0〜1へクランプし、データ項の重み10⁵〜1へ |
| `PaletteLevels` | 2〜16へクランプ |
| `Misregistration` | `value / 100` を0〜1へクランプし、刷りずれ0〜10画素へ |
| `Baren` | `value / 100` を0〜1へクランプ |
| `Paper` | `value / 100` を0〜1へクランプ |
| `LineColor` | RGB各成分を0〜1へ |
| `Seed` | 0以上へクランプ |
強さが0以下のときは入力映像をそのまま出力します。入力の範囲が有限でない場合や、計算領域の余白を確保できない場合も、入力映像を表示します。
### 11. 品質設定
品質は、処理格子の解像度と各段階の反復回数をまとめて切り替えます。
| 品質 | 格子解像度 | 接線流反復 | 主線反復 | 平坦化反復 |
|---|---:|---:|---:|---:|
| 標準 | 1024 | 2回 | 2回 | 24回 |
| 高品質 | 1440 | 3回 | 2回 | 40回 |
| 最高品質 | 2048 | 3回 | 3回 | 64回 |
格子解像度は計算領域の長辺のセル数です。短辺のセル数は計算領域の縦横比に合わせ、最小4セルとします。
### 12. ローカライズ
`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 |
|---|---|
| `Ukiyoe` | 浮世絵 |
| `BasicGroup` | 基本 |
| `LineGroup` | 主線 |
| `ColorGroup` | 色面 |
| `CraftGroup` | 意匠 |
| `Amount` | 強さ |
| `Quality` | 品質 |
| `LineWidth` | 線の太さ |
| `Coherence` | 線の流れ |
| `LineDetail` | 線の量 |
| `LineStrength` | 線の濃さ |
| `LineColor` | 主線色 |
| `Flatten` | 平坦化 |
| `PaletteLevels` | 色数 |
| `Misregistration` | 版ずれ |
| `Baren` | ばれん目 |
| `Paper` | 和紙 |
| `Seed` | シード |
| `QualityBalanced` | 標準 |
| `QualityHigh` | 高品質 |
| `QualityUltra` | 最高品質 |
| `TagWoodblock` | 木版画 |
| `TagPrint` | 版画 |
| `TagJapanese` | 和風 |
| `UpdateAvailableMessage` | 新しいバージョン {0} が公開されています。 |
ファイルの表示
差分なしでファイル名を変更。
+1 -1
ファイルの表示
@@ -1,5 +1,5 @@
========================================
浮世絵 for YMM4 v1.0.0
浮世絵 for YMM4 v1.2.0
========================================
YukkuriMovieMaker4上で動作する、素材を浮世絵の多色木版画とみなして
描画する映像エフェクトプラグインです。
+306 -67
ファイルの表示
@@ -14,31 +14,20 @@ 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
- name: .NET SDK のセットアップ
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最新リリースの取得と解凍
- name: YMM4 最新リリースの取得と解凍
id: ymm4
shell: pwsh
run: |
@@ -48,20 +37,12 @@ jobs:
if (-not $asset) {
$asset = $release.assets | Where-Object { $_.name -like "*.zip" } | Select-Object -First 1
}
if (-not $asset) {
Write-Error "YMM4のリリースにZIPファイルが見つかりませんでした。"
exit 1
}
Write-Host "ダウンロード対象: $($asset.name)"
Invoke-WebRequest -Uri $asset.browser_download_url -OutFile "ymm4.zip"
Expand-Archive -Path "ymm4.zip" -DestinationPath "ymm4_extracted" -Force
$ymm4Dir = (Get-ChildItem -Path "ymm4_extracted" -Recurse -Filter "YukkuriMovieMaker.dll" |
Select-Object -First 1).DirectoryName
if (-not $ymm4Dir) {
Write-Error "YukkuriMovieMaker.dllが見つかりませんでした。"
exit 1
}
Write-Host "YMM4 DLLディレクトリ: $ymm4Dir"
Write-Host "YMM4 DLL ディレクトリ: $ymm4Dir"
echo "YMM4_DIR=$ymm4Dir\" >> $env:GITHUB_OUTPUT
- name: タグ名からバージョンを取得
@@ -70,17 +51,47 @@ jobs:
run: |
$tag = "${{ github.ref_name }}"
echo "TAG=$tag" >> $env:GITHUB_OUTPUT
echo "VERSION=$($tag.TrimStart('v'))" >> $env:GITHUB_OUTPUT
- name: resxファイルの生成
- name: バージョン記載の照合
shell: pwsh
run: |
$proj = "Ukiyoe/Ukiyoe.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 = "Ukiyoe/Ukiyoe.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 Ukiyoe.Shader/Ukiyoe.Shader.vcxproj `
/p:Configuration=Release `
/p:Platform=Win32 `
/nologo
- name: プロジェクトのビルド
shell: pwsh
@@ -89,28 +100,6 @@ jobs:
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
- name: テストプロジェクトのビルド
shell: pwsh
run: |
dotnet build Ukiyoe.Tests/Ukiyoe.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: テストの実行
shell: pwsh
run: |
dotnet test Ukiyoe.Tests/Ukiyoe.Tests.csproj `
--no-build `
--no-restore `
-c Release `
-p:Platform=x64 `
-p:SkipPluginDeploy=true
@@ -118,17 +107,20 @@ jobs:
id: package
shell: pwsh
run: |
$version = "${{ steps.version.outputs.TAG }}"
$outDir = "Ukiyoe/bin/x64/Release/net10.0-windows10.0.19041.0"
$version = "${{ steps.version.outputs.TAG }}"
$outDir = "Ukiyoe/bin/x64/Release/net10.0-windows10.0.19041.0"
$stageRoot = "stage/Ukiyoe"
$pkgName = "Ukiyoe_$version.ymme"
$pkgName = "Ukiyoe_$version.ymme"
New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
Copy-Item "$outDir/Ukiyoe.dll" "$stageRoot/"
Copy-Item "$outDir/Ukiyoe.ComputeSharp.dll" "$stageRoot/"
Copy-Item "$outDir/Ukiyoe.ComputeSharp.Core.dll" "$stageRoot/"
$dll = "$outDir/plugin/Ukiyoe.dll"
if (-not (Test-Path $dll)) {
Write-Error "ビルド結果に Ukiyoe.dll が見つかりませんでした: $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"
@@ -138,17 +130,264 @@ jobs:
}
}
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
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: GitHubリリースの作成
uses: softprops/action-gh-release@v2
- 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@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 -3
ファイルの表示
@@ -4,6 +4,6 @@
[submodule "YMM4-GitHubUpdateNotifier"]
path = YMM4-GitHubUpdateNotifier
url = https://github.com/routersys/YMM4-GitHubUpdateNotifier.git
[submodule "ComputeSharp"]
path = ComputeSharp
url = https://github.com/routersys/ComputeSharp.git
[submodule "YMM4-Telemetry"]
path = YMM4-Telemetry
url = https://github.com/routersys/YMM4-Telemetry.git
サブモジュール ComputeSharp が 7c4145d5f2 から削除されました。
-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>
+42 -7
ファイルの表示
@@ -1,4 +1,4 @@
# 浮世絵 for YMM4
# 浮世絵 for YMM4
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](#)
[![.NET](https://img.shields.io/badge/.NET-10.0-purple.svg)](#)
@@ -34,9 +34,10 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を多色木版画の原
- [意匠グループ](#意匠グループ)
6. [制限事項](#制限事項)
7. [注意事項](#注意事項)
8. [免責事項](#免責事項)
9. [サードパーティライセンス](#サードパーティライセンス)
10. [ライセンス](#ライセンス)
8. [不具合の報告](#不具合の報告)
9. [免責事項](#免責事項)
10. [サードパーティライセンス](#サードパーティライセンス)
11. [ライセンス](#ライセンス)
---
@@ -46,7 +47,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を多色木版画の原
入力された現在のフレームの色とアルファ値から素材の絵柄を求め、多色木版画の工程になぞらえて3つの層を刷り重ねます。主線の層は、Kang・Lee・Chuiの論文「Coherent Line Drawing」(NPAR 2007)に基づき、エッジ接線流の非線形ベクトル平滑化で絵柄の流れを求め、流れに直交する方向の差分ガウスを流線に沿って集計して、つながりの良い輪郭線を取り出します。色面の層は、Bi・Han・Yuの論文「An L1 Image Transform for Edge-Preserving Smoothing and Scene-Level Intrinsic Decomposition」(SIGGRAPH 2015)のL1局所平坦化を前向きの反復重み付き最小二乗として解き、細部を消しながら際を保った均質な色面を作り、Winnemöllerらの論文「Real-Time Video Abstraction」(SIGGRAPH 2006)の軟量子化で限定パレットの階調へ寄せます。意匠の層は、階調ごとの刷り位置のずれ、ばれんの擦り跡、和紙の繊維のかすれを決定論的なハッシュ模様として重ねます。
計算はComputeSharpの計算シェーダーがDirect3D 12で実行します。YMM4のDirect3D 11側とComputeSharpのDirect3D 12側は、共有テクスチャと共有フェンスで接続します。通常のフレーム処理では、CPUへの画素の読み戻しを行わず、8個の整数の読み戻しだけで素材の変化を判定します。素材が存在する最小の矩形の範囲だけを描画し、絵柄と構造のパラメータが変わらないフレームでは輪郭と平坦化の計算を再利用します。
計算はComputeWeaveの計算シェーダーがDirect3D 12で実行します。YMM4のDirect3D 11側とComputeWeaveのDirect3D 12側は、共有テクスチャと共有フェンスで接続します。通常のフレーム処理では、CPUへの画素の読み戻しを行わず、8個の整数の読み戻しだけで素材の変化を判定します。素材が存在する最小の矩形の範囲だけを描画し、絵柄と構造のパラメータが変わらないフレームでは輪郭と平坦化の計算を再利用します。
このエフェクトはAviUtl向けのEXO出力には対応していません。
@@ -171,10 +172,44 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を多色木版画の原
- シードと再現性: 和紙の繊維とばれん目と版ずれの形は、シードと画素位置から決定論的に算出します。時間値は生成に使用しません。
- 透明部分: 主線と版ずれは素材の外側にもわずかに描画されるため、出力範囲は素材より広がります。出力は元映像と強さの割合で合成します。
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ新しい正式版を確認します。更新情報を取得できない場合は通知せず、そのまま動作します。プレリリースは通知の対象に含めません。
- 不具合の自動送信: 想定していない例外が起きたときは、その内容を開発者へ自動で送信します。内容は「不具合の報告」に書いています。
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを作成することを推奨します。
---
## 不具合の報告
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で送信します。同意は求めず、常に送信します。
送信する情報は次のとおりです。
| 種類 | 内容 |
|---|---|
| 例外 | 型の完全名、メッセージ、スタックトレース |
| 発生位置 | モジュール名、関数名、ファイル名、行番号 |
| プラグイン | アセンブリ名、バージョン |
| 実行環境 | OSの名前とバージョン、.NETのバージョン、CPUのアーキテクチャ、論理プロセッサ数 |
| 識別子 | YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子 |
メッセージとファイル名は、送信の前に置き換えを通します。置き換えるのは、Windowsのユーザー名、ユーザーフォルダー、AppDataのパス、マシン名、ドメイン名、メールアドレス、IPv4アドレスです。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値になります。
送信するのは想定していない例外だけです。本プラグインがエフェクトのプロセッサを作るとき、Direct3D 12の計算資源を確保するとき、フレームごとに更新するとき、エフェクトの入力をつなぎ直すときと、Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後はYMM4へそのまま渡します。画面の操作やバックグラウンドの処理で未処理になった例外も報告しますが、本プラグインのコードが関わる例外に限ります。本プラグインの外で起きた例外は送信しません。
次の失敗は送信しません。
| 種類 | 例 |
|---|---|
| 効果をかけないだけで済ませるもの | Direct3D 12デバイスを取得できない、YMM4のDirect3D 11デバイスとの共有テクスチャや共有フェンスを作成できない、計算領域が上限を超えるときに、エフェクトを適用せず入力映像を表示したとき |
| 更新の確認の通信の失敗 | GitHubへ接続できない |
送信できなかった報告はYMM4のユーザーフォルダーへ退避し、次回の起動時に送り直します。送信も再送も非同期に行うため、起動と描画が遅くなることはありません。
実装は [YMM4-Telemetry](https://github.com/routersys/YMM4-Telemetry) をサブモジュールとして取り込んでいます。
---
## 免責事項
本プラグインはMITライセンスのもとで公開されています。
@@ -187,11 +222,11 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を多色木版画の原
## サードパーティライセンス
本プラグインは以下のサードパーティソフトウェアを同梱・使用しています。ライセンスの全文は、リポジトリの [`.github/LICENSE/ComputeSharp.txt`](.github/LICENSE/ComputeSharp.txt) と、配布パッケージの `LICENSE` フォルダーに収録しています。
本プラグインは以下のサードパーティソフトウェアを同梱・使用しています。ライセンスの全文は、リポジトリの [`.github/LICENSE/ComputeWeave.txt`](.github/LICENSE/ComputeWeave.txt) と、配布パッケージの `LICENSE` フォルダーに収録しています。
| ソフトウェア | 用途 | ライセンス | 著作権表示 |
|---|---|---|---|
| [ComputeSharp](https://github.com/routersys/ComputeSharp) | Direct3D 12計算シェーダーとDirect3D 11・12共有処理 | MIT License | Copyright (c) 2024 Sergio Pedri |
| [ComputeWeave](https://github.com/routersys/ComputeWeave) | Direct3D 12計算シェーダーとDirect3D 11・12共有処理 | MIT License | Copyright (c) 2024 Sergio Pedri |
---
+55
ファイルの表示
@@ -0,0 +1,55 @@
using System.IO;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Json;
namespace Ukiyoe.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 Ukiyoe.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 Ukiyoe.Harness;
internal sealed class HarnessException(string message) : Exception(message);
internal enum HarnessMode
{
Render,
Golden,
Verify,
Transition,
Compare,
Benchmark,
Structure,
}
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 <画像>] 描画を計測します
--structure 構造の再計算がパラメータごとに掛かる時間を内訳で計測します
""";
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 "--structure":
mode = Select(mode, HarnessMode.Structure);
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 つだけ指定してください。");
}
+64
ファイルの表示
@@ -0,0 +1,64 @@
using System.Windows.Media;
namespace Ukiyoe.Harness;
internal static class HarnessCases
{
public static IEnumerable<(string Name, UkiyoeEffect 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 ("quality-balanced", Create(effect => effect.Quality = UkiyoeQuality.Balanced), [0]);
yield return ("quality-ultra", Create(effect => effect.Quality = UkiyoeQuality.Ultra), [0]);
yield return ("line-width-0", Create(effect => effect.LineWidth.Values[0].Value = 0), [0]);
yield return ("line-width-100", Create(effect => effect.LineWidth.Values[0].Value = 100), [0]);
yield return ("coherence-0", Create(effect => effect.Coherence.Values[0].Value = 0), [0]);
yield return ("coherence-100", Create(effect => effect.Coherence.Values[0].Value = 100), [0]);
yield return ("line-detail-100", Create(effect => effect.LineDetail.Values[0].Value = 100), [0]);
yield return ("line-strength-0", Create(effect => effect.LineStrength.Values[0].Value = 0), [0]);
yield return ("flatten-0", Create(effect => effect.Flatten.Values[0].Value = 0), [0]);
yield return ("flatten-100", Create(effect => effect.Flatten.Values[0].Value = 100), [0]);
yield return ("palette-levels-2", Create(effect => effect.PaletteLevels = 2), [0]);
yield return ("palette-levels-16", Create(effect => effect.PaletteLevels = 16), [0]);
yield return ("misregistration-0", Create(effect => effect.Misregistration.Values[0].Value = 0), [0]);
yield return ("misregistration-100", Create(effect => effect.Misregistration.Values[0].Value = 100), [0]);
yield return ("baren-100", Create(effect => effect.Baren.Values[0].Value = 100), [0]);
yield return ("paper-100", Create(effect => effect.Paper.Values[0].Value = 100), [0]);
yield return ("seed-42", Create(effect => effect.Seed = 42), [0]);
yield return ("line-color", Create(effect => effect.LineColor = Color.FromArgb(255, 200, 20, 20)), [0]);
}
public static IEnumerable<(string Name, Func<UkiyoeEffect> Create, Action<UkiyoeEffect> Change, int Frame)> Transitions()
{
yield return ("line-width-50-to-100", () => Create(), effect => effect.LineWidth.Values[0].Value = 100, 0);
yield return ("coherence-50-to-100", () => Create(), effect => effect.Coherence.Values[0].Value = 100, 0);
yield return ("line-detail-50-to-100", () => Create(), effect => effect.LineDetail.Values[0].Value = 100, 0);
yield return ("flatten-60-to-0", () => Create(), effect => effect.Flatten.Values[0].Value = 0, 0);
yield return ("quality-high-to-ultra", () => Create(), effect => effect.Quality = UkiyoeQuality.Ultra, 0);
yield return ("palette-levels-6-to-2", () => Create(), effect => effect.PaletteLevels = 2, 0);
yield return ("misregistration-30-to-100", () => Create(), effect => effect.Misregistration.Values[0].Value = 100, 0);
yield return ("baren-40-to-100", () => Create(), effect => effect.Baren.Values[0].Value = 100, 0);
yield return ("paper-50-to-100", () => Create(), effect => effect.Paper.Values[0].Value = 100, 0);
yield return ("line-strength-85-to-0", () => Create(), effect => effect.LineStrength.Values[0].Value = 0, 0);
yield return ("line-color-change", () => Create(), effect => effect.LineColor = Color.FromArgb(255, 200, 20, 20), 0);
yield return ("seed-0-to-42", () => Create(), effect => effect.Seed = 42, 0);
yield return ("amount-100-to-0", () => Create(), effect => effect.Amount.Values[0].Value = 0, 0);
}
public static IEnumerable<(string Name, UkiyoeEffect Effect)> Benchmarks()
{
yield return ("quality-balanced", Create(effect => effect.Quality = UkiyoeQuality.Balanced));
yield return ("default", Create());
yield return ("quality-ultra", Create(effect => effect.Quality = UkiyoeQuality.Ultra));
yield return ("flatten-100", Create(effect => effect.Flatten.Values[0].Value = 100));
yield return ("amount-0", Create(effect => effect.Amount.Values[0].Value = 0));
}
public static UkiyoeEffect Create(Action<UkiyoeEffect>? configure = null)
{
var effect = new UkiyoeEffect();
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 Ukiyoe.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 Ukiyoe.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 Ukiyoe.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 Ukiyoe.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);
}
}
+394 -206
ファイルの表示
@@ -1,254 +1,442 @@
using System.Diagnostics;
using ComputeSharp;
using System.IO;
using System.IO.Packaging;
using System.Security.Cryptography;
using ComputeWeave;
using Ukiyoe;
using Ukiyoe.Harness;
using SharpGen.Runtime;
var width = 1280;
var height = 720;
var outputDirectory = args.Length > 0 && !args[0].StartsWith("--") ? args[0] : Path.Combine(AppContext.BaseDirectory, "harness-output");
Directory.CreateDirectory(outputDirectory);
const int CanvasWidth = 1280;
const int CanvasHeight = 720;
const int ImageWidth = 640;
const int ImageHeight = 480;
const int FullHdWidth = 1920;
const int FullHdHeight = 1080;
using var pipeline = UkiyoePipeline.TryCreate();
if (pipeline is null)
_ = PackUriHelper.UriSchemePack;
HarnessArguments arguments;
try
{
Console.WriteLine("Direct3D 12 is unavailable.");
return 1;
arguments = HarnessArguments.Parse(args);
}
catch (HarnessException exception)
{
Console.Error.WriteLine(exception.Message);
Console.Error.WriteLine(HarnessArguments.Usage);
return 2;
}
var source = CreateTestImage(width, height);
var destination = new int[source.Length];
if (args.Contains("--golden"))
try
{
var goldenCases = new (string Name, UkiyoePipeline.Parameters Parameters)[]
if (arguments.Mode == HarnessMode.Compare)
return Compare(arguments.Before!, arguments.After!);
if (arguments.Mode == HarnessMode.Structure)
{
("balanced-default", new(UkiyoeQuality.Balanced, 0.5f, 0.5f, 0.5f, 0.6f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0)),
("high-default", new(UkiyoeQuality.High, 0.5f, 0.5f, 0.5f, 0.6f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0)),
("seed-42", new(UkiyoeQuality.Balanced, 0.5f, 0.5f, 0.5f, 0.6f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 42)),
("flat-none", new(UkiyoeQuality.Balanced, 0.5f, 0.5f, 0.5f, 0f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0)),
("flat-full", new(UkiyoeQuality.Balanced, 0.5f, 0.5f, 0.5f, 1f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0)),
("palette-2", new(UkiyoeQuality.Balanced, 0.5f, 0.5f, 0.5f, 0.6f, 2, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0)),
("shift-full", new(UkiyoeQuality.Balanced, 0.5f, 0.5f, 0.5f, 0.6f, 6, 1f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0)),
("thick-line", new(UkiyoeQuality.Balanced, 1f, 1f, 0.8f, 0.6f, 6, 0.3f, 0.4f, 0.5f, 1f, 0.12f, 0.1f, 0.09f, 0)),
};
foreach (var (name, goldenParameters) in goldenCases)
{
var parameters = goldenParameters;
pipeline.Process(source, destination, width, height, in parameters);
var bytes = new byte[destination.Length * sizeof(int)];
Buffer.BlockCopy(destination, 0, bytes, 0, bytes.Length);
Console.WriteLine($"{name}: {Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(bytes))}");
var structureImage = arguments.Input is { } structureInput ? HarnessImage.Load(structureInput) : HarnessImage.Synthetic(CanvasWidth, CanvasHeight);
return Structure(structureImage);
}
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;
}
foreach (var quality in new[] { UkiyoeQuality.Balanced, UkiyoeQuality.High, UkiyoeQuality.Ultra })
static int Verify(HarnessRenderer renderer, HarnessImage image)
{
var parameters = new UkiyoePipeline.Parameters(quality, 0.5f, 0.5f, 0.5f, 0.6f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0);
pipeline.Process(source, destination, width, height, in parameters);
pipeline.Process(source, destination, width, height, in parameters);
var stopwatch = Stopwatch.StartNew();
const int frames = 5;
for (var frame = 0; frame < frames; frame++)
pipeline.Process(source, destination, width, height, in parameters);
stopwatch.Stop();
Console.WriteLine($"{quality}: {stopwatch.Elapsed.TotalMilliseconds / frames:F2} ms/frame ({width}x{height}) litPixels={CountLit(destination)}");
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 Structure(HarnessImage image)
{
const int Rounds = 12;
const int Seed = 17;
const int RectFrames = 20;
using var pipeline = UkiyoePipeline.TryCreate();
if (pipeline is null)
throw new HarnessException("Direct3D 12を利用できません。");
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
var pixels = new Bgra32[source.Length];
for (var index = 0; index < source.Length; index++)
pixels[index].PackedValue = unchecked((uint)source[index]);
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(image.Width, image.Height);
var pixels = new Bgra32[image.Width * image.Height];
for (var index = 0; index < pixels.Length; index++)
{
var offset = index * HarnessImage.BytesPerPixel;
pixels[index] = new Bgra32(image.Pixels[offset + 2], image.Pixels[offset + 1], image.Pixels[offset], image.Pixels[offset + 3]);
}
sourceTexture.CopyFrom(pixels);
var parameters = new UkiyoePipeline.Parameters(UkiyoeQuality.High, 0.5f, 0.5f, 0.5f, 0.6f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0);
pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in parameters);
var stopwatch = Stopwatch.StartNew();
pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, parameters with { Flatten = 0.7f });
pipeline.Simulate(sourceTexture, image.Width, image.Height, 0, 0, image.Width, image.Height, in parameters);
pipeline.WaitForCompletion();
stopwatch.Stop();
Console.WriteLine($"structure recompute: {stopwatch.Elapsed.TotalMilliseconds:F2} ms");
var stopwatch = new Stopwatch();
if (pipeline.TryGetVisibleBounds(width, height, in parameters, out var rect))
var variants = new (string Name, Func<bool, UkiyoePipeline.Parameters> Make)[]
{
("cached", _ => parameters),
("flatten", flip => parameters with { Flatten = flip ? 0.70f : 0.60f }),
("lineWidth", flip => parameters with { LineWidth = flip ? 0.60f : 0.50f }),
("coherence", flip => parameters with { Coherence = flip ? 0.60f : 0.50f }),
("lineDetail", flip => parameters with { LineDetail = flip ? 0.60f : 0.50f }),
("all", flip => parameters with
{
Flatten = flip ? 0.70f : 0.60f,
LineWidth = flip ? 0.60f : 0.50f,
Coherence = flip ? 0.60f : 0.50f,
LineDetail = flip ? 0.60f : 0.50f,
}),
};
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 warmup = make(true);
pipeline.Simulate(sourceTexture, image.Width, image.Height, 0, 0, image.Width, image.Height, in warmup);
pipeline.WaitForCompletion();
}
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 settled = variants[index].Make(false);
pipeline.Simulate(sourceTexture, image.Width, image.Height, 0, 0, image.Width, image.Height, in settled);
pipeline.WaitForCompletion();
var measured = variants[index].Make(true);
stopwatch.Restart();
pipeline.Simulate(sourceTexture, image.Width, image.Height, 0, 0, image.Width, image.Height, in measured);
pipeline.WaitForCompletion();
stopwatch.Stop();
samples[index].Add(stopwatch.Elapsed.TotalMilliseconds);
}
}
Console.WriteLine($"structure recompute 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,-11} min={sorted[0],7:F2} median={median,7:F2} max={sorted[^1],7:F2}");
}
if (pipeline.TryGetVisibleBounds(image.Width, image.Height, in parameters, out var rect))
{
using var rectOutput = device.AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
pipeline.RenderVisible(rectOutput, width, height, rect, in parameters);
pipeline.RenderVisible(rectOutput, image.Width, image.Height, rect, in parameters);
pipeline.WaitForCompletion();
stopwatch.Restart();
const int rectFrames = 20;
for (var frame = 0; frame < rectFrames; frame++)
for (var frame = 0; frame < RectFrames; frame++)
{
pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in parameters);
pipeline.TryGetVisibleBounds(width, height, in parameters, out rect);
pipeline.RenderVisible(rectOutput, width, height, rect, in parameters);
pipeline.Simulate(sourceTexture, image.Width, image.Height, 0, 0, image.Width, image.Height, in parameters);
pipeline.TryGetVisibleBounds(image.Width, image.Height, in parameters, out rect);
pipeline.RenderVisible(rectOutput, image.Width, image.Height, rect, in parameters);
}
pipeline.WaitForCompletion();
stopwatch.Stop();
Console.WriteLine($"cached frame with rect {rect.Width}x{rect.Height} at ({rect.X},{rect.Y}): {stopwatch.Elapsed.TotalMilliseconds / rectFrames:F2} ms/frame");
Console.WriteLine($"cached frame with rect {rect.Width}x{rect.Height} at ({rect.X},{rect.Y}): {stopwatch.Elapsed.TotalMilliseconds / RectFrames:F2} ms/frame");
}
return 0;
}
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));
}
}
foreach (var flatten in new[] { 0f, 0.5f, 1f })
{
var parameters = new UkiyoePipeline.Parameters(UkiyoeQuality.High, 0.5f, 0.5f, 0.5f, flatten, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0);
pipeline.Process(source, destination, width, height, in parameters);
Console.WriteLine($"flatten={flatten:F2} litPixels={CountLit(destination)}");
WriteBmp(Path.Combine(outputDirectory, $"flatten{(int)(flatten * 100):D3}.bmp"), Composite(source, destination), width, height);
}
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}");
foreach (var palette in new[] { 2, 6, 12 })
static List<GoldenCase> Evaluate(HarnessRenderer renderer, Action<GoldenCase, string[], byte[][]>? report)
{
var parameters = new UkiyoePipeline.Parameters(UkiyoeQuality.High, 0.5f, 0.5f, 0.5f, 0.6f, palette, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0);
pipeline.Process(source, destination, width, height, in parameters);
Console.WriteLine($"palette={palette} litPixels={CountLit(destination)}");
WriteBmp(Path.Combine(outputDirectory, $"palette{palette:D2}.bmp"), Composite(source, destination), width, height);
}
foreach (var shift in new[] { 0f, 0.5f, 1f })
{
var parameters = new UkiyoePipeline.Parameters(UkiyoeQuality.High, 0.5f, 0.5f, 0.5f, 0.6f, 6, shift, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0);
pipeline.Process(source, destination, width, height, in parameters);
Console.WriteLine($"shift={shift:F2} litPixels={CountLit(destination)}");
WriteBmp(Path.Combine(outputDirectory, $"shift{(int)(shift * 100):D3}.bmp"), Composite(source, destination), width, height);
}
foreach (var paper in new[] { 0f, 0.5f, 1f })
{
var parameters = new UkiyoePipeline.Parameters(UkiyoeQuality.High, 0.5f, 0.5f, 0.5f, 0.6f, 6, 0.3f, 0.4f, paper, 0.85f, 0.12f, 0.1f, 0.09f, 0);
pipeline.Process(source, destination, width, height, in parameters);
Console.WriteLine($"paper={paper:F2} litPixels={CountLit(destination)}");
WriteBmp(Path.Combine(outputDirectory, $"paper{(int)(paper * 100):D3}.bmp"), Composite(source, destination), width, height);
}
foreach (var lineWidth in new[] { 0f, 0.5f, 1f })
{
var parameters = new UkiyoePipeline.Parameters(UkiyoeQuality.High, lineWidth, 0.5f, 0.5f, 0.6f, 6, 0.3f, 0.4f, 0.5f, 0.85f, 0.12f, 0.1f, 0.09f, 0);
pipeline.Process(source, destination, width, height, in parameters);
Console.WriteLine($"lineWidth={lineWidth:F2} litPixels={CountLit(destination)}");
WriteBmp(Path.Combine(outputDirectory, $"linewidth{(int)(lineWidth * 100):D3}.bmp"), Composite(source, destination), width, height);
}
WriteBmp(Path.Combine(outputDirectory, "source.bmp"), Composite(source, new int[source.Length]), width, height);
Console.WriteLine($"images written to {outputDirectory}");
return 0;
static int[] CreateTestImage(int width, int height)
{
var pixels = new int[width * height];
var centerX = width * 0.5;
var centerY = height * 0.5;
for (var y = 0; y < height; y++)
var cases = new List<GoldenCase>();
var names = new HashSet<string>(StringComparer.Ordinal);
foreach (var (name, effect, frames) in HarnessCases.All())
{
for (var x = 0; x < width; x++)
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++)
{
var inRect = Math.Abs(x - centerX) < 300 && Math.Abs(y - centerY) < 220;
var dx = x - (centerX + 160);
var dy = y - (centerY - 60);
var inCircle = dx * dx + dy * dy < 130 * 130;
if (!inRect && !inCircle)
continue;
int r;
int g;
int b;
if (inCircle)
{
var shade = 1.0 - Math.Sqrt(dx * dx + dy * dy) / 130.0 * 0.6;
r = (int)(220 * shade);
g = (int)(80 * shade);
b = (int)(60 * shade);
}
else
{
var vertical = (y - (centerY - 220)) / 440.0;
r = (int)(70 + 60 * vertical);
g = (int)(110 + 70 * vertical);
b = (int)(170 + 60 * vertical);
if ((x / 3 + y / 7) % 9 == 0)
{
r += 25;
g += 25;
b += 20;
}
}
var hash = (uint)(x * 374761393 + y * 668265263);
hash = (hash ^ (hash >> 13)) * 1274126177u;
var noise = (int)((hash >> 24) & 31) - 16;
r = Math.Clamp(r + noise, 0, 255);
g = Math.Clamp(g + noise, 0, 255);
b = Math.Clamp(b + noise, 0, 255);
pixels[y * width + x] = unchecked((int)0xFF000000 | (r << 16) | (g << 8) | b);
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 pixels;
return duplicates;
}
static int CountLit(int[] pixels)
static int CountOpaque(byte[] pixels)
{
var count = 0;
foreach (var pixel in pixels)
for (var offset = HarnessImage.BytesPerPixel - 1; offset < pixels.Length; offset += HarnessImage.BytesPerPixel)
{
if (((pixel >> 24) & 255) > 8)
if (pixels[offset] != 0)
count++;
}
return count;
}
static int[] Composite(int[] source, int[] print)
{
var result = new int[source.Length];
for (var index = 0; index < source.Length; index++)
{
var s = source[index];
var p = print[index];
var sa = (s >> 24) & 255;
var pa = (p >> 24) & 255;
var a = Math.Min(pa + sa * (255 - pa) / 255, 255);
var r = Over((s >> 16) & 255, (p >> 16) & 255, pa);
var g = Over((s >> 8) & 255, (p >> 8) & 255, pa);
var b = Over(s & 255, p & 255, pa);
result[index] = 255 << 24 | OverWhite(r, a) << 16 | OverWhite(g, a) << 8 | OverWhite(b, a);
}
return result;
static int Over(int s, int p, int pa) => Math.Min(p + s * (255 - pa) / 255, 255);
static int OverWhite(int c, int a) => Math.Min(c + 255 - a, 255);
}
static void WriteBmp(string path, int[] pixels, int width, int height)
{
var stride = width * 3;
var padding = (4 - stride % 4) % 4;
var dataSize = (stride + padding) * height;
using var stream = new FileStream(path, FileMode.Create, FileAccess.Write);
using var writer = new BinaryWriter(stream);
writer.Write((byte)'B');
writer.Write((byte)'M');
writer.Write(54 + dataSize);
writer.Write(0);
writer.Write(54);
writer.Write(40);
writer.Write(width);
writer.Write(height);
writer.Write((short)1);
writer.Write((short)24);
writer.Write(0);
writer.Write(dataSize);
writer.Write(2835);
writer.Write(2835);
writer.Write(0);
writer.Write(0);
var pad = new byte[padding];
for (var y = height - 1; y >= 0; y--)
{
for (var x = 0; x < width; x++)
{
var pixel = pixels[y * width + x];
writer.Write((byte)(pixel & 255));
writer.Write((byte)((pixel >> 8) & 255));
writer.Write((byte)((pixel >> 16) & 255));
}
writer.Write(pad);
}
}
+51
ファイルの表示
@@ -0,0 +1,51 @@
namespace Ukiyoe.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);
}
+36 -5
ファイルの表示
@@ -1,14 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<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>Ukiyoe.Harness</AssemblyName>
<RootNamespace>Ukiyoe.Harness</RootNamespace>
<PlatformTarget>x64</PlatformTarget>
<TieredCompilation>false</TieredCompilation>
</PropertyGroup>
<ItemGroup>
@@ -18,14 +20,43 @@
</ItemGroup>
<ItemGroup>
<Reference Include="YukkuriMovieMaker.Plugin">
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Plugin.dll</HintPath>
<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>
<Import Project="..\Ukiyoe\ComputeSharp.Reference.props" />
</Project>
+163
ファイルの表示
@@ -0,0 +1,163 @@
{
"adapter": "Intel(R) Iris(R) Xe Graphics",
"driver": "32.0.101.7085",
"input": "synthetic 640x480 89838D8976198E40",
"canvas": "1280x720",
"cases": [
{
"name": "default",
"frames": [
0
],
"hash": "4E5044B29BA02EDE390E292DF2E57722AD86A0444CE6D8B4B413663DD10342FF"
},
{
"name": "default-frames-0-8",
"frames": [
0,
1,
2,
3,
4,
5,
6,
7,
8
],
"hash": "6B4BC84AA9879C9FBC615776A9AF80017AEF8EA99BC45F60DA13026CD6004CA2"
},
{
"name": "amount-0",
"frames": [
0
],
"hash": "0A700F76CEDDBAD7C4B6A2C19D46939C1A93940E86C6EFEF1E5A53DB48D2A020"
},
{
"name": "quality-balanced",
"frames": [
0
],
"hash": "B6B6633E5860BBEF1A629688FBB5D8CC5FE9E950879C16F291A799727CF33C9C"
},
{
"name": "quality-ultra",
"frames": [
0
],
"hash": "01F005AA19C031F827C64EF945CA002B8D9B85B3E8507F9FB2E8412B42D64941"
},
{
"name": "line-width-0",
"frames": [
0
],
"hash": "D53BFBE7A913BDC0D553DC6029E57F4E9526C3E8C189E301A7E3740C7D6A99BC"
},
{
"name": "line-width-100",
"frames": [
0
],
"hash": "3CEB63D2506249E0A5E969A66FA49DFFD7857C80280404791E3B38798DA9A811"
},
{
"name": "coherence-0",
"frames": [
0
],
"hash": "42FD6018D180C3CB78F5E43513F0DB63E0976FBD163D5E789EA40CAC46E2E100"
},
{
"name": "coherence-100",
"frames": [
0
],
"hash": "6C65959AC2BD18FE30320402A006804ED0401377FB12CF50BBEF1C67051358AF"
},
{
"name": "line-detail-100",
"frames": [
0
],
"hash": "62D3960B3470AB50246AB24459830BFF8F9B47FC0B7DCE6EE8459BA96CA11DCE"
},
{
"name": "line-strength-0",
"frames": [
0
],
"hash": "8CB6B048A0B652C90C4C479BFB32B808994FE73BF1A841F1D3D0B5512D8C100C"
},
{
"name": "flatten-0",
"frames": [
0
],
"hash": "AED3C8EFC249FB5F11B28ED031C73F61F935B83994487F8EABE87FAA33981A7D"
},
{
"name": "flatten-100",
"frames": [
0
],
"hash": "F4F86CB8941EB38E81EA15B4706036D50FCFC498F1E5C0A4426C00EDCE211563"
},
{
"name": "palette-levels-2",
"frames": [
0
],
"hash": "622FBF96D0F68584D39A20B53D79D5CB5412026447BD3FA69AFD05B1E7ED5634"
},
{
"name": "palette-levels-16",
"frames": [
0
],
"hash": "983797EE1A95E88FA631E4050B9F5244296768BE922EAF8A4ACDE5D2CF50024F"
},
{
"name": "misregistration-0",
"frames": [
0
],
"hash": "18EE76C0E16C45E52E3E392421A9DB5559A2B3748B6AD8D15F693DA9316232A7"
},
{
"name": "misregistration-100",
"frames": [
0
],
"hash": "CA48A1D66F7016F468380329AA4B7F43FF25DAB30E9B7EAE573530493C211C76"
},
{
"name": "baren-100",
"frames": [
0
],
"hash": "A7E85EE210A56C3495041D3F51D22B8F3C65E2CA8AA36FF1C7499CFFDA8F04CD"
},
{
"name": "paper-100",
"frames": [
0
],
"hash": "37A10A9C50DDD961C7DA31E2C671CF7E3B74FE564C13077CD3A96280183E8064"
},
{
"name": "seed-42",
"frames": [
0
],
"hash": "7D531AD31E841C097FE1FB3FB951FFA8D3E3D7F8F0939DC188436F06575D91A4"
},
{
"name": "line-color",
"frames": [
0
],
"hash": "0378B44DD9334EA8339F0EBD547DD9C94D17639E154D15D0CBF74B0BDA368D12"
}
]
}
+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>{C7DCA1E0-297A-41B2-9B15-8C8593EC861E}</ProjectGuid>
<RootNamespace>UkiyoeShader</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="Ukiyoe.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="Ukiyoe.hlsl">
<Filter>ソース ファイル</Filter>
</FxCompile>
</ItemGroup>
</Project>
ファイルの表示
差分なしでファイル名を変更。
+1 -2
ファイルの表示
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
@@ -63,6 +63,5 @@
<Using Include="Xunit" />
</ItemGroup>
<Import Project="..\Ukiyoe\ComputeSharp.Reference.props" />
</Project>
+101 -17
ファイルの表示
@@ -1,6 +1,6 @@
using System.Runtime.InteropServices;
using ComputeSharp;
using ComputeSharp.Interop;
using System.Runtime.InteropServices;
using ComputeWeave;
using ComputeWeave.Interop;
using Vortice;
using Vortice.Direct2D1;
using Vortice.DXGI;
@@ -490,6 +490,63 @@ public sealed class UkiyoeEffectTests
}
}
[Theory]
[InlineData("flatten")]
[InlineData("lineWidth")]
[InlineData("coherence")]
[InlineData("lineDetail")]
public void PartialStructureRecomputeMatchesAFullRecompute(string changed)
{
using var incremental = UkiyoePipeline.TryCreate();
using var reference = UkiyoePipeline.TryCreate();
if (incremental is null || reference is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 128;
const int height = 128;
var source = CreateGradientSource(width, height, 40, 40, 48, 48);
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
var sourcePixels = new Bgra32[source.Length];
for (var index = 0; index < source.Length; index++)
sourcePixels[index].PackedValue = unchecked((uint)source[index]);
sourceTexture.CopyFrom(sourcePixels);
var first = CreateParameters(seed: 7);
var second = changed switch
{
"flatten" => first with { Flatten = 0.15f },
"lineWidth" => first with { LineWidth = 0.95f },
"coherence" => first with { Coherence = 0.05f },
_ => first with { LineDetail = 0.95f }
};
incremental.Simulate(sourceTexture, width, height, 0, 0, width, height, in first);
Assert.True(incremental.Simulate(sourceTexture, width, height, 0, 0, width, height, in second));
reference.Simulate(sourceTexture, width, height, 0, 0, width, height, in second);
Assert.True(incremental.TryGetVisibleBounds(width, height, in second, out var rect));
Assert.True(reference.TryGetVisibleBounds(width, height, in second, out var referenceRect));
Assert.Equal(referenceRect, rect);
using var incrementalOutput = device.AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
using var referenceOutput = device.AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
incremental.RenderVisible(incrementalOutput, width, height, rect, in second);
reference.RenderVisible(referenceOutput, width, height, rect, in second);
var incrementalPixels = new Bgra32[rect.Width * rect.Height];
var referencePixels = new Bgra32[rect.Width * rect.Height];
incrementalOutput.CopyTo(incrementalPixels);
referenceOutput.CopyTo(referencePixels);
for (var index = 0; index < incrementalPixels.Length; index++)
Assert.Equal(referencePixels[index].PackedValue, incrementalPixels[index].PackedValue);
}
[Fact]
public void SimulateCachesStructureUntilInputsChange()
{
@@ -537,18 +594,21 @@ public sealed class UkiyoeEffectTests
}
[Fact]
public void Direct2DInteropProducesPrintFromOpaqueCore()
public void Direct2DInteropProducesPrintAfterGrowingFullHdOutput()
{
using var devices = new GraphicsDevices();
using var graphicsContext = devices.CreateContext();
using var interop = UkiyoeGpuInterop.TryCreate(graphicsContext);
if (interop is null)
using var scheduler = ComputeExternalQueueScheduler.Create();
using var provider = UkiyoeInteropProvider.TryCreate(graphicsContext, scheduler, out var interopDevice);
if (provider is null || interopDevice is null)
{
Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable.");
return;
}
using var pipeline = UkiyoePipeline.TryCreate(interop.Device);
using var domain = interopDevice.RegisterExternalDomain(provider);
using var resourceSet = UkiyoeResourceSet.Create(interopDevice, domain);
using var pipeline = UkiyoePipeline.TryCreate(interopDevice);
Assert.NotNull(pipeline);
const int width = 96;
@@ -571,24 +631,47 @@ public sealed class UkiyoeEffectTests
handle.Free();
}
Assert.True(interop.EnsureResources(width, height));
var bounds = new RawRectF(0f, 0f, width, height);
Assert.True(resourceSet.TryEnsureSource(width, height, out _));
var parameters = CreateParameters();
var renderContext = provider.RenderContext;
for (var iteration = 0; iteration < 2; iteration++)
{
interop.RenderInput(inputBitmap, bounds);
interop.BeginCompute();
try
using (var borrow = resourceSet.BeginSourceExternalOperation())
{
pipeline!.Process(interop.SourceTexture, interop.OutputTexture, width, height, in parameters);
var previousTarget = renderContext.Target;
using var sourceBitmap = new ID2D1Bitmap1(borrow.DangerousGetView().AddRefBitmap());
renderContext.Target = sourceBitmap;
renderContext.BeginDraw();
renderContext.Clear(null);
renderContext.DrawImage(
inputBitmap,
new System.Numerics.Vector2(0f, 0f),
null,
InterpolationMode.NearestNeighbor,
CompositeMode.SourceCopy);
renderContext.EndDraw();
renderContext.Target = previousTarget;
}
finally
pipeline!.Simulate(
resourceSet.GetSourceComputeBinding(), width, height, 0, 0, width, height, in parameters);
Assert.True(pipeline.TryGetVisibleBounds(width, height, in parameters, out var visible));
Assert.True(resourceSet.TryEnsureOutput(
iteration == 0 ? width : 1920,
iteration == 0 ? height : 1080,
out _));
pipeline.RenderVisible(
resourceSet.GetOutputComputeBinding(), width, height, visible, in parameters);
if (iteration == 0)
{
interop.EndCompute();
using var retiredLease = resourceSet.AcquireOutputExternalViewLease();
Assert.Equal(width, retiredLease.Width);
Assert.Equal(height, retiredLease.Height);
}
}
interop.WaitForIdle();
using var outputLease = resourceSet.AcquireOutputExternalViewLease();
using var staging = graphicsContext.DeviceContext.CreateBitmap(
new SizeI(width, height),
new BitmapProperties1(
@@ -596,7 +679,8 @@ public sealed class UkiyoeEffectTests
96f,
96f,
BitmapOptions.CpuRead | BitmapOptions.CannotDraw));
staging.CopyFromBitmap(interop.OutputBitmap);
using var outputBitmap = new ID2D1Bitmap1(outputLease.DangerousGetView().AddRefBitmap());
staging.CopyFromBitmap(outputBitmap);
var mapped = staging.Map(MapOptions.Read);
try
{
+14 -9
ファイルの表示
@@ -1,20 +1,25 @@
<Solution>
<Solution>
<Configurations>
<Platform Name="Any CPU" />
<Platform Name="x64" />
</Configurations>
<Project Path="ComputeSharp/src/ComputeSharp.Core/ComputeSharp.Core.csproj">
<Platform Solution="*|x64" Project="Any CPU" />
</Project>
<Project Path="ComputeSharp/src/ComputeSharp.Core.SourceGenerators/ComputeSharp.Core.SourceGenerators.csproj" />
<Project Path="ComputeSharp/src/ComputeSharp/ComputeSharp.csproj">
<Platform Solution="*|x64" Project="Any CPU" />
</Project>
<Project Path="ComputeSharp/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj" />
<Folder Name="/Solution Items/">
<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="Ukiyoe/Ukiyoe.csproj">
<Platform Solution="*|x64" Project="x64" />
<BuildDependency Project="Ukiyoe.Shader/Ukiyoe.Shader.vcxproj" />
</Project>
<Project Path="Ukiyoe.Tests/Ukiyoe.Tests.csproj" />
<Project Path="Ukiyoe.Harness/Ukiyoe.Harness.csproj" />
<Project Path="Ukiyoe.Shader/Ukiyoe.Shader.vcxproj">
<BuildType Solution="*|*" Project="Release" />
<Platform Solution="*|*" Project="Win32" />
</Project>
<Project Path="YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator.csproj" />
</Solution>
-8
ファイルの表示
@@ -1,8 +0,0 @@
<Project>
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp' or '$(MSBuildProjectName)' == 'ComputeSharp.Core'">
<IsPackagedProject>false</IsPackagedProject>
</PropertyGroup>
<ItemGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp.Core'">
<InternalsVisibleTo Include="Ukiyoe.ComputeSharp, PublicKey=$(AssemblySignPublicKey)" />
</ItemGroup>
</Project>
-14
ファイルの表示
@@ -1,14 +0,0 @@
<Project>
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp' or '$(MSBuildProjectName)' == 'ComputeSharp.Core'">
<BaseOutputPath>$(MSBuildProjectDirectory)\bin\Ukiyoe\</BaseOutputPath>
<BaseIntermediateOutputPath>$(MSBuildProjectDirectory)\obj\Ukiyoe\</BaseIntermediateOutputPath>
<MSBuildProjectExtensionsPath>$(MSBuildProjectDirectory)\obj\</MSBuildProjectExtensionsPath>
<DefaultItemExcludes>$(DefaultItemExcludes);$(MSBuildProjectDirectory)\obj\**</DefaultItemExcludes>
</PropertyGroup>
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp'">
<AssemblyName>Ukiyoe.ComputeSharp</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp.Core'">
<AssemblyName>Ukiyoe.ComputeSharp.Core</AssemblyName>
</PropertyGroup>
</Project>
-9
ファイルの表示
@@ -1,9 +0,0 @@
<Project>
<PropertyGroup>
<PrivateComputeSharpBuildProperties Condition="'$(BuildingSolutionFile)' != 'true'">CustomBeforeDirectoryBuildProps=$(MSBuildThisFileDirectory)ComputeSharp.Build.props;CustomAfterDirectoryBuildProps=$(MSBuildThisFileDirectory)ComputeSharp.Build.after.props</PrivateComputeSharpBuildProperties>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="$(MSBuildThisFileDirectory)..\ComputeSharp\src\ComputeSharp.Core\ComputeSharp.Core.csproj" SetConfiguration="Configuration=$(Configuration)" SetPlatform="Platform=AnyCPU" AdditionalProperties="$(PrivateComputeSharpBuildProperties)" GlobalPropertiesToRemove="SkipPluginDeploy" />
<ProjectReference Include="$(MSBuildThisFileDirectory)..\ComputeSharp\src\ComputeSharp\ComputeSharp.csproj" SetConfiguration="Configuration=$(Configuration)" SetPlatform="Platform=AnyCPU" AdditionalProperties="$(PrivateComputeSharpBuildProperties)" GlobalPropertiesToRemove="SkipPluginDeploy" />
</ItemGroup>
</Project>
+1 -1
ファイルの表示
@@ -2,5 +2,5 @@ namespace Ukiyoe;
internal static class ShaderResourceUri
{
public static Uri Get(string shaderName) => new($"pack://application:,,,/Ukiyoe;component/Shaders/{shaderName}.cso", UriKind.Absolute);
public static Uri Get(string shaderName) => new($"pack://application:,,,/Ukiyoe;component/Resources/Shader/{shaderName}.cso", UriKind.Absolute);
}
+13 -26
ファイルの表示
@@ -5,32 +5,18 @@
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>1.0.0</Version>
<Version>1.2.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)Ukiyoe.cso" Link="Resources\Shader\Ukiyoe.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>
@@ -82,7 +68,11 @@
<Compile Include="..\YMM4-GitHubUpdateNotifier\GitHubUpdateNotifier\*.cs" LinkBase="GitHubUpdateNotifier" />
</ItemGroup>
<Import Project="..\YMM4-Telemetry\Telemetry.props" />
<ItemGroup>
<PackageReference Include="ComputeWeave" Version="2.3.0" />
<PackageReference Include="ILRepack" Version="2.0.46" PrivateAssets="all" ExcludeAssets="all" GeneratePathProperty="true" />
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.142" />
</ItemGroup>
@@ -96,20 +86,17 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ComputeSharp\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" SetConfiguration="Configuration=$(Configuration)" SetPlatform="Platform=AnyCPU" GlobalPropertiesToRemove="SkipPluginDeploy" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<ProjectReference Include="..\ComputeSharp\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" SetConfiguration="Configuration=$(Configuration)" SetPlatform="Platform=AnyCPU" GlobalPropertiesToRemove="SkipPluginDeploy" 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>
<Import Project="ComputeSharp.Reference.props" />
<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>
<ItemGroup>
<Folder Include="Shaders\" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent" 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;$(TargetPath)&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;&#xD;&#xA;copy &quot;$(TargetDir)Ukiyoe.ComputeSharp.dll&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;&#xD;&#xA;copy &quot;$(TargetDir)Ukiyoe.ComputeSharp.Core.dll&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;" />
<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)plugin\$(TargetFileName)&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;&#xD;&#xA;del &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\ComputeWeave.dll&quot; &gt; NUL 2&gt;&amp;1&#xD;&#xA;del &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\ComputeWeave.Core.dll&quot; &gt; NUL 2&gt;&amp;1" />
</Target>
</Project>
+12 -1
ファイルの表示
@@ -33,7 +33,18 @@ internal sealed class UkiyoeCustomEffect(IGraphicsDevicesAndContext devices)
protected override void UpdateConstants()
{
drawInformation?.SetPixelShaderConstantBuffer(_cb);
if (drawInformation is null)
return;
try
{
drawInformation.SetPixelShaderConstantBuffer(_cb);
}
catch (Exception exception)
{
UkiyoeTelemetry.Report(exception);
throw;
}
}
public override void MapInputRectsToOutputRect(
+12 -1
ファイルの表示
@@ -16,6 +16,7 @@ public sealed class UkiyoeEffect : VideoEffectBase
public UkiyoeEffect()
{
UkiyoeTelemetry.EnsureStartedOnce();
UkiyoeUpdateNotifier.EnsureCheckedOnce();
}
@@ -96,7 +97,17 @@ public sealed class UkiyoeEffect : VideoEffectBase
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices)
=> new UkiyoeEffectProcessor(devices, this);
{
try
{
return new UkiyoeEffectProcessor(devices, this);
}
catch (Exception exception)
{
UkiyoeTelemetry.Report(exception);
throw;
}
}
protected override IEnumerable<IAnimatable> GetAnimatables()
=> _animatables ??= [Amount, LineWidth, Coherence, LineDetail, LineStrength, Flatten, Misregistration, Baren, Paper];
+158 -57
ファイルの表示
@@ -1,4 +1,5 @@
using System.Numerics;
using ComputeWeave;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using YukkuriMovieMaker.Commons;
@@ -11,7 +12,11 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
{
private readonly IGraphicsDevicesAndContext _devices;
private readonly UkiyoeEffect _item;
private UkiyoeGpuInterop? _interop;
private ComputeExternalQueueScheduler? _scheduler;
private UkiyoeInteropProvider? _interopProvider;
private ComputeInteropDomain? _interopDomain;
private UkiyoeResourceSet? _resourceSet;
private ExternalTextureLease<ExternalDirect3D11TextureView>? _outputLease;
private UkiyoePipeline? _pipeline;
private UkiyoeCustomEffect? _effect;
private Crop? _outputCrop;
@@ -37,7 +42,20 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
public override DrawDescription Update(EffectDescription effectDescription)
{
if (IsPassThroughEffect || _effect is null || _outputCrop is null || _outputTransform is null || _outputTransformOutput is null || _interop is null || _pipeline is null || input is null)
try
{
return UpdateCore(effectDescription);
}
catch (Exception exception)
{
UkiyoeTelemetry.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;
@@ -109,8 +127,14 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
var itemWidth = (int)widthValue;
var itemHeight = (int)heightValue;
_interop.EnsureSource(itemWidth, itemHeight);
_interop.RenderInput(input, new Vortice.RawRectF(bounds.Left, bounds.Top, bounds.Left + itemWidth, bounds.Top + itemHeight));
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 pipelineParameters = new UkiyoePipeline.Parameters(
parameters.Quality,
@@ -128,24 +152,15 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
parameters.LineColor.B / 255f,
Math.Max(parameters.Seed, 0));
bool structureChanged;
_interop.BeginCompute();
try
{
structureChanged = _pipeline.Simulate(
_interop.SourceTexture,
canvasWidth,
canvasHeight,
margin,
margin,
itemWidth,
itemHeight,
in pipelineParameters);
}
finally
{
_interop.EndCompute();
}
var structureChanged = _pipeline.Simulate(
_resourceSet.GetSourceComputeBinding(),
canvasWidth,
canvasHeight,
margin,
margin,
itemWidth,
itemHeight,
in pipelineParameters);
if (!_pipeline.TryGetVisibleBounds(canvasWidth, canvasHeight, in pipelineParameters, out var rect))
{
@@ -156,9 +171,16 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
return effectDescription.DrawDescription;
}
if (!_interop.OutputCovers(rect.Width, rect.Height))
if (!OutputCovers(rect.Width, rect.Height))
_outputCrop.SetInput(0, null, true);
var outputChanged = _interop.EnsureOutput(rect.Width, rect.Height);
if (!EnsureOutput(rect.Width, rect.Height, out var outputChanged))
{
_effect.Amount = 0f;
_parameters = parameters;
_isFirst = true;
_hasRenderState = false;
return effectDescription.DrawDescription;
}
var renderState = new RenderState(
pipelineParameters.LineDetail,
pipelineParameters.LineStrength,
@@ -173,27 +195,22 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
rect);
if (structureChanged || outputChanged || !_hasOutput || !_hasRenderState || _renderState != renderState)
{
_interop.BeginCompute();
try
{
_pipeline.RenderVisible(
_interop.OutputTexture,
canvasWidth,
canvasHeight,
rect,
in pipelineParameters);
}
finally
{
_interop.EndCompute();
}
_pipeline.RenderVisible(
_resourceSet.GetOutputComputeBinding(),
canvasWidth,
canvasHeight,
rect,
in pipelineParameters);
_renderState = renderState;
_hasRenderState = true;
}
_outputLease ??= _resourceSet.AcquireOutputExternalViewLease();
if (outputChanged || !_hasOutput)
{
_outputCrop.SetInput(0, _interop.OutputBitmap, true);
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);
@@ -216,15 +233,93 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
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 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 interop = UkiyoeGpuInterop.TryCreate(devices);
if (interop is null)
return null;
var pipeline = UkiyoePipeline.TryCreate(interop.Device);
if (pipeline is null)
var scheduler = ComputeExternalQueueScheduler.Create();
var interopProvider = UkiyoeInteropProvider.TryCreate(devices, scheduler, out var interopDevice);
if (interopProvider is null || interopDevice is null)
{
interop.Dispose();
scheduler.Dispose();
return null;
}
_scheduler = scheduler;
try
{
_interopProvider = interopProvider;
_interopDomain = interopDevice.RegisterExternalDomain(interopProvider);
_resourceSet = UkiyoeResourceSet.Create(interopDevice, _interopDomain);
_pipeline = UkiyoePipeline.TryCreate(interopDevice);
}
catch (Exception exception)
{
UkiyoeTelemetry.Report(exception);
ReleaseInterop();
throw;
}
if (_pipeline is null)
{
ReleaseInterop();
return null;
}
@@ -240,8 +335,7 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
if (!effect.IsEnabled)
{
effect.Dispose();
pipeline.Dispose();
interop.Dispose();
ReleaseInterop();
return null;
}
outputCrop = new Crop(devices.DeviceContext);
@@ -253,8 +347,6 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
outputTransform.SetInput(0, outputCropOutput, true);
outputTransformOutput = outputTransform.Output;
output = effect.Output;
_interop = interop;
_pipeline = pipeline;
_effect = effect;
_outputCrop = outputCrop;
_outputCropOutput = outputCropOutput;
@@ -268,16 +360,16 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
disposer.Collect(output);
return output;
}
catch
catch (Exception exception)
{
UkiyoeTelemetry.Report(exception);
output?.Dispose();
outputTransformOutput?.Dispose();
outputTransform?.Dispose();
outputCropOutput?.Dispose();
outputCrop?.Dispose();
effect?.Dispose();
pipeline.Dispose();
interop.Dispose();
ReleaseInterop();
throw;
}
}
@@ -290,6 +382,19 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
}
protected override void ClearEffectChain()
{
try
{
ClearEffectChainCore();
}
catch (Exception exception)
{
UkiyoeTelemetry.Report(exception);
throw;
}
}
private void ClearEffectChainCore()
{
_effect?.SetInput(0, null, true);
_effect?.SetInput(1, null, true);
@@ -308,11 +413,7 @@ internal sealed class UkiyoeEffectProcessor : VideoEffectProcessorBase
if (disposing)
{
ClearEffectChain();
_interop?.WaitForIdle();
_pipeline?.Dispose();
_pipeline = null;
_interop?.Dispose();
_interop = null;
ReleaseInterop();
}
}
finally
+61 -291
ファイルの表示
@@ -1,323 +1,93 @@
using System.Runtime.InteropServices;
using ComputeSharp;
using ComputeSharp.Interop;
using Vortice;
using ComputeWeave;
using Vortice.Direct2D1;
using Vortice.Direct3D11;
using Vortice.DXGI;
using YukkuriMovieMaker.Commons;
using PixelFormat = Vortice.DCommon.PixelFormat;
namespace Ukiyoe;
internal sealed class UkiyoeGpuInterop : IDisposable
internal sealed class UkiyoeInteropProvider : ComputeExternalDirect3D11Provider
{
private static readonly Guid D3D12FenceGuid = new("0a753dcf-c4d8-4b91-adf6-be5a60d95a76");
private readonly GraphicsDevice _device;
private readonly ID3D11Device1 _d3dDevice;
private readonly ID3D11DeviceContext4 _d3dContext;
private readonly ID3D11Fence _fence;
private readonly ID2D1DeviceContext6 _renderContext;
private nint _d3d12Fence;
private ReadWriteTexture2D<Bgra32, Float4>? _sourceTexture;
private ReadWriteTexture2D<Bgra32, Float4>? _outputTexture;
private ID3D11Texture2D? _sourceD3D11Texture;
private ID3D11Texture2D? _outputD3D11Texture;
private ID2D1Bitmap1? _sourceBitmap;
private ID2D1Bitmap1? _outputBitmap;
private int _sourceWidth;
private int _sourceHeight;
private int _outputWidth;
private int _outputHeight;
private ulong _fenceValue;
private bool _computeActive;
private bool _disposed;
private UkiyoeGpuInterop(
GraphicsDevice device,
ID3D11Device1 d3dDevice,
ID3D11DeviceContext4 d3dContext,
ID3D11Fence fence,
private UkiyoeInteropProvider(
ID3D11Device1 device,
ID3D11DeviceContext4 context,
ID2D1DeviceContext6 renderContext,
nint d3d12Fence)
ComputeExternalQueueScheduler scheduler)
: base(device.NativePointer, context.NativePointer, renderContext.NativePointer, scheduler)
{
_device = device;
_d3dDevice = d3dDevice;
_d3dContext = d3dContext;
_fence = fence;
_renderContext = renderContext;
_d3d12Fence = d3d12Fence;
}
public GraphicsDevice Device => _device;
public ID2D1DeviceContext6 RenderContext => _renderContext;
public ReadWriteTexture2D<Bgra32, Float4> SourceTexture => _sourceTexture!;
public ReadWriteTexture2D<Bgra32, Float4> OutputTexture => _outputTexture!;
public ID2D1Bitmap1 OutputBitmap => _outputBitmap!;
public bool SourceMatches(int width, int height)
=> _sourceTexture is not null && _sourceWidth == width && _sourceHeight == height;
public bool OutputCovers(int width, int height)
=> _outputTexture is not null && _outputWidth >= width && _outputHeight >= height;
public static unsafe UkiyoeGpuInterop? TryCreate(IGraphicsDevicesAndContext devices)
public static UkiyoeInteropProvider? TryCreate(
IGraphicsDevicesAndContext devices,
ComputeExternalQueueScheduler scheduler,
out GraphicsDevice? graphicsDevice)
{
ID3D11Device1? d3dDevice = null;
ID3D11DeviceContext4? d3dContext = null;
ID3D11Fence? fence = null;
ArgumentNullException.ThrowIfNull(scheduler);
graphicsDevice = null;
ID3D11Device1? device = null;
ID3D11DeviceContext4? context = null;
ID2D1DeviceContext6? renderContext = null;
nint d3d12Fence = 0;
nint fenceHandle = 0;
try
{
var device = GetMatchingDevice(devices);
d3dDevice = devices.D3D.Device.QueryInterface<ID3D11Device1>();
d3dContext = devices.D3D.DeviceContext.QueryInterface<ID3D11DeviceContext4>();
using var d3dDevice5 = devices.D3D.Device.QueryInterface<ID3D11Device5>();
var fenceGuid = D3D12FenceGuid;
InteropServices.CreateSharedFence(device, &fenceGuid, (void**)&d3d12Fence, &fenceHandle);
fence = d3dDevice5.OpenSharedFence(fenceHandle);
renderContext = devices.D2D.Device.CreateDeviceContext(DeviceContextOptions.EnableMultithreadedOptimizations);
return new UkiyoeGpuInterop(device, d3dDevice, d3dContext, fence, renderContext, d3d12Fence);
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)
.QueryInterface<ID2D1DeviceContext6>();
var provider = new UkiyoeInteropProvider(device, context, renderContext, scheduler);
renderContext = null;
return provider;
}
catch
{
renderContext?.Dispose();
fence?.Dispose();
d3dContext?.Dispose();
d3dDevice?.Dispose();
if (d3d12Fence != 0)
Marshal.Release(d3d12Fence);
graphicsDevice = null;
return null;
}
finally
{
if (fenceHandle != 0)
CloseHandle(fenceHandle);
// 基底は自身の参照を取得済みなので、ここで取得した参照は返す。
// renderContext は成功時に provider が引き取るため null にしてある。
renderContext?.Dispose();
context?.Dispose();
device?.Dispose();
}
}
public bool EnsureResources(int width, int height)
protected override void DisposeCore()
{
var sourceChanged = EnsureSource(width, height);
var outputChanged = EnsureOutput(width, height);
return sourceChanged || outputChanged;
_renderContext.Dispose();
}
public bool EnsureSource(int width, int height)
{
if (SourceMatches(width, height))
return false;
if (_sourceTexture is not null)
WaitForIdle();
ReleaseSourceResources();
CreateSourceResources(width, height);
return true;
}
public bool EnsureOutput(int width, int height)
{
if (OutputCovers(width, height))
return false;
var capacityWidth = Math.Max(width, _outputWidth);
var capacityHeight = Math.Max(height, _outputHeight);
if (_outputTexture is not null)
WaitForIdle();
ReleaseOutputResources();
CreateOutputResources(capacityWidth, capacityHeight);
return true;
}
public void RenderInput(ID2D1Image source, RawRectF bounds)
{
_renderContext.BeginDraw();
_renderContext.Clear(null);
_renderContext.DrawImage(
source,
new System.Numerics.Vector2(-bounds.Left, -bounds.Top),
null,
InterpolationMode.NearestNeighbor,
CompositeMode.SourceCopy);
_renderContext.EndDraw();
}
public unsafe void BeginCompute()
{
if (_computeActive)
throw new InvalidOperationException();
var value = ++_fenceValue;
_d3dContext.Signal(_fence, value);
_d3dContext.Flush();
InteropServices.WaitForSharedFence(_device, (void*)_d3d12Fence, value);
_computeActive = true;
}
public unsafe void EndCompute()
{
if (!_computeActive)
throw new InvalidOperationException();
try
{
var value = ++_fenceValue;
InteropServices.SignalSharedFence(_device, (void*)_d3d12Fence, value);
_d3dContext.Wait(_fence, value);
}
finally
{
_computeActive = false;
}
}
public void WaitForIdle()
{
if (_computeActive)
throw new InvalidOperationException();
var value = ++_fenceValue;
_d3dContext.Signal(_fence, value);
_d3dContext.Flush();
_fence.SetEventOnCompletion(value, 0);
}
private static GraphicsDevice GetMatchingDevice(IGraphicsDevicesAndContext devices)
{
var adapterLuid = devices.DXGI.Adapter.Description.Luid.ToString();
using var enumerator = GraphicsDevice.QueryDevices(
device => string.Equals(device.Luid.ToString(), adapterLuid, StringComparison.Ordinal)).GetEnumerator();
if (!enumerator.MoveNext())
throw new NotSupportedException();
return enumerator.Current;
}
private void CreateSourceResources(int width, int height)
{
ReadWriteTexture2D<Bgra32, Float4>? sourceTexture = null;
ID3D11Texture2D? sourceD3D11Texture = null;
ID2D1Bitmap1? sourceBitmap = null;
nint sourceHandle = 0;
try
{
sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(_device, width, height);
sourceHandle = InteropServices.CreateSharedHandle(sourceTexture);
sourceD3D11Texture = _d3dDevice.OpenSharedResource1<ID3D11Texture2D>(sourceHandle);
using var sourceSurface = sourceD3D11Texture.QueryInterface<IDXGISurface>();
var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
sourceBitmap = _renderContext.CreateBitmapFromDxgiSurface(
sourceSurface,
new BitmapProperties1(pixelFormat, 96f, 96f, BitmapOptions.Target));
_renderContext.Target = sourceBitmap;
_sourceTexture = sourceTexture;
_sourceD3D11Texture = sourceD3D11Texture;
_sourceBitmap = sourceBitmap;
_sourceWidth = width;
_sourceHeight = height;
sourceTexture = null;
sourceD3D11Texture = null;
sourceBitmap = null;
}
finally
{
if (sourceHandle != 0)
CloseHandle(sourceHandle);
sourceBitmap?.Dispose();
sourceD3D11Texture?.Dispose();
sourceTexture?.Dispose();
}
}
private void CreateOutputResources(int width, int height)
{
ReadWriteTexture2D<Bgra32, Float4>? outputTexture = null;
ID3D11Texture2D? outputD3D11Texture = null;
ID2D1Bitmap1? outputBitmap = null;
nint outputHandle = 0;
try
{
outputTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(_device, width, height);
outputHandle = InteropServices.CreateSharedHandle(outputTexture);
outputD3D11Texture = _d3dDevice.OpenSharedResource1<ID3D11Texture2D>(outputHandle);
using var outputSurface = outputD3D11Texture.QueryInterface<IDXGISurface>();
var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
outputBitmap = _renderContext.CreateBitmapFromDxgiSurface(
outputSurface,
new BitmapProperties1(pixelFormat, 96f, 96f, BitmapOptions.None));
_outputTexture = outputTexture;
_outputD3D11Texture = outputD3D11Texture;
_outputBitmap = outputBitmap;
_outputWidth = width;
_outputHeight = height;
outputTexture = null;
outputD3D11Texture = null;
outputBitmap = null;
}
finally
{
if (outputHandle != 0)
CloseHandle(outputHandle);
outputBitmap?.Dispose();
outputD3D11Texture?.Dispose();
outputTexture?.Dispose();
}
}
private void ReleaseSourceResources()
{
_renderContext.Target = null;
_sourceBitmap?.Dispose();
_sourceD3D11Texture?.Dispose();
_sourceTexture?.Dispose();
_sourceBitmap = null;
_sourceD3D11Texture = null;
_sourceTexture = null;
_sourceWidth = 0;
_sourceHeight = 0;
}
private void ReleaseOutputResources()
{
_outputBitmap?.Dispose();
_outputD3D11Texture?.Dispose();
_outputTexture?.Dispose();
_outputBitmap = null;
_outputD3D11Texture = null;
_outputTexture = null;
_outputWidth = 0;
_outputHeight = 0;
}
public void Dispose()
{
if (_disposed)
return;
try
{
WaitForIdle();
}
finally
{
_disposed = true;
ReleaseOutputResources();
ReleaseSourceResources();
_renderContext.Dispose();
_fence.Dispose();
_d3dContext.Dispose();
_d3dDevice.Dispose();
if (_d3d12Fence != 0)
{
Marshal.Release(_d3d12Fence);
_d3d12Fence = 0;
}
}
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(nint handle);
}
[ComputeInteropResourceSet]
internal sealed partial class UkiyoeResourceSet
{
[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;
}
+42 -11
ファイルの表示
@@ -1,4 +1,4 @@
using ComputeSharp;
using ComputeWeave;
namespace Ukiyoe;
@@ -326,7 +326,7 @@ internal readonly partial struct EtfShader(
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[ThreadGroupSize(8, 8, 1)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct FlattenShader(
ReadWriteBuffer<Float4> colorIn,
@@ -347,19 +347,50 @@ internal readonly partial struct FlattenShader(
private readonly int gridHeight = gridHeight;
private readonly float beta = beta;
[GroupShared(144)]
private static readonly Float4[] tileColor = null!;
[GroupShared(144)]
private static readonly float[] tileGradient = null!;
[GroupShared(144)]
private static readonly Float4[] tileIterate = null!;
public void Execute()
{
var originX = GridIds.X * UkiyoeSettings.FlattenGroupDim - UkiyoeSettings.FlattenRadius;
var originY = GridIds.Y * UkiyoeSettings.FlattenGroupDim - UkiyoeSettings.FlattenRadius;
for (var slot = GroupIds.Index; slot < UkiyoeSettings.FlattenTileCount; slot += UkiyoeSettings.FlattenGroupDim * UkiyoeSettings.FlattenGroupDim)
{
var tx = originX + slot % UkiyoeSettings.FlattenTileDim;
var ty = originY + slot / UkiyoeSettings.FlattenTileDim;
if (tx >= 0 && tx < gridWidth && ty >= 0 && ty < gridHeight)
{
var sampleIndex = ty * gridWidth + tx;
tileColor[slot] = colorIn[sampleIndex];
tileGradient[slot] = gradientMagnitude[sampleIndex];
tileIterate[slot] = iterateIn[sampleIndex];
}
else
{
tileColor[slot] = new Float4(0f, 0f, 0f, 0f);
tileGradient[slot] = 0f;
tileIterate[slot] = new Float4(0f, 0f, 0f, 0f);
}
}
Hlsl.GroupMemoryBarrierWithGroupSync();
var gx = ThreadIds.X;
var gy = ThreadIds.Y;
if (gx >= gridWidth || gy >= gridHeight)
return;
var index = gy * gridWidth + gx;
var original = colorIn[index];
var current = iterateIn[index];
var centerTile = (GroupIds.Y + UkiyoeSettings.FlattenRadius) * UkiyoeSettings.FlattenTileDim + GroupIds.X + UkiyoeSettings.FlattenRadius;
var original = tileColor[centerTile];
var current = tileIterate[centerTile];
var centerFeature = UkiyoeShaderMath.AffinityFeature(original);
var maxGradient = Hlsl.Max(Hlsl.AsFloat(scratch[UkiyoeSettings.ScratchMaxGradient]), 1e-6f);
var centerGradient = gradientMagnitude[index] / maxGradient;
var centerGradient = tileGradient[centerTile] / maxGradient;
var invTwoSigmaSquared = 0.5f / (UkiyoeSettings.FlattenSigma * UkiyoeSettings.FlattenSigma);
var numerator = original * beta;
@@ -374,15 +405,15 @@ internal readonly partial struct FlattenShader(
var ny = gy + dy;
if (nx < 0 || nx >= gridWidth || ny < 0 || ny >= gridHeight)
continue;
var neighborIndex = ny * gridWidth + nx;
var neighborOriginal = colorIn[neighborIndex];
var neighborTile = centerTile + dy * UkiyoeSettings.FlattenTileDim + dx;
var neighborOriginal = tileColor[neighborTile];
var feature = centerFeature - UkiyoeShaderMath.AffinityFeature(neighborOriginal);
var alphaDelta = original.W - neighborOriginal.W;
var featureDistance = feature.X * feature.X + feature.Y * feature.Y + feature.Z * feature.Z + alphaDelta * alphaDelta;
var neighborGradient = gradientMagnitude[neighborIndex] / maxGradient;
var neighborGradient = tileGradient[neighborTile] / maxGradient;
var edge = Hlsl.Max(centerGradient, neighborGradient);
var affinity = Hlsl.Exp(-Hlsl.Max(featureDistance, UkiyoeSettings.FlattenGradientWeight * edge * edge) * invTwoSigmaSquared);
var neighborCurrent = iterateIn[neighborIndex];
var neighborCurrent = tileIterate[neighborTile];
var difference = current - neighborCurrent;
var l1 = Hlsl.Abs(difference.X) + Hlsl.Abs(difference.Y) + Hlsl.Abs(difference.Z) + Hlsl.Abs(difference.W);
var weight = affinity / Hlsl.Max(l1, UkiyoeSettings.FlattenEpsilon);
@@ -391,7 +422,7 @@ internal readonly partial struct FlattenShader(
}
}
iterateOut[index] = numerator / denominator;
iterateOut[gy * gridWidth + gx] = numerator / denominator;
}
}
+114 -188
ファイルの表示
@@ -1,23 +1,17 @@
using System.Runtime.InteropServices;
using ComputeSharp;
using ComputeWeave;
namespace Ukiyoe;
internal sealed class UkiyoePipeline : IDisposable
{
private readonly GraphicsDevice _device;
private readonly UkiyoePipelineHost _host;
private readonly ReadWriteBuffer<int> _scratch;
private readonly ReadBackBuffer<int> _scratchReadBack;
private ReadWriteBuffer<Float4>? _colorIn;
private ReadWriteBuffer<Float4>? _colorA;
private ReadWriteBuffer<Float4>? _colorB;
private ReadWriteBuffer<float>? _gray;
private ReadWriteBuffer<float>? _gradientMagnitude;
private ReadWriteBuffer<float>? _response;
private ReadWriteBuffer<float>? _line;
private ReadWriteBuffer<Float2>? _tangentA;
private ReadWriteBuffer<Float2>? _tangentB;
private StructureKey? _structureKey;
private PrefixKey? _prefixKey;
private FlattenKey? _flattenKey;
private LinesKey? _linesKey;
private int _cachedLitCount;
private int _cachedBoundsMinX;
private int _cachedBoundsMinY;
@@ -30,9 +24,10 @@ internal sealed class UkiyoePipeline : IDisposable
private int _packedWidth;
private int _packedHeight;
private UkiyoePipeline(GraphicsDevice device)
private UkiyoePipeline(GraphicsDevice device, UkiyoePipelineHost host)
{
_device = device;
_host = host;
_scratch = device.AllocateReadWriteBuffer<int>(UkiyoeSettings.ScratchLength);
_scratchReadBack = device.AllocateReadBackBuffer<int>(UkiyoeSettings.ScratchLength);
}
@@ -41,7 +36,7 @@ internal sealed class UkiyoePipeline : IDisposable
{
try
{
return new UkiyoePipeline(GraphicsDevice.GetDefault());
return TryCreate(GraphicsDevice.GetDefault());
}
catch
{
@@ -51,12 +46,16 @@ internal sealed class UkiyoePipeline : IDisposable
public static UkiyoePipeline? TryCreate(GraphicsDevice device)
{
UkiyoePipelineHost? host = null;
try
{
return new UkiyoePipeline(device);
host = UkiyoePipelineHost.Create(device, UkiyoeSettings.MaximumPendingSubmissions);
return new UkiyoePipeline(device, host);
}
catch
{
host?.Dispose();
host?.WaitForDisposal();
return null;
}
}
@@ -74,8 +73,7 @@ internal sealed class UkiyoePipeline : IDisposable
var sourceTexture = _packedSource!;
var outputTexture = _packedOutput!;
sourceTexture.CopyFrom(MemoryMarshal.Cast<int, Bgra32>(source[..pixelCount]));
using (ComputeContext context = _device.CreateComputeContext())
RecordFullPipeline(in context, sourceTexture, outputTexture, width, height, in parameters);
SubmitFullPipeline(sourceTexture, outputTexture, width, height, in parameters).Wait();
outputTexture.CopyTo(MemoryMarshal.Cast<int, Bgra32>(destination[..pixelCount]));
}
@@ -87,9 +85,7 @@ internal sealed class UkiyoePipeline : IDisposable
in Parameters parameters)
{
EnsureGridFor(width, height, parameters.Quality);
using ComputeContext context = _device.CreateComputeContext();
RecordFullPipeline(in context, source, destination, width, height, in parameters);
context.Submit();
_ = SubmitFullPipeline(source, destination, width, height, in parameters);
}
internal void ProcessSharedAndWait(
@@ -100,8 +96,7 @@ internal sealed class UkiyoePipeline : IDisposable
in Parameters parameters)
{
EnsureGridFor(width, height, parameters.Quality);
using ComputeContext context = _device.CreateComputeContext();
RecordFullPipeline(in context, source, destination, width, height, in parameters);
SubmitFullPipeline(source, destination, width, height, in parameters).Wait();
}
internal bool Simulate(
@@ -113,14 +108,37 @@ internal sealed class UkiyoePipeline : IDisposable
int sourceWidth,
int sourceHeight,
in Parameters parameters)
{
var derived = BeginSimulate(canvasWidth, canvasHeight, in parameters);
_host.RecordSilhouetteAndMaskHash(
source, _scratch, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, _gridWidth, _gridHeight, in derived).Wait();
return CompleteSimulate(canvasWidth, canvasHeight, in parameters, in derived);
}
internal bool Simulate(
ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> source,
int canvasWidth,
int canvasHeight,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
in Parameters parameters)
{
var derived = BeginSimulate(canvasWidth, canvasHeight, in parameters);
_host.RecordSharedSilhouetteAndMaskHash(
source, _scratch, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, _gridWidth, _gridHeight, in derived).Wait();
return CompleteSimulate(canvasWidth, canvasHeight, in parameters, in derived);
}
private DerivedValues BeginSimulate(int canvasWidth, int canvasHeight, in Parameters parameters)
{
EnsureGridFor(canvasWidth, canvasHeight, parameters.Quality);
var derived = Derive(canvasWidth, canvasHeight, in parameters);
using (ComputeContext context = _device.CreateComputeContext())
{
RecordSilhouetteStage(in context, source, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, in derived);
RecordMaskHashStage(in context);
}
return Derive(canvasWidth, canvasHeight, in parameters);
}
private bool CompleteSimulate(int canvasWidth, int canvasHeight, in Parameters parameters, in DerivedValues derived)
{
_scratchReadBack.CopyFrom(_scratch);
var hashed = _scratchReadBack.Span;
_cachedLitCount = hashed[UkiyoeSettings.ScratchLitCount];
@@ -128,22 +146,36 @@ internal sealed class UkiyoePipeline : IDisposable
_cachedBoundsMinY = hashed[UkiyoeSettings.ScratchBoundsMinY];
_cachedBoundsMaxX = hashed[UkiyoeSettings.ScratchBoundsMaxX];
_cachedBoundsMaxY = hashed[UkiyoeSettings.ScratchBoundsMaxY];
var key = new StructureKey(
var prefixKey = new PrefixKey(
hashed[UkiyoeSettings.ScratchMaskHashSum],
hashed[UkiyoeSettings.ScratchMaskHashMix],
canvasWidth,
canvasHeight,
parameters.Quality,
parameters.LineWidth,
parameters.Coherence,
parameters.LineDetail,
parameters.Flatten);
if (_structureKey == key)
parameters.Quality);
var flattenKey = new FlattenKey(prefixKey, parameters.Flatten);
var linesKey = new LinesKey(prefixKey, parameters.LineWidth, parameters.Coherence, parameters.LineDetail);
if (_prefixKey == prefixKey && _flattenKey == flattenKey && _linesKey == linesKey)
return false;
using (ComputeContext context = _device.CreateComputeContext())
RecordStructureStage(in context, in derived);
_structureKey = key;
if (_prefixKey != prefixKey)
{
_host.RecordStructurePrefix(_scratch, _gridWidth, _gridHeight, in derived).Wait();
_prefixKey = prefixKey;
}
if (_flattenKey != flattenKey)
{
_host.RecordFlatten(_scratch, _gridWidth, _gridHeight, in derived).Wait();
_flattenKey = flattenKey;
}
if (_linesKey != linesKey)
{
_host.RecordLines(_gridWidth, _gridHeight, in derived).Wait();
_linesKey = linesKey;
}
return true;
}
@@ -177,119 +209,32 @@ internal sealed class UkiyoePipeline : IDisposable
in Parameters parameters)
{
var derived = Derive(canvasWidth, canvasHeight, in parameters);
using ComputeContext context = _device.CreateComputeContext();
RecordRenderStage(in context, output, rect, in derived, in parameters);
_host.RecordRender(output, in rect, _gridWidth, _gridHeight, in derived, in parameters).Wait();
}
private void RecordFullPipeline(
in ComputeContext context,
internal void RenderVisible(
ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> output,
int canvasWidth,
int canvasHeight,
PixelRect rect,
in Parameters parameters)
{
var derived = Derive(canvasWidth, canvasHeight, in parameters);
_host.RecordSharedRender(output, in rect, _gridWidth, _gridHeight, in derived, in parameters).Wait();
}
private ComputeSubmission SubmitFullPipeline(
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> output,
int width,
int height,
in Parameters parameters)
{
_structureKey = null;
_prefixKey = null;
_flattenKey = null;
_linesKey = null;
var derived = Derive(width, height, in parameters);
RecordSilhouetteStage(in context, source, 0, 0, width, height, in derived);
RecordStructureStage(in context, in derived);
RecordRenderStage(in context, output, new PixelRect(0, 0, width, height), in derived, in parameters);
}
private void RecordSilhouetteStage(
in ComputeContext context,
ReadWriteTexture2D<Bgra32, Float4> source,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
in DerivedValues derived)
{
context.For(_gridWidth, _gridHeight, new SilhouetteShader(
source, _colorIn!, _gray!, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, _gridWidth, _gridHeight, derived.CellSize));
context.Barrier(_colorIn!);
context.Barrier(_gray!);
}
private void RecordMaskHashStage(in ComputeContext context)
{
context.For(1, new MaskHashResetShader(_scratch));
context.Barrier(_scratch);
context.For(_gridWidth, _gridHeight, new MaskHashShader(_colorIn!, _scratch, _gridWidth, _gridHeight));
context.Barrier(_scratch);
}
private void RecordStructureStage(in ComputeContext context, in DerivedValues derived)
{
var gridWidth = _gridWidth;
var gridHeight = _gridHeight;
context.For(1, new InitScratchShader(_scratch));
context.Barrier(_scratch);
context.For(gridWidth, gridHeight, new GradientShader(_gray!, _tangentA!, _gradientMagnitude!, _scratch, gridWidth, gridHeight));
context.Barrier(_tangentA!);
context.Barrier(_gradientMagnitude!);
context.Barrier(_scratch);
var tangentIn = _tangentA!;
var tangentOut = _tangentB!;
for (var iteration = 0; iteration < derived.EtfIterations; iteration++)
{
context.For(gridWidth, gridHeight, new EtfShader(tangentIn, tangentOut, _gradientMagnitude!, _scratch, gridWidth, gridHeight));
context.Barrier(tangentOut);
(tangentIn, tangentOut) = (tangentOut, tangentIn);
}
var tangent = tangentIn;
context.For(gridWidth, gridHeight, new CopyColorShader(_colorIn!, _colorA!, gridWidth, gridHeight));
context.Barrier(_colorA!);
var iterateIn = _colorA!;
var iterateOut = _colorB!;
for (var iteration = 0; iteration < derived.FlattenIterations; iteration++)
{
context.For(gridWidth, gridHeight, new FlattenShader(
_colorIn!, iterateIn, iterateOut, _gradientMagnitude!, _scratch, gridWidth, gridHeight, derived.FlattenBeta));
context.Barrier(iterateOut);
(iterateIn, iterateOut) = (iterateOut, iterateIn);
}
for (var iteration = 0; iteration < derived.FdogIterations; iteration++)
{
context.For(gridWidth, gridHeight, new DogShader(
_gray!, tangent, _response!, gridWidth, gridHeight, derived.LineSigmaCells, derived.DogExtent));
context.Barrier(_response!);
context.For(gridWidth, gridHeight, new FlowAccumulateShader(
_response!, tangent, _line!, gridWidth, gridHeight, derived.FlowSigma, derived.FlowExtent));
context.Barrier(_line!);
if (iteration < derived.FdogIterations - 1)
{
context.For(gridWidth, gridHeight, new SuperimposeShader(_line!, _gray!, gridWidth, gridHeight, derived.LineThreshold));
context.Barrier(_gray!);
}
}
}
private void RecordRenderStage(
in ComputeContext context,
ReadWriteTexture2D<Bgra32, Float4> output,
PixelRect rect,
in DerivedValues derived,
in Parameters parameters)
{
context.For(rect.Width, rect.Height, new RenderShader(
_colorA!, _line!, output,
rect.X, rect.Y, rect.Width, rect.Height, _gridWidth, _gridHeight,
derived.CellSize,
UkiyoeSettings.ClampPaletteLevels(parameters.PaletteLevels),
derived.ShiftPixels,
Math.Clamp(parameters.Baren, 0f, 1f),
Math.Clamp(parameters.Paper, 0f, 1f),
derived.LineThreshold,
Math.Clamp(parameters.LineStrength, 0f, 1f),
parameters.LineColorR,
parameters.LineColorG,
parameters.LineColorB,
parameters.Seed));
return _host.RecordFullPipeline(source, output, _scratch, width, height, _gridWidth, _gridHeight, in derived, in parameters);
}
private DerivedValues Derive(int width, int height, in Parameters parameters)
@@ -326,22 +271,21 @@ internal sealed class UkiyoePipeline : IDisposable
if (_gridWidth == gridWidth && _gridHeight == gridHeight)
return;
DisposeGridBuffers();
var gridLength = gridWidth * gridHeight;
_colorIn = _device.AllocateReadWriteBuffer<Float4>(gridLength);
_colorA = _device.AllocateReadWriteBuffer<Float4>(gridLength);
_colorB = _device.AllocateReadWriteBuffer<Float4>(gridLength);
_gray = _device.AllocateReadWriteBuffer<float>(gridLength);
_gradientMagnitude = _device.AllocateReadWriteBuffer<float>(gridLength);
_response = _device.AllocateReadWriteBuffer<float>(gridLength);
_line = _device.AllocateReadWriteBuffer<float>(gridLength);
_tangentA = _device.AllocateReadWriteBuffer<Float2>(gridLength);
_tangentB = _device.AllocateReadWriteBuffer<Float2>(gridLength);
if (!_host.TryEnsureGrid(
new UkiyoeGridResources.Plan(
gridLength, gridLength, gridLength, gridLength, gridLength, gridLength, gridLength, gridLength, gridLength),
out _))
throw new InvalidOperationException();
_cachedLitCount = 0;
_cachedBoundsMinX = int.MaxValue;
_cachedBoundsMinY = int.MaxValue;
_cachedBoundsMaxX = int.MinValue;
_cachedBoundsMaxY = int.MinValue;
_prefixKey = null;
_flattenKey = null;
_linesKey = null;
_gridWidth = gridWidth;
_gridHeight = gridHeight;
}
@@ -359,63 +303,45 @@ internal sealed class UkiyoePipeline : IDisposable
_packedHeight = height;
}
private void DisposeGridBuffers()
{
_colorIn?.Dispose();
_colorA?.Dispose();
_colorB?.Dispose();
_gray?.Dispose();
_gradientMagnitude?.Dispose();
_response?.Dispose();
_line?.Dispose();
_tangentA?.Dispose();
_tangentB?.Dispose();
_colorIn = null;
_colorA = null;
_colorB = null;
_gray = null;
_gradientMagnitude = null;
_response = null;
_line = null;
_tangentA = null;
_tangentB = null;
_cachedLitCount = 0;
_cachedBoundsMinX = int.MaxValue;
_cachedBoundsMinY = int.MaxValue;
_cachedBoundsMaxX = int.MinValue;
_cachedBoundsMaxY = int.MinValue;
_structureKey = null;
_gridWidth = 0;
_gridHeight = 0;
}
public void Dispose()
{
DisposeGridBuffers();
_host.Dispose();
_host.WaitForDisposal();
_packedSource?.Dispose();
_packedOutput?.Dispose();
_packedSource = null;
_packedOutput = null;
_packedWidth = 0;
_packedHeight = 0;
_prefixKey = null;
_flattenKey = null;
_linesKey = null;
_gridWidth = 0;
_gridHeight = 0;
_scratchReadBack.Dispose();
_scratch.Dispose();
}
internal readonly record struct PixelRect(int X, int Y, int Width, int Height);
private readonly record struct StructureKey(
private readonly record struct PrefixKey(
int MaskHashSum,
int MaskHashMix,
int CanvasWidth,
int CanvasHeight,
UkiyoeQuality Quality,
float LineWidth,
float Coherence,
float LineDetail,
UkiyoeQuality Quality);
private readonly record struct FlattenKey(
PrefixKey Prefix,
float Flatten);
private readonly record struct DerivedValues(
private readonly record struct LinesKey(
PrefixKey Prefix,
float LineWidth,
float Coherence,
float LineDetail);
internal readonly record struct DerivedValues(
float CellSize,
int EtfIterations,
int FdogIterations,
+340
ファイルの表示
@@ -0,0 +1,340 @@
using ComputeWeave;
namespace Ukiyoe;
[ComputeResourceGroup]
internal sealed partial class UkiyoeGridResources
{
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<Float4> ColorIn { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<Float4> ColorA { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<Float4> ColorB { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> Gray { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> GradientMagnitude { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> Response { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> Line { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<Float2> TangentA { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<Float2> TangentB { get; }
}
[ComputePipelineHost("_device", 1)]
internal sealed partial class UkiyoePipelineHost
{
private readonly GraphicsDevice _device;
[ComputePipelineResource(ComputeResourceAccess.ReadWrite, ComputeResourceRecovery.Recompute)]
private readonly ComputeResourceGroupSlot<UkiyoeGridResources> _grid = new();
[ComputePipeline]
private void RecordFullPipeline(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] UkiyoeGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> output,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
int width,
int height,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived,
in UkiyoePipeline.Parameters parameters)
{
_ = _device;
RecordSilhouetteStage(in context, grid, source, 0, 0, width, height, gridWidth, gridHeight, in derived);
RecordStructureStage(in context, grid, scratch, gridWidth, gridHeight, in derived);
RecordRenderStage(in context, grid, output, new UkiyoePipeline.PixelRect(0, 0, width, height), gridWidth, gridHeight, in derived, in parameters);
}
[ComputePipeline]
private void RecordSilhouetteAndMaskHash(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] UkiyoeGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
_ = _device;
RecordSilhouetteStage(in context, grid, source, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, gridWidth, gridHeight, in derived);
RecordMaskHashStage(in context, grid, scratch, gridWidth, gridHeight);
}
[ComputePipeline]
[ComputeInterop]
private void RecordSharedSilhouetteAndMaskHash(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] UkiyoeGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
_ = _device;
RecordSilhouetteStage(in context, grid, source, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, gridWidth, gridHeight, in derived);
RecordMaskHashStage(in context, grid, scratch, gridWidth, gridHeight);
}
[ComputePipeline]
[ComputeInterop]
private void RecordSharedRender(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] UkiyoeGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> output,
in UkiyoePipeline.PixelRect rect,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived,
in UkiyoePipeline.Parameters parameters)
{
_ = _device;
RecordRenderStage(in context, grid, output, rect, gridWidth, gridHeight, in derived, in parameters);
}
[ComputePipeline]
private void RecordStructure(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] UkiyoeGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
_ = _device;
RecordStructureStage(in context, grid, scratch, gridWidth, gridHeight, in derived);
}
[ComputePipeline]
private void RecordStructurePrefix(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] UkiyoeGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
_ = _device;
RecordStructurePrefixStage(in context, grid, scratch, gridWidth, gridHeight, in derived);
}
[ComputePipeline]
private void RecordFlatten(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] UkiyoeGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
_ = _device;
RecordFlattenStage(in context, grid, scratch, gridWidth, gridHeight, in derived);
}
[ComputePipeline]
private void RecordLines(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] UkiyoeGridResources grid,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
_ = _device;
RecordLinesStage(in context, grid, gridWidth, gridHeight, in derived);
}
[ComputePipeline]
private void RecordRender(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] UkiyoeGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> output,
in UkiyoePipeline.PixelRect rect,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived,
in UkiyoePipeline.Parameters parameters)
{
_ = _device;
RecordRenderStage(in context, grid, output, rect, gridWidth, gridHeight, in derived, in parameters);
}
private static void RecordSilhouetteStage(
in ComputeContext context,
UkiyoeGridResources grid,
ReadWriteTexture2D<Bgra32, Float4> source,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
context.For(gridWidth, gridHeight, new SilhouetteShader(
source, grid.ColorIn, grid.Gray, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, gridWidth, gridHeight, derived.CellSize));
context.Barrier(grid.ColorIn);
context.Barrier(grid.Gray);
}
private static void RecordMaskHashStage(
in ComputeContext context,
UkiyoeGridResources grid,
ReadWriteBuffer<int> scratch,
int gridWidth,
int gridHeight)
{
context.For(1, new MaskHashResetShader(scratch));
context.Barrier(scratch);
context.For(gridWidth, gridHeight, new MaskHashShader(grid.ColorIn, scratch, gridWidth, gridHeight));
context.Barrier(scratch);
}
private static void RecordStructureStage(
in ComputeContext context,
UkiyoeGridResources grid,
ReadWriteBuffer<int> scratch,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
RecordStructurePrefixStage(in context, grid, scratch, gridWidth, gridHeight, in derived);
RecordFlattenStage(in context, grid, scratch, gridWidth, gridHeight, in derived);
RecordLinesStage(in context, grid, gridWidth, gridHeight, in derived);
}
private static ReadWriteBuffer<Float2> GetTangent(UkiyoeGridResources grid, in UkiyoePipeline.DerivedValues derived)
{
return (derived.EtfIterations & 1) == 0 ? grid.TangentA : grid.TangentB;
}
private static void RecordStructurePrefixStage(
in ComputeContext context,
UkiyoeGridResources grid,
ReadWriteBuffer<int> scratch,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
context.For(1, new InitScratchShader(scratch));
context.Barrier(scratch);
context.For(gridWidth, gridHeight, new GradientShader(grid.Gray, grid.TangentA, grid.GradientMagnitude, scratch, gridWidth, gridHeight));
context.Barrier(grid.TangentA);
context.Barrier(grid.GradientMagnitude);
context.Barrier(scratch);
var tangentIn = grid.TangentA;
var tangentOut = grid.TangentB;
for (var iteration = 0; iteration < derived.EtfIterations; iteration++)
{
context.For(gridWidth, gridHeight, new EtfShader(tangentIn, tangentOut, grid.GradientMagnitude, scratch, gridWidth, gridHeight));
context.Barrier(tangentOut);
(tangentIn, tangentOut) = (tangentOut, tangentIn);
}
}
private static void RecordFlattenStage(
in ComputeContext context,
UkiyoeGridResources grid,
ReadWriteBuffer<int> scratch,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
context.For(gridWidth, gridHeight, new CopyColorShader(grid.ColorIn, grid.ColorA, gridWidth, gridHeight));
context.Barrier(grid.ColorA);
var flattenDispatchWidth = (gridWidth + UkiyoeSettings.FlattenGroupDim - 1) & ~(UkiyoeSettings.FlattenGroupDim - 1);
var flattenDispatchHeight = (gridHeight + UkiyoeSettings.FlattenGroupDim - 1) & ~(UkiyoeSettings.FlattenGroupDim - 1);
var iterateIn = grid.ColorA;
var iterateOut = grid.ColorB;
for (var iteration = 0; iteration < derived.FlattenIterations; iteration++)
{
context.For(flattenDispatchWidth, flattenDispatchHeight, new FlattenShader(
grid.ColorIn, iterateIn, iterateOut, grid.GradientMagnitude, scratch, gridWidth, gridHeight, derived.FlattenBeta));
context.Barrier(iterateOut);
(iterateIn, iterateOut) = (iterateOut, iterateIn);
}
}
private static void RecordLinesStage(
in ComputeContext context,
UkiyoeGridResources grid,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived)
{
var tangent = GetTangent(grid, in derived);
for (var iteration = 0; iteration < derived.FdogIterations; iteration++)
{
context.For(gridWidth, gridHeight, new DogShader(
grid.Gray, tangent, grid.Response, gridWidth, gridHeight, derived.LineSigmaCells, derived.DogExtent));
context.Barrier(grid.Response);
context.For(gridWidth, gridHeight, new FlowAccumulateShader(
grid.Response, tangent, grid.Line, gridWidth, gridHeight, derived.FlowSigma, derived.FlowExtent));
context.Barrier(grid.Line);
if (iteration < derived.FdogIterations - 1)
{
context.For(gridWidth, gridHeight, new SuperimposeShader(grid.Line, grid.Gray, gridWidth, gridHeight, derived.LineThreshold));
context.Barrier(grid.Gray);
}
}
}
private static void RecordRenderStage(
in ComputeContext context,
UkiyoeGridResources grid,
ReadWriteTexture2D<Bgra32, Float4> output,
in UkiyoePipeline.PixelRect rect,
int gridWidth,
int gridHeight,
in UkiyoePipeline.DerivedValues derived,
in UkiyoePipeline.Parameters parameters)
{
context.For(rect.Width, rect.Height, new RenderShader(
grid.ColorA, grid.Line, output,
rect.X, rect.Y, rect.Width, rect.Height, gridWidth, gridHeight,
derived.CellSize,
UkiyoeSettings.ClampPaletteLevels(parameters.PaletteLevels),
derived.ShiftPixels,
Math.Clamp(parameters.Baren, 0f, 1f),
Math.Clamp(parameters.Paper, 0f, 1f),
derived.LineThreshold,
Math.Clamp(parameters.LineStrength, 0f, 1f),
parameters.LineColorR,
parameters.LineColorG,
parameters.LineColorB,
parameters.Seed));
}
}
+4
ファイルの表示
@@ -23,6 +23,9 @@ internal static class UkiyoeSettings
public const float FlattenLumaScale = 0.3f;
public const float FlattenGradientWeight = 0.4f;
public const int FlattenRadius = 2;
public const int FlattenGroupDim = 8;
public const int FlattenTileDim = FlattenGroupDim + 2 * FlattenRadius;
public const int FlattenTileCount = FlattenTileDim * FlattenTileDim;
public const float QuantizeEdgeWidth = 0.18f;
public const float ChromaScale = 0.9f;
public const float MaximumShiftPixels = 10f;
@@ -46,6 +49,7 @@ internal static class UkiyoeSettings
public const int ScratchBoundsMaxY = 5;
public const int ScratchMaskHashSum = 6;
public const int ScratchMaskHashMix = 7;
public const int MaximumPendingSubmissions = 32;
public static QualitySettings GetQuality(UkiyoeQuality quality)
=> quality switch
+102
ファイルの表示
@@ -0,0 +1,102 @@
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using System.Windows.Threading;
using Telemetry;
namespace Ukiyoe;
internal static class UkiyoeTelemetry
{
private const int MaxChainLength = 5;
private const int MaxFrames = 100;
private static readonly Assembly Own = typeof(UkiyoeTelemetry).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;
}
}
+4 -2
ファイルの表示
@@ -13,7 +13,7 @@ internal static class UkiyoeUpdateNotifier
public static void EnsureCheckedOnce()
{
if (Interlocked.Exchange(ref _started, 1) != 0)
if (Application.Current is null || Interlocked.Exchange(ref _started, 1) != 0)
return;
_ = RunAsync();
}
@@ -31,8 +31,10 @@ internal static class UkiyoeUpdateNotifier
};
await new Notifier(Owner, Repository, options).NotifyAsync().ConfigureAwait(false);
}
catch
catch (Exception exception)
{
if (exception is not UpdateCheckException)
UkiyoeTelemetry.Report(exception);
}
}
サブモジュール
+1
サブモジュール YMM4-Telemetry が 04010903ca で追加されました。
バイナリ
ファイルの表示
バイナリファイルは表示されません。

変更後

幅:  |  高さ:  |  サイズ: 400 KiB