コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
61f17b4469
|
||
|
|
0600b6a159
|
||
|
|
15fda80d2d
|
||
|
|
1505b0e1c8
|
||
|
|
709ec11404
|
||
|
|
cd9b17e057
|
||
|
|
64eb8c2b22
|
||
|
|
6ea6542267
|
||
|
|
a1150d0ee8
|
||
|
|
ee2a0c9120
|
||
|
|
cd433e5d75
|
検索条件に一致するファイルはありません
+22
-11
@@ -1,5 +1,5 @@
|
||||
========================================
|
||||
色ずれ(スペクトラム) for YMM4 v1.0.1
|
||||
色ずれ(スペクトラム) for YMM4 v1.2.0
|
||||
========================================
|
||||
YukkuriMovieMaker4上で動作する、映像の色を400nmから700nmの波長に分け、波長ごとに
|
||||
異なる量だけずらして足し合わせ、虹色の縁として描画する
|
||||
@@ -7,6 +7,11 @@ YukkuriMovieMaker4上で動作する、映像の色を400nmから700nmの波長
|
||||
等色関数の計算は、Wyman, Sloan and Shirleyの論文「Simple Analytic Approximations
|
||||
to the CIE XYZ Color Matching Functions」(Journal of Computer Graphics
|
||||
Techniques、2013年)に基づきます。
|
||||
「物理ベース」をオンにすると、映像の色から光のスペクトルを推定し、波長ごとの
|
||||
光をずらして足し合わせます。スペクトルの推定は、Mallett and Yukselの
|
||||
論文「Spectral Primary Decomposition for Rendering with sRGB
|
||||
Reflectance」(Eurographics Symposium on Rendering、2019年)に基づきます。既定は
|
||||
オフで、オフのときの結果は、従来のバージョンと同じです。
|
||||
履歴フレーム、参照画像、深度情報、学習済みモデルは使用しません。
|
||||
色のずれ方は設定と画素の位置から決定論的に決まり、同じ設定では常に同じ
|
||||
絵になります。
|
||||
@@ -29,19 +34,25 @@ Techniques、2013年)に基づきます。
|
||||
エフェクトを適用せず入力映像を表示します。
|
||||
|
||||
- 処理対象: 色のずれの計算には現在のフレームの色と不透明度だけを使用します。
|
||||
履歴フレーム、外部画像、深度情報、学習済みモデルは使用しません。映像の赤、緑、
|
||||
青の3つの値から色を作り直すため、映像に含まれない波長の情報を取り出す
|
||||
機能はありません。
|
||||
履歴フレーム、外部画像、深度情報、学習済みモデルは使用しません。
|
||||
「物理ベース」がオフのときは、映像の赤、緑、青の3つの値から色を作り直すため、
|
||||
映像に含まれない波長の情報を取り出す機能はありません。オンのときは、3つの
|
||||
値から滑らかなスペクトルを推定します。同じ色になるスペクトルは無数にあるため、
|
||||
元の映像が実際に出していた光のスペクトルとは違うことがあります。
|
||||
|
||||
- 等色関数: 論文の式(4)の近似式で求めています。CIEの数表との差は、400nmから
|
||||
700nmまでの範囲で、ピーク値の約1.3%以内です。色を混ぜる計算は、映像の
|
||||
値をそのまま使い、ガンマ補正を取り除く変換はしません。
|
||||
700nmまでの範囲で、ピーク値の約1.3%以内です。「物理ベース」がオフのときの色の
|
||||
足し合わせは、映像の値をそのまま使い、ガンマ補正を取り除く変換はしません。
|
||||
「物理ベース」がオンのときも、「強さ」で元の映像と混ぜる計算は、光の量ではなく
|
||||
映像の値で行います。
|
||||
|
||||
- 放射の上限: 各点の動きの上限は、その点の中心からの距離の半分です。
|
||||
「距離」がそれを超えても、それ以上は動きません。
|
||||
|
||||
- 処理負荷: 画素ごとの映像の読み取りは「ステップ数」に応じて増えるため、
|
||||
ステップ数が多いほど処理は重くなります。
|
||||
ステップ数が多いほど処理は重くなります。「物理ベース」がオンのときは、
|
||||
オフのときより処理が重く、GPUメモリも多く使います。映像とほぼ同じ画素数の
|
||||
画像を、内部で1枚余分に作るためです。
|
||||
|
||||
- 強さ0%と距離0px: 強さが0%のときと、距離が0pxのときは、映像の色を変更しません。
|
||||
|
||||
@@ -52,10 +63,10 @@ Techniques、2013年)に基づきます。
|
||||
大きくなります。直線では、「角度」で決めた向きに沿って「距離」を横の長さと縦の
|
||||
長さに分け、その長さをそれぞれ切り上げて2pxを足した幅だけ、出力範囲を
|
||||
広げます。放射と回転では、ずらした色が描かれる範囲を求め、さらに2pxを足した
|
||||
範囲まで広げます。どの色も描かれなかった画素は透明です。赤、緑、青の成分ごとに
|
||||
映像が覆う割合が違うため、輪郭の外側には一部の成分だけが届いた縁ができ、元の
|
||||
色にその成分が少ないと縁は暗く見えます。不透明度は、成分ごとの割合のうち最も
|
||||
大きいものです。
|
||||
範囲まで広げます。どの色も描かれなかった画素は透明です。「物理ベース」が
|
||||
オフのときは、赤、緑、青の成分ごとに映像が覆う割合が違うため、輪郭の外側には
|
||||
一部の成分だけが届いた縁ができ、元の色にその成分が少ないと縁は暗く見えます。
|
||||
不透明度は、成分ごとの割合のうち最も大きいものです。
|
||||
|
||||
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ新しい
|
||||
正式版を確認します。更新情報を取得できない場合は通知せず、そのまま動作します。
|
||||
|
||||
@@ -27,6 +27,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
|
||||
- [4. 分散](#4-分散)
|
||||
- [5. ステップ数](#5-ステップ数)
|
||||
- [6. 強さと映像の外形](#6-強さと映像の外形)
|
||||
- [7. 物理ベース](#7-物理ベース)
|
||||
5. [パラメータ一覧](#パラメータ一覧)
|
||||
- [色ずれグループ](#色ずれグループ)
|
||||
- [スペクトルグループ](#スペクトルグループ)
|
||||
@@ -46,6 +47,8 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
|
||||
|
||||
重みは、人の目が各波長の光をどんな色として感じるかを表す等色関数から求めます。等色関数の計算は、Wyman, Sloan and Shirleyの論文「Simple Analytic Approximations to the CIE XYZ Color Matching Functions」(Journal of Computer Graphics Techniques、2013年)に基づきます。
|
||||
|
||||
「物理ベース」をオンにすると、赤、緑、青の3つの値を別々にずらす代わりに、映像の色から光のスペクトルを推定し、波長ごとの光をずらして足し合わせます。色の足し合わせと、画素の間の補間は、映像の値を光の量に変換してから行います。既定はオフで、オフのときの結果は、従来のバージョンと同じです。詳しくは「7. 物理ベース」に書いています。
|
||||
|
||||
結果は設定と画素の位置だけから決まります。時間値と乱数は使いません。同じフレームは何度描いても同じ結果になります。
|
||||
|
||||
処理はDirect2Dのカスタムピクセルシェーダーが行います。波長ごとの重みとずれの大きさの表はCPUで求め、シェーダーの定数として渡します。CPUへの画素の読み戻しは行いません。
|
||||
@@ -118,6 +121,22 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
|
||||
|
||||
赤、緑、青の各成分には、波長ごとに違う重みを掛けます。そのため、映像の縁や半透明の部分では、成分ごとに映像が覆う割合が違います。不透明度は、そのうち最も大きい割合になります。輪郭の外側には、赤、緑、青の一部だけが届いた縁ができ、元の色にその成分が少ないと、縁は暗く見えます。
|
||||
|
||||
### 7. 物理ベース
|
||||
|
||||
「物理ベース」は、色の計算の方式を選ぶ項目です。オフでは、赤、緑、青のそれぞれに、波長ごとの重みを掛けて足し合わせます。オンでは、映像の色から推定したスペクトルを使って計算します。
|
||||
|
||||
次の画像は、「距離」を24pxにして、左が「物理ベース」オフ、右がオンの例です。上が直線、下が放射で、ほかの項目は既定値です。
|
||||
|
||||

|
||||
|
||||
映像の値は、まずsRGBの変換式で光の量に変換します。以降の計算は、画素の間の補間も含めて、この光の量で行い、最後にsRGBの値へ戻します。
|
||||
|
||||
画素の赤、緑、青の値から、その画素のスペクトルを推定します。推定は、Mallett and Yukselの論文「Spectral Primary Decomposition for Rendering with sRGB Reflectance」(Eurographics Symposium on Rendering、2019年)の方法に基づきます。赤、緑、青のそれぞれに、波長ごとの大きさを表す基底スペクトルがあり、画素の値を掛けて足したものが、その画素のスペクトルです。基底スペクトルは、sRGBの赤、緑、青の色を標準光源D65の下で再現する条件のもとで、波長方向に滑らかになるよう求めたものです。どの波長でも0以上で、3つを足すとどの波長でも1になります。このため、白は、すべての波長で同じ大きさのスペクトルになり、標準光源D65の白と一致します。
|
||||
|
||||
ずらしたあとのスペクトルは、等色関数と標準光源D65の分布を掛けて足し合わせ、赤、緑、青の値に変換します。この変換は、ステップ数ごとに、基底スペクトルの足し合わせが元の赤、緑、青の値と一致するよう揃えます。このため、「距離」が0pxのときと、色が一様な領域では、ステップ数がいくつでも、映像の色は変わりません。負になる成分は0にします。
|
||||
|
||||
オンのときの不透明度は、次の2つのうち大きいほうです。1つは、波長ごとの映像が覆う割合を、人の目の明るさの感じ方で重み付けして足した値です。もう1つは、描かれた赤、緑、青の最大の値です。輪郭の外側には、一部の波長の光だけが届いた縁ができます。
|
||||
|
||||
---
|
||||
|
||||
## パラメータ一覧
|
||||
@@ -137,6 +156,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 物理ベース | 真偽値 | オフ | オフ / オン | 非対応 | オンにすると、映像の色から推定したスペクトルを動かします。 |
|
||||
| 分散 | 列挙 | 回折格子 | 回折格子 / プリズム | 非対応 | 波長ごとの動きの大きさの決め方です。 |
|
||||
| 基準波長 | 数値 | 550nm | 400〜700nm | 対応 | 位置が動かない色の波長です。 |
|
||||
| ステップ数 | 整数 | 32 | 8〜64 | 非対応 | 400nmから700nmまでを等間隔に分ける波長の数です。 |
|
||||
@@ -148,9 +168,10 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
|
||||
- AviUtl向けのEXO出力には対応していません。
|
||||
- Direct2Dのカスタムエフェクトを作成できない場合は、エフェクトを適用せず入力映像を表示します。
|
||||
- 色のずれの計算には現在のフレームの色と不透明度だけを使用します。履歴フレーム、外部画像、学習済みモデルは使用しません。
|
||||
- 映像の赤、緑、青の3つの値から色を作り直します。映像に含まれない波長の情報を取り出す機能はありません。
|
||||
- 「物理ベース」がオフのときは、映像の赤、緑、青の3つの値から色を作り直します。映像に含まれない波長の情報を取り出す機能はありません。
|
||||
- 「物理ベース」がオンのときは、映像の赤、緑、青の3つの値からスペクトルを推定します。同じ色になるスペクトルは無数にあり、推定したスペクトルは、そのうちの滑らかな1つです。元の映像が実際に出していた光のスペクトルとは違うことがあります。
|
||||
- 等色関数は、論文の式(4)の近似式で求めています。CIEの数表との差は、400nmから700nmまでの範囲で、ピーク値の約1.3%以内です。
|
||||
- 色を混ぜる計算は、映像の値をそのまま使います。ガンマ補正を取り除く変換はしません。
|
||||
- 「物理ベース」がオフのときの色の足し合わせは、映像の値をそのまま使います。ガンマ補正を取り除く変換はしません。「物理ベース」がオンのときも、「強さ」で元の映像と混ぜる計算は、光の量ではなく映像の値で行います。
|
||||
- 放射では、各点の動きの上限が、その点の中心からの距離の半分です。「距離」がそれを超えても、それ以上は動きません。
|
||||
- 色をずらした映像は元の外形の外へ出るため、出力範囲は元の映像より大きくなります。
|
||||
|
||||
@@ -158,10 +179,10 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
|
||||
|
||||
## 注意事項
|
||||
|
||||
- 処理負荷: 画素ごとの映像の読み取りは「ステップ数」に応じて増えるため、ステップ数が多いほど処理は重くなります。
|
||||
- 処理負荷: 画素ごとの映像の読み取りは「ステップ数」に応じて増えるため、ステップ数が多いほど処理は重くなります。「物理ベース」がオンのときは、オフのときより処理が重く、GPUメモリも多く使います。映像とほぼ同じ画素数の画像を、内部で1枚余分に作るためです。
|
||||
- 強さ0%と距離0px: 強さが0%のときと、距離が0pxのときは、映像の色を変更しません。
|
||||
- 再現性: 結果は設定と画素の位置だけから決まります。時間値と乱数は使いません。同じフレームは何度描いても同じ結果になります。
|
||||
- 透明部分: 色をずらした映像は元の外形の外へはみ出すため、出力範囲は元の映像より大きくなります。赤、緑、青の成分ごとに映像が覆う割合が違うため、輪郭の外側には一部の成分だけが届いた縁ができ、元の色にその成分が少ないと縁は暗く見えます。不透明度は、成分ごとの割合のうち最も大きいものです。
|
||||
- 透明部分: 色をずらした映像は元の外形の外へはみ出すため、出力範囲は元の映像より大きくなります。「物理ベース」がオフのときは、赤、緑、青の成分ごとに映像が覆う割合が違うため、輪郭の外側には一部の成分だけが届いた縁ができ、元の色にその成分が少ないと縁は暗く見えます。不透明度は、成分ごとの割合のうち最も大きいものです。
|
||||
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ新しい正式版を確認します。更新情報を取得できない場合は通知せず、そのまま動作します。プレリリースは通知の対象に含めません。
|
||||
- 不具合の自動送信: 想定していない例外が起きたときは、その内容を開発者へ自動で送信します。内容は「不具合の報告」に書いています。
|
||||
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを作成することを推奨します。
|
||||
|
||||
@@ -44,6 +44,50 @@ internal static class HarnessCases
|
||||
yield return ("reference-650", Create(effect => effect.ReferenceWavelength.Values[0].Value = 650), [0]);
|
||||
yield return ("steps-8", Create(effect => effect.Steps = 8), [0]);
|
||||
yield return ("strength-50", Create(effect => effect.Strength.Values[0].Value = 50), [0]);
|
||||
yield return ("physical", Create(effect => effect.Physical = true), [0]);
|
||||
yield return ("physical-distance-24", Create(effect =>
|
||||
{
|
||||
effect.Physical = true;
|
||||
effect.Distance.Values[0].Value = 24;
|
||||
}), [0]);
|
||||
yield return ("physical-distance-100-steps-64", Create(effect =>
|
||||
{
|
||||
effect.Physical = true;
|
||||
effect.Distance.Values[0].Value = 100;
|
||||
effect.Steps = 64;
|
||||
}), [0]);
|
||||
yield return ("physical-radial-24", Create(effect =>
|
||||
{
|
||||
effect.Physical = true;
|
||||
effect.Mode = ShiftMode.Radial;
|
||||
effect.Distance.Values[0].Value = 24;
|
||||
}), [0]);
|
||||
yield return ("physical-rotational-24", Create(effect =>
|
||||
{
|
||||
effect.Physical = true;
|
||||
effect.Mode = ShiftMode.Rotational;
|
||||
effect.Distance.Values[0].Value = 24;
|
||||
}), [0]);
|
||||
yield return ("physical-prism", Create(effect =>
|
||||
{
|
||||
effect.Physical = true;
|
||||
effect.Dispersion = DispersionLaw.Prism;
|
||||
}), [0]);
|
||||
yield return ("physical-reference-450", Create(effect =>
|
||||
{
|
||||
effect.Physical = true;
|
||||
effect.ReferenceWavelength.Values[0].Value = 450;
|
||||
}), [0]);
|
||||
yield return ("physical-steps-8", Create(effect =>
|
||||
{
|
||||
effect.Physical = true;
|
||||
effect.Steps = 8;
|
||||
}), [0]);
|
||||
yield return ("physical-strength-50", Create(effect =>
|
||||
{
|
||||
effect.Physical = true;
|
||||
effect.Strength.Values[0].Value = 50;
|
||||
}), [0]);
|
||||
}
|
||||
|
||||
public static IEnumerable<(string Name, Func<SpectrumColorShiftEffect> Create, Action<SpectrumColorShiftEffect> Change, int Frame)> Transitions()
|
||||
@@ -60,6 +104,9 @@ internal static class HarnessCases
|
||||
yield return ("reference-550-to-450", () => Create(), effect => effect.ReferenceWavelength.Values[0].Value = 450, 0);
|
||||
yield return ("steps-32-to-8", () => Create(), effect => effect.Steps = 8, 0);
|
||||
yield return ("steps-8-to-64", () => Create(effect => effect.Steps = 8), effect => effect.Steps = 64, 0);
|
||||
yield return ("physical-off-to-on", () => Create(), effect => effect.Physical = true, 0);
|
||||
yield return ("physical-on-to-off", () => Create(effect => effect.Physical = true), effect => effect.Physical = false, 0);
|
||||
yield return ("physical-steps-32-to-8", () => Create(effect => effect.Physical = true), effect => effect.Steps = 8, 0);
|
||||
}
|
||||
|
||||
public static IEnumerable<(string Name, SpectrumColorShiftEffect Effect)> Benchmarks()
|
||||
@@ -76,6 +123,30 @@ internal static class HarnessCases
|
||||
effect.Mode = ShiftMode.Rotational;
|
||||
effect.Distance.Values[0].Value = 24;
|
||||
}));
|
||||
yield return ("physical", Create(effect => effect.Physical = true));
|
||||
yield return ("physical-steps-64", Create(effect =>
|
||||
{
|
||||
effect.Physical = true;
|
||||
effect.Steps = 64;
|
||||
}));
|
||||
yield return ("physical-distance-48-steps-64", Create(effect =>
|
||||
{
|
||||
effect.Physical = true;
|
||||
effect.Distance.Values[0].Value = 48;
|
||||
effect.Steps = 64;
|
||||
}));
|
||||
yield return ("physical-radial-24", Create(effect =>
|
||||
{
|
||||
effect.Physical = true;
|
||||
effect.Mode = ShiftMode.Radial;
|
||||
effect.Distance.Values[0].Value = 24;
|
||||
}));
|
||||
yield return ("physical-rotational-24", Create(effect =>
|
||||
{
|
||||
effect.Physical = true;
|
||||
effect.Mode = ShiftMode.Rotational;
|
||||
effect.Distance.Values[0].Value = 24;
|
||||
}));
|
||||
}
|
||||
|
||||
static SpectrumColorShiftEffect Create(Action<SpectrumColorShiftEffect>? configure = null)
|
||||
|
||||
@@ -115,6 +115,69 @@
|
||||
0
|
||||
],
|
||||
"hash": "C2D79B67A9585C913BFBB67E70038229CC7D9596CAB67FFD366FAA0C7BCF5F2D"
|
||||
},
|
||||
{
|
||||
"name": "physical",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "872E6C69B6384487C4455B575FED039B973D8F0CD0C86E83476DB7F8C4D6C5E9"
|
||||
},
|
||||
{
|
||||
"name": "physical-distance-24",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "C3EFCE6A5A4E9A737926D359AF302FFA10D15ED56E58EA8EB040ADAEF6F083D7"
|
||||
},
|
||||
{
|
||||
"name": "physical-distance-100-steps-64",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "514B1C1FF62D4C5F28AFC9D4158B5182B7A55E7CDBFC1D02531D86E22C0019AC"
|
||||
},
|
||||
{
|
||||
"name": "physical-radial-24",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "09C9FFD797F751E21CDB8A1AC4487193D0C2701FDD404F91B3AD452D1D5B61C1"
|
||||
},
|
||||
{
|
||||
"name": "physical-rotational-24",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "7A86209757529922BB33B2C5060E80A7DEC7D853F1F45536FEEB09C53D15A2D2"
|
||||
},
|
||||
{
|
||||
"name": "physical-prism",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "F118C51CD7930A110A7842776BF9F55035FF91A83974FE525E632101BC23AF3C"
|
||||
},
|
||||
{
|
||||
"name": "physical-reference-450",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "4D5C824E9F9A790F546F27F2D6DB891C4AA10CFF3AAF0F5A64E92403C760BDDD"
|
||||
},
|
||||
{
|
||||
"name": "physical-steps-8",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "160C24673BB43AE035287C22DB8366D0DB89D9D27CA65F9473E3DF3469BB747C"
|
||||
},
|
||||
{
|
||||
"name": "physical-strength-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "9491C6D44879AD71A7BAAA7AB7330D31507003C89F06179B056AE8415D19C7A0"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -144,13 +144,35 @@
|
||||
</FxCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<FxCompile Include="SpectrumColorShift.hlsl">
|
||||
<FxCompile Include="SpectrumColorShiftLinearize.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>
|
||||
<ItemGroup>
|
||||
<None Include="SpectrumColorShift.hlsl" />
|
||||
<None Include="SpectrumColorShiftPhysical.hlsl" />
|
||||
<None Include="Srgb.hlsli" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<StepCount Include="8;12;16;20;24;28;32;36;40;44;48;52;56;60;64" />
|
||||
</ItemGroup>
|
||||
<Target Name="AddStepCountShaders" BeforeTargets="FxCompile">
|
||||
<ItemGroup>
|
||||
<FxCompile Include="SpectrumColorShift.hlsl">
|
||||
<ShaderType>Pixel</ShaderType>
|
||||
<PreprocessorDefinitions>StepCount=%(StepCount.Identity)</PreprocessorDefinitions>
|
||||
<ObjectFileOutput>$(OutDir)SpectrumColorShift%(StepCount.Identity).cso</ObjectFileOutput>
|
||||
</FxCompile>
|
||||
<FxCompile Include="SpectrumColorShiftPhysical.hlsl">
|
||||
<ShaderType>Pixel</ShaderType>
|
||||
<PreprocessorDefinitions>StepCount=%(StepCount.Identity)</PreprocessorDefinitions>
|
||||
<ObjectFileOutput>$(OutDir)SpectrumColorShiftPhysical%(StepCount.Identity).cso</ObjectFileOutput>
|
||||
</FxCompile>
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
|
||||
@@ -15,8 +15,19 @@
|
||||
</Filter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<FxCompile Include="SpectrumColorShift.hlsl">
|
||||
<FxCompile Include="SpectrumColorShiftLinearize.hlsl">
|
||||
<Filter>ソース ファイル</Filter>
|
||||
</FxCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="SpectrumColorShift.hlsl">
|
||||
<Filter>ソース ファイル</Filter>
|
||||
</None>
|
||||
<None Include="SpectrumColorShiftPhysical.hlsl">
|
||||
<Filter>ソース ファイル</Filter>
|
||||
</None>
|
||||
<None Include="Srgb.hlsli">
|
||||
<Filter>ヘッダー ファイル</Filter>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,3 +1,7 @@
|
||||
#ifndef StepCount
|
||||
#error StepCount must be defined by the build.
|
||||
#endif
|
||||
|
||||
Texture2D SourceTexture : register(t0);
|
||||
SamplerState SourceSampler : register(s0);
|
||||
|
||||
@@ -69,6 +73,29 @@ void Accumulate(float4 entry, float4 shifted, inout float3 color, inout float3 c
|
||||
coverage += entry.rgb * shifted.a;
|
||||
}
|
||||
|
||||
void AccumulateRadial(int index, float2 uv, float2 offsetStep, float rate, inout float3 color, inout float3 coverage)
|
||||
{
|
||||
float4 entry = samples[index];
|
||||
float scale = clamp(entry.w * rate, -MaxRadialShift, MaxRadialShift);
|
||||
Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv - offsetStep * scale, 0), color, coverage);
|
||||
}
|
||||
|
||||
void AccumulateRotational(int index, float2 uv, float2 offset, float2 pixelStep, float rate, inout float3 color, inout float3 coverage)
|
||||
{
|
||||
float4 entry = samples[index];
|
||||
float sine;
|
||||
float cosine;
|
||||
sincos(entry.w * rate, sine, cosine);
|
||||
float2 delta = float2((cosine - 1.0) * offset.x + sine * offset.y, (cosine - 1.0) * offset.y - sine * offset.x);
|
||||
Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv + delta * pixelStep, 0), color, coverage);
|
||||
}
|
||||
|
||||
void AccumulateLinear(int index, float2 uv, float2 stride, inout float3 color, inout float3 coverage)
|
||||
{
|
||||
float4 entry = samples[index];
|
||||
Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv - entry.w * stride, 0), color, coverage);
|
||||
}
|
||||
|
||||
float4 Resolve(float3 color, float3 coverage)
|
||||
{
|
||||
float alpha = max(coverage.r, max(coverage.g, coverage.b));
|
||||
@@ -102,39 +129,25 @@ float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
|
||||
float2 offsetStep = offset * pixelStep;
|
||||
float rate = shiftDistance / radius;
|
||||
|
||||
[loop]
|
||||
for (int index = 0; index < steps; index++)
|
||||
{
|
||||
float4 entry = samples[index];
|
||||
float scale = clamp(entry.w * rate, -MaxRadialShift, MaxRadialShift);
|
||||
Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv - offsetStep * scale, 0), color, coverage);
|
||||
}
|
||||
[unroll]
|
||||
for (int index = 0; index < StepCount; index++)
|
||||
AccumulateRadial(index, uv, offsetStep, rate, color, coverage);
|
||||
}
|
||||
else if (mode == ModeRotational)
|
||||
{
|
||||
float rate = shiftDistance / radius;
|
||||
|
||||
[loop]
|
||||
for (int index = 0; index < steps; index++)
|
||||
{
|
||||
float4 entry = samples[index];
|
||||
float sine;
|
||||
float cosine;
|
||||
sincos(entry.w * rate, sine, cosine);
|
||||
float2 delta = float2((cosine - 1.0) * offset.x + sine * offset.y, (cosine - 1.0) * offset.y - sine * offset.x);
|
||||
Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv + delta * pixelStep, 0), color, coverage);
|
||||
}
|
||||
[unroll]
|
||||
for (int index = 0; index < StepCount; index++)
|
||||
AccumulateRotational(index, uv, offset, pixelStep, rate, color, coverage);
|
||||
}
|
||||
else
|
||||
{
|
||||
float2 stride = shiftDistance * direction * pixelStep;
|
||||
|
||||
[loop]
|
||||
for (int index = 0; index < steps; index++)
|
||||
{
|
||||
float4 entry = samples[index];
|
||||
Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv - entry.w * stride, 0), color, coverage);
|
||||
}
|
||||
[unroll]
|
||||
for (int index = 0; index < StepCount; index++)
|
||||
AccumulateLinear(index, uv, stride, color, coverage);
|
||||
}
|
||||
|
||||
return Resolve(color, coverage);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
#include "Srgb.hlsli"
|
||||
|
||||
Texture2D SourceTexture : register(t0);
|
||||
SamplerState SourceSampler : register(s0);
|
||||
|
||||
float4 main(
|
||||
float4 position : SV_POSITION,
|
||||
float4 scenePosition : SCENE_POSITION,
|
||||
float4 uv0 : TEXCOORD0
|
||||
) : SV_TARGET
|
||||
{
|
||||
return DecodePremultiplied(SourceTexture.SampleLevel(SourceSampler, uv0.xy, 0));
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
#ifndef StepCount
|
||||
#error StepCount must be defined by the build.
|
||||
#endif
|
||||
|
||||
#include "Srgb.hlsli"
|
||||
|
||||
Texture2D LinearTexture : register(t1);
|
||||
SamplerState LinearSampler : register(s1);
|
||||
|
||||
static const int MaxSteps = 64;
|
||||
static const int TableSize = 128;
|
||||
static const int ModeRadial = 2;
|
||||
static const int ModeRotational = 4;
|
||||
static const float MaxRadialShift = 0.5;
|
||||
static const float InteriorGuard = 0.51;
|
||||
|
||||
cbuffer Constants : register(b0)
|
||||
{
|
||||
float4 inputBounds : packoffset(c0);
|
||||
float2 direction : packoffset(c1.x);
|
||||
float2 center : packoffset(c1.z);
|
||||
float shiftDistance : packoffset(c2.x);
|
||||
float radius : packoffset(c2.y);
|
||||
float strength : packoffset(c2.z);
|
||||
int mode : packoffset(c2.w);
|
||||
int steps : packoffset(c3.x);
|
||||
float spreadScale : packoffset(c3.y);
|
||||
float4 samples[TableSize] : packoffset(c4);
|
||||
};
|
||||
|
||||
float2 SamplePosition(float2 scenePosition, float2 offset, float coefficient)
|
||||
{
|
||||
float shift = coefficient * shiftDistance;
|
||||
|
||||
if (mode == ModeRadial)
|
||||
{
|
||||
float scale = 1.0 - clamp(shift / radius, -MaxRadialShift, MaxRadialShift);
|
||||
return center + offset * scale;
|
||||
}
|
||||
|
||||
if (mode == ModeRotational)
|
||||
{
|
||||
float sine;
|
||||
float cosine;
|
||||
sincos(shift / radius, sine, cosine);
|
||||
return center + float2(cosine * offset.x + sine * offset.y, cosine * offset.y - sine * offset.x);
|
||||
}
|
||||
|
||||
return scenePosition - shift * direction;
|
||||
}
|
||||
|
||||
float2 Spread(float2 offset)
|
||||
{
|
||||
if (mode == ModeRadial)
|
||||
return abs(offset) * spreadScale;
|
||||
|
||||
if (mode == ModeRotational)
|
||||
return length(offset) * spreadScale;
|
||||
|
||||
return abs(shiftDistance) * abs(direction);
|
||||
}
|
||||
|
||||
float4 SampleCovered(float2 uv, float2 pixelStep, float2 scenePosition, float2 target)
|
||||
{
|
||||
float2 minimum = inputBounds.xy + 0.5;
|
||||
float2 maximum = inputBounds.zw - 0.5;
|
||||
float2 clamped = clamp(target, minimum, maximum);
|
||||
float4 color = LinearTexture.SampleLevel(LinearSampler, uv + (clamped - scenePosition) * pixelStep, 0);
|
||||
float2 coverage = saturate(min(target - inputBounds.xy, inputBounds.zw - target) + 0.5);
|
||||
return color * (coverage.x * coverage.y);
|
||||
}
|
||||
|
||||
void Accumulate(float4 gain, float3 basis, float4 shifted, inout float3 color, inout float alpha)
|
||||
{
|
||||
color += gain.rgb * dot(basis, shifted.rgb);
|
||||
alpha += gain.w * shifted.a;
|
||||
}
|
||||
|
||||
float4 Resolve(float3 color, float alpha)
|
||||
{
|
||||
float3 positive = max(color, 0.0);
|
||||
float resolved = saturate(max(alpha, max(positive.r, max(positive.g, positive.b))));
|
||||
return EncodePremultiplied(float4(positive, resolved));
|
||||
}
|
||||
|
||||
void AccumulateCovered(int index, float2 uv, float2 pixelStep, float2 scenePosition, float2 offset, inout float3 color, inout float alpha)
|
||||
{
|
||||
float4 gain = samples[index * 2];
|
||||
float4 basis = samples[index * 2 + 1];
|
||||
Accumulate(gain, basis.rgb, SampleCovered(uv, pixelStep, scenePosition, SamplePosition(scenePosition, offset, basis.w)), color, alpha);
|
||||
}
|
||||
|
||||
void AccumulateRadial(int index, float2 uv, float2 offsetStep, float rate, inout float3 color, inout float alpha)
|
||||
{
|
||||
float4 gain = samples[index * 2];
|
||||
float4 basis = samples[index * 2 + 1];
|
||||
float scale = clamp(basis.w * rate, -MaxRadialShift, MaxRadialShift);
|
||||
Accumulate(gain, basis.rgb, LinearTexture.SampleLevel(LinearSampler, uv - offsetStep * scale, 0), color, alpha);
|
||||
}
|
||||
|
||||
void AccumulateRotational(int index, float2 uv, float2 offset, float2 pixelStep, float rate, inout float3 color, inout float alpha)
|
||||
{
|
||||
float4 gain = samples[index * 2];
|
||||
float4 basis = samples[index * 2 + 1];
|
||||
float sine;
|
||||
float cosine;
|
||||
sincos(basis.w * rate, sine, cosine);
|
||||
float2 delta = float2((cosine - 1.0) * offset.x + sine * offset.y, (cosine - 1.0) * offset.y - sine * offset.x);
|
||||
Accumulate(gain, basis.rgb, LinearTexture.SampleLevel(LinearSampler, uv + delta * pixelStep, 0), color, alpha);
|
||||
}
|
||||
|
||||
void AccumulateLinear(int index, float2 uv, float2 stride, inout float3 color, inout float alpha)
|
||||
{
|
||||
float4 gain = samples[index * 2];
|
||||
float4 basis = samples[index * 2 + 1];
|
||||
Accumulate(gain, basis.rgb, LinearTexture.SampleLevel(LinearSampler, uv - basis.w * stride, 0), color, alpha);
|
||||
}
|
||||
|
||||
float4 GatherCovered(float2 uv, float2 pixelStep, float2 scenePosition)
|
||||
{
|
||||
float2 offset = scenePosition - center;
|
||||
float3 color = 0.0;
|
||||
float alpha = 0.0;
|
||||
|
||||
[loop]
|
||||
for (int index = 0; index < steps; index++)
|
||||
AccumulateCovered(index, uv, pixelStep, scenePosition, offset, color, alpha);
|
||||
|
||||
return Resolve(color, alpha);
|
||||
}
|
||||
|
||||
float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
|
||||
{
|
||||
float2 offset = scenePosition - center;
|
||||
float3 color = 0.0;
|
||||
float alpha = 0.0;
|
||||
|
||||
if (mode == ModeRadial)
|
||||
{
|
||||
float2 offsetStep = offset * pixelStep;
|
||||
float rate = shiftDistance / radius;
|
||||
|
||||
[unroll]
|
||||
for (int index = 0; index < StepCount; index++)
|
||||
AccumulateRadial(index, uv, offsetStep, rate, color, alpha);
|
||||
}
|
||||
else if (mode == ModeRotational)
|
||||
{
|
||||
float rate = shiftDistance / radius;
|
||||
|
||||
[unroll]
|
||||
for (int index = 0; index < StepCount; index++)
|
||||
AccumulateRotational(index, uv, offset, pixelStep, rate, color, alpha);
|
||||
}
|
||||
else
|
||||
{
|
||||
float2 stride = shiftDistance * direction * pixelStep;
|
||||
|
||||
[unroll]
|
||||
for (int index = 0; index < StepCount; index++)
|
||||
AccumulateLinear(index, uv, stride, color, alpha);
|
||||
}
|
||||
|
||||
return Resolve(color, alpha);
|
||||
}
|
||||
|
||||
float4 main(
|
||||
float4 position : SV_POSITION,
|
||||
float4 scenePosition : SCENE_POSITION,
|
||||
float4 uv0 : TEXCOORD0,
|
||||
float4 uv1 : TEXCOORD1
|
||||
) : SV_TARGET
|
||||
{
|
||||
if (shiftDistance == 0.0 || strength <= 0.0)
|
||||
return EncodePremultiplied(SampleCovered(uv1.xy, uv1.zw, scenePosition.xy, scenePosition.xy));
|
||||
|
||||
float2 margin = Spread(scenePosition.xy - center) + InteriorGuard;
|
||||
bool inside = all(scenePosition.xy >= inputBounds.xy + margin) && all(scenePosition.xy <= inputBounds.zw - margin);
|
||||
|
||||
float4 result;
|
||||
[branch]
|
||||
if (inside)
|
||||
result = GatherInside(uv1.xy, uv1.zw, scenePosition.xy);
|
||||
else
|
||||
result = GatherCovered(uv1.xy, uv1.zw, scenePosition.xy);
|
||||
|
||||
if (strength >= 1.0)
|
||||
return result;
|
||||
|
||||
return lerp(EncodePremultiplied(SampleCovered(uv1.xy, uv1.zw, scenePosition.xy, scenePosition.xy)), result, strength);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
static const float DecodeThreshold = 0.04045;
|
||||
static const float EncodeThreshold = 0.0031308;
|
||||
static const float LowSlope = 12.92;
|
||||
static const float Offset = 0.055;
|
||||
static const float Scale = 1.055;
|
||||
static const float Exponent = 2.4;
|
||||
|
||||
float3 Decode(float3 encoded)
|
||||
{
|
||||
float3 low = encoded / LowSlope;
|
||||
float3 high = pow((encoded + Offset) / Scale, Exponent);
|
||||
return encoded <= DecodeThreshold ? low : high;
|
||||
}
|
||||
|
||||
float3 Encode(float3 linearColor)
|
||||
{
|
||||
float3 low = linearColor * LowSlope;
|
||||
float3 high = Scale * pow(linearColor, 1.0 / Exponent) - Offset;
|
||||
return linearColor <= EncodeThreshold ? low : high;
|
||||
}
|
||||
|
||||
float3 Unpremultiply(float4 premultiplied)
|
||||
{
|
||||
return premultiplied.a > 0.0 ? saturate(premultiplied.rgb / premultiplied.a) : 0.0;
|
||||
}
|
||||
|
||||
float4 DecodePremultiplied(float4 encoded)
|
||||
{
|
||||
return float4(Decode(Unpremultiply(encoded)) * encoded.a, encoded.a);
|
||||
}
|
||||
|
||||
float4 EncodePremultiplied(float4 linearColor)
|
||||
{
|
||||
return float4(Encode(Unpremultiply(linearColor)) * linearColor.a, linearColor.a);
|
||||
}
|
||||
@@ -46,6 +46,7 @@ public sealed class AllocationTests
|
||||
impl.Dispersion = step & 1;
|
||||
impl.ReferenceWavelength = 400f + step % 300;
|
||||
impl.Steps = Spectrum.MinSteps + step % (Spectrum.MaxSteps - Spectrum.MinSteps + 1);
|
||||
impl.Physical = step & 1;
|
||||
});
|
||||
|
||||
Assert.Equal(0, allocated);
|
||||
@@ -67,4 +68,21 @@ public sealed class AllocationTests
|
||||
|
||||
Assert.Equal(0, allocated);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(DispersionLaw.Grating)]
|
||||
[InlineData(DispersionLaw.Prism)]
|
||||
public void FillingTheSpectralTableAllocatesNothing(DispersionLaw law)
|
||||
{
|
||||
var table = new Vector4[Spectrum.SpectralTableLength];
|
||||
var step = 0;
|
||||
|
||||
var allocated = Allocation.Of(() =>
|
||||
{
|
||||
step++;
|
||||
Spectrum.FillSpectral(table, Spectrum.MinSteps + step % (Spectrum.MaxSteps - Spectrum.MinSteps + 1), 400f + step % 300, law);
|
||||
});
|
||||
|
||||
Assert.Equal(0, allocated);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace SpectrumColorShift.Tests;
|
||||
|
||||
internal sealed class SpectralReferenceRenderer
|
||||
{
|
||||
readonly SourceImage source;
|
||||
readonly ShiftSettings settings;
|
||||
readonly Vector4[] table = new Vector4[Spectrum.SpectralTableLength];
|
||||
readonly Vector2 direction;
|
||||
readonly Vector2 center;
|
||||
readonly float radius;
|
||||
readonly int steps;
|
||||
|
||||
public SpectralReferenceRenderer(SourceImage source, ShiftSettings settings)
|
||||
{
|
||||
this.source = source;
|
||||
this.settings = settings;
|
||||
steps = Spectrum.ClampSteps(settings.Steps);
|
||||
Spectrum.FillSpectral(table, steps, settings.ReferenceWavelength, settings.Dispersion);
|
||||
var radians = settings.Angle * MathF.PI / 180f;
|
||||
direction = new Vector2(MathF.Cos(radians), MathF.Sin(radians));
|
||||
var rect = new Vortice.RawRect(0, 0, source.Width, source.Height);
|
||||
center = ShiftGeometry.Center(rect, settings.Center);
|
||||
radius = ShiftGeometry.Radius(rect, center);
|
||||
}
|
||||
|
||||
public Vector4 Pixel(int x, int y)
|
||||
{
|
||||
var position = new Vector2(x + 0.5f, y + 0.5f);
|
||||
var original = Srgb.EncodePremultiplied(Covered(position));
|
||||
if (settings.Distance == 0f || settings.Strength <= 0f)
|
||||
return original;
|
||||
|
||||
var (color, alpha) = Accumulated(position);
|
||||
var positive = Vector3.Max(color, Vector3.Zero);
|
||||
var resolved = Math.Clamp(Math.Max(alpha, Math.Max(positive.X, Math.Max(positive.Y, positive.Z))), 0f, 1f);
|
||||
var result = Srgb.EncodePremultiplied(new Vector4(positive, resolved));
|
||||
|
||||
return Vector4.Lerp(original, result, Math.Clamp(settings.Strength, 0f, 1f));
|
||||
}
|
||||
|
||||
public (Vector3 Color, float Alpha) Accumulated(Vector2 position)
|
||||
{
|
||||
var color = Vector3.Zero;
|
||||
var alpha = 0f;
|
||||
for (var index = 0; index < steps; index++)
|
||||
{
|
||||
var gain = table[index * Spectrum.EntriesPerStep];
|
||||
var basis = table[index * Spectrum.EntriesPerStep + 1];
|
||||
var target = ShiftReference.SamplePosition(settings.Mode, position, basis.W, settings.Distance, direction, center, radius);
|
||||
var lit = Covered(target);
|
||||
color += new Vector3(gain.X, gain.Y, gain.Z) * Vector3.Dot(new Vector3(basis.X, basis.Y, basis.Z), new Vector3(lit.X, lit.Y, lit.Z));
|
||||
alpha += gain.W * lit.W;
|
||||
}
|
||||
|
||||
return (color, alpha);
|
||||
}
|
||||
|
||||
Vector4 Covered(Vector2 target)
|
||||
{
|
||||
var (light, coverage) = Sample(target);
|
||||
|
||||
return light * coverage;
|
||||
}
|
||||
|
||||
(Vector4 Light, float Coverage) Sample(Vector2 target)
|
||||
{
|
||||
var size = new Vector2(source.Width, source.Height);
|
||||
var clamped = Vector2.Clamp(target, new Vector2(0.5f), size - new Vector2(0.5f));
|
||||
var edge = Vector2.Min(target, size - target) + new Vector2(0.5f);
|
||||
var coverage = Vector2.Clamp(edge, Vector2.Zero, Vector2.One);
|
||||
|
||||
return (Bilinear(clamped), coverage.X * coverage.Y);
|
||||
}
|
||||
|
||||
Vector4 Bilinear(Vector2 position)
|
||||
{
|
||||
var shifted = position - new Vector2(0.5f);
|
||||
var x = (int)MathF.Floor(shifted.X);
|
||||
var y = (int)MathF.Floor(shifted.Y);
|
||||
var fraction = new Vector2(shifted.X - x, shifted.Y - y);
|
||||
|
||||
return Vector4.Lerp(
|
||||
Vector4.Lerp(Texel(x, y), Texel(x + 1, y), fraction.X),
|
||||
Vector4.Lerp(Texel(x, y + 1), Texel(x + 1, y + 1), fraction.X),
|
||||
fraction.Y);
|
||||
}
|
||||
|
||||
Vector4 Texel(int x, int y)
|
||||
{
|
||||
var pixel = source[Math.Clamp(x, 0, source.Width - 1), Math.Clamp(y, 0, source.Height - 1)];
|
||||
|
||||
return Srgb.DecodePremultiplied(new Vector4(pixel.Red, pixel.Green, pixel.Blue, pixel.Alpha) / 255f);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,750 @@
|
||||
using System.Numerics;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace SpectrumColorShift.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class SpectralRenderingTests
|
||||
{
|
||||
const int Seam = 32;
|
||||
|
||||
static ShiftSettings Settings(
|
||||
ShiftMode Mode = ShiftMode.Linear,
|
||||
float Distance = 8f,
|
||||
float Angle = 0f,
|
||||
Vector2 Center = default,
|
||||
float Strength = 1f,
|
||||
DispersionLaw Dispersion = DispersionLaw.Grating,
|
||||
float ReferenceWavelength = 550f,
|
||||
int Steps = 32)
|
||||
=> new(Mode, Distance, Angle, Center, Strength, Dispersion, ReferenceWavelength, Steps, true);
|
||||
|
||||
static Bgra HalfAndHalf(int x, int y) => x < Seam ? Bgra.Opaque(255, 255, 255) : Bgra.Opaque(0, 0, 0);
|
||||
|
||||
static Bgra TopAndBottom(int x, int y) => y < Seam ? Bgra.Opaque(255, 255, 255) : Bgra.Opaque(0, 0, 0);
|
||||
|
||||
static Bgra Stripes(int x, int y) => Math.Abs(x + 0.5 - 64) is >= 30 and < 34 ? Bgra.Opaque(255, 255, 255) : Bgra.Opaque(0, 0, 0);
|
||||
|
||||
static Bgra Dot(int x, int y) => Math.Abs(x + 0.5 - 104) < 3 && Math.Abs(y + 0.5 - 64) < 3 ? Bgra.Opaque(255, 255, 255) : Bgra.Opaque(0, 0, 0);
|
||||
|
||||
static Bgra Textured(int x, int y)
|
||||
{
|
||||
if ((x / 8 + y / 8) % 5 == 4)
|
||||
return Bgra.Transparent;
|
||||
|
||||
return new Bgra((byte)(40 + x * 3 % 200), (byte)(30 + y * 5 % 210), (byte)(255 - (x + y) * 2 % 220), (byte)(110 + (x * 7 + y * 11) % 146));
|
||||
}
|
||||
|
||||
static Bgra PointSymmetric(int x, int y, int mirroredX, int mirroredY)
|
||||
{
|
||||
var value = Math.Min(x * 3 + y * 5, mirroredX * 3 + mirroredY * 5);
|
||||
|
||||
return Bgra.Opaque((byte)(40 + value * 7 % 200), (byte)(30 + value * 11 % 210), (byte)(255 - value * 13 % 220));
|
||||
}
|
||||
|
||||
static Rendering Render(IGraphicsDevicesAndContext devices, SourceImage source, ShiftSettings settings)
|
||||
{
|
||||
using var effect = new SpectrumColorShiftCustomEffect(devices);
|
||||
effect.SetInput(0, source.Bitmap, true);
|
||||
settings.Apply(effect);
|
||||
using var output = effect.Output;
|
||||
|
||||
return Rendering.Capture(devices, output);
|
||||
}
|
||||
|
||||
static bool WithinRounding(Bgra expected, Bgra actual, int tolerance = 1)
|
||||
=> Math.Abs(expected.Blue - actual.Blue) <= tolerance && Math.Abs(expected.Green - actual.Green) <= tolerance && Math.Abs(expected.Red - actual.Red) <= tolerance && Math.Abs(expected.Alpha - actual.Alpha) <= tolerance;
|
||||
|
||||
static double DistanceToBorder(SourceImage source, int x, int y)
|
||||
=> Math.Min(Math.Min(x, source.Width - 1 - x), Math.Min(y, source.Height - 1 - y));
|
||||
|
||||
static double Crossing(Func<int, byte> value, int from, int to)
|
||||
{
|
||||
for (var index = from; index < to; index++)
|
||||
{
|
||||
double a = value(index);
|
||||
double b = value(index + 1);
|
||||
if (a >= 127.5 && b < 127.5)
|
||||
return index + 0.5 + (a - 127.5) / (a - b);
|
||||
}
|
||||
|
||||
return double.NaN;
|
||||
}
|
||||
|
||||
static double EdgeWidth(Func<int, byte> value, int from, int to)
|
||||
{
|
||||
double high = double.NaN;
|
||||
double low = double.NaN;
|
||||
for (var index = from; index < to; index++)
|
||||
{
|
||||
double a = value(index);
|
||||
double b = value(index + 1);
|
||||
if (double.IsNaN(high) && a >= 230 && b < 230)
|
||||
high = index + 0.5 + (a - 230) / (a - b);
|
||||
if (double.IsNaN(low) && a >= 25 && b < 25)
|
||||
low = index + 0.5 + (a - 25) / (a - b);
|
||||
}
|
||||
|
||||
return low - high;
|
||||
}
|
||||
|
||||
static Func<int, byte> ExpectedProfile(ShiftSettings settings, int channel, float axisDirection)
|
||||
{
|
||||
var table = new Vector4[Spectrum.SpectralTableLength];
|
||||
Spectrum.FillSpectral(table, settings.Steps, settings.ReferenceWavelength, settings.Dispersion);
|
||||
var steps = Spectrum.ClampSteps(settings.Steps);
|
||||
|
||||
return index =>
|
||||
{
|
||||
var sum = 0d;
|
||||
for (var step = 0; step < steps; step++)
|
||||
{
|
||||
var gain = table[step * Spectrum.EntriesPerStep];
|
||||
var basis = table[step * Spectrum.EntriesPerStep + 1];
|
||||
var position = index + 0.5 - basis.W * settings.Distance * axisDirection;
|
||||
var value = Math.Clamp(Seam + 0.5 - position, 0d, 1d);
|
||||
sum += (channel switch { 0 => gain.X, 1 => gain.Y, _ => gain.Z }) * (basis.X + basis.Y + basis.Z) * value;
|
||||
}
|
||||
|
||||
return (byte)Math.Round(Srgb.Encode(Math.Clamp(sum, 0d, 1d)) * 255d);
|
||||
};
|
||||
}
|
||||
|
||||
static Bgra Blob(int x, int y)
|
||||
{
|
||||
var distance = Math.Sqrt(Math.Pow(x + 0.5 - 64, 2) + Math.Pow(y + 0.5 - 64, 2));
|
||||
var coverage = Math.Clamp((26 - distance) / 8, 0d, 1d);
|
||||
|
||||
return new Bgra(160, 160, 160, (byte)Math.Round(coverage * 255d));
|
||||
}
|
||||
|
||||
static Vector3 TotalLight(IEnumerable<Bgra> pixels)
|
||||
{
|
||||
var total = Vector3.Zero;
|
||||
foreach (var pixel in pixels)
|
||||
{
|
||||
var light = Srgb.DecodePremultiplied(new Vector4(pixel.Red, pixel.Green, pixel.Blue, pixel.Alpha) / 255f);
|
||||
total += new Vector3(light.X, light.Y, light.Z);
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
static Func<int, byte> Channel(Rendering rendering, int channel, Func<int, (int X, int Y)> position)
|
||||
=> index =>
|
||||
{
|
||||
var (x, y) = position(index);
|
||||
var pixel = rendering[x, y];
|
||||
|
||||
return channel switch { 0 => pixel.Red, 1 => pixel.Green, _ => pixel.Blue };
|
||||
};
|
||||
|
||||
static int PeakAt(Rendering rendering, int channel, int from, int to, Func<int, (int X, int Y)> position)
|
||||
{
|
||||
var value = Channel(rendering, channel, position);
|
||||
|
||||
return Enumerable.Range(from, to - from + 1).MaxBy(index => value(index));
|
||||
}
|
||||
|
||||
public static readonly TheoryData<ShiftMode> Modes = new() { ShiftMode.Linear, ShiftMode.Radial, ShiftMode.Rotational };
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Modes))]
|
||||
public void WithoutADistanceTheImagePassesThroughUntouched(ShiftMode mode)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 64, 48, Textured);
|
||||
|
||||
var rendering = Render(context, source, Settings(Mode: mode, Distance: 0f, Center: new Vector2(9f, -5f)));
|
||||
|
||||
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]));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(255)]
|
||||
[InlineData(200)]
|
||||
[InlineData(128)]
|
||||
[InlineData(7)]
|
||||
public void EveryGrayLevelSurvivesTheRoundTripThroughLinearLight(int alpha)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 256, 4, (x, _) => new Bgra((byte)x, (byte)x, (byte)x, (byte)alpha));
|
||||
|
||||
var rendering = Render(context, source, Settings(Distance: 0f));
|
||||
|
||||
Assert.All(rendering.Coordinates(), point => Assert.Equal(source[point.X, point.Y], rendering[point.X, point.Y]));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Modes))]
|
||||
public void WithoutStrengthTheImageIsUntouchedAndTheSpillStaysTransparent(ShiftMode mode)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 64, 48, Textured);
|
||||
|
||||
var rendering = Render(context, source, Settings(Mode: mode, Distance: 12f, Strength: 0f));
|
||||
|
||||
Assert.True(rendering.Left < 0 && rendering.Top < 0);
|
||||
Assert.All(rendering.Coordinates(), point => Assert.Equal(source.Contains(point.X, point.Y) ? source[point.X, point.Y] : Bgra.Transparent, rendering[point.X, point.Y]));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ShiftMode.Linear, DispersionLaw.Grating, 8)]
|
||||
[InlineData(ShiftMode.Linear, DispersionLaw.Prism, 33)]
|
||||
[InlineData(ShiftMode.Radial, DispersionLaw.Grating, 32)]
|
||||
[InlineData(ShiftMode.Radial, DispersionLaw.Prism, 64)]
|
||||
[InlineData(ShiftMode.Rotational, DispersionLaw.Grating, 17)]
|
||||
[InlineData(ShiftMode.Rotational, DispersionLaw.Prism, 32)]
|
||||
public void AUniformImageKeepsItsColorInTheInterior(ShiftMode mode, DispersionLaw law, int steps)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
var color = new Bgra(200, 90, 30, 255);
|
||||
using var source = SourceImage.Solid(context, 96, 96, color);
|
||||
|
||||
var rendering = Render(context, source, Settings(Mode: mode, Distance: 12f, Dispersion: law, Steps: steps, ReferenceWavelength: 600f));
|
||||
|
||||
var checkedPixels = 0;
|
||||
foreach (var (x, y) in rendering.Coordinates())
|
||||
{
|
||||
if (source.Contains(x, y) && DistanceToBorder(source, x, y) > 16)
|
||||
{
|
||||
Assert.True(WithinRounding(color, rendering[x, y]), $"({x}, {y}) {rendering[x, y]}");
|
||||
checkedPixels++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(checkedPixels > 3000, $"{checkedPixels}");
|
||||
}
|
||||
|
||||
public static readonly TheoryData<ShiftMode, int> DarkLevels = [.. from mode in new[] { ShiftMode.Linear, ShiftMode.Radial, ShiftMode.Rotational } from level in new[] { 1, 2, 3, 5, 8, 16, 40 } select (mode, level)];
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(DarkLevels))]
|
||||
public void ADarkUniformImageKeepsItsColorInTheInterior(ShiftMode mode, int level)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
var color = Bgra.Opaque((byte)level, (byte)level, (byte)level);
|
||||
using var source = SourceImage.Solid(context, 96, 96, color);
|
||||
|
||||
var rendering = Render(context, source, Settings(Mode: mode, Distance: 12f));
|
||||
|
||||
foreach (var (x, y) in rendering.Coordinates())
|
||||
{
|
||||
if (source.Contains(x, y) && DistanceToBorder(source, x, y) > 16)
|
||||
Assert.True(WithinRounding(color, rendering[x, y]), $"({x}, {y}) {rendering[x, y]}");
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Modes))]
|
||||
public void ASemiTransparentUniformImageKeepsItsPremultipliedColor(ShiftMode mode)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
var color = new Bgra(200, 90, 30, 128);
|
||||
using var source = SourceImage.Solid(context, 96, 96, color);
|
||||
|
||||
var rendering = Render(context, source, Settings(Mode: mode, Distance: 12f));
|
||||
|
||||
foreach (var (x, y) in rendering.Coordinates())
|
||||
{
|
||||
if (source.Contains(x, y) && DistanceToBorder(source, x, y) > 16)
|
||||
Assert.True(WithinRounding(color.Premultiplied(), rendering[x, y]), $"({x}, {y}) {rendering[x, y]}");
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(8f, 0f, DispersionLaw.Grating, 550f, 32)]
|
||||
[InlineData(8f, 0f, DispersionLaw.Prism, 550f, 32)]
|
||||
[InlineData(8f, 0f, DispersionLaw.Grating, 450f, 32)]
|
||||
[InlineData(8f, 0f, DispersionLaw.Grating, 650f, 32)]
|
||||
[InlineData(8f, 180f, DispersionLaw.Grating, 550f, 32)]
|
||||
[InlineData(-8f, 0f, DispersionLaw.Grating, 550f, 32)]
|
||||
[InlineData(16f, 0f, DispersionLaw.Grating, 550f, 64)]
|
||||
[InlineData(6f, 0f, DispersionLaw.Prism, 500f, 16)]
|
||||
public void TheEdgeOfEachChannelFollowsTheOneDimensionalModelAlongTheAngle(float distance, float angle, DispersionLaw law, float reference, int steps)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 64, 32, HalfAndHalf);
|
||||
var settings = Settings(Distance: distance, Angle: angle, Dispersion: law, ReferenceWavelength: reference, Steps: steps);
|
||||
var direction = MathF.Cos(angle * MathF.PI / 180f);
|
||||
|
||||
var rendering = Render(context, source, settings);
|
||||
|
||||
for (var channel = 0; channel < 3; channel++)
|
||||
{
|
||||
var crossing = Crossing(Channel(rendering, channel, x => (x, 16)), 4, 58);
|
||||
var expected = Crossing(ExpectedProfile(settings, channel, direction), 4, 58);
|
||||
Assert.True(Math.Abs(crossing - expected) <= 0.15, $"channel {channel}: {crossing} against {expected}");
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(90f)]
|
||||
[InlineData(-90f)]
|
||||
public void AVerticalAngleMovesTheEdgesOfAHorizontalSeam(float angle)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 32, 64, TopAndBottom);
|
||||
var settings = Settings(Distance: 8f, Angle: angle);
|
||||
var direction = MathF.Sin(angle * MathF.PI / 180f);
|
||||
|
||||
var rendering = Render(context, source, settings);
|
||||
|
||||
for (var channel = 0; channel < 3; channel++)
|
||||
{
|
||||
var crossing = Crossing(Channel(rendering, channel, y => (16, y)), 4, 58);
|
||||
var expected = Crossing(ExpectedProfile(settings, channel, direction), 4, 58);
|
||||
Assert.True(Math.Abs(crossing - expected) <= 0.15, $"channel {channel}: {crossing} against {expected}");
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(10f, 0f)]
|
||||
[InlineData(10f, 37f)]
|
||||
[InlineData(18f, 90f)]
|
||||
[InlineData(-14f, 200f)]
|
||||
public void ALinearShiftLosesNoLightAndGainsOnlyWhatClippingAdds(float distance, float angle)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 128, 128, Blob);
|
||||
|
||||
var rendering = Render(context, source, Settings(Distance: distance, Angle: angle));
|
||||
|
||||
var before = TotalLight(Enumerable.Range(0, source.Width * source.Height).Select(index => source[index % source.Width, index / source.Width]));
|
||||
var after = TotalLight(rendering.Coordinates().Select(point => rendering[point.X, point.Y]));
|
||||
var ratio = after / before;
|
||||
foreach (var (channel, value) in new[] { ("red", ratio.X), ("green", ratio.Y), ("blue", ratio.Z) })
|
||||
Assert.True(value is >= 0.995f and <= 1.08f, $"{channel} {value}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(8f, 0f, DispersionLaw.Grating, 32)]
|
||||
[InlineData(8f, 180f, DispersionLaw.Prism, 33)]
|
||||
[InlineData(16f, 0f, DispersionLaw.Grating, 64)]
|
||||
public void TheEdgeProfileOfEachChannelFollowsTheOneDimensionalModel(float distance, float angle, DispersionLaw law, int steps)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 64, 32, HalfAndHalf);
|
||||
var settings = Settings(Distance: distance, Angle: angle, Dispersion: law, Steps: steps);
|
||||
var direction = MathF.Cos(angle * MathF.PI / 180f);
|
||||
var margin = (int)MathF.Ceiling(MathF.Abs(distance)) + 1;
|
||||
|
||||
var rendering = Render(context, source, settings);
|
||||
|
||||
for (var channel = 0; channel < 3; channel++)
|
||||
{
|
||||
var actual = Channel(rendering, channel, x => (x, 16));
|
||||
var expected = ExpectedProfile(settings, channel, direction);
|
||||
for (var x = margin; x < 64 - margin; x++)
|
||||
Assert.True(Math.Abs(actual(x) - expected(x)) <= 2, $"channel {channel}, x {x}: {actual(x)} against {expected(x)}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BlueMovesAheadOfGreenAndRedAlongTheDirection()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 64, 32, HalfAndHalf);
|
||||
|
||||
var rendering = Render(context, source, Settings());
|
||||
var red = Crossing(Channel(rendering, 0, x => (x, 16)), 4, 58);
|
||||
var green = Crossing(Channel(rendering, 1, x => (x, 16)), 4, 58);
|
||||
var blue = Crossing(Channel(rendering, 2, x => (x, 16)), 4, 58);
|
||||
|
||||
Assert.True(red is >= 28d and <= 30.5d && green is >= 32.5d and <= 34.5d && blue is >= 37d and <= 39.5d, $"red {red}, green {green}, blue {blue}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0f)]
|
||||
[InlineData(37f)]
|
||||
[InlineData(90f)]
|
||||
[InlineData(200f)]
|
||||
public void ANegativeDistanceMirrorsAPositiveOneAtTheOppositeAngle(float angle)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 64, 48, Textured);
|
||||
|
||||
var negative = Render(context, source, Settings(Distance: -10f, Angle: angle));
|
||||
var opposite = Render(context, source, Settings(Distance: 10f, Angle: angle + 180f));
|
||||
|
||||
Assert.Equal((negative.Left, negative.Top, negative.Width, negative.Height), (opposite.Left, opposite.Top, opposite.Width, opposite.Height));
|
||||
Assert.All(negative.Coordinates(), point => Assert.True(WithinRounding(negative[point.X, point.Y], opposite[point.X, point.Y]), $"({point.X}, {point.Y})"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePrismLawNarrowsTheRedEdgeComparedWithTheGrating()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 64, 32, HalfAndHalf);
|
||||
|
||||
var grating = Render(context, source, Settings(Dispersion: DispersionLaw.Grating));
|
||||
var prism = Render(context, source, Settings(Dispersion: DispersionLaw.Prism));
|
||||
var gratingWidth = EdgeWidth(Channel(grating, 0, x => (x, 16)), 4, 58);
|
||||
var prismWidth = EdgeWidth(Channel(prism, 0, x => (x, 16)), 4, 58);
|
||||
|
||||
Assert.True(prismWidth < gratingWidth * 0.7, $"prism {prismWidth}, grating {gratingWidth}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoreStepsConvergeTowardsTheDenseSpectrum()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 64, 48, Textured);
|
||||
var dense = Render(context, source, Settings(Distance: 24f, Steps: 64));
|
||||
|
||||
long Distance(int steps)
|
||||
{
|
||||
var coarse = Render(context, source, Settings(Distance: 24f, Steps: steps));
|
||||
return dense.Coordinates().Sum(point =>
|
||||
{
|
||||
var a = dense[point.X, point.Y];
|
||||
var b = coarse[point.X, point.Y];
|
||||
return (long)(Math.Abs(a.Blue - b.Blue) + Math.Abs(a.Green - b.Green) + Math.Abs(a.Red - b.Red) + Math.Abs(a.Alpha - b.Alpha));
|
||||
});
|
||||
}
|
||||
|
||||
var eight = Distance(8);
|
||||
var sixteen = Distance(16);
|
||||
var thirtyTwo = Distance(32);
|
||||
|
||||
Assert.True(eight > sixteen, $"8: {eight}, 16: {sixteen}");
|
||||
Assert.True(sixteen > thirtyTwo, $"16: {sixteen}, 32: {thirtyTwo}");
|
||||
}
|
||||
|
||||
static readonly ShiftSettings[] ReferenceSettings =
|
||||
[
|
||||
Settings(),
|
||||
Settings(Distance: 20f, Angle: 37f),
|
||||
Settings(Distance: -14f, Angle: 215f, Dispersion: DispersionLaw.Prism),
|
||||
Settings(Mode: ShiftMode.Radial, Distance: 20f),
|
||||
Settings(Mode: ShiftMode.Radial, Distance: -18f, Center: new Vector2(30f, -12f)),
|
||||
Settings(Mode: ShiftMode.Rotational, Distance: 20f, Center: new Vector2(12f, -9f)),
|
||||
Settings(Mode: ShiftMode.Rotational, Distance: 35f),
|
||||
Settings(Mode: ShiftMode.Radial, Distance: 60f),
|
||||
Settings(Mode: ShiftMode.Radial, Distance: -75f, Center: new Vector2(-25f, 10f), Steps: 16),
|
||||
Settings(Mode: ShiftMode.Rotational, Distance: 90f, Center: new Vector2(20f, 14f), Steps: 64),
|
||||
Settings(Distance: 14f, Dispersion: DispersionLaw.Prism, ReferenceWavelength: 480f, Steps: 8, Strength: 0.6f),
|
||||
Settings(Distance: 18f, Angle: 120f, Steps: 13),
|
||||
Settings(Mode: ShiftMode.Radial, Distance: 30f, Center: new Vector2(-10f, 6f), Steps: 33),
|
||||
Settings(Mode: ShiftMode.Rotational, Distance: 50f, Dispersion: DispersionLaw.Prism, Steps: 21),
|
||||
Settings(Distance: 40f, Angle: 200f, Dispersion: DispersionLaw.Prism, ReferenceWavelength: 650f, Steps: 64),
|
||||
];
|
||||
|
||||
public static readonly TheoryData<int> ReferenceCases = [.. Enumerable.Range(0, ReferenceSettings.Length)];
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(ReferenceCases))]
|
||||
public void TheOutputMatchesAnIndependentCpuRendering(int index)
|
||||
{
|
||||
var settings = ReferenceSettings[index];
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 64, 48, Textured);
|
||||
var reference = new SpectralReferenceRenderer(source, settings);
|
||||
|
||||
var rendering = Render(context, source, settings);
|
||||
|
||||
foreach (var (x, y) in rendering.Coordinates())
|
||||
{
|
||||
var expected = reference.Pixel(x, y) * 255f;
|
||||
var actual = rendering[x, y];
|
||||
Assert.True(
|
||||
Math.Abs(expected.X - actual.Red) <= 2f && Math.Abs(expected.Y - actual.Green) <= 2f && Math.Abs(expected.Z - actual.Blue) <= 2f && Math.Abs(expected.W - actual.Alpha) <= 2f,
|
||||
$"({x}, {y}) expected {expected}, actual {actual}");
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(ReferenceCases))]
|
||||
public void NothingVisibleLiesBeyondTheOutputBounds(int index)
|
||||
{
|
||||
var settings = ReferenceSettings[index];
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 64, 48, Textured);
|
||||
var reference = new SpectralReferenceRenderer(source, settings);
|
||||
|
||||
var rendering = Render(context, source, settings);
|
||||
|
||||
for (var y = rendering.Top - 8; y < rendering.Bottom + 8; y++)
|
||||
{
|
||||
for (var x = rendering.Left - 8; x < rendering.Right + 8; x++)
|
||||
{
|
||||
if (!rendering.Contains(x, y))
|
||||
Assert.True(reference.Pixel(x, y).W * 255f <= 1f, $"({x}, {y}) {reference.Pixel(x, y)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BlueSpillsOutwardAndRedInwardOfARadialStripe()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 128, 128, Stripes);
|
||||
|
||||
var rendering = Render(context, source, Settings(Mode: ShiftMode.Radial, Distance: 20f));
|
||||
var red = PeakAt(rendering, 0, 80, 120, x => (x, 64));
|
||||
var green = PeakAt(rendering, 1, 80, 120, x => (x, 64));
|
||||
var blue = PeakAt(rendering, 2, 80, 120, x => (x, 64));
|
||||
|
||||
Assert.True(red < 94 && green is >= 94 and <= 97 && blue > 98, $"red {red}, green {green}, blue {blue}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARadialShiftKeepsTheMirrorSymmetryOfTheImage()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 128, 128, Stripes);
|
||||
|
||||
var rendering = Render(context, source, Settings(Mode: ShiftMode.Radial, Distance: 20f));
|
||||
|
||||
Assert.Equal(rendering.Left + rendering.Right, source.Width);
|
||||
Assert.All(rendering.Coordinates(), point => Assert.True(WithinRounding(rendering[point.X, point.Y], rendering[source.Width - 1 - point.X, point.Y]), $"({point.X}, {point.Y})"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BlueTurnsClockwiseAndRedCounterclockwiseAroundTheCenter()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 160, 128, Dot);
|
||||
|
||||
var rendering = Render(context, source, Settings(Mode: ShiftMode.Rotational, Distance: 40f));
|
||||
var red = PeakAt(rendering, 0, 40, 90, y => (104, y));
|
||||
var green = PeakAt(rendering, 1, 40, 90, y => (104, y));
|
||||
var blue = PeakAt(rendering, 2, 40, 90, y => (104, y));
|
||||
|
||||
Assert.True(red < 62 && green is >= 62 and <= 66 && blue > 66, $"red {red}, green {green}, blue {blue}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ShiftMode.Radial)]
|
||||
[InlineData(ShiftMode.Rotational)]
|
||||
public void APointSymmetricImageStaysPointSymmetric(ShiftMode mode)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 128, 128, (x, y) => PointSymmetric(x, y, 127 - x, 127 - y));
|
||||
|
||||
var rendering = Render(context, source, Settings(Mode: mode, Distance: 20f));
|
||||
|
||||
Assert.Equal((rendering.Left + rendering.Right, rendering.Top + rendering.Bottom), (source.Width, source.Height));
|
||||
Assert.All(rendering.Coordinates(), point => Assert.True(WithinRounding(rendering[point.X, point.Y], rendering[source.Width - 1 - point.X, source.Height - 1 - point.Y]), $"({point.X}, {point.Y})"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ShiftMode.Radial)]
|
||||
[InlineData(ShiftMode.Rotational)]
|
||||
public void TheCenterOffsetMovesThePointOfSymmetry(ShiftMode mode)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 128, 128, (x, y) => PointSymmetric(x, y, 167 - x, 107 - y));
|
||||
|
||||
var rendering = Render(context, source, Settings(Mode: mode, Distance: 20f, Center: new Vector2(20f, -10f)));
|
||||
|
||||
var compared = 0;
|
||||
foreach (var (x, y) in rendering.Coordinates())
|
||||
{
|
||||
var mirroredX = 167 - x;
|
||||
var mirroredY = 107 - y;
|
||||
if (DistanceToBorder(source, x, y) > 24 && source.Contains(mirroredX, mirroredY) && DistanceToBorder(source, mirroredX, mirroredY) > 24)
|
||||
{
|
||||
Assert.True(WithinRounding(rendering[x, y], rendering[mirroredX, mirroredY]), $"({x}, {y})");
|
||||
compared++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(compared > 1000, $"{compared}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ShiftMode.Linear, 100, 50)]
|
||||
[InlineData(ShiftMode.Linear, -37, 21)]
|
||||
[InlineData(ShiftMode.Radial, 100, 50)]
|
||||
[InlineData(ShiftMode.Radial, -37, 21)]
|
||||
[InlineData(ShiftMode.Rotational, 100, 50)]
|
||||
[InlineData(ShiftMode.Rotational, -37, 21)]
|
||||
public void TheShiftTravelsWithTheImage(ShiftMode mode, int dx, int dy)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 64, 48, Textured);
|
||||
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;
|
||||
var settings = Settings(Mode: mode, Distance: 16f, Angle: 30f, Center: new Vector2(6f, -4f));
|
||||
|
||||
var inPlace = Render(context, source, settings);
|
||||
using var effect = new SpectrumColorShiftCustomEffect(context);
|
||||
effect.SetInput(0, movedOutput, true);
|
||||
settings.Apply(effect);
|
||||
using var output = effect.Output;
|
||||
var travelled = Rendering.Capture(context, output);
|
||||
|
||||
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(WithinRounding(inPlace[point.X, point.Y], travelled[point.X + dx, point.Y + dy]), $"({point.X}, {point.Y})"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSpectrumSpillsOverTheEdgesInTheDirectionOfTheShift()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = SourceImage.Solid(context, 40, 24, Bgra.Opaque(255, 255, 255));
|
||||
|
||||
var rendering = Render(context, source, Settings(Distance: 20f));
|
||||
|
||||
var left = rendering[-5, 12];
|
||||
var right = rendering[44, 12];
|
||||
Assert.True(left.Alpha > 100 && left.Red > left.Blue + 100, $"{left}");
|
||||
Assert.True(right.Alpha > 100 && right.Blue > right.Red + 100, $"{right}");
|
||||
Assert.True(rendering[rendering.Left, 12].Alpha <= 2 && rendering[rendering.Right - 1, 12].Alpha <= 2);
|
||||
Assert.Equal(Bgra.Transparent, rendering[20, rendering.Top]);
|
||||
Assert.Equal(Bgra.Transparent, rendering[20, rendering.Bottom - 1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelsBeyondTheReachOfTheDistanceStayUnchanged()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 64, 32, HalfAndHalf);
|
||||
|
||||
var rendering = Render(context, source, Settings(Distance: 8f));
|
||||
|
||||
var checkedPixels = 0;
|
||||
foreach (var (x, y) in rendering.Coordinates())
|
||||
{
|
||||
if (source.Contains(x, y) && Math.Abs(x + 0.5 - Seam) > 9 && DistanceToBorder(source, x, y) > 9 && y > 9 && y < 22)
|
||||
{
|
||||
Assert.True(WithinRounding(source[x, y], rendering[x, y]), $"({x}, {y})");
|
||||
checkedPixels++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(checkedPixels > 100, $"{checkedPixels}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Modes))]
|
||||
public void ATransparentImageStaysTransparent(ShiftMode mode)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = SourceImage.Solid(context, 48, 32, Bgra.Transparent);
|
||||
|
||||
var rendering = Render(context, source, Settings(Mode: mode, Distance: 20f));
|
||||
|
||||
Assert.All(rendering.Coordinates(), point => Assert.Equal(Bgra.Transparent, rendering[point.X, point.Y]));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Modes))]
|
||||
public void EveryPixelIsAValidPremultipliedColor(ShiftMode mode)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 64, 48, Textured);
|
||||
|
||||
var rendering = Render(context, source, Settings(Mode: mode, Distance: 24f, Strength: 0.8f));
|
||||
|
||||
Assert.All(rendering.Coordinates(), point =>
|
||||
{
|
||||
var pixel = rendering[point.X, point.Y];
|
||||
Assert.True(pixel.Red <= pixel.Alpha + 1 && pixel.Green <= pixel.Alpha + 1 && pixel.Blue <= pixel.Alpha + 1, $"({point.X}, {point.Y}) {pixel}");
|
||||
});
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Modes))]
|
||||
public void AnOverbrightInputIsClampedToItsAlpha(ShiftMode mode)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
var stride = 96 * SourceImage.BytesPerPixel;
|
||||
var pixels = new byte[stride * 96];
|
||||
for (var offset = 0; offset < pixels.Length; offset += SourceImage.BytesPerPixel)
|
||||
{
|
||||
pixels[offset + 2] = 255;
|
||||
pixels[offset + 3] = 64;
|
||||
}
|
||||
|
||||
using var bitmap = context.DeviceContext.CreateBitmap(new SizeI(96, 96), nint.Zero, stride, new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.None));
|
||||
bitmap.CopyFromMemory(pixels, stride);
|
||||
using var effect = new SpectrumColorShiftCustomEffect(context);
|
||||
effect.SetInput(0, bitmap, true);
|
||||
Settings(Mode: mode, Distance: 12f).Apply(effect);
|
||||
using var output = effect.Output;
|
||||
|
||||
var rendering = Rendering.Capture(context, output);
|
||||
|
||||
var interior = rendering[48, 48];
|
||||
Assert.Equal(64, interior.Alpha);
|
||||
Assert.True(interior.Red <= interior.Alpha && interior.Green <= interior.Alpha && interior.Blue <= interior.Alpha, $"{interior}");
|
||||
Assert.True(interior.Red >= interior.Alpha - 1, $"{interior}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSameSettingsAlwaysProduceTheSamePixels()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 64, 48, Textured);
|
||||
var settings = Settings(Mode: ShiftMode.Rotational, Distance: 18f, Dispersion: DispersionLaw.Prism);
|
||||
|
||||
var first = Render(context, source, settings);
|
||||
var second = Render(context, source, settings);
|
||||
|
||||
Assert.True(first.SamePixelsAs(second));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Modes))]
|
||||
public void TurningTheToggleOnAndOffRestoresTheLegacyImage(ShiftMode mode)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 64, 48, Textured);
|
||||
var legacy = new ShiftSettings(Mode: mode, Distance: 14f);
|
||||
var expected = Render(context, source, legacy);
|
||||
|
||||
using var effect = new SpectrumColorShiftCustomEffect(context);
|
||||
effect.SetInput(0, source.Bitmap, true);
|
||||
legacy.Apply(effect);
|
||||
effect.Physical = 1;
|
||||
using var output = effect.Output;
|
||||
var physical = Rendering.Capture(context, output);
|
||||
effect.Physical = 0;
|
||||
var restored = Rendering.Capture(context, output);
|
||||
|
||||
Assert.Contains(physical.Coordinates(), point => physical[point.X, point.Y] != expected[point.X, point.Y]);
|
||||
Assert.Equal((expected.Left, expected.Top, expected.Width, expected.Height), (restored.Left, restored.Top, restored.Width, restored.Height));
|
||||
Assert.All(expected.Coordinates(), point => Assert.Equal(expected[point.X, point.Y], restored[point.X, point.Y]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.RegularExpressions;
|
||||
using static SpectrumColorShift.SpectrumColorShiftCustomEffect;
|
||||
|
||||
namespace SpectrumColorShift.Tests;
|
||||
|
||||
public sealed partial class SpectralShaderContractTests
|
||||
{
|
||||
static readonly Dictionary<string, string> Fields = new()
|
||||
{
|
||||
["inputBounds"] = "InputBounds",
|
||||
["direction"] = "Direction",
|
||||
["center"] = "Center",
|
||||
["shiftDistance"] = "Distance",
|
||||
["radius"] = "Radius",
|
||||
["strength"] = "Strength",
|
||||
["mode"] = "Mode",
|
||||
["steps"] = "Steps",
|
||||
["spreadScale"] = "SpreadScale",
|
||||
["samples"] = "Samples",
|
||||
};
|
||||
|
||||
static string Source { get; } = ShaderSource("SpectrumColorShiftPhysical.hlsl");
|
||||
|
||||
static string SrgbSource { get; } = ShaderSource("Srgb.hlsli");
|
||||
|
||||
static string ShaderSource(string name) => File.ReadAllText(Path.Combine(Path.GetDirectoryName(Here())!, "..", "SpectrumColorShift.Shader", name));
|
||||
|
||||
static string Here([CallerFilePath] string path = "") => path;
|
||||
|
||||
static int LinearInput { get; } = (int)typeof(SpectrumColorShiftCustomEffect).GetField("LinearInput", BindingFlags.NonPublic | BindingFlags.Static)!.GetRawConstantValue()!;
|
||||
|
||||
static Type ConstantBuffer => typeof(EffectImpl).GetNestedType("PhysicalConstantBuffer", BindingFlags.NonPublic)!;
|
||||
|
||||
[GeneratedRegex(@"static const (?:int|float) (?<name>\w+) = (?<value>[0-9.]+);")]
|
||||
private static partial Regex ConstantPattern();
|
||||
|
||||
[GeneratedRegex(@"Texture2D\s+LinearTexture\s*:\s*register\(t(?<register>\d+)\)")]
|
||||
private static partial Regex TexturePattern();
|
||||
|
||||
[GeneratedRegex(@"float4\s+\w+\s*:\s*TEXCOORD(?<index>\d+)")]
|
||||
private static partial Regex CoordinatePattern();
|
||||
|
||||
[GeneratedRegex(@"^\s*(?:float4|float2|float|int)\s+(?<name>\w+)(?:\[\w+\])?\s*:\s*packoffset\(c(?<register>\d+)(?:\.(?<component>[xyzw]))?\);", RegexOptions.Multiline)]
|
||||
private static partial Regex MemberPattern();
|
||||
|
||||
static float Constant(string name) => Constant(Source, name);
|
||||
|
||||
static float Constant(string source, string name)
|
||||
=> float.Parse(ConstantPattern().Matches(source).Single(match => match.Groups["name"].Value == name).Groups["value"].Value, CultureInfo.InvariantCulture);
|
||||
|
||||
[Fact]
|
||||
public void TheShaderAndTheEffectAgreeOnTheConstants()
|
||||
{
|
||||
Assert.Equal(Spectrum.MaxSteps, Constant("MaxSteps"));
|
||||
Assert.Equal(Spectrum.SpectralTableLength, Constant("TableSize"));
|
||||
Assert.Equal((int)ShiftMode.Radial, Constant("ModeRadial"));
|
||||
Assert.Equal((int)ShiftMode.Rotational, Constant("ModeRotational"));
|
||||
Assert.Equal(ShiftGeometry.MaxRadialShift, Constant("MaxRadialShift"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheShaderReadsTheTextureOfTheLinearizedInput()
|
||||
{
|
||||
Assert.Equal(LinearInput, int.Parse(TexturePattern().Match(Source).Groups["register"].Value, CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheShaderDeclaresTheTextureCoordinateOfEveryInputUpToTheOneItReads()
|
||||
{
|
||||
var declared = CoordinatePattern().Matches(Source).Select(match => int.Parse(match.Groups["index"].Value, CultureInfo.InvariantCulture));
|
||||
|
||||
Assert.Equal(Enumerable.Range(0, LinearInput + 1), declared.Order());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("DecodeThreshold", 0.04045f)]
|
||||
[InlineData("EncodeThreshold", 0.0031308f)]
|
||||
[InlineData("LowSlope", 12.92f)]
|
||||
[InlineData("Offset", 0.055f)]
|
||||
[InlineData("Scale", 1.055f)]
|
||||
[InlineData("Exponent", 2.4f)]
|
||||
public void TheSrgbHeaderHoldsTheStandardTransferConstants(string name, float expected)
|
||||
=> Assert.Equal(expected, Constant(SrgbSource, name));
|
||||
|
||||
[Fact]
|
||||
public void TheSrgbCurvesMeetAtTheThresholds()
|
||||
{
|
||||
var slope = Constant(SrgbSource, "LowSlope");
|
||||
var linearEnd = Constant(SrgbSource, "EncodeThreshold");
|
||||
var power = Constant(SrgbSource, "Scale") * MathF.Pow(linearEnd, 1f / Constant(SrgbSource, "Exponent")) - Constant(SrgbSource, "Offset");
|
||||
|
||||
Assert.Equal(Constant(SrgbSource, "DecodeThreshold"), slope * linearEnd, 1e-5f);
|
||||
Assert.Equal(slope * linearEnd, power, 1e-5f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheConstantBufferMatchesTheShaderLayout()
|
||||
{
|
||||
var members = MemberPattern().Matches(Source)
|
||||
.ToDictionary(
|
||||
match => match.Groups["name"].Value,
|
||||
match => int.Parse(match.Groups["register"].Value, CultureInfo.InvariantCulture) * 16
|
||||
+ (match.Groups["component"].Success ? "xyzw".IndexOf(match.Groups["component"].Value[0]) * 4 : 0));
|
||||
|
||||
Assert.Equal(Fields.Keys.Order(), members.Keys.Order());
|
||||
Assert.All(members, member => Assert.Equal(member.Value, (int)Marshal.OffsetOf(ConstantBuffer, Fields[member.Key])));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheConstantBufferFillsWholeRegistersAndHoldsTheTable()
|
||||
{
|
||||
var size = (int)typeof(Unsafe).GetMethod(nameof(Unsafe.SizeOf))!.MakeGenericMethod(ConstantBuffer).Invoke(null, null)!;
|
||||
|
||||
Assert.Equal(16 * (4 + Spectrum.SpectralTableLength), size);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace SpectrumColorShift.Tests;
|
||||
|
||||
public sealed class SpectralSpectrumTests
|
||||
{
|
||||
static Vector4[] Table(int steps, float reference, DispersionLaw law)
|
||||
{
|
||||
var table = new Vector4[Spectrum.SpectralTableLength];
|
||||
Spectrum.FillSpectral(table, steps, reference, law);
|
||||
return table;
|
||||
}
|
||||
|
||||
static Vector4 Gain(Vector4[] table, int index) => table[index * Spectrum.EntriesPerStep];
|
||||
|
||||
static Vector4 Basis(Vector4[] table, int index) => table[index * Spectrum.EntriesPerStep + 1];
|
||||
|
||||
static double Wavelength(int index, int steps) => 400d + 300d * index / (steps - 1);
|
||||
|
||||
static double Offset(DispersionLaw law, double wavelength, double reference)
|
||||
=> law == DispersionLaw.Prism ? 1d / (wavelength * wavelength) - 1d / (reference * reference) : reference - wavelength;
|
||||
|
||||
static (double X, double Y, double Z) Integrate(Func<int, double> spectrum)
|
||||
{
|
||||
double x = 0d, y = 0d, z = 0d;
|
||||
for (var index = 0; index < SpectralBasis.Count; index++)
|
||||
{
|
||||
var wavelength = SpectralBasis.First + SpectralBasis.Interval * index;
|
||||
var (cx, cy, cz) = Spectrum.ColorMatching(wavelength);
|
||||
var weight = spectrum(index) * SpectralBasis.IlluminantAt(wavelength) * (index == 0 || index == SpectralBasis.Count - 1 ? 0.5 : 1d);
|
||||
x += weight * cx;
|
||||
y += weight * cy;
|
||||
z += weight * cz;
|
||||
}
|
||||
|
||||
return (x, y, z);
|
||||
}
|
||||
|
||||
static double[] RgbOf(ReadOnlySpan<double> xyz, double[] white)
|
||||
{
|
||||
var primaries = new (double X, double Y)[] { (0.64, 0.33), (0.30, 0.60), (0.15, 0.06) };
|
||||
var columns = primaries.Select(p => new[] { p.X / p.Y, 1d, (1d - p.X - p.Y) / p.Y }).ToArray();
|
||||
var scale = Solve(columns, white);
|
||||
var matrix = columns.Select((column, c) => column.Select(value => value * scale[c]).ToArray()).ToArray();
|
||||
|
||||
return Solve(matrix, xyz.ToArray());
|
||||
}
|
||||
|
||||
static double[] Solve(double[][] columns, double[] target)
|
||||
{
|
||||
double[,] m = new double[3, 3];
|
||||
for (var c = 0; c < 3; c++)
|
||||
for (var r = 0; r < 3; r++)
|
||||
m[r, c] = columns[c][r];
|
||||
|
||||
var det = m[0, 0] * (m[1, 1] * m[2, 2] - m[1, 2] * m[2, 1]) - m[0, 1] * (m[1, 0] * m[2, 2] - m[1, 2] * m[2, 0]) + m[0, 2] * (m[1, 0] * m[2, 1] - m[1, 1] * m[2, 0]);
|
||||
var result = new double[3];
|
||||
for (var c = 0; c < 3; c++)
|
||||
{
|
||||
var t = (double[,])m.Clone();
|
||||
for (var r = 0; r < 3; r++)
|
||||
t[r, c] = target[r];
|
||||
|
||||
result[c] = (t[0, 0] * (t[1, 1] * t[2, 2] - t[1, 2] * t[2, 1]) - t[0, 1] * (t[1, 0] * t[2, 2] - t[1, 2] * t[2, 0]) + t[0, 2] * (t[1, 0] * t[2, 1] - t[1, 1] * t[2, 0])) / det;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static Vector3 BasisAt(int index) => SpectralBasis.At(SpectralBasis.First + SpectralBasis.Interval * index);
|
||||
|
||||
[Fact]
|
||||
public void TheIlluminantIsNormalizedTo100AtFiveHundredSixtyNanometers()
|
||||
{
|
||||
Assert.Equal(100d, SpectralBasis.IlluminantAt(560d), 1e-4);
|
||||
Assert.Equal(82.7549d, SpectralBasis.IlluminantAt(400d), 1e-4);
|
||||
Assert.Equal(71.6091d, SpectralBasis.IlluminantAt(700d), 1e-4);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheIlluminantHasTheChromaticityOfD65()
|
||||
{
|
||||
var (x, y, z) = Integrate(_ => 1d);
|
||||
var sum = x + y + z;
|
||||
|
||||
Assert.Equal(0.3127d, x / sum, 1e-3);
|
||||
Assert.Equal(0.3290d, y / sum, 1e-3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheBasisSpectraAreNeverNegativeAndSumToOneAtEveryWavelength()
|
||||
{
|
||||
for (var index = 0; index < SpectralBasis.Count; index++)
|
||||
{
|
||||
var basis = BasisAt(index);
|
||||
|
||||
Assert.True(basis.X >= 0f && basis.Y >= 0f && basis.Z >= 0f, $"{index}");
|
||||
Assert.Equal(1d, basis.X + basis.Y + basis.Z, 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(1)]
|
||||
[InlineData(2)]
|
||||
public void TheBasisSpectraReproduceTheSrgbPrimaries(int channel)
|
||||
{
|
||||
var white = Integrate(_ => 1d);
|
||||
var normalization = Integrate(_ => 1d).Y;
|
||||
var whiteXyz = new[] { white.X / normalization, white.Y / normalization, white.Z / normalization };
|
||||
var xyz = Integrate(index => channel switch { 0 => BasisAt(index).X, 1 => BasisAt(index).Y, _ => BasisAt(index).Z });
|
||||
var rgb = RgbOf([xyz.X / normalization, xyz.Y / normalization, xyz.Z / normalization], whiteXyz);
|
||||
|
||||
for (var component = 0; component < 3; component++)
|
||||
Assert.Equal(component == channel ? 1d : 0d, rgb[component], 1e-5);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 600d, 700d)]
|
||||
[InlineData(1, 500d, 580d)]
|
||||
[InlineData(2, 400d, 480d)]
|
||||
public void EachBasisSpectrumLivesInItsOwnPartOfTheSpectrum(int channel, double from, double to)
|
||||
{
|
||||
var peak = Enumerable.Range(0, SpectralBasis.Count)
|
||||
.MaxBy(index => channel switch { 0 => BasisAt(index).X, 1 => BasisAt(index).Y, _ => BasisAt(index).Z });
|
||||
|
||||
Assert.InRange(SpectralBasis.First + SpectralBasis.Interval * peak, from, to);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheBasisIsSmoothEnoughForTheSampledSpectrum()
|
||||
{
|
||||
for (var channel = 0; channel < 3; channel++)
|
||||
for (var index = 1; index < SpectralBasis.Count - 1; index++)
|
||||
{
|
||||
var before = BasisAt(index - 1);
|
||||
var here = BasisAt(index);
|
||||
var after = BasisAt(index + 1);
|
||||
var bend = channel switch
|
||||
{
|
||||
0 => before.X - 2f * here.X + after.X,
|
||||
1 => before.Y - 2f * here.Y + after.Y,
|
||||
_ => before.Z - 2f * here.Z + after.Z,
|
||||
};
|
||||
|
||||
Assert.InRange(Math.Abs(bend), 0f, 0.05f);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheBasisInterpolatesLinearlyBetweenItsSamples()
|
||||
{
|
||||
var left = BasisAt(10);
|
||||
var right = BasisAt(11);
|
||||
var middle = SpectralBasis.At(SpectralBasis.First + SpectralBasis.Interval * 10.5);
|
||||
|
||||
Assert.Equal((left.X + right.X) / 2f, middle.X, 1e-6f);
|
||||
Assert.Equal((left.Y + right.Y) / 2f, middle.Y, 1e-6f);
|
||||
Assert.Equal((left.Z + right.Z) / 2f, middle.Z, 1e-6f);
|
||||
Assert.Equal(BasisAt(0), SpectralBasis.At(100d));
|
||||
Assert.Equal(BasisAt(SpectralBasis.Count - 1), SpectralBasis.At(900d));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(8, 550f, DispersionLaw.Grating)]
|
||||
[InlineData(32, 550f, DispersionLaw.Grating)]
|
||||
[InlineData(64, 550f, DispersionLaw.Grating)]
|
||||
[InlineData(13, 400f, DispersionLaw.Prism)]
|
||||
[InlineData(40, 700f, DispersionLaw.Prism)]
|
||||
[InlineData(25, 620f, DispersionLaw.Prism)]
|
||||
public void TheGainsAndTheBasisReproduceEveryColorWhenNothingMoves(int steps, float reference, DispersionLaw law)
|
||||
{
|
||||
var table = Table(steps, reference, law);
|
||||
|
||||
var identity = new double[3, 3];
|
||||
for (var index = 0; index < steps; index++)
|
||||
{
|
||||
var gain = Gain(table, index);
|
||||
var basis = Basis(table, index);
|
||||
double[] g = [gain.X, gain.Y, gain.Z];
|
||||
double[] b = [basis.X, basis.Y, basis.Z];
|
||||
for (var row = 0; row < 3; row++)
|
||||
for (var column = 0; column < 3; column++)
|
||||
identity[row, column] += g[row] * b[column];
|
||||
}
|
||||
|
||||
for (var row = 0; row < 3; row++)
|
||||
for (var column = 0; column < 3; column++)
|
||||
Assert.Equal(row == column ? 1d : 0d, identity[row, column], 2e-5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EveryStepCountFromEightToSixtyFourReproducesWhiteAndKeepsTheCoverageNormalized()
|
||||
{
|
||||
for (var steps = Spectrum.MinSteps; steps <= Spectrum.MaxSteps; steps++)
|
||||
{
|
||||
var table = Table(steps, 550f, DispersionLaw.Grating);
|
||||
var red = 0d;
|
||||
var green = 0d;
|
||||
var blue = 0d;
|
||||
var coverage = 0d;
|
||||
for (var index = 0; index < steps; index++)
|
||||
{
|
||||
var gain = Gain(table, index);
|
||||
var basis = Basis(table, index);
|
||||
var amplitude = basis.X + basis.Y + basis.Z;
|
||||
red += gain.X * amplitude;
|
||||
green += gain.Y * amplitude;
|
||||
blue += gain.Z * amplitude;
|
||||
coverage += gain.W;
|
||||
}
|
||||
|
||||
Assert.True(Math.Abs(red - 1d) < 2e-5 && Math.Abs(green - 1d) < 2e-5 && Math.Abs(blue - 1d) < 2e-5, $"{steps} steps");
|
||||
Assert.Equal(1d, coverage, 1e-5);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(8)]
|
||||
[InlineData(20)]
|
||||
[InlineData(63)]
|
||||
public void EntriesBeyondTheStepsAreCleared(int steps)
|
||||
{
|
||||
var table = Enumerable.Repeat(new Vector4(9f), Spectrum.SpectralTableLength).ToArray();
|
||||
|
||||
Spectrum.FillSpectral(table, steps, 550f, DispersionLaw.Grating);
|
||||
|
||||
Assert.All(table.Skip(steps * Spectrum.EntriesPerStep), entry => Assert.Equal(Vector4.Zero, entry));
|
||||
Assert.All(table.Take(steps * Spectrum.EntriesPerStep), entry => Assert.NotEqual(new Vector4(9f), entry));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(DispersionLaw.Grating, 550f)]
|
||||
[InlineData(DispersionLaw.Grating, 450f)]
|
||||
[InlineData(DispersionLaw.Grating, 650f)]
|
||||
[InlineData(DispersionLaw.Prism, 550f)]
|
||||
[InlineData(DispersionLaw.Prism, 400f)]
|
||||
[InlineData(DispersionLaw.Prism, 700f)]
|
||||
public void TheShiftCoefficientFollowsTheDispersionLaw(DispersionLaw law, float reference)
|
||||
{
|
||||
const int steps = 24;
|
||||
var table = Table(steps, reference, law);
|
||||
var norm = Math.Max(Math.Abs(Offset(law, 400d, reference)), Math.Abs(Offset(law, 700d, reference)));
|
||||
|
||||
for (var index = 0; index < steps; index++)
|
||||
Assert.Equal(Offset(law, Wavelength(index, steps), reference) / norm, Basis(table, index).W, 1e-5);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(DispersionLaw.Grating, 550f, 1f, -1f)]
|
||||
[InlineData(DispersionLaw.Grating, 650f, 1f, -0.2f)]
|
||||
[InlineData(DispersionLaw.Grating, 450f, 0.2f, -1f)]
|
||||
[InlineData(DispersionLaw.Grating, 400f, 0f, -1f)]
|
||||
[InlineData(DispersionLaw.Grating, 700f, 1f, 0f)]
|
||||
[InlineData(DispersionLaw.Prism, 700f, 1f, 0f)]
|
||||
public void TheSpectrumEndsReachAtMostTheFullDistance(DispersionLaw law, float reference, float shortEnd, float longEnd)
|
||||
{
|
||||
var table = Table(16, reference, law);
|
||||
|
||||
Assert.Equal(shortEnd, Basis(table, 0).W, 1e-5);
|
||||
Assert.Equal(longEnd, Basis(table, 15).W, 1e-5);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(DispersionLaw.Grating)]
|
||||
[InlineData(DispersionLaw.Prism)]
|
||||
public void TheShiftCoefficientFallsAsTheWavelengthGrows(DispersionLaw law)
|
||||
{
|
||||
var table = Table(Spectrum.MaxSteps, 550f, law);
|
||||
|
||||
for (var index = 1; index < Spectrum.MaxSteps; index++)
|
||||
Assert.True(Basis(table, index).W < Basis(table, index - 1).W, $"{index}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(DispersionLaw.Grating)]
|
||||
[InlineData(DispersionLaw.Prism)]
|
||||
public void TheSampleAtTheReferenceWavelengthDoesNotMove(DispersionLaw law)
|
||||
{
|
||||
var table = Table(13, 550f, law);
|
||||
|
||||
Assert.Equal(0f, Basis(table, 6).W);
|
||||
Assert.NotEqual(0f, Basis(table, 5).W);
|
||||
Assert.NotEqual(0f, Basis(table, 7).W);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePrismLawSpreadsBlueMoreThanRed()
|
||||
{
|
||||
var table = Table(16, 550f, DispersionLaw.Prism);
|
||||
|
||||
Assert.InRange(-Basis(table, 15).W, 0.40f, 0.46f);
|
||||
Assert.True(Basis(table, 0).W > -Basis(table, 15).W * 2f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheTwoLawsGiveDifferentCoefficients()
|
||||
{
|
||||
var grating = Table(24, 550f, DispersionLaw.Grating);
|
||||
var prism = Table(24, 550f, DispersionLaw.Prism);
|
||||
|
||||
Assert.NotEqual(Basis(grating, 5).W, Basis(prism, 5).W);
|
||||
Assert.NotEqual(Basis(grating, 18).W, Basis(prism, 18).W);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheCoverageWeightsFollowTheLuminousEfficiency()
|
||||
{
|
||||
var table = Table(32, 550f, DispersionLaw.Grating);
|
||||
var centroid = Enumerable.Range(0, 32).Sum(index => Wavelength(index, 32) * Gain(table, index).W);
|
||||
|
||||
Assert.InRange(centroid, 548d, 560d);
|
||||
Assert.True(Gain(table, 0).W < Gain(table, 16).W / 100f);
|
||||
Assert.True(Gain(table, 31).W < Gain(table, 16).W / 10f);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(300f, 400f)]
|
||||
[InlineData(400f, 400f)]
|
||||
[InlineData(550f, 550f)]
|
||||
[InlineData(700f, 700f)]
|
||||
[InlineData(900f, 700f)]
|
||||
[InlineData(float.PositiveInfinity, 700f)]
|
||||
[InlineData(float.NegativeInfinity, 400f)]
|
||||
[InlineData(float.NaN, 550f)]
|
||||
public void TheReferenceStaysWithinTheSpectrum(float requested, float expected)
|
||||
{
|
||||
Assert.Equal(expected, Spectrum.ClampReference(requested));
|
||||
Assert.Equal(Table(16, expected, DispersionLaw.Grating), Table(16, requested, DispersionLaw.Grating));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(int.MinValue, 8)]
|
||||
[InlineData(9, 12)]
|
||||
[InlineData(33, 36)]
|
||||
[InlineData(61, 64)]
|
||||
[InlineData(int.MaxValue, 64)]
|
||||
public void ThePaddedStepsAreWholeMultiplesOfTheStepQuantum(int requested, int expected)
|
||||
{
|
||||
Assert.Equal(expected, Spectrum.Padded(requested));
|
||||
Assert.Equal(0, Spectrum.Padded(requested) % Spectrum.StepQuantum);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(int.MinValue, 8)]
|
||||
[InlineData(7, 8)]
|
||||
[InlineData(8, 8)]
|
||||
[InlineData(40, 40)]
|
||||
[InlineData(64, 64)]
|
||||
[InlineData(65, 64)]
|
||||
[InlineData(int.MaxValue, 64)]
|
||||
public void TheStepsStayWithinTheirRange(int requested, int expected)
|
||||
{
|
||||
Assert.Equal(expected, Spectrum.ClampSteps(requested));
|
||||
Assert.Equal(Table(expected, 550f, DispersionLaw.Grating), Table(requested, 550f, DispersionLaw.Grating));
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,30 @@ public sealed class SpectrumColorShiftEffectImplTests
|
||||
Assert.Equal(new RawRect(-7, -2, 57, 52), requested);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLegacyShaderRequestsOnlyTheSourceInput()
|
||||
{
|
||||
var impl = new EffectImpl { Distance = 5f };
|
||||
Map(impl, new RawRect(0, 0, 40, 24));
|
||||
var inputs = new RawRect[2];
|
||||
|
||||
impl.MapOutputRectToInputRects(new RawRect(0, 0, 50, 50), inputs);
|
||||
|
||||
Assert.Equal([new RawRect(-7, -2, 57, 52), default], inputs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePhysicalShaderRequestsOnlyTheLinearizedInput()
|
||||
{
|
||||
var impl = new EffectImpl { Distance = 5f, Physical = 1 };
|
||||
Map(impl, new RawRect(0, 0, 40, 24));
|
||||
var inputs = new RawRect[2];
|
||||
|
||||
impl.MapOutputRectToInputRects(new RawRect(0, 0, 50, 50), inputs);
|
||||
|
||||
Assert.Equal([default, new RawRect(-7, -2, 57, 52)], inputs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ANoInputRequestIsIgnored()
|
||||
{
|
||||
@@ -103,6 +127,7 @@ public sealed class SpectrumColorShiftEffectImplTests
|
||||
Dispersion = (int)DispersionLaw.Prism,
|
||||
ReferenceWavelength = 480f,
|
||||
Steps = 16,
|
||||
Physical = 1,
|
||||
};
|
||||
|
||||
Assert.Equal(12f, impl.Distance);
|
||||
@@ -114,5 +139,6 @@ public sealed class SpectrumColorShiftEffectImplTests
|
||||
Assert.Equal((int)DispersionLaw.Prism, impl.Dispersion);
|
||||
Assert.Equal(480f, impl.ReferenceWavelength);
|
||||
Assert.Equal(16, impl.Steps);
|
||||
Assert.Equal(1, impl.Physical);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,8 @@ internal sealed record ShiftSettings(
|
||||
float Strength = 1f,
|
||||
DispersionLaw Dispersion = DispersionLaw.Grating,
|
||||
float ReferenceWavelength = 550f,
|
||||
int Steps = 32)
|
||||
int Steps = 32,
|
||||
bool Physical = false)
|
||||
{
|
||||
public void Apply(SpectrumColorShiftCustomEffect effect)
|
||||
{
|
||||
@@ -23,6 +24,7 @@ internal sealed record ShiftSettings(
|
||||
effect.Dispersion = (int)Dispersion;
|
||||
effect.ReferenceWavelength = ReferenceWavelength;
|
||||
effect.Steps = Steps;
|
||||
effect.Physical = Physical ? 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace SpectrumColorShift.Tests;
|
||||
|
||||
internal static class Srgb
|
||||
{
|
||||
public static double Decode(double encoded)
|
||||
=> encoded <= 0.04045 ? encoded / 12.92 : Math.Pow((encoded + 0.055) / 1.055, 2.4);
|
||||
|
||||
public static double Encode(double linear)
|
||||
=> linear <= 0.0031308 ? linear * 12.92 : 1.055 * Math.Pow(linear, 1d / 2.4) - 0.055;
|
||||
|
||||
public static Vector3 Decode(Vector3 encoded)
|
||||
=> new((float)Decode(encoded.X), (float)Decode(encoded.Y), (float)Decode(encoded.Z));
|
||||
|
||||
public static Vector3 Encode(Vector3 linear)
|
||||
=> new((float)Encode(linear.X), (float)Encode(linear.Y), (float)Encode(linear.Z));
|
||||
|
||||
public static Vector4 DecodePremultiplied(Vector4 encoded)
|
||||
=> encoded.W <= 0f ? Vector4.Zero : new Vector4(Decode(Straight(encoded)) * encoded.W, encoded.W);
|
||||
|
||||
public static Vector4 EncodePremultiplied(Vector4 linear)
|
||||
=> linear.W <= 0f ? Vector4.Zero : new Vector4(Encode(Straight(linear)) * linear.W, linear.W);
|
||||
|
||||
static Vector3 Straight(Vector4 premultiplied)
|
||||
=> Vector3.Clamp(new Vector3(premultiplied.X, premultiplied.Y, premultiplied.Z) / premultiplied.W, Vector3.Zero, Vector3.One);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using System.Numerics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace SpectrumColorShift.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class StepCountRenderingTests
|
||||
{
|
||||
public static readonly TheoryData<ShiftMode, bool> Cases = [.. from physical in new[] { false, true } from mode in new[] { ShiftMode.Linear, ShiftMode.Radial, ShiftMode.Rotational } select (mode, physical)];
|
||||
|
||||
static Bgra Gradient(int x, int y)
|
||||
{
|
||||
if ((x / 6 + y / 6) % 4 == 3)
|
||||
return Bgra.Transparent;
|
||||
|
||||
return new Bgra((byte)(30 + x * 4 % 220), (byte)(20 + y * 7 % 230), (byte)(250 - (x + y) * 3 % 200), (byte)(120 + (x * 5 + y * 9) % 136));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Cases))]
|
||||
public void EveryStepCountMatchesTheCpuRendering(ShiftMode mode, bool physical)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 48, 32, Gradient);
|
||||
using var effect = new SpectrumColorShiftCustomEffect(context);
|
||||
effect.SetInput(0, source.Bitmap, true);
|
||||
using var output = effect.Output;
|
||||
|
||||
foreach (var steps in Enumerable.Range(Spectrum.MinSteps, Spectrum.MaxSteps - Spectrum.MinSteps + 1))
|
||||
{
|
||||
var settings = new ShiftSettings(Mode: mode, Distance: 16f, Angle: 30f, Steps: steps, Physical: physical);
|
||||
settings.Apply(effect);
|
||||
Func<int, int, Vector4> reference = physical ? new SpectralReferenceRenderer(source, settings).Pixel : new ShiftReferenceRenderer(source, settings).Pixel;
|
||||
|
||||
var rendering = Rendering.Capture(context, output);
|
||||
|
||||
foreach (var (x, y) in rendering.Coordinates())
|
||||
{
|
||||
var expected = reference(x, y) * 255f;
|
||||
var actual = rendering[x, y];
|
||||
Assert.True(
|
||||
Math.Abs(expected.X - actual.Red) <= 2f && Math.Abs(expected.Y - actual.Green) <= 2f && Math.Abs(expected.Z - actual.Blue) <= 2f && Math.Abs(expected.W - actual.Alpha) <= 2f,
|
||||
$"steps {steps}, ({x}, {y}) expected {expected}, actual {actual}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace SpectrumColorShift.Tests;
|
||||
|
||||
public sealed partial class StepShadersTests
|
||||
{
|
||||
static string Project { get; } = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Here())!, "..", "SpectrumColorShift.Shader", "SpectrumColorShift.Shader.vcxproj"));
|
||||
|
||||
static string Here([CallerFilePath] string path = "") => path;
|
||||
|
||||
[GeneratedRegex(@"<StepCount Include=""(?<counts>[^""]+)""")]
|
||||
private static partial Regex CountsPattern();
|
||||
|
||||
[Fact]
|
||||
public void TheCountsCoverTheWholeRangeInWholeQuanta()
|
||||
{
|
||||
Assert.Equal(0, Spectrum.MinSteps % Spectrum.StepQuantum);
|
||||
Assert.Equal(0, Spectrum.MaxSteps % Spectrum.StepQuantum);
|
||||
Assert.Equal(Enumerable.Range(0, (Spectrum.MaxSteps - Spectrum.MinSteps) / Spectrum.StepQuantum + 1).Select(index => Spectrum.MinSteps + index * Spectrum.StepQuantum), StepShaders.Counts);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheShaderProjectCompilesExactlyTheseCounts()
|
||||
{
|
||||
var compiled = CountsPattern().Match(Project).Groups["counts"].Value.Split(';').Select(count => int.Parse(count, CultureInfo.InvariantCulture));
|
||||
|
||||
Assert.Equal(StepShaders.Counts, compiled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EveryCountHasItsOwnShaderInEachFamily()
|
||||
{
|
||||
var ids = StepShaders.Counts.SelectMany(count => new[] { StepShaders.Select(false, count), StepShaders.Select(true, count) }).ToList();
|
||||
|
||||
Assert.Equal(2 * StepShaders.Counts.Count(), ids.Distinct().Count());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void StepsShareTheShaderOfTheirPaddedCount(bool physical)
|
||||
{
|
||||
foreach (var steps in Enumerable.Range(Spectrum.MinSteps, Spectrum.MaxSteps - Spectrum.MinSteps + 1))
|
||||
Assert.Equal(StepShaders.Select(physical, Spectrum.Padded(steps)), StepShaders.Select(physical, steps));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void EveryCountIsShippedAsAResource(bool physical)
|
||||
{
|
||||
foreach (var count in StepShaders.Counts)
|
||||
{
|
||||
var bytes = YukkuriMovieMaker.Commons.PackResourceReader.ReadAllBytes(ShaderResourceUri.Get(StepShaders.ResourceName(physical, count)));
|
||||
Assert.True(bytes.Length > 0, $"{StepShaders.ResourceName(physical, count)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace SpectrumColorShift;
|
||||
|
||||
internal sealed class LinearizeCustomEffect : D2D1CustomShaderEffectBase
|
||||
{
|
||||
public LinearizeCustomEffect(IGraphicsDevicesAndContext devices) : base(Create<EffectImpl>(devices))
|
||||
{
|
||||
if (IsEnabled)
|
||||
SetValue((int)Property.Precision, BufferPrecision.PerChannel16Float);
|
||||
}
|
||||
|
||||
[CustomEffect(1)]
|
||||
internal sealed class EffectImpl : D2D1CustomShaderEffectImplBase<EffectImpl>
|
||||
{
|
||||
public EffectImpl() : base(ShaderResourceUri.Get("SpectrumColorShiftLinearize"))
|
||||
{
|
||||
}
|
||||
|
||||
protected override void UpdateConstants()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace SpectrumColorShift;
|
||||
|
||||
internal static class SpectralBasis
|
||||
{
|
||||
public const double First = 400.0;
|
||||
public const double Interval = 5.0;
|
||||
public const int Count = 61;
|
||||
|
||||
private static ReadOnlySpan<float> Red =>
|
||||
[
|
||||
0.192512361f, 0.16935988f, 0.146196031f, 0.123059145f, 0.100109343f, 0.0777127425f, 0.0564703934f, 0.0371695051f,
|
||||
0.0207353365f, 0.00830780452f, 0.00137841186f, 7.5479875e-07f, 9.01286255e-07f, 1.06360691e-06f, 5.45645767e-07f, 3.57413785e-07f,
|
||||
2.57572257e-07f, 2.02100568e-07f, 1.641348e-07f, 1.31969263e-07f, 1.0800669e-07f, 9.0420405e-08f, 7.66890265e-08f, 6.68081003e-08f,
|
||||
5.99273434e-08f, 5.42758659e-08f, 4.43178079e-08f, 4.17441579e-08f, 4.91125451e-08f, 5.06339275e-08f, 4.67123455e-08f, 6.02243933e-08f,
|
||||
3.32734569e-08f, 0.00218982151f, 0.0301830399f, 0.0943962603f, 0.194844971f, 0.323868219f, 0.468912693f, 0.615343668f,
|
||||
0.748929449f, 0.858055159f, 0.935683229f, 0.980840619f, 0.99893757f, 0.999999877f, 0.999999636f, 0.999999509f,
|
||||
0.999999413f, 0.999999252f, 0.999999011f, 0.999998673f, 0.999998148f, 0.999997337f, 0.99999599f, 0.999993519f,
|
||||
0.99998865f, 0.999971924f, 0.99992753f, 0.999857504f, 0.99977574f,
|
||||
];
|
||||
|
||||
private static ReadOnlySpan<float> Green =>
|
||||
[
|
||||
1.81116187e-05f, 4.76598665e-06f, 2.06583504e-06f, 1.14787887e-06f, 7.01859312e-07f, 4.9802927e-07f, 3.91446971e-07f, 2.9659085e-07f,
|
||||
2.51710459e-07f, 1.52383012e-07f, 9.82642489e-08f, 0.0030716171f, 0.0200009702f, 0.0564915036f, 0.114178186f, 0.191829222f,
|
||||
0.285986432f, 0.391619914f, 0.502778259f, 0.613202335f, 0.716844931f, 0.808340572f, 0.883459214f, 0.939549555f,
|
||||
0.975987013f, 0.994593092f, 0.999999794f, 0.999999852f, 0.999999666f, 0.99999969f, 0.999999848f, 0.999548594f,
|
||||
0.992259651f, 0.973278248f, 0.929308352f, 0.85554009f, 0.753853787f, 0.631069348f, 0.497157023f, 0.363430426f,
|
||||
0.240949244f, 0.139096042f, 0.0643157669f, 0.0191591542f, 0.00106195131f, 4.56685713e-08f, 1.58152571e-07f, 2.22023037e-07f,
|
||||
2.65629655e-07f, 3.38276201e-07f, 4.47483004e-07f, 6.00414965e-07f, 8.37904682e-07f, 1.20521489e-06f, 1.81520325e-06f, 2.94309258e-06f,
|
||||
5.13254026e-06f, 1.23204315e-05f, 3.2743966e-05f, 6.68620547e-05f, 0.000107581877f,
|
||||
];
|
||||
|
||||
private static ReadOnlySpan<float> Blue =>
|
||||
[
|
||||
0.807469527f, 0.830635354f, 0.853801904f, 0.876939707f, 0.899889955f, 0.92228676f, 0.943529215f, 0.962830198f,
|
||||
0.979264412f, 0.991692043f, 0.99862149f, 0.996927628f, 0.979998128f, 0.943507433f, 0.885821269f, 0.808170421f,
|
||||
0.71401331f, 0.608379884f, 0.497221577f, 0.386797533f, 0.283154961f, 0.191659337f, 0.11654071f, 0.0604503786f,
|
||||
0.0240129266f, 0.00540685411f, 1.61548711e-07f, 1.06184152e-07f, 2.84808058e-07f, 2.59130901e-07f, 1.04914227e-07f, 0.000451346134f,
|
||||
0.00774031585f, 0.0245319302f, 0.0405086082f, 0.0500636496f, 0.051301242f, 0.0450624333f, 0.0339302845f, 0.021225906f,
|
||||
0.0101213068f, 0.00284879946f, 1.00408131e-06f, 2.26836029e-07f, 4.78697571e-07f, 7.77024557e-08f, 2.06003424e-07f, 2.68621395e-07f,
|
||||
3.21384151e-07f, 4.09280481e-07f, 5.4140573e-07f, 7.26436417e-07f, 1.01373333e-06f, 1.45801888e-06f, 2.19525189e-06f, 3.5375357e-06f,
|
||||
6.21747073e-06f, 1.57553175e-05f, 3.9726355e-05f, 7.56335619e-05f, 0.000116677997f,
|
||||
];
|
||||
|
||||
private static ReadOnlySpan<float> D65 =>
|
||||
[
|
||||
82.7549f, 87.1204f, 91.486f, 92.4589f, 93.4318f, 90.057f, 86.6823f, 95.7736f,
|
||||
104.865f, 110.936f, 117.008f, 117.41f, 117.812f, 116.336f, 114.861f, 115.392f,
|
||||
115.923f, 112.367f, 108.811f, 109.082f, 109.354f, 108.578f, 107.802f, 106.296f,
|
||||
104.79f, 106.239f, 107.689f, 106.047f, 104.405f, 104.225f, 104.046f, 102.023f,
|
||||
100f, 98.1671f, 96.3342f, 96.0611f, 95.788f, 92.2368f, 88.6856f, 89.3459f,
|
||||
90.0062f, 89.8026f, 89.5991f, 88.6489f, 87.6987f, 85.4936f, 83.2886f, 83.4939f,
|
||||
83.6992f, 81.863f, 80.0268f, 80.1207f, 80.2146f, 81.2462f, 82.2778f, 80.281f,
|
||||
78.2842f, 74.0027f, 69.7213f, 70.6652f, 71.6091f,
|
||||
];
|
||||
|
||||
public static Vector3 At(double wavelength)
|
||||
{
|
||||
var (index, fraction) = Locate(wavelength);
|
||||
|
||||
return new Vector3(
|
||||
Lerp(Red, index, fraction),
|
||||
Lerp(Green, index, fraction),
|
||||
Lerp(Blue, index, fraction));
|
||||
}
|
||||
|
||||
public static double IlluminantAt(double wavelength)
|
||||
{
|
||||
var (index, fraction) = Locate(wavelength);
|
||||
|
||||
return Lerp(D65, index, fraction);
|
||||
}
|
||||
|
||||
private static (int Index, float Fraction) Locate(double wavelength)
|
||||
{
|
||||
var position = Math.Clamp((wavelength - First) / Interval, 0.0, Count - 1);
|
||||
var index = Math.Min((int)position, Count - 2);
|
||||
|
||||
return (index, (float)(position - index));
|
||||
}
|
||||
|
||||
private static float Lerp(ReadOnlySpan<float> table, int index, float fraction)
|
||||
=> table[index] + (table[index + 1] - table[index]) * fraction;
|
||||
}
|
||||
@@ -7,12 +7,17 @@ internal static class Spectrum
|
||||
public const int MinSteps = 8;
|
||||
public const int MaxSteps = 64;
|
||||
public const int DefaultSteps = 32;
|
||||
public const int EntriesPerStep = 2;
|
||||
public const int StepQuantum = 4;
|
||||
public const int SpectralTableLength = MaxSteps * EntriesPerStep;
|
||||
public const float ShortestWavelength = 400f;
|
||||
public const float LongestWavelength = 700f;
|
||||
public const float DefaultReferenceWavelength = 550f;
|
||||
|
||||
public static int ClampSteps(int steps) => Math.Clamp(steps, MinSteps, MaxSteps);
|
||||
|
||||
public static int Padded(int steps) => (ClampSteps(steps) + StepQuantum - 1) / StepQuantum * StepQuantum;
|
||||
|
||||
public static float ClampReference(float wavelength)
|
||||
=> float.IsNaN(wavelength) ? DefaultReferenceWavelength : Math.Clamp(wavelength, ShortestWavelength, LongestWavelength);
|
||||
|
||||
@@ -70,6 +75,80 @@ internal static class Spectrum
|
||||
table[steps..].Clear();
|
||||
}
|
||||
|
||||
private static double Wavelength(int index, int steps)
|
||||
=> ShortestWavelength + (LongestWavelength - ShortestWavelength) * index / (steps - 1);
|
||||
|
||||
private static (double X, double Y, double Z) Emission(int index, int steps)
|
||||
{
|
||||
var wavelength = Wavelength(index, steps);
|
||||
var weight = (index == 0 || index == steps - 1 ? 0.5 : 1.0) * SpectralBasis.IlluminantAt(wavelength);
|
||||
var (x, y, z) = ColorMatching(wavelength);
|
||||
|
||||
return (weight * x, weight * y, weight * z);
|
||||
}
|
||||
|
||||
public static void FillSpectral(Span<Vector4> table, int steps, float referenceWavelength, DispersionLaw law)
|
||||
{
|
||||
steps = ClampSteps(steps);
|
||||
var reference = ClampReference(referenceWavelength);
|
||||
var norm = Math.Max(
|
||||
Math.Abs(Displacement(law, ShortestWavelength, reference)),
|
||||
Math.Abs(Displacement(law, LongestWavelength, reference)));
|
||||
|
||||
Span<double> matrix = stackalloc double[9];
|
||||
Span<double> inverse = stackalloc double[9];
|
||||
matrix.Clear();
|
||||
var luminance = 0.0;
|
||||
for (var index = 0; index < steps; index++)
|
||||
{
|
||||
var (x, y, z) = Emission(index, steps);
|
||||
var basis = SpectralBasis.At(Wavelength(index, steps));
|
||||
matrix[0] += x * basis.X;
|
||||
matrix[1] += x * basis.Y;
|
||||
matrix[2] += x * basis.Z;
|
||||
matrix[3] += y * basis.X;
|
||||
matrix[4] += y * basis.Y;
|
||||
matrix[5] += y * basis.Z;
|
||||
matrix[6] += z * basis.X;
|
||||
matrix[7] += z * basis.Y;
|
||||
matrix[8] += z * basis.Z;
|
||||
luminance += y;
|
||||
}
|
||||
|
||||
Invert(matrix, inverse);
|
||||
for (var index = 0; index < steps; index++)
|
||||
{
|
||||
var wavelength = Wavelength(index, steps);
|
||||
var (x, y, z) = Emission(index, steps);
|
||||
var basis = SpectralBasis.At(wavelength);
|
||||
var gain = new Vector3(
|
||||
(float)(inverse[0] * x + inverse[1] * y + inverse[2] * z),
|
||||
(float)(inverse[3] * x + inverse[4] * y + inverse[5] * z),
|
||||
(float)(inverse[6] * x + inverse[7] * y + inverse[8] * z));
|
||||
table[index * EntriesPerStep] = new Vector4(gain, (float)(y / luminance));
|
||||
table[index * EntriesPerStep + 1] = new Vector4(basis, (float)(Displacement(law, wavelength, reference) / norm));
|
||||
}
|
||||
|
||||
table[(steps * EntriesPerStep)..].Clear();
|
||||
}
|
||||
|
||||
private static void Invert(ReadOnlySpan<double> m, Span<double> inverse)
|
||||
{
|
||||
var c0 = m[4] * m[8] - m[5] * m[7];
|
||||
var c1 = m[5] * m[6] - m[3] * m[8];
|
||||
var c2 = m[3] * m[7] - m[4] * m[6];
|
||||
var scale = 1.0 / (m[0] * c0 + m[1] * c1 + m[2] * c2);
|
||||
inverse[0] = c0 * scale;
|
||||
inverse[1] = (m[2] * m[7] - m[1] * m[8]) * scale;
|
||||
inverse[2] = (m[1] * m[5] - m[2] * m[4]) * scale;
|
||||
inverse[3] = c1 * scale;
|
||||
inverse[4] = (m[0] * m[8] - m[2] * m[6]) * scale;
|
||||
inverse[5] = (m[2] * m[3] - m[0] * m[5]) * scale;
|
||||
inverse[6] = c2 * scale;
|
||||
inverse[7] = (m[1] * m[6] - m[0] * m[7]) * scale;
|
||||
inverse[8] = (m[0] * m[4] - m[1] * m[3]) * scale;
|
||||
}
|
||||
|
||||
private static double Displacement(DispersionLaw law, double wavelength, double reference)
|
||||
=> law == DispersionLaw.Prism
|
||||
? 1.0 / (wavelength * wavelength) - 1.0 / (reference * reference)
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<Version>1.0.1</Version>
|
||||
<Version>1.2.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
|
||||
<ShaderDirPath>..\Release\</ShaderDirPath>
|
||||
@@ -61,7 +61,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Resource Include="$(ShaderDirPath)SpectrumColorShift.cso" Link="Resources\Shader\SpectrumColorShift.cso" />
|
||||
<Resource Include="$(ShaderDirPath)SpectrumColorShift*.cso" Link="Resources\Shader\%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using SharpGen.Runtime;
|
||||
using Vortice;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
@@ -8,8 +9,40 @@ using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace SpectrumColorShift;
|
||||
|
||||
internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext devices) : D2D1CustomShaderEffectBase(Create<EffectImpl>(devices))
|
||||
internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBase
|
||||
{
|
||||
private const int SourceInput = 0;
|
||||
private const int LinearInput = 1;
|
||||
|
||||
private readonly LinearizeCustomEffect _linearized;
|
||||
|
||||
public SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext devices) : base(Create<EffectImpl>(devices))
|
||||
{
|
||||
_linearized = new LinearizeCustomEffect(devices);
|
||||
if (!IsEnabled)
|
||||
return;
|
||||
|
||||
using var linearized = _linearized.Output;
|
||||
base.SetInput(LinearInput, linearized, true);
|
||||
}
|
||||
|
||||
public new bool IsEnabled => base.IsEnabled && _linearized.IsEnabled;
|
||||
|
||||
public new void SetInput(int index, ID2D1Image? input, RawBool invalidate)
|
||||
{
|
||||
base.SetInput(index, input, invalidate);
|
||||
if (index == SourceInput)
|
||||
_linearized.SetInput(SourceInput, input, invalidate);
|
||||
}
|
||||
|
||||
protected override void DisposeCore(nint nativePointer, bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
_linearized.Dispose();
|
||||
|
||||
base.DisposeCore(nativePointer, disposing);
|
||||
}
|
||||
|
||||
internal enum PropertyIndex
|
||||
{
|
||||
Distance = 0,
|
||||
@@ -21,6 +54,7 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
||||
Dispersion,
|
||||
ReferenceWavelength,
|
||||
Steps,
|
||||
Physical,
|
||||
}
|
||||
|
||||
public float Distance { set => SetValue((int)PropertyIndex.Distance, value); }
|
||||
@@ -32,17 +66,22 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
||||
public int Dispersion { set => SetValue((int)PropertyIndex.Dispersion, value); }
|
||||
public float ReferenceWavelength { set => SetValue((int)PropertyIndex.ReferenceWavelength, value); }
|
||||
public int Steps { set => SetValue((int)PropertyIndex.Steps, value); }
|
||||
public int Physical { set => SetValue((int)PropertyIndex.Physical, value); }
|
||||
|
||||
[CustomEffect(1)]
|
||||
[CustomEffect(2)]
|
||||
internal sealed class EffectImpl : D2D1CustomShaderEffectImplBase<EffectImpl>
|
||||
{
|
||||
private ConstantBuffer _cb;
|
||||
private PhysicalConstantBuffer _physicalCb;
|
||||
private ShiftMode _mode = ShiftMode.Linear;
|
||||
private DispersionLaw _dispersion = DispersionLaw.Grating;
|
||||
private Vector2 _centerOffset;
|
||||
private float _referenceWavelength = Spectrum.DefaultReferenceWavelength;
|
||||
private int _steps = Spectrum.DefaultSteps;
|
||||
private bool _tableStale = true;
|
||||
private bool _spectralStale = true;
|
||||
private bool _physical;
|
||||
private Guid _shader = GUID_PixelShader;
|
||||
|
||||
[CustomEffectProperty(PropertyType.Float, (int)PropertyIndex.Distance)]
|
||||
public float Distance
|
||||
@@ -122,6 +161,7 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
||||
{
|
||||
_dispersion = value == (int)DispersionLaw.Prism ? DispersionLaw.Prism : DispersionLaw.Grating;
|
||||
_tableStale = true;
|
||||
_spectralStale = true;
|
||||
UpdateConstants();
|
||||
}
|
||||
}
|
||||
@@ -134,6 +174,7 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
||||
{
|
||||
_referenceWavelength = Spectrum.ClampReference(value);
|
||||
_tableStale = true;
|
||||
_spectralStale = true;
|
||||
UpdateConstants();
|
||||
}
|
||||
}
|
||||
@@ -147,11 +188,23 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
||||
_steps = Spectrum.ClampSteps(value);
|
||||
_cb.Steps = _steps;
|
||||
_tableStale = true;
|
||||
_spectralStale = true;
|
||||
UpdateConstants();
|
||||
}
|
||||
}
|
||||
|
||||
public EffectImpl() : base(ShaderResourceUri.Get("SpectrumColorShift"))
|
||||
[CustomEffectProperty(PropertyType.Int32, (int)PropertyIndex.Physical)]
|
||||
public int Physical
|
||||
{
|
||||
get => _physical ? 1 : 0;
|
||||
set
|
||||
{
|
||||
_physical = value != 0;
|
||||
UpdateConstants();
|
||||
}
|
||||
}
|
||||
|
||||
public EffectImpl() : base(StepShaders.DefaultBytes)
|
||||
{
|
||||
_cb.Direction = Vector2.UnitX;
|
||||
_cb.Radius = 1f;
|
||||
@@ -160,6 +213,12 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
||||
_cb.Steps = Spectrum.DefaultSteps;
|
||||
}
|
||||
|
||||
public override void Initialize(ID2D1EffectContext effectContext, ID2D1TransformGraph transformGraph)
|
||||
{
|
||||
base.Initialize(effectContext, transformGraph);
|
||||
StepShaders.Load(effectContext);
|
||||
}
|
||||
|
||||
protected override void UpdateConstants()
|
||||
{
|
||||
if (drawInformation is null)
|
||||
@@ -167,14 +226,19 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
||||
|
||||
try
|
||||
{
|
||||
if (_tableStale)
|
||||
_cb.SpreadScale = ShiftGeometry.Spread(_mode, _cb.Distance, _cb.Radius);
|
||||
|
||||
var shader = StepShaders.Select(_physical, _steps);
|
||||
if (shader != _shader)
|
||||
{
|
||||
Spectrum.Fill(_cb.Samples, _steps, _referenceWavelength, _dispersion);
|
||||
_tableStale = false;
|
||||
drawInformation.SetPixelShader(shader, PixelOptions.None);
|
||||
_shader = shader;
|
||||
}
|
||||
|
||||
_cb.SpreadScale = ShiftGeometry.Spread(_mode, _cb.Distance, _cb.Radius);
|
||||
drawInformation.SetPixelShaderConstantBuffer(_cb);
|
||||
if (_physical)
|
||||
SendPhysicalConstants();
|
||||
else
|
||||
SendConstants();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
@@ -183,6 +247,37 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
||||
}
|
||||
}
|
||||
|
||||
private void SendConstants()
|
||||
{
|
||||
if (_tableStale)
|
||||
{
|
||||
Spectrum.Fill(_cb.Samples, _steps, _referenceWavelength, _dispersion);
|
||||
_tableStale = false;
|
||||
}
|
||||
|
||||
drawInformation!.SetPixelShaderConstantBuffer(_cb);
|
||||
}
|
||||
|
||||
private void SendPhysicalConstants()
|
||||
{
|
||||
if (_spectralStale)
|
||||
{
|
||||
Spectrum.FillSpectral(_physicalCb.Samples, _steps, _referenceWavelength, _dispersion);
|
||||
_spectralStale = false;
|
||||
}
|
||||
|
||||
_physicalCb.InputBounds = _cb.InputBounds;
|
||||
_physicalCb.Direction = _cb.Direction;
|
||||
_physicalCb.Center = _cb.Center;
|
||||
_physicalCb.Distance = _cb.Distance;
|
||||
_physicalCb.Radius = _cb.Radius;
|
||||
_physicalCb.Strength = _cb.Strength;
|
||||
_physicalCb.Mode = _cb.Mode;
|
||||
_physicalCb.Steps = Spectrum.Padded(_steps);
|
||||
_physicalCb.SpreadScale = _cb.SpreadScale;
|
||||
drawInformation!.SetPixelShaderConstantBuffer(_physicalCb);
|
||||
}
|
||||
|
||||
public override void MapInputRectsToOutputRect(
|
||||
RawRect[] inputRects,
|
||||
RawRect[] inputOpaqueSubRects,
|
||||
@@ -207,16 +302,13 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
||||
|
||||
public override void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects)
|
||||
{
|
||||
if (inputRects.Length == 0)
|
||||
return;
|
||||
var requested = inputRect.Right <= inputRect.Left || inputRect.Bottom <= inputRect.Top
|
||||
? inputRect
|
||||
: ShiftGeometry.Input(outputRect, _mode, _cb.Distance, _cb.Direction, _cb.Center, _cb.Radius);
|
||||
var used = _physical ? LinearInput : SourceInput;
|
||||
|
||||
if (inputRect.Right <= inputRect.Left || inputRect.Bottom <= inputRect.Top)
|
||||
{
|
||||
inputRects[0] = inputRect;
|
||||
return;
|
||||
}
|
||||
|
||||
inputRects[0] = ShiftGeometry.Input(outputRect, _mode, _cb.Distance, _cb.Direction, _cb.Center, _cb.Radius);
|
||||
for (var index = 0; index < inputRects.Length; index++)
|
||||
inputRects[index] = index == used ? requested : default;
|
||||
}
|
||||
|
||||
public override RawRect MapInvalidRect(int inputIndex, RawRect invalidInputRect)
|
||||
@@ -240,6 +332,29 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
||||
private Vector4 _element;
|
||||
}
|
||||
|
||||
[InlineArray(Spectrum.SpectralTableLength)]
|
||||
private struct SpectralSampleTable
|
||||
{
|
||||
private Vector4 _element;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct PhysicalConstantBuffer
|
||||
{
|
||||
public Vector4 InputBounds;
|
||||
public Vector2 Direction;
|
||||
public Vector2 Center;
|
||||
public float Distance;
|
||||
public float Radius;
|
||||
public float Strength;
|
||||
public int Mode;
|
||||
public int Steps;
|
||||
public float SpreadScale;
|
||||
public float Pad1;
|
||||
public float Pad2;
|
||||
public SpectralSampleTable Samples;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct ConstantBuffer
|
||||
{
|
||||
|
||||
@@ -78,6 +78,15 @@ public sealed class SpectrumColorShiftEffect : VideoEffectBase
|
||||
}
|
||||
private int _steps = Spectrum.DefaultSteps;
|
||||
|
||||
[Display(GroupName = nameof(Texts.SpectrumGroup), Name = nameof(Texts.Physical), Description = nameof(Texts.PhysicalDescription), Order = 9, ResourceType = typeof(Texts))]
|
||||
[ToggleSlider]
|
||||
public bool Physical
|
||||
{
|
||||
get => _physical;
|
||||
set => Set(ref _physical, value);
|
||||
}
|
||||
private bool _physical;
|
||||
|
||||
private IAnimatable[]? _animatables;
|
||||
|
||||
public override IEnumerable<string> CreateExoVideoFilters(
|
||||
|
||||
@@ -46,7 +46,8 @@ internal sealed class SpectrumColorShiftEffectProcessor(
|
||||
(float)(_item.Strength.GetValue(frame, length, fps) / 100.0),
|
||||
(int)_item.Dispersion,
|
||||
(float)_item.ReferenceWavelength.GetValue(frame, length, fps),
|
||||
_item.Steps);
|
||||
_item.Steps,
|
||||
_item.Physical);
|
||||
|
||||
if (_isFirst || _parameters.Distance != parameters.Distance)
|
||||
_effect.Distance = parameters.Distance;
|
||||
@@ -66,6 +67,8 @@ internal sealed class SpectrumColorShiftEffectProcessor(
|
||||
_effect.ReferenceWavelength = parameters.ReferenceWavelength;
|
||||
if (_isFirst || _parameters.Steps != parameters.Steps)
|
||||
_effect.Steps = parameters.Steps;
|
||||
if (_isFirst || _parameters.Physical != parameters.Physical)
|
||||
_effect.Physical = parameters.Physical ? 1 : 0;
|
||||
|
||||
_parameters = parameters;
|
||||
_isFirst = false;
|
||||
@@ -122,5 +125,6 @@ internal sealed class SpectrumColorShiftEffectProcessor(
|
||||
float Strength,
|
||||
int Dispersion,
|
||||
float ReferenceWavelength,
|
||||
int Steps);
|
||||
int Steps,
|
||||
bool Physical);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace SpectrumColorShift;
|
||||
|
||||
internal static class StepShaders
|
||||
{
|
||||
private const string LegacyName = "SpectrumColorShift";
|
||||
private const string PhysicalName = "SpectrumColorShiftPhysical";
|
||||
|
||||
private static readonly Variants Legacy = new(LegacyName);
|
||||
private static readonly Variants Physical = new(PhysicalName);
|
||||
|
||||
public static IEnumerable<int> Counts => Enumerable.Range(0, Variants.Length).Select(CountAt);
|
||||
|
||||
public static byte[] DefaultBytes => Legacy.Bytes(Spectrum.DefaultSteps);
|
||||
|
||||
public static string ResourceName(bool physical, int count) => (physical ? Physical : Legacy).ResourceName(count);
|
||||
|
||||
public static Guid Select(bool physical, int steps) => (physical ? Physical : Legacy).Id(steps);
|
||||
|
||||
public static void Load(ID2D1EffectContext effectContext)
|
||||
{
|
||||
Legacy.Load(effectContext);
|
||||
Physical.Load(effectContext);
|
||||
}
|
||||
|
||||
private static int CountAt(int index) => Spectrum.MinSteps + index * Spectrum.StepQuantum;
|
||||
|
||||
private sealed class Variants(string name)
|
||||
{
|
||||
public static int Length { get; } = (Spectrum.MaxSteps - Spectrum.MinSteps) / Spectrum.StepQuantum + 1;
|
||||
|
||||
private readonly Guid[] _ids = [.. Enumerable.Range(0, Length).Select(_ => Guid.NewGuid())];
|
||||
private readonly Lazy<byte[]>[] _bytes = [.. Enumerable.Range(0, Length).Select(index => new Lazy<byte[]>(() => Read(name, CountAt(index))))];
|
||||
|
||||
public string ResourceName(int count) => $"{name}{count}";
|
||||
|
||||
public Guid Id(int steps) => _ids[IndexOf(steps)];
|
||||
|
||||
public byte[] Bytes(int steps) => _bytes[IndexOf(steps)].Value;
|
||||
|
||||
public void Load(ID2D1EffectContext effectContext)
|
||||
{
|
||||
for (var index = 0; index < Length; index++)
|
||||
{
|
||||
var bytes = _bytes[index].Value;
|
||||
effectContext.LoadPixelShader(_ids[index], bytes, bytes.Length);
|
||||
}
|
||||
}
|
||||
|
||||
private static int IndexOf(int steps) => (Spectrum.Padded(steps) - Spectrum.MinSteps) / Spectrum.StepQuantum;
|
||||
|
||||
private static byte[] Read(string name, int count) => PackResourceReader.ReadAllBytes(ShaderResourceUri.Get($"{name}{count}"));
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,8 @@ ReferenceWavelength,,基準波長,Reference Wavelength,基准波长,基準波長
|
||||
ReferenceWavelengthDescription,,ずれずにその位置に残る色の波長です。単位はnmで、450付近が青、550付近が緑、650付近が赤です,"Sets the wavelength in nm of the color that stays in place. Around 450 is blue, 550 is green, and 650 is red.",设置保持原位的颜色的波长,单位为nm。450附近为蓝色,550附近为绿色,650附近为红色。,設定保持原位的顏色的波長,單位為nm。450附近為藍色,550附近為綠色,650附近為紅色。,"제자리에 남는 색의 파장입니다. 단위는 nm이며 450 부근이 파랑, 550 부근이 초록, 650 부근이 빨강입니다.","Establece la longitud de onda, en nm, del color que permanece en su sitio. Alrededor de 450 es azul, 550 verde y 650 rojo.",يحدد الطول الموجي، بوحدة nm، للون الذي يبقى في مكانه. حوالي 450 أزرق و550 أخضر و650 أحمر.,"Mengatur panjang gelombang warna yang tetap di tempatnya, dalam nm. Sekitar 450 biru, 550 hijau, dan 650 merah."
|
||||
Steps,,ステップ数,Steps,步数,步數,단계 수,Pasos,عدد الخطوات,Langkah
|
||||
StepsDescription,,スペクトルを分ける数です。距離を大きくするときは増やすと、色が段になって見えるのを防げます,"Sets how many wavelengths the spectrum is divided into. For large distances, raise it to keep the colors from appearing as separate copies.",设置光谱的分割数。距离较大时请增大该值,以免颜色呈分层的重影。,設定光譜的分割數。距離較大時請增大此值,以免顏色呈分層的重影。,스펙트럼을 나누는 수입니다. 거리를 크게 할 때는 늘리면 색이 계단처럼 보이는 것을 막을 수 있습니다.,"Establece en cuántas longitudes de onda se divide el espectro. Con distancias grandes, auméntelo para evitar que los colores se vean como copias separadas.",يحدد عدد الأطوال الموجية التي يقسم إليها الطيف. عند المسافات الكبيرة، ارفعه لتجنب ظهور الألوان كنسخ منفصلة.,"Mengatur jumlah panjang gelombang yang dipakai untuk membagi spektrum. Untuk jarak besar, naikkan agar warna tidak tampak sebagai salinan terpisah."
|
||||
Physical,,物理ベース,Physically Based,基于物理,基於物理,물리 기반,Basado en física,قائم على الفيزياء,Berbasis fisika
|
||||
PhysicalDescription,,オンにすると、映像の色から光のスペクトルを推定し、波長ごとの光をずらして足し合わせます。色の足し合わせは、光の量で行います。オフでは、赤、緑、青を別々にずらします,"When on, the spectrum of light is estimated from the color of the image, and the light of each wavelength is shifted before being summed. Colors are summed as amounts of light. When off, red, green and blue are shifted separately.",开启后,根据图像的颜色估计光的光谱,将各波长的光错开后再叠加。颜色的叠加以光量进行。关闭时,红、绿、蓝分别错开。,開啟後,根據影像的顏色估計光的光譜,將各波長的光錯開後再疊加。顏色的疊加以光量進行。關閉時,紅、綠、藍分別錯開。,"켜면 영상의 색에서 빛의 스펙트럼을 추정하고, 파장별 빛을 어긋나게 한 뒤 더합니다. 색의 합산은 빛의 양으로 합니다. 끄면 빨강, 초록, 파랑을 따로 어긋나게 합니다.","Al activarlo, se estima el espectro de la luz a partir del color de la imagen y se desplaza la luz de cada longitud de onda antes de sumarla. Los colores se suman como cantidades de luz. Desactivado, el rojo, el verde y el azul se desplazan por separado.",عند التفعيل، يُقدَّر طيف الضوء من لون الصورة، ويُزاح ضوء كل طول موجي ثم تُجمع الأطوال الموجية. يتم جمع الألوان بوصفها كميات من الضوء. عند الإيقاف، تُزاح ألوان الأحمر والأخضر والأزرق بشكل منفصل.,"Jika diaktifkan, spektrum cahaya diperkirakan dari warna gambar, lalu cahaya tiap panjang gelombang digeser sebelum dijumlahkan. Warna dijumlahkan sebagai jumlah cahaya. Jika dinonaktifkan, merah, hijau, dan biru digeser secara terpisah."
|
||||
TagColorShift,,色ずれ,color shift,色偏,色偏,색 어긋남,desfase de color,إزاحة اللون,pergeseran warna
|
||||
TagChromaticAberration,,色収差,chromatic aberration,色差,色差,색수차,aberración cromática,الزيغ اللوني,aberasi kromatik
|
||||
TagSpectrum,,スペクトル,spectrum,光谱,光譜,스펙트럼,espectro,الطيف,spektrum
|
||||
|
||||
|
バイナリファイルは表示されません。
|
変更後 幅: | 高さ: | サイズ: 257 KiB |
新しいイシューから参照
ユーザーをブロックする