24. 物理ベースレンダリング

第10章からずっと、あたし達の面はBlinn-Phongで照らされて来ました。
拡散色、鏡面色、光沢度の指数で、全部目で見て選んだ値です。
第14章ではglTFのモデルを読み込みました。
其のマテリアルは物理ベースの金属・粗さ(metallic-roughness)の値で書かれていて、phongFromPbrでBlinn-Phongに押し込みました。
14.6節で其れを「正しい変換ではなく、一時的な橋」と呼び、本物は此の章でと約束しました。
第18章では金属に映り込む空を与えましたが、ボックスフィルターのミップマップを使った予告編で、ちゃんとした版は矢張り此処でと約束しました。

此の章で其の両方を返します。
物理ベースのシェーダーpbr.fragを作ります。
GGXの分布、Smithの幾何項、Fresnel–SchlickによるCook–TorranceのBRDFで、glTFの金属・粗さの値をglTFの仕様が定める通りに使います。
そして点光源、スポットライト、平行光源だけでなく、空全体でも照らします。
イメージベースドライティング(IBL)です。
起動時に、第18章の空のキューブマップからシェーダーで3つのテクスチャを作ります。
パラメーターが何をするか見る為に、プラスチックから金属へ、鏡の様な滑らかさから完全な粗さへと並ぶ7 × 7の球の格子も作ります。
最後に、此れがパート4の最後の章なので、パート4を振り返ります。

24.1 此の章で作る物

シーンは第23章の庭です。
レンガの壁、葉の茂ったパーゴラの下の樽、木箱、ジオラマがあり、今はpbr.fragで描かれます。
樽の前には新しい見本の球が4つ立っています。
磨いた金、クロム、粗い銅、赤いプラスチックです。

物理ベースで描いた第23章のシーン。レンガの壁、葉のパーゴラ、樽、木箱、風車のジオラマ。手前に4つの球:金、青い空を映すクロム、粗い銅、艶のある赤いプラスチック

動画ではカメラがシーンの周りを回ります。
球や樽の箍(たが)の映り込みが視点と一緒に動き、拡散の陰影は動かない事に注目して下さい:

操作:

  • W、A、S、D、スペース、左Ctrl、Shift、マウス、ホイール:今迄通り移動と見回し
  • M:PBR ⇔ Blinn-Phong、比較用(新規)
  • L:光、直接光+IBL → 直接光だけ → IBLだけ(新規)
  • K:カメラの移動、シーン → 球の格子 → 見本の球(新規)
  • V:表示モード。PBRでは全部、ベースカラー、金属度、粗さ、遮蔽、法線、直接光だけ、IBLだけ、影(新しい一覧)
  • H:影のオン・オフ
  • =と−:露出、1〜6:ポストプロセスの効果、C:FPS ⇔ オービットカメラ、N:昼 ⇔ 夜、F:懐中電灯、P:風車を止める
  • Tab:カーソルの解放、R:シェーダーを読み直す(IBLも作り直す)、Esc:終了

第23章の影のキーB、K、G、J、Z、Oは無くなりました。
其の設定は第23章の既定値(テクセル単位のバイアス、PCF 3 × 3、シーン全体を囲む光の箱)の定数になり、コードの道筋は残っています。
Kはカメラの移動に使い回しています。

第23章からの変更:

  • shaders/pbr.frag(新規):物理ベースのフラグメントシェーダー。頂点シェーダーはphong.vert
  • shaders/ibl_irradiance.frag、shaders/ibl_prefilter.frag、shaders/ibl_brdf.frag(新規):IBLのテクスチャを作る3つのシェーダー。post.vertの全画面の三角形で描く
  • src/ibl.hhとsrc/ibl.cc(新規):其れらを1回だけ実行するIblクラス
  • src/pbr_material.hhとsrc/pbr_material.cc(新規):glTFのマテリアルのモデルをC++の構造体にしたPbrMaterialと、toBlinnPhong()
  • src/model.hhとsrc/model.cc:enum class Shading。モデルをどちらのマテリアルのモデルでも描ける様に
  • src/main.cc:手で作るマテリアルを全部PbrMaterialに、見本の球と球の格子、新しいキー
  • CMakeLists.txt:2つの新しい.ccファイル

phong.fragは其のまま残り、Mで其れに戻せます。
第23章の前列の草の株2つは、見本の球を隠していたので消しました。

24.2 光を測る:放射輝度と放射照度

Blinn-Phongには単位が要りませんでした。
光には色があり、面にも色があり、其れを掛けるだけでした。
物理ベースのモデルは何を掛けているかを言わなければならないので、放射測定学の量が2つ必要です。
短くしますが、此の2つの言葉は全ての節に出て来ます。

左:放射輝度。法線からθの角度にある、一つの細い方向の円錐dωから面の一点に届く光。右:放射照度。点の上の半球の全ての方向からの光で、矢印は其々cos θで重み付けされている

放射輝度(radiance)Lは、一つの方向に進む光です。
単位面積(光線に垂直に測る)・単位立体角あたりのパワーで、単位はワット毎平方メートル毎ステラジアンです。
立体角は角度の3D版で、方向の円錐が単位球から切り取る面積です。
球全体は4πステラジアン、半球は2πです。
放射輝度はカメラのピクセルが測る物で、フラグメントシェーダーが出力する物でもあります。
「此の点から目の方へどれだけの光が出るか」です。
便利な性質が一つあります。
何も無い空間を通る光線に沿って放射輝度は変わらないので、ある方向の空の放射輝度は、空がどれだけ遠くても同じです。

放射照度(irradiance)Eは、面の一点に、其の上の半球の全ての方向から届く光の合計で、単位面積あたりのパワーです:

E=∫ΩLi(𝐥)(𝐧⋅𝐥)dω

Ωは法線𝐧の周りの半球、𝐥は其の方向を動き、dωは小さな立体角の欠片、Li(𝐥)は𝐥から届く放射輝度です。
コサイン𝐧⋅𝐥はGLSL 第4章のランバートの法則です。
斜めに届く光は広い面積に広がります。
空がどの方向でも同じ放射輝度Lなら、積分はE=πLです。
∫Ωcosθdω=πだからです(2πではありません。コサインが地平線の近くを0迄下げます)。
此のπは24.6節で効いて来ます。

面の反射は其のBRDF(双方向反射率分布関数)f(𝐥,𝐯)で表します。
𝐥から届く光について、目の方向𝐯へ出て行く放射輝度が、放射照度1あたりどれだけかです。
単位は「毎ステラジアン」で、1より大きくなる事もあります。
鏡は全てを一つの方向に送るので、其の方向のBRDFは巨大です。
してはいけないのはエネルギーを作る事です。
全ての出て行く方向で反射した合計は、届いた量以下でなければなりません。

24.3 レンダリング方程式

此の言葉を使うと、全てのピクセルの明るさは一つの方程式、レンダリング方程式(James Kajiya、1986年)になります:

Lo(𝐯)=Le(𝐯)+∫Ωf(𝐥,𝐯)Li(𝐥)(𝐧⋅𝐥)dω

点から目の方へ出る放射輝度Loは、点自身が出す光Le(発光の項)に、半球の全ての方向から届く光をBRDFとコサインで重み付けした物を足した物です。
本物のレンダラーではLi自体が方向𝐥にある面のLoなので、方程式は再帰的になります。
パストレーサーが何時間も光線を撃つのは其の為です。
リアルタイムのレンダラーは、届く光を払える部分に分けます:

届く光 積分の求め方 場所
太陽、点光源、スポットライト 光は其々一つの方向:積分は光の和になる pbr.fragのdirectLight()
空(其れ以外の全て) 起動時に3つのテクスチャに前計算し、ピクセル毎に引く 24.10節のIBLのマップ
他の面(跳ね返った光) 全くしない(遮蔽マップが隙間を暗くするだけ) 本物のエンジン:プローブ、SSR、GI

点光源類(punctual light:点、スポット、平行)は、丁度一つの方向から放射照度を届けます。
其の様な光では積分が一つの項f(𝐥,𝐯)E⊥(𝐧⋅𝐥)に潰れます。
E⊥は光の方を向いた面での放射照度です。
従って直接光に必要なのは一つだけ、良いBRDF fです。

24.4 微小面とエネルギー保存

小さな鏡

物理ベースのシェーディングは微小面理論(マイクロファセット理論)から始まります。
滑らかに見える面も、顕微鏡で見ると小さな平らな面(微小面)の起伏で、其々が完全な鏡です。
面の粗さは、微小面の法線が平均の法線𝐧の周りにどれだけ散らばるかで決まります。

拡大した粗い面の断面。法線が半ベクトルhと等しい微小面は黄色で示され、光の向きlを視線の向きvへ反射する。其の内2つは隣の山の影に入って光が届かず、1つは山に隠れて目から見えない

鏡が𝐥からの光を𝐯へ反射するのは、其の法線が丁度2つの真ん中、半ベクトルの方向にある時だけです:

𝐡=𝐥+𝐯‖𝐥+𝐯‖

第10章とGLSL 第9章のBlinnの半ベクトルで、何故其れが上手く行くのかが此処で分かります。
1ピクセルの下にある微小面の内、目に光を送るのは法線が𝐡の物だけです。
従って鏡面反射は「𝐡を向いた微小面がどれだけあるか」(分布D)×「其の内、影にも隠れてもいない物がどれだけあるか」(幾何項G)×「一つの微小面が此の角度でどれだけ反射するか」(フレネル項F)です。
其れがCook–Torranceの鏡面項の構造の全てです。

反射されない光

微小面は表面で光の割合Fを反射します。
残りの1−Fは物質の中に入り、其処で何が起きるかで、金属度のパラメーターが切り替える2種類の物質が分かれます。

左:誘電体は表面で白い小さな部分Fを反射する。残りは中に入り、表面の下で散乱し、ベースカラーに色付いて全ての方向へ出て行く。右:金属はベースカラーに色付いた大きな部分を反射する。中に入った部分はすぐに吸収されるので拡散光は無い

  • 誘電体(プラスチック、木、石、肌、塗料)は正面で約4%を反射し、其の反射は白です。赤いボールのハイライトは赤くありません。中に入った光は顔料に散乱され、吸収されなかった色に染まってランダムな方向に出て来ます。其れが拡散反射で、見える色がベースカラーです。
  • 金属は表面で50〜100%を反射し、其の量が波長で変わるので、反射自体に色が付きます。金は赤と緑を青よりずっと良く反射します。中に入った光は自由電子にナノメートル単位で吸収されます。金属には拡散反射が全く無いのです。

エネルギー保存は此処から直接出て来ます。
鏡面反射になった光は、拡散光として出て行く事は出来ません。
其の為、拡散の部分には次を掛けます:

𝐤d=(1−𝐅)(1−m)

mは金属度です。
1−𝐅は表面を通った分、1−mは金属が其れを吸収するからです。
Blinn-Phongは拡散と鏡面を別々に足していたので、白い面の明るいハイライトは届いたより多くの光を反射する事がありました。
其れがBlinn-Phongが「正しく」見えなかった2つの大きな理由の一つです(もう一つはフレネル効果が無い事)。

24.5 Cook–TorranceのBRDF

pbr.fragのBRDFは、glTF、Unreal Engine 4、Unity、Godot、Filamentが全て何らかの形で使っている物です:

f(𝐥,𝐯)=𝐤d𝐛π+DG𝐅4(𝐧⋅𝐥)(𝐧⋅𝐯)

𝐛はベースカラーです。
1つ目の項はランバートの拡散のBRDFです。
1/πがエネルギー保存の為の物です。
白いランバート面(𝐛=1)は、届いた光の∫Ω1πcosθdω=ππ=1、丁度全てを反射します。
2つ目の項はCook–Torranceの微小面の鏡面項(Robert CookとKenneth Torrance、1982年)で、D、G、𝐅は前の節の物です。
分母の4(𝐧⋅𝐥)(𝐧⋅𝐯)は、「𝐡の立体角あたりの微小面」をBRDFの「放射照度あたりの放射輝度」に直します。
4は𝐡の立体角と反射方向の立体角の関係から、2つのコサインは微小面を光から見た時と目から見た時の面への射影から来ます。

pbr.fragの其の部分の頭にあるコメントです:

//------------------------------------------------------------------
// Cook–TorranceのBRDF:f = kd · base/π + D · G · F / (4 (n·l)(n·v))
// The Cook–Torrance BRDF: f = kd · base/π + D · G · F / (4 (n·l)(n·v))
//------------------------------------------------------------------

では3つの項を、シェーダーが計算する通りに見て行きましょう。

D:GGXの分布

法線分布関数は、微小面の内𝐡を向いている物の割合を表します。
正確にはステラジアンあたりの密度で、射影した微小面の面積を積分すると面の面積になります:∫D(𝐡)(𝐧⋅𝐡)dωh=1。
使うのはGGX、又の名をTrowbridge-Reitzです(TrowbridgeとReitzが1975年に記述し、Walterらが2007年にGGXとして再び紹介しました):

D(𝐡)=α2π((𝐧⋅𝐡)2(α2−1)+1)2,α=r2

// D:法線の分布(GGX / Trowbridge-Reitz)。微小な面のうち、hを向いているものの割合。α = 粗さ²(glTF・UE4と同じ)
// D: the normal distribution (GGX / Trowbridge-Reitz): the share of microfacets facing h. α = roughness² (as glTF/UE4)
float distributionGgx(float nDotH, float roughness) {
  float a = roughness * roughness;
  float a2 = a * a;
  float d = nDotH * nDotH * (a2 - 1.0) + 1.0;
  return a2 / (PI * d * d);
}

rはglTFの粗さで、アーティストが打ち込む「知覚的な」値です。
式が欲しいのはα=r2で、此れでスライダーの見た目の変化が均等になります(ディズニーのBrent Burleyの観察で、Unreal Engine 4とglTFが採用しました)。
𝐧⋅𝐡=1では分母がπα4になるので、頂点はD=1/(πα2)です:

粗さr α=r2 頂点 D=1/(πα2)
0.25 0.0625 81.49
0.5 0.25 5.093
1.0 1.0 0.3183 = 1/π

滑らかな面は全ての微小面を細く高い山に集め、粗い面は広げます。
r=1では分布は完全に平らで、どの𝐡でも1/πです。
古い論文のベックマン分布(第14章のBlinn-Phongの指数が真似している物)と比べると、GGXは裾が長く、頂点から離れてもゆっくりしか下がりません。
其れがハイライトに、本物の物質が持つ「鋭い芯の周りの柔らかい光」を与えます。

G:Smithのシャドウイングとマスキング

𝐡を向いた微小面が全て効く訳ではありません。
微小面の図の様に、隣の影に入る物(光が届かない)や、隣の後ろに隠れる物(目から見えない)があります。
幾何項Gは、其の両方を生き延びた割合です。
Smithの方法はシャドウイングとマスキングが独立だと仮定するので、Gは光の分と視線の分の積になり、其々にGGX版のSchlickの近似を使います:

G=G1(𝐧⋅𝐯)G1(𝐧⋅𝐥),G1(x)=xx(1−k)+k,k=(r+1)28

// G:幾何減衰(Smith法にSchlick-GGX)。微小な面が互いに影を作り、隠し合う分。直接光ではk = (r + 1)² / 8
// G: geometric attenuation (Smith with Schlick-GGX): microfacets shadowing and masking each other. k = (r + 1)² / 8 for
// direct light
float geometrySmith(float nDotV, float nDotL, float roughness) {
  float k = (roughness + 1.0) * (roughness + 1.0) / 8.0;
  float gv = nDotV / (nDotV * (1.0 - k) + k);
  float gl = nDotL / (nDotL * (1.0 - k) + k);
  return gv * gl;
}

G1は真上から見ると(x=1)1で、斜めになると0迄下がり、粗い面程早く下がります。
定数kは2種類あるので注意が必要です:

  • 直接光:k=(r+1)2/8。Karis(Unreal Engine 4、2013年)は、ディズニーのBurleyの修正を取り入れて、k=α/2を計算する前に粗さを(r+1)/2に「付け替え」ました。其のままでは点光源類の下で粗い面が斜めから明る過ぎたからです。
  • イメージベースドライティング:k=α/2=r2/2、付け替え無し。24.10節のBRDFの表は此方を使います。

r 直接光のk=(r+1)2/8 IBLのk=r2/2
0.25 0.1953 0.03125
0.5 0.28125 0.125
1.0 0.5 0.5

取り違えても真っ黒な画面の様な分かり易い事は起きず、粗い面の縁が少し明る過ぎたり暗過ぎたりするだけです。
何ヶ月も見付からずに残るのは、丁度此う言う間違いです。

F:Fresnel–Schlick

フレネル項は第18章(18.10節)と同じSchlickの式ですが、違いが一つあります。
𝐅0が今はRGBの色です。

𝐅=𝐅0+(1−𝐅0)(1−𝐡⋅𝐯)5

// F:フレネル(Schlickの近似)。斜めから見るほど鏡のように反射する / F: Fresnel (Schlick's approximation): the more
// grazing the view, the more mirror-like
vec3 fresnelSchlick(float cosTheta, vec3 f0) {
  return f0 + (1.0 - f0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0);
}

一つの微小面にとって大事な角度は、其の法線𝐡と目の間の角度なので、𝐧⋅𝐯ではなく𝐡⋅𝐯です。
GLSLでは負の底のpowは未定義なので、丸め誤差で内積が1を少し超えても、clampが1−𝐡⋅𝐯を0〜1に保ちます。
誘電体と金の3つのチャンネルの値を幾つか:

角度 誘電体、F0=0.04 金のR(F0=1.0) 金のG(0.766) 金のB(0.336)
0° 0.04 1.0 0.766 0.336
60° 0.070 1.0 0.773 0.357
80° 0.410 1.0 0.856 0.592
90° 1.0 1.0 1.0 1.0

どの物質も斜めから見ると白い鏡になり、金の反射も其処では黄色さを失います。

0〜90度の角度に対する3つのグラフ。粗さ0.25、0.5、0.75のDを頂点の値で割った物:滑らかだと細く、粗いと広い。粗さ0.25、0.5、1のG1:急な角度迄ほぼ1で、其れから0へ下がる。Fresnel–Schlick:誘電体の曲線は60度位迄0.04の近くにあり、其れから1へ上がる。金の赤のチャンネルはどこでも1、緑は0.766、青は0.336から始まり、全て90度で1になる

一つの光

directLight()が一つの光について項を組み合わせます。
Surface構造体がピクセルの全ての情報を運びます:

struct Surface {
  vec3 n, v;
  vec3 base;     // ベースカラー(リニア) / base colour (linear)
  float metallic, roughness;
  vec3 f0;       // 正面の反射率:非金属0.04、金属はベースカラー / reflectance at normal incidence: 0.04 for dielectrics,
                 // the base colour for metals
};

// 一つの光の直接光。radiance = 面に届く光(光の色 × 減衰 × 影)
// Direct light from one light. radiance = the light reaching the surface (light colour × attenuation × shadow)
vec3 directLight(Surface s, vec3 l, vec3 radiance) {
  float nDotL = max(dot(s.n, l), 0.0);
  if (nDotL <= 0.0) return vec3(0.0);
  vec3 h = normalize(l + s.v);
  float nDotV = max(dot(s.n, s.v), 1e-4);
  float nDotH = max(dot(s.n, h), 0.0);
  float d = distributionGgx(nDotH, s.roughness);
  float g = geometrySmith(nDotV, nDotL, s.roughness);
  vec3 f = fresnelSchlick(max(dot(h, s.v), 0.0), s.f0);
  vec3 specular = d * g * f / (4.0 * nDotV * nDotL + 1e-4);
  // エネルギー保存:反射した分(F)は拡散しない。金属は拡散しない / energy conservation: what is reflected (F) does not
  // diffuse, and metals do not diffuse at all
  vec3 kd = (1.0 - f) * (1.0 - s.metallic);
  // このシリーズの光の色は「正面から照らした白い拡散面の明るさ」(Blinn-Phongと同じ意味)。物理的なランバートは
  // base/πなので、光の強さをπ倍して同じ明るさにする
  // Our light colours mean "how bright a white diffuse surface lit head-on looks" (as with Blinn-Phong). Physical
  // Lambert is base/π, so the light is scaled by π to get the same brightness
  return (kd * s.base / PI + specular) * radiance * PI * nDotL;
}

radianceは光の色に減衰、円錐、影を掛けた物で、第12章と第23章で既に計算していた物です。
2つの1e-4は、面が目から背を向ける所(シルエットで𝐧⋅𝐯→0、補間や法線マップの法線では少し負になる事も)で割り算を有限に保ちます。
最後の行にはBRDFに無いPIがあります。
其れが次の節の話題です。

1ピクセルを手で計算してみましょう。
ベースカラー0.5、金属度0、粗さ0.5の灰色のプラスチックを、正面から照らして正面から見ます。
従って𝐧=𝐥=𝐯=𝐡で、内積は全て1です。

  • α=0.25、α2=0.0625、𝐧⋅𝐡=1なのでD=1/(π⋅0.0625)=5.093。
  • k=1.52/8=0.28125、G1(1)=1/(0.71875+0.28125)=1なのでG=1。
  • 𝐡⋅𝐯=1なのでF=F0=0.04。
  • 鏡面:5.093⋅1⋅0.04/4=0.0509。
  • kd=(1−0.04)(1−0)=0.96、拡散:0.96⋅0.5/π=0.1528。
  • f=0.2037毎ステラジアンで、色𝐜の光に対する出力は0.2037⋅π⋅𝐜⋅1=0.640𝐜。

同じマテリアルをtoBlinnPhong(24.8節)でBlinn-Phongにすると、拡散0.5、n=30で鏡面0.04⋅(30+8)/8=0.19、正面では0.5+0.19=0.69 × 𝐜です。
正面から見たプラスチックなら近い値になるのが当然で、2つのモデルが分かれるのは斜めの角度と金属です。

24.6 光の単位:何故光をπ倍するのか

LightsBlock(第19章)には太陽の(2.6, 2.45, 2.2)の様な光の色が入っています。
第10章から、此の色は「正面から照らした白い拡散面に見える色」の意味でした。
Blinn-Phongの拡散項は𝐛⋅𝐜⋅(𝐧⋅𝐥)です。

物理的には、光は放射照度E⊥を届け、ランバートのBRDFが其れを𝐛πE⊥(𝐧⋅𝐥)にします。
PBRの絵が同じLightsBlockでBlinn-Phongの絵と合うには、此の2つが等しくなければなりません:

𝐛πE⊥(𝐧⋅𝐥)=𝐛𝐜(𝐧⋅𝐥)⇒E⊥=π𝐜

其の為directLight()は届く光をπ倍し、直接光の項全体は次の様になります:

Lo=(𝐤d𝐛π+DG𝐅4(𝐧⋅𝐥)(𝐧⋅𝐯))π𝐜(𝐧⋅𝐥)

拡散光では2つの係数が打ち消し合い、Blinn-Phongの𝐤d𝐛𝐜(𝐧⋅𝐥)に戻ります。
鏡面の部分ではπが残りますが、其れで正しいのです。
拡散の部分と同じ光だからです。

何故光の色を放射照度として定義し、C++でπ倍しないのでしょうか。
其うするとBlinn-Phongのモード(M)にはPBRのモードと違う光の色が必要になり、此の章の比較の絵が2つの違う照明を比べる事になるからです。
three.jsも長い間全く同じ事をしていました。
「レガシー」(物理的に正しくない)光のモードでは、此の理由で全ての点光源類をπ倍していました。
此の係数が無いと、日向のPBRのシーンはBlinn-Phongよりπ≈3.14倍暗くなり、明るさを戻すにはlog2π≈1.65段の露出が余分に要ります(課題2)。

イメージベースドライティングには此の様な係数は要りません。
放射照度マップはE/πを其のまま保存していて(24.10節)、其れが既に「白いランバート面の明るさ」だからです。

24.7 glTFの定義通りの金属・粗さ

glTF 2.0の仕様(マテリアルの節と付録B)は、5つのマテリアルの入力がどうBRDFの入力になるかを定めていて、pbr.fragは其れに一字一句従います:

  • ベースカラー𝐛 = baseColorFactor × baseColorTexture(sRGBのテクスチャ、第21章からGPUがリニアに直す)× インスタンスの色合い
  • 金属度m = metallicFactor × metallicRoughnessTextureの青チャンネル
  • 粗さr = roughnessFactor × 同じテクスチャの緑チャンネル、そしてα=r2
  • 𝐅0=mix(0.04,𝐛,m):誘電体は4%、金属は其のベースカラーを反射する
  • 拡散色=𝐛(1−m):此処では𝐤d=(1−𝐅)(1−m)を通して
  • 遮蔽 = 1 + 強さ × (occlusionTextureの赤チャンネル − 1)、間接光だけに掛ける
  • 発光 = emissiveFactor × emissiveTexture × emissiveStrength、上に足す

シェーダーでは、第22章の法線マッピングの後のmain()の此の行です:

  s.v = normalize(uViewPos - vWorldPos);
  s.base = uMaterial.baseColor.rgb * baseSample.rgb * vTint;
  vec4 mr = textureGrad(uMetallicRoughnessMap, uv, uvDx, uvDy);
  s.metallic = clamp(uMaterial.metallic * mr.b, 0.0, 1.0);
  // 粗さ0はGGXが一点に潰れて光が消える:少しだけ残す / roughness 0 collapses GGX to a point and the highlight vanishes:
  // keep a little
  s.roughness = clamp(uMaterial.roughness * mr.g, 0.03, 1.0);
  s.f0 = mix(vec3(0.04), s.base, s.metallic);
  float occlusion = 1.0 + uMaterial.occlusionStrength * (textureGrad(uOcclusionMap, uv, uvDx, uvDy).r - 1.0);
  vec3 emissive = uMaterial.emissive * textureGrad(uEmissiveMap, uv, uvDx, uvDy).rgb;

mix(vec3(0.04), s.base, s.metallic)は丁度glTFの𝐅0の式です。
4%は屈折率約1.5の普通の誘電体の反射率で、((1.5−1)/(1.5+1))2=0.04です(第18章では屈折率1.52のガラスで0.0426でした)。
金属ではベースカラーが𝐅0です。
金と銅の球は測定された反射率(1.0, 0.766, 0.336)と(0.955, 0.638, 0.538)を、sRGBで選んだ値ではなくリニアの値として使います。
「クロム」の球は理想化した95%の鏡(0.95, 0.95, 0.95)です。
本物のクロムは55%位しか反射せず、隣に並べると意外な程くすんで見えます。

テクスチャと其のユニット:

layout(binding = 0) uniform sampler2D uBaseColorMap;         // sRGB
layout(binding = 2) uniform sampler2D uEmissiveMap;          // sRGB
layout(binding = 4) uniform sampler2D uNormalMap;            // リニア、A = 高さ / linear, A = height
layout(binding = 5) uniform sampler2DShadow uShadowMap;      // 第23章 / chapter 23
layout(binding = 7) uniform sampler2D uMetallicRoughnessMap; // G = 粗さ / roughness, B = 金属度 / metallic
layout(binding = 8) uniform sampler2D uOcclusionMap;         // R = 環境光の遮蔽 / ambient occlusion
layout(binding = 9) uniform samplerCube uIrradianceMap;      // 拡散のIBL / diffuse IBL
layout(binding = 10) uniform samplerCube uPrefilteredMap;    // 鏡面のIBL(粗さ = ミップマップ) / specular IBL (roughness = mip)
layout(binding = 11) uniform sampler2D uBrdfLut;             // スプリットサムの表 / the split-sum table
uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く):IBLに掛ける / brightness of the sky: multiplies the IBL

  • ユニット7、金属・粗さ:G = 粗さ、B = 金属度、Rは使わない(エクスポーターによってはRに遮蔽を詰めます。「ORM」テクスチャ、課題4)。色ではなくデータなのでリニアで読み込み、sRGBにはしません。
  • ユニット8、遮蔽:R = 其の点から空がどれだけ見えるか、オフラインで焼いた物。glTFは其れが間接光だけに効くと定めています。樽の溝は空の光では暗いですが、太陽が真っ直ぐ差し込む所は照らされます。直接光に掛けると、照らされた隙間が間違って暗くなります。
  • ユニット9、10、11は24.10節のIBLのテクスチャです。

occlusionStrengthはglTFのocclusionTexture.strengthで、第13章のパーサーは其れをテクスチャ情報のscaleに入れています(どちらも「テクスチャの番号の隣の数」です)。

2つのクランプ

s.roughnessは少なくとも0.03にクランプします。
粗さ0ではGGXがデルタ関数になります。
α=0だとDは𝐧⋅𝐡=1丁度の所以外どこでも0で、其処では0を0で割ります。
丁度其処にあるピクセルは無いので、完全な鏡の上の太陽のハイライトは単に消えてしまいます。
0.03ならα=0.0009で、ハイライトは小さくて極めて明るい点になり、ブルームが其れを煌めきにします。
s.metallicを0〜1にクランプするのは、手で作るマテリアルでは係数 × テクスチャが範囲を出る事があるからです。

データの表示

Vを押すと、シェーダーが実際に使っている入力が見えます。
表示モード2〜5と8は生の数字を見せるので、pbr.fragはポストパスがsRGBにする前に其れをリニアに直し(第22章の技)、mainは其の間トーンマッピングを切ります。
其うすると0.5の値が本当に画面で50%の灰色に見えます。

シーンの4つの表示。ベースカラー:金属の球は淡く、赤い球は鮮やかな赤。金属度:木箱の枠、樽の箍、3つの金属の球、ジオラマの小さな金属の部品幾つかだけが白く、他は黒。粗さ:殆ど明るい灰色で、磨いた球は暗い。遮蔽:樽の溝の細い暗い線以外は白

第14章の橋に出来なかった事

第14章はphongFromPbrが失う物を並べました。
同じ一覧を、今度は返済済みとして:

  • 金属度と粗さはマテリアル毎に平均1つでした。今はユニット7からピクセル毎に読むので、木箱の鋼の枠は金属で、木は金属ではありません(上の金属度の表示と比べて下さい)。
  • 𝐅0はベースカラーの係数を使っていました。今は係数 × テクスチャです。
  • フレネル効果がありませんでした。今はどの面も斜めの角度に向かって明るくなります。
  • 遮蔽は無視していました。今は隙間の空の光を暗くします。法線マップは第22章で来ました。
  • 金属は映す物が無かったので、ハイライトが無い所は真っ黒でした。今はIBLで空を映します。

24.8 PbrMaterialとtoBlinnPhong

マテリアルの構造体

C++側では、物理ベースのマテリアルはglTFのフィールドを持つ普通の構造体です:

// 物理ベースのマテリアル(第24章):glTFの金属・粗さモデルそのまま / a physically based material (chapter 24): exactly
// glTF's metallic-roughness model
#pragma once

#include "gltf.hh"
#include "material.hh"
#include "mathx.hh"
#include "shader.hh"
#include "texture.hh"

// テクスチャはすべて「係数 × テクスチャ」。ないテクスチャには白を繋ぐ(白 × 係数 = 係数)。
// Every texture is "factor × texture". A missing texture is replaced by white (white × factor = factor).
struct PbrMaterial {
  Vec4 baseColor = {1.0f, 1.0f, 1.0f, 1.0f}; // リニア、aは不透明度 / linear, a = opacity
  float metallic = 0.0f;                     // 0 = 非金属(誘電体)、1 = 金属 / 0 = dielectric, 1 = metal
  float roughness = 0.5f;                    // 0 = 鏡、1 = つや消し / 0 = mirror, 1 = fully matte
  Vec3 emissive = {0.0f, 0.0f, 0.0f};        // 発光(HDR、強さを掛けた後) / emission (HDR, strength applied)
  float normalScale = 1.0f;                  // glTFのnormalTexture.scale
  float occlusionStrength = 1.0f;            // glTFのocclusionTexture.strength
  float parallaxScale = 0.0f;                // 第22章の視差(OpenGLのUVの物だけ) / chapter 22 parallax (OpenGL UVs only)
  AlphaMode alphaMode = AlphaMode::Opaque;
  float alphaCutoff = 0.5f;
  bool doubleSided = false;

  const Texture2D *baseColorMap = nullptr;         // ユニット0、sRGB / unit 0, sRGB
  const Texture2D *emissiveMap = nullptr;          // ユニット2、sRGB / unit 2, sRGB
  const Texture2D *normalMap = nullptr;            // ユニット4、リニア / unit 4, linear
  const Texture2D *metallicRoughnessMap = nullptr; // ユニット7:G = 粗さ、B = 金属度、リニア / unit 7: G = roughness, B = metallic
  const Texture2D *occlusionMap = nullptr;         // ユニット8:R = 遮蔽、リニア / unit 8: R = occlusion, linear

  // pbr.fragのuMaterialを設定し、マップを繋ぐ(ないものは白) / sets pbr.frag's uMaterial and binds the maps (white
  // for missing ones)
  void apply(const Shader &shader, const Texture2D &white) const;

  // glTFのマテリアルの係数(テクスチャは呼ぶ側が繋ぐ) / the factors of a glTF material (the caller attaches textures)
  static PbrMaterial fromGltf(const GltfMaterial &m);
};

// 比較用:同じ表面をBlinn-Phongで近似する(第14章のphongFromPbrと同じ式、ただしテクスチャの平均は使わない)
// For comparison: approximate the same surface with Blinn-Phong (the formulas of chapter 14's phongFromPbr, without
// texture averages)
Material toBlinnPhong(const PbrMaterial &m);

既定値はglTFの物ではなく、あたしが選んだ物です。
glTFの既定は金属度1、粗さ1(くすんだ灰色の金属)で、手で作るマテリアルの出発点としては良くありません。
其れがマテリアルの無いモデルに何をしたかは14.6節で説明しました。
フィールドの順番は指示付き初期化子が読み易くなる様にしてあります。
C++20の指示付き初期化子は宣言の順番にフィールドを並べなければならないので、.roughnessは.alphaModeより前、.alphaModeは.baseColorMapより前です。

apply()は第11章の規則に従います。
無いマップは全て1 × 1の白いテクスチャに置き換えるので、シェーダーは何時も係数 × テクスチャを掛け、「テクスチャがあるか」のフラグは要りません。

#include "pbr_material.hh"

void PbrMaterial::apply(const Shader &shader, const Texture2D &white) const {
  shader.set("uMaterial.baseColor", baseColor);
  shader.set("uMaterial.metallic", metallic);
  shader.set("uMaterial.roughness", roughness);
  shader.set("uMaterial.emissive", emissive);
  // 法線マップがなければ0:白(1,1,1)が平らな(0,0,1)になる(第22章) / 0 without a normal map: white (1,1,1) becomes the
  // flat (0,0,1) (chapter 22)
  shader.set("uMaterial.normalScale", normalMap ? normalScale : 0.0f);
  shader.set("uMaterial.parallaxScale", normalMap ? parallaxScale : 0.0f);
  shader.set("uMaterial.occlusionStrength", occlusionStrength);
  shader.set("uMaterial.alphaMode", static_cast<int>(alphaMode));
  shader.set("uMaterial.alphaCutoff", alphaCutoff);
  shader.set("uMaterial.doubleSided", doubleSided ? 1 : 0);
  (baseColorMap ? baseColorMap : &white)->bind(0);
  (emissiveMap ? emissiveMap : &white)->bind(2);
  (normalMap ? normalMap : &white)->bind(4);
  (metallicRoughnessMap ? metallicRoughnessMap : &white)->bind(7);
  (occlusionMap ? occlusionMap : &white)->bind(8);
}

此処では白が全てのマップの中立な値です。
金属・粗さのテクスチャでは(1, 1, 1)が「係数を其のまま使う」、遮蔽では「完全に開けている」の意味です。
法線マップだけは例外で、其の為マップが無ければnormalScaleとparallaxScaleを0にします。
第22章からのMaterial::applyと同じです。

fromGltf()は第13章のGltfMaterialから係数を写します。
テクスチャは呼ぶ側が付けます。
どのTexture2DがどのglTFのテクスチャ番号の物かを知っているのはModelだけだからです:

PbrMaterial PbrMaterial::fromGltf(const GltfMaterial &m) {
  PbrMaterial p;
  p.baseColor = m.baseColorFactor;
  p.metallic = m.metallicFactor;
  p.roughness = m.roughnessFactor;
  p.emissive = m.emissiveStrength * m.emissiveFactor;
  p.normalScale = m.normalTexture.scale;
  p.occlusionStrength = m.occlusionTexture.scale; // glTFのstrengthはscaleに入っている / glTF's strength is stored in scale
  p.alphaMode = m.alphaMode == GltfAlphaMode::Mask    ? AlphaMode::Mask
                : m.alphaMode == GltfAlphaMode::Blend ? AlphaMode::Blend
                                                      : AlphaMode::Opaque;
  p.alphaCutoff = m.alphaCutoff;
  p.doubleSided = m.doubleSided;
  return p;
}

Blinn-Phongへの変換

Mキーの為に、全てのPbrMaterialはphong.fragでも描けなければなりません。
toBlinnPhong()は第14章のphongFromPbr(14.6節の式)を、テクスチャの平均無しで、第18章の映り込みの予告編を足し、マップを其のまま渡す様にした物です:

Material toBlinnPhong(const PbrMaterial &m) {
  Vec3 base = {m.baseColor.x, m.baseColor.y, m.baseColor.z};
  Material p;
  p.diffuse = (1.0f - m.metallic) * base;
  Vec3 f0 = lerp({0.04f, 0.04f, 0.04f}, base, m.metallic);
  float alpha = m.roughness * m.roughness;
  float n = alpha > 0.0f ? 2.0f / (alpha * alpha) - 2.0f : 1024.0f;
  n = n < 1.0f ? 1.0f : n > 1024.0f ? 1024.0f : n;
  p.specular = ((n + 8.0f) / 8.0f) * f0;
  p.shininess = n;
  p.emission = m.emissive;
  p.alpha = m.baseColor.w;
  p.alphaMode = m.alphaMode;
  p.alphaCutoff = m.alphaCutoff;
  p.doubleSided = m.doubleSided;
  p.reflectivity = (m.metallic * m.metallic) * f0;
  p.reflectionBlur = m.roughness;
  p.diffuseMap = m.baseColorMap;
  p.emissionMap = m.emissiveMap;
  p.normalMap = m.normalMap;
  p.normalScale = m.normalScale;
  p.parallaxScale = m.parallaxScale;
  return p;
}

金属・粗さと遮蔽のマップは途中で失われます。
phong.fragには其れを置く場所が無いからです。
其れが比較の正直な状態です。
見せているのは、同じマテリアルでBlinn-Phongに何が出来るかで、調整したBlinn-Phongのシーンではありません。

モデル

Modelは第14章から両方のマテリアルを持っています。
MaterialData::phong(橋)とMaterialData::pbr(glTFの生の値)です。
新しいenumがどちらを使うかを決めます:

// どのマテリアルで描くか(第24章)。シェーダーに合わせる:phong.fragならBlinnPhong、pbr.fragならPbr
// Which material model to draw with (chapter 24). Match the shader: BlinnPhong for phong.frag, Pbr for pbr.frag
enum class Shading {
  BlinnPhong, // MaterialData::phong(第14章の近似) / MaterialData::phong (the chapter 14 approximation)
  Pbr,        // MaterialData::pbrのglTFの値そのまま(PbrMaterial) / MaterialData::pbr's glTF values as they are
};

draw()とdrawInstanced()は其れを最後の引数として受け取り、既定値はShading::BlinnPhongなので、既存の呼び出しは全て其のまま動きます。
drawItems()には、第23章の深度だけの分岐とBlinn-Phongの分岐の間に新しい分岐があります:

    } else if (white && shading == Shading::Pbr) {
      // glTFの値とテクスチャそのまま(第24章) / glTF's values and textures as they are (chapter 24)
      PbrMaterial m = PbrMaterial::fromGltf(md.pbr);
      m.baseColorMap = texture(md.pbr.baseColorTexture.index);
      m.emissiveMap = texture(md.pbr.emissiveTexture.index);
      m.normalMap = texture(md.pbr.normalTexture.index);
      m.metallicRoughnessMap = texture(md.pbr.metallicRoughnessTexture.index);
      m.occlusionMap = texture(md.pbr.occlusionTexture.index);
      m.apply(shader, *white);

glTFの5つのテクスチャを全て付け、ファイルに無い物にはapply()が白を繋ぎます。
glTFのテクスチャの色は第21章で使い方毎に既に決めてあります。
ベースカラーと発光はsRGB、金属・粗さ、法線、遮蔽はリニアです。

mainの手作りのマテリアル

mainが手で作るマテリアルは全てPbrMaterialになりました。
目で選んだ色はsRGBの値なので、小さなラムダが第21章のsrgbToLinearで変換します:

  // 手で作るマテリアルはすべてPbrMaterial(第24章)。Blinn-Phongで描くときはtoBlinnPhongで変換する。
  // 手で選んだ色はsRGBの値なのでsrgbToLinearでリニアに
  // Every hand-made material is a PbrMaterial (chapter 24); for Blinn-Phong they are converted with toBlinnPhong.
  // Hand-picked colours are sRGB values, so srgbToLinear makes them linear
  auto rgb = [](float r, float g, float b, float a = 1.0f) {
    Vec3 c = srgbToLinear(Vec3{r, g, b});
    return Vec4{c.x, c.y, c.z, a};
  };
  Mesh floorMesh = makePlane(160.0f, 40.0f);
  Mesh cubeMesh = makeCube();
  PbrMaterial floorMaterial{.roughness = 0.65f, .baseColorMap = &*floorTexture};

残りはマテリアルエディターのパネルの様に読めます:

  PbrMaterial leavesMaterial{.roughness = 0.8f, .alphaMode = AlphaMode::Mask, .doubleSided = true,
                             .baseColorMap = &*leavesTexture};
  PbrMaterial wireMaterial{.baseColor = rgb(0.04f, 0.04f, 0.045f), .roughness = 0.35f};

粗さの値は、テクスチャのライブラリで見る値と大体同じです。
磨いた金属0.05〜0.2、プラスチック0.3〜0.5、塗った木0.6〜0.8、レンガと石0.8〜0.9です。
出発点は「全て粗さ0.5の誘電体」にして、本当に金属の物だけを金属にするのが定番です。

24.9 シェーダーを組み立てる

頂点シェーダーは其のまま

pbr.fragには自分の頂点シェーダーがありません。
phong.vertの出力(vWorldPos、vNormal、vUv、vTint、vTangent)を其のまま読み、mainは此の組を此う読み込みます:

  std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag");
  // PBR:頂点シェーダーはphongと同じ / PBR: the same vertex shader as phong
  std::optional<Shader> pbr = Shader::load("shaders/phong.vert", "shaders/pbr.frag");

Camera、Lights、Shadow、Postのブロック、shadowFactor()、parallaxOcclusion()、アルファトゥカバレッジ付きのアルファモード、ブルーム用の明るい出力は、phong.fragから一字一句写してあります。
GLSLには#includeが無く、ブロックの大きさがC++の構造体と合わなくなれば、checkUniformBlock(第19章)が起動時に見付けます。
mainはpbrにも其れを実行します。

ユニフォームの構造体

マテリアルのユニフォームはPbrMaterialの写しです:

// glTFのpbrMetallicRoughnessと同じ(係数 × テクスチャ) / the same as glTF's pbrMetallicRoughness (factor × texture)
struct Material {
  vec4 baseColor;          // リニア、aは不透明度 / linear, a = opacity
  float metallic;
  float roughness;
  vec3 emissive;
  float normalScale;       // 0 = 法線マップなし / 0 = no normal map
  float parallaxScale;     // 0 = 視差なし / 0 = no parallax
  float occlusionStrength;
  int alphaMode;           // 0 = 不透明 / opaque, 1 = マスク / mask, 2 = ブレンド / blend
  float alphaCutoff;
  bool doubleSided;
};
uniform Material uMaterial;

直接光

main()は太陽(第23章の影付き)、点光源、スポットライトを、phong.fragと同じ減衰と円錐のコードで、其々directLight()を通して計算します:

  //------------------------------------------------------------------
  // 直接光:太陽(影付き)、点光源、スポットライト / direct light: the sun (shadowed), point lights, spotlights
  //------------------------------------------------------------------
  vec3 direct = vec3(0.0);
  float shadow = shadowFactor(vWorldPos, geometricNormal, -uDirLight.direction);
  direct += directLight(s, -uDirLight.direction, uDirLight.color * shadow);
  for (int i = 0; i < uPointLightCount; ++i) {
    vec3 toLight = uPointLights[i].position - vWorldPos;
    float d = length(toLight);
    direct += directLight(s, toLight / d, uPointLights[i].color * attenuate(d, uPointLights[i].attenuation));
  }
  for (int i = 0; i < uSpotLightCount; ++i) {
    vec3 toLight = uSpotLights[i].position - vWorldPos;
    float d = length(toLight);
    vec3 l = toLight / d;
    float cone = smoothstep(uSpotLights[i].cosOuter, uSpotLights[i].cosInner, dot(-l, uSpotLights[i].direction));
    if (cone <= 0.0) continue;
    direct += directLight(s, l, uSpotLights[i].color * attenuate(d, uSpotLights[i].attenuation) * cone);
  }

影の係数には、第23章で説明した理由で、法線マップ後の法線ではなく幾何の法線を使います。

最後の色

最後に部分を足し、デバッグの表示が結果を置き換えます:

  vec3 color = emissive;
  if (uLighting != 2) color += direct;
  if (uLighting != 1) color += ibl;
  if (uViewMode == 1) color = s.base;
  else if (uViewMode == 2) color = vec3(s.metallic);
  else if (uViewMode == 3) color = vec3(s.roughness);
  else if (uViewMode == 4) color = vec3(occlusion);
  else if (uViewMode == 5) color = s.n * 0.5 + 0.5;
  else if (uViewMode == 6) color = direct;
  else if (uViewMode == 7) color = ibl;
  else if (uViewMode == 8) color = vec3(shadow);
  // データの表示(2〜5、8)は、sRGBにされた後でちょうどこの値になるように先にリニアへ / data views (2-5, 8): converted
  // to linear first so that after the sRGB encoding the screen shows exactly this value
  if ((uViewMode >= 2 && uViewMode <= 5) || uViewMode == 8)
    color = mix(color / 12.92, pow((color + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), color));

uLightingはLキーです。
0は両方を足し、1はIBLを飛ばし、2は直接光を飛ばします。
発光はどのモードでも足すので、提灯は何時も光ります。

24.10 イメージベースドライティング

考え方

空については、レンダリング方程式の積分を少しの項に潰す事は出来ません。
光は全ての方向から届き、ピクセル毎にフレーム毎に空のキューブマップを何千回も読む必要があります。
イメージベースドライティングは積分を出来るだけ多く、1回だけテクスチャに前計算しておきます。
BRDFを2つの項に分けると、拡散の部分は簡単です。
ランバートのBRDFは定数だからです:

∫Ω𝐤d𝐛πLi(𝐥)(𝐧⋅𝐥)dω≈𝐤d𝐛E(𝐧)π

E(𝐧)は法線だけで決まるので、𝐧で引くキューブマップに保存出来ます。
放射照度マップです。
(𝐤dは𝐅を通して角度に依存しますが、積分の外に出します。良く使われる近似です。)

鏡面の部分は難しくなります。
BRDFが𝐯、粗さ、𝐅0に依存し、其の全てを引ける表は大き過ぎます。
Brian Karisのスプリットサム近似(Unreal Engine 4、2013年)は、積分を其々表に出来る2つの因子に分けます:

∫ΩfLi(𝐧⋅𝐥)dω≈∑kLi(𝐥k)(𝐧⋅𝐥k)∑k𝐧⋅𝐥k⏟prefiltered map⋅1N∑kf(𝐥k,𝐯)(𝐧⋅𝐥k)p(𝐥k)⏟𝐅0A+B

  • 1つ目の因子は、GGXのローブの形でぼかした空です。反射方向と粗さで決まるので、ミップマップの段が段々粗くなるキューブマップになります。プリフィルタ環境マップ(ぼかした映り込み)です。𝐯に依存しない様に、Karisは𝐧=𝐯=𝐫(面を正面から見ている)と仮定します。其の為、濡れた道路で斜めに見える縦に伸びたハイライトは失われます。其れが此の方法の代償です。
  • 2つ目の因子は、白い空に対して積分した鏡面のBRDFです。空とは全く関係無く、𝐧⋅𝐯、粗さ、𝐅0だけで決まります。Fc=(1−𝐯⋅𝐡)5として𝐅=𝐅0(1−Fc)+Fcと書くと𝐅0が和の外に出て、(𝐧⋅𝐯、粗さ)毎に2つの数AとBが残ります。小さな2Dテクスチャ、BRDFの表(LUT)です。

従って空全体の実行時のコストは、ピクセル毎にテクスチャを3回読むだけです。

IBLの流れ。起動時にIbl::buildがユニット3の空のキューブマップを読み、ibl irradiance fragでユニット9の放射照度マップ(32²、RGBA16F、1段)を、ibl prefilter fragでユニット10のぼかした映り込み(128²から8²迄の5段、粗さ0、0.25、0.5、0.75、1)を描く。ibl brdf fragは入力無しでユニット11の128²、RG16FのBRDFの表を描く。毎フレームpbr.fragが、拡散 = kd × 放射照度 × ベースカラー、鏡面 = 映り込み × (F0 × A + B)を計算する

キューブマップの面に描く

3つのテクスチャは全て、第17章の全画面の三角形を特別なフラグメントシェーダーで描いて作ります。
1回にキューブマップの面1つ(又はLUT)です。
フラグメントシェーダーは、自分のピクセルがどの方向を表すかを知る必要があります。
faceDirection()は、面の番号とgl_FragCoordを、第18章の面の表で其の方向にします:

// キューブマップの面faceのピクセル(gl_FragCoord.xy)が表す方向。第18章の表(行0 = t = 0、上の行)
// The direction of pixel gl_FragCoord.xy on cube face `face`. The table of chapter 18 (row 0 = t = 0, the top row)
vec3 faceDirection(int face, vec2 fragCoord, float size) {
  float sc = 2.0 * fragCoord.x / size - 1.0;
  float tc = 2.0 * fragCoord.y / size - 1.0;
  vec3 d;
  if (face == 0) d = vec3(1.0, -tc, -sc);       // +X
  else if (face == 1) d = vec3(-1.0, -tc, sc);  // -X
  else if (face == 2) d = vec3(sc, 1.0, tc);    // +Y
  else if (face == 3) d = vec3(sc, -1.0, -tc);  // -Y
  else if (face == 4) d = vec3(sc, -tc, 1.0);   // +Z
  else d = vec3(-sc, -tc, -1.0);                // -Z
  return normalize(d);
}

gl_FragCoord.xyはウィンドウ座標でのピクセルの中心で、最初のピクセルは(0.5, 0.5)です。
其のピクセルは面の0行目に書かれ、キューブマップでは其れがt=0です。
第18章で見た様に、仕様の表では0行目が各面の画像の上の端なので、tが−yに沿う面では-tcになります。
此処で符号を一つ間違えると映り込みが鏡像になったり回ったりするので、此の章を作る時に数値で確かめました。
粗さ0のぼかした映り込みは空自身の128²のミップマップの段と一致しなければならず、実際に平均の差は0.0017でした。

放射照度マップ

ibl_irradiance.fragは出力の方向𝐧毎に、半球を0.08ラジアンの等間隔の角度で歩き、空を足し合わせます:

void main() {
  vec3 n = faceDirection(uFace, gl_FragCoord.xy, uSize);
  vec3 up = abs(n.y) < 0.999 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0);
  vec3 right = normalize(cross(up, n));
  up = cross(n, right);
  // 半球を等間隔の角度で:φ(周り)0〜2π、θ(天頂から)0〜π/2。sinθは小さな立体角の補正
  // The hemisphere in equal angle steps: φ (around) 0..2π, θ (from the zenith) 0..π/2. sin θ corrects the solid angle
  const float delta = 0.08;
  vec3 sum = vec3(0.0);
  float count = 0.0;
  for (float phi = 0.0; phi < 2.0 * PI; phi += delta) {
    for (float theta = 0.0; theta < 0.5 * PI; theta += delta) {
      vec3 t = vec3(sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta)); // 接線空間 / tangent space
      vec3 dir = t.x * right + t.y * up + t.z * n;
      sum += textureLod(uEnvironment, dir, uSourceLod).rgb * cos(theta) * sin(theta);
      count += 1.0;
    }
  }
  // ∫L cosθ dω ≈ (π²/count)Σ…(= E)。÷π で拡散反射の明るさ / ≈ (π²/count) Σ ... (= E); ÷ π gives the diffuse brightness
  out_color = vec4(PI * sum / count, 1.0);
}

𝐧の周りの球座標では、方向は(sinθcosφ,sinθsinφ,cosθ)で、立体角の欠片はdω=sinθdθdφです。
sinθは、格子の輪が極に向かって小さくなる分の補正です。
従って

E=∫02π∫0π/2L(θ,φ)cosθsinθdθdφ≈Δ2∑Lcosθsinθ≈π2N∑Lcosθsinθ

格子の点の数がN≈(2π/Δ)(π2/Δ)=π2/Δ2だからです。
πで割ると保存する物E/π=πN∑Lcosθsinθになり、其れがシェーダーの最後の行です。
Δ=0.08ではループはピクセル毎に79 × 20 = 1580回回ります。
厳密ではありません。
一様に白い空では和は1ではなく0.981になります。
1580がπ2/0.082=1542より少し多く、θの格子が極から始まるからです。
空の光の2%の誤差は見えませんし、放射照度は何れにしても滑らかです。
其の為面毎に32 × 32で十分で、空も512²其のままではなく、ミップマップの段log2(512/32)=4(32²版)から読みます。
512²のテクセルを1580個のサンプルで平均してもエイリアシングが出るだけです。

upとrightの作り方は、𝐧の周りの接線の基底を作ります(任意の接線を使う第22章の考え方)。
cross(up, n)が0になる極の近くではx軸に切り替えます。

モンテカルロ積分と重点的サンプリング

ぼかした映り込みには等間隔の格子は使えません。
滑らかな面ではGGXのローブの殆どが小さな円錐に収まり、等間隔の格子ではサンプルの殆どがローブが0の所に落ちます。
代わりにモンテカルロ積分を使います。
ある確率密度pでランダムな方向xkを選ぶと:

∫g(x)dx≈1N∑k=1Ng(xk)p(xk)

此れはgが0でない所でpが0でなければどんなpでも正しいですが、ノイズが一番小さいのはpがgに似ている時です。
重点的サンプリング(importance sampling)はpをBRDFのローブに比例させ、大事な光が来る所にサンプルを送ります。

2つの半円の中に、粗さ0.5の反射方向のGGXの細いローブが描かれている。左:等間隔の16方向で、殆どがローブの外。右:GGXの重点的サンプリングで選んだ16方向で、ローブの中に集まっている

GGXには、一様な2つの数ξ1,ξ2∈[0,1)をD(𝐡)(𝐧⋅𝐡)の様に分布する半ベクトルにする閉じた式があります:

φ=2πξ1,cosθh=1−ξ21+(α2−1)ξ2

光の方向は𝐡に対する𝐯の鏡像𝐥=2(𝐯⋅𝐡)𝐡−𝐯(reflect(-v, h)を展開した物)で、其の密度はp(𝐥)=D(𝐡)(𝐧⋅𝐡)/(4(𝐡⋅𝐯))です。
BRDFと同じ4が出て来ます。

一様な数は乱数生成器からではなく、ハマースリー点列から取ります。
N個の内のi番目の点は(i/N,i の基数逆数)で、基数逆数はiのビットを小数点の周りで鏡に映した物です(2進数で0.1、0.01、0.11、0.001…)。
此の点は乱数よりずっと均等に単位正方形を埋めるので(乱数は、GLSL 第8章のハッシュによるホワイトノイズの様に、塊と隙間を作ります)、64個でも乱数64個よりずっと滑らかな結果になります。
GLSL 4.00にはbitfieldReverseがあるので、基数逆数は命令1つです。
定数は2−32です。

// ハマースリー点列:0〜1の正方形に均一に散らばる点(乱数より速く収束する) / the Hammersley sequence: points spread evenly
// over the unit square (converges faster than random numbers)
vec2 hammersley(uint i, uint n) {
  return vec2(float(i) / float(n), float(bitfieldReverse(i)) * 2.3283064365386963e-10);
}

// GGXの分布に従って半ベクトルHを選ぶ(重点的サンプリング)。Nの周りの接線空間で作ってワールドへ
// Picks a half vector H following the GGX distribution (importance sampling), built in tangent space around N
vec3 importanceSampleGgx(vec2 xi, vec3 n, float roughness) {
  float a = roughness * roughness;
  float phi = 2.0 * PI * xi.x;
  float cosTheta = sqrt((1.0 - xi.y) / (1.0 + (a * a - 1.0) * xi.y));
  float sinTheta = sqrt(1.0 - cosTheta * cosTheta);
  vec3 h = vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta);
  vec3 up = abs(n.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
  vec3 t = normalize(cross(up, n));
  vec3 b = cross(n, t);
  return normalize(t * h.x + b * h.y + n * h.z);
}

importanceSampleGgxは、z軸の周りの接線空間で𝐡を作り、𝐧の周りの基底に回します。
シェーダーはroughness * roughnessをaに入れてからa * aを使うので、式のα2はr4です。
其れで正しく、間違って2回2乗している訳ではありません。

ぼかした映り込み

ibl_prefilter.fragは面とミップマップの段毎に1回動き、5つの段ではuRoughness = 段 / 4です:

void main() {
  vec3 n = faceDirection(uFace, gl_FragCoord.xy, uSize);
  vec3 v = n; // 正面から見ていると仮定 / assume we look at it head-on
  vec3 sum = vec3(0.0);
  float weight = 0.0;
  // 空の1テクセルの立体角 / the solid angle of one sky texel
  float texelSolidAngle = 4.0 * PI / (6.0 * uSourceSize * uSourceSize);
  for (uint i = 0u; i < kSamples; ++i) {
    vec3 h = importanceSampleGgx(hammersley(i, kSamples), n, uRoughness);
    vec3 l = normalize(2.0 * dot(v, h) * h - v);
    float nDotL = dot(n, l);
    if (nDotL <= 0.0) continue;
    // この点が受け持つ立体角に合うミップマップの段(少ない点でも縞にならない)
    // The mip level whose texel matches the solid angle this sample stands for (no banding with few samples)
    float nDotH = max(dot(n, h), 0.0);
    float pdf = distributionGgx(nDotH, uRoughness) * nDotH / (4.0 * max(dot(h, v), 0.0)) + 1e-4;
    float sampleSolidAngle = 1.0 / (float(kSamples) * pdf);
    float lod = uRoughness == 0.0 ? 0.0 : 0.5 * log2(sampleSolidAngle / texelSolidAngle) + 1.0;
    sum += textureLod(uEnvironment, l, lod).rgb * nDotL;
    weight += nDotL;
  }
  out_color = vec4(sum / weight, 1.0);
}

𝐧=𝐯なので、全てのサンプルの𝐥はGGXの半ベクトルに対する𝐧の反射で、結果は其の方向の空の(𝐧⋅𝐥)による加重平均、スプリットサムの1つ目の因子です。

64個のサンプルは、ローブが半球の殆どを覆う粗い段にはとても少ない数です。
64回くっきりと読むと、結果には空の幽霊の様な像が64個重なって見えます。
対策(ColbertとKřivánek、GPU Gems 3)は、各サンプルを空のもっとぼやけたミップマップの段から読む事です。
サンプル1つは約Ωs=1/(Np)の立体角を受け持ち、空の0段目の1テクセルはΩp=4π/(6w2)を覆うので、テクセルがΩsを覆う段は:

lod=12log2ΩsΩp+1

(12は、ミップマップの1段がテクセルの幅を倍にし、立体角を4倍にするから。+1は残りの縞を隠す少しの余分なぼかしです。)
512²の空ではΩp=4π/(6⋅5122)≈8.0⋅10−6ステラジアンです。
此れには空の全てのミップマップが必要で、Cubemap::loadが第18章から作っています。
又シームレスなフィルタリング(GL_TEXTURE_CUBE_MAP_SEAMLESS、18.6節)も必要です。
ぼやけた段では1テクセルが面の大きな部分なので、辺をまたいで補間しないとキューブの継ぎ目が映り込みに焼き込まれます。

粗さ0ではシェーダーは0段目を読み、GGXのサンプルは全て𝐧に潰れるので、ぼかした映り込みの0段目は空の128²の写しです。
512²の空より柔らかく、クロムの球で其れが分かります。
エンジンは0段目に256²〜512²を使うか、別のくっきりした反射プローブを使います。

BRDFの表

ibl_brdf.fragはx=𝐧⋅𝐯、y = 粗さについて、同じ重点的サンプリングと256個のサンプルで2つ目の因子を計算します:

// IBL用のSchlick-GGXの幾何項:k = α/2(直接光ではk = (r+1)²/8) / the Schlick-GGX geometry term for IBL: k = α/2
// (for direct light k = (r+1)²/8)
float geometrySchlick(float nDotX, float roughness) {
  float k = roughness * roughness / 2.0;
  return nDotX / (nDotX * (1.0 - k) + k);
}

void main() {
  float nDotV = max(vUv.x, 1e-3);
  float roughness = vUv.y;
  vec3 v = vec3(sqrt(1.0 - nDotV * nDotV), 0.0, nDotV);
  vec3 n = vec3(0.0, 0.0, 1.0);
  float a = 0.0, b = 0.0;
  for (uint i = 0u; i < kSamples; ++i) {
    vec3 h = importanceSampleGgx(hammersley(i, kSamples), n, roughness);
    vec3 l = normalize(2.0 * dot(v, h) * h - v);
    float nDotL = max(l.z, 0.0);
    float nDotH = max(h.z, 0.0);
    float vDotH = max(dot(v, h), 0.0);
    if (nDotL <= 0.0) continue;
    float g = geometrySchlick(nDotV, roughness) * geometrySchlick(nDotL, roughness);
    float gVis = g * vDotH / (nDotH * nDotV);
    float fc = pow(1.0 - vDotH, 5.0); // フレネルを F0 · (1 − fc) + fc に分けて二つの数にする / split Fresnel into two numbers
    a += (1.0 - fc) * gVis;
    b += fc * gVis;
  }
  out_color = vec4(a / float(kSamples), b / float(kSamples), 0.0, 1.0);
}

視線のベクトルは平面の中に𝐯=(1−(𝐧⋅𝐯)2,0,𝐧⋅𝐯)と作り、𝐧はz軸です。
各サンプルの重みは、鏡面のBRDFのモンテカルロの項を𝐅で割った物です:

f(𝐧⋅𝐥)p=DG𝐅4(𝐧⋅𝐥)(𝐧⋅𝐯)⋅(𝐧⋅𝐥)⋅4(𝐯⋅𝐡)D(𝐧⋅𝐡)=𝐅G(𝐯⋅𝐡)(𝐧⋅𝐡)(𝐧⋅𝐯)

Dが打ち消し合います。
Dでサンプリングする事の美しい所です。
残りがgVisです。
𝐅を𝐅0(1−Fc)+Fcに分けると2つの和になります。
Aは(1−Fc)gVisを、BはFcgVisを集めます。
geometrySchlickは24.5節のIBLの定数k=α/2を使っている事に注意して下さい。
結果はGL_RG16Fのテクスチャに保存します。
赤 = A、緑 = Bで、どのPBRのチュートリアルでも見る赤と緑のグラデーションです。
簡単な確認をしましょう。
𝐧⋅𝐯=1、粗さ0では全ての𝐡が𝐧で、Fc=0、gVis = 1なので、A=1、B=0です。
鏡面のIBLは𝐅0 × 空、完全な鏡になります。
読み出したテクスチャの其の角は丁度(1.000, 0.000)でした。

Iblクラス

src/ibl.hhが3つの結果を持ちます:

// イメージベースドライティング(IBL、第24章):空のキューブマップから、拡散と鏡面の環境光の表を起動時に作る
// Image-based lighting (IBL, chapter 24): builds the diffuse and specular environment-light tables from the sky cube map
// at start-up
#pragma once

#include "cubemap.hh"
#include "framebuffer.hh"
#include "shader.hh"

#include <optional>

// 結合するテクスチャユニット(pbr.fragのlayout(binding = …)と同じ) / the texture units (same as layout(binding = ...)
// in pbr.frag)
constexpr GLuint kIrradianceUnit = 9;
constexpr GLuint kPrefilteredUnit = 10;
constexpr GLuint kBrdfLutUnit = 11;

struct IblSettings {
  int irradianceSize = 32;   // 放射照度は滑らかなので小さくて良い / irradiance is smooth: small is enough
  int prefilteredSize = 128; // ぼかした映り込みの0段目(粗さ0) / level 0 of the blurred reflections (roughness 0)
  int prefilteredLevels = 5; // 128, 64, 32, 16, 8:粗さ0, 0.25, 0.5, 0.75, 1 / roughness 0, 0.25, 0.5, 0.75, 1
  int brdfLutSize = 128;
};

// IBLの3つの表(RAII、コピー不可・移動可)。作り方はシェーダー:ibl_irradiance.frag、ibl_prefilter.frag、ibl_brdf.frag
// The three IBL tables (RAII, non-copyable, movable). Made by shaders: ibl_irradiance.frag, ibl_prefilter.frag,
// ibl_brdf.frag
class Ibl {
public:
  // environmentから作る(ミップマップ付きのキューブマップ)。シェーダーが読めなければstd::nullopt。かかった時間を表示する
  // Builds from `environment` (a cube map with mipmaps). std::nullopt if the shaders cannot be loaded. Prints the time taken
  static std::optional<Ibl> build(const Cubemap &environment, const IblSettings &settings = {});

  // ユニット9、10、11に繋ぐ / binds to units 9, 10 and 11
  void bind() const;

  const Cubemap &irradiance() const { return irradianceMap; }
  const Cubemap &prefiltered() const { return prefilteredMap; }
  const Texture2D &brdfLut() const { return brdfFbo.color(); }
  double buildMs[3] = {0.0, 0.0, 0.0}; // 放射照度、映り込み、LUT(ミリ秒) / irradiance, reflections, LUT (ms)

private:
  Cubemap irradianceMap;
  Cubemap prefilteredMap;
  Framebuffer brdfFbo; // 色のテクスチャがLUT(GL_RG16F) / its colour texture is the LUT (GL_RG16F)
};

ぼかした映り込みのキューブマップは128²で5段なので、段の幅は128、64、32、16、8テクセルで、粗さ0、0.25、0.5、0.75、1に当たります。
GL_RGBA16Fは1より大きい値を保ち(空がHDRになれば役に立ちます)、放射照度の暗く滑らかなグラデーションで縞が出るのを防ぎます。
メモリは小さく、放射照度マップは6⋅322⋅8=49152バイト、ぼかした映り込みは6⋅8⋅(1282+642+322+162+82)=1047552バイト(約1 MiB)、LUTは1282⋅4=65536バイトです。

キューブマップの面は、ibl.ccの小さな補助で描きます。
まだ何も付けていないFBOと、全画面の三角形用の空のVAOです:

// 面ごとに描くための、色の付け先だけのFBO(RAII) / an FBO with only a colour attachment, for drawing face by face (RAII)
struct FaceTarget {
  GLuint fbo = 0, vao = 0;
  FaceTarget() {
    glCreateFramebuffers(1, &fbo);
    glCreateVertexArrays(1, &vao); // 全画面の三角形(post.vert)用の空のVAO / empty VAO for the fullscreen triangle
  }
  ~FaceTarget() {
    glDeleteFramebuffers(1, &fbo);
    glDeleteVertexArrays(1, &vao);
  }
  FaceTarget(const FaceTarget &) = delete;
  FaceTarget &operator=(const FaceTarget &) = delete;

  // キューブマップの面face・ミップマップの段levelに描く:glNamedFramebufferTextureLayerのlayerが面の番号
  // Draws into face `face`, mip level `level` of a cube map: the layer of glNamedFramebufferTextureLayer is the face
  void drawFace(const Cubemap &cube, int level, int face, int size) const {
    glNamedFramebufferTextureLayer(fbo, GL_COLOR_ATTACHMENT0, cube.id(), level, face);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    glViewport(0, 0, size, size);
    glBindVertexArray(vao);
    glDrawArrays(GL_TRIANGLES, 0, 3);
  }
};

新しい関数は、第17章で触れたglNamedFramebufferTextureLayer(framebuffer, attachment, texture, level, layer)です:

  • framebuffer:変えるFBO(DSAなので結合しなくて良い)。
  • attachment:画像の行き先、此処ではGL_COLOR_ATTACHMENT0。
  • texture:キューブマップ、配列テクスチャ、又は3Dテクスチャ。
  • level:描くミップマップの段。此れで5つの粗さの段を一つずつ埋めます。
  • layer:キューブマップでは面で、+X、−X、+Y、−Y、+Z、−Zの順(第18章の順番)の0〜5。配列テクスチャでは配列の番号、3Dテクスチャでは奥行きの切れです。

良くある間違いは3つです。
代わりにglNamedFramebufferTextureを使うと、6つの面全てがレイヤー付きの付け先として付きます(其の時はジオメトリシェーダーのgl_Layerが面を選び、其れが無ければ全部が面0に描かれます)。
ビューポートを其の段の大きさにし忘れると、小さな段では絵全体が角に切り取られます。
テクスチャに無い段を渡すと、呼び出しはGL_INVALID_VALUEで失敗し、付け先は前のままなので、前の段をもう一度上書きします。
キューブマップの面は正方形で同じ大きさでなければならず、Cubemap(size, format, levels)が其れを保証します。

build()は3つのプログラムを読み込み、3つのテクスチャを描き、各段階の時間を測ります:

double elapsedMs(std::chrono::steady_clock::time_point start) {
  // 本当に描き終わるまで待つ(GPUはコマンドを溜めてから実行する) / wait until drawing really finished (the GPU queues
  // commands and runs them later)
  glFinish();
  return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
}

} // namespace

std::optional<Ibl> Ibl::build(const Cubemap &environment, const IblSettings &settings) {
  std::optional<Shader> irradianceShader = Shader::load("shaders/post.vert", "shaders/ibl_irradiance.frag");
  std::optional<Shader> prefilterShader = Shader::load("shaders/post.vert", "shaders/ibl_prefilter.frag");
  std::optional<Shader> brdfShader = Shader::load("shaders/post.vert", "shaders/ibl_brdf.frag");
  if (!irradianceShader || !prefilterShader || !brdfShader) return std::nullopt;

  Ibl ibl;
  FaceTarget target;
  glDisable(GL_DEPTH_TEST);
  glDisable(GL_BLEND);
  environment.bind(0);

  // 1. 放射照度(拡散の環境光):ミップマップなし / 1. irradiance (diffuse environment light): no mipmaps
  auto start = std::chrono::steady_clock::now();
  ibl.irradianceMap = Cubemap(settings.irradianceSize, GL_RGBA16F, 1);
  irradianceShader->use();
  irradianceShader->set("uSize", static_cast<float>(settings.irradianceSize));
  // 空の32×32くらいの段で十分 / a sky level of about 32 × 32 is enough
  float sourceLod = std::max(0.0f, std::log2(static_cast<float>(environment.size()) / 32.0f));
  irradianceShader->set("uSourceLod", sourceLod);
  for (int face = 0; face < 6; ++face) {
    irradianceShader->set("uFace", face);
    target.drawFace(ibl.irradianceMap, 0, face, settings.irradianceSize);
  }
  ibl.buildMs[0] = elapsedMs(start);

  // 2. ぼかした映り込み(鏡面の環境光):段ごとに粗さを上げる / 2. blurred reflections (specular environment light):
  //    more roughness on every mip level
  start = std::chrono::steady_clock::now();
  ibl.prefilteredMap = Cubemap(settings.prefilteredSize, GL_RGBA16F, settings.prefilteredLevels);
  prefilterShader->use();
  prefilterShader->set("uSourceSize", static_cast<float>(environment.size()));
  for (int level = 0; level < settings.prefilteredLevels; ++level) {
    int size = std::max(1, settings.prefilteredSize >> level);
    prefilterShader->set("uSize", static_cast<float>(size));
    // 段が1つだけなら粗さ0の段だけ(0で割らない) / a single level is just roughness 0 (no division by zero)
    float roughness = settings.prefilteredLevels > 1
                          ? static_cast<float>(level) / static_cast<float>(settings.prefilteredLevels - 1)
                          : 0.0f;
    prefilterShader->set("uRoughness", roughness);
    for (int face = 0; face < 6; ++face) {
      prefilterShader->set("uFace", face);
      target.drawFace(ibl.prefilteredMap, level, face, size);
    }
  }
  ibl.buildMs[1] = elapsedMs(start);

  // 3. BRDFの表:普通の2Dテクスチャ(赤と緑の2チャンネル、半精度) / 3. the BRDF table: an ordinary 2D texture
  //    (red and green, half floats)
  start = std::chrono::steady_clock::now();
  ibl.brdfFbo = Framebuffer(settings.brdfLutSize, settings.brdfLutSize, {.colorFormat = GL_RG16F, .depthStencilFormat = 0});
  ibl.brdfFbo.bind();
  brdfShader->use();
  glBindVertexArray(target.vao);
  glDrawArrays(GL_TRIANGLES, 0, 3);
  ibl.buildMs[2] = elapsedMs(start);

  glBindFramebuffer(GL_FRAMEBUFFER, 0);
  printf("IBL: irradiance %d² %.0f ms, prefiltered %d² × %d levels %.0f ms, BRDF LUT %d² %.0f ms\n",
         settings.irradianceSize, ibl.buildMs[0], settings.prefilteredSize, settings.prefilteredLevels, ibl.buildMs[1],
         settings.brdfLutSize, ibl.buildMs[2]);
  return ibl;
}

  • 深度テストとブレンディングは切ります。全てのピクセルを上書きするからです。裏面のカリングはまだ関係ありません。mainが其れを有効にするのはIbl::buildの後で、全画面の三角形は何れにしても反時計回りです。
  • ぼかした映り込みのlevel段目の粗さはlevel / (prefilteredLevels - 1)なので、5つの段は0、0.25、0.5、0.75、1になります。段が1つだけだと0で割ってしまうので、prefilteredLevels = 1なら単に粗さ0、空のくっきりした写しになります。
  • 空はユニット0に繋ぎ、放射照度とぼかした映り込みのシェーダーが其れをuEnvironmentとして宣言します(BRDFのシェーダーには入力が全くありません)。IBLのプログラムはシーンの物と別なので、ポストプロセスのプログラムと同じくユニットは0から始まります。
  • BRDFの表は、GL_RG16Fで深度無しの普通のFramebuffer(第23章のFramebufferSpec)の色のテクスチャで、bind()が其のビューポートを設定します。
  • glFinish()は、其れ迄に出した全てのコマンドをGPUが終える迄止まります。OpenGLの呼び出しはGPUが仕事をするずっと前に戻るので(第19章)、此れが無いとタイマーはコマンドを並べる速さしか測りません。フレームのループでは絶対に呼ばないで下さい。CPUとGPUの並列性が壊れます。起動時の一度きりの段階なら、一番簡単で正直な時計です。

bind()は3つのテクスチャをユニット9、10、11に繋ぎます:

void Ibl::bind() const {
  irradianceMap.bind(kIrradianceUnit);
  prefilteredMap.bind(kPrefilteredUnit);
  brdfFbo.color().bind(kBrdfLutUnit);
}

mainはモデルを読み込んだ直後に1回だけIBLを作ります。
ぼかした映り込みのシェーダーは面の辺をまたいで読むので、シームレスなフィルタリングは作る前に有効でなければなりません。
其の為、第18章からフレームバッファの後にあったglEnableを此処に移します:

  // IBL:空から、拡散(放射照度)・鏡面(ぼかした映り込み)・BRDFの表を一度だけ作る(第24章)
  // IBL: build the diffuse (irradiance), specular (blurred reflections) and BRDF tables from the sky once (chapter 24)
  // 作る前にシームレスなフィルタリングを有効にする:ぼかす時に面の辺をまたいで読む(18.6節)
  // Seamless filtering must be on before building: the blurring reads across the faces' edges (section 18.6)
  glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
  std::optional<Ibl> ibl = Ibl::build(*sky);
  if (!ibl) return 1;

そしてプログラムが時間を表示します:

IBL: irradiance 32² 167 ms, prefiltered 128² × 5 levels 203 ms, BRDF LUT 128² 30 ms

此の回は合計0.40秒でした。
此のマシンのllvmpipeでは、2つのCPUコアが他に何をしているかで、作るのに大体0.35〜0.6秒掛かりました。
仕事は本物です。
放射照度で空を970万回(32² × 6 × 1580)、ぼかした映り込みで840万回(21 824テクセル × 6面 × 64)読み、BRDFで420万回(128² × 256)ループします。
デスクトップのGPUなら同じ事が数ミリ秒です。
エンジンはBRDFの表をオフラインで焼きます(決して変わらないので)。
環境マップも大抵焼きますが、起動時に作ると方法が追い易く、道具無しで空を変えられます。
IBLを作り直すのは環境が変わった時か、其のシェーダーを直した時だけにして下さい。
ibl_*.fragは作る時にしか動かないので、Rは其れらを読み直す為にIBLを作り直します(シェーダーのコンパイルに失敗したら前のIBLのままです)。

一時的なビルドでglGetTextureImageを使って読み出したマップです:

ミップマップ2段目の空のキューブマップと粗さ0のぼかした映り込みは、どちらも雲と太陽のあるくっきりしたキューブの十字。粗さ0.25、0.5、1の映り込みは段々ぼやけ、最後は上の青から下の灰色へのグラデーションだけになる。πで割った放射照度マップはとても滑らかなグラデーション。BRDFの表は、n・vが大きい方が赤く、n・vも粗さも小さい角が緑

マップを使う

pbr.fragのmain()のIBLの部分:

  //------------------------------------------------------------------
  // IBL:空からの光。拡散 = 放射照度 × ベースカラー、鏡面 = ぼかした映り込み × (F0 · A + B)(スプリットサム)
  // IBL: light from the sky. Diffuse = irradiance × base colour, specular = blurred reflection × (F0 · A + B) (split sum)
  //------------------------------------------------------------------
  float nDotV = max(dot(s.n, s.v), 1e-4);
  vec3 f = fresnelSchlickRoughness(nDotV, s.f0, s.roughness);
  vec3 kd = (1.0 - f) * (1.0 - s.metallic);
  vec3 irradiance = texture(uIrradianceMap, s.n).rgb;
  vec3 r = reflect(-s.v, s.n);
  float maxLod = float(textureQueryLevels(uPrefilteredMap) - 1);
  vec3 prefiltered = textureLod(uPrefilteredMap, r, s.roughness * maxLod).rgb;
  vec2 brdf = texture(uBrdfLut, vec2(nDotV, s.roughness)).rg;
  // 鏡面はF0のまま:フレネルはBRDF LUTの中で積分済み(fを使うと二重になる) / the specular uses F0 itself: the BRDF
  // LUT already integrates Fresnel (using f would apply it twice)
  vec3 specular = prefiltered * (s.f0 * brdf.x + brdf.y);
  // 遮蔽(AO)は環境光だけに掛ける(glTFの決まり) / occlusion only affects the environment light (as glTF says)
  vec3 ibl = (kd * irradiance * s.base + specular) * occlusion * uEnvironmentTint;

  • 拡散の部分は𝐤d⋅𝐛⋅E/πで、法線で放射照度マップを1回引きます。πの係数はありません。マップが既に白いランバート面の見え方を保存しています。
  • 鏡面の部分は、反射方向𝐫でぼかした映り込みを、ミップマップの段 = 粗さ × 4で引きます。textureLodなので、段はGPUが微分から選ぶ物ではなくあたし達が決めた物です。textureQueryLevelsは段の数(5)を返すので、シェーダーに書き込む必要がありません。保存された2つの段の間は補間され、トライリニアフィルタリングが粗さの補間をただでしてくれます。
  • 𝐅0A+Bはs.f0 * brdf.x + brdf.yと書き、マテリアル其のものの𝐅0を使います(Karisの形)。LUTは既にローブ全体でフレネル項を積分しているので(其れがAとBです)、他には何も掛けません。LUTはtexture(バイリニア)で読み、端ではクランプされます。
  • 遮蔽とuEnvironmentTint(昼は1、夜は暗い青、第18章)はIBLだけに掛けます。

フレネル項fは其れでも必要ですが、使うのは拡散の重み𝐤dだけです。
間接光には半ベクトルが一つではないので、其処では𝐧⋅𝐯を使います。
又粗いローブで平均すると斜めの明るさは弱くなるので、Sébastien Lagardeの変形は𝐅をmax(1−r,𝐅0)迄しか上げません:

// IBL用:粗い面では斜めでも1まで上がらない(Sébastien Lagarde) / for IBL: rough surfaces do not reach 1 at grazing angles
vec3 fresnelSchlickRoughness(float cosTheta, vec3 f0, float roughness) {
  return f0 + (max(vec3(1.0 - roughness), f0) - f0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0);
}

此れが無いと、とても粗い面でも斜めの角度で𝐤dが0に近付き、粗い誘電体の縁で空の拡散光が消えてしまいます。

多くのPBRのチュートリアルは此処でf * brdf.x + brdf.yと書きますが、其れではfとLUTのA・Bの中で2回フレネルが掛かり、誘電体が斜めの角度で明るくなり過ぎます。

映り込みに太陽が無い

画面に見える物について、大事な制限が一つあります。
環境は第18章のLDRの空です。
チャンネル毎に8ビットで、太陽の円盤は1.0でクリップされ、白い雲と同じ明るさです。
第21章からスカイボックスはHDRの太陽を上に描きますが、其れはskybox.fragの中の話で、IBLを作る元のキューブマップのテクスチャはLDRのままです。
従ってIBLの映り込みには空の色と雲は映りますが、明るい太陽は映りません。
クロムの球の太陽は、雲より明るくない白い点に過ぎません。
見える明るいハイライトは、directLight()を通る直接の太陽光から来ていて、其方はHDR(2.6のπ倍)です。
此の分担は筋が通っています。
本物の太陽が入ったHDRの環境を使うと、太陽はIBLと平行光源で2回数えられてしまいます。
本物のエンジンはHDRの画像から太陽を消すか、平行光源の鏡面を省きます。
夜のシーンは逆の形で同じ事を見せます。
IBLは殆ど0迄小さくなり、点光源の提灯が主役になります。

24.11 シーン

見本の球

4つの見本の球は其々PbrMaterialで、指示付き初期化子で書きます:

  // 見本の球:磨いた金、クロム、粗い銅、赤いプラスチック(glTFの値で、金属のベースカラー = F0)
  // Sample spheres: polished gold, chrome, rough copper, red plastic (glTF values; a metal's base colour = its F0)
  struct Showcase {
    Vec3 position;
    PbrMaterial material;
  };
  const Showcase showcase[] = {
    {{-1.8f, 0.35f, 8.0f}, {.baseColor = {1.0f, 0.766f, 0.336f, 1.0f}, .metallic = 1.0f, .roughness = 0.15f}},
    {{-0.6f, 0.35f, 8.3f}, {.baseColor = {0.95f, 0.95f, 0.95f, 1.0f}, .metallic = 1.0f, .roughness = 0.05f}},
    {{0.6f, 0.35f, 8.3f}, {.baseColor = {0.955f, 0.638f, 0.538f, 1.0f}, .metallic = 1.0f, .roughness = 0.55f}},
    {{1.8f, 0.35f, 8.0f}, {.baseColor = rgb(0.75f, 0.08f, 0.06f), .metallic = 0.0f, .roughness = 0.3f}},
  };

金属はベースカラーを𝐅0として使うので、測定したリニアの値です。
プラスチックだけがrgb()を通したsRGBの色で、リニアでは(0.5225, 0.0072, 0.0049)になります。
球はsphereMeshで描きます。
滑らかな映り込みは粗い球の面をすぐに見せてしまうので、24 × 12ではなく48 × 24の分割になりました。
影も落とします。

球の格子

定番のPBRのテストは、一方向に金属度が、もう一方向に粗さが増える球の格子です。
あたし達の格子は、既定のカメラの後ろの地面から5.5 mの所に浮かんでいます:

  // 金属度 × 粗さの球の格子(7 × 7):宙に浮かべる。上の行ほど金属、右の列ほど粗い(Kで見に行く)
  // The metallic × roughness sphere grid (7 × 7), floating in the air: metal towards the top row, rougher to the right
  // (go and look with K)
  constexpr int kGrid = 7;
  const Vec3 kGridCentre = {0.0f, 5.5f, 24.0f};
  const Vec4 kGridColor = rgb(0.9f, 0.35f, 0.15f);

    // 球の格子:行 = 金属度 0〜1(下から上)、列 = 粗さ 0〜1(左から右) / the grid: rows = metallic 0..1 (bottom to
    // top), columns = roughness 0..1 (left to right)
    for (int row = 0; row < kGrid; ++row)
      for (int col = 0; col < kGrid; ++col) {
        PbrMaterial m{.baseColor = kGridColor, .metallic = static_cast<float>(row) / (kGrid - 1),
                      .roughness = static_cast<float>(col) / (kGrid - 1)};
        apply(m);
        Vec3 p = kGridCentre + Vec3{1.1f * (static_cast<float>(col) - 3.0f), 1.1f * (static_cast<float>(row) - 3.0f), 0.0f};
        drawMesh(sphereMesh, translate(p) * scale({0.9f, 0.9f, 0.9f}));
      }

i行目の金属度はi/6、j列目の粗さはj/6なので、値は0、0.17、0.33、0.5、0.67、0.83、1です。
中間の金属度は自然には存在しません(面は金属か、其うでないかです)。
ですが金属・粗さのテクスチャのアンチエイリアスされた縁や、埃や塗料の下では起きるので、シェーダーは其れを無理無く扱える必要があります。
オレンジはsRGBで(0.9, 0.35, 0.15)、リニアで(0.7874, 0.1005, 0.0196)です。

Kはカメラを決まった場所に動かします:

    if (key == GLFW_KEY_K) {
      // 決まった場所にカメラを置く / put the camera at a fixed place
      place = (place + 1) % 3;
      useOrbit = false;
      const Vec3 positions[] = {{0.6f, 3.6f, 12.5f}, {0.0f, 5.5f, 36.5f}, {0.0f, 1.3f, 11.4f}};
      const float pitches[] = {-17.0f, 0.0f, -14.0f};
      fps.position = positions[place];
      fps.yaw = 0.0f;
      fps.pitch = radians(pitches[place]);
    }

2つ目の場所(0, 5.5, 36.5)は格子の12.5 m前です。
両方のモードの格子です。
左がPBR、右が同じPbrMaterialの値をtoBlinnPhongに通した物です:

オレンジの球の7 × 7の格子が2つ。行は下から上へ金属度0〜1、列は左から右へ粗さ0〜1。左のPBR:左上の滑らかな金属の球はオレンジに空を映し、粗い金属は暗くなる。下のプラスチックの球はオレンジのままで、白い映り込みと、滑らかな物には鋭いハイライトがある。右のBlinn-Phongの近似:ハイライトは似ているが、粗い金属は明るいオレンジで、プラスチックには映り込む縁が無い

見所:

  • 一番下の行(プラスチック):オレンジの本体に白いハイライトがあり、左から右へ大きく暗くなります。縁の周りには空の薄く白い映り込み、フレネル効果があります。拡散のオレンジはどの列でも同じです。
  • 一番上の行(金属):拡散は全くありません。滑らかな金属は空を色付きで映す鏡で(左の球には地平線が見えます)、粗い金属はぼやけた暗いオレンジです。粗いローブが上の明るい空と下の灰色の地面を平均するからです。
  • 粗い金属は思ったより暗く見えます。 其れは一部は本当で、一部は一回散乱の微小面モデルの既知の限界です。とても粗い面では、光は出て行く前に微小面の間で何度も跳ね返りますが、Gは其の跳ね返りを単に捨てます。エンジンは多重散乱の補正(KullaとConty、Fdez-Agüera)を足しますが、あたし達はしません。
  • Blinn-Phongの側(toBlinnPhong)は、第14章の橋がハイライトについてどれだけ良かったかと、何が足りないかを見せます。フレネルの縁が無く、プラスチックに映り込みが無く、粗い金属が明るいままです。Blinn-Phongの正規化したローブはエネルギーを全く失わないからです。

PBRとBlinn-Phongを並べる

シーン全体と見本の球(Kを2回)で同じ比較をします:

4つの絵。上の行:Blinn-PhongとPBRのシーン全体。PBRの木箱と床の方が自然に見え、金属の箍が空を映す。下の行:Blinn-Phongの4つの見本の球は金属にプラスチックの様な白いハイライトがあり、PBRでは金、クロム、銅が自分の色で空を映し、赤いプラスチックの縁には空が薄く映る

バグではなく予想通りの事:PBRの床は地平線に向かって明るくなり(斜めの角度のフレネル)、金属のハイライトは白ではなくベースカラーになり、粗い銅はBlinn-Phong版より暗く均一です。

直接光とIBLを別々に

Lで光のモードを切り替えます:

見本の球が3回。直接光+IBL:全部が照らされている。直接光だけ:金とクロムの球は小さな太陽のハイライト以外真っ黒、銅は広いハイライト、赤いプラスチックは日の当たる側が照らされ、影は真っ黒。IBLだけ:硬い影は無く、全てが青っぽい空で柔らかく照らされ、金属は其れを映す

真ん中の絵は、第14章の問題の一番純粋な形です。
点光源類だけでは、鏡の様な金属は太陽を映す所以外真っ黒です。
右の絵は空だけで、柔らかく青っぽい曇りの様な見た目です。
シーンには両方が必要です。

夜

夜はuEnvironmentTintがIBLを(0.02, 0.025, 0.05)迄小さくし、提灯が仕事をします:

Blinn-PhongとPBRの夜のシーン。月と提灯で照らされている。PBRでは球が提灯の小さなハイライトを拾い、木箱が少し暗い

どちらのシェーダーでも描く

drawSceneはプログラムとマテリアルのモデルを1回選び、後は2つの小さなラムダを使います:

  auto drawScene = [&] {
    glEnable(GL_DEPTH_TEST);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    sky->bind(3);
    ibl->bind();

    const Shader &lit = usePbr ? *pbr : *phong;
    Shading shading = usePbr ? Shading::Pbr : Shading::BlinnPhong;
    auto apply = [&](const PbrMaterial &m) {
      if (usePbr) m.apply(lit, white);
      else toBlinnPhong(m).apply(lit, white);
    };
    auto drawMesh = [&](const Mesh &mesh, const Mat4 &model) {
      lit.set("uModel", model);
      lit.set("uNormalMatrix", normalMatrix(model));
      mesh.draw();
    };
    lit.use();
    lit.set("uViewMode", viewMode);
    lit.set("uEnvironmentTint", environmentTint);
    if (usePbr) lit.set("uLighting", lighting);

    apply(floorMaterial);
    drawMesh(floorMesh, Mat4::identity());
    scene->draw(lit, Mat4::identity(), white, ModelPass::Opaque, {}, shading);
    for (const Placement &c : kCrates)
      crate->draw(lit, translate(c.position) * rotateY(c.angle), white, ModelPass::Opaque, {}, shading);
    for (const Placement &b : barrels)
      barrel->draw(lit, translate(b.position) * rotateY(b.angle), white, ModelPass::Opaque, {}, shading);

sky->bind(3)とibl->bind()は、第19章からのフレームの構成通りフレーム毎に1回です。
phong.fragはユニット7〜11を宣言していないだけです。
不透明のパスは並べ替えないので、視点の位置に{}を渡して構いません。

ポストの設定はPBRのデータの表示を見分けます:

    // ベクトルの表示(法線・接線)は値をそのまま見せる:トーンマッピングなし、露出1(phong.fragが逆変換して出す)
    // The vector views (normals, tangents) show the raw values: no tone mapping, exposure 1 (phong.frag outputs them
    // pre-decoded)
    if (usePbr ? (viewMode >= 2 && viewMode <= 5) || viewMode == 8 : viewMode >= kFirstVectorView) {
      postSettings.exposure = 1.0f;
      postSettings.toneMapper = static_cast<int>(ToneMapper::Clamp);
    } else {
      postSettings.toneMapper = static_cast<int>(ToneMapper::Aces);
    }

24.12 性能

此のマシン(llvmpipe、2つのCPUコアで動くMesaのソフトウェアラスタライザー。其れが何故大事かは第19章で説明しました)では、全部を有効にした1フレームがPBRで約440 ms、Blinn-Phongで約390 msです。
49個の球の格子、影のパス、2つのGL_RGBA16Fの付け先への4× MSAA、ブルームを含みます。
此れはCPUの数字で、互いに比べる意味しかありません。
此処ではPBRが約50 ms、13%余分に掛かり、GPUならフレーム全体が数ミリ秒です。
違いは大体シェーダーのコードから想像出来る通りです。
光毎にdirectLight()はD、G、𝐅を計算し、Blinn-Phongはpowを1回計算するだけです。
ピクセル毎にpbr.fragは8つのマテリアルと環境のテクスチャ(ベースカラー、法線、金属・粗さ、遮蔽、発光、3つのIBLのマップ)を読み、phong.fragは5つです。
本物のGPUでは、フォワードレンダラーのボトルネックがPBRのシェーディングである事は滅多にありません。
光とピクセルの数の方です。

IBLの作成は、此処では起動時に1回だけ0.4〜0.6秒足されます。

24.13 プラットフォーム毎の注意

  • Windowsのコンソール。 IBLの行は²と×を表示します。コンソールがUTF-8(chcp 65001)でなければ別の文字に化けますが、数字には影響しません。
  • フォーマット。 GL_RGBA16FとGL_RG16FはOpenGL 3.0から必須のカラーレンダラブルなフォーマットで、bitfieldReverseはGLSL 4.00からあるので、全てGL 4.6のどのドライバーでも動きます。WindowsとLinuxのNVIDIA、AMD、Intel、LinuxとFreeBSDのMesa(radeonsi、iris)です。
  • 時間。 glFinishの時間は、ハードウェアのドライバーでは本物のGPUの時間です。llvmpipe(仮想マシン、GPUのドライバー無し)では、24.12節の全てと同じくCPUの時間です。

24.14 本物のエンジンではどうしているか

  • HDRの環境。 エンジンはHDRの空の画像(.hdr、.exr、又はBC6Hで圧縮したKTX2)か、キューブマップに描いた手続き的な空を使い、時刻が変われば撮り直す事も多いです。其の時太陽は環境の中にあるので、画像から消すか平行光源の鏡面を省き、2回数えない様にします。
  • オフラインで焼く。 BRDFの表は定数なので、大抵ファイルとして配布するか、解析的な近似(Karisのモバイル向けの近似)で置き換えます。ぼかした映り込みはcmgen(Filament)やIBLBakerの様な道具で焼き、KTX2で保存する事が多いです。
  • 球面調和関数。 放射照度はとても滑らかなので、9個の球面調和関数の係数(27個の数)でほぼ完全に表せます(RamamoorthiとHanrahan、2001年)。エンジンはキューブマップを読む代わりにシェーダーで其れを計算します(課題6)。
  • ローカルの反射プローブ。 此のIBLは空が無限に遠いと仮定しているので、クロムの球は後ろのレンガの壁ではなく空を映します。エンジンはレベルの中に反射プローブ(其の場所から描いたキューブマップ)を置き、其の間を混ぜ、箱の代理で視差を補正し、残りはスクリーンスペースリフレクションで補います(課題7)。
  • 多重散乱。 KullaとConty(2017年)やFdez-Agüera(2019年)は、一回散乱のGGXが粗い金属で失うエネルギーを、小さな表をもう一つ使って(KullaとConty)、又はBRDFの表のA+Bだけで(Fdez-Agüera)戻します。
  • もっと多くのマテリアルのモデル。 glTFの拡張KHR_materials_clearcoat(車の塗装)、KHR_materials_transmission(ガラス)、KHR_materials_sheen(布)、KHR_materials_ior、KHR_materials_specularは、同じ金属・粗さの核を広げます。エリアライトは大抵、線型変換したコサイン(LTC、Heitzら、2016年)で扱います。
  • VulkanとSlang。 此処にOpenGL特有の物は何もありません。同じBRDF、同じスプリットサム、同じ3つのテクスチャが全てのVulkanのPBRレンダラーに出て来て、シェーダーの関数は一行ずつSlangに訳せます。

24.15 パート4の振り返り

此の章でパート4「高度なOpenGL」が終わります。
第14章のジオラマから10章経って、レンダラーが何を出来る様になったかを見ておく価値があります:

  • 深度とステンシル(第15章):深度関数、リニアな深度、Zファイティング、ステンシルバッファによる輪郭。
  • ブレンディングとカリング(第16章):アルファテスト、並べ替えた半透明、乗算済みアルファ、裏面のカリング。
  • フレームバッファ(第17章):テクスチャへの描画、全画面の三角形、ポストプロセス。
  • キューブマップ(第18章):スカイボックス、反射、屈折、フレネル。
  • ユニフォームバッファとインスタンシング(第19章):カメラと光のstd140のブロック、描画呼び出し1回で何千個もの岩。
  • アンチエイリアス(第20章):マルチサンプルのフレームバッファ、解決、アルファトゥカバレッジ。
  • ガンマとHDR(第21章):リニアなライティング、sRGBのテクスチャ、浮動小数点のフレームバッファ、トーンマッピング、ブルーム。
  • 法線マッピング(第22章):接線、TBN、視差オクルージョンマッピング。
  • シャドウマッピング(第23章):太陽からの深度のパス、バイアス、PCF、テクセルへのスナップ。
  • 物理ベースレンダリング(此の章):Cook–Torrance、glTFのマテリアル、イメージベースドライティング。

合わせると、現代のフォワードレンダラーの核です。
1フレームは、影のパス → PBR、IBL、影、法線マップ付きのMSAAのHDRのシーンのパス → 解決 → ブルーム → トーンマッピングとsRGB → ポストエフェクト、と進みます。
商用のエンジンが上に足す物(ディファードやクラスターのシェーディング、テンポラルアンチエイリアス、グローバルイルミネーション、ストリーミング)は全て此の部品の上に作られています。

此れで「大きなmain.cc一つ」の時期も終わりです。
第25章から始まるパート5では、使い回せるクラス(Window、Shader、Mesh、Texture2D、Framebuffer、Model、PbrMaterial、Ibl等)がエンジンのライブラリに移り、ゲームは其々其れをリンクする自分の実行ファイルになります。
最初のゲームは2D(スペースインベーダー、格闘ゲーム、トップダウンRPG)なので、先ずはスプライト、テキスト、ゲームループに一歩戻ります。
最後のTPSで、pbr.frag、影のパス、IBLと共に此の章のレンダラーに戻って来ます。

24.16 まとめ

  • 放射輝度Lは一つの方向の光(面積・立体角あたり)、放射照度E=∫Lcosθdωは一点に届く全ての光で、一様な空ではπLです。BRDFは𝐥からの放射照度を𝐯への放射輝度にします。
  • レンダリング方程式は、発光と、半球から届く光をBRDFで重み付けした物を足します。点光源類は積分を和にし、空は前計算します(IBL)。
  • 微小面:法線が𝐡の微小面だけが𝐥を𝐯へ反射します。エネルギー保存:𝐤d=(1−𝐅)(1−m)。金属には拡散がありません。
  • Cook–Torrance:f=𝐤d𝐛/π+DG𝐅/(4(𝐧⋅𝐥)(𝐧⋅𝐯))。GGX D=α2/(π((𝐧⋅𝐡)2(α2−1)+1)2)、α=r2、Smith-Schlick-GGX G1(x)=x/(x(1−k)+k)で直接光はk=(r+1)2/8、IBLはk=α/2、Fresnel–Schlick 𝐅=𝐅0+(1−𝐅0)(1−𝐡⋅𝐯)5。
  • glTFの金属・粗さ:𝐅0=mix(0.04,𝐛,m)、拡散𝐛(1−m)、金属度 = 係数 × ユニット7のテクスチャのB、粗さ = 係数 × G(リニア)、遮蔽 = ユニット8のRで間接光だけ。粗さは0.03でクランプ。
  • 光の単位:光の色はBlinn-Phongの意味のままなので、pbr.fragは点光源類をπ倍してランバートの1/πを打ち消します。放射照度マップはE/πを保存し、係数は要りません。
  • IBL:Ibl::build()が起動時にシェーダーで(llvmpipeで約0.4〜0.6秒)、放射照度マップ(32²、ユニット9)、ぼかした映り込み(128²で粗さの5段、ハマースリー点列によるGGXの重点的サンプリングと立体角によるミップマップの選択、ユニット10)、スプリットサムのBRDFの表(128²、GL_RG16F、ユニット11)を描きます。glNamedFramebufferTextureLayerが面と段一つに描きます。
  • 環境はLDRの空なので、映り込みに明るい太陽はありません。ハイライトは直接の太陽光から来ます。
  • PbrMaterialはglTFのマテリアルの構造体、toBlinnPhongは比較用の変換、Shading::Pbrは其れでモデルを描きます。キー:M(PBR / Blinn-Phong)、L(直接光+IBL / 直接光 / IBL)、K(カメラの移動)。
  • llvmpipeでは1フレームがPBRで約440 ms、Blinn-Phongで約390 ms。CPUの時間で、比べる意味しかありません。

24.17 課題

  1. ★ distributionGgxで粗さを其のままαとして使って下さい(2乗を消します)。0と1の間ではr>r2なので、球の格子の直接光のハイライトは広く暗くなるはずです。粗さ0.33の列は、前の約0.58(1/3≈0.577)の列の様に見え、1の列は変わりません(12=1)。0の列さえ変わります。シェーダーが粗さを0.03にクランプするので、αが0.0009ではなく0.03になり、針の先の様なハイライトが小さな丸いハイライトになります。IBLのマップはr2のままなので空の映り込みは変わりません。全ての項が同じαを使わなければならないのは、此の食い違いの為です。
  2. ★ directLight()の最後の行から* PIを消して下さい。日向のPBRのシーンはBlinn-Phongより約π倍暗くなるはずです(Mで比べて下さい)。log2π≈1.65なので、露出が+1.5 EVになる迄=を押すと(0.5ずつ3回)、ほぼ同じ明るさに戻るはずです。
  3. ★ 床を磨いた金属にして下さい:floorMaterialに.metallic = 1.0f, .roughness = 0.1f。床のテクスチャの色が付いた、ぼやけた空を映す濡れた様な鏡の床になるはずですが、上に立っている物は映りません(IBLには空しか無いからです)。
  4. ★★ 遮蔽を金属・粗さのテクスチャのRチャンネルに詰めた「ORM」テクスチャ(多くのエクスポーターが書きます)に対応して下さい。PbrMaterialにbool occlusionInMetallicRoughnessと対応するユニフォームを足し、其れが設定されていればユニット8の代わりにmr.rから遮蔽を読みます。Texture2D::fromPixelsでR = 77(0.3)、G = 255、B = 255の1 × 1のテクスチャを作り、格子の一番上の行の真ん中の球で試します。Lの「IBLだけ」では其の球が隣よりはっきり暗く、「直接光だけ」では前と全く同じに見えるはずです。
  5. ★★ ぼかした映り込みをprefilteredSize = 256に、サンプル数を256に上げて下さい。クロムの球の映り込みが目に見えてくっきりし、表示されるぼかした映り込みの作成時間はllvmpipeで約16倍(テクセル4倍、サンプル4倍)になるはずです。表示して確かめて下さい。
  6. ★★ 放射照度マップを9個の球面調和関数の係数に置き換えて下さい。空の面(glGetTextureImageで読み、先にsRGBを戻します)からCPUで係数を計算し、vec3[9]のユニフォームとして渡し、pbr.fragで法線を使って計算します。拡散のIBLは同じに見え(V、IBLだけで確かめます)、ユニット9は要らなくなるはずです。
  7. ★★★ ローカルの反射プローブ:クロムの球の位置からシーンをキューブマップに描き(第18章の面の表で90°のカメラを6つ)、其のキューブマップからIblを作り、其のぼかした映り込みを4つの見本の球に使って下さい。クロムの球は空だけでなく樽、レンガの壁、パーゴラを映し、粗い銅はレンガから赤っぽい色を拾うはずです。

DIFFをダウンロード

プロジェクトをダウンロード(ZIP)

ファイル: a/CMakeLists.txt | b/CMakeLists.txt

前新
@@ -44,7 +44,9 @@ add_executable(game
44 src/framebuffer.cc 44 src/framebuffer.cc
45 src/cubemap.cc 45 src/cubemap.cc
46 src/gpu_timer.cc 46 src/gpu_timer.cc
47 src/tangents.cc) 47 src/tangents.cc
    48 src/ibl.cc
    49 src/pbr_material.cc)
48 target_include_directories(game PRIVATE src external/stb external/linalg) 50 target_include_directories(game PRIVATE src external/stb external/linalg)
49 target_link_libraries(game PRIVATE glad stb_image glfw) 51 target_link_libraries(game PRIVATE glad stb_image glfw)
50   52  

ファイル: /dev/null | b/shaders/ibl_brdf.frag

前新
@@ -0,0 +1,60 @@
    1 #version 460 core
    2 // IBL(第24章):スプリットサムの後半=BRDFの積分の表(LUT)。x = n·v、y = 粗さ → (A, B)。
    3 // 鏡面のIBL = ぼかした映り込み × (F0 · A + B)。光と関係ないので、どの場面でも同じ表
    4 // IBL (chapter 24): the second half of the split sum = a table (LUT) of the BRDF integral. x = n·v, y = roughness →
    5 // (A, B). Specular IBL = blurred reflection × (F0 · A + B). It does not depend on the lighting: the same for any scene
    6 in vec2 vUv;
    7  
    8 layout(location = 0) out vec4 out_color;
    9  
    10 const float PI = 3.14159265359;
    11 const uint kSamples = 256u;
    12  
    13 // ハマースリー点列:0〜1の正方形に均一に散らばる点(乱数より速く収束する) / the Hammersley sequence: points spread evenly
    14 // over the unit square (converges faster than random numbers)
    15 vec2 hammersley(uint i, uint n) {
    16 return vec2(float(i) / float(n), float(bitfieldReverse(i)) * 2.3283064365386963e-10);
    17 }
    18  
    19 // GGXの分布に従って半ベクトルHを選ぶ(重点的サンプリング)。Nの周りの接線空間で作ってワールドへ
    20 // Picks a half vector H following the GGX distribution (importance sampling), built in tangent space around N
    21 vec3 importanceSampleGgx(vec2 xi, vec3 n, float roughness) {
    22 float a = roughness * roughness;
    23 float phi = 2.0 * PI * xi.x;
    24 float cosTheta = sqrt((1.0 - xi.y) / (1.0 + (a * a - 1.0) * xi.y));
    25 float sinTheta = sqrt(1.0 - cosTheta * cosTheta);
    26 vec3 h = vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta);
    27 vec3 up = abs(n.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
    28 vec3 t = normalize(cross(up, n));
    29 vec3 b = cross(n, t);
    30 return normalize(t * h.x + b * h.y + n * h.z);
    31 }
    32  
    33 // IBL用のSchlick-GGXの幾何項:k = α/2(直接光ではk = (r+1)²/8) / the Schlick-GGX geometry term for IBL: k = α/2
    34 // (for direct light k = (r+1)²/8)
    35 float geometrySchlick(float nDotX, float roughness) {
    36 float k = roughness * roughness / 2.0;
    37 return nDotX / (nDotX * (1.0 - k) + k);
    38 }
    39  
    40 void main() {
    41 float nDotV = max(vUv.x, 1e-3);
    42 float roughness = vUv.y;
    43 vec3 v = vec3(sqrt(1.0 - nDotV * nDotV), 0.0, nDotV);
    44 vec3 n = vec3(0.0, 0.0, 1.0);
    45 float a = 0.0, b = 0.0;
    46 for (uint i = 0u; i < kSamples; ++i) {
    47 vec3 h = importanceSampleGgx(hammersley(i, kSamples), n, roughness);
    48 vec3 l = normalize(2.0 * dot(v, h) * h - v);
    49 float nDotL = max(l.z, 0.0);
    50 float nDotH = max(h.z, 0.0);
    51 float vDotH = max(dot(v, h), 0.0);
    52 if (nDotL <= 0.0) continue;
    53 float g = geometrySchlick(nDotV, roughness) * geometrySchlick(nDotL, roughness);
    54 float gVis = g * vDotH / (nDotH * nDotV);
    55 float fc = pow(1.0 - vDotH, 5.0); // フレネルを F0 · (1 − fc) + fc に分けて二つの数にする / split Fresnel into two numbers
    56 a += (1.0 - fc) * gVis;
    57 b += fc * gVis;
    58 }
    59 out_color = vec4(a / float(kSamples), b / float(kSamples), 0.0, 1.0);
    60 }

ファイル: /dev/null | b/shaders/ibl_irradiance.frag

前新
@@ -0,0 +1,52 @@
    1 #version 460 core
    2 // IBL(第24章):放射照度のキューブマップ。各方向Nについて、半球全体から来る空の光をcosθで重み付けして平均する。
    3 // 結果は「白い拡散面がNを向いていたら反射する明るさ」(= 放射照度E / π)。pbr.fragはベースカラーを掛けるだけ
    4 // IBL (chapter 24): the irradiance cube map. For each direction N, average the sky light arriving from the whole
    5 // hemisphere weighted by cos θ. The result is "how bright a white diffuse surface facing N looks" (= irradiance E / π);
    6 // pbr.frag only multiplies it by the base colour
    7 layout(binding = 0) uniform samplerCube uEnvironment;
    8 uniform int uFace;
    9 uniform float uSize; // この面の大きさ(ピクセル) / this face's size (pixels)
    10 uniform float uSourceLod; // 空のどのミップマップから読むか(小さい段で十分、速い) / which sky mip level to read
    11 // (a small one is enough, and fast)
    12  
    13 layout(location = 0) out vec4 out_color;
    14  
    15 const float PI = 3.14159265359;
    16  
    17 // キューブマップの面faceのピクセル(gl_FragCoord.xy)が表す方向。第18章の表(行0 = t = 0、上の行)
    18 // The direction of pixel gl_FragCoord.xy on cube face `face`. The table of chapter 18 (row 0 = t = 0, the top row)
    19 vec3 faceDirection(int face, vec2 fragCoord, float size) {
    20 float sc = 2.0 * fragCoord.x / size - 1.0;
    21 float tc = 2.0 * fragCoord.y / size - 1.0;
    22 vec3 d;
    23 if (face == 0) d = vec3(1.0, -tc, -sc); // +X
    24 else if (face == 1) d = vec3(-1.0, -tc, sc); // -X
    25 else if (face == 2) d = vec3(sc, 1.0, tc); // +Y
    26 else if (face == 3) d = vec3(sc, -1.0, -tc); // -Y
    27 else if (face == 4) d = vec3(sc, -tc, 1.0); // +Z
    28 else d = vec3(-sc, -tc, -1.0); // -Z
    29 return normalize(d);
    30 }
    31  
    32 void main() {
    33 vec3 n = faceDirection(uFace, gl_FragCoord.xy, uSize);
    34 vec3 up = abs(n.y) < 0.999 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0);
    35 vec3 right = normalize(cross(up, n));
    36 up = cross(n, right);
    37 // 半球を等間隔の角度で:φ(周り)0〜2π、θ(天頂から)0〜π/2。sinθは小さな立体角の補正
    38 // The hemisphere in equal angle steps: φ (around) 0..2π, θ (from the zenith) 0..π/2. sin θ corrects the solid angle
    39 const float delta = 0.08;
    40 vec3 sum = vec3(0.0);
    41 float count = 0.0;
    42 for (float phi = 0.0; phi < 2.0 * PI; phi += delta) {
    43 for (float theta = 0.0; theta < 0.5 * PI; theta += delta) {
    44 vec3 t = vec3(sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta)); // 接線空間 / tangent space
    45 vec3 dir = t.x * right + t.y * up + t.z * n;
    46 sum += textureLod(uEnvironment, dir, uSourceLod).rgb * cos(theta) * sin(theta);
    47 count += 1.0;
    48 }
    49 }
    50 // ∫L cosθ dω ≈ (π²/count)Σ…(= E)。÷π で拡散反射の明るさ / ≈ (π²/count) Σ ... (= E); ÷ π gives the diffuse brightness
    51 out_color = vec4(PI * sum / count, 1.0);
    52 }

ファイル: /dev/null | b/shaders/ibl_prefilter.frag

前新
@@ -0,0 +1,81 @@
    1 #version 460 core
    2 // IBL(第24章):粗さごとにぼかした映り込み(スプリットサムの前半)。ミップマップの段mは粗さ m/(段数−1)。
    3 // GGXで重点的サンプリングし、N = V = R と仮定する(Karisの近似)。ぼかしが粗い点はぼけた空のミップマップから読む
    4 // IBL (chapter 24): reflections blurred per roughness (the first half of the split sum). Mip level m is roughness
    5 // m/(levels − 1). Importance-sampled with GGX assuming N = V = R (Karis' approximation). Coarse samples read a blurrier
    6 // sky mip level
    7 layout(binding = 0) uniform samplerCube uEnvironment;
    8 uniform int uFace;
    9 uniform float uSize; // この段の面の大きさ / this level's face size
    10 uniform float uRoughness;
    11 uniform float uSourceSize; // 空の0段目の面の大きさ / the sky's level-0 face size
    12  
    13 layout(location = 0) out vec4 out_color;
    14  
    15 const float PI = 3.14159265359;
    16 const uint kSamples = 64u;
    17  
    18 // キューブマップの面faceのピクセル(gl_FragCoord.xy)が表す方向。第18章の表(行0 = t = 0、上の行)
    19 // The direction of pixel gl_FragCoord.xy on cube face `face`. The table of chapter 18 (row 0 = t = 0, the top row)
    20 vec3 faceDirection(int face, vec2 fragCoord, float size) {
    21 float sc = 2.0 * fragCoord.x / size - 1.0;
    22 float tc = 2.0 * fragCoord.y / size - 1.0;
    23 vec3 d;
    24 if (face == 0) d = vec3(1.0, -tc, -sc); // +X
    25 else if (face == 1) d = vec3(-1.0, -tc, sc); // -X
    26 else if (face == 2) d = vec3(sc, 1.0, tc); // +Y
    27 else if (face == 3) d = vec3(sc, -1.0, -tc); // -Y
    28 else if (face == 4) d = vec3(sc, -tc, 1.0); // +Z
    29 else d = vec3(-sc, -tc, -1.0); // -Z
    30 return normalize(d);
    31 }
    32 // ハマースリー点列:0〜1の正方形に均一に散らばる点(乱数より速く収束する) / the Hammersley sequence: points spread evenly
    33 // over the unit square (converges faster than random numbers)
    34 vec2 hammersley(uint i, uint n) {
    35 return vec2(float(i) / float(n), float(bitfieldReverse(i)) * 2.3283064365386963e-10);
    36 }
    37  
    38 // GGXの分布に従って半ベクトルHを選ぶ(重点的サンプリング)。Nの周りの接線空間で作ってワールドへ
    39 // Picks a half vector H following the GGX distribution (importance sampling), built in tangent space around N
    40 vec3 importanceSampleGgx(vec2 xi, vec3 n, float roughness) {
    41 float a = roughness * roughness;
    42 float phi = 2.0 * PI * xi.x;
    43 float cosTheta = sqrt((1.0 - xi.y) / (1.0 + (a * a - 1.0) * xi.y));
    44 float sinTheta = sqrt(1.0 - cosTheta * cosTheta);
    45 vec3 h = vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta);
    46 vec3 up = abs(n.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
    47 vec3 t = normalize(cross(up, n));
    48 vec3 b = cross(n, t);
    49 return normalize(t * h.x + b * h.y + n * h.z);
    50 }
    51  
    52 float distributionGgx(float nDotH, float roughness) {
    53 float a = roughness * roughness;
    54 float a2 = a * a;
    55 float d = nDotH * nDotH * (a2 - 1.0) + 1.0;
    56 return a2 / (PI * d * d);
    57 }
    58  
    59 void main() {
    60 vec3 n = faceDirection(uFace, gl_FragCoord.xy, uSize);
    61 vec3 v = n; // 正面から見ていると仮定 / assume we look at it head-on
    62 vec3 sum = vec3(0.0);
    63 float weight = 0.0;
    64 // 空の1テクセルの立体角 / the solid angle of one sky texel
    65 float texelSolidAngle = 4.0 * PI / (6.0 * uSourceSize * uSourceSize);
    66 for (uint i = 0u; i < kSamples; ++i) {
    67 vec3 h = importanceSampleGgx(hammersley(i, kSamples), n, uRoughness);
    68 vec3 l = normalize(2.0 * dot(v, h) * h - v);
    69 float nDotL = dot(n, l);
    70 if (nDotL <= 0.0) continue;
    71 // この点が受け持つ立体角に合うミップマップの段(少ない点でも縞にならない)
    72 // The mip level whose texel matches the solid angle this sample stands for (no banding with few samples)
    73 float nDotH = max(dot(n, h), 0.0);
    74 float pdf = distributionGgx(nDotH, uRoughness) * nDotH / (4.0 * max(dot(h, v), 0.0)) + 1e-4;
    75 float sampleSolidAngle = 1.0 / (float(kSamples) * pdf);
    76 float lod = uRoughness == 0.0 ? 0.0 : 0.5 * log2(sampleSolidAngle / texelSolidAngle) + 1.0;
    77 sum += textureLod(uEnvironment, l, lod).rgb * nDotL;
    78 weight += nDotL;
    79 }
    80 out_color = vec4(sum / weight, 1.0);
    81 }

ファイル: /dev/null | b/shaders/pbr.frag

前新
@@ -0,0 +1,366 @@
    1 #version 460 core
    2 // 物理ベースレンダリング(第24章):Cook–Torrance(GGX・Smith-Schlick-GGX・Fresnel–Schlick)、glTFの金属・粗さ、
    3 // 直接光(影付き)+空からのイメージベースドライティング。頂点シェーダーはphong.vert(またはphong_instanced.vert)
    4 // Physically based rendering (chapter 24): Cook–Torrance (GGX, Smith-Schlick-GGX, Fresnel–Schlick), glTF's
    5 // metallic-roughness, direct light (shadowed) + image-based lighting from the sky. Vertex shader: phong.vert (or
    6 // phong_instanced.vert)
    7 in vec3 vWorldPos;
    8 in vec3 vNormal;
    9 in vec2 vUv;
    10 in vec3 vTint;
    11 in vec4 vTangent;
    12  
    13 // glTFのpbrMetallicRoughnessと同じ(係数 × テクスチャ) / the same as glTF's pbrMetallicRoughness (factor × texture)
    14 struct Material {
    15 vec4 baseColor; // リニア、aは不透明度 / linear, a = opacity
    16 float metallic;
    17 float roughness;
    18 vec3 emissive;
    19 float normalScale; // 0 = 法線マップなし / 0 = no normal map
    20 float parallaxScale; // 0 = 視差なし / 0 = no parallax
    21 float occlusionStrength;
    22 int alphaMode; // 0 = 不透明 / opaque, 1 = マスク / mask, 2 = ブレンド / blend
    23 float alphaCutoff;
    24 bool doubleSided;
    25 };
    26 uniform Material uMaterial;
    27  
    28 layout(binding = 0) uniform sampler2D uBaseColorMap; // sRGB
    29 layout(binding = 2) uniform sampler2D uEmissiveMap; // sRGB
    30 layout(binding = 4) uniform sampler2D uNormalMap; // リニア、A = 高さ / linear, A = height
    31 layout(binding = 5) uniform sampler2DShadow uShadowMap; // 第23章 / chapter 23
    32 layout(binding = 7) uniform sampler2D uMetallicRoughnessMap; // G = 粗さ / roughness, B = 金属度 / metallic
    33 layout(binding = 8) uniform sampler2D uOcclusionMap; // R = 環境光の遮蔽 / ambient occlusion
    34 layout(binding = 9) uniform samplerCube uIrradianceMap; // 拡散のIBL / diffuse IBL
    35 layout(binding = 10) uniform samplerCube uPrefilteredMap; // 鏡面のIBL(粗さ = ミップマップ) / specular IBL (roughness = mip)
    36 layout(binding = 11) uniform sampler2D uBrdfLut; // スプリットサムの表 / the split-sum table
    37 uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く):IBLに掛ける / brightness of the sky: multiplies the IBL
    38  
    39 // 光の構造体。std140では各vec3が16バイトの境目から始まる:C++のLightsBlockと同じ並び(lights.hh)
    40 // The light structs. In std140 each vec3 starts on a 16-byte boundary: the same layout as LightsBlock in C++ (lights.hh)
    41  
    42 // 平行光源:向きだけ / directional light: a direction only
    43 struct DirectionalLight {
    44 vec3 direction; // 光が進む向き(単位ベクトル) / the direction the light travels (unit vector)
    45 vec3 color; // 0 = オフ / 0 = off
    46 };
    47  
    48 // 点光源:位置と減衰 / point light: a position and attenuation
    49 struct PointLight {
    50 vec3 position;
    51 vec3 color;
    52 vec3 attenuation; // 定数項・一次・二次 / constant, linear, quadratic
    53 };
    54  
    55 // スポットライト:点光源+円錐。floatはvec3の後ろの隙間に入れる(詰め物が減る)
    56 // spotlight: a point light + a cone. The floats sit in the gaps after the vec3s (less padding)
    57 struct SpotLight {
    58 vec3 position;
    59 float cosInner; // 内側の円錐の半角のコサイン / cosine of the inner cone's half angle
    60 vec3 direction; // 円錐の軸(単位ベクトル) / the cone's axis (unit vector)
    61 float cosOuter; // 外側の円錐の半角のコサイン / cosine of the outer cone's half angle
    62 vec3 color;
    63 vec3 attenuation;
    64 };
    65  
    66 // C++側の kMaxPointLights、kMaxSpotLights と同じ / same as kMaxPointLights and kMaxSpotLights in C++
    67 #define MAX_POINT_LIGHTS 8
    68 #define MAX_SPOT_LIGHTS 4
    69  
    70 // 全部の光(ユニフォームバッファ、結合点1) / all lights (uniform buffer, binding 1)
    71 layout(std140, binding = 1) uniform Lights {
    72 DirectionalLight uDirLight;
    73 PointLight uPointLights[MAX_POINT_LIGHTS];
    74 SpotLight uSpotLights[MAX_SPOT_LIGHTS];
    75 vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness
    76 int uPointLightCount; // 使っている数 / how many are in use
    77 int uSpotLightCount;
    78 };
    79  
    80 // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
    81 // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
    82 layout(std140, binding = 0) uniform Camera {
    83 mat4 uView;
    84 mat4 uProj;
    85 vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
    86 float uTime; // アニメーションの時間(秒) / animation time (seconds)
    87 };
    88  
    89 // 影(ユニフォームバッファ、結合点2、std140)。使う全部のシェーダーで同じ宣言(C++ではShadowBlock)
    90 // Shadows (uniform buffer, binding 2, std140). The same declaration in every shader that uses it (ShadowBlock in C++)
    91 layout(std140, binding = 2) uniform Shadow {
    92 mat4 uLightSpace; // ワールド → 光のクリップ座標 / world → the light's clip space
    93 float uShadowBias; // 一定のバイアス(0〜1の深度) / constant bias (0..1 depth)
    94 float uShadowSlopeBias; // 傾きに比例するバイアス / slope-scaled bias
    95 float uShadowNormalOffset; // 法線方向のずらし(m) / normal offset (m)
    96 int uShadowFilter; // 0 = 硬い / hard, 1 = 2×2, 2 = PCF 3×3, 3 = PCF 5×5
    97 vec2 uShadowTexel; // 1テクセルのUV / one texel in UV
    98 int uShadowsEnabled;
    99 int uShadowPad;
    100 };
    101  
    102 // 0 = 全部、1 = ベースカラー、2 = 金属度、3 = 粗さ、4 = 遮蔽、5 = 法線、6 = 直接光だけ、7 = IBLだけ、8 = 影
    103 // 0 = everything, 1 = base colour, 2 = metallic, 3 = roughness, 4 = occlusion, 5 = normals, 6 = direct light only,
    104 // 7 = IBL only, 8 = shadow
    105 uniform int uViewMode;
    106 // 0 = 直接光+IBL、1 = 直接光だけ、2 = IBLだけ / 0 = direct + IBL, 1 = direct only, 2 = IBL only
    107 uniform int uLighting = 0;
    108 uniform bool uAlphaToCoverage = false; // 第20章 / chapter 20
    109 uniform bool uParallaxMapping = true; // 第22章 / chapter 22
    110  
    111 #define ALPHA_OPAQUE 0
    112 #define ALPHA_MASK 1
    113 #define ALPHA_BLEND 2
    114  
    115 const float PI = 3.14159265359;
    116  
    117 layout(location = 0) out vec4 out_color;
    118  
    119 // 後処理の設定(ユニフォームバッファ、結合点3、std140、第21章)。使う全部のシェーダーで同じ宣言(C++ではPostBlock)
    120 // Post-processing settings (uniform buffer, binding 3, std140, chapter 21). The same declaration in every shader that
    121 // uses it (PostBlock in C++)
    122 layout(std140, binding = 3) uniform Post {
    123 float uExposure; // 明るさの倍率 / brightness multiplier
    124 float uBloomStrength; // ブルームの強さ / bloom strength
    125 float uBloomThreshold; // これより明るい部分が光る(リニアのHDR値) / brighter than this glows (linear HDR value)
    126 int uToneMapper; // 0 = クランプ / clamp, 1 = Reinhard, 2 = ACES
    127 int uGammaMode; // 0 = シェーダー / shader, 1 = GL_FRAMEBUFFER_SRGB, 2 = なし / none, 3 = 二重 / double
    128 int uPostView; // 0 = 完成 / final, 1 = ブルームなし / no bloom, 2 = 明るい部分 / bright part, 3 = ブルーム / bloom
    129 int uPostPad0, uPostPad1; // std140の大きさを32バイトにそろえる / pads the block to 32 bytes
    130 };
    131  
    132 // ブルーム用の2つ目の出力(MRT、GL_COLOR_ATTACHMENT1):しきい値より明るい部分だけ(色合いは保つ)
    133 // The second output for bloom (MRT, GL_COLOR_ATTACHMENT1): only what is brighter than the threshold (hue kept)
    134 layout(location = 1) out vec4 out_bright;
    135 vec3 brightPart(vec3 c) {
    136 float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); // 輝度 / luminance
    137 return c * (max(l - uBloomThreshold, 0.0) / max(l, 1e-4));
    138 }
    139  
    140 //------------------------------------------------------------------
    141 // Cook–TorranceのBRDF:f = kd · base/π + D · G · F / (4 (n·l)(n·v))
    142 // The Cook–Torrance BRDF: f = kd · base/π + D · G · F / (4 (n·l)(n·v))
    143 //------------------------------------------------------------------
    144  
    145 // D:法線の分布(GGX / Trowbridge-Reitz)。微小な面のうち、hを向いているものの割合。α = 粗さ²(glTF・UE4と同じ)
    146 // D: the normal distribution (GGX / Trowbridge-Reitz): the share of microfacets facing h. α = roughness² (as glTF/UE4)
    147 float distributionGgx(float nDotH, float roughness) {
    148 float a = roughness * roughness;
    149 float a2 = a * a;
    150 float d = nDotH * nDotH * (a2 - 1.0) + 1.0;
    151 return a2 / (PI * d * d);
    152 }
    153  
    154 // G:幾何減衰(Smith法にSchlick-GGX)。微小な面が互いに影を作り、隠し合う分。直接光ではk = (r + 1)² / 8
    155 // G: geometric attenuation (Smith with Schlick-GGX): microfacets shadowing and masking each other. k = (r + 1)² / 8 for
    156 // direct light
    157 float geometrySmith(float nDotV, float nDotL, float roughness) {
    158 float k = (roughness + 1.0) * (roughness + 1.0) / 8.0;
    159 float gv = nDotV / (nDotV * (1.0 - k) + k);
    160 float gl = nDotL / (nDotL * (1.0 - k) + k);
    161 return gv * gl;
    162 }
    163  
    164 // F:フレネル(Schlickの近似)。斜めから見るほど鏡のように反射する / F: Fresnel (Schlick's approximation): the more
    165 // grazing the view, the more mirror-like
    166 vec3 fresnelSchlick(float cosTheta, vec3 f0) {
    167 return f0 + (1.0 - f0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0);
    168 }
    169 // IBL用:粗い面では斜めでも1まで上がらない(Sébastien Lagarde) / for IBL: rough surfaces do not reach 1 at grazing angles
    170 vec3 fresnelSchlickRoughness(float cosTheta, vec3 f0, float roughness) {
    171 return f0 + (max(vec3(1.0 - roughness), f0) - f0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0);
    172 }
    173  
    174 struct Surface {
    175 vec3 n, v;
    176 vec3 base; // ベースカラー(リニア) / base colour (linear)
    177 float metallic, roughness;
    178 vec3 f0; // 正面の反射率:非金属0.04、金属はベースカラー / reflectance at normal incidence: 0.04 for dielectrics,
    179 // the base colour for metals
    180 };
    181  
    182 // 一つの光の直接光。radiance = 面に届く光(光の色 × 減衰 × 影)
    183 // Direct light from one light. radiance = the light reaching the surface (light colour × attenuation × shadow)
    184 vec3 directLight(Surface s, vec3 l, vec3 radiance) {
    185 float nDotL = max(dot(s.n, l), 0.0);
    186 if (nDotL <= 0.0) return vec3(0.0);
    187 vec3 h = normalize(l + s.v);
    188 float nDotV = max(dot(s.n, s.v), 1e-4);
    189 float nDotH = max(dot(s.n, h), 0.0);
    190 float d = distributionGgx(nDotH, s.roughness);
    191 float g = geometrySmith(nDotV, nDotL, s.roughness);
    192 vec3 f = fresnelSchlick(max(dot(h, s.v), 0.0), s.f0);
    193 vec3 specular = d * g * f / (4.0 * nDotV * nDotL + 1e-4);
    194 // エネルギー保存:反射した分(F)は拡散しない。金属は拡散しない / energy conservation: what is reflected (F) does not
    195 // diffuse, and metals do not diffuse at all
    196 vec3 kd = (1.0 - f) * (1.0 - s.metallic);
    197 // このシリーズの光の色は「正面から照らした白い拡散面の明るさ」(Blinn-Phongと同じ意味)。物理的なランバートは
    198 // base/πなので、光の強さをπ倍して同じ明るさにする
    199 // Our light colours mean "how bright a white diffuse surface lit head-on looks" (as with Blinn-Phong). Physical
    200 // Lambert is base/π, so the light is scaled by π to get the same brightness
    201 return (kd * s.base / PI + specular) * radiance * PI * nDotL;
    202 }
    203  
    204 float attenuate(float d, vec3 k) {
    205 return 1.0 / (k.x + k.y * d + k.z * d * d);
    206 }
    207  
    208 // 平行光源の影(第23章):このピクセルを光のクリップ座標に移し、影の地図の深度と比べる。1 = 光が当たる、0 = 影。
    209 // n = 頂点の法線(法線マップ前)、l = 光へ向かう向き
    210 // Directional-light shadow (chapter 23): move this pixel into the light's clip space and compare with the shadow map's
    211 // depth. 1 = lit, 0 = in shadow. n = the vertex normal (before normal mapping), l = towards the light
    212 float shadowFactor(vec3 worldPos, vec3 n, vec3 l) {
    213 if (uShadowsEnabled == 0) return 1.0;
    214 float cosTheta = clamp(dot(n, l), 0.0, 1.0);
    215 // 法線方向に少しずらす(斜めの面ほど多く):影の地図の1テクセルの中で面が自分を影にする「シャドウアクネ」を防ぐ
    216 // Push the point a little along the normal (more on tilted surfaces): prevents "shadow acne", where a surface shadows
    217 // itself inside one shadow-map texel
    218 vec3 p = worldPos + n * (uShadowNormalOffset * (1.0 - cosTheta));
    219 vec4 clip = uLightSpace * vec4(p, 1.0);
    220 vec3 c = clip.xyz / clip.w * 0.5 + 0.5; // NDC → 0..1(UVと深度) / NDC → 0..1 (UV and depth)
    221 if (c.z > 1.0) return 1.0; // 光の箱より奥:影なし / beyond the light's box: not shadowed
    222 // 傾きに比例するバイアス:光に対して斜めな面ほど1テクセルの中の深度の差が大きい(tanθに比例)
    223 // Slope-scaled bias: the more a surface tilts away from the light, the larger the depth change within one texel (∝ tan θ)
    224 float tanTheta = sqrt(max(1.0 - cosTheta * cosTheta, 0.0)) / max(cosTheta, 0.05);
    225 c.z -= uShadowBias + uShadowSlopeBias * min(tanTheta, 10.0);
    226 if (uShadowFilter <= 1) return texture(uShadowMap, c); // 1回:GL_NEARESTなら硬い、GL_LINEARなら2×2 / one lookup
    227 // PCF(percentage-closer filtering):周りの何点かで比べた結果を平均する(深度を平均するのではない)
    228 // PCF (percentage-closer filtering): average the RESULTS of comparisons around the point (not the depths)
    229 int r = uShadowFilter == 2 ? 1 : 2;
    230 float sum = 0.0;
    231 for (int y = -r; y <= r; ++y)
    232 for (int x = -r; x <= r; ++x) sum += texture(uShadowMap, vec3(c.xy + vec2(x, y) * uShadowTexel, c.z));
    233 return sum / float((2 * r + 1) * (2 * r + 1));
    234 }
    235  
    236 // 視差オクルージョンマッピング(第22章):目から表面の奥へ、高さマップの層を一枚ずつ進み、最初に高さマップの
    237 // 下に入った所のUVを返す(前の層との間は直線で補間)。v = 接線空間の目への向き。
    238 // ループの中は分岐なので、ミップマップの段は外で求めた微分で指定する(textureGrad)
    239 // Parallax occlusion mapping (chapter 22): march from the eye into the surface one height layer at a time and return
    240 // the UV where the ray first goes below the height map (interpolated linearly with the previous layer). v = the
    241 // direction to the eye in tangent space. Inside the loop we are in a branch, so the mip level comes from derivatives
    242 // computed outside (textureGrad)
    243 vec2 parallaxOcclusion(vec2 uv, vec3 v, vec2 dx, vec2 dy) {
    244 float layers = mix(32.0, 8.0, clamp(v.z, 0.0, 1.0)); // 斜めほど多く / more layers at grazing angles
    245 float layerDepth = 1.0 / layers;
    246 // 一層ごとのUVのずれ:視線の傾き(xy / z)× 深さ / the UV step per layer: the view's slope (xy / z) × depth
    247 vec2 delta = v.xy / max(v.z, 0.1) * uMaterial.parallaxScale / layers;
    248 float depth = 0.0;
    249 float mapDepth = 1.0 - textureGrad(uNormalMap, uv, dx, dy).a; // 深さ = 1 − 高さ / depth = 1 − height
    250 for (int i = 0; i < 32 && depth < mapDepth; ++i) {
    251 uv -= delta;
    252 mapDepth = 1.0 - textureGrad(uNormalMap, uv, dx, dy).a;
    253 depth += layerDepth;
    254 }
    255 // 最後の2層の間で交点を補間 / interpolate the crossing between the last two layers
    256 vec2 prev = uv + delta;
    257 float after = mapDepth - depth;
    258 float before = (1.0 - textureGrad(uNormalMap, prev, dx, dy).a) - depth + layerDepth;
    259 float w = after / (after - before + 1e-6);
    260 return mix(uv, prev, w);
    261 }
    262  
    263 void main() {
    264 // 接線空間(第22章) / tangent space (chapter 22)
    265 vec3 geometricNormal = normalize(vNormal);
    266 vec3 tangent = vTangent.xyz - dot(vTangent.xyz, geometricNormal) * geometricNormal;
    267 bool hasTangent = dot(tangent, tangent) > 1e-10;
    268 tangent = hasTangent ? normalize(tangent) : vec3(1.0, 0.0, 0.0);
    269 vec3 bitangent = cross(geometricNormal, tangent) * (vTangent.w < 0.0 ? -1.0 : 1.0);
    270 if (uMaterial.doubleSided && !gl_FrontFacing) geometricNormal = -geometricNormal;
    271  
    272 vec2 uv = vUv;
    273 vec2 uvDx = dFdx(vUv), uvDy = dFdy(vUv);
    274 if (uParallaxMapping && uMaterial.parallaxScale > 0.0 && hasTangent) {
    275 vec3 toEye = normalize(uViewPos - vWorldPos);
    276 uv = parallaxOcclusion(vUv, vec3(dot(toEye, tangent), dot(toEye, bitangent), dot(toEye, geometricNormal)), uvDx, uvDy);
    277 }
    278  
    279 // ベースカラーとアルファ(第16・20章と同じ扱い) / base colour and alpha (handled as in chapters 16 and 20)
    280 vec4 baseSample = textureGrad(uBaseColorMap, uv, uvDx, uvDy);
    281 float alpha = uMaterial.baseColor.a * baseSample.a;
    282 float alphaWidth = fwidth(alpha);
    283 if (uMaterial.alphaMode == ALPHA_MASK && uAlphaToCoverage) {
    284 alpha = (alpha - uMaterial.alphaCutoff) / max(alphaWidth, 1e-4) + 0.5;
    285 if (alpha <= 0.0) discard;
    286 } else if (uMaterial.alphaMode == ALPHA_MASK && alpha < uMaterial.alphaCutoff) {
    287 discard;
    288 }
    289 if (uMaterial.alphaMode == ALPHA_BLEND && alpha < 1.0 / 255.0) discard;
    290  
    291 Surface s;
    292 s.n = geometricNormal;
    293 if (hasTangent && uMaterial.normalScale > 0.0) {
    294 vec3 m = textureGrad(uNormalMap, uv, uvDx, uvDy).xyz * 2.0 - 1.0;
    295 m.xy *= uMaterial.normalScale;
    296 s.n = normalize(m.x * tangent + m.y * bitangent + m.z * geometricNormal);
    297 }
    298 s.v = normalize(uViewPos - vWorldPos);
    299 s.base = uMaterial.baseColor.rgb * baseSample.rgb * vTint;
    300 vec4 mr = textureGrad(uMetallicRoughnessMap, uv, uvDx, uvDy);
    301 s.metallic = clamp(uMaterial.metallic * mr.b, 0.0, 1.0);
    302 // 粗さ0はGGXが一点に潰れて光が消える:少しだけ残す / roughness 0 collapses GGX to a point and the highlight vanishes:
    303 // keep a little
    304 s.roughness = clamp(uMaterial.roughness * mr.g, 0.03, 1.0);
    305 s.f0 = mix(vec3(0.04), s.base, s.metallic);
    306 float occlusion = 1.0 + uMaterial.occlusionStrength * (textureGrad(uOcclusionMap, uv, uvDx, uvDy).r - 1.0);
    307 vec3 emissive = uMaterial.emissive * textureGrad(uEmissiveMap, uv, uvDx, uvDy).rgb;
    308  
    309 //------------------------------------------------------------------
    310 // 直接光:太陽(影付き)、点光源、スポットライト / direct light: the sun (shadowed), point lights, spotlights
    311 //------------------------------------------------------------------
    312 vec3 direct = vec3(0.0);
    313 float shadow = shadowFactor(vWorldPos, geometricNormal, -uDirLight.direction);
    314 direct += directLight(s, -uDirLight.direction, uDirLight.color * shadow);
    315 for (int i = 0; i < uPointLightCount; ++i) {
    316 vec3 toLight = uPointLights[i].position - vWorldPos;
    317 float d = length(toLight);
    318 direct += directLight(s, toLight / d, uPointLights[i].color * attenuate(d, uPointLights[i].attenuation));
    319 }
    320 for (int i = 0; i < uSpotLightCount; ++i) {
    321 vec3 toLight = uSpotLights[i].position - vWorldPos;
    322 float d = length(toLight);
    323 vec3 l = toLight / d;
    324 float cone = smoothstep(uSpotLights[i].cosOuter, uSpotLights[i].cosInner, dot(-l, uSpotLights[i].direction));
    325 if (cone <= 0.0) continue;
    326 direct += directLight(s, l, uSpotLights[i].color * attenuate(d, uSpotLights[i].attenuation) * cone);
    327 }
    328  
    329 //------------------------------------------------------------------
    330 // IBL:空からの光。拡散 = 放射照度 × ベースカラー、鏡面 = ぼかした映り込み × (F0 · A + B)(スプリットサム)
    331 // IBL: light from the sky. Diffuse = irradiance × base colour, specular = blurred reflection × (F0 · A + B) (split sum)
    332 //------------------------------------------------------------------
    333 float nDotV = max(dot(s.n, s.v), 1e-4);
    334 vec3 f = fresnelSchlickRoughness(nDotV, s.f0, s.roughness);
    335 vec3 kd = (1.0 - f) * (1.0 - s.metallic);
    336 vec3 irradiance = texture(uIrradianceMap, s.n).rgb;
    337 vec3 r = reflect(-s.v, s.n);
    338 float maxLod = float(textureQueryLevels(uPrefilteredMap) - 1);
    339 vec3 prefiltered = textureLod(uPrefilteredMap, r, s.roughness * maxLod).rgb;
    340 vec2 brdf = texture(uBrdfLut, vec2(nDotV, s.roughness)).rg;
    341 // 鏡面はF0のまま:フレネルはBRDF LUTの中で積分済み(fを使うと二重になる) / the specular uses F0 itself: the BRDF
    342 // LUT already integrates Fresnel (using f would apply it twice)
    343 vec3 specular = prefiltered * (s.f0 * brdf.x + brdf.y);
    344 // 遮蔽(AO)は環境光だけに掛ける(glTFの決まり) / occlusion only affects the environment light (as glTF says)
    345 vec3 ibl = (kd * irradiance * s.base + specular) * occlusion * uEnvironmentTint;
    346  
    347 vec3 color = emissive;
    348 if (uLighting != 2) color += direct;
    349 if (uLighting != 1) color += ibl;
    350 if (uViewMode == 1) color = s.base;
    351 else if (uViewMode == 2) color = vec3(s.metallic);
    352 else if (uViewMode == 3) color = vec3(s.roughness);
    353 else if (uViewMode == 4) color = vec3(occlusion);
    354 else if (uViewMode == 5) color = s.n * 0.5 + 0.5;
    355 else if (uViewMode == 6) color = direct;
    356 else if (uViewMode == 7) color = ibl;
    357 else if (uViewMode == 8) color = vec3(shadow);
    358 // データの表示(2〜5、8)は、sRGBにされた後でちょうどこの値になるように先にリニアへ / data views (2-5, 8): converted
    359 // to linear first so that after the sRGB encoding the screen shows exactly this value
    360 if ((uViewMode >= 2 && uViewMode <= 5) || uViewMode == 8)
    361 color = mix(color / 12.92, pow((color + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), color));
    362  
    363 bool coverage = uMaterial.alphaMode == ALPHA_MASK && uAlphaToCoverage;
    364 out_color = vec4(color, uMaterial.alphaMode == ALPHA_BLEND || coverage ? clamp(alpha, 0.0, 1.0) : 1.0);
    365 out_bright = vec4(uViewMode == 0 ? brightPart(color) : vec3(0.0), out_color.a);
    366 }

ファイル: /dev/null | b/src/ibl.cc

前新
@@ -0,0 +1,113 @@
    1 #include "ibl.hh"
    2  
    3 #include <algorithm>
    4 #include <chrono>
    5 #include <cmath>
    6 #include <cstdio>
    7 #include <utility>
    8  
    9 namespace {
    10  
    11 // 面ごとに描くための、色の付け先だけのFBO(RAII) / an FBO with only a colour attachment, for drawing face by face (RAII)
    12 struct FaceTarget {
    13 GLuint fbo = 0, vao = 0;
    14 FaceTarget() {
    15 glCreateFramebuffers(1, &fbo);
    16 glCreateVertexArrays(1, &vao); // 全画面の三角形(post.vert)用の空のVAO / empty VAO for the fullscreen triangle
    17 }
    18 ~FaceTarget() {
    19 glDeleteFramebuffers(1, &fbo);
    20 glDeleteVertexArrays(1, &vao);
    21 }
    22 FaceTarget(const FaceTarget &) = delete;
    23 FaceTarget &operator=(const FaceTarget &) = delete;
    24  
    25 // キューブマップの面face・ミップマップの段levelに描く:glNamedFramebufferTextureLayerのlayerが面の番号
    26 // Draws into face `face`, mip level `level` of a cube map: the layer of glNamedFramebufferTextureLayer is the face
    27 void drawFace(const Cubemap &cube, int level, int face, int size) const {
    28 glNamedFramebufferTextureLayer(fbo, GL_COLOR_ATTACHMENT0, cube.id(), level, face);
    29 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    30 glViewport(0, 0, size, size);
    31 glBindVertexArray(vao);
    32 glDrawArrays(GL_TRIANGLES, 0, 3);
    33 }
    34 };
    35  
    36 double elapsedMs(std::chrono::steady_clock::time_point start) {
    37 // 本当に描き終わるまで待つ(GPUはコマンドを溜めてから実行する) / wait until drawing really finished (the GPU queues
    38 // commands and runs them later)
    39 glFinish();
    40 return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
    41 }
    42  
    43 } // namespace
    44  
    45 std::optional<Ibl> Ibl::build(const Cubemap &environment, const IblSettings &settings) {
    46 std::optional<Shader> irradianceShader = Shader::load("shaders/post.vert", "shaders/ibl_irradiance.frag");
    47 std::optional<Shader> prefilterShader = Shader::load("shaders/post.vert", "shaders/ibl_prefilter.frag");
    48 std::optional<Shader> brdfShader = Shader::load("shaders/post.vert", "shaders/ibl_brdf.frag");
    49 if (!irradianceShader || !prefilterShader || !brdfShader) return std::nullopt;
    50  
    51 Ibl ibl;
    52 FaceTarget target;
    53 glDisable(GL_DEPTH_TEST);
    54 glDisable(GL_BLEND);
    55 environment.bind(0);
    56  
    57 // 1. 放射照度(拡散の環境光):ミップマップなし / 1. irradiance (diffuse environment light): no mipmaps
    58 auto start = std::chrono::steady_clock::now();
    59 ibl.irradianceMap = Cubemap(settings.irradianceSize, GL_RGBA16F, 1);
    60 irradianceShader->use();
    61 irradianceShader->set("uSize", static_cast<float>(settings.irradianceSize));
    62 // 空の32×32くらいの段で十分 / a sky level of about 32 × 32 is enough
    63 float sourceLod = std::max(0.0f, std::log2(static_cast<float>(environment.size()) / 32.0f));
    64 irradianceShader->set("uSourceLod", sourceLod);
    65 for (int face = 0; face < 6; ++face) {
    66 irradianceShader->set("uFace", face);
    67 target.drawFace(ibl.irradianceMap, 0, face, settings.irradianceSize);
    68 }
    69 ibl.buildMs[0] = elapsedMs(start);
    70  
    71 // 2. ぼかした映り込み(鏡面の環境光):段ごとに粗さを上げる / 2. blurred reflections (specular environment light):
    72 // more roughness on every mip level
    73 start = std::chrono::steady_clock::now();
    74 ibl.prefilteredMap = Cubemap(settings.prefilteredSize, GL_RGBA16F, settings.prefilteredLevels);
    75 prefilterShader->use();
    76 prefilterShader->set("uSourceSize", static_cast<float>(environment.size()));
    77 for (int level = 0; level < settings.prefilteredLevels; ++level) {
    78 int size = std::max(1, settings.prefilteredSize >> level);
    79 prefilterShader->set("uSize", static_cast<float>(size));
    80 // 段が1つだけなら粗さ0の段だけ(0で割らない) / a single level is just roughness 0 (no division by zero)
    81 float roughness = settings.prefilteredLevels > 1
    82 ? static_cast<float>(level) / static_cast<float>(settings.prefilteredLevels - 1)
    83 : 0.0f;
    84 prefilterShader->set("uRoughness", roughness);
    85 for (int face = 0; face < 6; ++face) {
    86 prefilterShader->set("uFace", face);
    87 target.drawFace(ibl.prefilteredMap, level, face, size);
    88 }
    89 }
    90 ibl.buildMs[1] = elapsedMs(start);
    91  
    92 // 3. BRDFの表:普通の2Dテクスチャ(赤と緑の2チャンネル、半精度) / 3. the BRDF table: an ordinary 2D texture
    93 // (red and green, half floats)
    94 start = std::chrono::steady_clock::now();
    95 ibl.brdfFbo = Framebuffer(settings.brdfLutSize, settings.brdfLutSize, {.colorFormat = GL_RG16F, .depthStencilFormat = 0});
    96 ibl.brdfFbo.bind();
    97 brdfShader->use();
    98 glBindVertexArray(target.vao);
    99 glDrawArrays(GL_TRIANGLES, 0, 3);
    100 ibl.buildMs[2] = elapsedMs(start);
    101  
    102 glBindFramebuffer(GL_FRAMEBUFFER, 0);
    103 printf("IBL: irradiance %d² %.0f ms, prefiltered %d² × %d levels %.0f ms, BRDF LUT %d² %.0f ms\n",
    104 settings.irradianceSize, ibl.buildMs[0], settings.prefilteredSize, settings.prefilteredLevels, ibl.buildMs[1],
    105 settings.brdfLutSize, ibl.buildMs[2]);
    106 return ibl;
    107 }
    108  
    109 void Ibl::bind() const {
    110 irradianceMap.bind(kIrradianceUnit);
    111 prefilteredMap.bind(kPrefilteredUnit);
    112 brdfFbo.color().bind(kBrdfLutUnit);
    113 }

ファイル: /dev/null | b/src/ibl.hh

前新
@@ -0,0 +1,46 @@
    1 // イメージベースドライティング(IBL、第24章):空のキューブマップから、拡散と鏡面の環境光の表を起動時に作る
    2 // Image-based lighting (IBL, chapter 24): builds the diffuse and specular environment-light tables from the sky cube map
    3 // at start-up
    4 #pragma once
    5  
    6 #include "cubemap.hh"
    7 #include "framebuffer.hh"
    8 #include "shader.hh"
    9  
    10 #include <optional>
    11  
    12 // 結合するテクスチャユニット(pbr.fragのlayout(binding = …)と同じ) / the texture units (same as layout(binding = ...)
    13 // in pbr.frag)
    14 constexpr GLuint kIrradianceUnit = 9;
    15 constexpr GLuint kPrefilteredUnit = 10;
    16 constexpr GLuint kBrdfLutUnit = 11;
    17  
    18 struct IblSettings {
    19 int irradianceSize = 32; // 放射照度は滑らかなので小さくて良い / irradiance is smooth: small is enough
    20 int prefilteredSize = 128; // ぼかした映り込みの0段目(粗さ0) / level 0 of the blurred reflections (roughness 0)
    21 int prefilteredLevels = 5; // 128, 64, 32, 16, 8:粗さ0, 0.25, 0.5, 0.75, 1 / roughness 0, 0.25, 0.5, 0.75, 1
    22 int brdfLutSize = 128;
    23 };
    24  
    25 // IBLの3つの表(RAII、コピー不可・移動可)。作り方はシェーダー:ibl_irradiance.frag、ibl_prefilter.frag、ibl_brdf.frag
    26 // The three IBL tables (RAII, non-copyable, movable). Made by shaders: ibl_irradiance.frag, ibl_prefilter.frag,
    27 // ibl_brdf.frag
    28 class Ibl {
    29 public:
    30 // environmentから作る(ミップマップ付きのキューブマップ)。シェーダーが読めなければstd::nullopt。かかった時間を表示する
    31 // Builds from `environment` (a cube map with mipmaps). std::nullopt if the shaders cannot be loaded. Prints the time taken
    32 static std::optional<Ibl> build(const Cubemap &environment, const IblSettings &settings = {});
    33  
    34 // ユニット9、10、11に繋ぐ / binds to units 9, 10 and 11
    35 void bind() const;
    36  
    37 const Cubemap &irradiance() const { return irradianceMap; }
    38 const Cubemap &prefiltered() const { return prefilteredMap; }
    39 const Texture2D &brdfLut() const { return brdfFbo.color(); }
    40 double buildMs[3] = {0.0, 0.0, 0.0}; // 放射照度、映り込み、LUT(ミリ秒) / irradiance, reflections, LUT (ms)
    41  
    42 private:
    43 Cubemap irradianceMap;
    44 Cubemap prefilteredMap;
    45 Framebuffer brdfFbo; // 色のテクスチャがLUT(GL_RG16F) / its colour texture is the LUT (GL_RG16F)
    46 };

ファイル: a/src/main.cc | b/src/main.cc

前新
@@ -1,5 +1,5 @@
1 // 第23章:シャドウマッピング 1 // 第24章:物理ベースレンダリング
2 // Chapter 23: shadow mapping 2 // Chapter 24: physically based rendering
3 // 3 //
4 // 操作 / Controls: 4 // 操作 / Controls:
5 // WASD 前後左右に移動 / move forward, back, left, right 5 // WASD 前後左右に移動 / move forward, back, left, right
@@ -7,18 +7,13 @@
7 // Shift 速く動く / move faster 7 // Shift 速く動く / move faster
8 // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit 8 // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit
9 // ホイール / wheel ズーム / zoom 9 // ホイール / wheel ズーム / zoom
    10 // M PBR ⇔ Blinn-Phong(比較) / PBR ⇔ Blinn-Phong (comparison)
    11 // L 光:直接光+IBL → 直接光だけ → IBLだけ / lighting: direct + IBL → direct only → IBL only
    12 // K 見る場所:場面 → 球の格子(金属度 × 粗さ) → 見本の球 / look at: the scene → the sphere grid
    13 // (metallic × roughness) → the sample spheres
    14 // V 表示(PBR):全部 → ベースカラー → 金属度 → 粗さ → 遮蔽 → 法線 → 直接光 → IBL → 影
    15 // view (PBR): all → base colour → metallic → roughness → occlusion → normals → direct → IBL → shadow
10 // H 影のオン・オフ / shadows on / off 16 // H 影のオン・オフ / shadows on / off
11 // B バイアス:なし → 一定 → 傾き+法線ずらし → glPolygonOffset → 大きすぎ(ピーターパン)    
12 // bias: none → constant → slope-scaled + normal offset → glPolygonOffset → too large (peter-panning)    
13 // K 影の地図を描くときのカリング:裏面 → 表面 → なし / culling in the shadow pass: back → front → none    
14 // G 影のフィルター:硬い → 2×2(ハードウェア) → PCF 3×3 → PCF 5×5    
15 // shadow filter: hard → 2 × 2 (hardware) → PCF 3 × 3 → PCF 5 × 5    
16 // J 光の箱:場面全体 ⇔ カメラの視錐台(手前8 m) / light box: whole scene ⇔ camera frustum (first 8 m)    
17 // Z 影の地図の大きさ:512 → 1024 → 2048 → 4096 / shadow map size    
18 // O 影の地図を左下に表示 / show the shadow map at the bottom left    
19 // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 → 頂点の法線 → 接線 → 従法線 → 影    
20 // view: all → ambient → diffuse → specular → emission → normals → vertex normals → tangents →    
21 // bitangents → shadow    
22 // = / - 露出を上げる・下げる / exposure up / down 17 // = / - 露出を上げる・下げる / exposure up / down
23 // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 18 // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出
24 // effect: none / invert / grayscale / sharpen / blur / edge detection 19 // effect: none / invert / grayscale / sharpen / blur / edge detection
@@ -32,11 +27,13 @@
32 #include "camera.hh" 27 #include "camera.hh"
33 #include "cubemap.hh" 28 #include "cubemap.hh"
34 #include "framebuffer.hh" 29 #include "framebuffer.hh"
    30 #include "ibl.hh"
35 #include "lights.hh" 31 #include "lights.hh"
36 #include "material.hh" 32 #include "material.hh"
37 #include "mathx.hh" 33 #include "mathx.hh"
38 #include "mesh.hh" 34 #include "mesh.hh"
39 #include "model.hh" 35 #include "model.hh"
    36 #include "pbr_material.hh"
40 #include "shader.hh" 37 #include "shader.hh"
41 #include "shapes.hh" 38 #include "shapes.hh"
42 #include "texture.hh" 39 #include "texture.hh"
@@ -48,6 +45,7 @@
48 #include <cstdint> 45 #include <cstdint>
49 #include <cstdio> 46 #include <cstdio>
50 #include <optional> 47 #include <optional>
    48 #include <utility>
51 #include <vector> 49 #include <vector>
52   50  
53 // 物を置く場所:位置(底の中心)とY軸周りの回転 / where things go: position (bottom centre) and yaw 51 // 物を置く場所:位置(底の中心)とY軸周りの回転 / where things go: position (bottom centre) and yaw
@@ -64,9 +62,11 @@ static const Placement kCrates[] = {
64 constexpr int kMsaaSamples = 4; // 第20章 / chapter 20 62 constexpr int kMsaaSamples = 4; // 第20章 / chapter 20
65 constexpr int kBloomPasses = 4; // 横+縦の組の数 / number of horizontal + vertical pairs 63 constexpr int kBloomPasses = 4; // 横+縦の組の数 / number of horizontal + vertical pairs
66   64  
67 static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", 65 static const char *const kPbrViewNames[] = {"all", "base colour", "metallic", "roughness", "occlusion",
68 "normals", "vertex normals", "tangents", "bitangents", "shadow"}; 66 "normals", "direct only", "IBL only", "shadow"};
69 constexpr int kViewModes = 10; 67 static const char *const kPhongViewNames[] = {"all", "ambient", "diffuse", "specular", "emission",
    68 "normals", "vertex normals", "tangents", "bitangents", "shadow"};
    69 static const char *const kLightingNames[] = {"direct + IBL", "direct only", "IBL only"};
70   70  
71 // 影のバイアスの方法 / the shadow bias methods 71 // 影のバイアスの方法 / the shadow bias methods
72 struct BiasMode { 72 struct BiasMode {
@@ -86,8 +86,6 @@ static const BiasMode kBiasModes[] = {
86 {"too large: 40 cm (peter-panning)", 0.4f, 0.0f, 0.0f, false, false}, 86 {"too large: 40 cm (peter-panning)", 0.4f, 0.0f, 0.0f, false, false},
87 }; 87 };
88 constexpr size_t kDefaultBias = 2; 88 constexpr size_t kDefaultBias = 2;
89 static const char *const kCullNames[] = {"back faces", "front faces", "none"};    
90 static const char *const kFilterNames[] = {"hard (GL_NEAREST)", "hardware 2x2 (GL_LINEAR)", "PCF 3x3", "PCF 5x5"};    
91 constexpr int kShadowSizes[] = {512, 1024, 2048, 4096}; 89 constexpr int kShadowSizes[] = {512, 1024, 2048, 4096};
92   90  
93 // 平行光源の光から見た行列:centreを中心とする半径radiusの球を正射影の箱に収める。箱は影の地図の1テクセル単位で 91 // 平行光源の光から見た行列:centreを中心とする半径radiusの球を正射影の箱に収める。箱は影の地図の1テクセル単位で
@@ -127,7 +125,7 @@ static std::vector<Placement> makeGrass() {
127 if (ok) grass.push_back({p, 2.0f * PI * random01(seed)}); 125 if (ok) grass.push_back({p, 2.0f * PI * random01(seed)});
128 } 126 }
129 const Placement front[] = {{{1.5f, 0, 6.2f}, 0.3f}, {{-4.0f, 0, 7.6f}, 1.2f}, {{3.9f, 0, 5.4f}, 2.0f}, 127 const Placement front[] = {{{1.5f, 0, 6.2f}, 0.3f}, {{-4.0f, 0, 7.6f}, 1.2f}, {{3.9f, 0, 5.4f}, 2.0f},
130 {{1.4f, 0, 8.9f}, 0.7f}, {{-1.6f, 0, 8.6f}, 2.6f}, {{0.2f, 0, 10.0f}, 1.9f}}; 128 {{0.2f, 0, 10.0f}, 1.9f}};
131 for (const Placement &p : front) grass.push_back(p); 129 for (const Placement &p : front) grass.push_back(p);
132 return grass; 130 return grass;
133 } 131 }
@@ -195,7 +193,7 @@ static std::vector<Lantern> makeLanterns() {
195   193  
196 int main() { 194 int main() {
197 Window window; 195 Window window;
198 if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 23")) return 1; 196 if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 24")) return 1;
199   197  
200 // 画面(既定のフレームバッファ)がsRGBか:GL_FRAMEBUFFER_SRGBが効くのはsRGBのときだけ 198 // 画面(既定のフレームバッファ)がsRGBか:GL_FRAMEBUFFER_SRGBが効くのはsRGBのときだけ
201 // Is the screen (the default framebuffer) sRGB? GL_FRAMEBUFFER_SRGB only has an effect if it is 199 // Is the screen (the default framebuffer) sRGB? GL_FRAMEBUFFER_SRGB only has an effect if it is
@@ -204,6 +202,8 @@ int main() {
204 printf("default framebuffer encoding: %s\n", encoding == GL_SRGB ? "sRGB" : "linear"); 202 printf("default framebuffer encoding: %s\n", encoding == GL_SRGB ? "sRGB" : "linear");
205   203  
206 std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); 204 std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag");
    205 // PBR:頂点シェーダーはphongと同じ / PBR: the same vertex shader as phong
    206 std::optional<Shader> pbr = Shader::load("shaders/phong.vert", "shaders/pbr.frag");
207 std::optional<Shader> skybox = Shader::load("shaders/skybox.vert", "shaders/skybox.frag"); 207 std::optional<Shader> skybox = Shader::load("shaders/skybox.vert", "shaders/skybox.frag");
208 std::optional<Shader> post = Shader::load("shaders/post.vert", "shaders/post.frag"); 208 std::optional<Shader> post = Shader::load("shaders/post.vert", "shaders/post.frag");
209 std::optional<Shader> blur = Shader::load("shaders/post.vert", "shaders/blur.frag"); 209 std::optional<Shader> blur = Shader::load("shaders/post.vert", "shaders/blur.frag");
@@ -221,11 +221,11 @@ int main() {
221 // 影の地図を描くシェーダーと、それを見せるシェーダー / the shader that draws the shadow map and the one that shows it 221 // 影の地図を描くシェーダーと、それを見せるシェーダー / the shader that draws the shadow map and the one that shows it
222 std::optional<Shader> shadowShader = Shader::load("shaders/shadow.vert", "shaders/shadow.frag"); 222 std::optional<Shader> shadowShader = Shader::load("shaders/shadow.vert", "shaders/shadow.frag");
223 std::optional<Shader> shadowDebug = Shader::load("shaders/post.vert", "shaders/shadow_debug.frag"); 223 std::optional<Shader> shadowDebug = Shader::load("shaders/post.vert", "shaders/shadow_debug.frag");
224 if (!phong || !skybox || !post || !blur || !unlit || !sky || !floorTexture || !grassTexture || !brickTexture || 224 if (!phong || !pbr || !skybox || !post || !blur || !unlit || !sky || !floorTexture || !grassTexture || !brickTexture ||
225 !brickNormal || !leavesTexture || !shadowShader || !shadowDebug) 225 !brickNormal || !leavesTexture || !shadowShader || !shadowDebug)
226 return 1; 226 return 1;
227 grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); 227 grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
228 for (const Shader *s : {&*phong, &*skybox, &*post, &*unlit, &*shadowShader}) 228 for (const Shader *s : {&*phong, &*pbr, &*skybox, &*post, &*unlit, &*shadowShader})
229 if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)) || 229 if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)) ||
230 !s->checkUniformBlock("Post", sizeof(PostBlock)) || !s->checkUniformBlock("Shadow", sizeof(ShadowBlock))) 230 !s->checkUniformBlock("Post", sizeof(PostBlock)) || !s->checkUniformBlock("Shadow", sizeof(ShadowBlock)))
231 return 1; 231 return 1;
@@ -237,6 +237,14 @@ int main() {
237 std::optional<Model> barrel = Model::load("assets/models/barrel.glb"); 237 std::optional<Model> barrel = Model::load("assets/models/barrel.glb");
238 if (!scene || !crate || !barrel) return 1; 238 if (!scene || !crate || !barrel) return 1;
239   239  
    240 // IBL:空から、拡散(放射照度)・鏡面(ぼかした映り込み)・BRDFの表を一度だけ作る(第24章)
    241 // IBL: build the diffuse (irradiance), specular (blurred reflections) and BRDF tables from the sky once (chapter 24)
    242 // 作る前にシームレスなフィルタリングを有効にする:ぼかす時に面の辺をまたいで読む(18.6節)
    243 // Seamless filtering must be on before building: the blurring reads across the faces' edges (section 18.6)
    244 glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
    245 std::optional<Ibl> ibl = Ibl::build(*sky);
    246 if (!ibl) return 1;
    247  
240 const unsigned char whitePixel[4] = {255, 255, 255, 255}; 248 const unsigned char whitePixel[4] = {255, 255, 255, 255};
241 Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); 249 Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false});
242   250  
@@ -285,7 +293,6 @@ int main() {
285 sceneFbo.resize(width, height); 293 sceneFbo.resize(width, height);
286 for (Framebuffer &f : bloomFbo) f.resize(width / 2, height / 2); 294 for (Framebuffer &f : bloomFbo) f.resize(width / 2, height / 2);
287 }; 295 };
288 glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);    
289   296  
290 Camera fps; 297 Camera fps;
291 fps.position = {0.6f, 3.6f, 12.5f}; 298 fps.position = {0.6f, 3.6f, 12.5f};
@@ -296,9 +303,12 @@ int main() {
296 orbit.distance = 11.0f; 303 orbit.distance = 11.0f;
297 orbit.yaw = radians(20.0f); 304 orbit.yaw = radians(20.0f);
298   305  
299 bool useOrbit = false, shadowsOn = true, fitFrustum = false, showShadowMap = false; 306 bool useOrbit = false, shadowsOn = true, usePbr = true;
300 size_t biasMode = kDefaultBias; 307 int lighting = 0, place = 0;
301 int cullMode = 0, shadowFilter = static_cast<int>(ShadowFilter::Pcf3x3); 308 // 第23章の影の設定(この章では固定。キーは第23章) / the chapter 23 shadow settings (fixed here; the keys are in ch23)
    309 const bool fitFrustum = false, showShadowMap = false;
    310 const size_t biasMode = kDefaultBias;
    311 const int cullMode = 0, shadowFilter = static_cast<int>(ShadowFilter::Pcf3x3);
302 int viewMode = 0, effect = 0; 312 int viewMode = 0, effect = 0;
303 float exposureEv = 0.0f; // 露出(段、EV):倍率は2^EV / exposure in stops (EV): the multiplier is 2^EV 313 float exposureEv = 0.0f; // 露出(段、EV):倍率は2^EV / exposure in stops (EV): the multiplier is 2^EV
304 PostBlock postSettings; 314 PostBlock postSettings;
@@ -309,9 +319,16 @@ int main() {
309 window.onKey = [&](int key, int action, int /*mods*/) { 319 window.onKey = [&](int key, int action, int /*mods*/) {
310 if (action != GLFW_PRESS) return; 320 if (action != GLFW_PRESS) return;
311 if (key == GLFW_KEY_ESCAPE) window.close(); 321 if (key == GLFW_KEY_ESCAPE) window.close();
312 if (key == GLFW_KEY_R && phong->reload() && skybox->reload() && post->reload() && blur->reload() && unlit->reload() && 322 // IBLのシェーダー(ibl_*.frag)は作るときだけ使う:読み直す = IBLを作り直す(失敗したら前のIBLのまま)
313 shadowShader->reload() && shadowDebug->reload()) 323 // The IBL shaders (ibl_*.frag) are only used while building: reloading them = rebuilding the IBL (the old one stays
314 printf("シェーダーを読み直した / shaders reloaded\n"); 324 // if that fails)
    325 if (key == GLFW_KEY_R && phong->reload() && pbr->reload() && skybox->reload() && post->reload() && blur->reload() &&
    326 unlit->reload() && shadowShader->reload() && shadowDebug->reload()) {
    327 if (std::optional<Ibl> rebuilt = Ibl::build(*sky)) {
    328 ibl = std::move(rebuilt);
    329 printf("シェーダーを読み直した / shaders reloaded\n");
    330 }
    331 }
315 if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); 332 if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured());
316 if (key == GLFW_KEY_C) { 333 if (key == GLFW_KEY_C) {
317 useOrbit = !useOrbit; 334 useOrbit = !useOrbit;
@@ -319,8 +336,27 @@ int main() {
319 printf("camera: %s\n", useOrbit ? "orbit" : "fps"); 336 printf("camera: %s\n", useOrbit ? "orbit" : "fps");
320 } 337 }
321 if (key == GLFW_KEY_V) { 338 if (key == GLFW_KEY_V) {
322 viewMode = (viewMode + 1) % kViewModes; 339 viewMode = (viewMode + 1) % (usePbr ? 9 : 10);
323 printf("view: %s\n", kViewModeNames[viewMode]); 340 printf("view: %s\n", usePbr ? kPbrViewNames[viewMode] : kPhongViewNames[viewMode]);
    341 }
    342 if (key == GLFW_KEY_M) {
    343 usePbr = !usePbr;
    344 viewMode = 0;
    345 printf("shading: %s\n", usePbr ? "PBR (Cook-Torrance + IBL)" : "Blinn-Phong");
    346 }
    347 if (key == GLFW_KEY_L) {
    348 lighting = (lighting + 1) % 3;
    349 printf("lighting: %s\n", kLightingNames[lighting]);
    350 }
    351 if (key == GLFW_KEY_K) {
    352 // 決まった場所にカメラを置く / put the camera at a fixed place
    353 place = (place + 1) % 3;
    354 useOrbit = false;
    355 const Vec3 positions[] = {{0.6f, 3.6f, 12.5f}, {0.0f, 5.5f, 36.5f}, {0.0f, 1.3f, 11.4f}};
    356 const float pitches[] = {-17.0f, 0.0f, -14.0f};
    357 fps.position = positions[place];
    358 fps.yaw = 0.0f;
    359 fps.pitch = radians(pitches[place]);
324 } 360 }
325 if (key >= GLFW_KEY_1 && key <= GLFW_KEY_6) { 361 if (key >= GLFW_KEY_1 && key <= GLFW_KEY_6) {
326 effect = key - GLFW_KEY_1; 362 effect = key - GLFW_KEY_1;
@@ -334,60 +370,33 @@ int main() {
334 shadowsOn = !shadowsOn; 370 shadowsOn = !shadowsOn;
335 printf("shadows: %s\n", shadowsOn ? "on" : "off"); 371 printf("shadows: %s\n", shadowsOn ? "on" : "off");
336 } 372 }
337 if (key == GLFW_KEY_B) {    
338 biasMode = (biasMode + 1) % std::size(kBiasModes);    
339 printf("shadow bias: %s\n", kBiasModes[biasMode].name);    
340 }    
341 if (key == GLFW_KEY_K) {    
342 cullMode = (cullMode + 1) % 3;    
343 printf("shadow pass culling: %s\n", kCullNames[cullMode]);    
344 }    
345 if (key == GLFW_KEY_G) {    
346 shadowFilter = (shadowFilter + 1) % 4;    
347 printf("shadow filter: %s\n", kFilterNames[shadowFilter]);    
348 }    
349 if (key == GLFW_KEY_J) {    
350 fitFrustum = !fitFrustum;    
351 printf("light box: %s\n", fitFrustum ? "camera frustum (0.1-8 m)" : "whole scene");    
352 }    
353 if (key == GLFW_KEY_Z) {    
354 shadowSizeIndex = (shadowSizeIndex + 1) % std::size(kShadowSizes);    
355 shadowFbo = Framebuffer(kShadowSizes[shadowSizeIndex], kShadowSizes[shadowSizeIndex], shadowSpec);    
356 printf("shadow map: %d x %d\n", shadowFbo.width(), shadowFbo.height());    
357 }    
358 if (key == GLFW_KEY_O) showShadowMap = !showShadowMap;    
359 if (key == GLFW_KEY_N) night = !night; 373 if (key == GLFW_KEY_N) night = !night;
360 if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; 374 if (key == GLFW_KEY_F) flashlightOn = !flashlightOn;
361 if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; 375 if (key == GLFW_KEY_P) windmillMoving = !windmillMoving;
362 }; 376 };
363   377  
    378 // 手で作るマテリアルはすべてPbrMaterial(第24章)。Blinn-Phongで描くときはtoBlinnPhongで変換する。
    379 // 手で選んだ色はsRGBの値なのでsrgbToLinearでリニアに
    380 // Every hand-made material is a PbrMaterial (chapter 24); for Blinn-Phong they are converted with toBlinnPhong.
    381 // Hand-picked colours are sRGB values, so srgbToLinear makes them linear
    382 auto rgb = [](float r, float g, float b, float a = 1.0f) {
    383 Vec3 c = srgbToLinear(Vec3{r, g, b});
    384 return Vec4{c.x, c.y, c.z, a};
    385 };
364 Mesh floorMesh = makePlane(160.0f, 40.0f); 386 Mesh floorMesh = makePlane(160.0f, 40.0f);
365 Mesh cubeMesh = makeCube(); 387 Mesh cubeMesh = makeCube();
366 Material floorMaterial; 388 PbrMaterial floorMaterial{.roughness = 0.65f, .baseColorMap = &*floorTexture};
367 floorMaterial.diffuseMap = &*floorTexture;    
368 floorMaterial.specular = {0.15f, 0.15f, 0.15f};    
369 floorMaterial.shininess = 16.0f;    
370   389  
371 Mesh tuftMesh = makeCrossedQuads(3); 390 Mesh tuftMesh = makeCrossedQuads(3);
372 std::vector<Placement> grass = makeGrass(); 391 std::vector<Placement> grass = makeGrass();
373 Material grassMaterial; 392 PbrMaterial grassMaterial{.roughness = 0.9f, .alphaMode = AlphaMode::Mask, .baseColorMap = &*grassTexture};
374 grassMaterial.diffuseMap = &*grassTexture;    
375 grassMaterial.alphaMode = AlphaMode::Mask;    
376 grassMaterial.specular = {0.04f, 0.04f, 0.04f};    
377 grassMaterial.shininess = 8.0f;    
378   393  
379 std::vector<Mat4> wires = makeWires(); 394 std::vector<Mat4> wires = makeWires();
380 // レンガの壁(5 × 2.5 m、厚さ0.3 m)、柱、球。箱のUVはメートル単位で、1 mごとにテクスチャ1枚    
381 // The brick wall (5 × 2.5 m, 0.3 m thick), a pillar and a sphere. Box UVs are in metres, one texture tile per metre    
382 Mesh wallMesh = makeBox({5.0f, 2.5f, 0.3f}); 395 Mesh wallMesh = makeBox({5.0f, 2.5f, 0.3f});
383 Mesh pillarMesh = makeBox({0.6f, 3.0f, 0.6f}); 396 Mesh pillarMesh = makeBox({0.6f, 3.0f, 0.6f});
384 Mesh brickSphere = makeSphere(48, 24); 397 Mesh brickSphere = makeSphere(48, 24);
385 Material brickMaterial; 398 PbrMaterial brickMaterial{.roughness = 0.85f, .parallaxScale = 0.04f, .baseColorMap = &*brickTexture,
386 brickMaterial.diffuseMap = &*brickTexture; 399 .normalMap = &*brickNormal};
387 brickMaterial.normalMap = &*brickNormal;    
388 brickMaterial.specular = {0.08f, 0.08f, 0.08f};    
389 brickMaterial.shininess = 24.0f;    
390 brickMaterial.parallaxScale = 0.04f; // 1枚(1 m)の4% = 4 cm の深さ / 4 % of a tile (1 m) = 4 cm deep    
391 struct Piece { 400 struct Piece {
392 const Mesh *mesh; 401 const Mesh *mesh;
393 Mat4 model; 402 Mat4 model;
@@ -397,121 +406,115 @@ int main() {
397 {&pillarMesh, translate({1.6f, 1.5f, 4.4f}) * rotateY(0.3f)}, 406 {&pillarMesh, translate({1.6f, 1.5f, 4.4f}) * rotateY(0.3f)},
398 {&brickSphere, translate({-2.3f, 0.6f, 6.9f}) * scale({1.2f, 1.2f, 1.2f})}, 407 {&brickSphere, translate({-2.3f, 0.6f, 6.9f}) * scale({1.2f, 1.2f, 1.2f})},
399 }; 408 };
400 // 樽の置き場所 / where the barrels stand    
401 const Placement barrels[] = {{{-0.4f, 0.0f, 5.6f}, 0.3f}, {{0.35f, 0.0f, 6.1f}, 2.0f}, {{2.6f, 0.0f, 5.9f}, 1.1f}}; 409 const Placement barrels[] = {{{-0.4f, 0.0f, 5.6f}, 0.3f}, {{0.35f, 0.0f, 6.1f}, 2.0f}, {{2.6f, 0.0f, 5.9f}, 1.1f}};
402 // パーゴラ:木の柱4本と、葉(切り抜き)の屋根。葉の形の影を落とす / a pergola: four wooden posts and a roof of    
403 // (cut-out) leaves. It casts leaf-shaped shadows    
404 const Vec3 kPergola = {1.3f, 0.0f, 5.8f}; 410 const Vec3 kPergola = {1.3f, 0.0f, 5.8f};
405 Mesh postMesh = makeBox({0.12f, 2.6f, 0.12f}); 411 Mesh postMesh = makeBox({0.12f, 2.6f, 0.12f});
406 Mesh roofMesh = makePlane(2.8f, 4.0f); 412 Mesh roofMesh = makePlane(2.8f, 4.0f);
407 Material postMaterial; 413 PbrMaterial postMaterial{.baseColor = rgb(0.45f, 0.32f, 0.2f), .roughness = 0.8f};
408 postMaterial.diffuse = srgbToLinear(Vec3{0.45f, 0.32f, 0.2f});    
409 postMaterial.specular = {0.05f, 0.05f, 0.05f};    
410 postMaterial.shininess = 8.0f;    
411 std::vector<Mat4> posts; 414 std::vector<Mat4> posts;
412 for (float x : {-1.3f, 1.3f}) 415 for (float x : {-1.3f, 1.3f})
413 for (float z : {-1.3f, 1.3f}) posts.push_back(translate(kPergola + Vec3{x, 1.3f, z})); 416 for (float z : {-1.3f, 1.3f}) posts.push_back(translate(kPergola + Vec3{x, 1.3f, z}));
414 // 葉の板2枚(2枚目は45°回して少し上に:隙間を埋める) / two leaf layers (the second turned 45° and a little higher:    
415 // fills the gaps)    
416 const Mat4 roofModels[] = {translate(kPergola + Vec3{0.0f, 2.6f, 0.0f}), 417 const Mat4 roofModels[] = {translate(kPergola + Vec3{0.0f, 2.6f, 0.0f}),
417 translate(kPergola + Vec3{0.0f, 2.68f, 0.0f}) * rotateY(0.785f) * scale({0.75f, 1.0f, 0.75f})}; 418 translate(kPergola + Vec3{0.0f, 2.68f, 0.0f}) * rotateY(0.785f) * scale({0.75f, 1.0f, 0.75f})};
418 Material leavesMaterial; 419 PbrMaterial leavesMaterial{.roughness = 0.8f, .alphaMode = AlphaMode::Mask, .doubleSided = true,
419 leavesMaterial.diffuseMap = &*leavesTexture; 420 .baseColorMap = &*leavesTexture};
420 leavesMaterial.alphaMode = AlphaMode::Mask; 421 PbrMaterial wireMaterial{.baseColor = rgb(0.04f, 0.04f, 0.045f), .roughness = 0.35f};
421 leavesMaterial.doubleSided = true; 422  
422 leavesMaterial.specular = {0.03f, 0.03f, 0.03f};    
423 leavesMaterial.shininess = 8.0f;    
424 // 手で選んだ色はsRGBの値(カラーピッカーの値):シェーダーはリニアで計算するので変換する    
425 // Hand-picked colours are sRGB values (what a colour picker shows): the shaders compute in linear space, so convert    
426 Material wireMaterial;    
427 wireMaterial.diffuse = srgbToLinear(Vec3{0.04f, 0.04f, 0.045f});    
428 wireMaterial.specular = {0.3f, 0.3f, 0.3f};    
429 wireMaterial.shininess = 32.0f;    
430      
431 // 提灯:本体は暗い紙、発光で光る(1より明るい:HDR) / lanterns: dark paper, glowing through emission (brighter    
432 // than 1: HDR)    
433 std::vector<Lantern> lanterns = makeLanterns(); 423 std::vector<Lantern> lanterns = makeLanterns();
434 Mesh sphereMesh = makeSphere(24, 12); 424 Mesh sphereMesh = makeSphere(48, 24);
435 constexpr float kLanternGlow = 6.0f; 425 constexpr float kLanternGlow = 6.0f;
436   426  
    427 // 見本の球:磨いた金、クロム、粗い銅、赤いプラスチック(glTFの値で、金属のベースカラー = F0)
    428 // Sample spheres: polished gold, chrome, rough copper, red plastic (glTF values; a metal's base colour = its F0)
    429 struct Showcase {
    430 Vec3 position;
    431 PbrMaterial material;
    432 };
    433 const Showcase showcase[] = {
    434 {{-1.8f, 0.35f, 8.0f}, {.baseColor = {1.0f, 0.766f, 0.336f, 1.0f}, .metallic = 1.0f, .roughness = 0.15f}},
    435 {{-0.6f, 0.35f, 8.3f}, {.baseColor = {0.95f, 0.95f, 0.95f, 1.0f}, .metallic = 1.0f, .roughness = 0.05f}},
    436 {{0.6f, 0.35f, 8.3f}, {.baseColor = {0.955f, 0.638f, 0.538f, 1.0f}, .metallic = 1.0f, .roughness = 0.55f}},
    437 {{1.8f, 0.35f, 8.0f}, {.baseColor = rgb(0.75f, 0.08f, 0.06f), .metallic = 0.0f, .roughness = 0.3f}},
    438 };
    439 // 金属度 × 粗さの球の格子(7 × 7):宙に浮かべる。上の行ほど金属、右の列ほど粗い(Kで見に行く)
    440 // The metallic × roughness sphere grid (7 × 7), floating in the air: metal towards the top row, rougher to the right
    441 // (go and look with K)
    442 constexpr int kGrid = 7;
    443 const Vec3 kGridCentre = {0.0f, 5.5f, 24.0f};
    444 const Vec4 kGridColor = rgb(0.9f, 0.35f, 0.15f);
437   445  
438 FullscreenTriangle fullscreen; 446 FullscreenTriangle fullscreen;
439 glEnable(GL_CULL_FACE); 447 glEnable(GL_CULL_FACE);
440   448  
441 // 場面全体を今のフレームバッファに描く(ビューポートは呼ぶ側) / draws the whole scene into the current framebuffer 449 // 場面全体を今のフレームバッファに描く。litはpbr(PBR)かphong(比較用のBlinn-Phong)
442 // (the caller sets the viewport) 450 // Draws the whole scene into the current framebuffer. `lit` is pbr (PBR) or phong (Blinn-Phong, for comparison)
443 Vec3 environmentTint; 451 Vec3 environmentTint;
444 auto drawScene = [&] { 452 auto drawScene = [&] {
445 glEnable(GL_DEPTH_TEST); 453 glEnable(GL_DEPTH_TEST);
446 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); 454 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
447 sky->bind(3); 455 sky->bind(3);
    456 ibl->bind();
448   457  
449 phong->use(); 458 const Shader &lit = usePbr ? *pbr : *phong;
450 phong->set("uViewMode", viewMode); 459 Shading shading = usePbr ? Shading::Pbr : Shading::BlinnPhong;
451   460 auto apply = [&](const PbrMaterial &m) {
452 phong->set("uEnvironmentTint", environmentTint); 461 if (usePbr) m.apply(lit, white);
453 phong->set("uModel", Mat4::identity()); 462 else toBlinnPhong(m).apply(lit, white);
454 phong->set("uNormalMatrix", normalMatrix(Mat4::identity())); 463 };
455 floorMaterial.apply(*phong, white); 464 auto drawMesh = [&](const Mesh &mesh, const Mat4 &model) {
456 floorMesh.draw(); 465 lit.set("uModel", model);
457 scene->draw(*phong, Mat4::identity(), white, ModelPass::Opaque); 466 lit.set("uNormalMatrix", normalMatrix(model));
458 for (const Placement &c : kCrates) crate->draw(*phong, translate(c.position) * rotateY(c.angle), white, ModelPass::Opaque); 467 mesh.draw();
459 Material lanternMaterial; 468 };
460 lanternMaterial.diffuse = {0.05f, 0.03f, 0.02f}; 469 lit.use();
461 lanternMaterial.specular = {0.02f, 0.02f, 0.02f}; 470 lit.set("uViewMode", viewMode);
    471 lit.set("uEnvironmentTint", environmentTint);
    472 if (usePbr) lit.set("uLighting", lighting);
    473  
    474 apply(floorMaterial);
    475 drawMesh(floorMesh, Mat4::identity());
    476 scene->draw(lit, Mat4::identity(), white, ModelPass::Opaque, {}, shading);
    477 for (const Placement &c : kCrates)
    478 crate->draw(lit, translate(c.position) * rotateY(c.angle), white, ModelPass::Opaque, {}, shading);
    479 for (const Placement &b : barrels)
    480 barrel->draw(lit, translate(b.position) * rotateY(b.angle), white, ModelPass::Opaque, {}, shading);
    481 PbrMaterial lanternMaterial{.baseColor = rgb(0.2f, 0.15f, 0.1f), .roughness = 0.6f};
462 for (const Lantern &l : lanterns) { 482 for (const Lantern &l : lanterns) {
463 lanternMaterial.emission = kLanternGlow * l.color; 483 lanternMaterial.emissive = kLanternGlow * l.color;
464 lanternMaterial.apply(*phong, white); 484 apply(lanternMaterial);
465 Mat4 model = translate(l.position) * scale({0.3f, 0.38f, 0.3f}); 485 drawMesh(sphereMesh, translate(l.position) * scale({0.3f, 0.38f, 0.3f}));
466 phong->set("uModel", model);    
467 phong->set("uNormalMatrix", normalMatrix(model));    
468 sphereMesh.draw();    
469 }    
470 wireMaterial.apply(*phong, white);    
471 for (const Mat4 &m : wires) {    
472 phong->set("uModel", m);    
473 phong->set("uNormalMatrix", normalMatrix(m));    
474 cubeMesh.draw();    
475 } 486 }
476 // レンガ(法線マップ+視差) / the bricks (normal map + parallax) 487 apply(wireMaterial);
477 brickMaterial.apply(*phong, white); 488 for (const Mat4 &m : wires) drawMesh(cubeMesh, m);
478 for (const Piece &b : bricks) { 489 apply(brickMaterial);
479 phong->set("uModel", b.model); 490 for (const Piece &b : bricks) drawMesh(*b.mesh, b.model);
480 phong->set("uNormalMatrix", normalMatrix(b.model)); 491 apply(postMaterial);
481 b.mesh->draw(); 492 for (const Mat4 &m : posts) drawMesh(postMesh, m);
482 } 493 for (const Showcase &sc : showcase) {
483 for (const Placement &b : barrels) barrel->draw(*phong, translate(b.position) * rotateY(b.angle), white, ModelPass::Opaque); 494 apply(sc.material);
484 postMaterial.apply(*phong, white); 495 drawMesh(sphereMesh, translate(sc.position) * scale({0.7f, 0.7f, 0.7f}));
485 for (const Mat4 &m : posts) {    
486 phong->set("uModel", m);    
487 phong->set("uNormalMatrix", normalMatrix(m));    
488 postMesh.draw();    
489 } 496 }
    497 // 球の格子:行 = 金属度 0〜1(下から上)、列 = 粗さ 0〜1(左から右) / the grid: rows = metallic 0..1 (bottom to
    498 // top), columns = roughness 0..1 (left to right)
    499 for (int row = 0; row < kGrid; ++row)
    500 for (int col = 0; col < kGrid; ++col) {
    501 PbrMaterial m{.baseColor = kGridColor, .metallic = static_cast<float>(row) / (kGrid - 1),
    502 .roughness = static_cast<float>(col) / (kGrid - 1)};
    503 apply(m);
    504 Vec3 p = kGridCentre + Vec3{1.1f * (static_cast<float>(col) - 3.0f), 1.1f * (static_cast<float>(row) - 3.0f), 0.0f};
    505 drawMesh(sphereMesh, translate(p) * scale({0.9f, 0.9f, 0.9f}));
    506 }
490   507  
491 // 草:アルファトゥカバレッジならdiscardの代わりにサンプルの一部だけを覆う(MSAAのときだけ意味がある) 508 // 切り抜き(第16・20章):アルファトゥカバレッジ / cut-outs (chapters 16 and 20): alpha to coverage
492 // Grass: with alpha to coverage, a fragment covers only some of the samples instead of being discarded (only    
493 // meaningful with MSAA)    
494 glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); 509 glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
495 phong->set("uAlphaToCoverage", 1); 510 lit.set("uAlphaToCoverage", 1);
496 // 葉の屋根(両面) / the roof of leaves (double-sided)    
497 leavesMaterial.apply(*phong, white);    
498 glDisable(GL_CULL_FACE); 511 glDisable(GL_CULL_FACE);
499 for (const Mat4 &m : roofModels) { 512 apply(leavesMaterial);
500 phong->set("uModel", m); 513 for (const Mat4 &m : roofModels) drawMesh(roofMesh, m);
501 phong->set("uNormalMatrix", normalMatrix(m)); 514 apply(grassMaterial);
502 roofMesh.draw(); 515 for (const Placement &g : grass) drawMesh(tuftMesh, translate(g.position) * rotateY(g.angle) * scale({0.75f, 0.75f, 0.75f}));
503 }    
504 glEnable(GL_CULL_FACE);    
505 grassMaterial.apply(*phong, white);    
506 glDisable(GL_CULL_FACE);    
507 for (const Placement &g : grass) {    
508 Mat4 model = translate(g.position) * rotateY(g.angle) * scale({0.75f, 0.75f, 0.75f});    
509 phong->set("uModel", model);    
510 phong->set("uNormalMatrix", normalMatrix(model));    
511 tuftMesh.draw();    
512 }    
513 glEnable(GL_CULL_FACE); 516 glEnable(GL_CULL_FACE);
514 phong->set("uAlphaToCoverage", 0); 517 lit.set("uAlphaToCoverage", 0);
515 glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); 518 glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
516   519  
517 glDepthFunc(GL_LEQUAL); 520 glDepthFunc(GL_LEQUAL);
@@ -541,6 +544,7 @@ int main() {
541 for (const Mat4 &m : wires) drawMesh(cubeMesh, m); 544 for (const Mat4 &m : wires) drawMesh(cubeMesh, m);
542 for (const Piece &b : bricks) drawMesh(*b.mesh, b.model); 545 for (const Piece &b : bricks) drawMesh(*b.mesh, b.model);
543 for (const Mat4 &m : posts) drawMesh(postMesh, m); 546 for (const Mat4 &m : posts) drawMesh(postMesh, m);
    547 for (const Showcase &sc : showcase) drawMesh(sphereMesh, translate(sc.position) * scale({0.7f, 0.7f, 0.7f}));
544 // 切り抜き:両面なのでカリングなし / cut-outs: two-sided, so no culling 548 // 切り抜き:両面なのでカリングなし / cut-outs: two-sided, so no culling
545 glDisable(GL_CULL_FACE); 549 glDisable(GL_CULL_FACE);
546 shadowShader->set("uAlphaMask", 1); 550 shadowShader->set("uAlphaMask", 1);
@@ -621,7 +625,7 @@ int main() {
621 // ベクトルの表示(法線・接線)は値をそのまま見せる:トーンマッピングなし、露出1(phong.fragが逆変換して出す) 625 // ベクトルの表示(法線・接線)は値をそのまま見せる:トーンマッピングなし、露出1(phong.fragが逆変換して出す)
622 // The vector views (normals, tangents) show the raw values: no tone mapping, exposure 1 (phong.frag outputs them 626 // The vector views (normals, tangents) show the raw values: no tone mapping, exposure 1 (phong.frag outputs them
623 // pre-decoded) 627 // pre-decoded)
624 if (viewMode >= kFirstVectorView) { 628 if (usePbr ? (viewMode >= 2 && viewMode <= 5) || viewMode == 8 : viewMode >= kFirstVectorView) {
625 postSettings.exposure = 1.0f; 629 postSettings.exposure = 1.0f;
626 postSettings.toneMapper = static_cast<int>(ToneMapper::Clamp); 630 postSettings.toneMapper = static_cast<int>(ToneMapper::Clamp);
627 } else { 631 } else {

ファイル: a/src/model.cc | b/src/model.cc

前新
@@ -305,7 +305,7 @@ void Model::draw(const Shader &shader, const Mat4 &transform, const Texture2D &w
305 } 305 }
306   306  
307 void Model::draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, ModelPass pass, 307 void Model::draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, ModelPass pass,
308 Vec3 viewPos) const { 308 Vec3 viewPos, Shading shading) const {
309 std::vector<DrawItem> items; 309 std::vector<DrawItem> items;
310 for (int root : roots) collect(root, transform, transform, true, pass, viewPos, items); 310 for (int root : roots) collect(root, transform, transform, true, pass, viewPos, items);
311 if (pass == ModelPass::Transparent) { 311 if (pass == ModelPass::Transparent) {
@@ -314,7 +314,7 @@ void Model::draw(const Shader &shader, const Mat4 &transform, const Texture2D &w
314 std::stable_sort(items.begin(), items.end(), 314 std::stable_sort(items.begin(), items.end(),
315 [](const DrawItem &a, const DrawItem &b) { return a.distance > b.distance; }); 315 [](const DrawItem &a, const DrawItem &b) { return a.distance > b.distance; });
316 } 316 }
317 drawItems(items, shader, &white, true); 317 drawItems(items, shader, &white, true, 0, false, shading);
318 } 318 }
319   319  
320 void Model::drawGeometry(const Shader &shader, const Mat4 &transform) const { 320 void Model::drawGeometry(const Shader &shader, const Mat4 &transform) const {
@@ -355,14 +355,14 @@ void Model::setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span<co
355 for (Primitive &p : m.primitives) p.mesh.setInstanceBuffer(buffer, stride, layout); 355 for (Primitive &p : m.primitives) p.mesh.setInstanceBuffer(buffer, stride, layout);
356 } 356 }
357   357  
358 void Model::drawInstanced(const Shader &shader, const Texture2D &white, GLsizei count) const { 358 void Model::drawInstanced(const Shader &shader, const Texture2D &white, GLsizei count, Shading shading) const {
359 std::vector<DrawItem> items; 359 std::vector<DrawItem> items;
360 for (int root : roots) collect(root, Mat4::identity(), Mat4::identity(), true, ModelPass::All, {}, items); 360 for (int root : roots) collect(root, Mat4::identity(), Mat4::identity(), true, ModelPass::All, {}, items);
361 drawItems(items, shader, &white, shader.has("uNormalMatrix"), count); 361 drawItems(items, shader, &white, shader.has("uNormalMatrix"), count, false, shading);
362 } 362 }
363   363  
364 void Model::drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white, 364 void Model::drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white,
365 bool normals, GLsizei instances, bool depthOnly) const { 365 bool normals, GLsizei instances, bool depthOnly, Shading shading) const {
366 bool culling = glIsEnabled(GL_CULL_FACE); // 呼ぶ側の設定を覚えておく / remember the caller's setting 366 bool culling = glIsEnabled(GL_CULL_FACE); // 呼ぶ側の設定を覚えておく / remember the caller's setting
367 for (const DrawItem &item : items) { 367 for (const DrawItem &item : items) {
368 const Primitive &p = *item.primitive; 368 const Primitive &p = *item.primitive;
@@ -379,6 +379,15 @@ void Model::drawItems(const std::vector<DrawItem> &items, const Shader &shader,
379 shader.set("uAlphaCutoff", md.phong.alphaCutoff); 379 shader.set("uAlphaCutoff", md.phong.alphaCutoff);
380 shader.set("uBaseAlpha", md.phong.alpha); 380 shader.set("uBaseAlpha", md.phong.alpha);
381 } 381 }
    382 } else if (white && shading == Shading::Pbr) {
    383 // glTFの値とテクスチャそのまま(第24章) / glTF's values and textures as they are (chapter 24)
    384 PbrMaterial m = PbrMaterial::fromGltf(md.pbr);
    385 m.baseColorMap = texture(md.pbr.baseColorTexture.index);
    386 m.emissiveMap = texture(md.pbr.emissiveTexture.index);
    387 m.normalMap = texture(md.pbr.normalTexture.index);
    388 m.metallicRoughnessMap = texture(md.pbr.metallicRoughnessTexture.index);
    389 m.occlusionMap = texture(md.pbr.occlusionTexture.index);
    390 m.apply(shader, *white);
382 } else if (white) { 391 } else if (white) {
383 Material m = md.phong; 392 Material m = md.phong;
384 m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture 393 m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture

ファイル: a/src/model.hh | b/src/model.hh

前新
@@ -4,6 +4,7 @@
4 #include "gltf.hh" 4 #include "gltf.hh"
5 #include "material.hh" 5 #include "material.hh"
6 #include "mesh.hh" 6 #include "mesh.hh"
    7 #include "pbr_material.hh"
7 #include "shader.hh" 8 #include "shader.hh"
8 #include "texture.hh" 9 #include "texture.hh"
9   10  
@@ -21,6 +22,13 @@ enum class ModelPass {
21 // (the caller sets up blending) 22 // (the caller sets up blending)
22 }; 23 };
23   24  
    25 // どのマテリアルで描くか(第24章)。シェーダーに合わせる:phong.fragならBlinnPhong、pbr.fragならPbr
    26 // Which material model to draw with (chapter 24). Match the shader: BlinnPhong for phong.frag, Pbr for pbr.frag
    27 enum class Shading {
    28 BlinnPhong, // MaterialData::phong(第14章の近似) / MaterialData::phong (the chapter 14 approximation)
    29 Pbr, // MaterialData::pbrのglTFの値そのまま(PbrMaterial) / MaterialData::pbr's glTF values as they are
    30 };
    31  
24 // 読み込んだモデル:メッシュ(VAO)、テクスチャ、マテリアル、ノードの階層(RAII、コピー不可・移動可)。 32 // 読み込んだモデル:メッシュ(VAO)、テクスチャ、マテリアル、ノードの階層(RAII、コピー不可・移動可)。
25 // 描くときは、ノードごとに 親のワールド行列 × 自分のローカル行列 をたどる。 33 // 描くときは、ノードごとに 親のワールド行列 × 自分のローカル行列 をたどる。
26 // A loaded model: meshes (VAOs), textures, materials and the node hierarchy (RAII, non-copyable, movable). 34 // A loaded model: meshes (VAOs), textures, materials and the node hierarchy (RAII, non-copyable, movable).
@@ -63,8 +71,10 @@ public:
63 // 両面(doubleSided)のマテリアルは、その間だけフェイスカリングを切って描く。 71 // 両面(doubleSided)のマテリアルは、その間だけフェイスカリングを切って描く。
64 // Draws only the primitives of `pass`. Transparent sorts them back to front by the distance from viewPos to the 72 // Draws only the primitives of `pass`. Transparent sorts them back to front by the distance from viewPos to the
65 // centre of each primitive's box. Double-sided materials are drawn with face culling turned off for that draw. 73 // centre of each primitive's box. Double-sided materials are drawn with face culling turned off for that draw.
    74 // shading = Pbrならマテリアルは金属・粗さ・遮蔽などのテクスチャごとPbrMaterialで設定する(第24章)
    75 // With shading = Pbr the materials are set as PbrMaterial, with their metallic-roughness, occlusion... maps (ch. 24)
66 void draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, ModelPass pass, 76 void draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, ModelPass pass,
67 Vec3 viewPos = {}) const; 77 Vec3 viewPos = {}, Shading shading = Shading::BlinnPhong) const;
68 // 形だけを描く:マテリアルもテクスチャも設定せず、ノードごとにuModelだけ(シェーダーが使っていればuNormalMatrixも)。 78 // 形だけを描く:マテリアルもテクスチャも設定せず、ノードごとにuModelだけ(シェーダーが使っていればuNormalMatrixも)。
69 // 深度の表示、輪郭、のちの影(第23章)のように、色を使わないパス用。 79 // 深度の表示、輪郭、のちの影(第23章)のように、色を使わないパス用。
70 // Draws the shape only: no materials or textures, just uModel per node (and uNormalMatrix if the shader uses it). 80 // Draws the shape only: no materials or textures, just uModel per node (and uNormalMatrix if the shader uses it).
@@ -86,7 +96,8 @@ public:
86 // インスタンスの行列はシェーダーで掛ける(phong_instanced.vert:world = aInstanceModel × uModel × 位置)。 96 // インスタンスの行列はシェーダーで掛ける(phong_instanced.vert:world = aInstanceModel × uModel × 位置)。
87 // Draws count instances with one draw call per primitive. uModel is the node's model-space matrix; the shader 97 // Draws count instances with one draw call per primitive. uModel is the node's model-space matrix; the shader
88 // multiplies the instance matrix on top (phong_instanced.vert: world = aInstanceModel × uModel × position). 98 // multiplies the instance matrix on top (phong_instanced.vert: world = aInstanceModel × uModel × position).
89 void drawInstanced(const Shader &shader, const Texture2D &white, GLsizei count) const; 99 void drawInstanced(const Shader &shader, const Texture2D &white, GLsizei count,
    100 Shading shading = Shading::BlinnPhong) const;
90   101  
91 // 名前でノードを探す。なければ-1 / finds a node by name; -1 if none 102 // 名前でノードを探す。なければ-1 / finds a node by name; -1 if none
92 int findNode(std::string_view name) const; 103 int findNode(std::string_view name) const;
@@ -117,7 +128,7 @@ private:
117 Vec3 viewPos, std::vector<DrawItem> &out) const; 128 Vec3 viewPos, std::vector<DrawItem> &out) const;
118 // white == nullptrなら形だけ(drawGeometry) / white == nullptr: shape only (drawGeometry) 129 // white == nullptrなら形だけ(drawGeometry) / white == nullptr: shape only (drawGeometry)
119 void drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white, bool normals, 130 void drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white, bool normals,
120 GLsizei instances = 0, bool depthOnly = false) const; 131 GLsizei instances = 0, bool depthOnly = false, Shading shading = Shading::BlinnPhong) const;
121 const MaterialData &materialOf(const Primitive &p) const; 132 const MaterialData &materialOf(const Primitive &p) const;
122 const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing 133 const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing
123   134  

ファイル: /dev/null | b/src/pbr_material.cc

前新
@@ -0,0 +1,62 @@
    1 #include "pbr_material.hh"
    2  
    3 void PbrMaterial::apply(const Shader &shader, const Texture2D &white) const {
    4 shader.set("uMaterial.baseColor", baseColor);
    5 shader.set("uMaterial.metallic", metallic);
    6 shader.set("uMaterial.roughness", roughness);
    7 shader.set("uMaterial.emissive", emissive);
    8 // 法線マップがなければ0:白(1,1,1)が平らな(0,0,1)になる(第22章) / 0 without a normal map: white (1,1,1) becomes the
    9 // flat (0,0,1) (chapter 22)
    10 shader.set("uMaterial.normalScale", normalMap ? normalScale : 0.0f);
    11 shader.set("uMaterial.parallaxScale", normalMap ? parallaxScale : 0.0f);
    12 shader.set("uMaterial.occlusionStrength", occlusionStrength);
    13 shader.set("uMaterial.alphaMode", static_cast<int>(alphaMode));
    14 shader.set("uMaterial.alphaCutoff", alphaCutoff);
    15 shader.set("uMaterial.doubleSided", doubleSided ? 1 : 0);
    16 (baseColorMap ? baseColorMap : &white)->bind(0);
    17 (emissiveMap ? emissiveMap : &white)->bind(2);
    18 (normalMap ? normalMap : &white)->bind(4);
    19 (metallicRoughnessMap ? metallicRoughnessMap : &white)->bind(7);
    20 (occlusionMap ? occlusionMap : &white)->bind(8);
    21 }
    22  
    23 PbrMaterial PbrMaterial::fromGltf(const GltfMaterial &m) {
    24 PbrMaterial p;
    25 p.baseColor = m.baseColorFactor;
    26 p.metallic = m.metallicFactor;
    27 p.roughness = m.roughnessFactor;
    28 p.emissive = m.emissiveStrength * m.emissiveFactor;
    29 p.normalScale = m.normalTexture.scale;
    30 p.occlusionStrength = m.occlusionTexture.scale; // glTFのstrengthはscaleに入っている / glTF's strength is stored in scale
    31 p.alphaMode = m.alphaMode == GltfAlphaMode::Mask ? AlphaMode::Mask
    32 : m.alphaMode == GltfAlphaMode::Blend ? AlphaMode::Blend
    33 : AlphaMode::Opaque;
    34 p.alphaCutoff = m.alphaCutoff;
    35 p.doubleSided = m.doubleSided;
    36 return p;
    37 }
    38  
    39 Material toBlinnPhong(const PbrMaterial &m) {
    40 Vec3 base = {m.baseColor.x, m.baseColor.y, m.baseColor.z};
    41 Material p;
    42 p.diffuse = (1.0f - m.metallic) * base;
    43 Vec3 f0 = lerp({0.04f, 0.04f, 0.04f}, base, m.metallic);
    44 float alpha = m.roughness * m.roughness;
    45 float n = alpha > 0.0f ? 2.0f / (alpha * alpha) - 2.0f : 1024.0f;
    46 n = n < 1.0f ? 1.0f : n > 1024.0f ? 1024.0f : n;
    47 p.specular = ((n + 8.0f) / 8.0f) * f0;
    48 p.shininess = n;
    49 p.emission = m.emissive;
    50 p.alpha = m.baseColor.w;
    51 p.alphaMode = m.alphaMode;
    52 p.alphaCutoff = m.alphaCutoff;
    53 p.doubleSided = m.doubleSided;
    54 p.reflectivity = (m.metallic * m.metallic) * f0;
    55 p.reflectionBlur = m.roughness;
    56 p.diffuseMap = m.baseColorMap;
    57 p.emissionMap = m.emissiveMap;
    58 p.normalMap = m.normalMap;
    59 p.normalScale = m.normalScale;
    60 p.parallaxScale = m.parallaxScale;
    61 return p;
    62 }

ファイル: /dev/null | b/src/pbr_material.hh

前新
@@ -0,0 +1,42 @@
    1 // 物理ベースのマテリアル(第24章):glTFの金属・粗さモデルそのまま / a physically based material (chapter 24): exactly
    2 // glTF's metallic-roughness model
    3 #pragma once
    4  
    5 #include "gltf.hh"
    6 #include "material.hh"
    7 #include "mathx.hh"
    8 #include "shader.hh"
    9 #include "texture.hh"
    10  
    11 // テクスチャはすべて「係数 × テクスチャ」。ないテクスチャには白を繋ぐ(白 × 係数 = 係数)。
    12 // Every texture is "factor × texture". A missing texture is replaced by white (white × factor = factor).
    13 struct PbrMaterial {
    14 Vec4 baseColor = {1.0f, 1.0f, 1.0f, 1.0f}; // リニア、aは不透明度 / linear, a = opacity
    15 float metallic = 0.0f; // 0 = 非金属(誘電体)、1 = 金属 / 0 = dielectric, 1 = metal
    16 float roughness = 0.5f; // 0 = 鏡、1 = つや消し / 0 = mirror, 1 = fully matte
    17 Vec3 emissive = {0.0f, 0.0f, 0.0f}; // 発光(HDR、強さを掛けた後) / emission (HDR, strength applied)
    18 float normalScale = 1.0f; // glTFのnormalTexture.scale
    19 float occlusionStrength = 1.0f; // glTFのocclusionTexture.strength
    20 float parallaxScale = 0.0f; // 第22章の視差(OpenGLのUVの物だけ) / chapter 22 parallax (OpenGL UVs only)
    21 AlphaMode alphaMode = AlphaMode::Opaque;
    22 float alphaCutoff = 0.5f;
    23 bool doubleSided = false;
    24  
    25 const Texture2D *baseColorMap = nullptr; // ユニット0、sRGB / unit 0, sRGB
    26 const Texture2D *emissiveMap = nullptr; // ユニット2、sRGB / unit 2, sRGB
    27 const Texture2D *normalMap = nullptr; // ユニット4、リニア / unit 4, linear
    28 const Texture2D *metallicRoughnessMap = nullptr; // ユニット7:G = 粗さ、B = 金属度、リニア / unit 7: G = roughness, B = metallic
    29 const Texture2D *occlusionMap = nullptr; // ユニット8:R = 遮蔽、リニア / unit 8: R = occlusion, linear
    30  
    31 // pbr.fragのuMaterialを設定し、マップを繋ぐ(ないものは白) / sets pbr.frag's uMaterial and binds the maps (white
    32 // for missing ones)
    33 void apply(const Shader &shader, const Texture2D &white) const;
    34  
    35 // glTFのマテリアルの係数(テクスチャは呼ぶ側が繋ぐ) / the factors of a glTF material (the caller attaches textures)
    36 static PbrMaterial fromGltf(const GltfMaterial &m);
    37 };
    38  
    39 // 比較用:同じ表面をBlinn-Phongで近似する(第14章のphongFromPbrと同じ式、ただしテクスチャの平均は使わない)
    40 // For comparison: approximate the same surface with Blinn-Phong (the formulas of chapter 14's phongFromPbr, without
    41 // texture averages)
    42 Material toBlinnPhong(const PbrMaterial &m);


コメント(0)

まだコメントはありません。