コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
67bfc55ac7
|
||
|
|
360a2483a5
|
||
|
|
92c5ed12c3
|
||
|
|
2df6049e09
|
||
|
|
0901834d34
|
||
|
|
f961c5528d
|
||
|
|
655cbc4c62
|
||
|
|
3f81fc027b
|
||
|
|
3a8ab13835
|
||
|
|
4a380316db
|
||
|
|
bb01da0d17
|
||
|
|
9eea31e30f
|
||
|
|
3481df9b95
|
||
|
|
1a570c2d1a
|
||
|
|
591ec6d71d
|
||
|
|
55b410544e
|
||
|
|
4f7c79af80
|
||
|
|
fe33963a29
|
||
|
|
ee7b84c0bc
|
||
|
|
77e1bca8ed
|
||
|
|
c1b199e3cc
|
||
|
|
6af1869806
|
||
|
|
63e6751720
|
||
|
|
32ba794793
|
||
|
|
c46de42cd6
|
||
|
|
54f9afe96a
|
||
|
|
d82a6fc6aa
|
||
|
|
514e683b52
|
||
|
|
95cd99200e
|
||
|
|
5a40018959
|
||
|
|
77e07d49a3
|
||
|
|
dba80fe22d
|
||
|
|
aac8cd85d0
|
||
|
|
40f9927be5
|
||
|
|
1daeef879d
|
||
|
|
198e3377e2
|
||
|
|
516d24ca65
|
||
|
|
d447968e77
|
||
|
|
7547502cb3
|
||
|
|
168a53f9cd
|
||
|
|
e2b1d9b7a1
|
||
|
|
e1451778ff
|
||
|
|
e985dac0d8
|
||
|
|
e84e0e6a55
|
||
|
|
9b1ff4ef76
|
||
|
|
8464947416
|
||
|
|
8101a8020a
|
||
|
|
a85f173c23
|
||
|
|
c9c2f07f94
|
||
|
|
af73269f9f
|
||
|
|
a2a8c907ab
|
||
|
|
50b4edce0a
|
||
|
|
9ff65faa0c
|
||
|
|
9c85e13f4e
|
||
|
|
12bedd3dcd
|
||
|
|
6b71fd871a
|
||
|
|
ab6d9e3901
|
||
|
|
b8b943897c
|
||
|
|
f62e1b4a4a
|
||
|
|
cd033f9105
|
||
|
|
a27a3d4081
|
||
|
|
33c311a474
|
||
|
|
3c026a2517
|
||
|
|
62338729d6
|
||
|
|
9d1d5ecc7d
|
||
|
|
03d0c5e00c
|
||
|
|
1c6234c48f
|
||
|
|
4d7cfd8000
|
||
|
|
d41d990fb0
|
||
|
|
ec860f1293
|
||
|
|
efcfc0b354
|
||
|
|
153fa4ff9e
|
||
|
|
bceccb0cc7
|
||
|
|
ef0b44b909
|
||
|
|
58b3e90fcb
|
||
|
|
deaa73151a
|
||
|
|
623c488b1b
|
||
|
|
8985352369
|
||
|
|
8c681e4331
|
||
|
|
ad99c5514b
|
||
|
|
b2c240d8b1
|
||
|
|
8b1ee954cc
|
検索条件に一致するファイルはありません
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": 1,
|
||||
"isRoot": true,
|
||||
"tools": {
|
||||
"dotnet-stryker": {
|
||||
"version": "5.0.0",
|
||||
"commands": [
|
||||
"dotnet-stryker"
|
||||
],
|
||||
"rollForward": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
# v1.0.0 - ローポリ化 for YMM4
|
||||
|
||||
YukkuriMovieMaker4向けのローポリ化エフェクトプラグインの初回リリースです。
|
||||
素材のエッジを拘束点とみなし、特徴フロー場を重みとした重心ボロノイのLloyd緩和で頂点を最適化し、ボロノイ双対の三角メッシュで素材をローポリ調に抽象化して描画します。
|
||||
三角形の配置はシードから決定論的に決まり、色の誤差が大きい三角形を細分化して細部へ密度を寄せます。
|
||||
計算はComputeSharpの計算シェーダーがDirect3D 12で実行し、YMM4のDirect3D 11側とは共有テクスチャおよび共有フェンスで接続します。
|
||||
8言語のリソース構成のUIを備えます。
|
||||
|
||||
---
|
||||
|
||||
## 新機能
|
||||
|
||||
### 1. ローポリ化の計算パイプライン
|
||||
|
||||
`LowPolyAbstractionPipeline`は、解析、構造、描画の3段階の計算シェーダーを`ComputeContext`へ記録して実行します。作業格子とサイトのバッファーは計算領域の大きさと品質に応じて確保し、サイズが変わらないフレームでは再利用します。処理の流れは次のとおりです。
|
||||
|
||||
1. `AnalyzeShader`が、現在のフレームを作業解像度へ箱型平均で縮小し、輝度、色、内容ハッシュ、シルエットのバウンディングボックスを求めます。
|
||||
2. `EdgeShader`が、輝度とアルファのSobel勾配からエッジ強度を求め、`EdgeDistanceSeedShader`と`JumpFloodPixelPassShader`がエッジまでの距離場をジャンプフラッドで求めます。`WeightShader`は距離の三角波から特徴フロー場の重みを作ります。
|
||||
3. `EdgeBestShader`と`EdgeEmitShader`がエッジ上の拘束点を、`InteriorCountShader`と`InteriorEmitShader`が内部点を、ブロック走査による圧縮で決定論的な順序のまま配置します。
|
||||
4. `VoronoiScatterShader`と`JumpFloodSitePassShader`がサイトのボロノイ割り当てを求め、`CentroidAccumulateShader`と`UpdateSitesShader`が重み付き重心へのLloyd緩和を反復します。
|
||||
5. `CornerCountShader`と`TriangleEmitShader`が割り当て図の双対として三角形を抽出し、`IncidenceBuildShader`がサイトごとの接続リストを構築します。
|
||||
6. `TriangleColorPassShader`と`FinalizeTrianglesShader`が三角形の色と輝度分散を集計し、`RefineCountShader`と`RefineEmitShader`が高誤差三角形の重心へサイトを挿入して、緩和と三角化を反復します。
|
||||
7. `SiteColorAccumulateShader`と`SiteColorFinalizeShader`が頂点色を集計し、`RenderShader`が画素ごとに包含三角形を求めて塗り、輪郭線、彩度、明度ゆらぎを適用します。
|
||||
|
||||
| シェーダー | 役割 |
|
||||
|---|---|
|
||||
| `AnalyzeShader` | 縮小、輝度、内容ハッシュ、バウンディングボックスを求める |
|
||||
| `EdgeShader` | Sobel勾配からエッジ強度を求める |
|
||||
| `EdgeDistanceSeedShader` / `JumpFloodPixelPassShader` | エッジまでの距離場を求める |
|
||||
| `WeightShader` | 特徴フロー場の重みを作る |
|
||||
| `EdgeBestShader` / `EdgeEmitShader` | エッジ上の拘束点を配置する |
|
||||
| `InteriorCountShader` / `InteriorEmitShader` | 内部点を層化ジッターで配置する |
|
||||
| `BlockCountShader` / `BlockPrefixShader` | ブロック走査で稠密な添字を確定する |
|
||||
| `VoronoiClearShader` / `VoronoiScatterShader` / `JumpFloodSitePassShader` | ボロノイ割り当てを求める |
|
||||
| `CentroidAccumulateShader` / `UpdateSitesShader` | 重み付き重心へのLloyd緩和を行う |
|
||||
| `CornerCountShader` / `TriangleEmitShader` | ボロノイ双対の三角形を抽出する |
|
||||
| `IncidenceBuildShader` | サイトごとの接続三角形を記録する |
|
||||
| `TriangleColorPassShader` / `FinalizeTrianglesShader` | 三角形の色と輝度分散を集計する |
|
||||
| `RefineCountShader` / `RefineEmitShader` | 高誤差三角形の重心へサイトを挿入する |
|
||||
| `SiteColorAccumulateShader` / `SiteColorFinalizeShader` | 頂点色を集計する |
|
||||
| `RenderShader` | 三角メッシュを描画する |
|
||||
|
||||
### 2. 特徴フロー場つき重み付きCVTと誤差駆動の細分化
|
||||
|
||||
頂点の最適化は、Gai and Wangの論文「Artistic Low Poly rendering for images」の特徴フロー場つき重心ボロノイに基づきます。エッジまでの距離`d`とレーン幅`m`から三角波の重みを作り、`exp(-d / 8m)`の減衰を掛けて、頂点をエッジに平行なレーンへ整列させます。レーン幅はGai and Wangのサンプル間隔`0.02(W+H)`の半分です。エッジ上の拘束点は固定し、内部点だけを重心へ動かします。
|
||||
|
||||
重心の集計は、重みを`64`倍で量子化した整数を、下位と上位の2つの32bit整数へ桁上がり付きの原子加算で足し込みます。加算順序に依存しない整数演算だけを使うため、並列実行でも結果は決定論的です。
|
||||
|
||||
細分化は、Lawonn and Güntherの論文「Stylized Image Triangulation」の高誤差三角形分割に基づきます。三角形ごとに輝度の平均と二乗平均から分散を求め、閾値を超えた三角形の重心へ新しいサイトを挿入し、Lloyd緩和2回と再三角化を品質に応じた回数だけ反復します。閾値は細分化のパラメータから`0.02`〜`0.0004`へ割り当てます。挿入の上限は目標サイト数の1.5倍です。
|
||||
|
||||
三角形の塗り色は、輝度の平均±1.2σの帯域内の画素だけを使う刈り込み平均で決めます。明部と暗部が混ざった三角形でも中間色に濁りません。
|
||||
|
||||
### 3. ボロノイ双対からの決定論的な三角形抽出
|
||||
|
||||
三角形は、ボロノイ割り当て図の2×2画素角で3つまたは4つの相異なるサイトが接する箇所の双対として抽出します。4つの場合は対角で2つへ分けます。抽出した三角形の添字は、ブロック走査による圧縮で角の位置順に確定するため、並列実行でも順序が揺れません。
|
||||
|
||||
画素の包含判定は、最近傍サイトの接続三角形だけを重心座標で調べます。辺上の画素が複数の三角形に該当する場合は最小添字を採用し、判定を決定論的に保ちます。
|
||||
|
||||
### 4. 可視範囲への出力矩形の最小化
|
||||
|
||||
`AnalyzeShader`がシルエットのバウンディングボックスを原子的最小値と最大値で集計し、`Simulate`の読み戻しでキャッシュします。描画はこの矩形に固定余白8画素を加え、4画素境界へそろえた範囲だけを計算します。三角形はシルエットの内側のサイトから作られるため、出力はこの矩形に収まります。
|
||||
|
||||
### 5. 構造キャッシュ
|
||||
|
||||
三角メッシュを決める入力が変わらないフレームでは、構造の計算を再利用します。
|
||||
|
||||
- 素材の内容は、作業格子の輝度とアルファの量子化値のハッシュの総和とXORの2値へ集約し、16個の整数の読み戻しで前フレームと比較します。
|
||||
- 内容のハッシュ、計算領域の大きさ、品質、シード、細かさ、輪郭忠実度、細分化が一致する場合は、構造段階を実行しません。
|
||||
- グラデーション、輪郭線、彩度、明度ゆらぎは描画専用のパラメータで、変更してもメッシュを再計算しません。構造と描画パラメータと出力矩形がすべて変わらないフレームでは、描画段階も実行せず、前フレームの出力テクスチャを使用します。
|
||||
|
||||
### 6. Direct3D 11・Direct3D 12相互運用
|
||||
|
||||
`LowPolyAbstractionGpuInterop`は、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`を返し、エフェクトを適用せず入力映像を表示します。
|
||||
|
||||
### 7. カスタムシェーダーによる合成
|
||||
|
||||
`LowPolyAbstractionCustomEffect`は、`[CustomEffect(2)]`の2入力エフェクトです。入力0は元映像、入力1は描画したローポリ画です。ピクセルシェーダー`LowPolyAbstraction.hlsl`の`main`は、`amount`が0以下のとき元映像をそのまま返し、そうでないときはローポリ画のRGBをアルファでクランプし、`poly + source * (1 - poly.a)`のアルファ合成の結果と元映像を`amount`で線形補間します。
|
||||
|
||||
定数バッファーは`Amount`と3つの詰め物で16バイトです。`MapInputRectsToOutputRect`は2つの入力矩形の和集合を出力矩形とします。
|
||||
|
||||
### 8. エフェクト定義とパラメータ
|
||||
|
||||
`LowPolyAbstractionEffect`は、YMM4の映像エフェクトとして宣言されます。
|
||||
|
||||
`[VideoEffect]`属性は以下のパラメーターで宣言されます。
|
||||
|
||||
- 表示名: `Texts.LowPolyAbstraction`(ローカライズキー、日本語では「ローポリ化」)
|
||||
- カテゴリー: `VideoEffectCategories.Decoration`・`VideoEffectCategories.Filtering`
|
||||
- 検索タグ: `TagLowPoly`・`TagTriangle`・`TagPolygon`
|
||||
- `IsAviUtlSupported = false`によりAviUtl向けEXO出力は非対応
|
||||
- `ResourceType = typeof(Texts)`でローカライズリソースを指定
|
||||
|
||||
公開プロパティは以下のとおりです。基本項目は「基本」グループ、三角形項目は「三角形」グループ、描画項目は「描画」グループに属します。
|
||||
|
||||
| プロパティ | 型 | デフォルト | 内部範囲 | アニメーション |
|
||||
|---|---|---|---|---|
|
||||
| `Amount` | `Animation` | 100 | 0〜100 | あり |
|
||||
| `Quality` | `LowPolyAbstractionQuality` | `High` | — | なし |
|
||||
| `Detail` | `Animation` | 60 | 0〜100 | あり |
|
||||
| `Fidelity` | `Animation` | 70 | 0〜100 | あり |
|
||||
| `Refine` | `Animation` | 50 | 0〜100 | あり |
|
||||
| `Seed` | `int` | 0 | 0〜int.MaxValue | なし |
|
||||
| `Gradient` | `Animation` | 30 | 0〜100 | あり |
|
||||
| `Wireframe` | `Animation` | 0 | 0〜100 | あり |
|
||||
| `Saturation` | `Animation` | 30 | 0〜100 | あり |
|
||||
| `Jitter` | `Animation` | 25 | 0〜100 | あり |
|
||||
|
||||
`GetAnimatables`は`Amount`・`Detail`・`Fidelity`・`Refine`・`Gradient`・`Wireframe`・`Saturation`・`Jitter`を返します。`Seed`は負値を代入すると0へ丸めます。
|
||||
|
||||
`CreateExoVideoFilters`は空のシーケンスを返します。`CreateVideoEffect`は映像処理用のインスタンスを生成します。エフェクトを最初に生成したときに、更新確認を一度だけ開始します。
|
||||
|
||||
### 9. フレームごとの更新
|
||||
|
||||
各フレームでYMM4の`EffectDescription`からフレーム位置、アイテム長、FPSを取得し、アニメーション値を評価します。値をパイプラインが前提とする範囲へ制限してから転送します。
|
||||
|
||||
| パラメータ | 変換 |
|
||||
|---|---|
|
||||
| `Amount` | `value / 100` をカスタムシェーダーの`Amount`へ |
|
||||
| `Detail` | `value / 100` を0〜1へクランプし、目標サイト数へ |
|
||||
| `Fidelity` | `value / 100` を0〜1へクランプし、エッジのサンプル間隔と重みの強さへ |
|
||||
| `Refine` | `value / 100` を0〜1へクランプし、分散の閾値へ |
|
||||
| `Gradient` | `value / 100` を0〜1へクランプ |
|
||||
| `Wireframe` | `value / 100` を0〜1へクランプし、最大1.5画素の線幅へ |
|
||||
| `Saturation` | `value / 100` を0〜1へクランプし、最大0.6の彩度強調へ |
|
||||
| `Jitter` | `value / 100` を0〜1へクランプし、最大0.08の明度変動へ |
|
||||
| `Seed` | 0以上へクランプ |
|
||||
|
||||
強さが0以下のときは、ローポリ画を描画せず入力映像をそのまま出力します。入力の範囲が有限でない場合や、計算領域の長辺が8192画素を超える場合も、入力映像を表示します。
|
||||
|
||||
### 10. 品質設定
|
||||
|
||||
品質は、作業解像度、頂点数の基準、Lloyd緩和の反復回数、細分化の反復回数をまとめて切り替えます。
|
||||
|
||||
| 品質 | 作業解像度 | 頂点数の基準 | 緩和反復 | 細分化反復 |
|
||||
|---|---:|---:|---:|---:|
|
||||
| 標準 | 1024 | 4096 | 6回 | 1回 |
|
||||
| 高品質 | 1536 | 8192 | 8回 | 2回 |
|
||||
| 最高品質 | 2048 | 16384 | 10回 | 3回 |
|
||||
|
||||
作業解像度は計算領域の長辺の画素数です。短辺は計算領域の縦横比に合わせ、最小16画素とします。
|
||||
|
||||
### 11. ローカライズ
|
||||
|
||||
`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 |
|
||||
|---|---|
|
||||
| `LowPolyAbstraction` | ローポリ化 |
|
||||
| `BasicGroup` | 基本 |
|
||||
| `StructureGroup` | 三角形 |
|
||||
| `AppearanceGroup` | 描画 |
|
||||
| `Amount` | 強さ |
|
||||
| `Quality` | 品質 |
|
||||
| `Detail` | 細かさ |
|
||||
| `Fidelity` | 輪郭忠実度 |
|
||||
| `Refine` | 細分化 |
|
||||
| `Seed` | シード |
|
||||
| `Gradient` | グラデーション |
|
||||
| `Wireframe` | 輪郭線 |
|
||||
| `Saturation` | 彩度 |
|
||||
| `Jitter` | 明度ゆらぎ |
|
||||
| `QualityBalanced` | 標準 |
|
||||
| `QualityHigh` | 高品質 |
|
||||
| `QualityUltra` | 最高品質 |
|
||||
| `TagLowPoly` | ローポリ |
|
||||
| `TagTriangle` | 三角形 |
|
||||
| `TagPolygon` | ポリゴン |
|
||||
| `UpdateAvailableMessage` | 新しいバージョン {0} が公開されています。 |
|
||||
@@ -0,0 +1 @@
|
||||
github: routersys
|
||||
@@ -0,0 +1,102 @@
|
||||
name: 不具合の報告
|
||||
description: エラーが出る、強制終了する、出力が乱れる、README と違う動きをする、といった不具合を報告します。
|
||||
title: "[Bug] "
|
||||
labels: ["bug"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
脆弱性はここに書かず、リポジトリのセキュリティポリシーに従って非公開で報告してください。
|
||||
README と実際の動きが違い、文書のほうが誤りだと考えるときは、文書の不備を使ってください。
|
||||
|
||||
- type: input
|
||||
id: plugin-version
|
||||
attributes:
|
||||
label: プラグインのバージョン
|
||||
description: GitHub のリリースか、配布パッケージの Readme.txt の見出しで確かめられます。
|
||||
placeholder: v1.0.0
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: ymm4-version
|
||||
attributes:
|
||||
label: YukkuriMovieMaker4 のバージョン
|
||||
description: YukkuriMovieMaker4 のメインウィンドウのタイトルに表示されるバージョンを、そのまま書いてください。
|
||||
placeholder: v4.56.1.0 Lite
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: os
|
||||
attributes:
|
||||
label: Windows のバージョン
|
||||
description: winver を実行し、ビルド番号まで書いてください。
|
||||
placeholder: Windows 11 24H2, 26100.2605
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: gpu
|
||||
attributes:
|
||||
label: GPU とドライバー
|
||||
description: 描画や GPU に関わる不具合では必ず書いてください。デバイスマネージャーか dxdiag に表示される GPU の名前と、ドライバーのバージョンです。
|
||||
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: 期待した動き
|
||||
description: 何が起きると考えたか。README に根拠があれば、その箇所も書いてください。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: actual
|
||||
attributes:
|
||||
label: 実際の動き
|
||||
description: 実際に起きたこと。エラー画面が出たときは、その内容を省略せずに貼ってください。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: 再現の手順
|
||||
description: |
|
||||
新しいプロジェクトから不具合が起きるまでの操作を、番号を付けて書いてください。変えた設定の項目と値も書いてください。
|
||||
プロジェクトファイルや素材は、zip に圧縮して添付できます。添付したファイルは誰でも見られます。プロジェクトファイルには素材を置いたフォルダーのパスが記録されるので、公開できない情報が無いかを確かめてください。
|
||||
placeholder: |
|
||||
1. 新しいプロジェクトを作る
|
||||
2. アイテムを置き、本プラグインを使う
|
||||
3. 設定を変える
|
||||
4. 不具合が起きる
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: frequency
|
||||
attributes:
|
||||
label: 起きる頻度
|
||||
description: ときどき起きるときは、何回試して何回起きたかを、下の「その他」の欄に書いてください。
|
||||
options:
|
||||
- 毎回起きる
|
||||
- ときどき起きる
|
||||
- 一度だけ起きた
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: その他
|
||||
description: 一緒に使っているほかのプラグインや、関係すると思われることを書いてください。
|
||||
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: 報告の前に
|
||||
options:
|
||||
- label: 最新のリリースを使っています。
|
||||
required: true
|
||||
- label: 既存の Issue を検索し、同じ報告が無いことを確かめました。
|
||||
required: true
|
||||
@@ -0,0 +1,5 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: YukkuriMovieMaker4 本体の不具合
|
||||
url: https://manjubox.net/contact/
|
||||
about: 本体に原因がある不具合は、YukkuriMovieMaker4 の「ヘルプ」の「フィードバックを送信」か、公式サイトのお問い合わせから報告してください。
|
||||
@@ -0,0 +1,63 @@
|
||||
name: 文書の不備
|
||||
description: 誤り、書き漏れ、実際の動きとの食い違いがある文書を報告します。
|
||||
title: "[Docs] "
|
||||
labels: ["documentation"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
実際の動きと文書が食い違うときは、ここで報告して構いません。動きのほうが誤りだと考えるときは、不具合の報告を使ってください。
|
||||
|
||||
- type: dropdown
|
||||
id: location
|
||||
attributes:
|
||||
label: 文書
|
||||
options:
|
||||
- README
|
||||
- 配布パッケージの Readme.txt
|
||||
- 設定の項目の名前や説明
|
||||
- 貢献の手引き、セキュリティポリシー、行動規範
|
||||
- その他
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: reference
|
||||
attributes:
|
||||
label: 文書の中の位置
|
||||
description: 見出し、行番号、設定の項目の名前のどれかを書いてください。
|
||||
placeholder: README の「制限事項」の 2 つ目の項目
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: says
|
||||
attributes:
|
||||
label: 今の記述
|
||||
description: そのまま引用してください。元の文書を開かずに検討できるようにするためです。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: どこが問題か
|
||||
description: |
|
||||
誤り、書き漏れ、曖昧さのどれに当たるかを書いてください。それによって読む人が何を取り違えるかも書いてください。
|
||||
実際の動きと食い違っているときは、文書と動きのどちらを直すべきと考えるかも書いてください。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: suggestion
|
||||
attributes:
|
||||
label: 提案する文面
|
||||
description: 具体的な文面があると、早く直せます。
|
||||
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: 報告の前に
|
||||
options:
|
||||
- label: 最新のリリースか、既定のブランチの最新の文書で確かめました。
|
||||
required: true
|
||||
@@ -0,0 +1,42 @@
|
||||
name: 機能の提案
|
||||
description: 新しい機能や設定の項目、既存の動きの変更を提案します。
|
||||
title: "[Proposal] "
|
||||
labels: ["enhancement"]
|
||||
body:
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: 困っていること
|
||||
description: 今のプラグインでできないことや、手間がかかることを、利用者の立場で書いてください。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: workaround
|
||||
attributes:
|
||||
label: 今はどうしているか
|
||||
description: 今の回避策と、それにかかる手間を書いてください。回避策が無ければ、その旨を書いてください。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: proposal
|
||||
attributes:
|
||||
label: 提案する動き
|
||||
description: どう動いてほしいかを書いてください。設定の項目を増やす提案では、項目の名前、範囲、既定値の案も書いてください。
|
||||
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: 検討したほかの方法
|
||||
description: ほかに考えた方法があれば、それでは足りない理由と一緒に書いてください。
|
||||
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: 提案の前に
|
||||
options:
|
||||
- label: 既存の Issue を検索し、同じ提案が無いことを確かめました。
|
||||
required: true
|
||||
- label: 最新のリリースに同じ機能が無いことを確かめました。
|
||||
required: true
|
||||
@@ -0,0 +1,49 @@
|
||||
name: 使い方の質問
|
||||
description: 使い方や、実際の動きが仕様どおりかを尋ねます。
|
||||
title: "[Question] "
|
||||
labels: ["question"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
プラグインの不具合だと分かっているときは、不具合の報告を使ってください。
|
||||
|
||||
- type: textarea
|
||||
id: question
|
||||
attributes:
|
||||
label: 質問
|
||||
description: 背景を書く前に、質問を 1 文か 2 文で書いてください。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: goal
|
||||
attributes:
|
||||
label: 何をしようとしているか
|
||||
description: つまずいている操作だけでなく、最終的に何を作りたいかを書いてください。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: tried
|
||||
attributes:
|
||||
label: 試したこと
|
||||
description: 試した設定と、そのとき実際に起きたことを書いてください。
|
||||
|
||||
- type: input
|
||||
id: plugin-version
|
||||
attributes:
|
||||
label: プラグインのバージョン
|
||||
placeholder: v1.0.0
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: 質問の前に
|
||||
options:
|
||||
- label: README の該当する節を読みました。
|
||||
required: true
|
||||
- label: 既存の Issue を検索し、同じ質問が無いことを確かめました。
|
||||
required: true
|
||||
+79
-22
@@ -1,12 +1,19 @@
|
||||
========================================
|
||||
ローポリ化 for YMM4 v1.0.0
|
||||
ローポリ化 for YMM4 v2.0.0
|
||||
========================================
|
||||
YukkuriMovieMaker4上で動作する、素材を三角メッシュへ抽象化して
|
||||
ローポリ調に描画する映像エフェクトプラグインです。
|
||||
エッジ拘束と特徴フロー場つきの重み付きボロノイ緩和で頂点を最適化し、
|
||||
色の誤差が大きい三角形を細分化して細部へ密度を寄せます。
|
||||
YukkuriMovieMaker4上で動作する、素材を三角形の面で塗り分けて
|
||||
ローポリ画として描画する映像エフェクトプラグインです。
|
||||
エッジの上に頂点を固定し、残りの頂点を、エッジからの距離に応じて重みを
|
||||
付けた重心ボロノイ分割で並べ、色の誤差が大きい三角形をさらに分割します。
|
||||
色の誤差は、三角形の中の画素の輝度のばらつきを表す分散です。
|
||||
頂点の置き方はGai and Wangの論文「Artistic Low Poly rendering for images」
|
||||
(The Visual Computer、2016年)に基づきます。
|
||||
色の誤差が大きい三角形を分割する処理は、Lawonn and Güntherの論文
|
||||
「Stylized Image Triangulation」(Computer Graphics Forum、2019年)に
|
||||
基づきます。
|
||||
履歴フレーム、参照画像、深度情報、学習済みモデルは使用しません。
|
||||
三角形の配置はシードから決定論的に決まり、同じ設定では常に同じ形になります。
|
||||
三角形の配置は素材とシードから決定論的に決まり、同じ設定では常に
|
||||
同じ形になります。
|
||||
強さ、細かさ、輪郭忠実度、細分化、グラデーション、輪郭線、彩度、明度ゆらぎの
|
||||
8項目はアニメーションに対応しています。
|
||||
エフェクトの種類一覧では「ローポリ化」として表示されます。
|
||||
@@ -28,29 +35,41 @@ YukkuriMovieMaker4上で動作する、素材を三角メッシュへ抽象化
|
||||
Direct3D 11デバイスとの共有テクスチャおよび共有フェンスを作成できない
|
||||
場合は、エフェクトを適用せず入力映像を表示します。
|
||||
|
||||
- 処理対象: 三角メッシュの生成には現在のフレームの色とアルファ値を
|
||||
- 処理対象: 三角メッシュの生成には現在のフレームの色と不透明度だけを
|
||||
使用します。履歴フレーム、外部画像、深度情報、学習済みモデルは
|
||||
使用しません。
|
||||
使用しません。画素の不透明度が5%以下の所は、頂点の配置と色の計算に
|
||||
使いません。素材のすべての画素の不透明度が5%以下のときは、
|
||||
エフェクトを適用せず入力映像を表示します。
|
||||
|
||||
- 計算領域: 素材の範囲に固定余白8画素を加えた大きさを計算領域とし、
|
||||
長辺は8192画素が上限です。素材が大きすぎる場合は、エフェクトを
|
||||
適用せず入力映像を表示します。
|
||||
- 計算領域: 透明な部分も含む素材全体の矩形の上下左右に8画素の余白を
|
||||
加えた大きさを計算領域とし、長辺は8192画素が上限です。素材の長辺が
|
||||
8176画素を超える場合は、エフェクトを適用せず入力映像を表示します。
|
||||
|
||||
- 処理負荷: 作業解像度と品質に応じて処理量とGPUメモリ使用量が増えます。
|
||||
- 処理負荷: 計算領域の大きさと品質に応じて処理量とGPUメモリ使用量が
|
||||
増えます。作業解像度は、縮小して計算するときの長辺の画素数の上限です。
|
||||
最高品質は作業解像度と反復回数が最も多いため、高品質と標準より
|
||||
処理負荷が高くなります。描画は素材が存在する矩形の範囲だけを計算します。
|
||||
処理負荷が高くなります。描画の計算は、素材の不透明な部分を囲む矩形に
|
||||
余白を加えた範囲に限ります。
|
||||
|
||||
- キャッシュ: 素材の内容と三角形の配置を決めるパラメータが変わらない
|
||||
フレームでは、三角メッシュの計算を再利用します。
|
||||
- キャッシュ: 素材の大きさと色と不透明度、品質、シード、細かさ、
|
||||
輪郭忠実度、細分化が変わらないフレームでは、三角メッシュの計算を
|
||||
再利用します。動画や口パクのように素材の内容が変わるフレームと、
|
||||
細かさ、輪郭忠実度、細分化をアニメーションで変えたフレームでは、
|
||||
毎回計算し直すので処理が重くなります。
|
||||
|
||||
- 強さ0%: 強さが0%のときは入力を変更しません。
|
||||
|
||||
- シードと再現性: 三角形の配置は、シード、セル位置、素材の内容から
|
||||
決定論的に算出します。時間値は生成に使用しません。
|
||||
決定論的に算出します。時間値は生成に使用しません。素材の内容が変わる
|
||||
フレームや、細かさ、輪郭忠実度、細分化をアニメーションで変えた
|
||||
フレームでは、三角形の配置も変わることがあります。
|
||||
|
||||
- 出力範囲: 三角形は素材のシルエットの内側に生成されるため、
|
||||
出力範囲は素材の範囲に余白を加えた矩形に収まります。ローポリ画は
|
||||
元映像の上へアルファ合成します。
|
||||
- 透明部分: 塗りの各画素の不透明度は、素材のその画素の不透明度を
|
||||
超えません。そのため、三角形が素材のくぼみや隙間をまたいでも、
|
||||
透明な部分は透明のまま残ります。出力範囲は計算領域に収まります。
|
||||
ローポリ画は、塗りで覆われない分だけ元映像が見えるように元映像と
|
||||
合成します。そのため、半透明な素材も元の不透明度のまま描かれ、
|
||||
三角形で覆われない画素では元映像がそのまま見えます。
|
||||
|
||||
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ
|
||||
新しい正式版を確認します。更新情報を取得できない場合は通知せず、
|
||||
@@ -58,6 +77,44 @@ YukkuriMovieMaker4上で動作する、素材を三角メッシュへ抽象化
|
||||
|
||||
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを
|
||||
作成することを推奨します。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 不具合の報告
|
||||
--------------------------------------------------------------------------------
|
||||
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で
|
||||
送信します。同意は求めず、常に送信します。
|
||||
|
||||
送信する情報は次のとおりです。
|
||||
例外 : 型の完全名、メッセージ、スタックトレース
|
||||
発生位置 : モジュール名、関数名、ファイル名、行番号
|
||||
プラグイン : アセンブリ名、バージョン
|
||||
実行環境 : OSの名前とバージョン、.NETのバージョン、
|
||||
CPUのアーキテクチャ、論理プロセッサ数
|
||||
識別子 : YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子
|
||||
|
||||
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する
|
||||
識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値に
|
||||
なります。メッセージとファイル名に含まれる利用者名などの文字列は、送信の
|
||||
前に置き換えます。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
|
||||
|
||||
送信するのは想定していない例外だけです。YMM4が本プラグインのエフェクトを
|
||||
作るとき、フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、
|
||||
Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後は
|
||||
YMM4へそのまま渡します。画面の操作やバックグラウンドの処理で未処理に
|
||||
なった例外も報告しますが、本プラグインのコードが関わる例外に限ります。
|
||||
本プラグインの外で起きた例外は送信しません。
|
||||
|
||||
次の失敗は送信しません。
|
||||
効果をかけないだけで済ませるもの : Direct3D 12デバイスを取得できない、
|
||||
YMM4のDirect3D 11デバイスとの共有
|
||||
テクスチャや共有フェンスを作成できない、
|
||||
計算領域が上限を超えるときに、
|
||||
エフェクトを適用せず入力映像を
|
||||
表示したとき
|
||||
更新の確認の通信の失敗 : GitHubへ接続できない
|
||||
|
||||
送信できなかった報告はYMM4のユーザーフォルダーへ退避し、次回の起動時に
|
||||
送り直します。送信も再送も非同期に行うため、起動と描画が遅くなることは
|
||||
ありません。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 免責事項
|
||||
--------------------------------------------------------------------------------
|
||||
@@ -71,9 +128,9 @@ YukkuriMovieMaker4上で動作する、素材を三角メッシュへ抽象化
|
||||
--------------------------------------------------------------------------------
|
||||
■ サードパーティライセンス
|
||||
--------------------------------------------------------------------------------
|
||||
本プラグインはComputeSharp(MIT License)を同梱しています。
|
||||
ライセンスの全文は同梱のLICENSEフォルダー(ComputeSharp.txt)に収録しています。
|
||||
ComputeSharp : Copyright (c) 2024 Sergio Pedri
|
||||
本プラグインはComputeWeave(MIT License)を同梱しています。
|
||||
ライセンスの全文は同梱のLICENSEフォルダー(ComputeWeave.txt)に収録しています。
|
||||
ComputeWeave : Copyright (c) 2024 Sergio Pedri
|
||||
--------------------------------------------------------------------------------
|
||||
■ ライセンス
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
<!--
|
||||
当てはまらない節は消してください。「関連する Issue」と「動きの変更」の節は残し、該当しないときは「なし」と書いてください。
|
||||
-->
|
||||
|
||||
## 概要
|
||||
|
||||
<!--
|
||||
何をどう変えたか。なぜその変更が必要か。
|
||||
-->
|
||||
|
||||
## 関連する Issue
|
||||
|
||||
<!--
|
||||
新しい機能、設定の項目や既定値の変更、大きめの不具合の修正、意図して出力を変える変更、互換性を損なう変更、コードの構成を大きく変える変更は、先に Issue で合意してください。
|
||||
Issue が無い変更では、下の行を「なし」に書き換えてください。
|
||||
-->
|
||||
|
||||
Closes #
|
||||
|
||||
## 変更の種類
|
||||
|
||||
<!-- 当てはまるものを残してください。 -->
|
||||
|
||||
- 不具合の修正
|
||||
- 機能の追加
|
||||
- 動きの変更
|
||||
- 性能の改善
|
||||
- テストの追加
|
||||
- 依存関係の更新
|
||||
- 文書
|
||||
- ビルド、リリース
|
||||
|
||||
## 動きの変更
|
||||
|
||||
<!--
|
||||
利用者から見て何が変わるか。設定の項目、既定値、出力の結果、エラーの出方の変化も含みます。
|
||||
保存済みのプロジェクトの結果が変わるなら、必ず書いてください。
|
||||
-->
|
||||
|
||||
## 検証
|
||||
|
||||
<!--
|
||||
手元で実際に確かめた結果を書いてください。
|
||||
- ビルドの結果と、テストのプロジェクトがあればテストの結果
|
||||
- YukkuriMovieMaker4 で実際に動かして確かめたこと
|
||||
- 実行できなかったテストと、その理由
|
||||
実際に動かして観察したこと、コードを読んで判断したこと、推測したことを分けて書いてください。
|
||||
-->
|
||||
|
||||
使った YukkuriMovieMaker4 のバージョン:
|
||||
|
||||
GPU に関わる変更では、使った GPU とドライバー:
|
||||
|
||||
## 確認
|
||||
|
||||
<!-- テストのプロジェクトが無いリポジトリでは、実装とテストを分ける項目を消してください。 -->
|
||||
|
||||
- [ ] 1 つの目的の変更だけを含み、関係の無い整理や整形を含めていない。
|
||||
- [ ] どのコミットも、それ単独でビルドが通る。
|
||||
- [ ] 実装の変更と、それを確かめるテストを、別のコミットに分けた。
|
||||
- [ ] コミットの件名は日本語で書き、50 文字以内に収め、「〜する」の形で終えた。日本語で書けない場合は、その旨を「レビューで見てほしい点」に書いた。
|
||||
- [ ] コミットの本文は、リリースノートでの変更の分類を指定する行を求められたときだけ書いた。
|
||||
- [ ] 変更する箇所で既に使われている実装のパターンに従った。
|
||||
- [ ] 新しく書いたコードにコメントを入れず、コメントアウトしたコードも残していない。既存のコメントとドキュメントコメントは残した。
|
||||
- [ ] 自分の変更で増えたビルドの警告を直した。
|
||||
- [ ] 出力を変えるつもりの無い変更では、変更前と変更後で出力が一致することを確かめた。
|
||||
- [ ] この変更と関係の無い依存関係の更新を含めていない。
|
||||
- [ ] 動きを変えた場合、README を直した。`.github/Plugin_Readme.txt` があるリポジトリでは、それも直した。
|
||||
- [ ] バージョンを上げる変更を含めていない。
|
||||
|
||||
## 性能の改善を主張する場合
|
||||
|
||||
<!-- それ以外の場合は、この節ごと消してください。 -->
|
||||
|
||||
- [ ] 同じ機材、ドライバー、設定、電源の条件で、変更前と変更後のビルドを交互に繰り返し測った。
|
||||
- [ ] 測定の間を空け、ほかのプロセスが GPU を使っていない状態で測った。
|
||||
- [ ] 正しさの確認と性能の測定を、別々に実行した。
|
||||
|
||||
<!--
|
||||
測定の条件と、測定値。
|
||||
-->
|
||||
|
||||
## レビューで見てほしい点
|
||||
|
||||
<!--
|
||||
判断に迷った点、意見を聞きたい点、意図して外した部分とその理由。
|
||||
-->
|
||||
+306
-47
@@ -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 = "LowPolyAbstraction/LowPolyAbstraction.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 = "LowPolyAbstraction/LowPolyAbstraction.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 LowPolyAbstraction.Shader/LowPolyAbstraction.Shader.vcxproj `
|
||||
/p:Configuration=Release `
|
||||
/p:Platform=Win32 `
|
||||
/nologo
|
||||
|
||||
- name: プロジェクトのビルド
|
||||
shell: pwsh
|
||||
@@ -89,7 +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
|
||||
|
||||
@@ -99,7 +109,6 @@ jobs:
|
||||
dotnet build LowPolyAbstraction.Tests/LowPolyAbstraction.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
|
||||
@@ -118,17 +127,20 @@ jobs:
|
||||
id: package
|
||||
shell: pwsh
|
||||
run: |
|
||||
$version = "${{ steps.version.outputs.TAG }}"
|
||||
$outDir = "LowPolyAbstraction/bin/x64/Release/net10.0-windows10.0.19041.0"
|
||||
$version = "${{ steps.version.outputs.TAG }}"
|
||||
$outDir = "LowPolyAbstraction/bin/x64/Release/net10.0-windows10.0.19041.0"
|
||||
$stageRoot = "stage/LowPolyAbstraction"
|
||||
$pkgName = "LowPolyAbstraction_$version.ymme"
|
||||
$pkgName = "LowPolyAbstraction_$version.ymme"
|
||||
|
||||
New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
|
||||
|
||||
Copy-Item "$outDir/LowPolyAbstraction.dll" "$stageRoot/"
|
||||
Copy-Item "$outDir/LowPolyAbstraction.ComputeSharp.dll" "$stageRoot/"
|
||||
Copy-Item "$outDir/LowPolyAbstraction.ComputeSharp.Core.dll" "$stageRoot/"
|
||||
$dll = "$outDir/plugin/LowPolyAbstraction.dll"
|
||||
if (-not (Test-Path $dll)) {
|
||||
Write-Error "ビルド結果に LowPolyAbstraction.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 +150,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
-1
@@ -362,4 +362,6 @@ MigrationBackup/
|
||||
.ionide/
|
||||
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
FodyWeavers.xsd
|
||||
# Stryker.NET
|
||||
StrykerOutput/
|
||||
+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
|
||||
@@ -0,0 +1,81 @@
|
||||
# Contributor Covenant 行動規範
|
||||
|
||||
## 私たちの約束
|
||||
|
||||
メンバー、貢献者、リーダーである私たちは、年齢、体格、目に見える障害と目に見えない障害、民族、性的特徴、性自認と性表現、経験の程度、教育、社会経済的地位、国籍、外見、人種、宗教、性的アイデンティティと性的指向を問わず、コミュニティへの参加を誰にとっても嫌がらせの無いものにすることを誓います。
|
||||
|
||||
私たちは、開かれていて誰もが歓迎される、多様で包摂的な、健全なコミュニティを作るように行動し、交流することを誓います。
|
||||
|
||||
## 私たちの基準
|
||||
|
||||
コミュニティのよい環境を作る行動の例は、次のとおりです。
|
||||
|
||||
- ほかの人に共感と思いやりを示す
|
||||
- 異なる意見、視点、経験を尊重する
|
||||
- 建設的な意見を伝え、また快く受け入れる
|
||||
- 自分たちの誤りに責任を持ち、影響を受けた人に謝り、その経験から学ぶ
|
||||
- 自分個人にとってだけでなく、コミュニティ全体にとって最善のことを考える
|
||||
|
||||
受け入れられない行動の例は、次のとおりです。
|
||||
|
||||
- 性的な言葉や画像を使うこと、どのような形であれ、相手に性的な関心を向けることや言い寄ること
|
||||
- 荒らし、侮辱的または軽蔑的な発言、個人攻撃や政治的な攻撃
|
||||
- 公の場か私的な場かを問わない嫌がらせ
|
||||
- 住所やメールアドレスなど、ほかの人の個人情報を明示の許可なく公開すること
|
||||
- 仕事の場で不適切と合理的に考えられるその他の行為
|
||||
|
||||
## 執行の責任
|
||||
|
||||
コミュニティリーダーは、受け入れられる行動の基準を明確にし、それを守らせる責任を負います。不適切、脅迫的、攻撃的、または有害と判断した行動には、適切で公正な是正措置をとります。
|
||||
|
||||
コミュニティリーダーは、この行動規範に沿わないコメント、コミット、コード、Wiki の編集、Issue、その他の貢献を削除、編集、または却下する権利と責任を持ちます。モデレーションの判断については、適切な場合に理由を伝えます。
|
||||
|
||||
## 適用範囲
|
||||
|
||||
この行動規範は、コミュニティのあらゆる場で適用されます。個人が公の場でコミュニティを公式に代表しているときにも適用されます。コミュニティを代表しているときとは、たとえば、公式のメールアドレスを使うとき、公式のソーシャルメディアのアカウントから投稿するとき、オンラインやオフラインのイベントで任命された代表として行動するときです。
|
||||
|
||||
## 執行
|
||||
|
||||
虐待的な言動、嫌がらせ、その他の受け入れられない行動は、執行を担当するコミュニティリーダーへ github.routersys@gmail.com で報告できます。コミュニティリーダーは、すべての苦情を速やかかつ公正に確認し、調査します。
|
||||
|
||||
すべてのコミュニティリーダーは、事案を報告した人のプライバシーと安全を尊重する義務を負います。
|
||||
|
||||
## 執行のガイドライン
|
||||
|
||||
コミュニティリーダーは、この行動規範に違反すると判断した行動への処置を決めるとき、次に示すコミュニティへの影響に応じたガイドラインに従います。
|
||||
|
||||
### 1. 是正
|
||||
|
||||
コミュニティへの影響: 不適切な言葉づかいや、コミュニティの中で、仕事の場にふさわしくない、または歓迎されないと判断されるその他の行動。
|
||||
|
||||
処置: コミュニティリーダーが、非公開の書面による警告を送ります。違反の内容を明らかにし、その行動がなぜ不適切だったかを説明します。公の場での謝罪を求めることがあります。
|
||||
|
||||
### 2. 警告
|
||||
|
||||
コミュニティへの影響: 1 回の出来事、または一連の行動による違反。
|
||||
|
||||
処置: 行動が続いた場合の処置を示した警告を送ります。警告を受けた人は、定められた期間、関係する人々とやり取りしてはいけません。行動規範を執行する人々へ、求められていないのに接触することも、これに含まれます。コミュニティの場だけでなく、ソーシャルメディアなど外部の場でのやり取りも避けなければなりません。これらの条件に違反すると、一時的または永久的な参加禁止につながることがあります。
|
||||
|
||||
### 3. 一時的な参加禁止
|
||||
|
||||
コミュニティへの影響: 不適切な行動を続けることを含む、コミュニティの基準への重大な違反。
|
||||
|
||||
処置: 定められた期間、コミュニティとのあらゆるやり取りと、コミュニティに向けた公の発信を禁止します。この期間中は、公の場か私的な場かを問わず、関係する人々とのやり取りを認めません。行動規範を執行する人々へ、求められていないのに接触することも、これに含まれます。これらの条件に違反すると、永久的な参加禁止につながることがあります。
|
||||
|
||||
### 4. 永久的な参加禁止
|
||||
|
||||
コミュニティへの影響: コミュニティの基準に繰り返し違反すること。不適切な行動を続けること、個人への嫌がらせ、特定の属性を持つ人々への攻撃や中傷も、これに当たります。
|
||||
|
||||
処置: コミュニティの中でのあらゆる公のやり取りを、永久に禁止します。
|
||||
|
||||
## 出典
|
||||
|
||||
この行動規範は、[Contributor Covenant][homepage] のバージョン 2.0 を基にしています。原文は https://www.contributor-covenant.org/version/2/0/code_of_conduct.html にあります。日本語の文は、公式の日本語訳 https://www.contributor-covenant.org/ja/version/2/0/code_of_conduct/ を基に、原文と照らし合わせて改めたものです。
|
||||
|
||||
Contributor Covenant は、[クリエイティブ・コモンズ 表示 4.0 国際 ライセンス](https://creativecommons.org/licenses/by/4.0/deed.ja)のもとで提供されています。
|
||||
|
||||
コミュニティへの影響に応じたガイドラインは、[Mozilla の行動規範の執行の段階](https://github.com/mozilla/diversity)に着想を得ています。
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
この行動規範についてのよくある質問と回答は、https://www.contributor-covenant.org/faq にあります。ほかの言語の訳は、https://www.contributor-covenant.org/translations にあります。
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
# 貢献の手引き
|
||||
|
||||
本プラグインへの貢献に関心を持っていただき、ありがとうございます。この手引きは、Issue の立て方、プルリクエストの作り方、変更の確かめ方、コードとコミットの書き方を定めます。
|
||||
|
||||
本プラグインでできることとできないことは、[README](README.md) に書いてあります。まず README を読んでください。
|
||||
|
||||
---
|
||||
|
||||
## 目次
|
||||
|
||||
1. [貢献の進め方](#貢献の進め方)
|
||||
2. [開発環境](#開発環境)
|
||||
3. [Issue](#issue)
|
||||
4. [プルリクエスト](#プルリクエスト)
|
||||
5. [検証](#検証)
|
||||
6. [コードの規約](#コードの規約)
|
||||
7. [コミットの規約](#コミットの規約)
|
||||
8. [行動規範](#行動規範)
|
||||
|
||||
---
|
||||
|
||||
## 貢献の進め方
|
||||
|
||||
誤字の修正、文書の修正、軽微な不具合の修正は、そのままプルリクエストを送ってください。
|
||||
|
||||
新しい機能、設定の項目や既定値の変更、大きめの不具合の修正、意図して出力を変える変更、互換性を損なう変更、コードの構成を大きく変える変更は、先に Issue を立ててください。実装を始める前に、意図する動きと変更の範囲について合意するためです。どちらに当たるか迷ったときも、Issue を立ててください。
|
||||
|
||||
脆弱性は Issue に書かず、[セキュリティポリシー](SECURITY.md)に従って非公開で報告してください。
|
||||
|
||||
Issue とプルリクエストは、日本語か英語で書いてください。
|
||||
|
||||
---
|
||||
|
||||
## 開発環境
|
||||
|
||||
| 項目 | 要件 |
|
||||
|---|---|
|
||||
| OS | Windows 10 バージョン 2004 以降の 64bit 版 |
|
||||
| SDK | .NET 10 |
|
||||
| YukkuriMovieMaker4 | ビルドがインストール先の DLL を参照するため、手元に入れておく |
|
||||
| シェーダーのビルド | HLSL をビルドのときにコンパイルするリポジトリでは Windows SDK が要る。シェーダーを `.vcxproj` でビルドするリポジトリでは、Visual Studio 2026 の「C++ によるデスクトップ開発」も要る |
|
||||
|
||||
### 取得
|
||||
|
||||
リポジトリをフォークし、自分のフォークをクローンしてください。リポジトリはサブモジュールを含むことがあるので、`--recursive` を付けます。
|
||||
|
||||
```console
|
||||
git clone --recursive https://github.com/<自分のアカウント>/<リポジトリ名>.git
|
||||
```
|
||||
|
||||
`--recursive` を付けずにクローンしたときは、後から次のコマンドでサブモジュールを取得できます。
|
||||
|
||||
```console
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
作業は `main` から切ったブランチで行ってください。
|
||||
|
||||
### YukkuriMovieMaker4 の場所
|
||||
|
||||
YukkuriMovieMaker4 のインストール先は、MSBuild のプロパティ `YMM4DirPath` で渡します。値の末尾には `\` を付けてください。
|
||||
|
||||
- コマンドラインでは、`-p:YMM4DirPath="<インストール先>\"` を付けてビルドします。PowerShell 7 以降で実行してください。Windows PowerShell 5.1 と cmd では、末尾の `\"` が正しく渡らないため、末尾を `\\"` と書いてください。
|
||||
- Visual Studio でビルドするときは、プラグインのプロジェクトのフォルダーか、その上のフォルダーに `Directory.Build.props` があれば、その `YMM4DirPath` を手元で書き換えます。無ければ、環境変数 `YMM4DirPath` を設定します。書き換えた `Directory.Build.props` はコミットに含めないでください。サブモジュールの中にある `Directory.Build.props` は書き換えないでください。
|
||||
|
||||
### ビルド
|
||||
|
||||
ソリューションを開き、Release でビルドしてください。
|
||||
|
||||
シェーダーを `.vcxproj` でビルドするリポジトリでは、コマンドラインのビルドに Visual Studio の MSBuild を使ってください。.NET SDK の `dotnet` コマンドは `.vcxproj` を扱えません。テストは、`dotnet test <名前>.Tests\<名前>.Tests.csproj` のようにテストのプロジェクトのファイルを指定して実行してください。ビルドの手順は、`.github/workflows/release.yml` があればそこに書いてあります。
|
||||
|
||||
多くのリポジトリでは、ビルドの後にプラグインが YukkuriMovieMaker4 の `user\plugin` フォルダーへ自動でコピーされます。
|
||||
|
||||
- YukkuriMovieMaker4 を起動したままだと、コピーの段階で失敗します。ビルドの前に終了してください。
|
||||
- 配布版のプラグインを入れているときは、同じ名前のファイルが上書きされます。
|
||||
- コマンドラインでソリューションをビルドしたときはコピーしないリポジトリがあります。その場合は、プラグインのプロジェクトを指定してビルドしてください。
|
||||
- `.csproj` に `SkipPluginDeploy` の条件があるリポジトリでは、`-p:SkipPluginDeploy=true` を付けるとコピーせずにビルドできます。
|
||||
|
||||
---
|
||||
|
||||
## Issue
|
||||
|
||||
Issue はテンプレートから立ててください。不具合の報告、文書の不備、機能の提案、使い方の質問の 4 つがあります。
|
||||
|
||||
不具合の報告には、次の内容を書いてください。
|
||||
|
||||
- 期待した動きと、実際の動き
|
||||
- 再現の手順。できれば、問題が起きる最小のプロジェクトファイルや素材
|
||||
- プラグインのバージョン、YukkuriMovieMaker4 のバージョン、Windows のバージョン
|
||||
- 描画や GPU に関わる不具合では、GPU の名前とドライバーのバージョン
|
||||
- エラー画面に出た内容。省略せずに貼ってください
|
||||
|
||||
ときどきしか起きない不具合も、確実な再現の手順が無いまま報告して構いません。何回試して何回起きたかと、どの操作の後に起きたかを書いてください。
|
||||
|
||||
コードを読んで見つけた不具合を報告するときは、実際に再現を確かめたかどうかも書いてください。
|
||||
|
||||
Issue に添付したファイルは、誰でも見られます。プロジェクトファイルには、素材を置いたフォルダーのパスが記録されています。パスにユーザー名が含まれることがあるので、公開できない情報が無いかを確かめてから添付してください。
|
||||
|
||||
不具合の情報を自動で送信するプラグインでも、Issue での報告には意味があります。自動で送られるのは、例外の内容と実行環境の一部です。そこに至った操作、YukkuriMovieMaker4 のバージョン、GPU、例外を伴わない描画の乱れは届きません。
|
||||
|
||||
---
|
||||
|
||||
## プルリクエスト
|
||||
|
||||
1 つのプルリクエストには、1 つの目的の変更だけを含めてください。関係の無い整理、整形、依存関係の更新を含めないでください。依存関係を更新するのは、必要な機能を使うため、不具合やセキュリティの問題を直すため、互換性を保つためなど、具体的な理由があるときだけにしてください。
|
||||
|
||||
特に注意が要るのは、次の箇所です。
|
||||
|
||||
- 設定の項目と、その既定値と範囲。保存済みのプロジェクトの結果が変わるおそれがある
|
||||
- 出力の結果。変えるつもりの無い変更で、映像や音が変わっていないか
|
||||
- GPU のリソース、ファイル、ハンドルの寿命
|
||||
- 破棄の処理と、失敗したときの処理
|
||||
- YukkuriMovieMaker4 の内部に手を入れるプラグインでは、YukkuriMovieMaker4 のバージョンによる違い
|
||||
|
||||
動きを変えたときは、同じプルリクエストで README を直してください。`.github/Plugin_Readme.txt` があるリポジトリでは、それも直してください。`Plugin_Readme.txt` は配布パッケージに `Readme.txt` として入り、利用者の手元に残ります。
|
||||
|
||||
バージョンを上げる変更は、プルリクエストに含めないでください。バージョンの更新とリリースは、開発者が行います。
|
||||
|
||||
レビューを受けて直すときは、コミットを目的ごとのまとまりに保つため、ブランチの履歴を組み直して強制プッシュして構いません。
|
||||
|
||||
プルリクエストを送った時点で、その貢献をリポジトリと同じライセンスで提供することに同意したものとみなします。リポジトリのライセンスは、リポジトリの直下にあるライセンスのファイルに書いてあります。
|
||||
|
||||
---
|
||||
|
||||
## 検証
|
||||
|
||||
プルリクエストには、手元で実際に確かめた結果を書いてください。
|
||||
|
||||
- ビルドの結果と、テストのプロジェクトがあればテストの結果
|
||||
- YukkuriMovieMaker4 で実際に動かして確かめたこと。使った YukkuriMovieMaker4 のバージョンを添え、GPU に関わる変更では GPU の名前とドライバーのバージョンも添えてください
|
||||
- 実行できなかったテストと、その理由
|
||||
|
||||
実際に動かして観察したこと、コードを読んで判断したこと、推測したことを分けて書いてください。
|
||||
|
||||
出力を変えるつもりの無い変更では、変更前と変更後で出力が一致することを確かめてください。`--golden` と `--verify` を持つハーネスのプロジェクトがあるリポジトリでは、それで描画を比べられます。基準値は、手元の環境で変更前のコミットから作り直し、作り直した基準値はコミットに含めないでください。そのようなハーネスが無いリポジトリでは、変更前と変更後の出力を比べてください。サブモジュールの中にあるハーネスは、この確認には使いません。
|
||||
|
||||
性能の改善を主張するときは、1 回の測定で判断しないでください。
|
||||
|
||||
- 同じ機材、ドライバー、設定、電源の条件で、変更前と変更後のビルドを交互に繰り返し測ってください。
|
||||
- GPU と CPU の温度で値が変わるため、測定の間を空けてください。
|
||||
- ほかのプロセスが GPU を使っていない状態で測ってください。
|
||||
- 正しさの確認と性能の測定は、別々に実行してください。確認のための処理が、測定値を変えるためです。
|
||||
|
||||
---
|
||||
|
||||
## コードの規約
|
||||
|
||||
変更する箇所で既に使われている実装のパターンと書き方に従ってください。既存の実装どうしが食い違っているときは、どちらかを機械的にまねず、README とテストに照らして意図された動きを確かめ、それに合うほうへ揃えてください。
|
||||
|
||||
自分の変更で増えたビルドの警告は、放置せず原因を直してください。
|
||||
|
||||
新しく書くコードには、コメントを入れず、コメントアウトしたコードも残さないでください。既存のコードにあるコメントとドキュメントコメントは残してください。
|
||||
|
||||
---
|
||||
|
||||
## コミットの規約
|
||||
|
||||
- 1 つのコミットは、目的ごとのまとまりを保てる範囲で、できるだけ小さくしてください。どのコミットも、それ単独でビルドが通るようにしてください。
|
||||
- 実装の変更と、それを確かめるテストは、別のコミットに分けてください。
|
||||
- 件名は日本語で書き、50 文字以内に収め、「〜する」の形で終えてください。「〜を追加する」「〜を直す」はよい例です。「〜の追加」「〜を修正」のように名詞で終える形は使いません。
|
||||
- 件名を日本語で書けないときは、プルリクエストにその旨を書いてください。
|
||||
- 本文は書かないでください。例外は、リリースノートでの変更の分類を指定する行だけです。この行が要るときは、書き方をレビューで伝えます。
|
||||
|
||||
---
|
||||
|
||||
## 行動規範
|
||||
|
||||
貢献するすべての人に、[行動規範](CODE_OF_CONDUCT.md)に従うことを求めます。
|
||||
-1
サブモジュール ComputeSharp が 7c4145d5f2 から削除されました。
@@ -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>
|
||||
@@ -0,0 +1,55 @@
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace LowPolyAbstraction.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} がありません。");
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Diagnostics;
|
||||
using Vortice.Direct3D11;
|
||||
|
||||
namespace LowPolyAbstraction.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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
namespace LowPolyAbstraction.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 つだけ指定してください。");
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
namespace LowPolyAbstraction.Harness;
|
||||
|
||||
internal static class HarnessCases
|
||||
{
|
||||
public static IEnumerable<(string Name, LowPolyAbstractionEffect Effect, IReadOnlyList<int> Frames)> All()
|
||||
{
|
||||
yield return ("default", Create(), [0]);
|
||||
yield return ("default-frames-0-8", Create(), Enumerable.Range(0, 9).ToArray());
|
||||
yield return ("amount-0", Create(effect => effect.Amount.Values[0].Value = 0), [0]);
|
||||
yield return ("amount-50", Create(effect => effect.Amount.Values[0].Value = 50), [0]);
|
||||
yield return ("quality-balanced", Create(effect => effect.Quality = LowPolyAbstractionQuality.Balanced), [0]);
|
||||
yield return ("quality-ultra", Create(effect => effect.Quality = LowPolyAbstractionQuality.Ultra), [0]);
|
||||
yield return ("detail-0", Create(effect => effect.Detail.Values[0].Value = 0), [0]);
|
||||
yield return ("detail-100", Create(effect => effect.Detail.Values[0].Value = 100), [0]);
|
||||
yield return ("fidelity-0", Create(effect => effect.Fidelity.Values[0].Value = 0), [0]);
|
||||
yield return ("fidelity-100", Create(effect => effect.Fidelity.Values[0].Value = 100), [0]);
|
||||
yield return ("refine-0", Create(effect => effect.Refine.Values[0].Value = 0), [0]);
|
||||
yield return ("refine-100", Create(effect => effect.Refine.Values[0].Value = 100), [0]);
|
||||
yield return ("seed-42", Create(effect => effect.Seed = 42), [0]);
|
||||
yield return ("gradient-0", Create(effect => effect.Gradient.Values[0].Value = 0), [0]);
|
||||
yield return ("gradient-100", Create(effect => effect.Gradient.Values[0].Value = 100), [0]);
|
||||
yield return ("wireframe-50", Create(effect => effect.Wireframe.Values[0].Value = 50), [0]);
|
||||
yield return ("wireframe-100", Create(effect => effect.Wireframe.Values[0].Value = 100), [0]);
|
||||
yield return ("saturation-0", Create(effect => effect.Saturation.Values[0].Value = 0), [0]);
|
||||
yield return ("saturation-100", Create(effect => effect.Saturation.Values[0].Value = 100), [0]);
|
||||
yield return ("jitter-0", Create(effect => effect.Jitter.Values[0].Value = 0), [0]);
|
||||
yield return ("jitter-100", Create(effect => effect.Jitter.Values[0].Value = 100), [0]);
|
||||
}
|
||||
|
||||
public static IEnumerable<(string Name, Func<LowPolyAbstractionEffect> Create, Action<LowPolyAbstractionEffect> Change, int Frame)> Transitions()
|
||||
{
|
||||
yield return ("quality-high-to-ultra", () => Create(), effect => effect.Quality = LowPolyAbstractionQuality.Ultra, 0);
|
||||
yield return ("detail-60-to-100", () => Create(), effect => effect.Detail.Values[0].Value = 100, 0);
|
||||
yield return ("fidelity-70-to-0", () => Create(), effect => effect.Fidelity.Values[0].Value = 0, 0);
|
||||
yield return ("refine-50-to-100", () => Create(), effect => effect.Refine.Values[0].Value = 100, 0);
|
||||
yield return ("seed-0-to-42", () => Create(), effect => effect.Seed = 42, 0);
|
||||
yield return ("gradient-30-to-100", () => Create(), effect => effect.Gradient.Values[0].Value = 100, 0);
|
||||
yield return ("wireframe-0-to-100", () => Create(), effect => effect.Wireframe.Values[0].Value = 100, 0);
|
||||
yield return ("saturation-30-to-100", () => Create(), effect => effect.Saturation.Values[0].Value = 100, 0);
|
||||
yield return ("jitter-25-to-100", () => Create(), effect => effect.Jitter.Values[0].Value = 100, 0);
|
||||
yield return ("amount-100-to-0", () => Create(), effect => effect.Amount.Values[0].Value = 0, 0);
|
||||
}
|
||||
|
||||
public static IEnumerable<(string Name, LowPolyAbstractionEffect Effect)> Benchmarks()
|
||||
{
|
||||
yield return ("quality-balanced", Create(effect => effect.Quality = LowPolyAbstractionQuality.Balanced));
|
||||
yield return ("default", Create());
|
||||
yield return ("quality-ultra", Create(effect => effect.Quality = LowPolyAbstractionQuality.Ultra));
|
||||
yield return ("detail-100", Create(effect => effect.Detail.Values[0].Value = 100));
|
||||
yield return ("amount-0", Create(effect => effect.Amount.Values[0].Value = 0));
|
||||
}
|
||||
|
||||
public static LowPolyAbstractionEffect Create(Action<LowPolyAbstractionEffect>? configure = null)
|
||||
{
|
||||
var effect = new LowPolyAbstractionEffect();
|
||||
configure?.Invoke(effect);
|
||||
return effect;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
|
||||
namespace LowPolyAbstraction.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);
|
||||
}
|
||||
}
|
||||
@@ -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 LowPolyAbstraction.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);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace LowPolyAbstraction.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;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
namespace LowPolyAbstraction.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);
|
||||
}
|
||||
}
|
||||
@@ -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>LowPolyAbstraction.Harness</AssemblyName>
|
||||
<RootNamespace>LowPolyAbstraction.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="..\LowPolyAbstraction\ComputeSharp.Reference.props" />
|
||||
|
||||
</Project>
|
||||
+394
-164
@@ -1,212 +1,442 @@
|
||||
using System.Diagnostics;
|
||||
using ComputeSharp;
|
||||
using System.IO;
|
||||
using System.IO.Packaging;
|
||||
using System.Security.Cryptography;
|
||||
using ComputeWeave;
|
||||
using LowPolyAbstraction;
|
||||
using LowPolyAbstraction.Harness;
|
||||
using SharpGen.Runtime;
|
||||
|
||||
var width = 1280;
|
||||
var height = 720;
|
||||
var outputDirectory = args.Length > 0 ? 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 = LowPolyAbstractionPipeline.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, LowPolyAbstractionPipeline.Parameters Parameters)[]
|
||||
if (arguments.Mode == HarnessMode.Compare)
|
||||
return Compare(arguments.Before!, arguments.After!);
|
||||
|
||||
if (arguments.Mode == HarnessMode.Structure)
|
||||
{
|
||||
("balanced-default", new(LowPolyAbstractionQuality.Balanced, 0.6f, 0.7f, 0.5f, 0.3f, 0f, 0.3f, 0.25f, 7)),
|
||||
("high-default", new(LowPolyAbstractionQuality.High, 0.6f, 0.7f, 0.5f, 0.3f, 0f, 0.3f, 0.25f, 7)),
|
||||
("seed-42", new(LowPolyAbstractionQuality.Balanced, 0.6f, 0.7f, 0.5f, 0.3f, 0f, 0.3f, 0.25f, 42)),
|
||||
("coarse-detail", new(LowPolyAbstractionQuality.Balanced, 0.1f, 0.7f, 0.5f, 0.3f, 0f, 0.3f, 0.25f, 7)),
|
||||
("fine-detail", new(LowPolyAbstractionQuality.Balanced, 1f, 0.7f, 0.5f, 0.3f, 0f, 0.3f, 0.25f, 7)),
|
||||
("flat-fill", new(LowPolyAbstractionQuality.Balanced, 0.6f, 0.7f, 0.5f, 0f, 0f, 0f, 0f, 7)),
|
||||
("wireframe", new(LowPolyAbstractionQuality.Balanced, 0.6f, 0.7f, 0.5f, 0.3f, 1f, 0.3f, 0.25f, 7)),
|
||||
("no-refine", new(LowPolyAbstractionQuality.Balanced, 0.6f, 0.7f, 0f, 0.3f, 0f, 0.3f, 0.25f, 7)),
|
||||
};
|
||||
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[] { LowPolyAbstractionQuality.Balanced, LowPolyAbstractionQuality.High, LowPolyAbstractionQuality.Ultra })
|
||||
static int Verify(HarnessRenderer renderer, HarnessImage image)
|
||||
{
|
||||
var parameters = new LowPolyAbstractionPipeline.Parameters(quality, 0.6f, 0.7f, 0.5f, 0.3f, 0f, 0.3f, 0.25f, 7);
|
||||
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 = LowPolyAbstractionPipeline.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 LowPolyAbstractionPipeline.Parameters(LowPolyAbstractionQuality.High, 0.6f, 0.7f, 0.5f, 0.3f, 0f, 0.3f, 0.25f, 7);
|
||||
pipeline.Simulate(sourceTexture, image.Width, image.Height, 0, 0, image.Width, image.Height, in parameters);
|
||||
pipeline.WaitForCompletion();
|
||||
var stopwatch = new Stopwatch();
|
||||
|
||||
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 { Seed = 8 });
|
||||
stopwatch.Stop();
|
||||
Console.WriteLine($"structure recompute: {stopwatch.Elapsed.TotalMilliseconds:F2} ms");
|
||||
var variants = new (string Name, Func<bool, LowPolyAbstractionPipeline.Parameters> Make)[]
|
||||
{
|
||||
("cached", _ => parameters),
|
||||
("detail", flip => parameters with { Detail = flip ? 0.70f : 0.60f }),
|
||||
("fidelity", flip => parameters with { Fidelity = flip ? 0.80f : 0.70f }),
|
||||
("refine", flip => parameters with { Refine = flip ? 0.60f : 0.50f }),
|
||||
("seed", flip => parameters with { Seed = flip ? 8 : 7 }),
|
||||
("all", flip => parameters with
|
||||
{
|
||||
Detail = flip ? 0.70f : 0.60f,
|
||||
Fidelity = flip ? 0.80f : 0.70f,
|
||||
Refine = flip ? 0.60f : 0.50f,
|
||||
Seed = flip ? 8 : 7,
|
||||
}),
|
||||
};
|
||||
|
||||
if (pipeline.TryGetVisibleBounds(width, height, in parameters, out var rect))
|
||||
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(sourceTexture, rectOutput, width, height, 0, 0, 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(sourceTexture, rectOutput, width, height, 0, 0, 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 detail in new[] { 0.1f, 0.4f, 0.7f, 1f })
|
||||
{
|
||||
var parameters = new LowPolyAbstractionPipeline.Parameters(LowPolyAbstractionQuality.High, detail, 0.7f, 0.5f, 0.3f, 0f, 0.3f, 0.25f, 7);
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
Console.WriteLine($"detail={detail:F2} litPixels={CountLit(destination)}");
|
||||
WriteBmp(Path.Combine(outputDirectory, $"detail{(int)(detail * 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 gradient in new[] { 0f, 0.5f, 1f })
|
||||
static List<GoldenCase> Evaluate(HarnessRenderer renderer, Action<GoldenCase, string[], byte[][]>? report)
|
||||
{
|
||||
var parameters = new LowPolyAbstractionPipeline.Parameters(LowPolyAbstractionQuality.High, 0.6f, 0.7f, 0.5f, gradient, 0f, 0.3f, 0.25f, 7);
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
Console.WriteLine($"gradient={gradient:F2} litPixels={CountLit(destination)}");
|
||||
WriteBmp(Path.Combine(outputDirectory, $"gradient{(int)(gradient * 100):D3}.bmp"), Composite(source, destination), width, height);
|
||||
}
|
||||
|
||||
foreach (var wireframe in new[] { 0f, 0.5f, 1f })
|
||||
{
|
||||
var parameters = new LowPolyAbstractionPipeline.Parameters(LowPolyAbstractionQuality.High, 0.6f, 0.7f, 0.5f, 0.3f, wireframe, 0.3f, 0.25f, 7);
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
Console.WriteLine($"wireframe={wireframe:F2} litPixels={CountLit(destination)}");
|
||||
WriteBmp(Path.Combine(outputDirectory, $"wireframe{(int)(wireframe * 100):D3}.bmp"), Composite(source, destination), width, height);
|
||||
}
|
||||
|
||||
WriteBmp(Path.Combine(outputDirectory, "source.bmp"), source, 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 / 2;
|
||||
var centerY = height / 2;
|
||||
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 dx = x - centerX;
|
||||
var dy = y - centerY;
|
||||
var radius = Math.Sqrt(dx * dx + dy * dy);
|
||||
if (radius > 240d)
|
||||
continue;
|
||||
var angle = Math.Atan2(dy, dx);
|
||||
var r = (int)(140 + 100 * Math.Cos(angle * 3d));
|
||||
var g = (int)(120 + 80 * Math.Sin(radius * 0.03d));
|
||||
var b = (int)(150 + 90 * Math.Sin(angle * 2d + radius * 0.02d));
|
||||
r = Math.Clamp(r, 0, 255);
|
||||
g = Math.Clamp(g, 0, 255);
|
||||
b = Math.Clamp(b, 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[] poly)
|
||||
{
|
||||
var result = new int[source.Length];
|
||||
for (var index = 0; index < source.Length; index++)
|
||||
{
|
||||
var s = source[index];
|
||||
var p = poly[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] = a << 24 | r << 16 | g << 8 | b;
|
||||
}
|
||||
return result;
|
||||
|
||||
static int Over(int s, int p, int pa) => Math.Min(p + s * (255 - pa) / 255, 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
namespace LowPolyAbstraction.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);
|
||||
}
|
||||
@@ -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": "D980ED4430735F411D334F54C241E610D39BAA14B10178D1AC3C90E114428356"
|
||||
},
|
||||
{
|
||||
"name": "default-frames-0-8",
|
||||
"frames": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8
|
||||
],
|
||||
"hash": "DDA237F119919E002DAF8227965F6980AA80C3B5DCA6CA65F3EBAFC502E28EB6"
|
||||
},
|
||||
{
|
||||
"name": "amount-0",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "0A700F76CEDDBAD7C4B6A2C19D46939C1A93940E86C6EFEF1E5A53DB48D2A020"
|
||||
},
|
||||
{
|
||||
"name": "amount-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "55EECEF3F4A754811F0BEBA81EA9C845F2E18854084F03793E048E988E688262"
|
||||
},
|
||||
{
|
||||
"name": "quality-balanced",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "97D1B5D44C5DFA2CC644162BDE03996B6A7332841CE5A06FE42A7011CA1E9A44"
|
||||
},
|
||||
{
|
||||
"name": "quality-ultra",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "D76684D9AF6F114E0FAE947634210EEEBFC8D7E9966F3A72AF477804A56D91CB"
|
||||
},
|
||||
{
|
||||
"name": "detail-0",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "073DF992E1E7E7F425F2C5A24B98FE77C3ED4B291376C79BE3E90FFE5DE6241A"
|
||||
},
|
||||
{
|
||||
"name": "detail-100",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "5FB3ECB4A51BEE5354B741E6CBEECA8B42D09948F30354D8624C5CFB297B314E"
|
||||
},
|
||||
{
|
||||
"name": "fidelity-0",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "96F9950CCB188A27953F6ABCBF3B81807CC2A8FF789E0F257AAC0279DC14D193"
|
||||
},
|
||||
{
|
||||
"name": "fidelity-100",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "346060B67DD4BE083A57B909F9005D2F852CA426A7F51CBD6463A60708365E13"
|
||||
},
|
||||
{
|
||||
"name": "refine-0",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "51FF4D5C490DE0914413023674D24046677D188D5611A5CC9DA29CA9B46CC82A"
|
||||
},
|
||||
{
|
||||
"name": "refine-100",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "17B0EDA3A75F16320F27A34AF9ACE524A41A68A41821280CD0076C2EBD50B736"
|
||||
},
|
||||
{
|
||||
"name": "seed-42",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "EADEB5F480B449B7F06CB3964699A9E90C3A8A5379EDD0102136F1FA93801E80"
|
||||
},
|
||||
{
|
||||
"name": "gradient-0",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "C881CFA2B3A5310F6F034F40568DA990C31679B139E230C838B6AA5DB02DEF57"
|
||||
},
|
||||
{
|
||||
"name": "gradient-100",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "6DE64CB761409CD2F2AE388AD9FD30876428AD42DD79237B40B58F81984915CE"
|
||||
},
|
||||
{
|
||||
"name": "wireframe-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "DBA4C73670BCF0BC66AD8FD0FC5DE2EF1E5E700A07A967DDBC9BF7B66A18312B"
|
||||
},
|
||||
{
|
||||
"name": "wireframe-100",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "7EE721A7C82B2FF5EFD86EF580147818F68CE59369D5EB719FAAD2DF84725600"
|
||||
},
|
||||
{
|
||||
"name": "saturation-0",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "2A690FED58F1E8E1E23607F3B75981EC28858D577064783ADAE69B065056A902"
|
||||
},
|
||||
{
|
||||
"name": "saturation-100",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "4EB8D314AE7012000D149A90EEF11CCA08B4839FA97423CD194C761AC1FEED56"
|
||||
},
|
||||
{
|
||||
"name": "jitter-0",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "BFA9BA597C530467FFC82BBBA16298EC9F85F030C55D3AD78394E84C9A9D0E35"
|
||||
},
|
||||
{
|
||||
"name": "jitter-100",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "284CAA9BA829A392ED3C638816A8E8C76EFC9C0F73EC8003745A673ECB635028"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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>{A23CD30E-4BB3-4CA4-8169-84A834009246}</ProjectGuid>
|
||||
<RootNamespace>LowPolyAbstractionShader</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="LowPolyAbstraction.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>
|
||||
@@ -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="LowPolyAbstraction.hlsl">
|
||||
<Filter>ソース ファイル</Filter>
|
||||
</FxCompile>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
+3
-1
@@ -24,6 +24,8 @@ float4 main(
|
||||
|
||||
float4 poly = PolyTexture.SampleLevel(PolySampler, uv1.xy, 0);
|
||||
poly.rgb = min(poly.rgb, poly.a.xxx);
|
||||
float4 blended = poly + source * (1.0 - poly.a);
|
||||
poly *= poly.a > source.a ? source.a / poly.a : 1.0;
|
||||
float covered = source.a > 0.0 ? saturate(poly.a / source.a) : 1.0;
|
||||
float4 blended = poly + source * (1.0 - covered);
|
||||
return lerp(source, blended, amount);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace LowPolyAbstraction.Tests;
|
||||
|
||||
internal readonly record struct Bgra(byte Blue, byte Green, byte Red, byte Alpha)
|
||||
{
|
||||
public static Bgra Transparent => default;
|
||||
|
||||
public static Bgra Opaque(byte blue, byte green, byte red) => new(blue, green, red, byte.MaxValue);
|
||||
|
||||
public Bgra Premultiplied() => new(Premultiply(Blue), Premultiply(Green), Premultiply(Red), Alpha);
|
||||
|
||||
byte Premultiply(byte value) => (byte)Math.Round(value * (double)Alpha / byte.MaxValue, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.Drawing;
|
||||
using System.Numerics;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace LowPolyAbstraction.Tests;
|
||||
|
||||
internal static class EffectDescriptions
|
||||
{
|
||||
public const int Fps = 30;
|
||||
|
||||
static readonly Size ScreenSize = new(1920, 1080);
|
||||
|
||||
public static EffectDescription At(int frame, int length)
|
||||
{
|
||||
var timeline = new TimelineSourceDescription(
|
||||
ScreenSize,
|
||||
new FrameTime(frame, Fps),
|
||||
new FrameTime(length, Fps),
|
||||
Fps,
|
||||
TimelineSourceUsage.Playing,
|
||||
Guid.Empty,
|
||||
[]);
|
||||
var item = new TimelineItemSourceDescription(timeline, frame, length, 0);
|
||||
var draw = new DrawDescription(Vector3.Zero, Vector2.Zero, Vector2.One, Vector3.Zero, Matrix4x4.Identity, InterpolationMode.Linear, 1d, false, []);
|
||||
return new EffectDescription(item, draw, 0, 1, 0, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace LowPolyAbstraction.Tests;
|
||||
|
||||
internal static class HostAssemblyResolver
|
||||
{
|
||||
const string MetadataKey = "HostDirectory";
|
||||
const string AssemblyExtension = ".dll";
|
||||
|
||||
public static string Directory { get; } = ReadDirectory();
|
||||
|
||||
public static bool IsConfigured => Directory.Length != 0 && System.IO.Directory.Exists(Directory);
|
||||
|
||||
[ModuleInitializer]
|
||||
internal static void Initialize()
|
||||
{
|
||||
if (!IsConfigured)
|
||||
return;
|
||||
|
||||
AppDomain.CurrentDomain.AssemblyResolve += (_, arguments) =>
|
||||
{
|
||||
var name = new AssemblyName(arguments.Name).Name;
|
||||
if (name is null)
|
||||
return null;
|
||||
|
||||
var candidate = Path.Combine(Directory, name + AssemblyExtension);
|
||||
return File.Exists(candidate) ? Assembly.LoadFrom(candidate) : null;
|
||||
};
|
||||
}
|
||||
|
||||
static string ReadDirectory() => typeof(HostAssemblyResolver).Assembly
|
||||
.GetCustomAttributes<AssemblyMetadataAttribute>()
|
||||
.FirstOrDefault(attribute => string.Equals(attribute.Key, MetadataKey, StringComparison.Ordinal))
|
||||
?.Value ?? string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using System.Windows;
|
||||
using Telemetry;
|
||||
|
||||
namespace LowPolyAbstraction.Tests;
|
||||
|
||||
public sealed class HostIntegrationTests
|
||||
{
|
||||
[Fact]
|
||||
public void OutsideAWpfApplicationNoTelemetryIsStartedOrSent()
|
||||
{
|
||||
Assert.Null(Application.Current);
|
||||
|
||||
LowPolyAbstractionTelemetry.EnsureStartedOnce();
|
||||
LowPolyAbstractionTelemetry.Report(new InvalidOperationException());
|
||||
|
||||
Assert.Null(ProcessState.Read("DrainClaimed"));
|
||||
Assert.Null(ProcessState.Read("SentCount"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OutsideAWpfApplicationTheEffectCanStillBeCreated()
|
||||
{
|
||||
Assert.Null(Application.Current);
|
||||
|
||||
var effect = new LowPolyAbstractionEffect();
|
||||
|
||||
Assert.Equal(Texts.LowPolyAbstraction, effect.Label);
|
||||
Assert.Null(ProcessState.Read("DrainClaimed"));
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
@@ -12,50 +13,67 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="10.0.1">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.6.0" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="xunit.v3" Version="3.2.2" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.10.1" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.0">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="xunit.v3" Version="4.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\LowPolyAbstraction\LowPolyAbstraction.csproj" SetConfiguration="Configuration=$(Configuration)" SetPlatform="Platform=x64">
|
||||
<ProjectReference Include="..\LowPolyAbstraction\LowPolyAbstraction.csproj" SetConfiguration="Configuration=$(Configuration)">
|
||||
<AdditionalProperties Condition="'$(BuildingSolutionFile)' != 'true'">SkipPluginDeploy=true</AdditionalProperties>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyMetadata Include="HostDirectory" Value="$(YMM4DirPath)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="Newtonsoft.Json">
|
||||
<HintPath>$(YMM4DirPath)Newtonsoft.Json.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="SharpGen.Runtime">
|
||||
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="SharpGen.Runtime.COM">
|
||||
<HintPath>$(YMM4DirPath)SharpGen.Runtime.COM.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Direct2D1">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Direct2D1.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Direct3D11">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Direct3D11.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DirectX">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DirectX.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DXGI">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DXGI.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Mathematics">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="YukkuriMovieMaker.Plugin">
|
||||
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Plugin.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>
|
||||
|
||||
@@ -63,6 +81,4 @@
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<Import Project="..\LowPolyAbstraction\ComputeSharp.Reference.props" />
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,205 @@
|
||||
using System.Numerics;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LowPolyAbstraction.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class LowPolyAbstractionCustomEffectTests
|
||||
{
|
||||
const int AmountIndex = 0;
|
||||
const int Width = 40;
|
||||
const int Height = 24;
|
||||
|
||||
static readonly Bgra Blue = Bgra.Opaque(255, 0, 0);
|
||||
static readonly Bgra HalfPoly = new(0, 0, 0, 128);
|
||||
|
||||
static Rendering Render(IGraphicsDevicesAndContext devices, ID2D1Image source, ID2D1Image poly, float amount)
|
||||
{
|
||||
using var effect = new LowPolyAbstractionCustomEffect(devices);
|
||||
effect.SetInput(0, source, true);
|
||||
effect.SetInput(1, poly, true);
|
||||
effect.Amount = amount;
|
||||
using var output = effect.Output;
|
||||
return Rendering.Capture(devices, output);
|
||||
}
|
||||
|
||||
static AffineTransform2D Translate(IGraphicsDevicesAndContext devices, ID2D1Image image, float dx, float dy)
|
||||
{
|
||||
var transform = new AffineTransform2D(devices.DeviceContext)
|
||||
{
|
||||
InterPolationMode = AffineTransform2DInterpolationMode.NearestNeighbor,
|
||||
BorderMode = BorderMode.Hard,
|
||||
TransformMatrix = Matrix3x2.CreateTranslation(dx, dy),
|
||||
};
|
||||
transform.SetInput(0, image, true);
|
||||
return transform;
|
||||
}
|
||||
|
||||
static bool WithinRounding(Bgra expected, Bgra actual)
|
||||
=> Math.Abs(expected.Blue - actual.Blue) <= 1 && Math.Abs(expected.Green - actual.Green) <= 1 && Math.Abs(expected.Red - actual.Red) <= 1 && Math.Abs(expected.Alpha - actual.Alpha) <= 1;
|
||||
|
||||
static Bgra Over(Bgra poly, Bgra source, float amount)
|
||||
{
|
||||
var polyAlpha = poly.Alpha * amount;
|
||||
var keep = 1d - polyAlpha / byte.MaxValue;
|
||||
byte Channel(byte polyValue, byte sourceValue) => (byte)Math.Round(polyValue * amount + sourceValue * keep, MidpointRounding.AwayFromZero);
|
||||
return new Bgra(Channel(poly.Blue, source.Blue), Channel(poly.Green, source.Green), Channel(poly.Red, source.Red), Channel(poly.Alpha, source.Alpha));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheEffectIsEnabledOnceCreated()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var effect = new LowPolyAbstractionCustomEffect(context);
|
||||
|
||||
Assert.True(effect.IsEnabled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheAmountStartsFromZero()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var effect = new LowPolyAbstractionCustomEffect(context);
|
||||
|
||||
Assert.Equal(0f, effect.GetFloatValue(AmountIndex));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-0.5f, 0f)]
|
||||
[InlineData(0f, 0f)]
|
||||
[InlineData(0.4f, 0.4f)]
|
||||
[InlineData(1f, 1f)]
|
||||
[InlineData(1.5f, 1f)]
|
||||
[InlineData(float.MaxValue, 1f)]
|
||||
public void TheAmountIsClampedToTheUnitRange(float value, float expected)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var effect = new LowPolyAbstractionCustomEffect(context);
|
||||
|
||||
effect.Amount = value;
|
||||
|
||||
Assert.Equal(expected, effect.GetFloatValue(AmountIndex));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheOutputBoundsCoverTheSourceAndTheTriangles()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = SourceImage.Solid(context, Width, Height, Blue);
|
||||
using var poly = SourceImage.Solid(context, 8, 8, HalfPoly);
|
||||
using var moved = Translate(context, poly.Bitmap, 50f, -6f);
|
||||
using var movedOutput = moved.Output;
|
||||
using var effect = new LowPolyAbstractionCustomEffect(context);
|
||||
effect.SetInput(0, source.Bitmap, true);
|
||||
effect.SetInput(1, movedOutput, true);
|
||||
using var output = effect.Output;
|
||||
|
||||
var bounds = context.DeviceContext.GetImageLocalBounds(output);
|
||||
|
||||
Assert.Equal(0f, bounds.Left);
|
||||
Assert.Equal(-6f, bounds.Top);
|
||||
Assert.Equal(58f, bounds.Right);
|
||||
Assert.Equal((float)Height, bounds.Bottom);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0f)]
|
||||
[InlineData(-1f)]
|
||||
public void WithoutAmountTheSourcePassesThroughUntouched(float amount)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = SourceImage.Solid(context, Width, Height, Blue);
|
||||
using var poly = SourceImage.Solid(context, Width, Height, HalfPoly);
|
||||
|
||||
var rendering = Render(context, source.Bitmap, poly.Bitmap, amount);
|
||||
|
||||
Assert.All(rendering.Coordinates(), point => Assert.Equal(source[point.X, point.Y], rendering[point.X, point.Y]));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1f)]
|
||||
[InlineData(0.5f)]
|
||||
[InlineData(0.25f)]
|
||||
public void TheTrianglesAreLaidOverTheSourceScaledByTheAmount(float amount)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = SourceImage.Solid(context, Width, Height, Blue);
|
||||
using var poly = SourceImage.Solid(context, Width, Height, HalfPoly);
|
||||
var expected = Over(HalfPoly.Premultiplied(), Blue.Premultiplied(), amount);
|
||||
|
||||
var rendering = Render(context, source.Bitmap, poly.Bitmap, amount);
|
||||
|
||||
Assert.All(rendering.Coordinates(), point => Assert.True(WithinRounding(expected, rendering[point.X, point.Y]), $"({point.X}, {point.Y}) {rendering[point.X, point.Y]}"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1f)]
|
||||
[InlineData(0.5f)]
|
||||
[InlineData(0.25f)]
|
||||
public void TrianglesCoveringASemiTransparentSourceKeepItsOpacity(float amount)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = SourceImage.Solid(context, Width, Height, new Bgra(255, 0, 0, 110));
|
||||
using var poly = SourceImage.Solid(context, Width, Height, new Bgra(0, 0, 255, 110));
|
||||
|
||||
var rendering = Render(context, source.Bitmap, poly.Bitmap, amount);
|
||||
|
||||
Assert.All(rendering.Coordinates(), point => Assert.InRange(rendering[point.X, point.Y].Alpha, 109, 111));
|
||||
if (amount == 1f)
|
||||
Assert.All(rendering.Coordinates(), point => Assert.True(WithinRounding(poly[point.X, point.Y], rendering[point.X, point.Y]), $"({point.X}, {point.Y}) {rendering[point.X, point.Y]}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSourceShowsOnlyThroughThePartTheTrianglesLeaveUncovered()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = SourceImage.Solid(context, Width, Height, new Bgra(255, 0, 0, 200));
|
||||
using var poly = SourceImage.Solid(context, Width, Height, new Bgra(0, 0, 255, 100));
|
||||
var expected = new Bgra(100, 0, 100, 200);
|
||||
|
||||
var rendering = Render(context, source.Bitmap, poly.Bitmap, 1f);
|
||||
|
||||
Assert.All(rendering.Coordinates(), point => Assert.True(WithinRounding(expected, rendering[point.X, point.Y]), $"({point.X}, {point.Y}) {rendering[point.X, point.Y]}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrianglesMoreOpaqueThanTheSourceAreLoweredToItsOpacity()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = SourceImage.Solid(context, Width, Height, new Bgra(255, 0, 0, 100));
|
||||
using var poly = SourceImage.Solid(context, Width, Height, new Bgra(0, 0, 255, 200));
|
||||
var expected = new Bgra(0, 0, 100, 100);
|
||||
|
||||
var rendering = Render(context, source.Bitmap, poly.Bitmap, 1f);
|
||||
|
||||
Assert.All(rendering.Coordinates(), point => Assert.True(WithinRounding(expected, rendering[point.X, point.Y]), $"({point.X}, {point.Y}) {rendering[point.X, point.Y]}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrianglesOutsideTheSourceAreNotDrawn()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = SourceImage.Solid(context, Width, Height, Blue);
|
||||
using var poly = SourceImage.Solid(context, 8, 8, HalfPoly);
|
||||
using var moved = Translate(context, poly.Bitmap, 50f, 4f);
|
||||
using var movedOutput = moved.Output;
|
||||
|
||||
var rendering = Render(context, source.Bitmap, movedOutput, 1f);
|
||||
|
||||
Assert.Equal(Bgra.Transparent, rendering[53, 7]);
|
||||
Assert.Equal(Blue.Premultiplied(), rendering[10, 10]);
|
||||
Assert.Equal(Bgra.Transparent, rendering[45, 10]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using ComputeWeave;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Json;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace LowPolyAbstraction.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class LowPolyAbstractionEffectProcessorTests
|
||||
{
|
||||
const int Size = 64;
|
||||
const int Length = 30;
|
||||
const int Start = 16;
|
||||
const int End = 48;
|
||||
|
||||
static readonly Bgra Red = Bgra.Opaque(0, 0, 255);
|
||||
static readonly Bgra GreenOfTheSameBrightness = Bgra.Opaque(0, 130, 0);
|
||||
|
||||
static Bgra Pattern(int x, int y)
|
||||
{
|
||||
var noise = (int)(((uint)(x * 73856093 ^ y * 19349663) * 0x85EBCA6Bu) >> 26);
|
||||
return Bgra.Opaque((byte)(64 + x * 2 + noise), (byte)(96 + noise), (byte)(224 - x * 2 - noise));
|
||||
}
|
||||
|
||||
static Bgra CenteredSquare(int x, int y) => x is >= Start and < End && y is >= Start and < End ? Pattern(x, y) : Bgra.Transparent;
|
||||
|
||||
static Func<int, int, Bgra> Filled(Bgra color) => (x, y) => x is >= Start and < End && y is >= Start and < End ? color : Bgra.Transparent;
|
||||
|
||||
static void RequireInterop(IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
using var scheduler = ComputeExternalQueueScheduler.Create();
|
||||
using var provider = LowPolyAbstractionInteropProvider.TryCreate(devices, scheduler, out var device);
|
||||
if (provider is null || device is null)
|
||||
Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable.");
|
||||
}
|
||||
|
||||
static Animation Linear(double from, double to)
|
||||
=> Json.LoadFromText<Animation>(string.Create(CultureInfo.InvariantCulture, $$"""{"AnimationType":"直線移動","Values":[{"Value":{{from}}},{"Value":{{to}}}]}"""))!;
|
||||
|
||||
static Rendering RenderFrame(IGraphicsDevicesAndContext devices, IVideoEffectProcessor processor, int frame)
|
||||
{
|
||||
processor.Update(EffectDescriptions.At(frame, Length));
|
||||
return Rendering.Capture(devices, processor.Output);
|
||||
}
|
||||
|
||||
static void AssertSameAsSource(Rendering rendering, SourceImage source)
|
||||
{
|
||||
Assert.Equal((0, 0, source.Width, source.Height), (rendering.Left, rendering.Top, rendering.Width, rendering.Height));
|
||||
Assert.All(rendering.Coordinates(), point => Assert.Equal(source[point.X, point.Y], rendering[point.X, point.Y]));
|
||||
}
|
||||
|
||||
static bool IsRedrawn(Rendering rendering, SourceImage source)
|
||||
=> rendering.Coordinates().Any(point => source.Contains(point.X, point.Y) && source[point.X, point.Y].Alpha > 0 && rendering[point.X, point.Y] != source[point.X, point.Y]);
|
||||
|
||||
[Fact]
|
||||
public void TheProcessorHandsTheDrawDescriptionBackUnchanged()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
using var processor = new LowPolyAbstractionEffect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var description = EffectDescriptions.At(0, Length);
|
||||
|
||||
var draw = processor.Update(description);
|
||||
|
||||
Assert.Same(description.DrawDescription, draw);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSquareIsRedrawnAsTrianglesWithinItsPadding()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
using var processor = new LowPolyAbstractionEffect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var padding = LowPolyAbstractionSettings.MarginPadding;
|
||||
|
||||
var rendering = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(IsRedrawn(rendering, source));
|
||||
Assert.All(rendering.Coordinates(), point =>
|
||||
{
|
||||
var pixel = rendering[point.X, point.Y];
|
||||
Assert.InRange(pixel.Blue, 0, pixel.Alpha);
|
||||
Assert.InRange(pixel.Green, 0, pixel.Alpha);
|
||||
Assert.InRange(pixel.Red, 0, pixel.Alpha);
|
||||
if (point.X < Start - padding || point.X > End + padding || point.Y < Start - padding || point.Y > End + padding)
|
||||
Assert.Equal(Bgra.Transparent, pixel);
|
||||
});
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(100, 50)]
|
||||
[InlineData(-37, 21)]
|
||||
public void TheTrianglesTravelWithTheImage(int dx, int dy)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
using var moved = new AffineTransform2D(context.DeviceContext)
|
||||
{
|
||||
InterPolationMode = AffineTransform2DInterpolationMode.NearestNeighbor,
|
||||
BorderMode = BorderMode.Hard,
|
||||
TransformMatrix = Matrix3x2.CreateTranslation(dx, dy),
|
||||
};
|
||||
moved.SetInput(0, source.Bitmap, true);
|
||||
using var movedOutput = moved.Output;
|
||||
using var inPlaceProcessor = new LowPolyAbstractionEffect().CreateVideoEffect(context);
|
||||
inPlaceProcessor.SetInput(source.Bitmap);
|
||||
var inPlace = RenderFrame(context, inPlaceProcessor, 0);
|
||||
using var travelledProcessor = new LowPolyAbstractionEffect().CreateVideoEffect(context);
|
||||
travelledProcessor.SetInput(movedOutput);
|
||||
|
||||
var travelled = RenderFrame(context, travelledProcessor, 0);
|
||||
|
||||
Assert.True(IsRedrawn(inPlace, source));
|
||||
Assert.Equal((inPlace.Left + dx, inPlace.Top + dy, inPlace.Width, inPlace.Height), (travelled.Left, travelled.Top, travelled.Width, travelled.Height));
|
||||
Assert.All(inPlace.Coordinates(), point => Assert.True(inPlace[point.X, point.Y] == travelled[point.X + dx, point.Y + dy], $"({point.X}, {point.Y})"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AZeroAmountPassesTheImageThrough()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
var effect = new LowPolyAbstractionEffect();
|
||||
effect.Amount.Values[0].Value = 0d;
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var rendering = RenderFrame(context, processor, 0);
|
||||
|
||||
AssertSameAsSource(rendering, source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASourceBelowTheAlphaThresholdPassesThrough()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, (x, y) => CenteredSquare(x, y) with { Alpha = (byte)(CenteredSquare(x, y).Alpha / 32) });
|
||||
using var processor = new LowPolyAbstractionEffect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var rendering = RenderFrame(context, processor, 0);
|
||||
|
||||
AssertSameAsSource(rendering, source);
|
||||
}
|
||||
|
||||
static Bgra Tiled(int x, int y) => Pattern(x % Size, y % Size);
|
||||
|
||||
static readonly int BeyondTheCanvasLimit = LowPolyAbstractionSettings.MaximumCanvasSize - LowPolyAbstractionSettings.MarginPadding * 2 + 1;
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public void AnImageBeyondTheCanvasLimitPassesThrough(bool wide)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = wide
|
||||
? new SourceImage(context, BeyondTheCanvasLimit, 16, Tiled)
|
||||
: new SourceImage(context, 16, BeyondTheCanvasLimit, Tiled);
|
||||
using var processor = new LowPolyAbstractionEffect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var rendering = RenderFrame(context, processor, 0);
|
||||
|
||||
AssertSameAsSource(rendering, source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnImageFillingTheCanvasLimitIsRedrawn()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, BeyondTheCanvasLimit - 1, 16, Tiled);
|
||||
using var processor = new LowPolyAbstractionEffect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var rendering = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(IsRedrawn(rendering, source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnImageAfterOneBeyondTheCanvasLimitIsRedrawnAgain()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
using var oversized = new SourceImage(context, BeyondTheCanvasLimit, 16, Tiled);
|
||||
using var processor = new LowPolyAbstractionEffect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var first = RenderFrame(context, processor, 0);
|
||||
processor.SetInput(oversized.Bitmap);
|
||||
RenderFrame(context, processor, 0);
|
||||
|
||||
processor.SetInput(source.Bitmap);
|
||||
var again = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(IsRedrawn(first, source));
|
||||
Assert.True(again.SamePixelsAs(first));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReturningToAFrameReproducesItExactly()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
using var processor = new LowPolyAbstractionEffect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var first = RenderFrame(context, processor, 4);
|
||||
RenderFrame(context, processor, 9);
|
||||
var again = RenderFrame(context, processor, 4);
|
||||
|
||||
Assert.True(first.SamePixelsAs(again));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ANewProcessorDrawsTheSameTriangles()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
var effect = new LowPolyAbstractionEffect { Seed = 9 };
|
||||
using var firstProcessor = effect.CreateVideoEffect(context);
|
||||
firstProcessor.SetInput(source.Bitmap);
|
||||
var first = RenderFrame(context, firstProcessor, 0);
|
||||
using var secondProcessor = effect.CreateVideoEffect(context);
|
||||
secondProcessor.SetInput(source.Bitmap);
|
||||
|
||||
var second = RenderFrame(context, secondProcessor, 0);
|
||||
|
||||
Assert.True(first.SamePixelsAs(second));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnimatedAmountIsReadAtEachFrame()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
var effect = new LowPolyAbstractionEffect();
|
||||
effect.Amount.CopyFrom(Linear(0d, 100d));
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var start = RenderFrame(context, processor, 0);
|
||||
var end = RenderFrame(context, processor, Length - 1);
|
||||
|
||||
AssertSameAsSource(start, source);
|
||||
Assert.True(IsRedrawn(end, source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARecoloredImageIsDrawnLikeAFreshOne()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var red = new SourceImage(context, Size, Size, Filled(Red));
|
||||
using var green = new SourceImage(context, Size, Size, Filled(GreenOfTheSameBrightness));
|
||||
var effect = new LowPolyAbstractionEffect();
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(red.Bitmap);
|
||||
RenderFrame(context, processor, 0);
|
||||
using var fresh = effect.CreateVideoEffect(context);
|
||||
fresh.SetInput(green.Bitmap);
|
||||
var expected = RenderFrame(context, fresh, 0);
|
||||
|
||||
processor.SetInput(green.Bitmap);
|
||||
var recolored = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(recolored.SamePixelsAs(expected));
|
||||
}
|
||||
|
||||
public static readonly TheoryData<string, Action<LowPolyAbstractionEffect>> LaterChanges = new()
|
||||
{
|
||||
{ nameof(LowPolyAbstractionEffect.Amount), effect => effect.Amount.Values[0].Value = 50d },
|
||||
{ nameof(LowPolyAbstractionEffect.Quality), effect => effect.Quality = LowPolyAbstractionQuality.Balanced },
|
||||
{ nameof(LowPolyAbstractionEffect.Detail), effect => effect.Detail.Values[0].Value = 0d },
|
||||
{ nameof(LowPolyAbstractionEffect.Fidelity), effect => effect.Fidelity.Values[0].Value = 0d },
|
||||
{ nameof(LowPolyAbstractionEffect.Refine), effect => effect.Refine.Values[0].Value = 100d },
|
||||
{ nameof(LowPolyAbstractionEffect.Seed), effect => effect.Seed = 1 },
|
||||
{ nameof(LowPolyAbstractionEffect.Gradient), effect => effect.Gradient.Values[0].Value = 100d },
|
||||
{ nameof(LowPolyAbstractionEffect.Wireframe), effect => effect.Wireframe.Values[0].Value = 100d },
|
||||
{ nameof(LowPolyAbstractionEffect.Saturation), effect => effect.Saturation.Values[0].Value = 100d },
|
||||
{ nameof(LowPolyAbstractionEffect.Jitter), effect => effect.Jitter.Values[0].Value = 100d },
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LaterChanges))]
|
||||
public void EverySettingChangedAfterTheFirstFrameReachesTheEffect(string setting, Action<LowPolyAbstractionEffect> change)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
var effect = new LowPolyAbstractionEffect();
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var before = RenderFrame(context, processor, 0);
|
||||
change(effect);
|
||||
var after = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.False(before.SamePixelsAs(after), setting);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Amount))]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Detail))]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Fidelity))]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Refine))]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Gradient))]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Wireframe))]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Saturation))]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Jitter))]
|
||||
public void AHalfwayValueDrawsDifferentlyFromTheFullValue(string setting)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
Rendering RenderWith(double value)
|
||||
{
|
||||
var effect = new LowPolyAbstractionEffect();
|
||||
((Animation)typeof(LowPolyAbstractionEffect).GetProperty(setting)!.GetValue(effect)!).Values[0].Value = value;
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
return RenderFrame(context, processor, 0);
|
||||
}
|
||||
|
||||
var halfway = RenderWith(50d);
|
||||
var full = RenderWith(100d);
|
||||
|
||||
Assert.False(halfway.SamePixelsAs(full), setting);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LaterChanges))]
|
||||
public void AProcessorThatDrewOtherSettingsDrawsLikeAFreshOne(string setting, Action<LowPolyAbstractionEffect> change)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
var effect = new LowPolyAbstractionEffect();
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
RenderFrame(context, processor, 0);
|
||||
change(effect);
|
||||
using var fresh = effect.CreateVideoEffect(context);
|
||||
fresh.SetInput(source.Bitmap);
|
||||
var expected = RenderFrame(context, fresh, 0);
|
||||
|
||||
var reused = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(reused.SamePixelsAs(expected), setting);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(32, 128)]
|
||||
[InlineData(128, 32)]
|
||||
public void AResizedSourceKeepsProducingTriangles(int firstSize, int secondSize)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var first = new SourceImage(context, firstSize, firstSize, (x, y) => Pattern(x * Size / firstSize, y * Size / firstSize));
|
||||
using var second = new SourceImage(context, secondSize, secondSize, (x, y) => Pattern(x * Size / secondSize, y * Size / secondSize));
|
||||
using var processor = new LowPolyAbstractionEffect().CreateVideoEffect(context);
|
||||
processor.SetInput(first.Bitmap);
|
||||
var before = RenderFrame(context, processor, 0);
|
||||
|
||||
processor.SetInput(second.Bitmap);
|
||||
var after = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(IsRedrawn(before, first));
|
||||
Assert.True(IsRedrawn(after, second));
|
||||
Assert.Equal(secondSize > firstSize, after.Width > before.Width);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrianglesAppearOnceATransparentSourceTakesShape()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var empty = SourceImage.Solid(context, Size, Size, Bgra.Transparent);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
using var processor = new LowPolyAbstractionEffect().CreateVideoEffect(context);
|
||||
processor.SetInput(empty.Bitmap);
|
||||
var before = RenderFrame(context, processor, 0);
|
||||
|
||||
processor.SetInput(source.Bitmap);
|
||||
var after = RenderFrame(context, processor, 0);
|
||||
|
||||
AssertSameAsSource(before, empty);
|
||||
Assert.True(IsRedrawn(after, source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFailureWhileUpdatingIsNotSwallowed()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var processor = new LowPolyAbstractionEffect().CreateVideoEffect(context);
|
||||
|
||||
Assert.ThrowsAny<Exception>(() => processor.Update(null!));
|
||||
}
|
||||
}
|
||||
@@ -1,44 +1,50 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.Interop;
|
||||
using Vortice;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Reflection;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using PixelFormat = Vortice.DCommon.PixelFormat;
|
||||
using YukkuriMovieMaker.Controls;
|
||||
using YukkuriMovieMaker.Exo;
|
||||
using YukkuriMovieMaker.Json;
|
||||
using YukkuriMovieMaker.Plugin.Effects;
|
||||
using YukkuriMovieMaker.Project;
|
||||
|
||||
namespace LowPolyAbstraction.Tests;
|
||||
|
||||
public sealed class LowPolyAbstractionEffectTests
|
||||
{
|
||||
private static double ValueAt(YukkuriMovieMaker.Commons.Animation animation) => animation.GetValue(0, 1, 30);
|
||||
static PropertyInfo Property(string name) => typeof(LowPolyAbstractionEffect).GetProperty(name)!;
|
||||
|
||||
private static LowPolyAbstractionPipeline.Parameters CreateParameters(
|
||||
LowPolyAbstractionQuality quality = LowPolyAbstractionQuality.Balanced,
|
||||
float detail = 0.6f,
|
||||
float fidelity = 0.7f,
|
||||
float refine = 0.5f,
|
||||
float gradient = 0.3f,
|
||||
float wireframe = 0f,
|
||||
float saturation = 0.3f,
|
||||
float jitter = 0.25f,
|
||||
int seed = 0)
|
||||
=> new(quality, detail, fidelity, refine, gradient, wireframe, saturation, jitter, seed);
|
||||
static T Attribute<T>(string property) where T : Attribute => Property(property).GetCustomAttribute<T>()!;
|
||||
|
||||
static Animation[] Animations(LowPolyAbstractionEffect effect)
|
||||
=> [effect.Amount, effect.Detail, effect.Fidelity, effect.Refine, effect.Gradient, effect.Wireframe, effect.Saturation, effect.Jitter];
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Amount), 100d, 0d, 100d)]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Detail), 60d, 0d, 100d)]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Fidelity), 70d, 0d, 100d)]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Refine), 50d, 0d, 100d)]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Gradient), 30d, 0d, 100d)]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Wireframe), 0d, 0d, 100d)]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Saturation), 30d, 0d, 100d)]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Jitter), 25d, 0d, 100d)]
|
||||
public void AnimatedParametersStartFromTheirDefaultsWithinTheirRange(string name, double defaultValue, double minimum, double maximum)
|
||||
{
|
||||
var effect = new LowPolyAbstractionEffect();
|
||||
|
||||
var animation = (Animation)Property(name).GetValue(effect)!;
|
||||
|
||||
Assert.Equal(defaultValue, animation.DefaultValue);
|
||||
Assert.Equal(minimum, animation.MinValue);
|
||||
Assert.Equal(maximum, animation.MaxValue);
|
||||
Assert.Equal(defaultValue, animation.GetValue(0, 1, EffectDescriptions.Fps));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DefaultParameterValuesMatchSpecification()
|
||||
public void QualityAndSeedStartFromTheirDefaults()
|
||||
{
|
||||
var effect = new LowPolyAbstractionEffect();
|
||||
|
||||
Assert.Equal(100d, ValueAt(effect.Amount), 6);
|
||||
Assert.Equal(60d, ValueAt(effect.Detail), 6);
|
||||
Assert.Equal(70d, ValueAt(effect.Fidelity), 6);
|
||||
Assert.Equal(50d, ValueAt(effect.Refine), 6);
|
||||
Assert.Equal(30d, ValueAt(effect.Gradient), 6);
|
||||
Assert.Equal(0d, ValueAt(effect.Wireframe), 6);
|
||||
Assert.Equal(30d, ValueAt(effect.Saturation), 6);
|
||||
Assert.Equal(25d, ValueAt(effect.Jitter), 6);
|
||||
Assert.Equal(LowPolyAbstractionQuality.High, effect.Quality);
|
||||
Assert.Equal(0, effect.Seed);
|
||||
}
|
||||
@@ -48,588 +54,179 @@ public sealed class LowPolyAbstractionEffectTests
|
||||
[InlineData(-1, 0)]
|
||||
[InlineData(0, 0)]
|
||||
[InlineData(1234, 1234)]
|
||||
public void SeedClampsNegativeInputToZero(int input, int expected)
|
||||
[InlineData(10000, 10000)]
|
||||
[InlineData(int.MaxValue, int.MaxValue)]
|
||||
public void SeedNeverDropsBelowZero(int value, int expected)
|
||||
{
|
||||
var effect = new LowPolyAbstractionEffect { Seed = input };
|
||||
var effect = new LowPolyAbstractionEffect { Seed = 5 };
|
||||
|
||||
effect.Seed = value;
|
||||
|
||||
Assert.Equal(expected, effect.Seed);
|
||||
Assert.False(effect.HasErrors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateExoVideoFiltersReturnsEmpty()
|
||||
public void ChangingQualityOrSeedNotifiesTheEditor()
|
||||
{
|
||||
var effect = new LowPolyAbstractionEffect();
|
||||
var changed = new List<string?>();
|
||||
effect.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
|
||||
|
||||
effect.Quality = LowPolyAbstractionQuality.Ultra;
|
||||
effect.Seed = 7;
|
||||
|
||||
Assert.Equal([nameof(LowPolyAbstractionEffect.Quality), nameof(LowPolyAbstractionEffect.Seed)], changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AssigningAnUnchangedOrClampedValueDoesNotNotify()
|
||||
{
|
||||
var effect = new LowPolyAbstractionEffect();
|
||||
var changed = new List<string?>();
|
||||
effect.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
|
||||
|
||||
effect.Quality = LowPolyAbstractionQuality.High;
|
||||
effect.Seed = 0;
|
||||
effect.Seed = -1;
|
||||
|
||||
Assert.Empty(changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLabelIsTheLocalizedEffectName()
|
||||
{
|
||||
var effect = new LowPolyAbstractionEffect();
|
||||
|
||||
Assert.Empty(effect.CreateExoVideoFilters(0, null!));
|
||||
Assert.Equal(Texts.LowPolyAbstraction, effect.Label);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheEightNumericParametersReceiveTheAnimationParameters()
|
||||
{
|
||||
var effect = new LowPolyAbstractionEffect();
|
||||
|
||||
effect.SetAnimationParameters(120, EffectDescriptions.Fps);
|
||||
|
||||
Assert.All(Animations(effect), animation => Assert.Equal(120, animation.Length));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LowPolyAbstractionQuality.Balanced, 1024, 4096, 6, 1)]
|
||||
[InlineData(LowPolyAbstractionQuality.High, 1536, 8192, 8, 2)]
|
||||
[InlineData(LowPolyAbstractionQuality.Ultra, 2048, 16384, 10, 3)]
|
||||
public void QualitySettingsMatchSpecification(LowPolyAbstractionQuality quality, int resolution, int sites, int iterations, int refinePasses)
|
||||
[InlineData(0)]
|
||||
[InlineData(1)]
|
||||
[InlineData(int.MaxValue)]
|
||||
public void NoExoFilterIsWrittenForAviUtl(int keyFrameIndex)
|
||||
{
|
||||
var settings = LowPolyAbstractionSettings.GetQuality(quality);
|
||||
var effect = new LowPolyAbstractionEffect();
|
||||
|
||||
Assert.Equal(resolution, settings.WorkingResolution);
|
||||
Assert.Equal(sites, settings.BaseSites);
|
||||
Assert.Equal(iterations, settings.CvtIterations);
|
||||
Assert.Equal(refinePasses, settings.RefinePasses);
|
||||
var description = new ExoOutputDescription(new VideoInfo(), string.Empty, new AviUtlDirectories(string.Empty, string.Empty));
|
||||
|
||||
Assert.Empty(effect.CreateExoVideoFilters(keyFrameIndex, description));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheEffectIsRegisteredForDecorationAndFilteringWithoutAviUtlSupport()
|
||||
{
|
||||
var attribute = typeof(LowPolyAbstractionEffect).GetCustomAttribute<VideoEffectAttribute>()!;
|
||||
|
||||
Assert.Equal(nameof(Texts.LowPolyAbstraction), attribute.Name);
|
||||
Assert.Equal([VideoEffectCategories.Decoration, VideoEffectCategories.Filtering], attribute.Categories);
|
||||
Assert.Equal([nameof(Texts.TagLowPoly), nameof(Texts.TagTriangle), nameof(Texts.TagPolygon)], attribute.Keywords);
|
||||
Assert.False(attribute.IsAviUtlSupported);
|
||||
Assert.True(attribute.IsEffectItemSupported);
|
||||
Assert.Equal(typeof(Texts), attribute.ResourceType);
|
||||
Assert.Equal(Texts.LowPolyAbstraction, attribute.GetName());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1920, 1080, 1536)]
|
||||
[InlineData(1080, 1920, 1536)]
|
||||
[InlineData(8, 8, 1536)]
|
||||
[InlineData(4096, 16, 1024)]
|
||||
[InlineData(100, 100, 2048)]
|
||||
public void WorkingSizeCoversCanvas(int width, int height, int resolution)
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Amount), nameof(Texts.BasicGroup), nameof(Texts.Amount), nameof(Texts.AmountDescription), 0)]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Quality), nameof(Texts.BasicGroup), nameof(Texts.Quality), nameof(Texts.QualityDescription), 1)]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Detail), nameof(Texts.StructureGroup), nameof(Texts.Detail), nameof(Texts.DetailDescription), 10)]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Fidelity), nameof(Texts.StructureGroup), nameof(Texts.Fidelity), nameof(Texts.FidelityDescription), 11)]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Refine), nameof(Texts.StructureGroup), nameof(Texts.Refine), nameof(Texts.RefineDescription), 12)]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Seed), nameof(Texts.StructureGroup), nameof(Texts.Seed), nameof(Texts.SeedDescription), 13)]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Gradient), nameof(Texts.AppearanceGroup), nameof(Texts.Gradient), nameof(Texts.GradientDescription), 20)]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Wireframe), nameof(Texts.AppearanceGroup), nameof(Texts.Wireframe), nameof(Texts.WireframeDescription), 21)]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Saturation), nameof(Texts.AppearanceGroup), nameof(Texts.Saturation), nameof(Texts.SaturationDescription), 22)]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Jitter), nameof(Texts.AppearanceGroup), nameof(Texts.Jitter), nameof(Texts.JitterDescription), 23)]
|
||||
public void EveryParameterIsDisplayedInItsGroupInOrder(string property, string group, string name, string description, int order)
|
||||
{
|
||||
var (workingWidth, workingHeight, scale) = LowPolyAbstractionSettings.GetWorkingSize(width, height, resolution);
|
||||
var display = Attribute<DisplayAttribute>(property);
|
||||
|
||||
Assert.True(workingWidth >= LowPolyAbstractionSettings.MinimumWorkingSize);
|
||||
Assert.True(workingHeight >= LowPolyAbstractionSettings.MinimumWorkingSize);
|
||||
Assert.True(scale > 0f);
|
||||
Assert.True(workingWidth * scale >= width);
|
||||
Assert.True(workingHeight * scale >= height);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParameterMappingsAreMonotonicAndBounded()
|
||||
{
|
||||
Assert.True(LowPolyAbstractionSettings.GetSiteCount(0f, 4096) < LowPolyAbstractionSettings.GetSiteCount(1f, 4096));
|
||||
Assert.Equal(LowPolyAbstractionSettings.GetSiteCount(0f, 4096), LowPolyAbstractionSettings.GetSiteCount(-5f, 4096));
|
||||
Assert.Equal(LowPolyAbstractionSettings.GetSiteCount(1f, 4096), LowPolyAbstractionSettings.GetSiteCount(5f, 4096));
|
||||
Assert.True(LowPolyAbstractionSettings.GetSiteCount(1f, 4096) <= LowPolyAbstractionSettings.GetSiteCapacity(4096));
|
||||
|
||||
Assert.True(LowPolyAbstractionSettings.GetEdgeSampleSpacing(1024, 1024, 1f) < LowPolyAbstractionSettings.GetEdgeSampleSpacing(1024, 1024, 0f));
|
||||
Assert.True(LowPolyAbstractionSettings.GetEdgeSampleSpacing(1024, 1024, 1f) >= 2f);
|
||||
|
||||
Assert.True(LowPolyAbstractionSettings.GetErrorThreshold(1f) < LowPolyAbstractionSettings.GetErrorThreshold(0f));
|
||||
Assert.Equal(LowPolyAbstractionSettings.MaximumErrorThreshold, LowPolyAbstractionSettings.GetErrorThreshold(-1f), 7);
|
||||
Assert.Equal(LowPolyAbstractionSettings.MinimumErrorThreshold, LowPolyAbstractionSettings.GetErrorThreshold(2f), 7);
|
||||
Assert.Equal(group, display.GroupName);
|
||||
Assert.Equal(name, display.Name);
|
||||
Assert.Equal(description, display.Description);
|
||||
Assert.Equal(order, display.Order);
|
||||
Assert.Equal(typeof(Texts), display.ResourceType);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1, 1, 1)]
|
||||
[InlineData(2, 2, 1)]
|
||||
[InlineData(3, 3, 2)]
|
||||
[InlineData(256, 128, 128)]
|
||||
[InlineData(257, 16, 256)]
|
||||
public void JumpFloodInitialStepCoversLongSide(int width, int height, int expected)
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Amount))]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Detail))]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Fidelity))]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Refine))]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Gradient))]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Wireframe))]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Saturation))]
|
||||
[InlineData(nameof(LowPolyAbstractionEffect.Jitter))]
|
||||
public void AnimatedParametersAreEditedAsPercentagesWithAnimationSliders(string property)
|
||||
{
|
||||
Assert.Equal(expected, LowPolyAbstractionSettings.GetJumpFloodInitialStep(width, height));
|
||||
var slider = Attribute<AnimationSliderAttribute>(property);
|
||||
|
||||
Assert.Equal("F1", slider.StringFormat);
|
||||
Assert.Equal("%", slider.UnitText);
|
||||
Assert.Equal(0d, slider.DefaultMin);
|
||||
Assert.Equal(100d, slider.DefaultMax);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TransparentInputYieldsTransparentOutput()
|
||||
public void TheQualityIsChosenFromACombo()
|
||||
{
|
||||
using var pipeline = LowPolyAbstractionPipeline.TryCreate();
|
||||
if (pipeline is null)
|
||||
{
|
||||
Assert.Skip("Direct3D 12 is unavailable.");
|
||||
return;
|
||||
}
|
||||
Assert.NotNull(Attribute<EnumComboBoxAttribute>(nameof(LowPolyAbstractionEffect.Quality)));
|
||||
Assert.Equal([LowPolyAbstractionQuality.Balanced, LowPolyAbstractionQuality.High, LowPolyAbstractionQuality.Ultra], Enum.GetValues<LowPolyAbstractionQuality>());
|
||||
}
|
||||
|
||||
const int width = 64;
|
||||
const int height = 64;
|
||||
var source = new int[width * height];
|
||||
var destination = new int[source.Length];
|
||||
Array.Fill(destination, -1);
|
||||
var parameters = CreateParameters();
|
||||
[Theory]
|
||||
[InlineData(LowPolyAbstractionQuality.Balanced, nameof(Texts.QualityBalanced), nameof(Texts.QualityBalancedDescription))]
|
||||
[InlineData(LowPolyAbstractionQuality.High, nameof(Texts.QualityHigh), nameof(Texts.QualityHighDescription))]
|
||||
[InlineData(LowPolyAbstractionQuality.Ultra, nameof(Texts.QualityUltra), nameof(Texts.QualityUltraDescription))]
|
||||
public void EveryQualityIsDisplayedWithItsLocalizedName(LowPolyAbstractionQuality quality, string name, string description)
|
||||
{
|
||||
var display = typeof(LowPolyAbstractionQuality).GetField(quality.ToString())!.GetCustomAttribute<DisplayAttribute>()!;
|
||||
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
|
||||
Assert.All(destination, pixel => Assert.Equal(0, pixel));
|
||||
Assert.Equal(name, display.Name);
|
||||
Assert.Equal(description, display.Description);
|
||||
Assert.Equal(typeof(Texts), display.ResourceType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OpaqueInputProducesTriangles()
|
||||
public void TheSeedIsEditedWithoutAUnitFromZero()
|
||||
{
|
||||
using var pipeline = LowPolyAbstractionPipeline.TryCreate();
|
||||
if (pipeline is null)
|
||||
{
|
||||
Assert.Skip("Direct3D 12 is unavailable.");
|
||||
return;
|
||||
}
|
||||
var slider = Attribute<TextBoxSliderAttribute>(nameof(LowPolyAbstractionEffect.Seed));
|
||||
var range = Attribute<RangeAttribute>(nameof(LowPolyAbstractionEffect.Seed));
|
||||
|
||||
const int width = 128;
|
||||
const int height = 128;
|
||||
var source = CreateTwoToneSource(width, height, 24, 24, 80, 80);
|
||||
var destination = new int[source.Length];
|
||||
var parameters = CreateParameters();
|
||||
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
|
||||
Assert.True(CountLitPixels(destination) > 0);
|
||||
Assert.Equal("F0", slider.StringFormat);
|
||||
Assert.Equal(string.Empty, slider.UnitText);
|
||||
Assert.Equal(0d, slider.DefaultMin);
|
||||
Assert.Equal(10000d, slider.DefaultMax);
|
||||
Assert.Equal(0, range.Minimum);
|
||||
Assert.Equal(int.MaxValue, range.Maximum);
|
||||
Assert.Equal(0, Attribute<DefaultValueAttribute>(nameof(LowPolyAbstractionEffect.Seed)).Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GpuPipelineIsDeterministic()
|
||||
public void EverySettingSurvivesAProjectRoundTrip()
|
||||
{
|
||||
using var pipeline = LowPolyAbstractionPipeline.TryCreate();
|
||||
if (pipeline is null)
|
||||
{
|
||||
Assert.Skip("Direct3D 12 is unavailable.");
|
||||
return;
|
||||
}
|
||||
var effect = new LowPolyAbstractionEffect { Quality = LowPolyAbstractionQuality.Ultra, Seed = 42 };
|
||||
var values = new[] { 55d, 45d, 40d, 20d, 65d, 15d, 85d, 35d };
|
||||
foreach (var (animation, value) in Animations(effect).Zip(values))
|
||||
animation.Values[0].Value = value;
|
||||
|
||||
const int width = 128;
|
||||
const int height = 128;
|
||||
var source = CreateTwoToneSource(width, height, 24, 24, 80, 80);
|
||||
var first = new int[source.Length];
|
||||
var second = new int[source.Length];
|
||||
var parameters = CreateParameters(jitter: 0.5f, seed: 42);
|
||||
var clone = Json.GetClone(effect)!;
|
||||
|
||||
pipeline.Process(source, first, width, height, in parameters);
|
||||
pipeline.Process(source, second, width, height, in parameters);
|
||||
|
||||
Assert.Equal(first, second);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DifferentSeedsProduceDifferentTriangulations()
|
||||
{
|
||||
using var pipeline = LowPolyAbstractionPipeline.TryCreate();
|
||||
if (pipeline is null)
|
||||
{
|
||||
Assert.Skip("Direct3D 12 is unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
const int width = 128;
|
||||
const int height = 128;
|
||||
var source = CreateTwoToneSource(width, height, 24, 24, 80, 80);
|
||||
var first = new int[source.Length];
|
||||
var second = new int[source.Length];
|
||||
|
||||
var parametersA = CreateParameters(seed: 1);
|
||||
var parametersB = CreateParameters(seed: 2);
|
||||
pipeline.Process(source, first, width, height, in parametersA);
|
||||
pipeline.Process(source, second, width, height, in parametersB);
|
||||
|
||||
Assert.NotEqual(first, second);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OutputAlphaStaysPremultipliedAndBounded()
|
||||
{
|
||||
using var pipeline = LowPolyAbstractionPipeline.TryCreate();
|
||||
if (pipeline is null)
|
||||
{
|
||||
Assert.Skip("Direct3D 12 is unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
const int width = 128;
|
||||
const int height = 128;
|
||||
var source = CreateTwoToneSource(width, height, 24, 24, 80, 80);
|
||||
var destination = new int[source.Length];
|
||||
var parameters = CreateParameters(gradient: 1f, wireframe: 1f, saturation: 1f, jitter: 1f);
|
||||
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
|
||||
foreach (var pixel in destination)
|
||||
{
|
||||
var alpha = (pixel >> 24) & 255;
|
||||
Assert.InRange((pixel >> 16) & 255, 0, alpha);
|
||||
Assert.InRange((pixel >> 8) & 255, 0, alpha);
|
||||
Assert.InRange(pixel & 255, 0, alpha);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DetailChangesTriangulation()
|
||||
{
|
||||
using var pipeline = LowPolyAbstractionPipeline.TryCreate();
|
||||
if (pipeline is null)
|
||||
{
|
||||
Assert.Skip("Direct3D 12 is unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
const int width = 128;
|
||||
const int height = 128;
|
||||
var source = CreateTwoToneSource(width, height, 24, 24, 80, 80);
|
||||
var coarse = new int[source.Length];
|
||||
var fine = new int[source.Length];
|
||||
|
||||
var coarseParameters = CreateParameters(detail: 0.1f);
|
||||
var fineParameters = CreateParameters(detail: 1f);
|
||||
pipeline.Process(source, coarse, width, height, in coarseParameters);
|
||||
pipeline.Process(source, fine, width, height, in fineParameters);
|
||||
|
||||
Assert.True(CountLitPixels(coarse) > 0);
|
||||
Assert.True(CountLitPixels(fine) > 0);
|
||||
Assert.NotEqual(coarse, fine);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RefinementChangesOutputOnHighVarianceSource()
|
||||
{
|
||||
using var pipeline = LowPolyAbstractionPipeline.TryCreate();
|
||||
if (pipeline is null)
|
||||
{
|
||||
Assert.Skip("Direct3D 12 is unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
const int width = 128;
|
||||
const int height = 128;
|
||||
var source = new int[width * height];
|
||||
for (var y = 16; y < 112; y++)
|
||||
{
|
||||
for (var x = 16; x < 112; x++)
|
||||
{
|
||||
var value = (uint)(x * 73856093 ^ y * 19349663);
|
||||
value ^= value >> 13;
|
||||
value *= 0x85EBCA6Bu;
|
||||
var gray = (int)(value >> 24);
|
||||
source[y * width + x] = unchecked((int)0xFF000000) | gray << 16 | gray << 8 | gray;
|
||||
}
|
||||
}
|
||||
var without = new int[source.Length];
|
||||
var with = new int[source.Length];
|
||||
|
||||
var withoutParameters = CreateParameters(refine: 0f);
|
||||
var withParameters = CreateParameters(refine: 1f);
|
||||
pipeline.Process(source, without, width, height, in withoutParameters);
|
||||
pipeline.Process(source, with, width, height, in withParameters);
|
||||
|
||||
Assert.True(CountLitPixels(without) > 0);
|
||||
Assert.NotEqual(without, with);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OutputStaysWithinSilhouetteBoundsWithPadding()
|
||||
{
|
||||
using var pipeline = LowPolyAbstractionPipeline.TryCreate();
|
||||
if (pipeline is null)
|
||||
{
|
||||
Assert.Skip("Direct3D 12 is unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
const int width = 192;
|
||||
const int height = 192;
|
||||
var source = CreateTwoToneSource(width, height, 64, 64, 48, 48);
|
||||
var destination = new int[source.Length];
|
||||
var parameters = CreateParameters();
|
||||
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
|
||||
var padding = LowPolyAbstractionSettings.MarginPadding;
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
if (((destination[y * width + x] >> 24) & 255) == 0)
|
||||
continue;
|
||||
Assert.InRange(x, 64 - padding, 64 + 48 + padding);
|
||||
Assert.InRange(y, 64 - padding, 64 + 48 + padding);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GpuPipelineDoesNotAllocateManagedMemoryAfterWarmup()
|
||||
{
|
||||
using var pipeline = LowPolyAbstractionPipeline.TryCreate();
|
||||
if (pipeline is null)
|
||||
{
|
||||
Assert.Skip("Direct3D 12 is unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
const int width = 64;
|
||||
const int height = 64;
|
||||
var source = CreateTwoToneSource(width, height, 16, 16, 32, 32);
|
||||
var destination = new int[source.Length];
|
||||
var parameters = CreateParameters();
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
GC.Collect();
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
|
||||
|
||||
Assert.Equal(0, allocated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SharedTexturePipelineMatchesPackedBufferPipeline()
|
||||
{
|
||||
using var pipeline = LowPolyAbstractionPipeline.TryCreate();
|
||||
if (pipeline is null)
|
||||
{
|
||||
Assert.Skip("Direct3D 12 is unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
const int width = 96;
|
||||
const int height = 96;
|
||||
var source = CreateTwoToneSource(width, height, 24, 24, 48, 48);
|
||||
var expected = new int[source.Length];
|
||||
var parameters = CreateParameters(seed: 11);
|
||||
pipeline.Process(source, expected, width, height, in parameters);
|
||||
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, width, height);
|
||||
using var outputTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 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);
|
||||
pipeline.ProcessSharedAndWait(sourceTexture, outputTexture, width, height, in parameters);
|
||||
var result = new Bgra32[source.Length];
|
||||
outputTexture.CopyTo(result);
|
||||
|
||||
for (var index = 0; index < expected.Length; index++)
|
||||
Assert.Equal(unchecked((uint)expected[index]), result[index].PackedValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SubmittedSharedTexturePipelineAllocationsAmortizeToZero()
|
||||
{
|
||||
using var pipeline = LowPolyAbstractionPipeline.TryCreate();
|
||||
if (pipeline is null)
|
||||
{
|
||||
Assert.Skip("Direct3D 12 is unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
const int width = 64;
|
||||
const int height = 64;
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var source = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, width, height);
|
||||
using var destination = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, width, height);
|
||||
var parameters = CreateParameters();
|
||||
for (var iteration = 0; iteration < 4; iteration++)
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
pipeline.WaitForCompletion();
|
||||
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
GC.Collect();
|
||||
var minimum = long.MaxValue;
|
||||
for (var iteration = 0; iteration < 16; iteration++)
|
||||
{
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
}
|
||||
pipeline.WaitForCompletion();
|
||||
|
||||
Assert.Equal(0, minimum);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VisibleBoundsCoverAllLitPixelsAndMatchFullRender()
|
||||
{
|
||||
using var pipeline = LowPolyAbstractionPipeline.TryCreate();
|
||||
if (pipeline is null)
|
||||
{
|
||||
Assert.Skip("Direct3D 12 is unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
const int width = 192;
|
||||
const int height = 192;
|
||||
var source = CreateTwoToneSource(width, height, 64, 64, 48, 40);
|
||||
var full = new int[source.Length];
|
||||
var parameters = CreateParameters(seed: 5);
|
||||
pipeline.Process(source, full, width, height, in parameters);
|
||||
|
||||
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);
|
||||
|
||||
pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in parameters);
|
||||
Assert.True(pipeline.TryGetVisibleBounds(width, height, in parameters, out var rect));
|
||||
Assert.True(rect.Width > 0 && rect.Height > 0);
|
||||
Assert.True(rect.X >= 0 && rect.Y >= 0);
|
||||
Assert.True(rect.X + rect.Width <= width && rect.Y + rect.Height <= height);
|
||||
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
if (full[y * width + x] == 0)
|
||||
continue;
|
||||
Assert.InRange(x, rect.X, rect.X + rect.Width - 1);
|
||||
Assert.InRange(y, rect.Y, rect.Y + rect.Height - 1);
|
||||
}
|
||||
}
|
||||
|
||||
using var outputTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
|
||||
pipeline.RenderVisible(sourceTexture, outputTexture, width, height, 0, 0, width, height, rect, in parameters);
|
||||
var result = new Bgra32[rect.Width * rect.Height];
|
||||
outputTexture.CopyTo(result);
|
||||
|
||||
for (var y = 0; y < rect.Height; y++)
|
||||
{
|
||||
for (var x = 0; x < rect.Width; x++)
|
||||
{
|
||||
var expected = unchecked((uint)full[(rect.Y + y) * width + rect.X + x]);
|
||||
Assert.Equal(expected, result[y * rect.Width + x].PackedValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SimulateCachesStructureUntilInputsChange()
|
||||
{
|
||||
using var pipeline = LowPolyAbstractionPipeline.TryCreate();
|
||||
if (pipeline is null)
|
||||
{
|
||||
Assert.Skip("Direct3D 12 is unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
const int width = 128;
|
||||
const int height = 128;
|
||||
var source = CreateTwoToneSource(width, height, 24, 24, 80, 80);
|
||||
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 parameters = CreateParameters(seed: 3);
|
||||
Assert.True(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in parameters));
|
||||
Assert.False(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in parameters));
|
||||
|
||||
var renderOnlyChanged = parameters with { Gradient = 1f, Wireframe = 1f };
|
||||
Assert.False(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in renderOnlyChanged));
|
||||
|
||||
var seedChanged = parameters with { Seed = 4 };
|
||||
Assert.True(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in seedChanged));
|
||||
|
||||
var movedSource = CreateTwoToneSource(width, height, 8, 8, 80, 80);
|
||||
for (var index = 0; index < movedSource.Length; index++)
|
||||
sourcePixels[index].PackedValue = unchecked((uint)movedSource[index]);
|
||||
sourceTexture.CopyFrom(sourcePixels);
|
||||
Assert.True(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in seedChanged));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Direct2DInteropProducesTrianglesFromOpaqueCore()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var graphicsContext = devices.CreateContext();
|
||||
using var interop = LowPolyAbstractionGpuInterop.TryCreate(graphicsContext);
|
||||
if (interop is null)
|
||||
{
|
||||
Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
using var pipeline = LowPolyAbstractionPipeline.TryCreate(interop.Device);
|
||||
Assert.NotNull(pipeline);
|
||||
|
||||
const int width = 96;
|
||||
const int height = 96;
|
||||
var pixels = CreateTwoToneSource(width, height, 24, 24, 48, 48);
|
||||
var handle = GCHandle.Alloc(pixels, GCHandleType.Pinned);
|
||||
using var inputBitmap = graphicsContext.DeviceContext.CreateBitmap(
|
||||
new SizeI(width, height),
|
||||
new BitmapProperties1(
|
||||
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
|
||||
96f,
|
||||
96f,
|
||||
BitmapOptions.None));
|
||||
try
|
||||
{
|
||||
inputBitmap.CopyFromMemory(handle.AddrOfPinnedObject(), width * sizeof(int));
|
||||
}
|
||||
finally
|
||||
{
|
||||
handle.Free();
|
||||
}
|
||||
|
||||
Assert.True(interop.EnsureResources(width, height));
|
||||
var bounds = new RawRectF(0f, 0f, width, height);
|
||||
var parameters = CreateParameters();
|
||||
for (var iteration = 0; iteration < 2; iteration++)
|
||||
{
|
||||
interop.RenderInput(inputBitmap, bounds);
|
||||
interop.BeginCompute();
|
||||
try
|
||||
{
|
||||
pipeline!.Process(interop.SourceTexture, interop.OutputTexture, width, height, in parameters);
|
||||
}
|
||||
finally
|
||||
{
|
||||
interop.EndCompute();
|
||||
}
|
||||
}
|
||||
interop.WaitForIdle();
|
||||
|
||||
using var staging = graphicsContext.DeviceContext.CreateBitmap(
|
||||
new SizeI(width, height),
|
||||
new BitmapProperties1(
|
||||
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
|
||||
96f,
|
||||
96f,
|
||||
BitmapOptions.CpuRead | BitmapOptions.CannotDraw));
|
||||
staging.CopyFromBitmap(interop.OutputBitmap);
|
||||
var mapped = staging.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
var lit = 0;
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var actual = Marshal.ReadInt32(mapped.Bits + (nint)(y * mapped.Pitch + x * sizeof(int)));
|
||||
var alpha = (actual >> 24) & 255;
|
||||
Assert.InRange((actual >> 16) & 255, 0, alpha);
|
||||
Assert.InRange((actual >> 8) & 255, 0, alpha);
|
||||
Assert.InRange(actual & 255, 0, alpha);
|
||||
if (alpha > 0)
|
||||
lit++;
|
||||
}
|
||||
}
|
||||
Assert.True(lit > 0);
|
||||
}
|
||||
finally
|
||||
{
|
||||
staging.Unmap();
|
||||
}
|
||||
}
|
||||
|
||||
private static int[] CreateTwoToneSource(int width, int height, int left, int top, int squareWidth, int squareHeight)
|
||||
{
|
||||
var source = new int[width * height];
|
||||
for (var y = top; y < top + squareHeight; y++)
|
||||
{
|
||||
for (var x = left; x < left + squareWidth; x++)
|
||||
{
|
||||
if (x < 0 || x >= width || y < 0 || y >= height)
|
||||
continue;
|
||||
source[y * width + x] = x - left < squareWidth / 2
|
||||
? unchecked((int)0xFFC04040)
|
||||
: unchecked((int)0xFF4040C0);
|
||||
}
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
private static int CountLitPixels(int[] pixels)
|
||||
{
|
||||
var count = 0;
|
||||
foreach (var pixel in pixels)
|
||||
{
|
||||
if (((pixel >> 24) & 255) > 8)
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
Assert.NotSame(effect, clone);
|
||||
Assert.Equal(LowPolyAbstractionQuality.Ultra, clone.Quality);
|
||||
Assert.Equal(42, clone.Seed);
|
||||
Assert.Equal(values, Animations(clone).Select(animation => animation.GetValue(0, 1, EffectDescriptions.Fps)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
using System.Numerics;
|
||||
using ComputeWeave;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LowPolyAbstraction.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class LowPolyAbstractionInteropTests
|
||||
{
|
||||
static readonly Bgra Red = Bgra.Opaque(64, 64, 192);
|
||||
static readonly Bgra Blue = Bgra.Opaque(192, 64, 64);
|
||||
|
||||
static LowPolyAbstractionPipeline.Parameters Parameters()
|
||||
=> new(LowPolyAbstractionQuality.Balanced, 0.6f, 0.7f, 0.5f, 0.3f, 0f, 0.3f, 0.25f, 0);
|
||||
|
||||
static Func<int, int, Bgra> CenteredTwoTone(int size, int square)
|
||||
{
|
||||
var start = (size - square) / 2;
|
||||
return (x, y) => x >= start && x < start + square && y >= start && y < start + square
|
||||
? x - start < square / 2 ? Red : Blue
|
||||
: Bgra.Transparent;
|
||||
}
|
||||
|
||||
sealed class Interop : IDisposable
|
||||
{
|
||||
readonly ComputeExternalQueueScheduler scheduler;
|
||||
readonly LowPolyAbstractionInteropProvider provider;
|
||||
readonly ComputeInteropDomain domain;
|
||||
|
||||
public LowPolyAbstractionResourceSet Resources { get; }
|
||||
|
||||
public LowPolyAbstractionPipeline Pipeline { get; }
|
||||
|
||||
Interop(ComputeExternalQueueScheduler scheduler, LowPolyAbstractionInteropProvider provider, GraphicsDevice device)
|
||||
{
|
||||
this.scheduler = scheduler;
|
||||
this.provider = provider;
|
||||
domain = device.RegisterExternalDomain(provider);
|
||||
Resources = LowPolyAbstractionResourceSet.Create(device, domain);
|
||||
Pipeline = LowPolyAbstractionPipeline.TryCreate(device)!;
|
||||
}
|
||||
|
||||
public static Interop Create(IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
var scheduler = ComputeExternalQueueScheduler.Create();
|
||||
var provider = LowPolyAbstractionInteropProvider.TryCreate(devices, scheduler, out var device);
|
||||
if (provider is null || device is null)
|
||||
{
|
||||
scheduler.Dispose();
|
||||
Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable.");
|
||||
}
|
||||
|
||||
return new Interop(scheduler, provider, device);
|
||||
}
|
||||
|
||||
public void Draw(ID2D1Image image)
|
||||
{
|
||||
var context = provider.RenderContext;
|
||||
using var borrow = Resources.BeginSourceExternalOperation();
|
||||
var previousTarget = context.Target;
|
||||
using var target = new ID2D1Bitmap1(borrow.DangerousGetView().AddRefBitmap());
|
||||
context.Target = target;
|
||||
context.BeginDraw();
|
||||
context.Clear(null);
|
||||
context.DrawImage(image, Vector2.Zero, null, InterpolationMode.NearestNeighbor, CompositeMode.SourceCopy);
|
||||
context.EndDraw();
|
||||
context.Target = previousTarget;
|
||||
}
|
||||
|
||||
public Rendering CaptureOutput(IGraphicsDevicesAndContext devices, out int width, out int height)
|
||||
{
|
||||
using var lease = Resources.AcquireOutputExternalViewLease();
|
||||
width = lease.Width;
|
||||
height = lease.Height;
|
||||
using var bitmap = new ID2D1Bitmap1(lease.DangerousGetView().AddRefBitmap());
|
||||
return Rendering.Capture(devices, bitmap);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Pipeline.Dispose();
|
||||
Resources.Dispose();
|
||||
Resources.WaitForDisposal();
|
||||
domain.Dispose();
|
||||
domain.WaitForDisposal();
|
||||
provider.Dispose();
|
||||
scheduler.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
static int LitPixels(Rendering rendering, LowPolyAbstractionPipeline.PixelRect visible)
|
||||
{
|
||||
var lit = 0;
|
||||
for (var y = 0; y < visible.Height; y++)
|
||||
{
|
||||
for (var x = 0; x < visible.Width; x++)
|
||||
{
|
||||
var pixel = rendering[x, y];
|
||||
Assert.InRange(pixel.Blue, 0, pixel.Alpha);
|
||||
Assert.InRange(pixel.Green, 0, pixel.Alpha);
|
||||
Assert.InRange(pixel.Red, 0, pixel.Alpha);
|
||||
if (pixel.Alpha > 0)
|
||||
lit++;
|
||||
}
|
||||
}
|
||||
|
||||
return lit;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrianglesAreDrawnAfterTheOutputGrowsToFullHd()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var interop = Interop.Create(context);
|
||||
using var source = new SourceImage(context, 96, 96, CenteredTwoTone(96, 48));
|
||||
var parameters = Parameters();
|
||||
Assert.True(interop.Resources.TryEnsureSource(96, 96, out _));
|
||||
LowPolyAbstractionPipeline.PixelRect RenderInto(Func<LowPolyAbstractionPipeline.PixelRect, (int Width, int Height)> outputSize)
|
||||
{
|
||||
interop.Draw(source.Bitmap);
|
||||
interop.Pipeline.Simulate(interop.Resources.GetSourceComputeBinding(), 96, 96, 0, 0, 96, 96, in parameters);
|
||||
Assert.True(interop.Pipeline.TryGetVisibleBounds(96, 96, in parameters, out var visible));
|
||||
var (width, height) = outputSize(visible);
|
||||
Assert.True(interop.Resources.TryEnsureOutput(width, height, out _));
|
||||
interop.Pipeline.RenderVisible(interop.Resources.GetOutputComputeBinding(), 96, 96, visible, in parameters);
|
||||
return visible;
|
||||
}
|
||||
|
||||
var first = RenderInto(visible => (visible.Width, visible.Height));
|
||||
interop.CaptureOutput(context, out var firstWidth, out var firstHeight);
|
||||
var second = RenderInto(_ => (1920, 1080));
|
||||
var output = interop.CaptureOutput(context, out var secondWidth, out var secondHeight);
|
||||
|
||||
Assert.Equal((first.Width, first.Height), (firstWidth, firstHeight));
|
||||
Assert.Equal((1920, 1080), (secondWidth, secondHeight));
|
||||
Assert.True(LitPixels(output, second) > 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrianglesAreDrawnAfterTheSourceIsReplacedByALargerOne()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var interop = Interop.Create(context);
|
||||
var parameters = Parameters();
|
||||
var previous = default(LowPolyAbstractionPipeline.PixelRect);
|
||||
var previousArea = 0;
|
||||
|
||||
foreach (var (size, square) in new[] { (96, 32), (128, 64) })
|
||||
{
|
||||
using var source = new SourceImage(context, size, size, CenteredTwoTone(size, square));
|
||||
Assert.True(interop.Resources.TryEnsureSource(size, size, out var sourceChanged));
|
||||
interop.Draw(source.Bitmap);
|
||||
Assert.True(interop.Pipeline.Simulate(interop.Resources.GetSourceComputeBinding(), size, size, 0, 0, size, size, in parameters));
|
||||
Assert.True(interop.Pipeline.TryGetVisibleBounds(size, size, in parameters, out var visible));
|
||||
Assert.True(interop.Resources.TryEnsureOutput(visible.Width, visible.Height, out _));
|
||||
interop.Pipeline.RenderVisible(interop.Resources.GetOutputComputeBinding(), size, size, visible, in parameters);
|
||||
var output = interop.CaptureOutput(context, out var width, out var height);
|
||||
|
||||
Assert.True(sourceChanged);
|
||||
Assert.True(visible.Width > previous.Width && visible.Height > previous.Height);
|
||||
Assert.Equal((visible.Width, visible.Height), (width, height));
|
||||
Assert.True(LitPixels(output, visible) > previousArea);
|
||||
previous = visible;
|
||||
previousArea = square * square;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,717 @@
|
||||
using ComputeWeave;
|
||||
using ComputeWeave.Interop;
|
||||
|
||||
namespace LowPolyAbstraction.Tests;
|
||||
|
||||
[Collection("Direct3D12")]
|
||||
public sealed class LowPolyAbstractionPipelineTests
|
||||
{
|
||||
const int Red = unchecked((int)0xFFC04040);
|
||||
const int Blue = unchecked((int)0xFF4040C0);
|
||||
|
||||
static LowPolyAbstractionPipeline CreatePipeline()
|
||||
{
|
||||
var pipeline = LowPolyAbstractionPipeline.TryCreate();
|
||||
if (pipeline is null)
|
||||
Assert.Skip("Direct3D 12 is unavailable.");
|
||||
return pipeline;
|
||||
}
|
||||
|
||||
static LowPolyAbstractionPipeline.Parameters Parameters(
|
||||
LowPolyAbstractionQuality quality = LowPolyAbstractionQuality.Balanced,
|
||||
float detail = 0.6f,
|
||||
float fidelity = 0.7f,
|
||||
float refine = 0.5f,
|
||||
float gradient = 0.3f,
|
||||
float wireframe = 0f,
|
||||
float saturation = 0.3f,
|
||||
float jitter = 0.25f,
|
||||
int seed = 0)
|
||||
=> new(quality, detail, fidelity, refine, gradient, wireframe, saturation, jitter, seed);
|
||||
|
||||
static int[] TwoTone(int width, int height, int left, int top, int squareWidth, int squareHeight)
|
||||
{
|
||||
var pixels = new int[width * height];
|
||||
for (var y = Math.Max(top, 0); y < Math.Min(top + squareHeight, height); y++)
|
||||
{
|
||||
for (var x = Math.Max(left, 0); x < Math.Min(left + squareWidth, width); x++)
|
||||
pixels[y * width + x] = x - left < squareWidth / 2 ? Red : Blue;
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
static int[] Noise(int width, int height, int left, int top, int squareWidth, int squareHeight)
|
||||
{
|
||||
var pixels = new int[width * height];
|
||||
for (var y = top; y < top + squareHeight; y++)
|
||||
{
|
||||
for (var x = left; x < left + squareWidth; x++)
|
||||
{
|
||||
var value = (uint)(x * 73856093 ^ y * 19349663);
|
||||
value ^= value >> 13;
|
||||
value *= 0x85EBCA6Bu;
|
||||
var gray = (int)(value >> 24);
|
||||
pixels[y * width + x] = unchecked((int)0xFF000000) | gray << 16 | gray << 8 | gray;
|
||||
}
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
static int[] Silhouette(int size, Func<int, int, bool> inside)
|
||||
{
|
||||
var pixels = new int[size * size];
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
var u = x * 256 / size;
|
||||
var v = y * 256 / size;
|
||||
if (inside(x, y))
|
||||
pixels[y * size + x] = unchecked((int)0xFF000000) | (40 + u * 3 / 4) << 16 | (200 - v / 2) << 8 | (80 + (u + v) / 4);
|
||||
}
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
public enum Hollow
|
||||
{
|
||||
Notch,
|
||||
Gap,
|
||||
Hole,
|
||||
}
|
||||
|
||||
static Func<int, int, bool> HollowShape(Hollow hollow)
|
||||
=> hollow switch
|
||||
{
|
||||
Hollow.Notch => (x, y) => x is >= 40 and < 216 && y is >= 40 and < 216 && !(x is >= 116 and < 140 && y < 180),
|
||||
Hollow.Gap => (x, y) => y is >= 60 and < 196 && (x is >= 40 and < 110 || x is >= 146 and < 216),
|
||||
_ => (x, y) => (x - 128) * (x - 128) + (y - 128) * (y - 128) is < 100 * 100 and >= 45 * 45,
|
||||
};
|
||||
|
||||
public enum FineGaps
|
||||
{
|
||||
Lattice,
|
||||
Speckles,
|
||||
}
|
||||
|
||||
static Func<int, int, bool> FineGapShape(FineGaps gaps)
|
||||
=> gaps switch
|
||||
{
|
||||
FineGaps.Lattice => (x, y) => x is >= 40 and < 216 && y is >= 40 and < 216 && x % 8 != 0 && y % 8 != 0,
|
||||
_ => (x, y) =>
|
||||
{
|
||||
var value = (uint)(x * 73856093 ^ y * 19349663);
|
||||
value ^= value >> 13;
|
||||
value *= 0x85EBCA6Bu;
|
||||
value ^= value >> 16;
|
||||
return x is >= 40 and < 216 && y is >= 40 and < 216 && value % 50 != 0;
|
||||
},
|
||||
};
|
||||
|
||||
static bool AnyWithin(int x, int y, int reach, Func<int, int, bool> predicate)
|
||||
{
|
||||
for (var dy = -reach; dy <= reach; dy++)
|
||||
{
|
||||
for (var dx = -reach; dx <= reach; dx++)
|
||||
{
|
||||
if (predicate(x + dx, y + dy))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static int Alpha(int pixel) => (pixel >> 24) & 255;
|
||||
|
||||
static int LitPixels(int[] pixels) => pixels.Count(pixel => Alpha(pixel) > 8);
|
||||
|
||||
static void Upload(ReadWriteTexture2D<Bgra32, Float4> texture, int[] pixels)
|
||||
=> texture.CopyFrom(pixels.Select(pixel => new Bgra32 { PackedValue = unchecked((uint)pixel) }).ToArray());
|
||||
|
||||
static int[] Render(LowPolyAbstractionPipeline pipeline, int[] source, int width, int height, LowPolyAbstractionPipeline.Parameters parameters)
|
||||
{
|
||||
var destination = new int[source.Length];
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
return destination;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATransparentSourceProducesNoTriangles()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var destination = Enumerable.Repeat(-1, 64 * 64).ToArray();
|
||||
var parameters = Parameters();
|
||||
|
||||
pipeline.Process(new int[64 * 64], destination, 64, 64, in parameters);
|
||||
|
||||
Assert.All(destination, pixel => Assert.Equal(0, pixel));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOpaqueSourceProducesTriangles()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
|
||||
var rendering = Render(pipeline, TwoTone(128, 128, 24, 24, 80, 80), 128, 128, Parameters());
|
||||
|
||||
Assert.True(LitPixels(rendering) > 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSameSettingsAlwaysProduceTheSameTriangles()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = TwoTone(128, 128, 24, 24, 80, 80);
|
||||
|
||||
var first = Render(pipeline, source, 128, 128, Parameters(jitter: 0.5f, seed: 42));
|
||||
var second = Render(pipeline, source, 128, 128, Parameters(jitter: 0.5f, seed: 42));
|
||||
|
||||
Assert.Equal(first, second);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADifferentSeedPlacesTheTrianglesDifferently()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = TwoTone(128, 128, 24, 24, 80, 80);
|
||||
|
||||
var first = Render(pipeline, source, 128, 128, Parameters(seed: 1));
|
||||
var second = Render(pipeline, source, 128, 128, Parameters(seed: 2));
|
||||
|
||||
Assert.NotEqual(first, second);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheTrianglesStayPremultiplied()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
|
||||
var rendering = Render(pipeline, TwoTone(128, 128, 24, 24, 80, 80), 128, 128, Parameters(gradient: 1f, wireframe: 1f, saturation: 1f, jitter: 1f));
|
||||
|
||||
Assert.All(rendering, pixel =>
|
||||
{
|
||||
Assert.InRange((pixel >> 16) & 255, 0, Alpha(pixel));
|
||||
Assert.InRange((pixel >> 8) & 255, 0, Alpha(pixel));
|
||||
Assert.InRange(pixel & 255, 0, Alpha(pixel));
|
||||
});
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LowPolyAbstractionQuality.Balanced, 0f, 128)]
|
||||
[InlineData(LowPolyAbstractionQuality.Balanced, 1f, 128)]
|
||||
[InlineData(LowPolyAbstractionQuality.High, 0f, 128)]
|
||||
[InlineData(LowPolyAbstractionQuality.High, 1f, 128)]
|
||||
[InlineData(LowPolyAbstractionQuality.High, 0f, 1600)]
|
||||
public void ASingleColorShapeIsDrawnInItsOwnColor(LowPolyAbstractionQuality quality, float gradient, int size)
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
const int color = unchecked((int)0xFF3080C0);
|
||||
var start = size * 3 / 16;
|
||||
var side = size * 5 / 8;
|
||||
var source = TwoTone(size, size, start, start, side, side).Select(pixel => pixel == 0 ? 0 : color).ToArray();
|
||||
|
||||
var rendering = Render(pipeline, source, size, size, Parameters(quality, gradient: gradient, saturation: 0f, jitter: 0f));
|
||||
|
||||
var drawn = 0;
|
||||
for (var y = start; y < start + side; y++)
|
||||
{
|
||||
for (var x = start; x < start + side; x++)
|
||||
{
|
||||
var pixel = rendering[y * size + x];
|
||||
if (Alpha(pixel) == 0)
|
||||
continue;
|
||||
drawn++;
|
||||
if (pixel != color)
|
||||
Assert.Fail($"({x}, {y}) {pixel:X8}");
|
||||
}
|
||||
}
|
||||
Assert.True(drawn > side * side / 2, $"{drawn}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.5f)]
|
||||
[InlineData(0.2f)]
|
||||
public void TheWireframeDarkensTheSameLinesInProportionToItsValue(float wireframe)
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
const int color = unchecked((int)0xFF3080C0);
|
||||
var source = TwoTone(128, 128, 24, 24, 80, 80).Select(pixel => pixel == 0 ? 0 : color).ToArray();
|
||||
int[] RenderWith(float value) => Render(pipeline, source, 128, 128, Parameters(gradient: 0f, wireframe: value, saturation: 0f, jitter: 0f, seed: 1));
|
||||
var plain = RenderWith(0f);
|
||||
var full = RenderWith(1f);
|
||||
|
||||
var partial = RenderWith(wireframe);
|
||||
|
||||
var lined = 0;
|
||||
for (var index = 0; index < source.Length; index++)
|
||||
{
|
||||
if (plain[index] != color)
|
||||
continue;
|
||||
if (full[index] != color)
|
||||
lined++;
|
||||
for (var shift = 0; shift < 24; shift += 8)
|
||||
{
|
||||
var channel = (color >> shift) & 255;
|
||||
var fullDarkening = channel - ((full[index] >> shift) & 255);
|
||||
var partialDarkening = channel - ((partial[index] >> shift) & 255);
|
||||
Assert.InRange(partialDarkening, fullDarkening * wireframe - 1, fullDarkening * wireframe + 1);
|
||||
}
|
||||
}
|
||||
Assert.True(lined > 128, $"{lined}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(128, 128, LowPolyAbstractionQuality.High)]
|
||||
[InlineData(96, 96, LowPolyAbstractionQuality.High)]
|
||||
[InlineData(160, 192, LowPolyAbstractionQuality.High)]
|
||||
[InlineData(128, 96, LowPolyAbstractionQuality.High)]
|
||||
[InlineData(96, 128, LowPolyAbstractionQuality.High)]
|
||||
[InlineData(128, 128, LowPolyAbstractionQuality.Balanced)]
|
||||
public void APipelineThatDrewAnotherImageDrawsLikeAFreshOne(int previousWidth, int previousHeight, LowPolyAbstractionQuality previousQuality)
|
||||
{
|
||||
var source = TwoTone(128, 128, 24, 24, 80, 80);
|
||||
var parameters = Parameters(LowPolyAbstractionQuality.High, seed: 7);
|
||||
int[] expected;
|
||||
using (var fresh = CreatePipeline())
|
||||
expected = Render(fresh, source, 128, 128, parameters);
|
||||
using var pipeline = CreatePipeline();
|
||||
Render(pipeline, Noise(previousWidth, previousHeight, 8, 8, previousWidth - 16, previousHeight - 16), previousWidth, previousHeight, Parameters(previousQuality, seed: 3));
|
||||
|
||||
var reused = Render(pipeline, source, 128, 128, parameters);
|
||||
|
||||
Assert.Equal(expected, reused);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void APixelCountBeyondTheIntegerRangeIsRejected()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var parameters = Parameters();
|
||||
|
||||
Assert.Throws<OverflowException>(() => pipeline.Process([], [], 65536, 65536, in parameters));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoreDetailChangesTheTriangulation()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = TwoTone(128, 128, 24, 24, 80, 80);
|
||||
|
||||
var coarse = Render(pipeline, source, 128, 128, Parameters(detail: 0.1f));
|
||||
var fine = Render(pipeline, source, 128, 128, Parameters(detail: 1f));
|
||||
|
||||
Assert.True(LitPixels(coarse) > 0);
|
||||
Assert.True(LitPixels(fine) > 0);
|
||||
Assert.NotEqual(coarse, fine);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RefinementChangesTheTrianglesOfANoisySource()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = Noise(128, 128, 16, 16, 96, 96);
|
||||
|
||||
var without = Render(pipeline, source, 128, 128, Parameters(refine: 0f));
|
||||
var with = Render(pipeline, source, 128, 128, Parameters(refine: 1f));
|
||||
|
||||
Assert.True(LitPixels(without) > 0);
|
||||
Assert.NotEqual(without, with);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheTrianglesStayWithinTheSilhouetteAndItsPadding()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var padding = LowPolyAbstractionSettings.MarginPadding;
|
||||
|
||||
var rendering = Render(pipeline, TwoTone(192, 192, 64, 64, 48, 48), 192, 192, Parameters());
|
||||
|
||||
for (var y = 0; y < 192; y++)
|
||||
{
|
||||
for (var x = 0; x < 192; x++)
|
||||
{
|
||||
if (Alpha(rendering[y * 192 + x]) == 0)
|
||||
continue;
|
||||
Assert.InRange(x, 64 - padding, 64 + 48 + padding);
|
||||
Assert.InRange(y, 64 - padding, 64 + 48 + padding);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LowPolyAbstractionQuality.Balanced)]
|
||||
[InlineData(LowPolyAbstractionQuality.High)]
|
||||
[InlineData(LowPolyAbstractionQuality.Ultra)]
|
||||
public void ADiscIsNotPaintedBeyondItsOutline(LowPolyAbstractionQuality quality)
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
const int size = 256;
|
||||
static int DistanceSquared(int x, int y) => (x - 128) * (x - 128) + (y - 128) * (y - 128);
|
||||
var source = Silhouette(size, (x, y) => DistanceSquared(x, y) < 90 * 90);
|
||||
|
||||
var rendering = Render(pipeline, source, size, size, Parameters(quality));
|
||||
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
if (DistanceSquared(x, y) > 93 * 93)
|
||||
Assert.True(Alpha(rendering[y * size + x]) == 0, $"({x}, {y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(Hollow.Notch, LowPolyAbstractionQuality.Balanced)]
|
||||
[InlineData(Hollow.Notch, LowPolyAbstractionQuality.High)]
|
||||
[InlineData(Hollow.Notch, LowPolyAbstractionQuality.Ultra)]
|
||||
[InlineData(Hollow.Gap, LowPolyAbstractionQuality.Balanced)]
|
||||
[InlineData(Hollow.Gap, LowPolyAbstractionQuality.High)]
|
||||
[InlineData(Hollow.Gap, LowPolyAbstractionQuality.Ultra)]
|
||||
[InlineData(Hollow.Hole, LowPolyAbstractionQuality.Balanced)]
|
||||
[InlineData(Hollow.Hole, LowPolyAbstractionQuality.High)]
|
||||
[InlineData(Hollow.Hole, LowPolyAbstractionQuality.Ultra)]
|
||||
public void TheHollowsOfAShapeStayTransparent(Hollow hollow, LowPolyAbstractionQuality quality)
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
const int size = 256;
|
||||
var inside = HollowShape(hollow);
|
||||
|
||||
var rendering = Render(pipeline, Silhouette(size, inside), size, size, Parameters(quality));
|
||||
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
if (!AnyWithin(x, y, 3, inside))
|
||||
Assert.True(Alpha(rendering[y * size + x]) == 0, $"({x}, {y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(Hollow.Notch, LowPolyAbstractionQuality.Balanced)]
|
||||
[InlineData(Hollow.Gap, LowPolyAbstractionQuality.High)]
|
||||
[InlineData(Hollow.Hole, LowPolyAbstractionQuality.Ultra)]
|
||||
public void TheBodyOfAHollowShapeStaysPainted(Hollow hollow, LowPolyAbstractionQuality quality)
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
const int size = 256;
|
||||
var inside = HollowShape(hollow);
|
||||
|
||||
var rendering = Render(pipeline, Silhouette(size, inside), size, size, Parameters(quality));
|
||||
|
||||
int body = 0, painted = 0;
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
if (AnyWithin(x, y, 3, (sx, sy) => !inside(sx, sy)))
|
||||
continue;
|
||||
body++;
|
||||
if (Alpha(rendering[y * size + x]) > 0)
|
||||
painted++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(body > 10000);
|
||||
Assert.True(painted >= body * 0.99, $"{painted}/{body}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FineGaps.Lattice)]
|
||||
[InlineData(FineGaps.Speckles)]
|
||||
public void FineGapsStayOpenAndTheMaterialAroundThemIsPainted(FineGaps gaps)
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
const int size = 256;
|
||||
var inside = FineGapShape(gaps);
|
||||
|
||||
var rendering = Render(pipeline, Silhouette(size, inside), size, size, Parameters(LowPolyAbstractionQuality.High));
|
||||
|
||||
int material = 0, painted = 0;
|
||||
for (var y = 44; y < 212; y++)
|
||||
{
|
||||
for (var x = 44; x < 212; x++)
|
||||
{
|
||||
var alpha = Alpha(rendering[y * size + x]);
|
||||
if (!inside(x, y))
|
||||
{
|
||||
Assert.True(alpha == 0, $"({x}, {y})");
|
||||
continue;
|
||||
}
|
||||
material++;
|
||||
if (alpha > 0)
|
||||
painted++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(painted >= material * 0.95, $"{painted}/{material}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LowPolyAbstractionQuality.Balanced)]
|
||||
[InlineData(LowPolyAbstractionQuality.High)]
|
||||
[InlineData(LowPolyAbstractionQuality.Ultra)]
|
||||
public void ThePaintIsNeverMoreOpaqueThanTheMaterial(LowPolyAbstractionQuality quality)
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
const int size = 256;
|
||||
var source = new int[size * size];
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
var distance = Math.Sqrt((x - 128) * (x - 128) + (y - 128) * (y - 128));
|
||||
var alpha = (int)Math.Round(Math.Clamp((100 - distance) / 24, 0, 1) * 255);
|
||||
source[y * size + x] = alpha << 24 | alpha * (40 + x * 3 / 4) / 255 << 16 | alpha * (200 - y / 2) / 255 << 8 | alpha * (80 + (x + y) / 4) / 255;
|
||||
}
|
||||
}
|
||||
|
||||
var rendering = Render(pipeline, source, size, size, Parameters(quality));
|
||||
|
||||
for (var index = 0; index < source.Length; index++)
|
||||
Assert.True(Alpha(rendering[index]) <= Alpha(source[index]), $"({index % size}, {index / size}) {Alpha(rendering[index])} > {Alpha(source[index])}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheHollowsStayTransparentWhenTheMaterialIsReducedForTheCalculation()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
const int scale = 8, size = 256 * scale;
|
||||
var hollow = HollowShape(Hollow.Notch);
|
||||
bool Inside(int x, int y) => hollow(x / scale, y / scale);
|
||||
|
||||
var rendering = Render(pipeline, Silhouette(size, Inside), size, size, Parameters(LowPolyAbstractionQuality.Balanced));
|
||||
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
if (Alpha(rendering[y * size + x]) > 0)
|
||||
Assert.True(AnyWithin(x, y, 3, Inside), $"({x}, {y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AWarmPipelineAllocatesNoManagedMemory()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = TwoTone(64, 64, 16, 16, 32, 32);
|
||||
var destination = new int[source.Length];
|
||||
var parameters = Parameters();
|
||||
for (var iteration = 0; iteration < 4; iteration++)
|
||||
pipeline.Process(source, destination, 64, 64, in parameters);
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
GC.Collect();
|
||||
|
||||
var minimum = long.MaxValue;
|
||||
for (var iteration = 0; iteration < 16; iteration++)
|
||||
{
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
pipeline.Process(source, destination, 64, 64, in parameters);
|
||||
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
}
|
||||
|
||||
Assert.Equal(0, minimum);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SharedTexturesProduceTheSameTrianglesAsPackedBuffers()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = TwoTone(96, 96, 24, 24, 48, 48);
|
||||
var parameters = Parameters(seed: 11);
|
||||
var expected = Render(pipeline, source, 96, 96, parameters);
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 96, 96);
|
||||
using var outputTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 96, 96);
|
||||
Upload(sourceTexture, source);
|
||||
|
||||
pipeline.ProcessSharedAndWait(sourceTexture, outputTexture, 96, 96, in parameters);
|
||||
var result = new Bgra32[source.Length];
|
||||
outputTexture.CopyTo(result);
|
||||
|
||||
Assert.Equal(expected.Select(pixel => unchecked((uint)pixel)), result.Select(pixel => pixel.PackedValue));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RepeatedSharedTextureSubmissionsAllocateNoManagedMemory()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var source = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 64, 64);
|
||||
using var destination = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 64, 64);
|
||||
var parameters = Parameters();
|
||||
for (var iteration = 0; iteration < 4; iteration++)
|
||||
pipeline.Process(source, destination, 64, 64, in parameters);
|
||||
pipeline.WaitForCompletion();
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
GC.Collect();
|
||||
|
||||
var minimum = long.MaxValue;
|
||||
for (var iteration = 0; iteration < 16; iteration++)
|
||||
{
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
pipeline.Process(source, destination, 64, 64, in parameters);
|
||||
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
}
|
||||
pipeline.WaitForCompletion();
|
||||
|
||||
Assert.Equal(0, minimum);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheVisibleBoundsHoldEveryLitPixelAndRenderTheSameTriangles()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = TwoTone(192, 192, 64, 64, 48, 40);
|
||||
var parameters = Parameters(seed: 5);
|
||||
var full = Render(pipeline, source, 192, 192, parameters);
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(192, 192);
|
||||
Upload(sourceTexture, source);
|
||||
|
||||
pipeline.Simulate(sourceTexture, 192, 192, 0, 0, 192, 192, in parameters);
|
||||
Assert.True(pipeline.TryGetVisibleBounds(192, 192, in parameters, out var rect));
|
||||
using var outputTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
|
||||
pipeline.RenderVisible(outputTexture, 192, 192, rect, in parameters);
|
||||
var visible = new Bgra32[rect.Width * rect.Height];
|
||||
outputTexture.CopyTo(visible);
|
||||
|
||||
Assert.True(rect is { Width: > 0, Height: > 0, X: >= 0, Y: >= 0 });
|
||||
Assert.True(rect.X + rect.Width <= 192 && rect.Y + rect.Height <= 192);
|
||||
for (var y = 0; y < 192; y++)
|
||||
{
|
||||
for (var x = 0; x < 192; x++)
|
||||
{
|
||||
var inside = x >= rect.X && x < rect.X + rect.Width && y >= rect.Y && y < rect.Y + rect.Height;
|
||||
if (!inside)
|
||||
Assert.Equal(0, full[y * 192 + x]);
|
||||
else
|
||||
Assert.Equal(unchecked((uint)full[y * 192 + x]), visible[(y - rect.Y) * rect.Width + x - rect.X].PackedValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(192, 64, 64, 48, 40)]
|
||||
[InlineData(192, 61, 70, 45, 37)]
|
||||
[InlineData(192, 2, 3, 40, 41)]
|
||||
[InlineData(192, 150, 149, 42, 43)]
|
||||
[InlineData(190, 148, 147, 42, 43)]
|
||||
public void TheVisibleBoundsHugTheShapeAndItsPaddingOnAFourPixelGrid(int canvas, int left, int top, int width, int height)
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var padding = LowPolyAbstractionSettings.MarginPadding;
|
||||
var parameters = Parameters(seed: 5);
|
||||
using var source = GraphicsDevice.GetDefault().AllocateReadWriteTexture2D<Bgra32, Float4>(canvas, canvas);
|
||||
Upload(source, TwoTone(canvas, canvas, left, top, width, height));
|
||||
|
||||
pipeline.Simulate(source, canvas, canvas, 0, 0, canvas, canvas, in parameters);
|
||||
|
||||
Assert.True(pipeline.TryGetVisibleBounds(canvas, canvas, in parameters, out var rect));
|
||||
Assert.Equal((0, 0), (rect.X % 4, rect.Y % 4));
|
||||
Assert.True(rect.Width % 4 == 0 || rect.X + rect.Width == canvas, $"{rect}");
|
||||
Assert.True(rect.Height % 4 == 0 || rect.Y + rect.Height == canvas, $"{rect}");
|
||||
Assert.InRange(rect.X, Math.Max(left - padding - 3, 0), Math.Max(left - padding, 0));
|
||||
Assert.InRange(rect.Y, Math.Max(top - padding - 3, 0), Math.Max(top - padding, 0));
|
||||
Assert.InRange(rect.X + rect.Width, Math.Min(left + width + padding, canvas), Math.Min(left + width + padding + 3, canvas));
|
||||
Assert.InRange(rect.Y + rect.Height, Math.Min(top + height + padding, canvas), Math.Min(top + height + padding + 3, canvas));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASourceThatTurnsTransparentHasNoVisibleBounds()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var parameters = Parameters();
|
||||
using var source = UploadedSquare();
|
||||
pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in parameters);
|
||||
Assert.True(pipeline.TryGetVisibleBounds(128, 128, in parameters, out _));
|
||||
|
||||
Upload(source, new int[128 * 128]);
|
||||
pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in parameters);
|
||||
|
||||
Assert.False(pipeline.TryGetVisibleBounds(128, 128, in parameters, out var rect));
|
||||
Assert.Equal(default, rect);
|
||||
}
|
||||
|
||||
static LowPolyAbstractionPipeline.Parameters Changed(LowPolyAbstractionPipeline.Parameters parameters, string setting)
|
||||
=> setting switch
|
||||
{
|
||||
nameof(LowPolyAbstractionPipeline.Parameters.Quality) => parameters with { Quality = LowPolyAbstractionQuality.High },
|
||||
nameof(LowPolyAbstractionPipeline.Parameters.Detail) => parameters with { Detail = 0.9f },
|
||||
nameof(LowPolyAbstractionPipeline.Parameters.Fidelity) => parameters with { Fidelity = 0.2f },
|
||||
nameof(LowPolyAbstractionPipeline.Parameters.Refine) => parameters with { Refine = 0.9f },
|
||||
nameof(LowPolyAbstractionPipeline.Parameters.Seed) => parameters with { Seed = 4 },
|
||||
nameof(LowPolyAbstractionPipeline.Parameters.Gradient) => parameters with { Gradient = 1f },
|
||||
nameof(LowPolyAbstractionPipeline.Parameters.Wireframe) => parameters with { Wireframe = 1f },
|
||||
nameof(LowPolyAbstractionPipeline.Parameters.Saturation) => parameters with { Saturation = 1f },
|
||||
nameof(LowPolyAbstractionPipeline.Parameters.Jitter) => parameters with { Jitter = 1f },
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(setting), setting, null),
|
||||
};
|
||||
|
||||
static ReadWriteTexture2D<Bgra32, Float4> UploadedSquare()
|
||||
{
|
||||
var texture = GraphicsDevice.GetDefault().AllocateReadWriteTexture2D<Bgra32, Float4>(128, 128);
|
||||
Upload(texture, TwoTone(128, 128, 24, 24, 80, 80));
|
||||
return texture;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(LowPolyAbstractionPipeline.Parameters.Gradient))]
|
||||
[InlineData(nameof(LowPolyAbstractionPipeline.Parameters.Wireframe))]
|
||||
[InlineData(nameof(LowPolyAbstractionPipeline.Parameters.Saturation))]
|
||||
[InlineData(nameof(LowPolyAbstractionPipeline.Parameters.Jitter))]
|
||||
public void ChangingOnlyTheDrawingKeepsTheMesh(string setting)
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
using var source = UploadedSquare();
|
||||
var parameters = Parameters(seed: 3);
|
||||
Assert.True(pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in parameters));
|
||||
|
||||
var changed = Changed(parameters, setting);
|
||||
|
||||
Assert.False(pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in changed), setting);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(LowPolyAbstractionPipeline.Parameters.Quality))]
|
||||
[InlineData(nameof(LowPolyAbstractionPipeline.Parameters.Detail))]
|
||||
[InlineData(nameof(LowPolyAbstractionPipeline.Parameters.Fidelity))]
|
||||
[InlineData(nameof(LowPolyAbstractionPipeline.Parameters.Refine))]
|
||||
[InlineData(nameof(LowPolyAbstractionPipeline.Parameters.Seed))]
|
||||
public void ChangingTheMeshSettingsComputesTheMeshAgain(string setting)
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
using var source = UploadedSquare();
|
||||
var parameters = Parameters(seed: 3);
|
||||
Assert.True(pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in parameters));
|
||||
Assert.False(pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in parameters));
|
||||
|
||||
var changed = Changed(parameters, setting);
|
||||
|
||||
Assert.True(pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in changed), setting);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MovingTheShapeComputesTheMeshAgain()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
using var source = UploadedSquare();
|
||||
var parameters = Parameters(seed: 3);
|
||||
Assert.True(pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in parameters));
|
||||
Assert.False(pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in parameters));
|
||||
|
||||
Upload(source, TwoTone(128, 128, 8, 8, 80, 80));
|
||||
|
||||
Assert.True(pipeline.Simulate(source, 128, 128, 0, 0, 128, 128, in parameters));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
namespace LowPolyAbstraction.Tests;
|
||||
|
||||
public sealed class LowPolyAbstractionSettingsTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(LowPolyAbstractionQuality.Balanced, 1024, 4096, 6, 1)]
|
||||
[InlineData(LowPolyAbstractionQuality.High, 1536, 8192, 8, 2)]
|
||||
[InlineData(LowPolyAbstractionQuality.Ultra, 2048, 16384, 10, 3)]
|
||||
public void EveryQualityChoosesItsResolutionSitesAndIterations(LowPolyAbstractionQuality quality, int resolution, int sites, int cvtIterations, int refinePasses)
|
||||
{
|
||||
var settings = LowPolyAbstractionSettings.GetQuality(quality);
|
||||
|
||||
Assert.Equal(resolution, settings.WorkingResolution);
|
||||
Assert.Equal(sites, settings.BaseSites);
|
||||
Assert.Equal(cvtIterations, settings.CvtIterations);
|
||||
Assert.Equal(refinePasses, settings.RefinePasses);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1920, 1080, 1536)]
|
||||
[InlineData(1080, 1920, 1536)]
|
||||
[InlineData(8, 8, 1536)]
|
||||
[InlineData(4096, 16, 1024)]
|
||||
[InlineData(100, 100, 2048)]
|
||||
public void TheWorkingGridCoversTheWholeCanvas(int width, int height, int resolution)
|
||||
{
|
||||
var (workingWidth, workingHeight, scale) = LowPolyAbstractionSettings.GetWorkingSize(width, height, resolution);
|
||||
|
||||
Assert.True(workingWidth >= LowPolyAbstractionSettings.MinimumWorkingSize);
|
||||
Assert.True(workingHeight >= LowPolyAbstractionSettings.MinimumWorkingSize);
|
||||
Assert.True(scale > 0f);
|
||||
Assert.True(workingWidth * scale >= width);
|
||||
Assert.True(workingHeight * scale >= height);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1920, 1080, 1536, 1536, 864, 1.25f)]
|
||||
[InlineData(1080, 1920, 1536, 864, 1536, 1.25f)]
|
||||
[InlineData(100, 100, 2048, 100, 100, 1f)]
|
||||
[InlineData(8, 8, 1536, 16, 16, 1f)]
|
||||
[InlineData(4096, 16, 1024, 1024, 16, 4f)]
|
||||
public void TheLongSideIsReducedToTheResolutionButNotBelowTheMinimum(int width, int height, int resolution, int expectedWidth, int expectedHeight, float expectedScale)
|
||||
{
|
||||
var (workingWidth, workingHeight, scale) = LowPolyAbstractionSettings.GetWorkingSize(width, height, resolution);
|
||||
|
||||
Assert.Equal(expectedWidth, workingWidth);
|
||||
Assert.Equal(expectedHeight, workingHeight);
|
||||
Assert.Equal(expectedScale, scale, 6);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(4096, 6144)]
|
||||
[InlineData(8192, 12288)]
|
||||
[InlineData(16384, 24576)]
|
||||
public void TheSiteCapacityLeavesRoomForRefinement(int baseSites, int expected)
|
||||
=> Assert.Equal(expected, LowPolyAbstractionSettings.GetSiteCapacity(baseSites));
|
||||
|
||||
[Theory]
|
||||
[InlineData(6144, 12304)]
|
||||
[InlineData(24576, 49168)]
|
||||
public void TheTriangleCapacityHoldsEveryTriangleOfTheSites(int siteCapacity, int expected)
|
||||
=> Assert.Equal(expected, LowPolyAbstractionSettings.GetTriangleCapacity(siteCapacity));
|
||||
|
||||
[Theory]
|
||||
[InlineData(-5f, 4096, 409)]
|
||||
[InlineData(0f, 4096, 409)]
|
||||
[InlineData(1f, 4096, 4096)]
|
||||
[InlineData(5f, 4096, 4096)]
|
||||
[InlineData(0f, 100, 64)]
|
||||
[InlineData(1f, 100, 100)]
|
||||
public void TheSiteCountStaysWithinItsRange(float detail, int baseSites, int expected)
|
||||
=> Assert.Equal(expected, LowPolyAbstractionSettings.GetSiteCount(detail, baseSites));
|
||||
|
||||
[Fact]
|
||||
public void MoreDetailPlacesMoreSites()
|
||||
=> Assert.True(LowPolyAbstractionSettings.GetSiteCount(0.75f, 4096) > LowPolyAbstractionSettings.GetSiteCount(0.25f, 4096));
|
||||
|
||||
[Fact]
|
||||
public void EveryQualityPlacesNoMoreSitesThanItsCapacity()
|
||||
{
|
||||
foreach (var quality in Enum.GetValues<LowPolyAbstractionQuality>())
|
||||
{
|
||||
var baseSites = LowPolyAbstractionSettings.GetQuality(quality).BaseSites;
|
||||
Assert.True(LowPolyAbstractionSettings.GetSiteCount(1f, baseSites) <= LowPolyAbstractionSettings.GetSiteCapacity(baseSites));
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-1f, 81.92f)]
|
||||
[InlineData(0f, 81.92f)]
|
||||
[InlineData(1f, 24.576f)]
|
||||
[InlineData(2f, 24.576f)]
|
||||
public void TheEdgeSpacingStaysWithinItsRange(float fidelity, float expected)
|
||||
=> Assert.Equal(expected, LowPolyAbstractionSettings.GetEdgeSampleSpacing(1024, 1024, fidelity), 3);
|
||||
|
||||
[Fact]
|
||||
public void AHigherFidelitySamplesTheEdgesMoreDensely()
|
||||
=> Assert.True(LowPolyAbstractionSettings.GetEdgeSampleSpacing(1024, 1024, 0.75f) < LowPolyAbstractionSettings.GetEdgeSampleSpacing(1024, 1024, 0.25f));
|
||||
|
||||
[Fact]
|
||||
public void TheEdgeSpacingNeverDropsBelowTwoPixels()
|
||||
=> Assert.Equal(2f, LowPolyAbstractionSettings.GetEdgeSampleSpacing(10, 10, 1f));
|
||||
|
||||
[Theory]
|
||||
[InlineData(1024, 1024, 20.48f)]
|
||||
[InlineData(10, 10, 1f)]
|
||||
public void TheLaneWidthFollowsTheWorkingSizeButNotBelowOnePixel(int width, int height, float expected)
|
||||
=> Assert.Equal(expected, LowPolyAbstractionSettings.GetLaneWidth(width, height), 4);
|
||||
|
||||
[Theory]
|
||||
[InlineData(-1f, LowPolyAbstractionSettings.MaximumErrorThreshold)]
|
||||
[InlineData(0f, LowPolyAbstractionSettings.MaximumErrorThreshold)]
|
||||
[InlineData(1f, LowPolyAbstractionSettings.MinimumErrorThreshold)]
|
||||
[InlineData(2f, LowPolyAbstractionSettings.MinimumErrorThreshold)]
|
||||
public void TheErrorThresholdStaysWithinItsRange(float refine, float expected)
|
||||
=> Assert.Equal(expected, LowPolyAbstractionSettings.GetErrorThreshold(refine), 7);
|
||||
|
||||
[Fact]
|
||||
public void MoreRefinementSplitsTrianglesWithSmallerErrors()
|
||||
=> Assert.True(LowPolyAbstractionSettings.GetErrorThreshold(0.75f) < LowPolyAbstractionSettings.GetErrorThreshold(0.25f));
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 0, 1)]
|
||||
[InlineData(1, 1, 1)]
|
||||
[InlineData(2, 2, 1)]
|
||||
[InlineData(3, 3, 2)]
|
||||
[InlineData(256, 128, 128)]
|
||||
[InlineData(257, 16, 256)]
|
||||
public void TheJumpFloodStartsFromHalfThePowerOfTwoCoveringTheLongSide(int width, int height, int expected)
|
||||
=> Assert.Equal(expected, LowPolyAbstractionSettings.GetJumpFloodInitialStep(width, height));
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.IO.Packaging;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace LowPolyAbstraction.Tests;
|
||||
|
||||
internal static class PackUriScheme
|
||||
{
|
||||
[ModuleInitializer]
|
||||
internal static void Register() => _ = PackUriHelper.UriSchemePack;
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LowPolyAbstraction.Tests;
|
||||
|
||||
internal sealed class Rendering
|
||||
{
|
||||
readonly byte[] pixels;
|
||||
|
||||
public int Left { get; }
|
||||
|
||||
public int Top { get; }
|
||||
|
||||
public int Width { get; }
|
||||
|
||||
public int Height { get; }
|
||||
|
||||
public int Right => Left + Width;
|
||||
|
||||
public int Bottom => Top + Height;
|
||||
|
||||
Rendering(int left, int top, int width, int height, byte[] pixels)
|
||||
{
|
||||
Left = left;
|
||||
Top = top;
|
||||
Width = width;
|
||||
Height = height;
|
||||
this.pixels = pixels;
|
||||
}
|
||||
|
||||
public static Rendering Capture(IGraphicsDevicesAndContext devices, ID2D1Image image)
|
||||
{
|
||||
var context = devices.DeviceContext;
|
||||
var bounds = context.GetImageLocalBounds(image);
|
||||
var left = (int)Math.Floor(bounds.Left);
|
||||
var top = (int)Math.Floor(bounds.Top);
|
||||
var width = (int)Math.Ceiling(bounds.Right) - left;
|
||||
var height = (int)Math.Ceiling(bounds.Bottom) - top;
|
||||
var stride = width * SourceImage.BytesPerPixel;
|
||||
var size = new SizeI(width, height);
|
||||
|
||||
using var target = context.CreateBitmap(size, nint.Zero, stride,
|
||||
new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.Target));
|
||||
using var readback = context.CreateBitmap(size, nint.Zero, stride,
|
||||
new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.CpuRead | BitmapOptions.CannotDraw));
|
||||
|
||||
context.Target = target;
|
||||
context.BeginDraw();
|
||||
context.Clear(new Color4(0f, 0f, 0f, 0f));
|
||||
context.DrawImage(image, new Vector2(-left, -top), null, InterpolationMode.NearestNeighbor, CompositeMode.SourceCopy);
|
||||
context.EndDraw();
|
||||
context.Target = null;
|
||||
|
||||
readback.CopyFromBitmap(target);
|
||||
var pixels = new byte[stride * height];
|
||||
var mapped = readback.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
for (var y = 0; y < height; y++)
|
||||
Marshal.Copy(mapped.Bits + y * (int)mapped.Pitch, pixels, y * stride, stride);
|
||||
}
|
||||
finally
|
||||
{
|
||||
readback.Unmap();
|
||||
}
|
||||
|
||||
return new Rendering(left, top, width, height, pixels);
|
||||
}
|
||||
|
||||
public Bgra this[int x, int y]
|
||||
{
|
||||
get
|
||||
{
|
||||
var offset = ((y - Top) * Width + (x - Left)) * SourceImage.BytesPerPixel;
|
||||
return new Bgra(pixels[offset], pixels[offset + 1], pixels[offset + 2], pixels[offset + 3]);
|
||||
}
|
||||
}
|
||||
|
||||
public bool Contains(int x, int y) => x >= Left && y >= Top && x < Right && y < Bottom;
|
||||
|
||||
public bool SamePixelsAs(Rendering other)
|
||||
=> Left == other.Left && Top == other.Top && Width == other.Width && Height == other.Height && pixels.AsSpan().SequenceEqual(other.pixels);
|
||||
|
||||
public IEnumerable<(int X, int Y)> Coordinates()
|
||||
{
|
||||
for (var y = Top; y < Bottom; y++)
|
||||
{
|
||||
for (var x = Left; x < Right; x++)
|
||||
yield return (x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LowPolyAbstraction.Tests;
|
||||
|
||||
internal sealed class SourceImage : IDisposable
|
||||
{
|
||||
public const float Dpi = 96f;
|
||||
public const int BytesPerPixel = 4;
|
||||
|
||||
public static readonly PixelFormat PixelFormat = new(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
|
||||
|
||||
readonly Func<int, int, Bgra> pixelOf;
|
||||
|
||||
public int Width { get; }
|
||||
|
||||
public int Height { get; }
|
||||
|
||||
public ID2D1Bitmap1 Bitmap { get; }
|
||||
|
||||
public SourceImage(IGraphicsDevicesAndContext devices, int width, int height, Func<int, int, Bgra> pixelOf)
|
||||
{
|
||||
this.pixelOf = pixelOf;
|
||||
Width = width;
|
||||
Height = height;
|
||||
|
||||
var stride = width * BytesPerPixel;
|
||||
var pixels = new byte[stride * height];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var (blue, green, red, alpha) = pixelOf(x, y).Premultiplied();
|
||||
var offset = y * stride + x * BytesPerPixel;
|
||||
pixels[offset] = blue;
|
||||
pixels[offset + 1] = green;
|
||||
pixels[offset + 2] = red;
|
||||
pixels[offset + 3] = alpha;
|
||||
}
|
||||
}
|
||||
|
||||
Bitmap = devices.DeviceContext.CreateBitmap(
|
||||
new SizeI(width, height), nint.Zero, stride,
|
||||
new BitmapProperties1(PixelFormat, Dpi, Dpi, BitmapOptions.None));
|
||||
Bitmap.CopyFromMemory(pixels, stride);
|
||||
}
|
||||
|
||||
public static SourceImage Solid(IGraphicsDevicesAndContext devices, int width, int height, Bgra color)
|
||||
=> new(devices, width, height, (_, _) => color);
|
||||
|
||||
public Bgra this[int x, int y] => pixelOf(x, y).Premultiplied();
|
||||
|
||||
public bool Contains(int x, int y) => x >= 0 && y >= 0 && x < Width && y < Height;
|
||||
|
||||
public void Dispose() => Bitmap.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using System.Collections;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
|
||||
namespace LowPolyAbstraction.Tests;
|
||||
|
||||
public sealed class TextsTests
|
||||
{
|
||||
public static readonly TheoryData<string> Cultures = ["ja-JP", "en-US", "zh-CN", "zh-TW", "ko-KR", "es-ES", "ar-SA", "id-ID"];
|
||||
|
||||
static readonly string[] Keys = typeof(Texts)
|
||||
.GetProperties(BindingFlags.Public | BindingFlags.Static)
|
||||
.Where(property => property.PropertyType == typeof(string) && property.Name != nameof(Texts.CurrentCulture))
|
||||
.Select(property => property.Name)
|
||||
.ToArray();
|
||||
|
||||
[Fact]
|
||||
public void EveryLocalizedKeyHasAProperty()
|
||||
{
|
||||
var resources = Texts.ResourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, false)!;
|
||||
var keys = resources.Cast<DictionaryEntry>().Select(entry => (string)entry.Key).Where(key => key != nameof(Texts.CurrentCulture));
|
||||
|
||||
Assert.Equal(keys.Order(), Keys.Order());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Cultures))]
|
||||
public void EveryKeyIsTranslated(string culture)
|
||||
{
|
||||
var cultureInfo = CultureInfo.GetCultureInfo(culture);
|
||||
|
||||
Assert.All(Keys, key => Assert.False(string.IsNullOrWhiteSpace(Texts.ResourceManager.GetString(key, cultureInfo)), key));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Cultures))]
|
||||
public void EveryCultureCarriesItsOwnTranslations(string culture)
|
||||
{
|
||||
var cultureInfo = CultureInfo.GetCultureInfo(culture);
|
||||
|
||||
Assert.Equal(culture.ToLowerInvariant(), Texts.ResourceManager.GetString(nameof(Texts.CurrentCulture), cultureInfo));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JapaneseIsTheNeutralLanguage()
|
||||
{
|
||||
var neutral = Texts.ResourceManager.GetString(nameof(Texts.LowPolyAbstraction), CultureInfo.InvariantCulture);
|
||||
|
||||
Assert.Equal("ローポリ化", neutral);
|
||||
Assert.Equal(neutral, Texts.ResourceManager.GetString(nameof(Texts.LowPolyAbstraction), CultureInfo.GetCultureInfo("ja-JP")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheUpdateMessageEmbedsTheVersion()
|
||||
{
|
||||
var message = string.Format(CultureInfo.InvariantCulture, Texts.ResourceManager.GetString(nameof(Texts.UpdateAvailableMessage), CultureInfo.InvariantCulture)!, "v1.2.3");
|
||||
|
||||
Assert.Contains("v1.2.3", message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"stryker-config": {
|
||||
"project": "LowPolyAbstraction.csproj",
|
||||
"test-runner": "mtp",
|
||||
"coverage-analysis": "perTest",
|
||||
"concurrency": 8,
|
||||
"additional-timeout": 60000,
|
||||
"mutate": [
|
||||
"**/*.cs",
|
||||
"!**/YMM4-GitHubUpdateNotifier/**",
|
||||
"!**/YMM4-Telemetry/**",
|
||||
"!**/LowPolyAbstractionTelemetry.cs",
|
||||
"!**/LowPolyAbstractionUpdateNotifier.cs"
|
||||
],
|
||||
"reporters": [
|
||||
"progress",
|
||||
"cleartext",
|
||||
"html"
|
||||
],
|
||||
"thresholds": {
|
||||
"high": 80,
|
||||
"low": 60,
|
||||
"break": 60
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
-8
@@ -3,18 +3,23 @@
|
||||
<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="LowPolyAbstraction/LowPolyAbstraction.csproj">
|
||||
<Platform Solution="*|x64" Project="x64" />
|
||||
<BuildDependency Project="LowPolyAbstraction.Shader/LowPolyAbstraction.Shader.vcxproj" />
|
||||
</Project>
|
||||
<Project Path="LowPolyAbstraction.Tests/LowPolyAbstraction.Tests.csproj" />
|
||||
<Project Path="LowPolyAbstraction.Harness/LowPolyAbstraction.Harness.csproj" />
|
||||
<Project Path="LowPolyAbstraction.Shader/LowPolyAbstraction.Shader.vcxproj">
|
||||
<BuildType Solution="*|*" Project="Release" />
|
||||
<Platform Solution="*|*" Project="Win32" />
|
||||
</Project>
|
||||
<Project Path="YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator.csproj" />
|
||||
</Solution>
|
||||
@@ -1,8 +0,0 @@
|
||||
<Project>
|
||||
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp' or '$(MSBuildProjectName)' == 'ComputeSharp.Core'">
|
||||
<IsPackagedProject>false</IsPackagedProject>
|
||||
</PropertyGroup>
|
||||
<ItemGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp.Core'">
|
||||
<InternalsVisibleTo Include="LowPolyAbstraction.ComputeSharp, PublicKey=$(AssemblySignPublicKey)" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,14 +0,0 @@
|
||||
<Project>
|
||||
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp' or '$(MSBuildProjectName)' == 'ComputeSharp.Core'">
|
||||
<BaseOutputPath>$(MSBuildProjectDirectory)\bin\LowPolyAbstraction\</BaseOutputPath>
|
||||
<BaseIntermediateOutputPath>$(MSBuildProjectDirectory)\obj\LowPolyAbstraction\</BaseIntermediateOutputPath>
|
||||
<MSBuildProjectExtensionsPath>$(MSBuildProjectDirectory)\obj\</MSBuildProjectExtensionsPath>
|
||||
<DefaultItemExcludes>$(DefaultItemExcludes);$(MSBuildProjectDirectory)\obj\**</DefaultItemExcludes>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp'">
|
||||
<AssemblyName>LowPolyAbstraction.ComputeSharp</AssemblyName>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp.Core'">
|
||||
<AssemblyName>LowPolyAbstraction.ComputeSharp.Core</AssemblyName>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -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>
|
||||
@@ -5,32 +5,18 @@
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<Version>1.0.0</Version>
|
||||
<Version>2.0.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
|
||||
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
|
||||
<ShaderDirPath>..\Release\</ShaderDirPath>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<HlslShader Include="Shaders\**\*.hlsl" />
|
||||
<Resource Include="@(HlslShader->'%(RelativeDir)%(Filename).cso')" />
|
||||
<Resource Include="$(ShaderDirPath)LowPolyAbstraction.cso" Link="Resources\Shader\LowPolyAbstraction.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=""$(FxcPath)" /nologo /T %(HlslShader.ShaderType) /E %(HlslShader.EntryPoint) /Fo "%(HlslShader.ObjectFileOutput)" "%(HlslShader.FullPath)"" 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.6.0" />
|
||||
<PackageReference Include="ILRepack" Version="2.0.48" PrivateAssets="all" ExcludeAssets="all" GeneratePathProperty="true" />
|
||||
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.142" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -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=""$(PkgILRepack)\tools\ILRepack.exe" /out:"$(TargetDir)plugin\$(TargetFileName)" /lib:"$([System.IO.Path]::GetDirectoryName('$(TargetPath)'))" /lib:"$([System.IO.Path]::GetDirectoryName('$(YMM4DirPath)'))" /internalize "$(TargetPath)" "$(TargetDir)ComputeWeave.dll" "$(TargetDir)ComputeWeave.Core.dll"" />
|
||||
</Target>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Shaders\" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(SkipPluginDeploy)' != 'true' AND '$(BuildingSolutionFile)' != 'true'">
|
||||
<Exec Command="mkdir "$(YMM4DirPath)user\plugin\$(ProjectName)" > NUL 2>&1
copy "$(TargetPath)" "$(YMM4DirPath)user\plugin\$(ProjectName)\"
copy "$(TargetDir)LowPolyAbstraction.ComputeSharp.dll" "$(YMM4DirPath)user\plugin\$(ProjectName)\"
copy "$(TargetDir)LowPolyAbstraction.ComputeSharp.Core.dll" "$(YMM4DirPath)user\plugin\$(ProjectName)\"" />
|
||||
<Target Name="PostBuild" AfterTargets="MergePluginAssembly" Condition="'$(SkipPluginDeploy)' != 'true' AND '$(BuildingSolutionFile)' != 'true'">
|
||||
<Exec Command="mkdir "$(YMM4DirPath)user\plugin\$(ProjectName)" > NUL 2>&1
del "$(YMM4DirPath)user\plugin\$(ProjectName)\ComputeWeave.dll" > NUL 2>&1
del "$(YMM4DirPath)user\plugin\$(ProjectName)\ComputeWeave.Core.dll" > NUL 2>&1
copy "$(TargetDir)plugin\$(TargetFileName)" "$(YMM4DirPath)user\plugin\$(ProjectName)\"" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
@@ -33,7 +33,18 @@ internal sealed class LowPolyAbstractionCustomEffect(IGraphicsDevicesAndContext
|
||||
|
||||
protected override void UpdateConstants()
|
||||
{
|
||||
drawInformation?.SetPixelShaderConstantBuffer(_cb);
|
||||
if (drawInformation is null)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
drawInformation.SetPixelShaderConstantBuffer(_cb);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
LowPolyAbstractionTelemetry.Report(exception);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public override void MapInputRectsToOutputRect(
|
||||
|
||||
@@ -15,6 +15,7 @@ public sealed class LowPolyAbstractionEffect : VideoEffectBase
|
||||
|
||||
public LowPolyAbstractionEffect()
|
||||
{
|
||||
LowPolyAbstractionTelemetry.EnsureStartedOnce();
|
||||
LowPolyAbstractionUpdateNotifier.EnsureCheckedOnce();
|
||||
}
|
||||
|
||||
@@ -71,7 +72,17 @@ public sealed class LowPolyAbstractionEffect : VideoEffectBase
|
||||
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
|
||||
|
||||
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices)
|
||||
=> new LowPolyAbstractionEffectProcessor(devices, this);
|
||||
{
|
||||
try
|
||||
{
|
||||
return new LowPolyAbstractionEffectProcessor(devices, this);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
LowPolyAbstractionTelemetry.Report(exception);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
protected override IEnumerable<IAnimatable> GetAnimatables()
|
||||
=> _animatables ??= [Amount, Detail, Fidelity, Refine, Gradient, Wireframe, Saturation, Jitter];
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.ComponentModel;
|
||||
using System.Numerics;
|
||||
using ComputeWeave;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
@@ -11,7 +13,11 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa
|
||||
{
|
||||
private readonly IGraphicsDevicesAndContext _devices;
|
||||
private readonly LowPolyAbstractionEffect _item;
|
||||
private LowPolyAbstractionGpuInterop? _interop;
|
||||
private ComputeExternalQueueScheduler? _scheduler;
|
||||
private LowPolyAbstractionInteropProvider? _interopProvider;
|
||||
private ComputeInteropDomain? _interopDomain;
|
||||
private LowPolyAbstractionResourceSet? _resourceSet;
|
||||
private ExternalTextureLease<ExternalDirect3D11TextureView>? _outputLease;
|
||||
private LowPolyAbstractionPipeline? _pipeline;
|
||||
private LowPolyAbstractionCustomEffect? _effect;
|
||||
private Crop? _outputCrop;
|
||||
@@ -37,7 +43,20 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa
|
||||
|
||||
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)
|
||||
{
|
||||
LowPolyAbstractionTelemetry.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;
|
||||
@@ -93,8 +112,14 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa
|
||||
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 LowPolyAbstractionPipeline.Parameters(
|
||||
parameters.Quality,
|
||||
@@ -107,24 +132,15 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa
|
||||
Math.Clamp(parameters.Jitter, 0f, 1f),
|
||||
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))
|
||||
{
|
||||
@@ -135,9 +151,16 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa
|
||||
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.Gradient,
|
||||
pipelineParameters.Wireframe,
|
||||
@@ -146,32 +169,22 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa
|
||||
rect);
|
||||
if (structureChanged || outputChanged || !_hasOutput || !_hasRenderState || _renderState != renderState)
|
||||
{
|
||||
_interop.BeginCompute();
|
||||
try
|
||||
{
|
||||
_pipeline.RenderVisible(
|
||||
_interop.SourceTexture,
|
||||
_interop.OutputTexture,
|
||||
canvasWidth,
|
||||
canvasHeight,
|
||||
margin,
|
||||
margin,
|
||||
itemWidth,
|
||||
itemHeight,
|
||||
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);
|
||||
@@ -194,15 +207,97 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa
|
||||
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 = LowPolyAbstractionGpuInterop.TryCreate(devices);
|
||||
if (interop is null)
|
||||
return null;
|
||||
var pipeline = LowPolyAbstractionPipeline.TryCreate(interop.Device);
|
||||
if (pipeline is null)
|
||||
var scheduler = ComputeExternalQueueScheduler.Create();
|
||||
var interopProvider = LowPolyAbstractionInteropProvider.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 = LowPolyAbstractionResourceSet.Create(interopDevice, _interopDomain);
|
||||
_pipeline = LowPolyAbstractionPipeline.TryCreate(interopDevice);
|
||||
}
|
||||
catch (Win32Exception)
|
||||
{
|
||||
ReleaseInterop();
|
||||
return null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
ReleaseInterop();
|
||||
throw;
|
||||
}
|
||||
|
||||
if (_pipeline is null)
|
||||
{
|
||||
ReleaseInterop();
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -218,8 +313,7 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa
|
||||
if (!effect.IsEnabled)
|
||||
{
|
||||
effect.Dispose();
|
||||
pipeline.Dispose();
|
||||
interop.Dispose();
|
||||
ReleaseInterop();
|
||||
return null;
|
||||
}
|
||||
outputCrop = new Crop(devices.DeviceContext);
|
||||
@@ -231,8 +325,6 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa
|
||||
outputTransform.SetInput(0, outputCropOutput, true);
|
||||
outputTransformOutput = outputTransform.Output;
|
||||
output = effect.Output;
|
||||
_interop = interop;
|
||||
_pipeline = pipeline;
|
||||
_effect = effect;
|
||||
_outputCrop = outputCrop;
|
||||
_outputCropOutput = outputCropOutput;
|
||||
@@ -254,13 +346,25 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa
|
||||
outputCropOutput?.Dispose();
|
||||
outputCrop?.Dispose();
|
||||
effect?.Dispose();
|
||||
pipeline.Dispose();
|
||||
interop.Dispose();
|
||||
ReleaseInterop();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void setInput(ID2D1Image? inputImage)
|
||||
{
|
||||
try
|
||||
{
|
||||
SetInputCore(inputImage);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
LowPolyAbstractionTelemetry.Report(exception);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private void SetInputCore(ID2D1Image? inputImage)
|
||||
{
|
||||
_effect?.SetInput(0, inputImage, true);
|
||||
if (!_hasOutput)
|
||||
@@ -286,13 +390,14 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa
|
||||
if (disposing)
|
||||
{
|
||||
ClearEffectChain();
|
||||
_interop?.WaitForIdle();
|
||||
_pipeline?.Dispose();
|
||||
_pipeline = null;
|
||||
_interop?.Dispose();
|
||||
_interop = null;
|
||||
ReleaseInterop();
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
LowPolyAbstractionTelemetry.Report(exception);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
base.Dispose(disposing);
|
||||
|
||||
@@ -1,323 +1,89 @@
|
||||
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 LowPolyAbstraction;
|
||||
|
||||
internal sealed class LowPolyAbstractionGpuInterop : IDisposable
|
||||
internal sealed class LowPolyAbstractionInteropProvider : 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 LowPolyAbstractionGpuInterop(
|
||||
GraphicsDevice device,
|
||||
ID3D11Device1 d3dDevice,
|
||||
ID3D11DeviceContext4 d3dContext,
|
||||
ID3D11Fence fence,
|
||||
private LowPolyAbstractionInteropProvider(
|
||||
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 LowPolyAbstractionGpuInterop? TryCreate(IGraphicsDevicesAndContext devices)
|
||||
public static LowPolyAbstractionInteropProvider? 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);
|
||||
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);
|
||||
return new LowPolyAbstractionGpuInterop(device, d3dDevice, d3dContext, fence, renderContext, d3d12Fence);
|
||||
var provider = new LowPolyAbstractionInteropProvider(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?.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 LowPolyAbstractionResourceSet
|
||||
{
|
||||
[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;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using ComputeSharp;
|
||||
// Stryker disable all
|
||||
using ComputeWeave;
|
||||
|
||||
namespace LowPolyAbstraction;
|
||||
|
||||
@@ -108,9 +109,12 @@ internal readonly partial struct AnalyzeShader(
|
||||
var index = wy * workingWidth + wx;
|
||||
color[index] = mean;
|
||||
var l = mean.X * 0.299f + mean.Y * 0.587f + mean.Z * 0.114f;
|
||||
luma[index] = l;
|
||||
luma[index] = l + mean.W;
|
||||
|
||||
var quantized = (uint)(Hlsl.Saturate(l) * 255f + 0.5f) | ((uint)(Hlsl.Saturate(mean.W) * 255f + 0.5f) << 8);
|
||||
var quantized = (uint)(Hlsl.Saturate(mean.X) * 255f + 0.5f) |
|
||||
((uint)(Hlsl.Saturate(mean.Y) * 255f + 0.5f) << 8) |
|
||||
((uint)(Hlsl.Saturate(mean.Z) * 255f + 0.5f) << 16) |
|
||||
((uint)(Hlsl.Saturate(mean.W) * 255f + 0.5f) << 24);
|
||||
var mixed = ((uint)index * 0x9E3779B9u) ^ (quantized * 0x85EBCA6Bu);
|
||||
mixed ^= mixed >> 16;
|
||||
mixed *= 0x85EBCA6Bu;
|
||||
@@ -137,13 +141,11 @@ internal readonly partial struct AnalyzeShader(
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct EdgeShader(
|
||||
ReadWriteBuffer<float> luma,
|
||||
ReadWriteBuffer<Float4> color,
|
||||
ReadWriteBuffer<float> edgeMagnitude,
|
||||
int workingWidth,
|
||||
int workingHeight) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<float> luma = luma;
|
||||
private readonly ReadWriteBuffer<Float4> color = color;
|
||||
private readonly ReadWriteBuffer<float> edgeMagnitude = edgeMagnitude;
|
||||
private readonly int workingWidth = workingWidth;
|
||||
private readonly int workingHeight = workingHeight;
|
||||
@@ -152,8 +154,7 @@ internal readonly partial struct EdgeShader(
|
||||
{
|
||||
x = Hlsl.Clamp(x, 0, workingWidth - 1);
|
||||
y = Hlsl.Clamp(y, 0, workingHeight - 1);
|
||||
var index = y * workingWidth + x;
|
||||
return luma[index] + color[index].W;
|
||||
return luma[y * workingWidth + x];
|
||||
}
|
||||
|
||||
public void Execute()
|
||||
@@ -933,22 +934,50 @@ internal readonly partial struct IncidenceBuildShader(
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct SortIncidenceShader(
|
||||
ReadWriteBuffer<int> incidenceCounts,
|
||||
ReadWriteBuffer<int> incidence,
|
||||
int siteCapacity) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<int> incidenceCounts = incidenceCounts;
|
||||
private readonly ReadWriteBuffer<int> incidence = incidence;
|
||||
private readonly int siteCapacity = siteCapacity;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var site = ThreadIds.X;
|
||||
if (site >= siteCapacity)
|
||||
return;
|
||||
var listed = Hlsl.Min(incidenceCounts[site], LowPolyAbstractionSettings.MaxIncidence);
|
||||
var baseIndex = site * LowPolyAbstractionSettings.MaxIncidence;
|
||||
for (var i = 1; i < listed; i++)
|
||||
{
|
||||
var value = incidence[baseIndex + i];
|
||||
var j = i - 1;
|
||||
while (j >= 0 && incidence[baseIndex + j] > value)
|
||||
{
|
||||
incidence[baseIndex + j + 1] = incidence[baseIndex + j];
|
||||
j--;
|
||||
}
|
||||
incidence[baseIndex + j + 1] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct TriangleColorPassShader(
|
||||
internal readonly partial struct TriangleMapShader(
|
||||
ReadWriteBuffer<int> assignment,
|
||||
ReadWriteBuffer<Float4> color,
|
||||
ReadWriteBuffer<Float2> sitePositions,
|
||||
ReadWriteBuffer<int> triangleVertices,
|
||||
ReadWriteBuffer<int> incidenceCounts,
|
||||
ReadWriteBuffer<int> incidence,
|
||||
ReadWriteBuffer<int> scratch,
|
||||
ReadWriteBuffer<int> accumulatorsA,
|
||||
ReadWriteBuffer<int> accumulatorsB,
|
||||
ReadWriteBuffer<int> triangleMap,
|
||||
int workingWidth,
|
||||
int workingHeight,
|
||||
int trimmedPass,
|
||||
float trimSigmaFactor,
|
||||
float alphaThreshold) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<int> assignment = assignment;
|
||||
@@ -957,14 +986,72 @@ internal readonly partial struct TriangleColorPassShader(
|
||||
private readonly ReadWriteBuffer<int> triangleVertices = triangleVertices;
|
||||
private readonly ReadWriteBuffer<int> incidenceCounts = incidenceCounts;
|
||||
private readonly ReadWriteBuffer<int> incidence = incidence;
|
||||
private readonly ReadWriteBuffer<int> scratch = scratch;
|
||||
private readonly ReadWriteBuffer<int> triangleMap = triangleMap;
|
||||
private readonly int workingWidth = workingWidth;
|
||||
private readonly int workingHeight = workingHeight;
|
||||
private readonly float alphaThreshold = alphaThreshold;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var x = ThreadIds.X;
|
||||
var y = ThreadIds.Y;
|
||||
if (x >= workingWidth || y >= workingHeight)
|
||||
return;
|
||||
|
||||
var index = y * workingWidth + x;
|
||||
if (color[index].W <= alphaThreshold)
|
||||
{
|
||||
triangleMap[index] = -1;
|
||||
return;
|
||||
}
|
||||
var site = assignment[index];
|
||||
if (site < 0)
|
||||
{
|
||||
triangleMap[index] = -1;
|
||||
return;
|
||||
}
|
||||
var px = x + 0.5f;
|
||||
var py = y + 0.5f;
|
||||
var listed = Hlsl.Min(incidenceCounts[site], LowPolyAbstractionSettings.MaxIncidence);
|
||||
var best = -1;
|
||||
for (var slot = 0; slot < listed; slot++)
|
||||
{
|
||||
var triangle = incidence[site * LowPolyAbstractionSettings.MaxIncidence + slot];
|
||||
if (best >= 0 && triangle >= best)
|
||||
continue;
|
||||
var a = sitePositions[triangleVertices[triangle * 3]];
|
||||
var b = sitePositions[triangleVertices[triangle * 3 + 1]];
|
||||
var c = sitePositions[triangleVertices[triangle * 3 + 2]];
|
||||
if (LowPolyAbstractionShaderMath.ContainsPoint(a, b, c, px, py))
|
||||
best = triangle;
|
||||
}
|
||||
triangleMap[index] = best;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct TriangleColorPassShader(
|
||||
ReadWriteBuffer<int> triangleMap,
|
||||
ReadWriteBuffer<Float4> color,
|
||||
ReadWriteBuffer<int> accumulatorsA,
|
||||
ReadWriteBuffer<int> accumulatorsB,
|
||||
int workingWidth,
|
||||
int workingHeight,
|
||||
int trimmedPass,
|
||||
float trimSigmaFactor) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<int> triangleMap = triangleMap;
|
||||
private readonly ReadWriteBuffer<Float4> color = color;
|
||||
private readonly ReadWriteBuffer<int> accumulatorsA = accumulatorsA;
|
||||
private readonly ReadWriteBuffer<int> accumulatorsB = accumulatorsB;
|
||||
private readonly int workingWidth = workingWidth;
|
||||
private readonly int workingHeight = workingHeight;
|
||||
private readonly int trimmedPass = trimmedPass;
|
||||
private readonly float trimSigmaFactor = trimSigmaFactor;
|
||||
private readonly float alphaThreshold = alphaThreshold;
|
||||
|
||||
private float ReconstructA(int index)
|
||||
=> accumulatorsA[index + 1] * 4294967296f + Hlsl.AsUInt(accumulatorsA[index]);
|
||||
|
||||
private void AddCarryA(int index, int value)
|
||||
{
|
||||
@@ -982,27 +1069,6 @@ internal readonly partial struct TriangleColorPassShader(
|
||||
Hlsl.InterlockedAdd(ref accumulatorsB[index + 1], 1);
|
||||
}
|
||||
|
||||
private float ReconstructA(int index)
|
||||
=> accumulatorsA[index + 1] * 4294967296f + Hlsl.AsUInt(accumulatorsA[index]);
|
||||
|
||||
private int FindTriangle(float px, float py, int site)
|
||||
{
|
||||
var listed = Hlsl.Min(incidenceCounts[site], LowPolyAbstractionSettings.MaxIncidence);
|
||||
var best = -1;
|
||||
for (var slot = 0; slot < listed; slot++)
|
||||
{
|
||||
var triangle = incidence[site * LowPolyAbstractionSettings.MaxIncidence + slot];
|
||||
if (best >= 0 && triangle >= best)
|
||||
continue;
|
||||
var a = sitePositions[triangleVertices[triangle * 3]];
|
||||
var b = sitePositions[triangleVertices[triangle * 3 + 1]];
|
||||
var c = sitePositions[triangleVertices[triangle * 3 + 2]];
|
||||
if (LowPolyAbstractionShaderMath.ContainsPoint(a, b, c, px, py))
|
||||
best = triangle;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var x = ThreadIds.X;
|
||||
@@ -1011,16 +1077,10 @@ internal readonly partial struct TriangleColorPassShader(
|
||||
return;
|
||||
|
||||
var index = y * workingWidth + x;
|
||||
var pixel = color[index];
|
||||
if (pixel.W <= alphaThreshold)
|
||||
return;
|
||||
var site = assignment[index];
|
||||
if (site < 0)
|
||||
return;
|
||||
var triangle = FindTriangle(x + 0.5f, y + 0.5f, site);
|
||||
var triangle = triangleMap[index];
|
||||
if (triangle < 0)
|
||||
return;
|
||||
|
||||
var pixel = color[index];
|
||||
var l = pixel.X * 0.299f + pixel.Y * 0.587f + pixel.Z * 0.114f;
|
||||
var lq = (int)(Hlsl.Saturate(l) * LowPolyAbstractionSettings.ColorScale + 0.5f);
|
||||
if (trimmedPass != 0)
|
||||
@@ -1065,7 +1125,8 @@ internal readonly partial struct FinalizeTrianglesShader(
|
||||
ReadWriteBuffer<int> scratch,
|
||||
ReadWriteBuffer<Float4> triangleColors,
|
||||
ReadWriteBuffer<float> triangleErrors,
|
||||
int triangleCapacity) : IComputeShader
|
||||
int triangleCapacity,
|
||||
int computeColors) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<int> accumulatorsA = accumulatorsA;
|
||||
private readonly ReadWriteBuffer<int> accumulatorsB = accumulatorsB;
|
||||
@@ -1073,6 +1134,7 @@ internal readonly partial struct FinalizeTrianglesShader(
|
||||
private readonly ReadWriteBuffer<Float4> triangleColors = triangleColors;
|
||||
private readonly ReadWriteBuffer<float> triangleErrors = triangleErrors;
|
||||
private readonly int triangleCapacity = triangleCapacity;
|
||||
private readonly int computeColors = computeColors;
|
||||
|
||||
private float ReconstructA(int index)
|
||||
=> accumulatorsA[index + 1] * 4294967296f + Hlsl.AsUInt(accumulatorsA[index]);
|
||||
@@ -1087,7 +1149,8 @@ internal readonly partial struct FinalizeTrianglesShader(
|
||||
return;
|
||||
if (triangle >= scratch[LowPolyAbstractionSettings.ScratchTriangleCount])
|
||||
{
|
||||
triangleColors[triangle] = new Float4(0f, 0f, 0f, 0f);
|
||||
if (computeColors != 0)
|
||||
triangleColors[triangle] = new Float4(0f, 0f, 0f, 0f);
|
||||
triangleErrors[triangle] = 0f;
|
||||
return;
|
||||
}
|
||||
@@ -1096,7 +1159,8 @@ internal readonly partial struct FinalizeTrianglesShader(
|
||||
var countA = ReconstructA(baseA);
|
||||
if (countA <= 0f)
|
||||
{
|
||||
triangleColors[triangle] = new Float4(0f, 0f, 0f, 0f);
|
||||
if (computeColors != 0)
|
||||
triangleColors[triangle] = new Float4(0f, 0f, 0f, 0f);
|
||||
triangleErrors[triangle] = 0f;
|
||||
return;
|
||||
}
|
||||
@@ -1104,6 +1168,8 @@ internal readonly partial struct FinalizeTrianglesShader(
|
||||
var meanL = ReconstructA(baseA + 10) * inverseScaleA;
|
||||
var meanL2 = ReconstructA(baseA + 12) / (countA * (float)LowPolyAbstractionSettings.ColorScale);
|
||||
triangleErrors[triangle] = Hlsl.Max(meanL2 - meanL * meanL, 0f);
|
||||
if (computeColors == 0)
|
||||
return;
|
||||
|
||||
var baseB = triangle * 10;
|
||||
var countB = ReconstructB(baseB);
|
||||
@@ -1295,6 +1361,7 @@ internal readonly partial struct RenderShader(
|
||||
ReadWriteBuffer<int> incidence,
|
||||
ReadWriteBuffer<Float4> triangleColors,
|
||||
ReadWriteBuffer<Float4> siteColors,
|
||||
ReadWriteBuffer<Float4> color,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
int rectOffsetX,
|
||||
int rectOffsetY,
|
||||
@@ -1317,6 +1384,7 @@ internal readonly partial struct RenderShader(
|
||||
private readonly ReadWriteBuffer<int> incidence = incidence;
|
||||
private readonly ReadWriteBuffer<Float4> triangleColors = triangleColors;
|
||||
private readonly ReadWriteBuffer<Float4> siteColors = siteColors;
|
||||
private readonly ReadWriteBuffer<Float4> color = color;
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> output = output;
|
||||
private readonly int rectOffsetX = rectOffsetX;
|
||||
private readonly int rectOffsetY = rectOffsetY;
|
||||
@@ -1350,6 +1418,21 @@ internal readonly partial struct RenderShader(
|
||||
return best;
|
||||
}
|
||||
|
||||
private float SourceAlpha(float x, float y)
|
||||
{
|
||||
var fx = Hlsl.Clamp(x - 0.5f, 0f, workingWidth - 1f);
|
||||
var fy = Hlsl.Clamp(y - 0.5f, 0f, workingHeight - 1f);
|
||||
var x0 = (int)fx;
|
||||
var y0 = (int)fy;
|
||||
var x1 = Hlsl.Min(x0 + 1, workingWidth - 1);
|
||||
var y1 = Hlsl.Min(y0 + 1, workingHeight - 1);
|
||||
var tx = fx - x0;
|
||||
var ty = fy - y0;
|
||||
var top = Hlsl.Lerp(color[y0 * workingWidth + x0].W, color[y0 * workingWidth + x1].W, tx);
|
||||
var bottom = Hlsl.Lerp(color[y1 * workingWidth + x0].W, color[y1 * workingWidth + x1].W, tx);
|
||||
return Hlsl.Saturate(Hlsl.Lerp(top, bottom, ty));
|
||||
}
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
if (ThreadIds.X >= rectWidth || ThreadIds.Y >= rectHeight)
|
||||
@@ -1416,6 +1499,7 @@ internal readonly partial struct RenderShader(
|
||||
straight *= 1f - wireframeStrength * 0.65f * line;
|
||||
}
|
||||
straight = Hlsl.Saturate(straight);
|
||||
alpha = Hlsl.Min(alpha, SourceAlpha(wxf, wyf));
|
||||
|
||||
var r = Hlsl.Min(straight.X * alpha, alpha);
|
||||
var g = Hlsl.Min(straight.Y * alpha, alpha);
|
||||
@@ -1482,6 +1566,10 @@ internal static class LowPolyAbstractionShaderMath
|
||||
|
||||
public static bool ContainsPoint(Float2 a, Float2 b, Float2 c, float px, float py)
|
||||
{
|
||||
var v0 = b - a;
|
||||
var v1 = c - a;
|
||||
if (Hlsl.Abs(v0.X * v1.Y - v0.Y * v1.X) < 1e-6f)
|
||||
return false;
|
||||
var bary = Barycentric(a, b, c, px, py);
|
||||
return bary.X >= -1e-4f && bary.Y >= -1e-4f && bary.Z >= -1e-4f;
|
||||
}
|
||||
|
||||
@@ -1,35 +1,15 @@
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp;
|
||||
using ComputeWeave;
|
||||
|
||||
namespace LowPolyAbstraction;
|
||||
|
||||
internal sealed class LowPolyAbstractionPipeline : IDisposable
|
||||
{
|
||||
private readonly GraphicsDevice _device;
|
||||
private readonly LowPolyAbstractionPipelineHost _host;
|
||||
private readonly ReadWriteBuffer<int> _scratch;
|
||||
private readonly ReadBackBuffer<int> _scratchReadBack;
|
||||
private ReadWriteBuffer<Float4>? _color;
|
||||
private ReadWriteBuffer<float>? _luma;
|
||||
private ReadWriteBuffer<float>? _edgeMagnitude;
|
||||
private ReadWriteBuffer<float>? _weight;
|
||||
private ReadWriteBuffer<int>? _jumpFloodA;
|
||||
private ReadWriteBuffer<int>? _jumpFloodB;
|
||||
private ReadWriteBuffer<int>? _assignment;
|
||||
private ReadWriteBuffer<int>? _counts;
|
||||
private ReadWriteBuffer<int>? _blockSums;
|
||||
private ReadWriteBuffer<int>? _cellBest;
|
||||
private ReadWriteBuffer<Float2>? _sitePositions;
|
||||
private ReadWriteBuffer<int>? _siteKinds;
|
||||
private ReadWriteBuffer<int>? _siteAccumulators;
|
||||
private ReadWriteBuffer<int>? _siteColorAccumulators;
|
||||
private ReadWriteBuffer<Float4>? _siteColors;
|
||||
private ReadWriteBuffer<int>? _incidenceCounts;
|
||||
private ReadWriteBuffer<int>? _incidence;
|
||||
private ReadWriteBuffer<int>? _triangleVertices;
|
||||
private ReadWriteBuffer<int>? _triangleAccumulatorsA;
|
||||
private ReadWriteBuffer<int>? _triangleAccumulatorsB;
|
||||
private ReadWriteBuffer<Float4>? _triangleColors;
|
||||
private ReadWriteBuffer<float>? _triangleErrors;
|
||||
private StructureKey? _structureKey;
|
||||
private int _workingWidth;
|
||||
private int _workingHeight;
|
||||
@@ -44,9 +24,10 @@ internal sealed class LowPolyAbstractionPipeline : IDisposable
|
||||
private int _packedWidth;
|
||||
private int _packedHeight;
|
||||
|
||||
private LowPolyAbstractionPipeline(GraphicsDevice device)
|
||||
private LowPolyAbstractionPipeline(GraphicsDevice device, LowPolyAbstractionPipelineHost host)
|
||||
{
|
||||
_device = device;
|
||||
_host = host;
|
||||
_scratch = device.AllocateReadWriteBuffer<int>(LowPolyAbstractionSettings.ScratchLength);
|
||||
_scratchReadBack = device.AllocateReadBackBuffer<int>(LowPolyAbstractionSettings.ScratchLength);
|
||||
}
|
||||
@@ -55,7 +36,7 @@ internal sealed class LowPolyAbstractionPipeline : IDisposable
|
||||
{
|
||||
try
|
||||
{
|
||||
return new LowPolyAbstractionPipeline(GraphicsDevice.GetDefault());
|
||||
return TryCreate(GraphicsDevice.GetDefault());
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -65,14 +46,23 @@ internal sealed class LowPolyAbstractionPipeline : IDisposable
|
||||
|
||||
public static LowPolyAbstractionPipeline? TryCreate(GraphicsDevice device)
|
||||
{
|
||||
LowPolyAbstractionPipelineHost? host = null;
|
||||
try
|
||||
{
|
||||
return new LowPolyAbstractionPipeline(device);
|
||||
host = LowPolyAbstractionPipelineHost.Create(device, LowPolyAbstractionSettings.MaximumPendingSubmissions);
|
||||
var pipeline = new LowPolyAbstractionPipeline(device, host);
|
||||
host = null;
|
||||
return pipeline;
|
||||
}
|
||||
catch
|
||||
catch (Win32Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
host?.Dispose();
|
||||
host?.WaitForDisposal();
|
||||
}
|
||||
}
|
||||
|
||||
internal void WaitForCompletion()
|
||||
@@ -88,8 +78,7 @@ internal sealed class LowPolyAbstractionPipeline : 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]));
|
||||
}
|
||||
|
||||
@@ -101,9 +90,7 @@ internal sealed class LowPolyAbstractionPipeline : 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(
|
||||
@@ -114,8 +101,7 @@ internal sealed class LowPolyAbstractionPipeline : 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(
|
||||
@@ -127,11 +113,35 @@ internal sealed class LowPolyAbstractionPipeline : IDisposable
|
||||
int sourceWidth,
|
||||
int sourceHeight,
|
||||
in Parameters parameters)
|
||||
{
|
||||
var derived = BeginSimulate(canvasWidth, canvasHeight, in parameters);
|
||||
_host.RecordAnalyze(source, _scratch, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, 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.RecordSharedAnalyze(source, _scratch, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, 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())
|
||||
RecordAnalyzeStage(in context, source, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, in derived);
|
||||
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;
|
||||
_cachedMinX = hashed[LowPolyAbstractionSettings.ScratchBoundsMinX];
|
||||
@@ -152,10 +162,7 @@ internal sealed class LowPolyAbstractionPipeline : IDisposable
|
||||
return false;
|
||||
|
||||
if (_cachedMinX <= _cachedMaxX && _cachedMinY <= _cachedMaxY)
|
||||
{
|
||||
using ComputeContext context = _device.CreateComputeContext();
|
||||
RecordStructureStage(in context, in derived, in parameters);
|
||||
}
|
||||
_host.RecordStructure(_scratch, _siteCapacity, in derived, in parameters).Wait();
|
||||
_hasStructure = _cachedMinX <= _cachedMaxX && _cachedMinY <= _cachedMaxY;
|
||||
_structureKey = key;
|
||||
return true;
|
||||
@@ -182,24 +189,28 @@ internal sealed class LowPolyAbstractionPipeline : IDisposable
|
||||
}
|
||||
|
||||
internal void RenderVisible(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
int canvasWidth,
|
||||
int canvasHeight,
|
||||
int sourceOffsetX,
|
||||
int sourceOffsetY,
|
||||
int sourceWidth,
|
||||
int sourceHeight,
|
||||
PixelRect rect,
|
||||
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, 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, in derived, in parameters).Wait();
|
||||
}
|
||||
|
||||
private ComputeSubmission SubmitFullPipeline(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
int width,
|
||||
@@ -208,247 +219,11 @@ internal sealed class LowPolyAbstractionPipeline : IDisposable
|
||||
{
|
||||
_structureKey = null;
|
||||
var derived = Derive(width, height, in parameters);
|
||||
RecordAnalyzeStage(in context, source, 0, 0, width, height, in derived);
|
||||
RecordStructureStage(in context, in derived, in parameters);
|
||||
var submission = _host.RecordFullPipeline(source, output, _scratch, width, height, _siteCapacity, in derived, in parameters);
|
||||
_hasStructure = true;
|
||||
RecordRenderStage(in context, output, new PixelRect(0, 0, width, height), in derived, in parameters);
|
||||
return submission;
|
||||
}
|
||||
|
||||
private void RecordAnalyzeStage(
|
||||
in ComputeContext context,
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
int sourceOffsetX,
|
||||
int sourceOffsetY,
|
||||
int sourceWidth,
|
||||
int sourceHeight,
|
||||
in DerivedValues derived)
|
||||
{
|
||||
context.For(1, new InitScratchShader(_scratch));
|
||||
context.Barrier(_scratch);
|
||||
context.For(derived.WorkingWidth, derived.WorkingHeight, new AnalyzeShader(
|
||||
source, _color!, _luma!, _scratch,
|
||||
sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight,
|
||||
derived.WorkingWidth, derived.WorkingHeight, derived.Scale,
|
||||
LowPolyAbstractionSettings.AlphaThreshold));
|
||||
context.Barrier(_color!);
|
||||
context.Barrier(_luma!);
|
||||
context.Barrier(_scratch);
|
||||
}
|
||||
|
||||
private void RecordStructureStage(
|
||||
in ComputeContext context,
|
||||
in DerivedValues derived,
|
||||
in Parameters parameters)
|
||||
{
|
||||
var workingWidth = derived.WorkingWidth;
|
||||
var workingHeight = derived.WorkingHeight;
|
||||
var pixelCount = workingWidth * workingHeight;
|
||||
|
||||
context.For(workingWidth, workingHeight, new EdgeShader(_luma!, _color!, _edgeMagnitude!, workingWidth, workingHeight));
|
||||
context.Barrier(_edgeMagnitude!);
|
||||
|
||||
context.For(workingWidth, workingHeight, new EdgeDistanceSeedShader(
|
||||
_edgeMagnitude!, _jumpFloodA!, workingWidth, workingHeight, LowPolyAbstractionSettings.EdgeThreshold));
|
||||
context.Barrier(_jumpFloodA!);
|
||||
var reading = _jumpFloodA!;
|
||||
var writing = _jumpFloodB!;
|
||||
for (var stepSize = derived.JumpFloodInitialStep; stepSize >= 1; stepSize >>= 1)
|
||||
{
|
||||
context.For(workingWidth, workingHeight, new JumpFloodPixelPassShader(reading, writing, workingWidth, workingHeight, stepSize));
|
||||
context.Barrier(writing);
|
||||
(reading, writing) = (writing, reading);
|
||||
}
|
||||
context.For(workingWidth, workingHeight, new WeightShader(
|
||||
reading, _color!, _weight!, workingWidth, workingHeight,
|
||||
derived.LaneWidth, parameters.Fidelity, LowPolyAbstractionSettings.AlphaThreshold));
|
||||
context.Barrier(_weight!);
|
||||
|
||||
var edgeCellCount = derived.EdgeCellCols * derived.EdgeCellRows;
|
||||
context.For(edgeCellCount, new FillIntShader(_cellBest!, edgeCellCount, -1));
|
||||
context.Barrier(_cellBest!);
|
||||
context.For(workingWidth, workingHeight, new EdgeBestShader(
|
||||
_edgeMagnitude!, _color!, _cellBest!, workingWidth, workingHeight,
|
||||
derived.EdgeCellCols, derived.EdgeSpacing, LowPolyAbstractionSettings.EdgeThreshold,
|
||||
LowPolyAbstractionSettings.AlphaThreshold));
|
||||
context.Barrier(_cellBest!);
|
||||
context.For(edgeCellCount, new CellCountShader(_cellBest!, _counts!, edgeCellCount));
|
||||
context.Barrier(_counts!);
|
||||
RecordScan(in context, edgeCellCount, derived.EdgeBudget, 0, LowPolyAbstractionSettings.ScratchPendingCount);
|
||||
context.For(BlockCount(edgeCellCount), new EdgeEmitShader(
|
||||
_cellBest!, _blockSums!, _scratch, _sitePositions!, _siteKinds!,
|
||||
edgeCellCount, BlockCount(edgeCellCount), derived.EdgeCellCols, derived.EdgeSpacing));
|
||||
context.Barrier(_sitePositions!);
|
||||
context.Barrier(_siteKinds!);
|
||||
context.For(1, new CommitSitesShader(_scratch));
|
||||
context.Barrier(_scratch);
|
||||
|
||||
var interiorCellCount = derived.InteriorCellCols * derived.InteriorCellRows;
|
||||
context.For(interiorCellCount, new InteriorCountShader(
|
||||
_color!, _counts!, workingWidth, workingHeight,
|
||||
derived.InteriorCellCols, interiorCellCount, derived.InteriorSpacing,
|
||||
parameters.Seed, LowPolyAbstractionSettings.AlphaThreshold));
|
||||
context.Barrier(_counts!);
|
||||
RecordScan(in context, interiorCellCount, derived.TargetSites, 1, LowPolyAbstractionSettings.ScratchPendingCount);
|
||||
context.For(BlockCount(interiorCellCount), new InteriorEmitShader(
|
||||
_counts!, _blockSums!, _scratch, _sitePositions!, _siteKinds!,
|
||||
interiorCellCount, BlockCount(interiorCellCount), derived.InteriorCellCols, derived.InteriorSpacing,
|
||||
parameters.Seed));
|
||||
context.Barrier(_sitePositions!);
|
||||
context.Barrier(_siteKinds!);
|
||||
context.For(1, new CommitSitesShader(_scratch));
|
||||
context.Barrier(_scratch);
|
||||
|
||||
RecordLloydIterations(in context, in derived, derived.CvtIterations);
|
||||
RecordVoronoi(in context, in derived);
|
||||
RecordTriangulation(in context, in derived, pixelCount);
|
||||
RecordTriangleColors(in context, in derived);
|
||||
|
||||
for (var pass = 0; pass < derived.RefinePasses; pass++)
|
||||
{
|
||||
context.For(derived.TriangleCapacity, new RefineCountShader(
|
||||
_triangleErrors!, _scratch, _counts!, derived.TriangleCapacity, derived.ErrorThreshold));
|
||||
context.Barrier(_counts!);
|
||||
RecordScan(in context, derived.TriangleCapacity, derived.RefineSiteLimit, 1, LowPolyAbstractionSettings.ScratchPendingCount);
|
||||
context.For(BlockCount(derived.TriangleCapacity), new RefineEmitShader(
|
||||
_counts!, _blockSums!, _scratch, _triangleVertices!, _sitePositions!, _siteKinds!,
|
||||
derived.TriangleCapacity, BlockCount(derived.TriangleCapacity)));
|
||||
context.Barrier(_sitePositions!);
|
||||
context.Barrier(_siteKinds!);
|
||||
context.For(1, new CommitSitesShader(_scratch));
|
||||
context.Barrier(_scratch);
|
||||
|
||||
RecordLloydIterations(in context, in derived, LowPolyAbstractionSettings.PostInsertLloydIterations);
|
||||
RecordVoronoi(in context, in derived);
|
||||
RecordTriangulation(in context, in derived, pixelCount);
|
||||
RecordTriangleColors(in context, in derived);
|
||||
}
|
||||
|
||||
var siteColorLength = _siteCapacity * 10;
|
||||
context.For(siteColorLength, new FillIntShader(_siteColorAccumulators!, siteColorLength, 0));
|
||||
context.Barrier(_siteColorAccumulators!);
|
||||
context.For(workingWidth, workingHeight, new SiteColorAccumulateShader(
|
||||
_assignment!, _color!, _siteColorAccumulators!, workingWidth, workingHeight,
|
||||
LowPolyAbstractionSettings.AlphaThreshold));
|
||||
context.Barrier(_siteColorAccumulators!);
|
||||
context.For(_siteCapacity, new SiteColorFinalizeShader(_siteColorAccumulators!, _siteColors!, _siteCapacity));
|
||||
context.Barrier(_siteColors!);
|
||||
}
|
||||
|
||||
private void RecordLloydIterations(in ComputeContext context, in DerivedValues derived, int iterations)
|
||||
{
|
||||
var accumulatorLength = _siteCapacity * 6;
|
||||
for (var iteration = 0; iteration < iterations; iteration++)
|
||||
{
|
||||
RecordVoronoi(in context, in derived);
|
||||
context.For(accumulatorLength, new FillIntShader(_siteAccumulators!, accumulatorLength, 0));
|
||||
context.Barrier(_siteAccumulators!);
|
||||
context.For(derived.WorkingWidth, derived.WorkingHeight, new CentroidAccumulateShader(
|
||||
_assignment!, _weight!, _siteAccumulators!, derived.WorkingWidth, derived.WorkingHeight));
|
||||
context.Barrier(_siteAccumulators!);
|
||||
context.For(_siteCapacity, new UpdateSitesShader(
|
||||
_sitePositions!, _siteKinds!, _siteAccumulators!, _scratch,
|
||||
derived.WorkingWidth, derived.WorkingHeight, _siteCapacity));
|
||||
context.Barrier(_sitePositions!);
|
||||
}
|
||||
}
|
||||
|
||||
private void RecordVoronoi(in ComputeContext context, in DerivedValues derived)
|
||||
{
|
||||
var workingWidth = derived.WorkingWidth;
|
||||
var workingHeight = derived.WorkingHeight;
|
||||
context.For(workingWidth, workingHeight, new VoronoiClearShader(_jumpFloodA!, workingWidth, workingHeight));
|
||||
context.Barrier(_jumpFloodA!);
|
||||
context.For(_siteCapacity, new VoronoiScatterShader(
|
||||
_sitePositions!, _scratch, _jumpFloodA!, workingWidth, workingHeight, _siteCapacity));
|
||||
context.Barrier(_jumpFloodA!);
|
||||
var reading = _jumpFloodA!;
|
||||
var writing = _jumpFloodB!;
|
||||
for (var stepSize = derived.JumpFloodInitialStep; stepSize >= 1; stepSize >>= 1)
|
||||
{
|
||||
context.For(workingWidth, workingHeight, new JumpFloodSitePassShader(
|
||||
reading, writing, _sitePositions!, workingWidth, workingHeight, stepSize));
|
||||
context.Barrier(writing);
|
||||
(reading, writing) = (writing, reading);
|
||||
}
|
||||
_assignment = reading;
|
||||
}
|
||||
|
||||
private void RecordTriangulation(in ComputeContext context, in DerivedValues derived, int pixelCount)
|
||||
{
|
||||
context.For(derived.WorkingWidth, derived.WorkingHeight, new CornerCountShader(
|
||||
_assignment!, _counts!, derived.WorkingWidth, derived.WorkingHeight));
|
||||
context.Barrier(_counts!);
|
||||
RecordScan(in context, pixelCount, derived.TriangleCapacity, 0, LowPolyAbstractionSettings.ScratchTriangleCount);
|
||||
context.For(BlockCount(pixelCount), new TriangleEmitShader(
|
||||
_assignment!, _counts!, _blockSums!, _scratch, _triangleVertices!,
|
||||
derived.WorkingWidth, derived.WorkingHeight, BlockCount(pixelCount)));
|
||||
context.Barrier(_triangleVertices!);
|
||||
context.For(_siteCapacity, new FillIntShader(_incidenceCounts!, _siteCapacity, 0));
|
||||
context.Barrier(_incidenceCounts!);
|
||||
context.For(derived.TriangleCapacity, new IncidenceBuildShader(
|
||||
_triangleVertices!, _incidenceCounts!, _incidence!, _scratch, derived.TriangleCapacity));
|
||||
context.Barrier(_incidenceCounts!);
|
||||
context.Barrier(_incidence!);
|
||||
}
|
||||
|
||||
private void RecordTriangleColors(in ComputeContext context, in DerivedValues derived)
|
||||
{
|
||||
var lengthA = derived.TriangleCapacity * 14;
|
||||
var lengthB = derived.TriangleCapacity * 10;
|
||||
context.For(lengthA, new FillIntShader(_triangleAccumulatorsA!, lengthA, 0));
|
||||
context.Barrier(_triangleAccumulatorsA!);
|
||||
context.For(derived.WorkingWidth, derived.WorkingHeight, new TriangleColorPassShader(
|
||||
_assignment!, _color!, _sitePositions!, _triangleVertices!, _incidenceCounts!, _incidence!, _scratch,
|
||||
_triangleAccumulatorsA!, _triangleAccumulatorsB!, derived.WorkingWidth, derived.WorkingHeight,
|
||||
0, LowPolyAbstractionSettings.TrimSigmaFactor, LowPolyAbstractionSettings.AlphaThreshold));
|
||||
context.Barrier(_triangleAccumulatorsA!);
|
||||
context.For(lengthB, new FillIntShader(_triangleAccumulatorsB!, lengthB, 0));
|
||||
context.Barrier(_triangleAccumulatorsB!);
|
||||
context.For(derived.WorkingWidth, derived.WorkingHeight, new TriangleColorPassShader(
|
||||
_assignment!, _color!, _sitePositions!, _triangleVertices!, _incidenceCounts!, _incidence!, _scratch,
|
||||
_triangleAccumulatorsA!, _triangleAccumulatorsB!, derived.WorkingWidth, derived.WorkingHeight,
|
||||
1, LowPolyAbstractionSettings.TrimSigmaFactor, LowPolyAbstractionSettings.AlphaThreshold));
|
||||
context.Barrier(_triangleAccumulatorsB!);
|
||||
context.For(derived.TriangleCapacity, new FinalizeTrianglesShader(
|
||||
_triangleAccumulatorsA!, _triangleAccumulatorsB!, _scratch, _triangleColors!, _triangleErrors!,
|
||||
derived.TriangleCapacity));
|
||||
context.Barrier(_triangleColors!);
|
||||
context.Barrier(_triangleErrors!);
|
||||
}
|
||||
|
||||
private void RecordScan(in ComputeContext context, int elementCount, int capLimit, int subtractSiteCount, int outputSlot)
|
||||
{
|
||||
var blocks = BlockCount(elementCount);
|
||||
context.For(blocks, new BlockCountShader(_counts!, _blockSums!, elementCount, blocks));
|
||||
context.Barrier(_blockSums!);
|
||||
context.For(1, new BlockPrefixShader(_blockSums!, _scratch, blocks, capLimit, subtractSiteCount, outputSlot));
|
||||
context.Barrier(_blockSums!);
|
||||
context.Barrier(_scratch);
|
||||
}
|
||||
|
||||
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(
|
||||
_assignment!, _sitePositions!, _triangleVertices!, _incidenceCounts!, _incidence!,
|
||||
_triangleColors!, _siteColors!, output,
|
||||
rect.X, rect.Y, rect.Width, rect.Height,
|
||||
derived.WorkingWidth, derived.WorkingHeight, derived.Scale,
|
||||
Math.Clamp(parameters.Gradient, 0f, 1f),
|
||||
Math.Clamp(parameters.Wireframe, 0f, 1f) * LowPolyAbstractionSettings.MaximumWireframeWidth,
|
||||
Math.Clamp(parameters.Wireframe, 0f, 1f) > 0f ? 1f : 0f,
|
||||
Math.Clamp(parameters.Saturation, 0f, 1f),
|
||||
Math.Clamp(parameters.Jitter, 0f, 1f),
|
||||
parameters.Seed));
|
||||
}
|
||||
|
||||
private static int BlockCount(int elementCount)
|
||||
=> (elementCount + LowPolyAbstractionSettings.ScanBlockSize - 1) / LowPolyAbstractionSettings.ScanBlockSize;
|
||||
|
||||
private DerivedValues Derive(int width, int height, in Parameters parameters)
|
||||
{
|
||||
var settings = LowPolyAbstractionSettings.GetQuality(parameters.Quality);
|
||||
@@ -494,38 +269,43 @@ internal sealed class LowPolyAbstractionPipeline : IDisposable
|
||||
if (_workingWidth == workingWidth && _workingHeight == workingHeight && _siteCapacity == siteCapacity)
|
||||
return;
|
||||
|
||||
DisposeGridBuffers();
|
||||
_structureKey = null;
|
||||
_hasStructure = false;
|
||||
_workingWidth = 0;
|
||||
_workingHeight = 0;
|
||||
_siteCapacity = 0;
|
||||
var pixelCount = workingWidth * workingHeight;
|
||||
var triangleCapacity = LowPolyAbstractionSettings.GetTriangleCapacity(siteCapacity);
|
||||
var scanLength = Math.Max((workingWidth + 1) * (workingHeight + 1), triangleCapacity);
|
||||
var cellBestLength = (workingWidth / 2 + 1) * (workingHeight / 2 + 1);
|
||||
_color = _device.AllocateReadWriteBuffer<Float4>(pixelCount);
|
||||
_luma = _device.AllocateReadWriteBuffer<float>(pixelCount);
|
||||
_edgeMagnitude = _device.AllocateReadWriteBuffer<float>(pixelCount);
|
||||
_weight = _device.AllocateReadWriteBuffer<float>(pixelCount);
|
||||
_jumpFloodA = _device.AllocateReadWriteBuffer<int>(pixelCount);
|
||||
_jumpFloodB = _device.AllocateReadWriteBuffer<int>(pixelCount);
|
||||
_counts = _device.AllocateReadWriteBuffer<int>(scanLength);
|
||||
_blockSums = _device.AllocateReadWriteBuffer<int>(BlockCount(scanLength) + 1);
|
||||
_cellBest = _device.AllocateReadWriteBuffer<int>(cellBestLength);
|
||||
_sitePositions = _device.AllocateReadWriteBuffer<Float2>(siteCapacity);
|
||||
_siteKinds = _device.AllocateReadWriteBuffer<int>(siteCapacity);
|
||||
_siteAccumulators = _device.AllocateReadWriteBuffer<int>(siteCapacity * 6);
|
||||
_siteColorAccumulators = _device.AllocateReadWriteBuffer<int>(siteCapacity * 10);
|
||||
_siteColors = _device.AllocateReadWriteBuffer<Float4>(siteCapacity);
|
||||
_incidenceCounts = _device.AllocateReadWriteBuffer<int>(siteCapacity);
|
||||
_incidence = _device.AllocateReadWriteBuffer<int>(siteCapacity * LowPolyAbstractionSettings.MaxIncidence);
|
||||
_triangleVertices = _device.AllocateReadWriteBuffer<int>(triangleCapacity * 3);
|
||||
_triangleAccumulatorsA = _device.AllocateReadWriteBuffer<int>(triangleCapacity * 14);
|
||||
_triangleAccumulatorsB = _device.AllocateReadWriteBuffer<int>(triangleCapacity * 10);
|
||||
_triangleColors = _device.AllocateReadWriteBuffer<Float4>(triangleCapacity);
|
||||
_triangleErrors = _device.AllocateReadWriteBuffer<float>(triangleCapacity);
|
||||
_assignment = null;
|
||||
if (!_host.TryEnsureGrid(
|
||||
new LowPolyAbstractionGridResources.Plan(
|
||||
blockSumsLength: LowPolyAbstractionPipelineHost.BlockCount(scanLength) + 1,
|
||||
cellBestLength: cellBestLength,
|
||||
colorLength: pixelCount,
|
||||
countsLength: scanLength,
|
||||
edgeMagnitudeLength: pixelCount,
|
||||
incidenceLength: siteCapacity * LowPolyAbstractionSettings.MaxIncidence,
|
||||
incidenceCountsLength: siteCapacity,
|
||||
jumpFloodALength: pixelCount,
|
||||
jumpFloodBLength: pixelCount,
|
||||
lumaLength: pixelCount,
|
||||
siteAccumulatorsLength: siteCapacity * 6,
|
||||
siteColorAccumulatorsLength: siteCapacity * 10,
|
||||
siteColorsLength: siteCapacity,
|
||||
siteKindsLength: siteCapacity,
|
||||
sitePositionsLength: siteCapacity,
|
||||
triangleAccumulatorsALength: triangleCapacity * 14,
|
||||
triangleAccumulatorsBLength: triangleCapacity * 10,
|
||||
triangleColorsLength: triangleCapacity,
|
||||
triangleErrorsLength: triangleCapacity,
|
||||
triangleVerticesLength: triangleCapacity * 3,
|
||||
weightLength: pixelCount),
|
||||
out _))
|
||||
throw new InvalidOperationException();
|
||||
_workingWidth = workingWidth;
|
||||
_workingHeight = workingHeight;
|
||||
_siteCapacity = siteCapacity;
|
||||
_structureKey = null;
|
||||
_hasStructure = false;
|
||||
}
|
||||
|
||||
private void EnsurePackedTextures(int width, int height)
|
||||
@@ -541,61 +321,10 @@ internal sealed class LowPolyAbstractionPipeline : IDisposable
|
||||
_packedHeight = height;
|
||||
}
|
||||
|
||||
private void DisposeGridBuffers()
|
||||
{
|
||||
_color?.Dispose();
|
||||
_luma?.Dispose();
|
||||
_edgeMagnitude?.Dispose();
|
||||
_weight?.Dispose();
|
||||
_jumpFloodA?.Dispose();
|
||||
_jumpFloodB?.Dispose();
|
||||
_counts?.Dispose();
|
||||
_blockSums?.Dispose();
|
||||
_cellBest?.Dispose();
|
||||
_sitePositions?.Dispose();
|
||||
_siteKinds?.Dispose();
|
||||
_siteAccumulators?.Dispose();
|
||||
_siteColorAccumulators?.Dispose();
|
||||
_siteColors?.Dispose();
|
||||
_incidenceCounts?.Dispose();
|
||||
_incidence?.Dispose();
|
||||
_triangleVertices?.Dispose();
|
||||
_triangleAccumulatorsA?.Dispose();
|
||||
_triangleAccumulatorsB?.Dispose();
|
||||
_triangleColors?.Dispose();
|
||||
_triangleErrors?.Dispose();
|
||||
_color = null;
|
||||
_luma = null;
|
||||
_edgeMagnitude = null;
|
||||
_weight = null;
|
||||
_jumpFloodA = null;
|
||||
_jumpFloodB = null;
|
||||
_assignment = null;
|
||||
_counts = null;
|
||||
_blockSums = null;
|
||||
_cellBest = null;
|
||||
_sitePositions = null;
|
||||
_siteKinds = null;
|
||||
_siteAccumulators = null;
|
||||
_siteColorAccumulators = null;
|
||||
_siteColors = null;
|
||||
_incidenceCounts = null;
|
||||
_incidence = null;
|
||||
_triangleVertices = null;
|
||||
_triangleAccumulatorsA = null;
|
||||
_triangleAccumulatorsB = null;
|
||||
_triangleColors = null;
|
||||
_triangleErrors = null;
|
||||
_structureKey = null;
|
||||
_hasStructure = false;
|
||||
_workingWidth = 0;
|
||||
_workingHeight = 0;
|
||||
_siteCapacity = 0;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
DisposeGridBuffers();
|
||||
_host.Dispose();
|
||||
_host.WaitForDisposal();
|
||||
_packedSource?.Dispose();
|
||||
_packedOutput?.Dispose();
|
||||
_packedSource = null;
|
||||
@@ -619,7 +348,7 @@ internal sealed class LowPolyAbstractionPipeline : IDisposable
|
||||
float Fidelity,
|
||||
float Refine);
|
||||
|
||||
private readonly record struct DerivedValues(
|
||||
internal readonly record struct DerivedValues(
|
||||
int WorkingWidth,
|
||||
int WorkingHeight,
|
||||
float Scale,
|
||||
|
||||
@@ -0,0 +1,463 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace LowPolyAbstraction;
|
||||
|
||||
[ComputeResourceGroup]
|
||||
internal sealed partial class LowPolyAbstractionGridResources
|
||||
{
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<Float4> Color { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<float> Luma { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<float> EdgeMagnitude { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<float> Weight { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<int> JumpFloodA { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<int> JumpFloodB { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<int> Counts { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<int> BlockSums { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<int> CellBest { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<Float2> SitePositions { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<int> SiteKinds { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<int> SiteAccumulators { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<int> SiteColorAccumulators { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<Float4> SiteColors { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<int> IncidenceCounts { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<int> Incidence { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<int> TriangleVertices { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<int> TriangleAccumulatorsA { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<int> TriangleAccumulatorsB { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<Float4> TriangleColors { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<float> TriangleErrors { get; }
|
||||
}
|
||||
|
||||
[ComputePipelineHost("_device", 1)]
|
||||
internal sealed partial class LowPolyAbstractionPipelineHost
|
||||
{
|
||||
private readonly GraphicsDevice _device;
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite, ComputeResourceRecovery.Recompute)]
|
||||
private readonly ComputeResourceGroupSlot<LowPolyAbstractionGridResources> _grid = new();
|
||||
|
||||
internal static int BlockCount(int elementCount)
|
||||
=> (elementCount + LowPolyAbstractionSettings.ScanBlockSize - 1) / LowPolyAbstractionSettings.ScanBlockSize;
|
||||
|
||||
[ComputePipeline]
|
||||
private void RecordFullPipeline(
|
||||
in ComputeContext context,
|
||||
[ComputeOwnedResource(nameof(_grid))] LowPolyAbstractionGridResources 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 siteCapacity,
|
||||
in LowPolyAbstractionPipeline.DerivedValues derived,
|
||||
in LowPolyAbstractionPipeline.Parameters parameters)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordAnalyzeStage(in context, grid, source, scratch, 0, 0, width, height, in derived);
|
||||
RecordStructureStage(in context, grid, scratch, siteCapacity, in derived, in parameters);
|
||||
RecordRenderStage(in context, grid, output, new LowPolyAbstractionPipeline.PixelRect(0, 0, width, height), in derived, in parameters);
|
||||
}
|
||||
|
||||
[ComputePipeline]
|
||||
private void RecordAnalyze(
|
||||
in ComputeContext context,
|
||||
[ComputeOwnedResource(nameof(_grid))] LowPolyAbstractionGridResources grid,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
|
||||
int sourceOffsetX,
|
||||
int sourceOffsetY,
|
||||
int sourceWidth,
|
||||
int sourceHeight,
|
||||
in LowPolyAbstractionPipeline.DerivedValues derived)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordAnalyzeStage(in context, grid, source, scratch, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, in derived);
|
||||
}
|
||||
|
||||
[ComputePipeline]
|
||||
[ComputeInterop]
|
||||
private void RecordSharedAnalyze(
|
||||
in ComputeContext context,
|
||||
[ComputeOwnedResource(nameof(_grid))] LowPolyAbstractionGridResources 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,
|
||||
in LowPolyAbstractionPipeline.DerivedValues derived)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordAnalyzeStage(in context, grid, source, scratch, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, in derived);
|
||||
}
|
||||
|
||||
[ComputePipeline]
|
||||
[ComputeInterop]
|
||||
private void RecordSharedRender(
|
||||
in ComputeContext context,
|
||||
[ComputeOwnedResource(nameof(_grid))] LowPolyAbstractionGridResources grid,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
in LowPolyAbstractionPipeline.PixelRect rect,
|
||||
in LowPolyAbstractionPipeline.DerivedValues derived,
|
||||
in LowPolyAbstractionPipeline.Parameters parameters)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordRenderStage(in context, grid, output, rect, in derived, in parameters);
|
||||
}
|
||||
|
||||
[ComputePipeline]
|
||||
private void RecordStructure(
|
||||
in ComputeContext context,
|
||||
[ComputeOwnedResource(nameof(_grid))] LowPolyAbstractionGridResources grid,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
|
||||
int siteCapacity,
|
||||
in LowPolyAbstractionPipeline.DerivedValues derived,
|
||||
in LowPolyAbstractionPipeline.Parameters parameters)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordStructureStage(in context, grid, scratch, siteCapacity, in derived, in parameters);
|
||||
}
|
||||
|
||||
[ComputePipeline]
|
||||
private void RecordRender(
|
||||
in ComputeContext context,
|
||||
[ComputeOwnedResource(nameof(_grid))] LowPolyAbstractionGridResources grid,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
in LowPolyAbstractionPipeline.PixelRect rect,
|
||||
in LowPolyAbstractionPipeline.DerivedValues derived,
|
||||
in LowPolyAbstractionPipeline.Parameters parameters)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordRenderStage(in context, grid, output, rect, in derived, in parameters);
|
||||
}
|
||||
|
||||
private static void RecordAnalyzeStage(
|
||||
in ComputeContext context,
|
||||
LowPolyAbstractionGridResources grid,
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteBuffer<int> scratch,
|
||||
int sourceOffsetX,
|
||||
int sourceOffsetY,
|
||||
int sourceWidth,
|
||||
int sourceHeight,
|
||||
in LowPolyAbstractionPipeline.DerivedValues derived)
|
||||
{
|
||||
context.For(1, new InitScratchShader(scratch));
|
||||
context.Barrier(scratch);
|
||||
context.For(derived.WorkingWidth, derived.WorkingHeight, new AnalyzeShader(
|
||||
source, grid.Color, grid.Luma, scratch,
|
||||
sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight,
|
||||
derived.WorkingWidth, derived.WorkingHeight, derived.Scale,
|
||||
LowPolyAbstractionSettings.AlphaThreshold));
|
||||
context.Barrier(grid.Color);
|
||||
context.Barrier(grid.Luma);
|
||||
context.Barrier(scratch);
|
||||
}
|
||||
|
||||
private static void RecordStructureStage(
|
||||
in ComputeContext context,
|
||||
LowPolyAbstractionGridResources grid,
|
||||
ReadWriteBuffer<int> scratch,
|
||||
int siteCapacity,
|
||||
in LowPolyAbstractionPipeline.DerivedValues derived,
|
||||
in LowPolyAbstractionPipeline.Parameters parameters)
|
||||
{
|
||||
var workingWidth = derived.WorkingWidth;
|
||||
var workingHeight = derived.WorkingHeight;
|
||||
var pixelCount = workingWidth * workingHeight;
|
||||
|
||||
context.For(workingWidth, workingHeight, new EdgeShader(grid.Luma, grid.EdgeMagnitude, workingWidth, workingHeight));
|
||||
context.Barrier(grid.EdgeMagnitude);
|
||||
|
||||
context.For(workingWidth, workingHeight, new EdgeDistanceSeedShader(
|
||||
grid.EdgeMagnitude, grid.JumpFloodA, workingWidth, workingHeight, LowPolyAbstractionSettings.EdgeThreshold));
|
||||
context.Barrier(grid.JumpFloodA);
|
||||
var reading = grid.JumpFloodA;
|
||||
var writing = grid.JumpFloodB;
|
||||
for (var stepSize = derived.JumpFloodInitialStep; stepSize >= 1; stepSize >>= 1)
|
||||
{
|
||||
context.For(workingWidth, workingHeight, new JumpFloodPixelPassShader(reading, writing, workingWidth, workingHeight, stepSize));
|
||||
context.Barrier(writing);
|
||||
(reading, writing) = (writing, reading);
|
||||
}
|
||||
context.For(workingWidth, workingHeight, new WeightShader(
|
||||
reading, grid.Color, grid.Weight, workingWidth, workingHeight,
|
||||
derived.LaneWidth, parameters.Fidelity, LowPolyAbstractionSettings.AlphaThreshold));
|
||||
context.Barrier(grid.Weight);
|
||||
|
||||
var edgeCellCount = derived.EdgeCellCols * derived.EdgeCellRows;
|
||||
context.For(edgeCellCount, new FillIntShader(grid.CellBest, edgeCellCount, -1));
|
||||
context.Barrier(grid.CellBest);
|
||||
context.For(workingWidth, workingHeight, new EdgeBestShader(
|
||||
grid.EdgeMagnitude, grid.Color, grid.CellBest, workingWidth, workingHeight,
|
||||
derived.EdgeCellCols, derived.EdgeSpacing, LowPolyAbstractionSettings.EdgeThreshold,
|
||||
LowPolyAbstractionSettings.AlphaThreshold));
|
||||
context.Barrier(grid.CellBest);
|
||||
context.For(edgeCellCount, new CellCountShader(grid.CellBest, grid.Counts, edgeCellCount));
|
||||
context.Barrier(grid.Counts);
|
||||
RecordScan(in context, grid, scratch, edgeCellCount, derived.EdgeBudget, 0, LowPolyAbstractionSettings.ScratchPendingCount);
|
||||
context.For(BlockCount(edgeCellCount), new EdgeEmitShader(
|
||||
grid.CellBest, grid.BlockSums, scratch, grid.SitePositions, grid.SiteKinds,
|
||||
edgeCellCount, BlockCount(edgeCellCount), derived.EdgeCellCols, derived.EdgeSpacing));
|
||||
context.Barrier(grid.SitePositions);
|
||||
context.Barrier(grid.SiteKinds);
|
||||
context.For(1, new CommitSitesShader(scratch));
|
||||
context.Barrier(scratch);
|
||||
|
||||
var interiorCellCount = derived.InteriorCellCols * derived.InteriorCellRows;
|
||||
context.For(interiorCellCount, new InteriorCountShader(
|
||||
grid.Color, grid.Counts, workingWidth, workingHeight,
|
||||
derived.InteriorCellCols, interiorCellCount, derived.InteriorSpacing,
|
||||
parameters.Seed, LowPolyAbstractionSettings.AlphaThreshold));
|
||||
context.Barrier(grid.Counts);
|
||||
RecordScan(in context, grid, scratch, interiorCellCount, derived.TargetSites, 1, LowPolyAbstractionSettings.ScratchPendingCount);
|
||||
context.For(BlockCount(interiorCellCount), new InteriorEmitShader(
|
||||
grid.Counts, grid.BlockSums, scratch, grid.SitePositions, grid.SiteKinds,
|
||||
interiorCellCount, BlockCount(interiorCellCount), derived.InteriorCellCols, derived.InteriorSpacing,
|
||||
parameters.Seed));
|
||||
context.Barrier(grid.SitePositions);
|
||||
context.Barrier(grid.SiteKinds);
|
||||
context.For(1, new CommitSitesShader(scratch));
|
||||
context.Barrier(scratch);
|
||||
|
||||
RecordLloydIterations(in context, grid, scratch, siteCapacity, in derived, derived.CvtIterations);
|
||||
RecordVoronoi(in context, grid, scratch, siteCapacity, in derived);
|
||||
RecordTriangulation(in context, grid, scratch, siteCapacity, in derived, pixelCount);
|
||||
RecordTriangleColors(in context, grid, scratch, in derived, false);
|
||||
|
||||
for (var pass = 0; pass < derived.RefinePasses; pass++)
|
||||
{
|
||||
context.For(derived.TriangleCapacity, new RefineCountShader(
|
||||
grid.TriangleErrors, scratch, grid.Counts, derived.TriangleCapacity, derived.ErrorThreshold));
|
||||
context.Barrier(grid.Counts);
|
||||
RecordScan(in context, grid, scratch, derived.TriangleCapacity, derived.RefineSiteLimit, 1, LowPolyAbstractionSettings.ScratchPendingCount);
|
||||
context.For(BlockCount(derived.TriangleCapacity), new RefineEmitShader(
|
||||
grid.Counts, grid.BlockSums, scratch, grid.TriangleVertices, grid.SitePositions, grid.SiteKinds,
|
||||
derived.TriangleCapacity, BlockCount(derived.TriangleCapacity)));
|
||||
context.Barrier(grid.SitePositions);
|
||||
context.Barrier(grid.SiteKinds);
|
||||
context.For(1, new CommitSitesShader(scratch));
|
||||
context.Barrier(scratch);
|
||||
|
||||
RecordLloydIterations(in context, grid, scratch, siteCapacity, in derived, LowPolyAbstractionSettings.PostInsertLloydIterations);
|
||||
RecordVoronoi(in context, grid, scratch, siteCapacity, in derived);
|
||||
RecordTriangulation(in context, grid, scratch, siteCapacity, in derived, pixelCount);
|
||||
RecordTriangleColors(in context, grid, scratch, in derived, pass == derived.RefinePasses - 1);
|
||||
}
|
||||
|
||||
var siteColorLength = siteCapacity * 10;
|
||||
context.For(siteColorLength, new FillIntShader(grid.SiteColorAccumulators, siteColorLength, 0));
|
||||
context.Barrier(grid.SiteColorAccumulators);
|
||||
context.For(workingWidth, workingHeight, new SiteColorAccumulateShader(
|
||||
GetAssignment(grid, in derived), grid.Color, grid.SiteColorAccumulators, workingWidth, workingHeight,
|
||||
LowPolyAbstractionSettings.AlphaThreshold));
|
||||
context.Barrier(grid.SiteColorAccumulators);
|
||||
context.For(siteCapacity, new SiteColorFinalizeShader(grid.SiteColorAccumulators, grid.SiteColors, siteCapacity));
|
||||
context.Barrier(grid.SiteColors);
|
||||
}
|
||||
|
||||
private static void RecordLloydIterations(
|
||||
in ComputeContext context,
|
||||
LowPolyAbstractionGridResources grid,
|
||||
ReadWriteBuffer<int> scratch,
|
||||
int siteCapacity,
|
||||
in LowPolyAbstractionPipeline.DerivedValues derived,
|
||||
int iterations)
|
||||
{
|
||||
var accumulatorLength = siteCapacity * 6;
|
||||
for (var iteration = 0; iteration < iterations; iteration++)
|
||||
{
|
||||
RecordVoronoi(in context, grid, scratch, siteCapacity, in derived);
|
||||
context.For(accumulatorLength, new FillIntShader(grid.SiteAccumulators, accumulatorLength, 0));
|
||||
context.Barrier(grid.SiteAccumulators);
|
||||
context.For(derived.WorkingWidth, derived.WorkingHeight, new CentroidAccumulateShader(
|
||||
GetAssignment(grid, in derived), grid.Weight, grid.SiteAccumulators, derived.WorkingWidth, derived.WorkingHeight));
|
||||
context.Barrier(grid.SiteAccumulators);
|
||||
context.For(siteCapacity, new UpdateSitesShader(
|
||||
grid.SitePositions, grid.SiteKinds, grid.SiteAccumulators, scratch,
|
||||
derived.WorkingWidth, derived.WorkingHeight, siteCapacity));
|
||||
context.Barrier(grid.SitePositions);
|
||||
}
|
||||
}
|
||||
|
||||
private static void RecordVoronoi(
|
||||
in ComputeContext context,
|
||||
LowPolyAbstractionGridResources grid,
|
||||
ReadWriteBuffer<int> scratch,
|
||||
int siteCapacity,
|
||||
in LowPolyAbstractionPipeline.DerivedValues derived)
|
||||
{
|
||||
var workingWidth = derived.WorkingWidth;
|
||||
var workingHeight = derived.WorkingHeight;
|
||||
context.For(workingWidth, workingHeight, new VoronoiClearShader(grid.JumpFloodA, workingWidth, workingHeight));
|
||||
context.Barrier(grid.JumpFloodA);
|
||||
context.For(siteCapacity, new VoronoiScatterShader(
|
||||
grid.SitePositions, scratch, grid.JumpFloodA, workingWidth, workingHeight, siteCapacity));
|
||||
context.Barrier(grid.JumpFloodA);
|
||||
var reading = grid.JumpFloodA;
|
||||
var writing = grid.JumpFloodB;
|
||||
for (var stepSize = derived.JumpFloodInitialStep; stepSize >= 1; stepSize >>= 1)
|
||||
{
|
||||
context.For(workingWidth, workingHeight, new JumpFloodSitePassShader(
|
||||
reading, writing, grid.SitePositions, workingWidth, workingHeight, stepSize));
|
||||
context.Barrier(writing);
|
||||
(reading, writing) = (writing, reading);
|
||||
}
|
||||
}
|
||||
|
||||
private static ReadWriteBuffer<int> GetAssignment(LowPolyAbstractionGridResources grid, in LowPolyAbstractionPipeline.DerivedValues derived)
|
||||
{
|
||||
var passes = 0;
|
||||
for (var stepSize = derived.JumpFloodInitialStep; stepSize >= 1; stepSize >>= 1)
|
||||
passes++;
|
||||
return (passes & 1) == 0 ? grid.JumpFloodA : grid.JumpFloodB;
|
||||
}
|
||||
|
||||
private static void RecordTriangulation(
|
||||
in ComputeContext context,
|
||||
LowPolyAbstractionGridResources grid,
|
||||
ReadWriteBuffer<int> scratch,
|
||||
int siteCapacity,
|
||||
in LowPolyAbstractionPipeline.DerivedValues derived,
|
||||
int pixelCount)
|
||||
{
|
||||
var assignment = GetAssignment(grid, in derived);
|
||||
context.For(derived.WorkingWidth, derived.WorkingHeight, new CornerCountShader(
|
||||
assignment, grid.Counts, derived.WorkingWidth, derived.WorkingHeight));
|
||||
context.Barrier(grid.Counts);
|
||||
RecordScan(in context, grid, scratch, pixelCount, derived.TriangleCapacity, 0, LowPolyAbstractionSettings.ScratchTriangleCount);
|
||||
context.For(BlockCount(pixelCount), new TriangleEmitShader(
|
||||
assignment, grid.Counts, grid.BlockSums, scratch, grid.TriangleVertices,
|
||||
derived.WorkingWidth, derived.WorkingHeight, BlockCount(pixelCount)));
|
||||
context.Barrier(grid.TriangleVertices);
|
||||
context.For(siteCapacity, new FillIntShader(grid.IncidenceCounts, siteCapacity, 0));
|
||||
context.Barrier(grid.IncidenceCounts);
|
||||
context.For(derived.TriangleCapacity, new IncidenceBuildShader(
|
||||
grid.TriangleVertices, grid.IncidenceCounts, grid.Incidence, scratch, derived.TriangleCapacity));
|
||||
context.Barrier(grid.IncidenceCounts);
|
||||
context.Barrier(grid.Incidence);
|
||||
context.For(siteCapacity, new SortIncidenceShader(grid.IncidenceCounts, grid.Incidence, siteCapacity));
|
||||
context.Barrier(grid.Incidence);
|
||||
}
|
||||
|
||||
private static void RecordTriangleColors(
|
||||
in ComputeContext context,
|
||||
LowPolyAbstractionGridResources grid,
|
||||
ReadWriteBuffer<int> scratch,
|
||||
in LowPolyAbstractionPipeline.DerivedValues derived,
|
||||
bool computeColors)
|
||||
{
|
||||
var lengthA = derived.TriangleCapacity * 14;
|
||||
context.For(lengthA, new FillIntShader(grid.TriangleAccumulatorsA, lengthA, 0));
|
||||
context.Barrier(grid.TriangleAccumulatorsA);
|
||||
context.For(derived.WorkingWidth, derived.WorkingHeight, new TriangleMapShader(
|
||||
GetAssignment(grid, in derived), grid.Color, grid.SitePositions, grid.TriangleVertices, grid.IncidenceCounts, grid.Incidence, grid.Counts,
|
||||
derived.WorkingWidth, derived.WorkingHeight, LowPolyAbstractionSettings.AlphaThreshold));
|
||||
context.Barrier(grid.Counts);
|
||||
context.For(derived.WorkingWidth, derived.WorkingHeight, new TriangleColorPassShader(
|
||||
grid.Counts, grid.Color, grid.TriangleAccumulatorsA, grid.TriangleAccumulatorsB,
|
||||
derived.WorkingWidth, derived.WorkingHeight, 0, LowPolyAbstractionSettings.TrimSigmaFactor));
|
||||
context.Barrier(grid.TriangleAccumulatorsA);
|
||||
if (computeColors)
|
||||
{
|
||||
var lengthB = derived.TriangleCapacity * 10;
|
||||
context.For(lengthB, new FillIntShader(grid.TriangleAccumulatorsB, lengthB, 0));
|
||||
context.Barrier(grid.TriangleAccumulatorsB);
|
||||
context.For(derived.WorkingWidth, derived.WorkingHeight, new TriangleColorPassShader(
|
||||
grid.Counts, grid.Color, grid.TriangleAccumulatorsA, grid.TriangleAccumulatorsB,
|
||||
derived.WorkingWidth, derived.WorkingHeight, 1, LowPolyAbstractionSettings.TrimSigmaFactor));
|
||||
context.Barrier(grid.TriangleAccumulatorsB);
|
||||
}
|
||||
context.For(derived.TriangleCapacity, new FinalizeTrianglesShader(
|
||||
grid.TriangleAccumulatorsA, grid.TriangleAccumulatorsB, scratch, grid.TriangleColors, grid.TriangleErrors,
|
||||
derived.TriangleCapacity, computeColors ? 1 : 0));
|
||||
if (computeColors)
|
||||
context.Barrier(grid.TriangleColors);
|
||||
context.Barrier(grid.TriangleErrors);
|
||||
}
|
||||
|
||||
private static void RecordScan(
|
||||
in ComputeContext context,
|
||||
LowPolyAbstractionGridResources grid,
|
||||
ReadWriteBuffer<int> scratch,
|
||||
int elementCount,
|
||||
int capLimit,
|
||||
int subtractSiteCount,
|
||||
int outputSlot)
|
||||
{
|
||||
var blocks = BlockCount(elementCount);
|
||||
context.For(blocks, new BlockCountShader(grid.Counts, grid.BlockSums, elementCount, blocks));
|
||||
context.Barrier(grid.BlockSums);
|
||||
context.For(1, new BlockPrefixShader(grid.BlockSums, scratch, blocks, capLimit, subtractSiteCount, outputSlot));
|
||||
context.Barrier(grid.BlockSums);
|
||||
context.Barrier(scratch);
|
||||
}
|
||||
|
||||
private static void RecordRenderStage(
|
||||
in ComputeContext context,
|
||||
LowPolyAbstractionGridResources grid,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
in LowPolyAbstractionPipeline.PixelRect rect,
|
||||
in LowPolyAbstractionPipeline.DerivedValues derived,
|
||||
in LowPolyAbstractionPipeline.Parameters parameters)
|
||||
{
|
||||
context.For(rect.Width, rect.Height, new RenderShader(
|
||||
GetAssignment(grid, in derived), grid.SitePositions, grid.TriangleVertices, grid.IncidenceCounts, grid.Incidence,
|
||||
grid.TriangleColors, grid.SiteColors, grid.Color, output,
|
||||
rect.X, rect.Y, rect.Width, rect.Height,
|
||||
derived.WorkingWidth, derived.WorkingHeight, derived.Scale,
|
||||
Math.Clamp(parameters.Gradient, 0f, 1f),
|
||||
LowPolyAbstractionSettings.WireframeWidth,
|
||||
Math.Clamp(parameters.Wireframe, 0f, 1f),
|
||||
Math.Clamp(parameters.Saturation, 0f, 1f),
|
||||
Math.Clamp(parameters.Jitter, 0f, 1f),
|
||||
parameters.Seed));
|
||||
}
|
||||
}
|
||||
@@ -36,9 +36,10 @@ internal static class LowPolyAbstractionSettings
|
||||
public const float MaximumErrorThreshold = 0.02f;
|
||||
public const float MaximumSaturationBoost = 0.6f;
|
||||
public const float MaximumLuminanceJitter = 0.08f;
|
||||
public const float MaximumWireframeWidth = 1.5f;
|
||||
public const float WireframeWidth = 1.5f;
|
||||
public const float SiteCapacityFraction = 1.5f;
|
||||
public const int TriangleCapacitySlack = 16;
|
||||
public const int MaximumPendingSubmissions = 32;
|
||||
|
||||
public static QualitySettings GetQuality(LowPolyAbstractionQuality quality)
|
||||
=> quality switch
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
using Telemetry;
|
||||
|
||||
namespace LowPolyAbstraction;
|
||||
|
||||
internal static class LowPolyAbstractionTelemetry
|
||||
{
|
||||
private const int MaxChainLength = 5;
|
||||
private const int MaxFrames = 100;
|
||||
|
||||
private static readonly Assembly Own = typeof(LowPolyAbstractionTelemetry).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;
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ internal static class LowPolyAbstractionUpdateNotifier
|
||||
|
||||
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 LowPolyAbstractionUpdateNotifier
|
||||
};
|
||||
await new Notifier(Owner, Repository, options).NotifyAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
catch (Exception exception)
|
||||
{
|
||||
if (exception is not UpdateCheckException)
|
||||
LowPolyAbstractionTelemetry.Report(exception);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,5 +2,5 @@ namespace LowPolyAbstraction;
|
||||
|
||||
internal static class ShaderResourceUri
|
||||
{
|
||||
public static Uri Get(string shaderName) => new($"pack://application:,,,/LowPolyAbstraction;component/Shaders/{shaderName}.cso", UriKind.Absolute);
|
||||
public static Uri Get(string shaderName) => new($"pack://application:,,,/LowPolyAbstraction;component/Resources/Shader/{shaderName}.cso", UriKind.Absolute);
|
||||
}
|
||||
@@ -18,7 +18,7 @@ SeedDescription,,三角形の配置を決める固定値です,A fixed value tha
|
||||
Gradient,,グラデーション,Gradient,渐变,漸變,그라데이션,Degradado,التدرج,Gradasi
|
||||
GradientDescription,,三角形内の塗りのグラデーションの強さです,Strength of the gradient fill inside each triangle,三角形内部渐变填充的强度,三角形內部漸變填充的強度,삼각형 내부 그라데이션 채우기의 강도입니다,Intensidad del relleno degradado dentro de cada triángulo,شدة التعبئة المتدرجة داخل كل مثلث,Kekuatan isian gradasi di dalam setiap segitiga
|
||||
Wireframe,,輪郭線,Wireframe,轮廓线,輪廓線,윤곽선,Malla,الإطار الشبكي,Rangka
|
||||
WireframeDescription,,三角形の境界線の濃さです,Darkness of the triangle boundary lines,三角形边界线的浓度,三角形邊界線的濃度,삼각형 경계선의 진하기입니다,Oscuridad de las líneas de borde de los triángulos,شدة خطوط حدود المثلثات,Ketebalan garis batas segitiga
|
||||
WireframeDescription,,三角形の境界線の濃さです,Darkness of the triangle boundary lines,三角形边界线的浓度,三角形邊界線的濃度,삼각형 경계선의 진하기입니다,Oscuridad de las líneas de borde de los triángulos,شدة خطوط حدود المثلثات,Tingkat kegelapan garis batas segitiga
|
||||
Saturation,,彩度,Saturation,饱和度,飽和度,채도,Saturación,التشبع,Saturasi
|
||||
SaturationDescription,,三角形の色の彩度の強調量です,Amount of saturation boost of the triangle colors,三角形颜色饱和度的增强量,三角形顏色飽和度的增強量,삼각형 색 채도의 강조량입니다,Cantidad de realce de saturación de los colores de los triángulos,مقدار تعزيز تشبع ألوان المثلثات,Jumlah peningkatan saturasi warna segitiga
|
||||
Jitter,,明度ゆらぎ,Brightness Jitter,明度扰动,明度擾動,명도 요동,Variación de brillo,تذبذب السطوع,Fluktuasi Kecerahan
|
||||
|
||||
|
@@ -6,10 +6,10 @@
|
||||
|
||||
---
|
||||
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、素材を三角メッシュへ抽象化してローポリ調に描画する映像エフェクトプラグインです。
|
||||
エッジ拘束と特徴フロー場つきの重み付きボロノイ緩和で頂点を最適化し、色の誤差が大きい三角形を細分化して細部へ密度を寄せます。
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、素材を三角形の面で塗り分けてローポリ画として描画する映像エフェクトプラグインです。
|
||||
エッジの上に頂点を固定し、残りの頂点を、エッジからの距離に応じて重みを付けた重心ボロノイ分割で並べ、色の誤差が大きい三角形をさらに分割します。
|
||||
履歴フレーム、参照画像、学習済みモデルを使わず、入力された一枚の映像だけを処理します。
|
||||
三角形の配置はシードから決定論的に決まり、同じ設定では常に同じ形になります。
|
||||
三角形の配置は素材とシードから決定論的に決まり、同じ設定では常に同じ形になります。
|
||||
強さ、細かさ、輪郭忠実度、細分化、グラデーション、輪郭線、彩度、明度ゆらぎの8項目はアニメーションに対応しています。
|
||||
|
||||

|
||||
@@ -22,11 +22,11 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を三角メッシュへ
|
||||
2. [動作要件](#動作要件)
|
||||
3. [インストール方法](#インストール方法)
|
||||
4. [主な機能](#主な機能)
|
||||
- [1. 三角メッシュ化](#1-三角メッシュ化)
|
||||
- [1. エッジに沿う三角メッシュ](#1-エッジに沿う三角メッシュ)
|
||||
- [2. 細かさとシード](#2-細かさとシード)
|
||||
- [3. 輪郭忠実度](#3-輪郭忠実度)
|
||||
- [4. 誤差駆動の細分化](#4-誤差駆動の細分化)
|
||||
- [5. グラデーション・輪郭線・彩度・明度ゆらぎ](#5-グラデーション輪郭線彩度明度ゆらぎ)
|
||||
- [4. 色の誤差に応じた細分化](#4-色の誤差に応じた細分化)
|
||||
- [5. 塗りとグラデーション・輪郭線・彩度・明度ゆらぎ](#5-塗りとグラデーション輪郭線彩度明度ゆらぎ)
|
||||
- [6. 品質の選択](#6-品質の選択)
|
||||
5. [パラメータ一覧](#パラメータ一覧)
|
||||
- [基本グループ](#基本グループ)
|
||||
@@ -34,9 +34,10 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を三角メッシュへ
|
||||
- [描画グループ](#描画グループ)
|
||||
6. [制限事項](#制限事項)
|
||||
7. [注意事項](#注意事項)
|
||||
8. [免責事項](#免責事項)
|
||||
9. [サードパーティライセンス](#サードパーティライセンス)
|
||||
10. [ライセンス](#ライセンス)
|
||||
8. [不具合の報告](#不具合の報告)
|
||||
9. [免責事項](#免責事項)
|
||||
10. [サードパーティライセンス](#サードパーティライセンス)
|
||||
11. [ライセンス](#ライセンス)
|
||||
|
||||
---
|
||||
|
||||
@@ -44,11 +45,9 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を三角メッシュへ
|
||||
|
||||
本プラグインはYMM4の映像エフェクトとして動作し、エフェクトの種類一覧では「ローポリ化」として表示されます。カテゴリは装飾と加工です。
|
||||
|
||||
入力された現在のフレームを作業解像度へ縮小し、輝度とアルファのSobel勾配からエッジを抽出します。頂点の配置はGai and Wangの論文「Artistic Low Poly rendering for images」(2016年)に基づき、エッジまでの距離場から作る特徴フロー場を重みとした重心ボロノイのLloyd緩和で最適化します。エッジ上の拘束点は固定し、内部点だけを動かすことで、輪郭が三角形の辺として保たれます。三角形はボロノイ割り当て図の双対として求め、三角形ごとに刈り込み平均で色を集計します。輝度分散が大きい三角形の重心へ新しい頂点を挿入する細分化は、Lawonn and Güntherの論文「Stylized Image Triangulation」(2019年)の高誤差三角形分割に基づきます。
|
||||
入力された現在のフレームを、長辺が品質で決まる画素数に収まるように縮小し、輝度と不透明度からエッジを求めます。エッジの上に頂点を固定し、残りの頂点を、エッジからの距離に応じて重みを付けた重心ボロノイ分割で並べます。並べた頂点を結んで、素材を三角形に分けます。この頂点の置き方は、Gai and Wangの論文「Artistic Low Poly rendering for images」(The Visual Computer、2016年)に基づきます。色の誤差は、三角形の中の画素の輝度のばらつきを表す分散です。色の誤差が大きい三角形をさらに分割する処理は、Lawonn and Güntherの論文「Stylized Image Triangulation」(Computer Graphics Forum、2019年)に基づきます。三角形の塗りは、縮小する前の素材の解像度で描きます。配置の計算は決定論的で、時間値や実行のたびに変わる乱数を使用しません。同じ素材、同じシード、同じパラメータからは常に同じ配置になります。
|
||||
|
||||
生成は決定論的で、乱数と時間値を使用しません。同じ素材、同じシード、同じパラメータからは常に同じ三角メッシュになります。
|
||||
|
||||
計算はComputeSharpの計算シェーダーがDirect3D 12で実行します。YMM4のDirect3D 11側とComputeSharpのDirect3D 12側は、共有テクスチャと共有フェンスで接続します。通常のフレーム処理では、CPUへの画素の読み戻しを行わず、内容ハッシュとバウンディングボックスだけを読み戻します。素材が存在する矩形の範囲だけを描画し、素材の内容とメッシュを決めるパラメータが変わらないフレームでは三角メッシュの計算を再利用します。
|
||||
計算はComputeWeaveの計算シェーダーがDirect3D 12で実行します。YMM4のDirect3D 11側とComputeWeaveのDirect3D 12側は、共有テクスチャと共有フェンスで接続します。通常のフレーム処理では、CPUへの画素の読み戻しを行わず、16個の整数の読み戻しだけで素材の変化を判定します。三角形を描くのは、素材の不透明な部分を囲む矩形に余白を加えた範囲だけです。素材の大きさと色と不透明度、三角形の配置を決めるパラメータが変わらないフレームでは、三角メッシュの計算を再利用します。
|
||||
|
||||
このエフェクトはAviUtl向けのEXO出力には対応していません。
|
||||
|
||||
@@ -76,45 +75,59 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を三角メッシュへ
|
||||
|
||||
## 主な機能
|
||||
|
||||
### 1. 三角メッシュ化
|
||||
### 1. エッジに沿う三角メッシュ
|
||||
|
||||
素材のアルファ値が示すシルエットの内側へ頂点を配置し、ボロノイ割り当て図の双対として求めた三角メッシュで素材を覆います。各三角形は、内部の画素色の刈り込み平均で塗られます。刈り込み平均は輝度の平均±1.2σの帯域内の画素だけを使うため、明部と暗部が混ざった三角形でも中間色に濁りません。
|
||||
エッジは、輝度や不透明度が急に変わる所です。素材の輪郭と、輝度の違う色の境界がこれに当たります。本プラグインは、輝度と不透明度を足した値が急に変わる所をエッジとし、ソーベルフィルタで求めます。輝度が同じで色だけが違う境界はエッジとして求まりにくく、三角形の辺として残りにくくなります。
|
||||
|
||||
頂点の配置は重み付き重心ボロノイのLloyd緩和で最適化します。重みはエッジまでの距離の三角波で、頂点がエッジに平行なレーンへ整列し、輪郭に沿った三角形の帯ができます。
|
||||
頂点には、エッジの上に固定する頂点と、内側で動かす頂点の2種類があります。エッジの上の頂点は、素材を区切った格子のセルごとに、最もエッジの強い画素へ1つずつ置きます。エッジの上にない頂点を、内側の頂点と呼びます。内側の頂点は、別の格子のセルごとに1つずつ、シードで決めた位置に置いてから動かします。画素の不透明度が5%以下の所には、どちらの頂点も置きません。
|
||||
|
||||
ボロノイ図は、各画素を最も近い頂点に割り当てて領域に分けた図です。各頂点が自分の領域の重心に一致するボロノイ図を、重心ボロノイ分割と呼びます。内側の頂点は、Lloyd法で重心ボロノイ分割に近づけます。Lloyd法は、各頂点を自分の領域の重心へ動かし、ボロノイ図を求め直すことを繰り返す方法です。重心は画素ごとの重みを掛けて求めるので、頂点は重みの大きい所へ寄ります。重みはエッジからの距離に応じて周期的に上下し、上下の幅はエッジから離れるほど小さくなります。重みの大きい帯はエッジと平行に並ぶので、内側の頂点はこの帯に沿って列を作ります。
|
||||
|
||||
三角形は、画素単位で求めたボロノイ図から作ります。3つの領域が接する所ごとに、その3つの領域の頂点を結んで三角形にします。エッジの上の頂点は動かないので、素材の輪郭と色の境界は三角形の辺として残り、エッジに沿って三角形が帯状に並びます。三角形は頂点どうしを結んで作るので、素材のくぼみや隙間をまたぐことがあります。ただし、素材の透明な部分には塗りを描きません。
|
||||
|
||||
### 2. 細かさとシード
|
||||
|
||||
細かさは、三角形の目標数を決めます。低いほど大きな三角形で大胆に抽象化され、高いほど細かく分割されます。
|
||||
細かさは、頂点の数の目安を決めます。細かさが0%のときは頂点数の基準の10分の1、100%のときは基準と同じ数が目安です。頂点数の基準は品質ごとに決まり、「品質の選択」の表にあります。低いほど大きな三角形で大胆に抽象化され、高いほど細かく分割されます。目安は素材の大きさによらないので、小さな素材ほど三角形も小さくなります。素材に透明な部分が多いほど、実際の頂点の数は目安より少なくなります。
|
||||
|
||||
シードは、内部頂点の初期配置のジッターを決める固定値です。頂点の配置はシード、セル位置、素材の内容から決定論的に算出するため、同じ設定では常に同じメッシュになります。
|
||||
シードは、内側の頂点を初めに置く位置と、明度ゆらぎの模様を決める固定値です。
|
||||
|
||||
### 3. 輪郭忠実度
|
||||
|
||||
輪郭忠実度は、エッジ上の拘束点の密度と、特徴フロー場の重みの強さを決めます。高いほどエッジのサンプル間隔が狭まり、頂点がエッジへ強く引き寄せられるため、素材の輪郭と色の境界が三角形の辺として保たれます。低いほど頂点が一様に近づき、境界を跨ぐ大きな三角形が増えます。
|
||||
輪郭忠実度は、エッジの上に置く頂点の間隔と、エッジからの距離に応じた重みの上下の幅を決めます。高いほど、エッジの上の頂点の間隔が狭まって数が増え、内側の頂点もエッジに沿った列へ強く集まります。その結果、素材の輪郭と色の境界が三角形の辺として保たれます。0%では重みが一様になり、内側の頂点は素材の中へ均等に散らばります。エッジの上の頂点も減り、色の境界をまたぐ大きな三角形が増えます。
|
||||
|
||||
### 4. 誤差駆動の細分化
|
||||
### 4. 色の誤差に応じた細分化
|
||||
|
||||
細分化は、色の誤差が大きい三角形を分割する強さを決めます。三角形ごとに輝度の分散を集計し、閾値を超えた三角形の重心へ新しい頂点を挿入して、ボロノイ緩和と三角化をやり直します。この反復により、色の変化が細かい領域へ三角形の密度が寄り、平坦な領域は大きな三角形のまま保たれます。
|
||||
細分化は、色の誤差が大きい三角形を分割する強さを決めます。色の誤差は、三角形の中の画素の輝度のばらつきを表す分散です。細かさが全体の頂点の数を決めるのに対し、細分化は色の誤差が大きい所にだけ頂点を足します。
|
||||
|
||||
### 5. グラデーション・輪郭線・彩度・明度ゆらぎ
|
||||
色の誤差がしきい値を超えた三角形の重心へ新しい頂点を足し、Lloyd法で頂点を2回動かしてから三角形を作り直します。細分化を上げるほどしきい値が下がり、分割する三角形が増えます。細分化を0%にしても分割は止まらず、色の誤差が特に大きい三角形は分割します。
|
||||
|
||||
グラデーションは、三角形内の塗りを平坦塗りから頂点色の線形補間へ混ぜる割合です。0%では完全な平坦塗り、100%では滑らかなグラデーション塗りになります。
|
||||
この分割を品質で決まる回数だけ繰り返すと、色の変化が細かい所ほど三角形が細かくなり、平坦な所は大きな三角形のまま残ります。足した頂点を合わせても、頂点の数は細かさで決まる目安の1.5倍までです。
|
||||
|
||||
輪郭線は、三角形の境界線の濃さです。値を上げると辺に沿って暗い線が入り、ステンドグラスやワイヤーフレームの趣になります。
|
||||
### 5. 塗りとグラデーション・輪郭線・彩度・明度ゆらぎ
|
||||
|
||||
彩度は、三角形の色の彩度の強調量です。明度ゆらぎは、三角形ごとの明るさの微小な変動で、平坦な領域でも三角形の面が見分けられるようになります。ゆらぎは三角形の重心とシードから決定論的に決まります。
|
||||
各三角形は、中の画素の色の平均で一色に塗ります。ただし、輝度が三角形の中の輝度の平均から大きく外れた画素は、色の平均に含めません。外れたとみなすのは、平均との輝度の差が標準偏差の1.2倍を超える画素です。標準偏差は、ばらつきの目安です。三角形の中の少数の明るい画素や暗い画素に、色が引きずられにくくなります。不透明度が5%以下の画素も含めません。塗りは縮小する前の素材の解像度で描くので、縮小して計算しても三角形の辺はぼやけません。塗りの各画素の不透明度は、縮小する前の素材のその画素の不透明度を上限にします。
|
||||
|
||||
グラデーションは、三角形の中で色を滑らかに変える割合です。三角形ごとの一色の塗りに、頂点の色から補間した塗りを混ぜます。頂点の色は、その頂点の領域にある画素の平均の色です。0%では三角形ごとに一色、100%では三角形の中で色が滑らかに変わります。
|
||||
|
||||
輪郭線は、三角形の辺に沿って入れる暗い線の濃さです。素材の輪郭だけでなく、すべての三角形の辺に線を入れます。線は縮小する前の解像度で辺から1.5画素までの範囲に入り、辺から離れるほど元の明るさに戻ります。値を上げるほど線は暗くなり、100%では辺の真上の明るさが元の35%になります。
|
||||
|
||||
彩度は、三角形の色を鮮やかにする量です。0%では元の色のまま、100%では同じ輝度の灰色からの色の差を1.6倍にします。
|
||||
|
||||
明度ゆらぎは、三角形ごとに明るさを変える量です。100%では三角形ごとに明るさを最大8%上げ下げし、平坦な所でも三角形の面が見分けられるようにします。ゆらぎは三角形の重心とシードから決定論的に決まります。
|
||||
|
||||
### 6. 品質の選択
|
||||
|
||||
品質は、作業解像度、頂点数の基準、Lloyd緩和の反復回数、細分化の反復回数をまとめて切り替えます。
|
||||
品質は、作業解像度、頂点数の基準、Lloyd法の反復回数、分割の反復回数をまとめて切り替えます。作業解像度は、縮小して計算するときの長辺の画素数の上限です。頂点数の基準が変わるので、同じ細かさでも品質を変えると三角形の数が変わります。
|
||||
|
||||
| 品質 | 作業解像度 | 頂点数の基準 | 緩和反復 | 細分化反復 |
|
||||
| 品質 | 作業解像度 | 頂点数の基準 | Lloyd法の反復 | 分割の反復 |
|
||||
|---|---:|---:|---:|---:|
|
||||
| 標準 | 1024 | 4096 | 6回 | 1回 |
|
||||
| 高品質 | 1536 | 8192 | 8回 | 2回 |
|
||||
| 最高品質 | 2048 | 16384 | 10回 | 3回 |
|
||||
|
||||
作業解像度は計算領域の長辺の画素数です。短辺は計算領域の縦横比に合わせて決めます。
|
||||
表のLloyd法の反復は分割の前に行う回数で、分割のたびに行う2回は含みません。
|
||||
|
||||
縮小するかどうかは、透明な部分も含む素材全体に余白を加えた計算領域の長辺で決まります。計算領域の長辺の画素数が作業解像度を超えるときは、長辺が作業解像度になるように縮小して計算し、短辺は縦横比に合わせます。
|
||||
|
||||
---
|
||||
|
||||
@@ -125,25 +138,25 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を三角メッシュへ
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 強さ | 数値 | 100% | 0〜100% | 対応 | ローポリ画の合成量です。0%では入力を変更しません。 |
|
||||
| 品質 | 列挙 | 高品質 | 標準 / 高品質 / 最高品質 | 非対応 | 作業解像度と最適化の反復回数を選択します。 |
|
||||
| 品質 | 列挙 | 高品質 | 標準 / 高品質 / 最高品質 | 非対応 | 作業解像度と頂点数の基準と反復回数を選択します。 |
|
||||
|
||||
### 三角形グループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 細かさ | 数値 | 60% | 0〜100% | 対応 | 三角形の数です。高いほど細かく分割されます。 |
|
||||
| 輪郭忠実度 | 数値 | 70% | 0〜100% | 対応 | 輪郭への頂点の集まり具合です。高いほど輪郭が保たれます。 |
|
||||
| 細かさ | 数値 | 60% | 0〜100% | 対応 | 頂点の数の目安です。高いほど三角形が細かくなります。 |
|
||||
| 輪郭忠実度 | 数値 | 70% | 0〜100% | 対応 | エッジへの頂点の集まり具合です。高いほど素材の輪郭と色の境界が保たれます。 |
|
||||
| 細分化 | 数値 | 50% | 0〜100% | 対応 | 色の誤差が大きい三角形を分割する強さです。 |
|
||||
| シード | 整数 | 0 | 0〜10000 | 非対応 | 三角形の配置を決める固定値です。直接入力では2147483647まで指定できます。 |
|
||||
| シード | 整数 | 0 | 0〜10000 | 非対応 | 三角形の配置と明度ゆらぎの模様を決める固定値です。直接入力では2147483647まで指定できます。 |
|
||||
|
||||
### 描画グループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| グラデーション | 数値 | 30% | 0〜100% | 対応 | 三角形内の塗りのグラデーションの強さです。 |
|
||||
| 輪郭線 | 数値 | 0% | 0〜100% | 対応 | 三角形の境界線の濃さです。 |
|
||||
| 彩度 | 数値 | 30% | 0〜100% | 対応 | 三角形の色の彩度の強調量です。 |
|
||||
| 明度ゆらぎ | 数値 | 25% | 0〜100% | 対応 | 三角形ごとの明るさのゆらぎです。 |
|
||||
| グラデーション | 数値 | 30% | 0〜100% | 対応 | 三角形の中で色を滑らかに変える割合です。0%で三角形ごとに一色になります。 |
|
||||
| 輪郭線 | 数値 | 0% | 0〜100% | 対応 | 三角形の辺に入れる暗い線の濃さです。0%で線を入れません。 |
|
||||
| 彩度 | 数値 | 30% | 0〜100% | 対応 | 三角形の色を鮮やかにする量です。0%で元の色のままです。 |
|
||||
| 明度ゆらぎ | 数値 | 25% | 0〜100% | 対応 | 三角形ごとに明るさを変える量です。0%で変えません。 |
|
||||
|
||||
---
|
||||
|
||||
@@ -151,24 +164,58 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を三角メッシュへ
|
||||
|
||||
- AviUtl向けのEXO出力には対応していません。
|
||||
- Direct3D 12デバイスを取得できない場合や、YMM4が使うDirect3D 11デバイスとの共有テクスチャおよび共有フェンスを作成できない場合は、エフェクトを適用せず入力映像を表示します。
|
||||
- 三角メッシュの生成には現在のフレームの色とアルファ値だけを使用します。履歴フレーム、外部画像、学習済みモデルは使用しません。
|
||||
- 計算領域は素材の範囲に固定余白8画素を加えた大きさで、長辺は8192画素が上限です。素材が大きすぎる場合は、エフェクトを適用せず入力映像を表示します。
|
||||
- 三角メッシュの生成には現在のフレームの色と不透明度だけを使用します。履歴フレーム、外部画像、学習済みモデルは使用しません。画素の不透明度が5%以下の所は、頂点の配置と色の計算に使いません。素材のすべての画素の不透明度が5%以下のときは、エフェクトを適用せず入力映像を表示します。
|
||||
- 計算領域は、透明な部分も含む素材全体の矩形の上下左右に8画素の余白を加えた大きさで、長辺は8192画素が上限です。素材の長辺が8176画素を超える場合は、エフェクトを適用せず入力映像を表示します。
|
||||
- 処理量とGPUメモリ使用量は、計算領域の大きさと品質に応じて増えます。
|
||||
|
||||
---
|
||||
|
||||
## 注意事項
|
||||
|
||||
- 処理負荷: 最高品質は作業解像度と反復回数が最も多いため、高品質と標準より処理負荷が高くなります。三角メッシュの再計算は素材の内容が変わったフレームだけで実行され、変わらないフレームでは描画だけを行います。描画は素材が存在する矩形の範囲だけを計算します。
|
||||
- キャッシュ: 素材の内容と、品質、シード、細かさ、輪郭忠実度、細分化が変わらないフレームでは、三角メッシュの計算を再利用します。グラデーション、輪郭線、彩度、明度ゆらぎだけを変えたフレームでは、メッシュを再計算しません。
|
||||
- 処理負荷: 最高品質は作業解像度と反復回数が最も多いため、高品質と標準より処理負荷が高くなります。描画の計算は、素材の不透明な部分を囲む矩形に余白を加えた範囲に限ります。
|
||||
- キャッシュ: 素材の大きさと色と不透明度、品質、シード、細かさ、輪郭忠実度、細分化が変わらないフレームでは、三角メッシュの計算を再利用します。強さ、グラデーション、輪郭線、彩度、明度ゆらぎだけを変えたフレームでは、三角メッシュを計算し直しません。動画や口パクのように素材の内容が変わるフレームと、細かさ、輪郭忠実度、細分化をアニメーションで変えたフレームでは、毎回計算し直すので処理が重くなります。素材が変わったかどうかを調べる計算は、再利用するフレームでも毎フレーム行います。
|
||||
- 強さ0%: 強さが0%のときは入力を変更しません。
|
||||
- シードと再現性: 三角形の配置は、シード、セル位置、素材の内容から決定論的に算出します。時間値は生成に使用しません。
|
||||
- 出力範囲: 三角形は素材のシルエットの内側に生成されるため、出力範囲は素材の範囲に余白を加えた矩形に収まります。ローポリ画は元映像の上へアルファ合成します。
|
||||
- シードと再現性: 三角形の配置は、シード、セル位置、素材の内容から決定論的に算出します。時間値は生成に使用しません。素材の内容が変わるフレームや、細かさ、輪郭忠実度、細分化をアニメーションで変えたフレームでは、三角形の配置も変わることがあります。
|
||||
- 透明部分: 塗りの各画素の不透明度は、素材のその画素の不透明度を超えません。そのため、三角形が素材のくぼみや隙間をまたいでも、透明な部分は透明のまま残ります。出力範囲は計算領域に収まります。ローポリ画は、塗りで覆われない分だけ元映像が見えるように元映像と合成します。そのため、半透明な素材も元の不透明度のまま描かれ、三角形で覆われない画素では元映像がそのまま見えます。
|
||||
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ新しい正式版を確認します。更新情報を取得できない場合は通知せず、そのまま動作します。プレリリースは通知の対象に含めません。
|
||||
- 不具合の自動送信: 想定していない例外が起きたときは、その内容を開発者へ自動で送信します。内容は「不具合の報告」に書いています。
|
||||
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを作成することを推奨します。
|
||||
|
||||
---
|
||||
|
||||
## 不具合の報告
|
||||
|
||||
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で送信します。同意は求めず、常に送信します。
|
||||
|
||||
送信する情報は次のとおりです。
|
||||
|
||||
| 種類 | 内容 |
|
||||
|---|---|
|
||||
| 例外 | 型の完全名、メッセージ、スタックトレース |
|
||||
| 発生位置 | モジュール名、関数名、ファイル名、行番号 |
|
||||
| プラグイン | アセンブリ名、バージョン |
|
||||
| 実行環境 | OSの名前とバージョン、.NETのバージョン、CPUのアーキテクチャ、論理プロセッサ数 |
|
||||
| 識別子 | YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子 |
|
||||
|
||||
メッセージとファイル名は、送信の前に置き換えを通します。置き換えるのは、Windowsのユーザー名、ユーザーフォルダー、AppDataのパス、マシン名、ドメイン名、メールアドレス、IPv4アドレスです。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
|
||||
|
||||
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値になります。
|
||||
|
||||
送信するのは想定していない例外だけです。YMM4が本プラグインのエフェクトを作るとき、フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後はYMM4へそのまま渡します。画面の操作やバックグラウンドの処理で未処理になった例外も報告しますが、本プラグインのコードが関わる例外に限ります。本プラグインの外で起きた例外は送信しません。
|
||||
|
||||
次の失敗は送信しません。
|
||||
|
||||
| 種類 | 例 |
|
||||
|---|---|
|
||||
| 効果をかけないだけで済ませるもの | Direct3D 12デバイスを取得できない、YMM4のDirect3D 11デバイスとの共有テクスチャや共有フェンスを作成できない、計算領域が上限を超えるときに、エフェクトを適用せず入力映像を表示したとき |
|
||||
| 更新の確認の通信の失敗 | GitHubへ接続できない |
|
||||
|
||||
送信できなかった報告はYMM4のユーザーフォルダーへ退避し、次回の起動時に送り直します。送信も再送も非同期に行うため、起動と描画が遅くなることはありません。
|
||||
|
||||
実装は [YMM4-Telemetry](https://github.com/routersys/YMM4-Telemetry) をサブモジュールとして取り込んでいます。
|
||||
|
||||
---
|
||||
|
||||
## 免責事項
|
||||
|
||||
本プラグインはMITライセンスのもとで公開されています。
|
||||
@@ -181,11 +228,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 |
|
||||
|
||||
---
|
||||
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
# セキュリティポリシー
|
||||
|
||||
## サポートするバージョン
|
||||
|
||||
セキュリティの修正は、最新のリリースだけを対象にします。
|
||||
|
||||
| バージョン | サポート |
|
||||
|---|---|
|
||||
| 最新のリリース | 対象 |
|
||||
| それより前のリリース | 対象外 |
|
||||
|
||||
修正は、最新のリリースの次のバージョンとして公開します。報告する前に、最新のリリースでも問題が起きるかを確かめてください。
|
||||
|
||||
## 対象とする問題
|
||||
|
||||
本プラグインのコードと配布パッケージに原因がある問題を対象にします。たとえば次のようなものです。
|
||||
|
||||
- 細工したプロジェクトファイルや素材を開くと、意図しない処理が実行される
|
||||
- 更新の確認などで行う通信の内容を、第三者が書き換えられる
|
||||
- 不具合の情報を自動で送信するプラグインで、個人を特定できる情報が伏せられないまま送信される
|
||||
|
||||
配布パッケージに同梱したライブラリの脆弱性は、本プラグインを通じて悪用できる場合に対象にします。
|
||||
|
||||
YukkuriMovieMaker4 本体や、ほかのプラグインに原因がある問題は対象外です。それぞれの開発者へ報告してください。
|
||||
|
||||
## 報告の方法
|
||||
|
||||
脆弱性は、公開の Issue に書かないでください。修正を公開する前に悪用されるおそれがあります。
|
||||
|
||||
1. リポジトリの URL の末尾に `/security` を付けたページを開き、「Report a vulnerability」から非公開で報告してください。報告の内容を見られるのは、開発者と報告した人、開発者が招いた人だけです。
|
||||
2. この方法が使えないときは、github.routersys@gmail.com へメールで報告してください。
|
||||
|
||||
報告には、次の内容を書いてください。分からない項目は書かなくて構いません。
|
||||
|
||||
| 項目 | 内容 |
|
||||
|---|---|
|
||||
| バージョン | 問題を確かめたプラグインのバージョンと、YukkuriMovieMaker4 のバージョン |
|
||||
| 再現の手順 | 問題を起こす操作と、使ったプロジェクトファイルや素材 |
|
||||
| 影響 | 問題によって何ができてしまうか |
|
||||
| 回避策 | 分かっていれば、修正までの間に被害を避ける方法 |
|
||||
|
||||
## 報告の後
|
||||
|
||||
開発者は、報告を受け取ったら内容を確かめ、修正の見込みを返信します。
|
||||
|
||||
報告した人は、修正を含むバージョンが出るまで、報告の内容を明かさないでください。問題の詳細は、修正版の公開後に開発者が公表します。
|
||||
サブモジュール
+1
サブモジュール YMM4-Telemetry が 04010903ca で追加されました。
バイナリファイルは表示されません。
|
変更前 幅: | 高さ: | サイズ: 522 KiB 変更後 幅: | 高さ: | サイズ: 839 KiB |
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"test": {
|
||||
"runner": "Microsoft.Testing.Platform"
|
||||
}
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする