22. 法線マッピング
GLSL 第12章では、法線マッピングのシェーダー側を書きました。
テクセル毎に法線を保存したテクスチャ、其れをワールド座標に直すTBN行列、そして接線を手で求められるレンガの壁と球です。
其の章は「そういうメッシュの読み込みはOpenGL編で」という約束で終わりました。
此の章が其の約束です。
本物のレンダラーは接線を手で求められません。
モデルのファイルから貰うか、ファイルに無ければ位置とUVから計算し、其れを頂点の形式、モデル行列、補間を通して壊さずに運ばなければなりません。
あたし達の形にはまだ接線が全く無く、glTFとあたし達の形ではの向きが逆で、鏡像のテクスチャは座標系全体を裏返します。
此れらを全部片付け、法線マップと高さマップ付きのレンガのテクスチャを作り、蓋にわざと接線の無い樽を読み込み、最後に目地が本当に壁に沈んで見える視差オクルージョンマッピングで仕上げます。
22.1 此の章で作る物
ジオラマの前に、幅5 m・高さ2.5 mのレンガの壁、レンガの柱、レンガの球、木の樽が3つ置かれています。
暖かい色の点光源が壁のすぐ前を回るので、レンガの1つ1つが色々な側から光を受ける様子が見えます:
操作:
- W、A、S、D、スペース、左Ctrl、Shift、マウス、ホイール:今迄通り移動と見回し
- M:法線マップのオン・オフ(新規)
- X:視差マッピングのオン・オフ(新規)
- L:回る点光源のオン・オフ(新規)
- V:表示モード、9つに:全部、環境光、拡散、鏡面、発光、法線、頂点の法線、接線、従法線(3つ新規)
- =と−:露出(第21章と同じ)
- P:風車と回る光を止める・動かす
- 1〜6:ポストプロセスの効果、C:FPS ⇔ オービットカメラ、N:昼 ⇔ 夜、F:懐中電灯
- Tab:カーソルの解放、R:シェーダーを読み直す、Esc:終了
第21章のキーT、G、B、O、Kは無くなりました。
ACESのトーンマッピング、シェーダーでのガンマ、ブルームは常にオンです。
第20章の柵は壁に場所を譲りました。
第21章からの変更:
src/tangents.hhとsrc/tangents.cc(新規):UvConventionとcomputeTangentssrc/shapes.hhとsrc/shapes.cc:全ての形に接線が付き、UVがメートル単位のmakeBoxが新しく加わるsrc/model.cc:法線マップがあるのにTANGENTの無いglTFのプリミティブの接線を計算し、法線マップをマテリアルに渡すsrc/material.hhとsrc/material.cc:テクスチャユニット4のnormalMap、normalScale、parallaxScaleshaders/phong.vertとshaders/phong_instanced.vert:location 3の接線の属性shaders/phong.frag:TBN、法線マップ、視差オクルージョンマッピング、3つの新しい表示モードsrc/main.cc:新しいシーンassets/textures/bricks.pngとassets/textures/bricks_normal.png(新規)、assets/models/barrel.glb(新規、223 KiB)(完成したファイルは章のZIPとアセットのZIPのch22/に入っています)CMakeLists.txt:gameにsrc/tangents.ccを追加
src/gpu_timer.cc
src/tangents.cc)
22.2 もう知っている事と、足りない物
GLSL 第12章の簡単なおさらいです。
法線マップは全てのテクセルに、接線空間の単位ベクトルを保存しています。
は画像の右、は画像の上、は表面の外を向きます。
の値は色のとして保存されるので、平らなテクセルは見慣れた水色のになります。
表面の或る点では、3つのベクトルが接線空間の基底を作ります。
接線(画像の右が表面のどちらにあるか)、従法線(画像の上がどちらにあるか。GLSL編では従接線と呼びました。コードのコメントに合わせて此処では従法線と呼びます)、そして法線です。
基底の変換(線型代数 第11章)で、戻したテクセルがワールド座標の法線になります:
GLSL 第12章では、壁のとは単にとで、球では媒介変数の式を手で微分しました。
ファイルから読んだモデルは只の三角形の集まりなので、エンジンはシェーダーの章では飛ばせた4つの問いに答えなければなりません:
- 全ての頂点のは何処から来るのか?
- UV空間で「画像の上」はどちらか?(glTFとあたし達の形では違います。)
- はどうやってモデル座標からワールド座標に行き、フラグメントシェーダーに着く迄に何が起きるのか?
- 全てのシェーダーにフラグを置かずに、マテリアルが「法線マップは無い」とどう伝えるのか?
此れが道筋の全体で、此の章の残りは上から下へ順に此れを辿ります:
22.3 接線は何処から来るか
ファイルから
glTFには此の為の頂点属性TANGENTがあります。
頂点毎にfloatのVEC4です。
xyzが単位ベクトルの接線で、wは又はのハンドネス(座標系が右手か左手か)です。
従法線は保存されず、シェーダーが次の式で作り直します:
頂点毎にfloatが3つ節約出来、が両方に垂直である事も保証されます(何故が必要なのかは22.4節で説明します)。
あたし達のローダーは第14章からTANGENTをModelVertexに読んでいて、レイアウトは其れをずっとlocation 3に渡し、此の章を待っていました:
// モデル(glTF)の頂点:Vertex3Dに接線を足したもの。接線は第22章の法線マッピングで使う。
// wは従法線の向き(±1):従法線 = cross(normal, tangent.xyz) * tangent.w。接線がなければ (0, 0, 0, 0)。
// A model (glTF) vertex: Vertex3D plus a tangent, used for normal mapping in chapter 22.
// w is the bitangent's sign (±1): bitangent = cross(normal, tangent.xyz) * tangent.w. (0, 0, 0, 0) if there is none.
struct ModelVertex {
Vec3 position;
Vec3 normal;
Vec2 uv;
Vec4 tangent;
};
constexpr VertexAttrib kModelVertexLayout[] = {
{0, 3, offsetof(ModelVertex, position)}, // layout(location = 0) in vec3 aPosition
{1, 3, offsetof(ModelVertex, normal)}, // layout(location = 1) in vec3 aNormal
{2, 2, offsetof(ModelVertex, uv)}, // layout(location = 2) in vec2 aUv
{3, 4, offsetof(ModelVertex, tangent)}, // layout(location = 3) in vec4 aTangent(第22章 / chapter 22)
};
接線の無い頂点は(0, 0, 0, 0)のままで、フラグメントシェーダーは其れを「接線無し」として扱います(22.10節)。
位置とUVから計算する
glTFではTANGENTは省略出来ます。
仕様は、法線マップがあるのに接線の無いプリミティブでは、レンダラーが自分で計算する様に言い、Morten MikkelsenのMikkTSpaceというアルゴリズムを勧めています。
Blenderや殆どのベイクの道具が使っている物です。
MikkTSpaceは二千行近い丁寧なコードです。
代わりに、あたし達は昔からある簡単な方法を書きます。
滑らかなメッシュでは殆ど同じ結果になり、違いが出るのは主に硬い角とUVの継ぎ目の周りです(22.15節で又触れます)。
考え方は三角形1つに収まります。
三角形の中では、位置はテクスチャ座標の線型な関数です。
テクスチャの上で進むと表面の上を動き、進むと動きます。
此処で、です。
角を原点にします。
2本の辺、と其のUVの差、は、次を満たさなければなりません:
未知のベクトル2つに対してベクトルの式が2つです。
ベクトルを列にして行列で書くと:
両辺に右から2 × 2のUVの行列の逆行列を掛けます(線型代数 第10章:対角を入れ替え、残りの符号を変え、行列式で割ります):
として、列毎に書くと:
なら三角形のUVは直線(又は点)の上にあり、テクスチャが其の三角形を2つの方向に覆っていないので、其の三角形からは何も分かりません。
計算例
床の上の三角形です。
何も軸に揃わない様に、わざとテクスチャを45°回してあります:
| 角 | 位置 | UV |
|---|---|---|
| a | (0, 0, 0) | (0, 0) |
| b | (2, 0, 0) | (1, 1) |
| c | (0, 0, −2) | (−1, 1) |
辺はとで、UVの差はとです。
行列式はです。
すると
確かめ:、です。
どちらも長さはです。
テクスチャが対角線に沿って其れだけ伸びているので、の1単位が床の1.414 mに当たります。
法線マッピングに大事なのは長さではなく向きだけなので、コードはをに正規化し、の長さは捨てます。
頂点毎に沢山の三角形
1つの頂点は幾つもの三角形に属し、三角形毎にとがあります。
簡単な方法では、其れらを正規化せずに頂点毎に足します。
テクスチャが余計に伸びている三角形(が長い物)が少しだけ多く数えられますが、均等にテクスチャが貼られたメッシュでは殆ど普通の平均です。
結果は一般に頂点の法線に垂直ではありません。
法線は別の三角形から別のやり方で平均された物だからです。
其の為、最後の段階はグラム・シュミットです。
の方向の成分(線型代数 第4章の射影、壁ずりと同じ式)を取り除いてから正規化します:
此の例ではで既になので、何も変わりません。
コード
src/tangents.hhは関数とUVの決まり(22.5節)を宣言します:
// 接線の計算(第22章):法線マップの「右」と「上」が、表面のどの向きかを頂点ごとに求める
// Computing tangents (chapter 22): for every vertex, which surface directions a normal map's "right" and "up" are
#pragma once
#include "mesh.hh"
#include <cstdint>
#include <vector>
// UVの向きの決まり / which way the image's "up" runs in UV space
enum class UvConvention {
OpenGl, // vが上へ増える(stb_imageで反転して読んだ画像、shapes.cc) / v grows upwards (images loaded flipped, shapes.cc)
Gltf, // vが下へ増える(glTF:画像を反転しない) / v grows downwards (glTF: images are not flipped)
};
// 三角形の位置とUVの変化から接線(uが増える向き)を求め、頂点ごとに足して、法線に垂直にして正規化する
// (グラム・シュミット)。wは従法線の向き:cross(normal, tangent.xyz) * w が画像の「上」を向くように±1。
// indicesが空なら頂点を3つずつ三角形として使う。三角形(GL_TRIANGLES)だけ。
// Computes tangents (the direction in which u grows) from each triangle's position and UV differences, sums them
// per vertex, then makes them perpendicular to the normal and normalizes them (Gram-Schmidt). w is the bitangent's
// sign: ±1 so that cross(normal, tangent.xyz) * w points to the image's "up". With empty indices, every three
// vertices form a triangle. Triangles (GL_TRIANGLES) only.
void computeTangents(std::vector<ModelVertex> &vertices, const std::vector<std::uint32_t> &indices,
UvConvention uv);
src/tangents.ccの前半は三角形毎の部分で、d1 = (Δu₁, Δv₁)、d2 = (Δu₂, Δv₂)とした上の式其の物です:
#include "tangents.hh"
#include <cmath>
void computeTangents(std::vector<ModelVertex> &vertices, const std::vector<std::uint32_t> &indices,
UvConvention convention) {
size_t n = vertices.size();
std::vector<Vec3> tangent(n), bitangent(n);
size_t corners = indices.empty() ? n : indices.size();
for (size_t t = 0; t + 2 < corners; t += 3) {
std::uint32_t i0 = indices.empty() ? static_cast<std::uint32_t>(t) : indices[t];
std::uint32_t i1 = indices.empty() ? static_cast<std::uint32_t>(t + 1) : indices[t + 1];
std::uint32_t i2 = indices.empty() ? static_cast<std::uint32_t>(t + 2) : indices[t + 2];
const ModelVertex &a = vertices[i0], &b = vertices[i1], &c = vertices[i2];
Vec3 e1 = b.position - a.position, e2 = c.position - a.position;
Vec2 d1 = b.uv - a.uv, d2 = c.uv - a.uv;
// e1 = d1.x T + d1.y B、e2 = d2.x T + d2.y B を T(∂P/∂u)と B(∂P/∂v)について解く(2×2の逆行列)
// Solve e1 = d1.x T + d1.y B, e2 = d2.x T + d2.y B for T (∂P/∂u) and B (∂P/∂v) (a 2 × 2 inverse)
float det = d1.x * d2.y - d2.x * d1.y;
if (std::fabs(det) < 1e-12f) continue; // UVが潰れた三角形 / a triangle with degenerate UVs
float r = 1.0f / det;
Vec3 tu = r * (d2.y * e1 - d1.y * e2);
Vec3 bv = r * (d1.x * e2 - d2.x * e1);
// 正規化せずに足す:テクスチャを大きく引き伸ばす三角形ほど重みが大きい / summed unnormalized: triangles that
// stretch the texture more weigh more
for (std::uint32_t i : {i0, i1, i2}) {
tangent[i] = tangent[i] + tu;
bitangent[i] = bitangent[i] + bv;
}
}
インデックスはglDrawArraysとglDrawElementsの様に省略出来ます。
無ければ頂点3つずつが三角形です。
detが0に近い時に飛ばすのは、UVが直線に潰れた三角形の為です。
UV球の極や、単色の為に1テクセルだけを使うモデルの部分で起こります。
(24行目のコメントの通り、重みが大きいのは単に大きい三角形ではなく、テクスチャを余計に伸ばす三角形です。は三角形の大きさでは変わらないからです。)
後半で全ての頂点を仕上げます:
for (size_t i = 0; i < n; ++i) {
Vec3 nrm = vertices[i].normal;
// グラム・シュミット:法線の成分を引いて垂直にする / Gram-Schmidt: remove the normal component
Vec3 t = tangent[i] - dot(nrm, tangent[i]) * nrm;
if (dot(t, t) < 1e-12f) {
// UVがない・潰れている:法線に垂直なら何でも良い / no usable UVs: any direction perpendicular to the normal
t = cross(std::fabs(nrm.y) < 0.99f ? Vec3{0.0f, 1.0f, 0.0f} : Vec3{1.0f, 0.0f, 0.0f}, nrm);
}
t = normalize(t);
// 画像の「上」:OpenGLの決まりでは+v、glTFでは-v / the image's "up": +v in the OpenGL convention, -v in glTF
Vec3 up = convention == UvConvention::OpenGl ? bitangent[i] : -bitangent[i];
float w = dot(cross(nrm, t), up) < 0.0f ? -1.0f : 1.0f; // 鏡像のUVなら-1 / -1 for mirrored UVs
vertices[i].tangent = {t.x, t.y, t.z, w};
}
}
2つの場合に一言要ります。
合計が法線と(殆ど)平行か、頂点の三角形が全部飛ばされて0なら、グラム・シュミットの後には何も残りません。
其の時コードは法線に垂直な向きを何か1つ選びます。
との外積、法線自身が殆ど垂直ならとの外積です。
其処で法線マップが正しくなる事はありませんが、少なくともベクトルは有効で、ライティングは壊れません。
もう1つは最後の3行、ハンドネスで、此れには節を1つ使います。
22.4 ハンドネス:wの成分
、、がいつも右手系の基底になるとは限りません。
アーティストは良くUVを鏡像にします。
テクスチャの場所を節約する為に、顔の左右や樽の両側でテクスチャの同じ半分を使い、片方を裏返すのです。
鏡像の部分ではが逆に進むのでは逆を向きますが、(画像の上)とは変わりません:
が手前を向いている時、はなら上、なら下を向きます(線型代数 第5章の右手の法則)。
左では其れが本当の従法線で、右では丁度逆です。
が其の補正を持ちます:
そしてシェーダーのは、いつも画像の上を向きます。
其れがtangents.ccの42行目です。
計算例です。
床の三角形のUVを鏡像にする為、bとcのを入れ替えて、bを、cをにします。
するとで、式から、になります。
は向きを変え、は変わりません。
でとなり、との内積はなのでです。
鏡像でない方では、内積はでです。
何故其の物を保存しないのでしょうか?
頂点毎にfloatを3つ余計に使えば出来ます。
符号だけで足りるのは、(グラム・シュミットの後は)はどうせにもにも垂直なので、分からないのはに沿った向きだけだからです。
22.5 2つのUVの決まり
tangents.ccの41行目が「画像の上」が何かを決めます。
此処でOpenGLとglTFは意見が違います。
あたし達の形はOpenGLの決まりを使います。
第6章からTexture2D::loadは画像を読む時に反転するので、画像の一番下の行が、一番上の行がです。
makeCube等も、全ての面の上にを置きます。
画像の上の向きには増えるので、上はです。
glTFはを画像の左上の角に置き、は下へ増えます。
そして第14章から、glTFの画像は決して反転しません。
すると画像の上はが減る向き、です。
法線マップ自体はどちらも同じです。
glTFも、法線マップの(緑)は「画像の上」を意味するOpenGL流だと決めています。
そしてglTFのTANGENT.wは、式と緑チャンネルを通して、画像の上に対して決められています。
従って違うのは比べる「上」の符号だけで、UvConventionが変えるのも其れだけです。
(が増える向き)はどちらでも同じです。
間違えるとモデルの全てのが反転し、緑チャンネルを間違えた法線マップと全く同じに見えます。
下から照らされた凹凸です。
22.6 あたし達の形の接線
shapes.ccは今迄Vertex3D(位置、法線、UV)を作っていました。
今は全ての形がModelVertexを作り、UvConvention::OpenGlでcomputeTangentsを呼び、kModelVertexLayoutを使うので、形とglTFのモデルは1つの頂点の形式を共有します。
Vertex3Dと其のレイアウトはmesh.hhに残っていますが、もう何も使っていません。
makeSphereでは関数の最後の2行です:
computeTangents(vertices, indices, UvConvention::OpenGl);
return Mesh(vertices, indices, kModelVertexLayout);
makeCube、makePlane、makeCrossedQuadsも同じ様に終わり、頂点には接線の為の4つ目の空の初期化子({})が付きました。
レンガの壁にはもう1つ要る物があります。
テクスチャが伸びない箱です。
makeCubeは全ての面に0〜1を貼るので、5 m × 2.5 mの壁では、5 m × 2.5 mのレンガの1枚になってしまいます。
新しいmakeBoxは全ての面にメートル単位のUVを付けます:
// 原点を中心とした大きさsizeの箱。UVはメートル単位でtileSizeごとに繰り返す(伸びない:壁、柱、段に。第22章)
// A box of the given size centred on the origin. UVs are in metres, repeating every tileSize (no stretching: for walls,
// pillars, steps; chapter 22)
Mesh makeBox(Vec3 size, float tileSize = 1.0f);
addFaceには箱の大きさの半分とタイルの大きさという2つの引数が増えました:
// 一つの面(正方形)を足す。normal = 外向き、right × up = normal になるように選ぶ。
// Adds one face (a square). normal points outwards; choose right and up so that right × up = normal.
static void addFace(std::vector<ModelVertex> &vertices, std::vector<std::uint32_t> &indices, Vec3 normal, Vec3 right,
Vec3 up, Vec3 half = {0.5f, 0.5f, 0.5f}, float tile = 0.0f) {
std::uint32_t first = static_cast<std::uint32_t>(vertices.size());
auto extent = [&](Vec3 axis) { return std::fabs(axis.x) * half.x + std::fabs(axis.y) * half.y + std::fabs(axis.z) * half.z; };
Vec3 c = extent(normal) * normal; // 面の中心 / centre of the face
Vec3 r = extent(right) * right, u = extent(up) * up;
// tile > 0:UVはメートル÷tile(面の大きさに合わせて繰り返す)、0:面ごとに0〜1 / tile > 0: UV = metres ÷ tile
// (repeats with the face size); 0: 0..1 per face
float su = tile > 0.0f ? 2.0f * extent(right) / tile : 1.0f, sv = tile > 0.0f ? 2.0f * extent(up) / tile : 1.0f;
vertices.push_back({c - r - u, normal, {0.0f, 0.0f}, {}}); // 左下 / bottom left
vertices.push_back({c + r - u, normal, {su, 0.0f}, {}}); // 右下 / bottom right
vertices.push_back({c + r + u, normal, {su, sv}, {}}); // 右上 / top right
vertices.push_back({c - r + u, normal, {0.0f, sv}, {}}); // 左上 / top left
// 反時計回りの三角形2つ / two counter-clockwise triangles
indices.insert(indices.end(), {first, first + 1, first + 2, first + 2, first + 3, first});
}
extent(axis)は、面の軸の1つに沿った箱の大きさの半分です。
壁の前の面ではrightがでextent(right)は2.5、upがでextent(up)は1.25です。
tile = 1なら、UVは横に0〜5、上に0〜2.5で、タイル5枚 × 2枚半です。
タイル1枚に4個ずつのレンガが8段あるので、20段 × 20個のレンガになります。
tile = 0は今迄通り面毎に0〜1で、makeCubeは其れを渡します。
Mesh makeBox(Vec3 size, float tileSize) {
std::vector<ModelVertex> vertices;
std::vector<std::uint32_t> indices;
Vec3 h = 0.5f * size;
addFace(vertices, indices, {0, 0, 1}, {1, 0, 0}, {0, 1, 0}, h, tileSize);
addFace(vertices, indices, {0, 0, -1}, {-1, 0, 0}, {0, 1, 0}, h, tileSize);
addFace(vertices, indices, {1, 0, 0}, {0, 0, -1}, {0, 1, 0}, h, tileSize);
addFace(vertices, indices, {-1, 0, 0}, {0, 0, 1}, {0, 1, 0}, h, tileSize);
addFace(vertices, indices, {0, 1, 0}, {1, 0, 0}, {0, 0, -1}, h, tileSize);
addFace(vertices, indices, {0, -1, 0}, {1, 0, 0}, {0, 0, 1}, h, tileSize);
computeTangents(vertices, indices, UvConvention::OpenGl);
return Mesh(vertices, indices, kModelVertexLayout);
}
全ての面はright × up = normalになる様に選んであり(addFaceの上のコメント)、はrightに、はupに沿って増えるので、6つの面は全て right、 up、です。
computeTangentsは丁度其れを見付けるので、箱は最初の確認に向いています。
表示モード7では、壁の前の面はの色、ピンクのでなければなりません。
22.7 glTFのモデルの接線
model.ccでは、loadPrimitiveが、接線が必要なのに無い時に計算します:
// 法線マップがあるのにTANGENTがなければ自分で計算する(glTFの仕様はMikkTSpaceを勧めるが、ここでは簡単な方法、第22章)
// A normal map but no TANGENT: compute them ourselves (the glTF spec recommends MikkTSpace; we use the simple
// method, chapter 22)
bool normalMapped = p.material >= 0 && static_cast<size_t>(p.material) < g.materials.size() &&
g.materials[static_cast<size_t>(p.material)].normalTexture.index >= 0;
if (normalMapped && !tangents && uvs && p.mode == kGltfTriangles)
computeTangents(vertices, indices, UvConvention::Gltf);
条件は4つで、其々に理由があります:
- 法線マップがある。 無ければ接線は読まれないので、計算する(又は無いと文句を言う)理由がありません。
TANGENTが無い。 ファイルの接線がいつも優先です。普通は法線マップをベイクしたのと同じ道具が作った物で、ベイクを完全に正しく出来るのは其れだけです。- UVがある。
TEXCOORD_0が無ければ、辿るがありません。 - 三角形である。
computeTangentsはGL_TRIANGLESしか知りません。ストリップとファンは先に展開する必要があります。
第14章の平らな法線のコードの後で実行されるので、法線の無いプリミティブは先にインデックスを外した角張った頂点になり、其の頂点の接線が作られます。
そしてUVがglTFのファイルから来るので、UvConvention::Gltfを使います。
其れから、プリミティブを描く時に、drawItemsがglTFの法線テクスチャをBlinn-Phongのマテリアルに渡します:
if (white) {
Material m = md.phong;
m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture
m.emissionMap = texture(md.pbr.emissiveTexture.index);
m.normalMap = texture(md.pbr.normalTexture.index); // 第22章 / chapter 22
m.normalScale = md.pbr.normalTexture.scale;
m.apply(shader, *white);
}
normalTexture.scaleはglTFの凹凸の強さで、法線マップの戻したとに掛かります。
其れが何処に行くかは次の節で見ます。
第21章から、glTFが法線マップとして使うテクスチャは全てsRGBではなくリニアなデータとしてアップロードされています。
樽
此れを本物のアセットで試す為に、assets/models/barrel.glbをあたしは作った、PBRの完全な樽にしました。
高さ0.9 m、半径は両端で0.30 m、真ん中で0.34 mの膨らんだ円柱に、16枚の側板、鋲の付いた3本の鉄の箍、そしてベースカラー、金属と粗さ、法線マップ、遮蔽マップの4つのテクスチャがあります。
プリミティブは2つです。
胴(頂点429個、三角形768枚)にはTANGENTの属性があります。
上の蓋(頂点34個、三角形32枚)には板の継ぎ目の法線マップがありますが、TANGENTはありません。
わざとそうして、毎回の実行でcomputeTangents(…, UvConvention::Gltf)が使われる様にしてあります。
第13章のgltf_dumpで違いが見えます:
#0 TRIANGLES, material 0 "BarrelWood", 2304 indices (UNSIGNED_SHORT)
POSITION VEC3 FLOAT x 429 view 7 +0
NORMAL VEC3 FLOAT x 429 view 8 +0
TEXCOORD_0 VEC2 FLOAT x 429 view 9 +0
TANGENT VEC4 FLOAT x 429 view 10 +0
#1 TRIANGLES, material 1 "BarrelLid", 96 indices (UNSIGNED_BYTE)
POSITION VEC3 FLOAT x 34 view 12 +0
NORMAL VEC3 FLOAT x 34 view 13 +0
TEXCOORD_0 VEC2 FLOAT x 34 view 14 +0
メインのプログラムは他のモデルと同じ様に読み込み、3つ描きます:
// 樽:色・金属と粗さ・法線・遮蔽のテクスチャ付き。蓋にはTANGENTがない(Modelが計算する)
// The barrel: colour, metallic-roughness, normal and occlusion textures. The lid has no TANGENT (Model computes it)
std::optional<Model> barrel = Model::load("assets/models/barrel.glb");
if (!scene || !crate || !barrel) return 1;
側板、溝、鋲には形が全く無いので、凹凸の違いはレンガより樽の方が大きいです:
箍はまだ鉄ではなく灰色のプラスチックの様に見えます。
第14章のPBRからBlinn-Phongへの変換が、金属と粗さのテクスチャを樽全体で平均するからです。
其れは第24章で正しく直します。
22.8 頂点シェーダー
phong.vertの全体です。
新しいのはaTangentの入力、vTangentの出力、mainの2行です:
#version 460 core
layout(location = 0) in vec3 aPosition;
layout(location = 1) in vec3 aNormal; // 面の向き(モデル座標) / which way the surface faces (model space)
layout(location = 2) in vec2 aUv;
// 接線(第22章):xyz = uが増える向き、w = 従法線の向き(±1)。(0,0,0,0) = なし
// Tangent (chapter 22): xyz = the direction in which u grows, w = the bitangent's sign (±1). (0,0,0,0) = none
layout(location = 3) in vec4 aTangent;
// カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
// The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
layout(std140, binding = 0) uniform Camera {
mat4 uView;
mat4 uProj;
vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
float uTime; // アニメーションの時間(秒) / animation time (seconds)
};
uniform mat4 uModel;
uniform mat3 uNormalMatrix; // 法線をワールド座標へ(モデル行列の逆行列の転置) / normals to world space (inverse transpose of uModel)
// ライティングはワールド座標で計算する / lighting is computed in world space
out vec3 vWorldPos;
out vec3 vNormal;
out vec2 vUv;
out vec4 vTangent; // ワールド座標の接線と向き / world-space tangent and sign
// インスタンスごとの色(第19章)。インスタンシングでないときはこのユニフォーム(既定値は白)
// The per-instance colour (chapter 19). Without instancing it comes from this uniform (white by default)
uniform vec3 uTint = vec3(1.0);
out vec3 vTint;
void main() {
vec4 world = uModel * vec4(aPosition, 1.0);
vWorldPos = world.xyz;
vNormal = uNormalMatrix * aNormal; // 正規化はフラグメントシェーダーで / normalized in the fragment shader
vUv = aUv;
// 接線は面に沿う向きなので、法線行列ではなくモデル行列で変換する。鏡像(行列式が負)なら従法線も反転
// A tangent lies along the surface, so it is transformed with the model matrix, not the normal matrix. A mirroring
// matrix (negative determinant) flips the bitangent too
mat3 m = mat3(uModel);
vTangent = vec4(m * aTangent.xyz, aTangent.w * (determinant(m) < 0.0 ? -1.0 : 1.0));
vTint = uTint;
gl_Position = uProj * uView * world;
}
何故法線行列ではなくモデル行列なのか
第10章では法線を法線行列で変換しました。
一様でない拡大縮小では、モデル行列が法線を垂直から曲げてしまうからです。
接線は別の種類のベクトルです。
表面の中にあり、表面上の2点を結ぶ短い辺の様な物です。
辺は位置と全く同じ様に(平行移動を除いて)変換されるので、接線はモデル行列其の物の3 × 3の部分mat3(uModel)を使います:
数字で見ます。
、、なら、接線はになり、伸びた表面に沿ったままです。
は間違いで、です。
は正しく、です。
此れは偶然ではありません。
どんなとでもなので、垂直に始まった接線と法線は、其々が自分の行列を使えば垂直のままです。
どちらの結果も長さは1ではなく、フラグメントシェーダーが両方を正規化します。
何故行列式なのか
行列式が負のモデル行列は鏡映します(例えばscale({-1, 1, 1})、線型代数 第10章)。
形を鏡映すると其の上のテクスチャも鏡映されるので、鏡像のUVと同じ状況です。
ワールド座標では向きを変え、(法線行列を使う)は変わらず、は画像の下を向きます。
其の為シェーダーはdeterminant(m) < 0.0の時にを反転します。
determinantはmat2、mat3、mat4用のGLSLの組み込み関数です。
mat3では列の三重積で、掛け算9回です。
あたし達の物は何も鏡映されていませんが、小物を鏡映出来るレベルエディターならすぐに此れに当たります(課題3)。
インスタンシング版
第19章のphong_instanced.vertにも同じ2行が入ります。
modelは公転、インスタンスの行列、ノードの行列の積で、接線は其の全部を使います:
void main() {
// 公転:内側ほど速い(ケプラーの法則:角速度 ∝ 半径^-1.5)。C++のorbitAngle()と同じ式
// Orbit: inner rocks are faster (Kepler: angular speed ∝ radius^-1.5). The same formula as orbitAngle() in C++
float radius = length(aInstanceModel[3].xz);
mat4 orbit = rotationY(uTime * uOrbitSpeed * pow(8.0 / radius, 1.5));
mat4 model = orbit * aInstanceModel * uModel;
vec4 world = model * vec4(aPosition, 1.0);
vWorldPos = world.xyz;
// 岩の拡大縮小は一様なので、法線は行列の3×3で回すだけで良い(長さはphong.fragで正規化)
// The rocks are scaled uniformly, so the normal can simply be rotated by the 3×3 part (phong.frag normalizes it)
vNormal = mat3(orbit * aInstanceModel) * (uNormalMatrix * aNormal);
vUv = aUv;
mat3 m = mat3(model);
vTangent = vec4(m * aTangent.xyz, aTangent.w * (determinant(m) < 0.0 ? -1.0 : 1.0));
vTint = aInstanceColor;
gl_Position = uProj * uView * world;
}
法線はまだインスタンスの行列の3 × 3の部分で回すだけです。
第19章で言った通り、岩が一様に拡大縮小されているから正しいのです。
此の章ではインスタンシングで何も描きませんが、phong.fragがvTangentを読む様になったので、組み合わせる全ての頂点シェーダーが其れを書かなければなりません。
第19章のvTintと全く同じです。
フラグメントシェーダーが読む出力を宣言し忘れた頂点シェーダーは、リンクの時にvTangentについてのメッセージで失敗します。
(此れは大丈夫です。此の章を書く間に一時的にphong.fragと一緒に読み込み、コンパイルとリンクが通る事を確かめました。)
22.9 マテリアル:ユニット4、フラグ無し
法線マップはMaterialのテクスチャが1つ増えただけです:
// 法線マップ(第22章):接線空間の法線(RGB、リニア)。Aは視差マッピング用の高さ(1 = 一番高い)
// Normal map (chapter 22): tangent-space normals (RGB, linear). A = height for parallax mapping (1 = highest)
const Texture2D *normalMap = nullptr; // テクスチャユニット4 / texture unit 4
float normalScale = 1.0f; // 凹凸の強さ(glTFのnormalTexture.scale:xyに掛ける) / bump strength (glTF's
// normalTexture.scale: multiplies x and y)
float parallaxScale = 0.0f; // 視差の深さ(UVの単位、0 = なし)。OpenGLのUV(vが上)の物だけ / parallax depth (in UV
// units, 0 = none). Only for OpenGL-convention UVs (v up)
そしてapplyが其れを、第18章の表から法線マップ用に取ってあるテクスチャユニット4に繋ぎます:
(diffuseMap ? diffuseMap : &white)->bind(0);
(specularMap ? specularMap : &white)->bind(1);
(emissionMap ? emissionMap : &white)->bind(2);
shader.set("uMaterial.normalScale", normalMap ? normalScale : 0.0f);
shader.set("uMaterial.parallaxScale", normalMap ? parallaxScale : 0.0f);
(normalMap ? normalMap : &white)->bind(4);
第11章で、無いマップの代わりに1 × 1の白いテクスチャを繋ぐ事に決めたので、シェーダーには「拡散マップがある」というフラグが要りません。
白を掛けても何も変わらないからです。
法線マップでは、白はで、戻すと平らなではなくになります。
仕掛けは強さです。
法線マップが無い時、applyはnormalScale = 0を送り、シェーダーはとに其れを掛けます。
とを0にした白は、丁度表面の法線です。
シェーダーは強さが0なら読む事自体を飛ばす(22.10節)ので、実際には白いテクスチャが法線として読まれる事はありません。
其れでも繋ぐのは、ユニット4に他の物の法線マップが残らない様にする為です。
parallaxScaleも同じで、高さは法線マップのアルファにあるので、法線マップが無ければ0です。
normalScaleはglTFのnormalTexture.scaleです。
1は「ベイクした通り」、2は傾きを倍に、0.5は半分にします。
とだけに掛けて後で正規化するのはglTFの仕様の定義で、どんな強さでも法線が表面の外を向いたままになります。
22.10 フラグメントシェーダー:TBN
phong.fragは、新しい入力、マテリアルの新しい2つのメンバー、ユニット4のサンプラー、MとXのキーの為のデバッグ用の2つのスイッチを宣言します:
in vec4 vTangent; // ワールド座標の接線、w = 従法線の向き(第22章) / world-space tangent, w = bitangent sign (chapter 22)
float normalScale; // 法線マップの強さ(0 = マップなし、第22章) / normal map strength (0 = no map, chapter 22)
float parallaxScale; // 視差マッピングの深さ(UV単位、0 = なし) / parallax depth (UV units, 0 = none)
// 法線マップ(第22章):RGB = 接線空間の法線、A = 高さ(視差マッピング用)。ユニット4
// Normal map (chapter 22): RGB = tangent-space normal, A = height (for parallax mapping). Unit 4
layout(binding = 4) uniform sampler2D uNormalMap;
uniform bool uNormalMapping = true; // 法線マップを使う(デバッグ用に切れる) / use normal maps (can be turned off for debugging)
uniform bool uParallaxMapping = true; // 視差マッピングを使う / use parallax mapping
uniform bool … = trueは第19章のユニフォームの初期化子です。
C++側が設定しないプログラムでは、法線マッピングも視差マッピングもオンです。
mainの初めで基底を作ります:
void main() {
// 接線空間(TBN):補間で直交が崩れるので、法線に対してもう一度グラム・シュミット(第22章)
// Tangent space (TBN): interpolation breaks the orthogonality, so Gram-Schmidt against the normal again (chapter 22)
vec3 geometricNormal = normalize(vNormal);
vec3 tangent = vTangent.xyz - dot(vTangent.xyz, geometricNormal) * geometricNormal;
bool hasTangent = dot(tangent, tangent) > 1e-10; // 接線がない頂点は(0,0,0,0) / vertices without tangents have (0,0,0,0)
tangent = hasTangent ? normalize(tangent) : vec3(1.0, 0.0, 0.0);
vec3 bitangent = cross(geometricNormal, tangent) * (vTangent.w < 0.0 ? -1.0 : 1.0);
// 両面のマテリアルを裏から見ているなら、法線は裏を向く(接線と従法線はそのまま)
// Seen from behind, a double-sided surface's normal points the other way (tangent and bitangent stay)
if (uMaterial.doubleSided && !gl_FrontFacing) geometricNormal = -geometricNormal;
もう一度グラム・シュミット
computeTangentsは既に全ての頂点の接線を法線に垂直にしたのに、何故もう一度するのでしょうか?
ラスタライザーはvNormalとvTangentを、成分毎に別々に補間するからです。
法線の違う2つの頂点の間では、補間された法線は一方へ、補間された接線は別の方へ回り、真ん中ではもう垂直ではありません(長さも1ではありません)。
わざと大げさにした例です。
補間された法線が、補間された接線がだとします。
此の接線の長さは1()なので正規化しても変わりませんが、表面から36.9°浮き上がっています。
に36.9°傾いた法線マップのテクセルを取ります。
グラム・シュミット無しではで、正規化すると、傾きは22.5°しかありません。
しかもは長さ1ですらありません。
グラム・シュミット有りでは、正規化してで、結果は、ちゃんと36.9°です。
本物のメッシュでは誤差は数度で、曲面の片側でもう片側より凹凸が少し弱く見えるという形で出ます。
たった2行なので、必ずやって下さい。
基底の残り
hasTangentは接線の無い頂点を見付けます。
法線マップの無いglTFのプリミティブは(0, 0, 0, 0)のままで、0の補間は0です。
VAOにlocation 3の属性が全く無ければ、シェーダーは既定の汎用の値を読みますが、此れもxyzは0です。
接線が無ければ作る物も無いので、法線マップと視差は飛ばされ、接線と従法線の表示は黒になります。
従法線はにwの符号を掛けた物です。
vTangent.w其の物やsign(…)ではなくvTangent.w < 0.0 ? -1.0 : 1.0を使います。
wは全ての頂点でですが、鏡像の三角形とそうでない三角形が辺を共有する所では、補間された値は間の何にでもなり得て、signは丁度0では0を返すからです。
(接線を書き出す道具は符号が変わる所で頂点を分けるので、1つの三角形の中でwは変わりません。比較は其れを安全に読む方法です。)
両面のマテリアル(第16章)は、裏面では幾何学的な法線だけを反転し、接線と従法線は其のままです。
法線マップの付いた薄い両面の表面では、此れで凹凸が両側に飛び出します。
glTFのサンプルビューアーは代わりに3つ全部を反転し、表の出っ張りは裏から見ると凹みになります。
あたし達の両面のマテリアル(葉、ガラス、帆)には法線マップが無いので、此のシーンでは違いは見えません。
法線マップを使う
もっと下、アルファの判定の後で、表面の法線を置き換えます:
Surface s;
s.position = vWorldPos;
s.normal = geometricNormal;
// 法線マップ:接線空間の法線(x, y, z)を、ワールド座標の x·T + y·B + z·N に直す。強さはxyに掛ける(glTFと同じ)
// Normal map: turn the tangent-space normal (x, y, z) into world space as x·T + y·B + z·N. The strength scales xy
// (as in glTF)
if (uNormalMapping && hasTangent && uMaterial.normalScale > 0.0) {
vec3 m = textureGrad(uNormalMap, uv, uvDx, uvDy).xyz * 2.0 - 1.0; // 0..1 → -1..1
m.xy *= uMaterial.normalScale;
s.normal = normalize(m.x * tangent + m.y * bitangent + m.z * geometricNormal);
}
22.2節の式にglTFの強さを足した物です。
mat3(T, B, N)を作らない事に気を付けて下さい。
線型結合を書き下すのと同じ事で(行列とベクトルの積は列の線型結合です)、式が言っている事其の物です。
読み込みにはずらしたuvでtextureGradを使います。
どちらも22.12節の視差マッピングで説明します。
此処から後の全て、光、鏡面反射、第18章の空の映り込みはs.normalを使うので、凹凸が其のまま付きます。
デバッグ表示
Vは9つのモードを巡る様になり、其の内3つが新しい物です:
static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission",
"normals", "vertex normals", "tangents", "bitangents"};
constexpr int kViewModes = 9;
constexpr int kFirstVectorView = 5; // ここからはベクトルを色で見せる / from here on, vectors are shown as colours
if (uViewMode == 1) color = ambient;
else if (uViewMode == 2) color = diffuse;
else if (uViewMode == 3) color = specular;
else if (uViewMode == 4) color = emission;
else if (uViewMode == 5) color = s.normal * 0.5 + 0.5;
else if (uViewMode == 6) color = geometricNormal * 0.5 + 0.5;
else if (uViewMode == 7) color = hasTangent ? tangent * 0.5 + 0.5 : vec3(0.0);
else if (uViewMode == 8) color = hasTangent ? bitangent * 0.5 + 0.5 : vec3(0.0);
// ベクトルの表示は、post.fragがsRGBにした後でちょうどこの値になるように、先にリニアへ戻しておく
// Vector views: convert to linear first, so that after post.frag's sRGB encoding the screen shows exactly this value
if (uViewMode >= 5)
color = mix(color / 12.92, pow((color + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), color));
モード5は法線マップ後の法線、モード6は其の前の法線、モード7と8は接線と従法線で、全てとして表示します。
第21章が作った落とし穴があります。
シーンはpost.fragで露出、ACESのトーンマッピング、リニアからsRGBへの変換を通るので、色0.5として書いた法線は画面では0.8位になってしまいます。
デバッグ表示は生のベクトルを見せるべきなので、main.ccは此れらのモードで露出1とクランプのトーンマッパーを設定します:
// ベクトルの表示(法線・接線)は値をそのまま見せる:トーンマッピングなし、露出1(phong.fragが逆変換して出す)
// The vector views (normals, tangents) show the raw values: no tone mapping, exposure 1 (phong.frag outputs them
// pre-decoded)
if (viewMode >= kFirstVectorView) {
postSettings.exposure = 1.0f;
postSettings.toneMapper = static_cast<int>(ToneMapper::Clamp);
} else {
postSettings.toneMapper = static_cast<int>(ToneMapper::Aces);
}
postUbo.update(postSettings);
そしてphong.fragは、書く前に色をsRGBのデコードの曲線(post.fragが最後にする事の逆)に通します。
post.fragのエンコードの後、画面には又丁度が出ます。
mix(…, step(…))の形は、第21章の区分的なsRGBの曲線をif無しで書いた物です。
step(0.04045, c)はしきい値未満で0、以上で1で、mixがチャンネル毎にリニアの部分か累乗の部分を選びます。
GLSL 第12章の表で色を読みます。
壁の接線は、のピンクで、従法線は、の緑です。
床(makePlane)はがへ増えるので、従法線は、のオリーブ色です。
樽の胴の従法線は樽の上を向いているので、glTFのTANGENT.wとあたし達の読み方は合っています。
computeTangentsが接線を作った蓋も、滑らかで揃った接線を見せています。
法線マッピングがおかしく見える時、此れが一番役に立つ確認です。
モード7と8を見て、とが画像の右と上があるべき方を向いているか確かめて下さい。
22.11 レンガのテクスチャ
まず高さ
レンガの法線マップを直接描くのではなく、まず高さ場を作り、全てを其処から導きます。
タイル1枚は1 m × 1 mで、4個ずつのレンガ(1個25 cm × 12.5 cm)が8段あり、1段置きに半個ずれています。
高さはレンガの面で1、レンガの縁の面取りで下がり、目地では約0.2です。
ノイズで細かいざらつきと小さな穴を付けます。
512 × 512テクセルなので、1テクセルは1000 mm / 512 ≈ 1.95 mmです。
高さ場から法線へ
曲面の法線は、正規化したです。
右へ高さが上がる所では、法線は左へ傾きます。
スクリプトは隣の2つのテクセルの中心差分で微分を近似し、強さを掛けます:
は画像の上へ数え(OpenGLの「緑が上」)、です。
端では隣が反対側に回り込むので、タイルは継ぎ目が無く、GL_REPEATでもタイルの間に境目が見えません。
GLSL 第12章のCのコードと同じ方法で、違うのは結果の使い方です。
4つのチャンネル、2つの意味
bricks_normal.pngはRGBAの画像です:
- RGB = 法線、。
- A = 高さ其の物、視差マッピング用(22.12節)。レンガの面で1、目地で約0.2。
高さを法線マップのアルファに詰めるとテクスチャと読み込みが1つ減り、良くある配置です。
色の画像は別のbricks.pngで、同じレンガにレンガ毎の色の違いと灰色の目地があります。
どちらもmain.ccで読み込みます:
// レンガ:色はsRGB、法線マップはデータなのでリニア(Aは高さ) / bricks: the colour is sRGB, the normal map is data and
// stays linear (A = height)
std::optional<Texture2D> brickTexture = Texture2D::load("assets/textures/bricks.png", {.srgb = true});
std::optional<Texture2D> brickNormal = Texture2D::load("assets/textures/bricks_normal.png");
色の画像は、第21章からの全ての色の画像と同じくsRGBです。
法線マップはデータなので、リニアのままです。
既定のTextureOptions(反転有り、ミップマップ有り、sRGB無し)のTexture2D::loadです。
間違えると何が起きるかは22.14節で見せます。
法線マップのミップマップは隣の法線を平均するので1より短くなりますが、TBNの後のシェーダーのnormalizeが面倒を見ます。
マテリアルと3つのレンガの物:
// レンガの壁(5 × 2.5 m、厚さ0.3 m)、柱、球。箱のUVはメートル単位で、1 mごとにテクスチャ1枚
// 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
Mesh wallMesh = makeBox({5.0f, 2.5f, 0.3f});
Mesh pillarMesh = makeBox({0.6f, 3.0f, 0.6f});
Mesh brickSphere = makeSphere(48, 24);
Material brickMaterial;
brickMaterial.diffuseMap = &*brickTexture;
brickMaterial.normalMap = &*brickNormal;
brickMaterial.specular = {0.08f, 0.08f, 0.08f};
brickMaterial.shininess = 24.0f;
brickMaterial.parallaxScale = 0.04f; // 1枚(1 m)の4% = 4 cm の深さ / 4 % of a tile (1 m) = 4 cm deep
struct Piece {
const Mesh *mesh;
Mat4 model;
};
const Piece bricks[] = {
{&wallMesh, translate({-1.6f, 1.25f, 4.2f})},
{&pillarMesh, translate({1.6f, 1.5f, 4.4f}) * rotateY(0.3f)},
{&brickSphere, translate({-2.3f, 0.6f, 6.9f}) * scale({1.2f, 1.2f, 1.2f})},
};
壁と柱はメートル単位のUVのmakeBoxなので、レンガはどちらでも同じ大きさです。
球はmakeSphereの0〜1のUVで、周り全体の mにタイル1枚なので、レンガの幅は4倍近くあります。
球は見た目ではなく接線の為にあります。
継ぎ目と極は、接線の生成が大抵間違える所だからです。
極では全ての三角形が1点に集まってUVが潰れるので、computeTangentsは其処で代わりの向きを使い、極の真上では陰影に小さな乱れが出るのは仕方ありません。
マテリアルを適用すれば、描くのはいつものループです:
// レンガ(法線マップ+視差) / the bricks (normal map + parallax)
brickMaterial.apply(*phong, white);
for (const Piece &b : bricks) {
phong->set("uModel", b.model);
phong->set("uNormalMatrix", normalMatrix(b.model));
b.mesh->draw();
}
for (const Placement &b : barrels) barrel->draw(*phong, translate(b.position) * rotateY(b.angle), white, ModelPass::Opaque);
夜、回る光と提灯だけの時に、法線マップでどれだけ違うかです:
回る光
法線マップは光が表面をかすめる時に一番良く見えるので、シーンには壁の前を動く光があります:
const Vec3 kMovingLightColor = {1.0f, 0.75f, 0.45f};
Vec3 movingLightPos;
// 壁の前を回る光:壁すれすれの角度から照らすと凹凸がよく見える / the light circling in front of the wall: light from
// grazing angles shows the bumps best
movingLightPos = {-1.6f + 1.8f * std::cos(0.7f * windmillTime), 1.3f + 0.6f * std::sin(1.3f * windmillTime), 4.75f};
if (movingLight)
lights.points.push_back({.position = movingLightPos, .color = 2.5f * kMovingLightColor, .attenuation = kMediumRange});
壁の前の面はにあるので、光は其の0.4 m前の平面で、〜、〜の間を動きます。
第12章の中距離の普通の点光源で、色はです(第21章のお陰で使えるHDRの値です)。
目印は其の色の8倍の小さなunlitの球なので、ブルームで光ります。
光は風車の時計を使うのでPで両方止まり、Lで消えます。
22.12 視差オクルージョンマッピング
法線マッピングに出来ない事
壁を横から見て下さい。
ライティングは目地が沈んでいると言っているのに、レンガは後ろの目地を少しも隠さず、目地は描かれた絵の様に真っ直ぐです。
テクスチャ座標がまだ平らな表面の物だからです。
レンガは3Dのレンガの様に照らされていますが、2Dの絵の様に置かれています。
視差マッピングは置き方を直します。
高さマップを使ってピクセル毎のテクスチャ座標を、目が本当に凸凹の表面を見る所へずらすので、レンガが飛び出して後ろの目地を隠す様に見えます。
考え方
高さ場が平らな表面の下に吊り下がっていると考えて下さい。
表面で深さ0、底で深さ1、全てのテクセルは深さにあります。
目からの光線はピクセルのuvで平らな表面に入り、奥へ進みます。
最初に高さ場に当たる所が目が本当に見る点で、其のuvを全てのテクスチャに使うべきです。
GLSL 第12章の課題の簡単な視差マッピングは、光線の上で1回だけ推測します。
視差オクルージョンマッピング(POM)は層に分けて光線の上を進みます:
テクスチャ空間で進むには、接線空間の視線の向きが要ります。
TBNの逆で、正規直交の基底なら其れは転置(線型代数 第11章)なので、3つの座標は只の内積です:
は表面から目への向きです。
光線に沿って深さ1単位下りると、に、に、と逆向きに動きます(光線は目から遠ざかるからです)。
高さマップの深さ全体はUV単位でparallaxScaleなので、層が枚なら1層でUVは次だけ動きます:
コード
vec2 parallaxOcclusion(vec2 uv, vec3 v, vec2 dx, vec2 dy) {
float layers = mix(32.0, 8.0, clamp(v.z, 0.0, 1.0)); // 斜めほど多く / more layers at grazing angles
float layerDepth = 1.0 / layers;
// 一層ごとのUVのずれ:視線の傾き(xy / z)× 深さ / the UV step per layer: the view's slope (xy / z) × depth
vec2 delta = v.xy / max(v.z, 0.1) * uMaterial.parallaxScale / layers;
float depth = 0.0;
float mapDepth = 1.0 - textureGrad(uNormalMap, uv, dx, dy).a; // 深さ = 1 − 高さ / depth = 1 − height
for (int i = 0; i < 32 && depth < mapDepth; ++i) {
uv -= delta;
mapDepth = 1.0 - textureGrad(uNormalMap, uv, dx, dy).a;
depth += layerDepth;
}
// 最後の2層の間で交点を補間 / interpolate the crossing between the last two layers
vec2 prev = uv + delta;
float after = mapDepth - depth;
float before = (1.0 - textureGrad(uNormalMap, prev, dx, dy).a) - depth + layerDepth;
float w = after / (after - before + 1e-6);
return mix(uv, prev, w);
}
1つずつ:
- 層の数は、表面を真っ直ぐ見る時()の8から、かすめる角度()の32迄変わります。其の時は光線が1層で沢山のテクセルを横切るからです。
max(v.z, 0.1)は、かすめる角度で1歩が爆発しない様にします。を超えると、ずれは殆ど大きくなりません。- ループはUVと光線の深さを1層ずつ進め、光線の深さが今のUVのマップの深さに届くと止まります。32という固定の上限は層の最大の数で、テクスチャの中身が何でもループが必ず終わる事も保証します。
- 補間が最後にあります。
afterは最後の標本で光線がマップよりどれだけ下にあるか(0か負)、beforeは1つ前の標本でどれだけ上にあるか(正)です。2つを結ぶ直線が0を横切る所は、どちらの標本よりもずっと良い交点で、mix(uv, prev, w)が其れを返します。層を進むだけの時に見える「階段」が殆ど消えます。
あたし達の壁はparallaxScale = 0.04、UVの1単位の4 %を使います。
壁のUVはメートル単位なので、目地(高さ0.2、深さ0.8)は cmの深さです。
法線から60°の角度で壁を見るとなので、層は枚で、1層で UV単位、3.5 mm動きます。
目地の底に届く光線は16層進み、壁に沿って約5.5 cm動いています。
80°では同じ目地がテクスチャを約18 cmずらすので、壁に沿って歩くと視差がとても強く見えます。
parallaxScaleはUV単位なので、メートルでの深さはメッシュによります。
レンガの球ではUVの1単位が周りに3.77 m、極から極へ1.88 mなので、同じ0.04でも壁より深い(そして少し伸びた)効果になります。
makeBoxの様にUVをメートル単位にしておけば、予想通りになります。
ずらしたUVを使う
mainは接線空間の視線を計算し、スイッチがオンで、マテリアルに深さがあり、頂点に接線がある時だけ関数を呼びます:
// 視差マッピング:これより後のテクスチャはすべてずらしたUVで読む / parallax mapping: every texture below is read at
// the shifted UV
vec2 uv = vUv;
vec2 uvDx = dFdx(vUv), uvDy = dFdy(vUv);
if (uParallaxMapping && uMaterial.parallaxScale > 0.0 && hasTangent) {
vec3 v = normalize(uViewPos - vWorldPos);
uv = parallaxOcclusion(vUv, vec3(dot(v, tangent), dot(v, bitangent), dot(v, geometricNormal)), uvDx, uvDy);
}
vec4 base = textureGrad(uDiffuseMap, uv, uvDx, uvDy);
此処から後は全てのテクスチャを、ずらしたuvで読みます。
ベースカラー、鏡面反射、発光、そして法線マップ自身もです。
此れは大事です。
法線マップを古いvUvで読むと、凹凸のライティングが見えているレンガと揃わなくなります。
textureGradと暗黙の微分
此のシェーダーの全ての読み込みは、textureではなくtextureGradを使う様になりました。
texture(sampler, uv)は、隣のピクセルとの間でuvがどれだけ速く変わるかからミップマップの段を選びます。
GPUはピクセルを2 × 2の組で処理し、組の中の差を取ります。
GLSL 第6章のdFdxとdFdyと同じ仕組みです。
此の暗黙の微分は、組の4つのピクセルが全て同じ命令を実行する一様な制御フローの中でしか定義されていません。
POMのループは隣のピクセルで回る回数が違い、其の周りのifも或るピクセルでは通り、別のピクセルでは通りません(レンガの物の縁、接線の無いフラグメント)。
そういうコードの中の暗黙の微分は、其処に居ないピクセルの値と比べる事になり、GLSLの仕様は結果を未定義としています。
textureGrad(sampler, P, dPdx, dPdy)は代わりに微分を引数で受け取ります:
sampler、P:textureと同じ。dPdx、dPdy:此のピクセルから画面のとの隣のピクセルへPがどれだけ変わるか。暗黙の物と全く同じ様に、ミップマップの段(と、オンなら異方性フィルタリング)を選びます。
シェーダーはmainの初めの一様な制御フローでdFdx(vUv)とdFdy(vUv)を1回計算し、全ての読み込みに渡します。
其れがずらす前のUVの微分なのもわざとです。
ずらしたUVはレンガが目地を隠し始める所で跳ぶので、其の微分はそういう縁に沿って極小のミップマップの段を選び、縁をちらつかせてしまいます。
llvmpipeではループの中の普通のtextureが偶々動きますが、GPUでは正にそういう縁に沿ったミップマップの段のノイズが出る事があるので、当てにしないで下さい。
見た目と、出来ない事
POMは限界のある錯覚です:
- 輪郭は平らなまま。 動くのはテクスチャ座標だけなので、壁の上の縁と球の輪郭は前と同じく真っ直ぐで丸いです。本当の変位には本当の形が要ります(テッセレーション、GLSL 第15章)。
- 自分の影が無い。 光に向かって2本目の光線を進めない限り、レンガは隣の目地に影を落としません(課題5)。
- かすめる角度では補間をしても層が段々に見え、2つの面が違う向きにずれる箱の角ではテクスチャが泳ぎます。
- OpenGL流のUVだけ。 ずれはをに、をに沿って動かすので、画像の上がの時だけ正しいです。glTFのUV(が下)では、の部分の符号が逆でなければなりません。其の為
parallaxScaleはあたし達の手作りのMaterialの性質で、Modelは決して設定しません。glTFの核の仕様にはそもそも高さマップが無く、glTFのマテリアルはparallaxScale = 0のままです。課題7で両方の決まりで動く様にします。
22.13 キーとスイッチ
main.ccの残りは入力です:
if (key == GLFW_KEY_M) {
normalMaps = !normalMaps;
printf("normal maps: %s\n", normalMaps ? "on" : "off");
}
if (key == GLFW_KEY_X) {
parallax = !parallax;
printf("parallax mapping: %s\n", parallax ? "on" : "off");
}
if (key == GLFW_KEY_L) movingLight = !movingLight;
そして2つのスイッチは、表示モードの隣でフレーム毎に1回シェーダーに送ります:
phong->set("uViewMode", viewMode);
phong->set("uNormalMapping", normalMaps ? 1 : 0);
phong->set("uParallaxMapping", parallax ? 1 : 0);
Mを2回、Xを1回、Vを何回か押すと、次の様に表示されます:
normal maps: off
normal maps: on
parallax mapping: off
view: ambient
view: diffuse
view: specular
view: emission
view: normals
view: vertex normals
view: tangents
22.14 良くある間違い
法線マッピングのバグで何かが落ちる事は殆どありません。
一目ではもっともらしく、良く見ると間違っているライティングになるので、良くある犯人を見た目で知っておく価値があります。
其の内の2つを、夜の壁の回る光の真上で見せます:
sRGBで読んだ法線マップ。
Texture2D::load("assets/textures/bricks_normal.png", {.srgb = true})とすると、GPUは値をガンマでエンコードされた色の様にデコードします。
平らなテクセルはとに128を保存していて、に戻るはずです。
sRGBの曲線を通すとは0.216になり、です。
の255は1のままです。
壁の全ての平らな所の法線はになり、画像の左下へ38.8°傾きます。
其れが真ん中の画像です。
光がレンガの左にあれば照らされ、右にあれば黒くなります。
第21章の規則に例外はありません。
色の画像はsRGB、其れ以外(法線、高さ、粗さ、遮蔽)はリニアです。
緑チャンネル。
OpenGL流の法線マップ(Blender、Unity、glTF、あたし達)は = 画像の上で保存します。
DirectX流のマップ(Unreal、3ds Max、多くのテクスチャのサイト)は = 下です。
DirectXのマップをあたし達のシェーダーで使うと、全ての面取りが縦に逆になります。
右の画像では、光の上のレンガの明るい縁が上にあり、光が上から来ている様に見えますが、左右の縁は正しいままです。
「横は正しく縦は逆」という混ざり方が見分ける印です。
読み込む時に1回(画像の緑チャンネルを反転)か、シェーダーでm.y = -m.yとして直します。
但し両方してはいけません。
鏡像のUVとハンドネス。
wを無視してを直接使うと、鏡像でない全ての三角形では動き、鏡像の全ての三角形で緑チャンネルのバグになります。
UVが鏡像のキャラクターでは、顔の半分は正しく、もう半分は間違った側から照らされて見えます。
モデル行列が鏡映するのにシェーダーが行列式でwを反転しない時は物全体に、UVの決まりを間違えた時(22.5節)はglTFのモデル全体に同じ事が起きます。
表示モード8ですぐに分かります。
従法線が上ではなく下を向くからです。
補間の後に直交化しない。
フラグメントシェーダーでグラム・シュミットを飛ばしても(22.10節)、補間された接線が垂直なままの平らな壁は壊れません。
曲面では向きによって凹凸が弱過ぎたり強過ぎたりし、法線マップのせいにしがちな、気付き難い間違いになります。
接線を法線行列で変換する。
uNormalMatrix * aTangent.xyzは害が無さそうに見え、回転と一様な拡大縮小では正確です。
一様でない拡大縮小では接線を表面から浮かせ(22.8節)、グラム・シュミットが其れを間違った向きに「直し」ます。
戻し忘れ、正規化忘れ。
* 2.0 - 1.0無しでテクセルを使うと全ての法線がとに傾き、最後のnormalizeを忘れると、ミップマップが反対向きの面取りを平均して短くしたベクトルの所で凹凸が暗くなります。
ユニット4に何も繋いでいない。
法線マップの無いマテリアルがユニット4に何も繋がないと、前の描画が其処に残した物を読むので、木箱が急に樽の溝を纏う事があります。
Material::applyは、他に何も無ければ白を、必ず何かを繋ぎます。
22.15 本物のエンジンではどうしているか
- MikkTSpace。 ベイクした法線マップは、ベイクに使ったのと全く同じ接線でしか正しくなりません。継ぎ目で頂点をどう分けるか、三角形にどう重みを付けるか迄同じでなければなりません。MikkTSpaceはBlender、Substance、Unity、Unreal、glTFの仕様が合意している標準で、エンジンは自前の物ではなく其の参照実装(Cのファイル1つ)を使います。あたし達の方法は滑らかで均等にマップされたメッシュでは近い結果になります(MikkTSpaceは三角形に伸びではなく角の角度で重みを付けるので、其処でも少しは違います)。硬い角、UVの継ぎ目、鏡像の線ではMikkTSpaceは頂点の分け方も違い、Blenderのベイクをあたし達の接線で使うと其処に薄い継ぎ目が見えます。
- 2チャンネルの法線マップ。 表面の外を向く単位法線はとで決まります:。エンジンはとだけを
GL_RG8の形式か、BC5(OpenGLではGL_COMPRESSED_RG_RGTC2)の圧縮で保存し、色の圧縮よりずっと品質を保ち、シェーダーでを作り直します。あたし達のアルファの高さは其の時は別のテクスチャに移ります。 - 微分からの接線。 フラグメントシェーダーは、ワールドの位置とUVの
dFdxとdFdyからとを自分で計算出来ます(「コタンジェントフレーム」)。接線の属性は全く要りません。頂点のメモリが節約出来、前計算も要りませんが、基底は三角形毎に一定なので、ポリゴンの少ない曲面では角張り、ベイクしたマップとは完全には合いません。課題4で作ります。 - ディテールの法線マップ。 繰り返す2つ目の法線マップ(毛穴、傷、布)を主な物の上に混ぜます。2つのベクトルを足すだけでは両方が平らになるので、良くある方法(「ホワイトアウト」、「リオリエンテッド・ノーマル・マッピング」)はディテールの法線を元の法線の基底へ回します。
- 法線のフィルタリング。 法線をミップマップに平均すると、表面が凸凹だったという情報が失われ、遠くのレンガの壁は滑らかで艶々になります。エンジンは平均した法線が短い所で鏡面反射のハイライトを広げたり(Toksvigの方法と其の後継)、ミップマップを作る時に粗さのマップを調整したりします。第24章の粗さが其の為の自然な場所です。
- 高さを使う効果。 POM、其の速い仲間(リリーフマッピング、コーンステップマッピング)、自分の影付きの変種は、床、壁、地形に使われます。大きな変位には、エンジンは本物の形を使います。変位マップ付きのテッセレーション、又は単に三角形を増やす事で、今のGPUは其れを上手く処理します。
22.16 プラットフォーム毎の注意
- 此の章にプラットフォーム固有の物はありません。 新しいOpenGLの呼び出しは無く、新しいGLSLの関数(
textureGrad、dFdx、dFdy、determinant)は昔からGLSLの核にあり、Windows、Linux、FreeBSDで同じ様に動きます。 - 「未定義」の意味はドライバーで違います。 一様でない制御フローの中の暗黙の微分(22.12節)は、Mesaのllvmpipe、NVIDIA、AMD、Intelで結果が違う事がある所です。「自分のマシンでは動く」エンジンには、大抵ループの中に
textureの呼び出しがあります。textureGradなら結果は何処でもきちんと定義されます。 - 他の道具の法線マップ。 BlenderはOpenGL流のマップをベイクします。Substance Painterや殆どのテクスチャの道具は選べます(書き出しの設定の「OpenGL」又は「DirectX」)。Unreal向けのアセットはDirectX流です。ダウンロードした法線マップが下から照らされて見えたら、まず緑チャンネルを確かめて下さい。
22.17 まとめ
- 法線マップは接線空間の法線を保存し、TBNの基底が其れをワールド座標に直します:。エンジンの仕事は、ピクセル毎に、、を用意する事です。
- 接線はglTFの
TANGENT(vec4:xyz= 、w= ±1)から来るか、計算します。三角形毎に、を2 × 2の逆行列で解き、頂点毎に足し、法線に対してグラム・シュミットをして正規化します。 - はハンドネスです:は画像の上を向かなければなりません。鏡像のUVはになり、鏡映するモデル行列は行列式の符号でを反転します。
- 画像の上は、あたし達の形(読む時に画像を反転)では、glTF(画像を決して反転しない)ではです。
UvConvention::OpenGlとUvConvention::Gltfの違いは其の符号だけです。 - 全ての形は、location 3に接線のある
ModelVertexになりました。makeBoxはメートル単位のUVを付けます。Modelは法線マップがあってTANGENTの無いglTFのプリミティブ(樽の蓋)の接線を計算します。 - 接線は
mat3(model)で、法線は法線行列で変換します。phong.vertとphong_instanced.vertの両方がvTangentを書きます。 - フラグメントシェーダーは補間の後にグラム・シュミットを繰り返します。法線マップが無ければ、
normalScale = 0とユニット4の白いテクスチャで普通の表面の法線になり、フラグは要りません。 - 法線マップはデータなのでリニアで読み込みます。OpenGL流は緑が上、DirectX流は緑が下です。
- 視差オクルージョンマッピングは視線を高さマップ(アルファ)の中で8〜32層に分けて進め、全てのテクスチャを交点のUVで読みます。微分はループの外で取って
textureGradを使います。OpenGL流のUVでしか動かないので、使うのはあたし達の形だけです。
22.18 課題
- ★ 手で計算して下さい。壁の三角形の位置が(0, 0, 0)、(4, 0, 0)、(0, 2, 0)、UVが(0, 0)、(2, 0)、(0, −1)です。22.3節の式でとを求め、を正規化し、両方のUVの決まりでを求めて下さい。其れから、此の3つの頂点(法線は(0, 0, 1))で
computeTangentsを呼んでtangentを表示する小さなテストプログラムで確かめて下さい。は両方の決まりで同じ、は逆になるはずです。 - ★
brickMaterial.normalScaleを3、次に0.3、次に0にして下さい。3では面取りがずっと深く、レンガの面がざらざらに見え、0.3では壁は殆ど平らに見え、0ではMを押した時と全く同じに見えるはずです(但し視差は残ります)。applyが0を送り、シェーダーがマップを飛ばすからです。 - ★★ 柱を鏡映して下さい。モデル行列に
scale({-1.0f, 1.0f, 1.0f})を掛け、glFrontFace(GL_CW)とglFrontFace(GL_CCW)の間で描きます(鏡映する行列は巻く向きも逆にします、第16章)。レンガは正しく照らされたままに見え(模様は鏡像になりますが、レンガでは殆ど気付きません)、表示モード8では柱の従法線が緑になるはずです。其れからphong.vertの行列式の判定を消して下さい。柱の従法線は紫のになり、レンガは縦に逆の側から照らされて見えるはずです。 - ★★ 微分からの接線:
phong.fragで、vWorldPosとvUvのdFdxとdFdyからとを作り(computeTangentsと同じ2 × 2の式を、三角形の辺の代わりに画面上の差で解きます)、vTangentの代わりに使って下さい。レンガは殆ど同じに見えるはずですが、樽の表示モード7は滑らかな色の変化の代わりに平らな面を見せるはずです。glTFの樽ではの符号を変える必要があります。何故かを22.5節で説明して下さい。 - ★★ 自分の影の付く視差:交点を見付けた後、交点から回る光に向かって接線空間で進み(同じ層のループを上向きに)、光線が深さ0に届く前に高さマップの下に入ったら、其の光の拡散反射と鏡面反射を暗くして下さい。夜、全てのレンガが光と反対側の目地に暗い帯を落とし、光が回ると其の帯が動くはずです。
- ★★ 床の法線マップ:
floor.pngをstbi_load(第6章の読み込み)で読み、輝度を高さにし、22.11節の中心差分で(端は回り込ませて)法線を計算し、Texture2D::fromPixelsでfloorMaterial.normalMapとしてアップロードして下さい。fromPixelsは反転しないので、Texture2D::loadに合わせて自分で行を反転し、緑がを意味する様にします。タイルの目地が回る光を受け、表示モード5で床にタイルの模様が見えるはずです。 - ★★★ 両方のUVの決まりで動く視差:
MaterialとuMaterialにfloat uvUp(OpenGLのUVで+1、glTFのUVで−1)を足し、deltaのの部分に掛けて下さい。UVのをに置き換え、接線をUvConvention::Gltfで計算し、レンガのテクスチャを両方flipY = falseで読んだ2つ目の壁で試します。uvUp = -1なら、MとXがオンでも、どの角度からでも元の壁と全く同じに見えるはずです。uvUp = +1なら、其の視差はレンガを縦に逆向きにずらすはずです。
ファイル: a/CMakeLists.txt | b/CMakeLists.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -43,7 +43,8 @@ add_executable(game | |||
| 43 | src/model.cc | 43 | src/model.cc |
| 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 | target_include_directories(game PRIVATE src external/stb external/linalg) | 48 | target_include_directories(game PRIVATE src external/stb external/linalg) |
| 48 | target_link_libraries(game PRIVATE glad stb_image glfw) | 49 | target_link_libraries(game PRIVATE glad stb_image glfw) |
| 49 | 50 | ||
ファイル: a/assets/LICENSE.txt | b/assets/LICENSE.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -14,3 +14,6 @@ models/window.glb 花箱つきの窓 / a window with a flower box (ch | |||
| 14 | models/rock.glb 岩(インスタンシング用) / a rock for instancing (chapter 19) | 14 | models/rock.glb 岩(インスタンシング用) / a rock for instancing (chapter 19) |
| 15 | models/crate.glb 木箱のモデル / crate model | 15 | models/crate.glb 木箱のモデル / crate model |
| 16 | models/diorama.glb 小さな場面 / a small diorama scene (chapter 21) | 16 | models/diorama.glb 小さな場面 / a small diorama scene (chapter 21) |
| 17 | textures/bricks.png レンガ / bricks (chapter 22) | ||
| 18 | textures/bricks_normal.png レンガの法線マップ+高さ / brick normal map + height (chapter 22) | ||
| 19 | models/barrel.glb 樽(PBRのテクスチャ付き) / a barrel with PBR textures (chapter 22) | ||
ファイル: /dev/null | b/assets/models/barrel.glb
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/assets/textures/bricks.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/assets/textures/bricks_normal.png
新しいファイル:100644 / バイナリファイル
ファイル: a/shaders/phong.frag | b/shaders/phong.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -3,6 +3,7 @@ in vec3 vWorldPos; | |||
| 3 | in vec3 vNormal; | 3 | in vec3 vNormal; |
| 4 | in vec2 vUv; | 4 | in vec2 vUv; |
| 5 | in vec3 vTint; // インスタンスの色(第19章) / the instance colour (chapter 19) | 5 | in vec3 vTint; // インスタンスの色(第19章) / the instance colour (chapter 19) |
| 6 | in vec4 vTangent; // ワールド座標の接線、w = 従法線の向き(第22章) / world-space tangent, w = bitangent sign (chapter 22) | ||
| 6 | 7 | ||
| 7 | // 表面の性質。色はそれぞれのマップと掛け合わされる / surface properties; each colour is multiplied with its map | 8 | // 表面の性質。色はそれぞれのマップと掛け合わされる / surface properties; each colour is multiplied with its map |
| 8 | struct Material { | 9 | struct Material { |
| @@ -16,12 +17,19 @@ struct Material { | |||
| 16 | bool doubleSided; // 裏面では法線を反転する / flip the normal on back faces | 17 | bool doubleSided; // 裏面では法線を反転する / flip the normal on back faces |
| 17 | vec3 reflectivity; // 空の映り込みの強さ(0 = なし、第18章) / strength of the sky reflection (0 = none, chapter 18) | 18 | vec3 reflectivity; // 空の映り込みの強さ(0 = なし、第18章) / strength of the sky reflection (0 = none, chapter 18) |
| 18 | float reflectionBlur; // 0 = 鏡、1 = 一番ぼやけたミップマップ / 0 = mirror, 1 = the blurriest mip level | 19 | float reflectionBlur; // 0 = 鏡、1 = 一番ぼやけたミップマップ / 0 = mirror, 1 = the blurriest mip level |
| 20 | float normalScale; // 法線マップの強さ(0 = マップなし、第22章) / normal map strength (0 = no map, chapter 22) | ||
| 21 | float parallaxScale; // 視差マッピングの深さ(UV単位、0 = なし) / parallax depth (UV units, 0 = none) | ||
| 19 | }; | 22 | }; |
| 20 | uniform Material uMaterial; | 23 | uniform Material uMaterial; |
| 21 | 24 | ||
| 22 | layout(binding = 0) uniform sampler2D uDiffuseMap; | 25 | layout(binding = 0) uniform sampler2D uDiffuseMap; |
| 23 | layout(binding = 1) uniform sampler2D uSpecularMap; | 26 | layout(binding = 1) uniform sampler2D uSpecularMap; |
| 24 | layout(binding = 2) uniform sampler2D uEmissionMap; | 27 | layout(binding = 2) uniform sampler2D uEmissionMap; |
| 28 | // 法線マップ(第22章):RGB = 接線空間の法線、A = 高さ(視差マッピング用)。ユニット4 | ||
| 29 | // Normal map (chapter 22): RGB = tangent-space normal, A = height (for parallax mapping). Unit 4 | ||
| 30 | layout(binding = 4) uniform sampler2D uNormalMap; | ||
| 31 | uniform bool uNormalMapping = true; // 法線マップを使う(デバッグ用に切れる) / use normal maps (can be turned off for debugging) | ||
| 32 | uniform bool uParallaxMapping = true; // 視差マッピングを使う / use parallax mapping | ||
| 25 | // 環境(空)のキューブマップ。ユニット3(第18章) / the environment (sky) cube map, unit 3 (chapter 18) | 33 | // 環境(空)のキューブマップ。ユニット3(第18章) / the environment (sky) cube map, unit 3 (chapter 18) |
| 26 | layout(binding = 3) uniform samplerCube uEnvironmentMap; | 34 | layout(binding = 3) uniform samplerCube uEnvironmentMap; |
| 27 | uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) | 35 | uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) |
| @@ -76,8 +84,10 @@ layout(std140, binding = 0) uniform Camera { | |||
| 76 | float uTime; // アニメーションの時間(秒) / animation time (seconds) | 84 | float uTime; // アニメーションの時間(秒) / animation time (seconds) |
| 77 | }; | 85 | }; |
| 78 | 86 | ||
| 79 | // 0 = 全部、1 = 環境光、2 = 拡散反射、3 = 鏡面反射、4 = 発光、5 = 法線 | 87 | // 0 = 全部、1 = 環境光、2 = 拡散反射、3 = 鏡面反射、4 = 発光、5 = 法線(法線マップ後)、 |
| 80 | // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals | 88 | // 6 = 頂点の法線(法線マップ前)、7 = 接線、8 = 従法線(第22章) |
| 89 | // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals (after normal mapping), | ||
| 90 | // 6 = vertex normals (before normal mapping), 7 = tangents, 8 = bitangents (chapter 22) | ||
| 81 | uniform int uViewMode; | 91 | uniform int uViewMode; |
| 82 | 92 | ||
| 83 | // アルファトゥカバレッジ(第20章):マスクのマテリアルを捨てる代わりに、アルファをMSAAのサンプルの割合にする。 | 93 | // アルファトゥカバレッジ(第20章):マスクのマテリアルを捨てる代わりに、アルファをMSAAのサンプルの割合にする。 |
| @@ -139,8 +149,55 @@ float attenuate(float d, vec3 k) { | |||
| 139 | return 1.0 / (k.x + k.y * d + k.z * d * d); | 149 | return 1.0 / (k.x + k.y * d + k.z * d * d); |
| 140 | } | 150 | } |
| 141 | 151 | ||
| 152 | // 視差オクルージョンマッピング(第22章):目から表面の奥へ、高さマップの層を一枚ずつ進み、最初に高さマップの | ||
| 153 | // 下に入った所のUVを返す(前の層との間は直線で補間)。v = 接線空間の目への向き。 | ||
| 154 | // ループの中は分岐なので、ミップマップの段は外で求めた微分で指定する(textureGrad) | ||
| 155 | // Parallax occlusion mapping (chapter 22): march from the eye into the surface one height layer at a time and return | ||
| 156 | // the UV where the ray first goes below the height map (interpolated linearly with the previous layer). v = the | ||
| 157 | // direction to the eye in tangent space. Inside the loop we are in a branch, so the mip level comes from derivatives | ||
| 158 | // computed outside (textureGrad) | ||
| 159 | vec2 parallaxOcclusion(vec2 uv, vec3 v, vec2 dx, vec2 dy) { | ||
| 160 | float layers = mix(32.0, 8.0, clamp(v.z, 0.0, 1.0)); // 斜めほど多く / more layers at grazing angles | ||
| 161 | float layerDepth = 1.0 / layers; | ||
| 162 | // 一層ごとのUVのずれ:視線の傾き(xy / z)× 深さ / the UV step per layer: the view's slope (xy / z) × depth | ||
| 163 | vec2 delta = v.xy / max(v.z, 0.1) * uMaterial.parallaxScale / layers; | ||
| 164 | float depth = 0.0; | ||
| 165 | float mapDepth = 1.0 - textureGrad(uNormalMap, uv, dx, dy).a; // 深さ = 1 − 高さ / depth = 1 − height | ||
| 166 | for (int i = 0; i < 32 && depth < mapDepth; ++i) { | ||
| 167 | uv -= delta; | ||
| 168 | mapDepth = 1.0 - textureGrad(uNormalMap, uv, dx, dy).a; | ||
| 169 | depth += layerDepth; | ||
| 170 | } | ||
| 171 | // 最後の2層の間で交点を補間 / interpolate the crossing between the last two layers | ||
| 172 | vec2 prev = uv + delta; | ||
| 173 | float after = mapDepth - depth; | ||
| 174 | float before = (1.0 - textureGrad(uNormalMap, prev, dx, dy).a) - depth + layerDepth; | ||
| 175 | float w = after / (after - before + 1e-6); | ||
| 176 | return mix(uv, prev, w); | ||
| 177 | } | ||
| 178 | |||
| 142 | void main() { | 179 | void main() { |
| 143 | vec4 base = texture(uDiffuseMap, vUv); | 180 | // 接線空間(TBN):補間で直交が崩れるので、法線に対してもう一度グラム・シュミット(第22章) |
| 181 | // Tangent space (TBN): interpolation breaks the orthogonality, so Gram-Schmidt against the normal again (chapter 22) | ||
| 182 | vec3 geometricNormal = normalize(vNormal); | ||
| 183 | vec3 tangent = vTangent.xyz - dot(vTangent.xyz, geometricNormal) * geometricNormal; | ||
| 184 | bool hasTangent = dot(tangent, tangent) > 1e-10; // 接線がない頂点は(0,0,0,0) / vertices without tangents have (0,0,0,0) | ||
| 185 | tangent = hasTangent ? normalize(tangent) : vec3(1.0, 0.0, 0.0); | ||
| 186 | vec3 bitangent = cross(geometricNormal, tangent) * (vTangent.w < 0.0 ? -1.0 : 1.0); | ||
| 187 | // 両面のマテリアルを裏から見ているなら、法線は裏を向く(接線と従法線はそのまま) | ||
| 188 | // Seen from behind, a double-sided surface's normal points the other way (tangent and bitangent stay) | ||
| 189 | if (uMaterial.doubleSided && !gl_FrontFacing) geometricNormal = -geometricNormal; | ||
| 190 | |||
| 191 | // 視差マッピング:これより後のテクスチャはすべてずらしたUVで読む / parallax mapping: every texture below is read at | ||
| 192 | // the shifted UV | ||
| 193 | vec2 uv = vUv; | ||
| 194 | vec2 uvDx = dFdx(vUv), uvDy = dFdy(vUv); | ||
| 195 | if (uParallaxMapping && uMaterial.parallaxScale > 0.0 && hasTangent) { | ||
| 196 | vec3 v = normalize(uViewPos - vWorldPos); | ||
| 197 | uv = parallaxOcclusion(vUv, vec3(dot(v, tangent), dot(v, bitangent), dot(v, geometricNormal)), uvDx, uvDy); | ||
| 198 | } | ||
| 199 | |||
| 200 | vec4 base = textureGrad(uDiffuseMap, uv, uvDx, uvDy); | ||
| 144 | float alpha = uMaterial.alpha * base.a; | 201 | float alpha = uMaterial.alpha * base.a; |
| 145 | // アルファが1ピクセルでどれだけ変わるか(分岐の前に:fwidthは隣のピクセルと一緒に計算する) | 202 | // アルファが1ピクセルでどれだけ変わるか(分岐の前に:fwidthは隣のピクセルと一緒に計算する) |
| 146 | // How much alpha changes across one pixel (before any branch: fwidth is computed together with the neighbours) | 203 | // How much alpha changes across one pixel (before any branch: fwidth is computed together with the neighbours) |
| @@ -160,14 +217,20 @@ void main() { | |||
| 160 | 217 | ||
| 161 | Surface s; | 218 | Surface s; |
| 162 | s.position = vWorldPos; | 219 | s.position = vWorldPos; |
| 163 | s.normal = normalize(vNormal); | 220 | s.normal = geometricNormal; |
| 164 | // 両面のマテリアルを裏から見ているなら、法線は裏を向く / seen from behind, a double-sided surface's normal points the other way | 221 | // 法線マップ:接線空間の法線(x, y, z)を、ワールド座標の x·T + y·B + z·N に直す。強さはxyに掛ける(glTFと同じ) |
| 165 | if (uMaterial.doubleSided && !gl_FrontFacing) s.normal = -s.normal; | 222 | // Normal map: turn the tangent-space normal (x, y, z) into world space as x·T + y·B + z·N. The strength scales xy |
| 223 | // (as in glTF) | ||
| 224 | if (uNormalMapping && hasTangent && uMaterial.normalScale > 0.0) { | ||
| 225 | vec3 m = textureGrad(uNormalMap, uv, uvDx, uvDy).xyz * 2.0 - 1.0; // 0..1 → -1..1 | ||
| 226 | m.xy *= uMaterial.normalScale; | ||
| 227 | s.normal = normalize(m.x * tangent + m.y * bitangent + m.z * geometricNormal); | ||
| 228 | } | ||
| 166 | s.view = normalize(uViewPos - vWorldPos); | 229 | s.view = normalize(uViewPos - vWorldPos); |
| 167 | s.diffuse = uMaterial.diffuse * vTint * base.rgb; | 230 | s.diffuse = uMaterial.diffuse * vTint * base.rgb; |
| 168 | s.specular = uMaterial.specular * texture(uSpecularMap, vUv).rgb; | 231 | s.specular = uMaterial.specular * textureGrad(uSpecularMap, uv, uvDx, uvDy).rgb; |
| 169 | s.shininess = uMaterial.shininess; | 232 | s.shininess = uMaterial.shininess; |
| 170 | vec3 emission = uMaterial.emission * texture(uEmissionMap, vUv).rgb; | 233 | vec3 emission = uMaterial.emission * textureGrad(uEmissionMap, uv, uvDx, uvDy).rgb; |
| 171 | 234 | ||
| 172 | vec3 diffuse = vec3(0.0); | 235 | vec3 diffuse = vec3(0.0); |
| 173 | vec3 specular = vec3(0.0); | 236 | vec3 specular = vec3(0.0); |
| @@ -209,6 +272,13 @@ void main() { | |||
| 209 | else if (uViewMode == 3) color = specular; | 272 | else if (uViewMode == 3) color = specular; |
| 210 | else if (uViewMode == 4) color = emission; | 273 | else if (uViewMode == 4) color = emission; |
| 211 | else if (uViewMode == 5) color = s.normal * 0.5 + 0.5; | 274 | else if (uViewMode == 5) color = s.normal * 0.5 + 0.5; |
| 275 | else if (uViewMode == 6) color = geometricNormal * 0.5 + 0.5; | ||
| 276 | else if (uViewMode == 7) color = hasTangent ? tangent * 0.5 + 0.5 : vec3(0.0); | ||
| 277 | else if (uViewMode == 8) color = hasTangent ? bitangent * 0.5 + 0.5 : vec3(0.0); | ||
| 278 | // ベクトルの表示は、post.fragがsRGBにした後でちょうどこの値になるように、先にリニアへ戻しておく | ||
| 279 | // Vector views: convert to linear first, so that after post.frag's sRGB encoding the screen shows exactly this value | ||
| 280 | if (uViewMode >= 5) | ||
| 281 | color = mix(color / 12.92, pow((color + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), color)); | ||
| 212 | // 不透明とマスクはアルファ1。ブレンドだけ本当のアルファを出す。アルファトゥカバレッジのときは、このアルファが | 282 | // 不透明とマスクはアルファ1。ブレンドだけ本当のアルファを出す。アルファトゥカバレッジのときは、このアルファが |
| 213 | // 覆うサンプルの数になる / opaque and mask output alpha 1; only blend outputs its alpha. With alpha to coverage this | 283 | // 覆うサンプルの数になる / opaque and mask output alpha 1; only blend outputs its alpha. With alpha to coverage this |
| 214 | // alpha becomes the number of samples covered | 284 | // alpha becomes the number of samples covered |
ファイル: a/shaders/phong.vert | b/shaders/phong.vert
| 前 | 新 | ||
|---|---|---|---|
| @@ -2,6 +2,9 @@ | |||
| 2 | layout(location = 0) in vec3 aPosition; | 2 | layout(location = 0) in vec3 aPosition; |
| 3 | layout(location = 1) in vec3 aNormal; // 面の向き(モデル座標) / which way the surface faces (model space) | 3 | layout(location = 1) in vec3 aNormal; // 面の向き(モデル座標) / which way the surface faces (model space) |
| 4 | layout(location = 2) in vec2 aUv; | 4 | layout(location = 2) in vec2 aUv; |
| 5 | // 接線(第22章):xyz = uが増える向き、w = 従法線の向き(±1)。(0,0,0,0) = なし | ||
| 6 | // Tangent (chapter 22): xyz = the direction in which u grows, w = the bitangent's sign (±1). (0,0,0,0) = none | ||
| 7 | layout(location = 3) in vec4 aTangent; | ||
| 5 | 8 | ||
| 6 | // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock) | 9 | // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock) |
| 7 | // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++) | 10 | // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++) |
| @@ -19,6 +22,7 @@ uniform mat3 uNormalMatrix; // 法線をワールド座標へ(モデル行列 | |||
| 19 | out vec3 vWorldPos; | 22 | out vec3 vWorldPos; |
| 20 | out vec3 vNormal; | 23 | out vec3 vNormal; |
| 21 | out vec2 vUv; | 24 | out vec2 vUv; |
| 25 | out vec4 vTangent; // ワールド座標の接線と向き / world-space tangent and sign | ||
| 22 | // インスタンスごとの色(第19章)。インスタンシングでないときはこのユニフォーム(既定値は白) | 26 | // インスタンスごとの色(第19章)。インスタンシングでないときはこのユニフォーム(既定値は白) |
| 23 | // The per-instance colour (chapter 19). Without instancing it comes from this uniform (white by default) | 27 | // The per-instance colour (chapter 19). Without instancing it comes from this uniform (white by default) |
| 24 | uniform vec3 uTint = vec3(1.0); | 28 | uniform vec3 uTint = vec3(1.0); |
| @@ -29,6 +33,11 @@ void main() { | |||
| 29 | vWorldPos = world.xyz; | 33 | vWorldPos = world.xyz; |
| 30 | vNormal = uNormalMatrix * aNormal; // 正規化はフラグメントシェーダーで / normalized in the fragment shader | 34 | vNormal = uNormalMatrix * aNormal; // 正規化はフラグメントシェーダーで / normalized in the fragment shader |
| 31 | vUv = aUv; | 35 | vUv = aUv; |
| 36 | // 接線は面に沿う向きなので、法線行列ではなくモデル行列で変換する。鏡像(行列式が負)なら従法線も反転 | ||
| 37 | // A tangent lies along the surface, so it is transformed with the model matrix, not the normal matrix. A mirroring | ||
| 38 | // matrix (negative determinant) flips the bitangent too | ||
| 39 | mat3 m = mat3(uModel); | ||
| 40 | vTangent = vec4(m * aTangent.xyz, aTangent.w * (determinant(m) < 0.0 ? -1.0 : 1.0)); | ||
| 32 | vTint = uTint; | 41 | vTint = uTint; |
| 33 | gl_Position = uProj * uView * world; | 42 | gl_Position = uProj * uView * world; |
| 34 | } | 43 | } |
ファイル: a/shaders/phong_instanced.vert | b/shaders/phong_instanced.vert
| 前 | 新 | ||
|---|---|---|---|
| @@ -4,7 +4,7 @@ | |||
| 4 | layout(location = 0) in vec3 aPosition; | 4 | layout(location = 0) in vec3 aPosition; |
| 5 | layout(location = 1) in vec3 aNormal; | 5 | layout(location = 1) in vec3 aNormal; |
| 6 | layout(location = 2) in vec2 aUv; | 6 | layout(location = 2) in vec2 aUv; |
| 7 | // location 3は接線(第22章) / location 3 is the tangent (chapter 22) | 7 | layout(location = 3) in vec4 aTangent; // 接線(第22章) / tangent (chapter 22) |
| 8 | layout(location = 4) in mat4 aInstanceModel; // mat4はlocationを4つ使う(4〜7) / a mat4 takes four locations (4..7) | 8 | layout(location = 4) in mat4 aInstanceModel; // mat4はlocationを4つ使う(4〜7) / a mat4 takes four locations (4..7) |
| 9 | layout(location = 8) in vec3 aInstanceColor; | 9 | layout(location = 8) in vec3 aInstanceColor; |
| 10 | 10 | ||
| @@ -24,6 +24,7 @@ uniform float uOrbitSpeed; // 環の公転の速さ(半径8 mで、ラジア | |||
| 24 | out vec3 vWorldPos; | 24 | out vec3 vWorldPos; |
| 25 | out vec3 vNormal; | 25 | out vec3 vNormal; |
| 26 | out vec2 vUv; | 26 | out vec2 vUv; |
| 27 | out vec4 vTangent; | ||
| 27 | out vec3 vTint; | 28 | out vec3 vTint; |
| 28 | 29 | ||
| 29 | // Y軸周りの回転 / rotation about the Y axis | 30 | // Y軸周りの回転 / rotation about the Y axis |
| @@ -44,6 +45,8 @@ void main() { | |||
| 44 | // The rocks are scaled uniformly, so the normal can simply be rotated by the 3×3 part (phong.frag normalizes it) | 45 | // The rocks are scaled uniformly, so the normal can simply be rotated by the 3×3 part (phong.frag normalizes it) |
| 45 | vNormal = mat3(orbit * aInstanceModel) * (uNormalMatrix * aNormal); | 46 | vNormal = mat3(orbit * aInstanceModel) * (uNormalMatrix * aNormal); |
| 46 | vUv = aUv; | 47 | vUv = aUv; |
| 48 | mat3 m = mat3(model); | ||
| 49 | vTangent = vec4(m * aTangent.xyz, aTangent.w * (determinant(m) < 0.0 ? -1.0 : 1.0)); | ||
| 47 | vTint = aInstanceColor; | 50 | vTint = aInstanceColor; |
| 48 | gl_Position = uProj * uView * world; | 51 | gl_Position = uProj * uView * world; |
| 49 | } | 52 | } |
ファイル: a/src/main.cc | b/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,5 +1,5 @@ | |||
| 1 | // 第21章:ガンマ補正とHDR | 1 | // 第22章:法線マッピング |
| 2 | // Chapter 21: gamma correction and HDR | 2 | // Chapter 22: normal mapping |
| 3 | // | 3 | // |
| 4 | // 操作 / Controls: | 4 | // 操作 / Controls: |
| 5 | // WASD 前後左右に移動 / move forward, back, left, right | 5 | // WASD 前後左右に移動 / move forward, back, left, right |
| @@ -7,20 +7,18 @@ | |||
| 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 | // = / - 露出を上げる・下げる(0.5段ずつ) / exposure up / down (half a stop each) | 10 | // M 法線マップのオン・オフ / normal maps on / off |
| 11 | // T トーンマッピング:なし(クランプ) → Reinhard → ACES / tone mapping: none (clamp) → Reinhard → ACES | 11 | // X 視差(オクルージョン)マッピングのオン・オフ / parallax (occlusion) mapping on / off |
| 12 | // G ガンマ:シェーダー → GL_FRAMEBUFFER_SRGB → なし(間違い) → 二重(間違い) | 12 | // L 壁の前を回る点光源のオン・オフ / the point light circling in front of the wall on / off |
| 13 | // gamma: shader → GL_FRAMEBUFFER_SRGB → none (wrong) → double (wrong) | 13 | // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 → 頂点の法線 → 接線 → 従法線 |
| 14 | // B ブルームのオン・オフ / bloom on / off | 14 | // view: all → ambient → diffuse → specular → emission → normals → vertex normals → tangents → bitangents |
| 15 | // K 太陽を見る(電線の向こうの太陽にカメラを向ける) / look at the sun (aims the camera at the sun behind the wires) | 15 | // = / - 露出を上げる・下げる / exposure up / down |
| 16 | // O 表示:完成 → ブルームなし → 明るい部分 → ぼかしたブルーム / view: final → no bloom → bright part → blurred bloom | ||
| 17 | // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 | 16 | // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 |
| 18 | // effect: none / invert / grayscale / sharpen / blur / edge detection | 17 | // effect: none / invert / grayscale / sharpen / blur / edge detection |
| 19 | // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera | 18 | // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera |
| 20 | // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals | ||
| 21 | // N 昼 ⇔ 夜 / day ⇔ night | 19 | // N 昼 ⇔ 夜 / day ⇔ night |
| 22 | // F 懐中電灯のオン・オフ / flashlight on / off | 20 | // F 懐中電灯のオン・オフ / flashlight on / off |
| 23 | // P 風車を止める・動かす / pause / resume the windmill | 21 | // P 風車と点光源を止める・動かす / pause / resume the windmill and the point light |
| 24 | // Tab カーソルのキャプチャ切り替え / toggle cursor capture | 22 | // Tab カーソルのキャプチャ切り替え / toggle cursor capture |
| 25 | // R シェーダーを読み直す / reload the shaders | 23 | // R シェーダーを読み直す / reload the shaders |
| 26 | // Esc 終了 / quit | 24 | // Esc 終了 / quit |
| @@ -58,11 +56,10 @@ static const Placement kCrates[] = { | |||
| 58 | constexpr int kMsaaSamples = 4; // 第20章 / chapter 20 | 56 | constexpr int kMsaaSamples = 4; // 第20章 / chapter 20 |
| 59 | constexpr int kBloomPasses = 4; // 横+縦の組の数 / number of horizontal + vertical pairs | 57 | constexpr int kBloomPasses = 4; // 横+縦の組の数 / number of horizontal + vertical pairs |
| 60 | 58 | ||
| 61 | static const char *const kToneMapperNames[] = {"none (clamp)", "Reinhard", "ACES"}; | 59 | static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", |
| 62 | static const char *const kGammaNames[] = {"shader (linear → sRGB in post.frag)", "GL_FRAMEBUFFER_SRGB", | 60 | "normals", "vertex normals", "tangents", "bitangents"}; |
| 63 | "none (wrong: too dark)", "double (wrong: washed out)"}; | 61 | constexpr int kViewModes = 9; |
| 64 | static const char *const kPostViewNames[] = {"final", "no bloom", "bright part (attachment 1)", "blurred bloom"}; | 62 | constexpr int kFirstVectorView = 5; // ここからはベクトルを色で見せる / from here on, vectors are shown as colours |
| 65 | static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; | ||
| 66 | static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; | 63 | static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; |
| 67 | 64 | ||
| 68 | static float random01(std::uint32_t &state) { | 65 | static float random01(std::uint32_t &state) { |
| @@ -104,20 +101,7 @@ static Mat4 beam(Vec3 a, Vec3 b, float thickness) { | |||
| 104 | return m; | 101 | return m; |
| 105 | } | 102 | } |
| 106 | 103 | ||
| 107 | // 柵と電柱と電線:細いものほどエイリアスが目立つ / a fence, poles and wires: the thinner, the worse the aliasing | 104 | // 電柱と電線(第20章) / poles and wires (chapter 20) |
| 108 | static std::vector<Mat4> makeFence() { | ||
| 109 | std::vector<Mat4> fence; | ||
| 110 | Vec3 a = {-5.4f, 0.0f, 5.0f}, b = {-1.9f, 0.0f, 8.3f}; | ||
| 111 | Vec3 along = normalize(b - a); | ||
| 112 | int pickets = static_cast<int>(length(b - a) / 0.2f); | ||
| 113 | for (int i = 0; i <= pickets; ++i) { | ||
| 114 | Vec3 p = a + (0.2f * static_cast<float>(i)) * along; | ||
| 115 | fence.push_back(beam(p, p + Vec3{0.0f, 0.95f, 0.0f}, 0.05f)); | ||
| 116 | } | ||
| 117 | for (float y : {0.3f, 0.75f}) fence.push_back(beam(a + Vec3{0, y, 0}, b + Vec3{0, y, 0}, 0.04f)); | ||
| 118 | return fence; | ||
| 119 | } | ||
| 120 | |||
| 121 | static std::vector<Mat4> makeWires() { | 105 | static std::vector<Mat4> makeWires() { |
| 122 | std::vector<Mat4> wires; | 106 | std::vector<Mat4> wires; |
| 123 | const Vec3 poles[] = {{-9.0f, 0.0f, -3.0f}, {-3.0f, 0.0f, -5.5f}, {4.0f, 0.0f, -5.0f}, {10.0f, 0.0f, -2.0f}}; | 107 | const Vec3 poles[] = {{-9.0f, 0.0f, -3.0f}, {-3.0f, 0.0f, -5.5f}, {4.0f, 0.0f, -5.0f}, {10.0f, 0.0f, -2.0f}}; |
| @@ -163,7 +147,7 @@ static std::vector<Lantern> makeLanterns() { | |||
| 163 | 147 | ||
| 164 | int main() { | 148 | int main() { |
| 165 | Window window; | 149 | Window window; |
| 166 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 21")) return 1; | 150 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 22")) return 1; |
| 167 | 151 | ||
| 168 | // 画面(既定のフレームバッファ)がsRGBか:GL_FRAMEBUFFER_SRGBが効くのはsRGBのときだけ | 152 | // 画面(既定のフレームバッファ)がsRGBか:GL_FRAMEBUFFER_SRGBが効くのはsRGBのときだけ |
| 169 | // Is the screen (the default framebuffer) sRGB? GL_FRAMEBUFFER_SRGB only has an effect if it is | 153 | // Is the screen (the default framebuffer) sRGB? GL_FRAMEBUFFER_SRGB only has an effect if it is |
| @@ -181,7 +165,13 @@ int main() { | |||
| 181 | std::optional<Cubemap> sky = Cubemap::loadDirectory("assets/textures/sky", ".png", true); | 165 | std::optional<Cubemap> sky = Cubemap::loadDirectory("assets/textures/sky", ".png", true); |
| 182 | std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png", {.srgb = true}); | 166 | std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png", {.srgb = true}); |
| 183 | std::optional<Texture2D> grassTexture = Texture2D::load("assets/textures/grass_blades.png", {.srgb = true}); | 167 | std::optional<Texture2D> grassTexture = Texture2D::load("assets/textures/grass_blades.png", {.srgb = true}); |
| 184 | if (!phong || !skybox || !post || !blur || !unlit || !sky || !floorTexture || !grassTexture) return 1; | 168 | // レンガ:色はsRGB、法線マップはデータなのでリニア(Aは高さ) / bricks: the colour is sRGB, the normal map is data and |
| 169 | // stays linear (A = height) | ||
| 170 | std::optional<Texture2D> brickTexture = Texture2D::load("assets/textures/bricks.png", {.srgb = true}); | ||
| 171 | std::optional<Texture2D> brickNormal = Texture2D::load("assets/textures/bricks_normal.png"); | ||
| 172 | if (!phong || !skybox || !post || !blur || !unlit || !sky || !floorTexture || !grassTexture || !brickTexture || | ||
| 173 | !brickNormal) | ||
| 174 | return 1; | ||
| 185 | grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); | 175 | grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); |
| 186 | for (const Shader *s : {&*phong, &*skybox, &*post, &*unlit}) | 176 | for (const Shader *s : {&*phong, &*skybox, &*post, &*unlit}) |
| 187 | if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)) || | 177 | if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)) || |
| @@ -190,7 +180,10 @@ int main() { | |||
| 190 | 180 | ||
| 191 | std::optional<Model> scene = Model::load("assets/models/diorama.glb"); | 181 | std::optional<Model> scene = Model::load("assets/models/diorama.glb"); |
| 192 | std::optional<Model> crate = Model::load("assets/models/crate.glb"); | 182 | std::optional<Model> crate = Model::load("assets/models/crate.glb"); |
| 193 | if (!scene || !crate) return 1; | 183 | // 樽:色・金属と粗さ・法線・遮蔽のテクスチャ付き。蓋にはTANGENTがない(Modelが計算する) |
| 184 | // The barrel: colour, metallic-roughness, normal and occlusion textures. The lid has no TANGENT (Model computes it) | ||
| 185 | std::optional<Model> barrel = Model::load("assets/models/barrel.glb"); | ||
| 186 | if (!scene || !crate || !barrel) return 1; | ||
| 194 | 187 | ||
| 195 | const unsigned char whitePixel[4] = {255, 255, 255, 255}; | 188 | const unsigned char whitePixel[4] = {255, 255, 255, 255}; |
| 196 | Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); | 189 | Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); |
| @@ -227,7 +220,7 @@ int main() { | |||
| 227 | glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); | 220 | glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); |
| 228 | 221 | ||
| 229 | Camera fps; | 222 | Camera fps; |
| 230 | fps.position = {0.0f, 2.0f, 12.5f}; | 223 | fps.position = {0.3f, 1.6f, 10.0f}; |
| 231 | fps.pitch = radians(-4.0f); | 224 | fps.pitch = radians(-4.0f); |
| 232 | 225 | ||
| 233 | OrbitCamera orbit; | 226 | OrbitCamera orbit; |
| @@ -235,7 +228,7 @@ int main() { | |||
| 235 | orbit.distance = 11.0f; | 228 | orbit.distance = 11.0f; |
| 236 | orbit.yaw = radians(20.0f); | 229 | orbit.yaw = radians(20.0f); |
| 237 | 230 | ||
| 238 | bool useOrbit = false, bloomOn = true; | 231 | bool useOrbit = false, normalMaps = true, parallax = true, movingLight = true; |
| 239 | int viewMode = 0, effect = 0; | 232 | int viewMode = 0, effect = 0; |
| 240 | float exposureEv = 0.0f; // 露出(段、EV):倍率は2^EV / exposure in stops (EV): the multiplier is 2^EV | 233 | float exposureEv = 0.0f; // 露出(段、EV):倍率は2^EV / exposure in stops (EV): the multiplier is 2^EV |
| 241 | PostBlock postSettings; | 234 | PostBlock postSettings; |
| @@ -255,7 +248,7 @@ int main() { | |||
| 255 | printf("camera: %s\n", useOrbit ? "orbit" : "fps"); | 248 | printf("camera: %s\n", useOrbit ? "orbit" : "fps"); |
| 256 | } | 249 | } |
| 257 | if (key == GLFW_KEY_V) { | 250 | if (key == GLFW_KEY_V) { |
| 258 | viewMode = (viewMode + 1) % 6; | 251 | viewMode = (viewMode + 1) % kViewModes; |
| 259 | printf("view: %s\n", kViewModeNames[viewMode]); | 252 | printf("view: %s\n", kViewModeNames[viewMode]); |
| 260 | } | 253 | } |
| 261 | if (key >= GLFW_KEY_1 && key <= GLFW_KEY_6) { | 254 | if (key >= GLFW_KEY_1 && key <= GLFW_KEY_6) { |
| @@ -266,30 +259,15 @@ int main() { | |||
| 266 | exposureEv += key == GLFW_KEY_EQUAL ? 0.5f : -0.5f; | 259 | exposureEv += key == GLFW_KEY_EQUAL ? 0.5f : -0.5f; |
| 267 | printf("exposure: %+.1f EV (x%.3g)\n", exposureEv, std::exp2(exposureEv)); | 260 | printf("exposure: %+.1f EV (x%.3g)\n", exposureEv, std::exp2(exposureEv)); |
| 268 | } | 261 | } |
| 269 | if (key == GLFW_KEY_T) { | 262 | if (key == GLFW_KEY_M) { |
| 270 | postSettings.toneMapper = (postSettings.toneMapper + 1) % 3; | 263 | normalMaps = !normalMaps; |
| 271 | printf("tone mapping: %s\n", kToneMapperNames[postSettings.toneMapper]); | 264 | printf("normal maps: %s\n", normalMaps ? "on" : "off"); |
| 272 | } | ||
| 273 | if (key == GLFW_KEY_G) { | ||
| 274 | postSettings.gammaMode = (postSettings.gammaMode + 1) % 4; | ||
| 275 | printf("gamma: %s\n", kGammaNames[postSettings.gammaMode]); | ||
| 276 | } | 265 | } |
| 277 | if (key == GLFW_KEY_B) { | 266 | if (key == GLFW_KEY_X) { |
| 278 | bloomOn = !bloomOn; | 267 | parallax = !parallax; |
| 279 | printf("bloom: %s\n", bloomOn ? "on" : "off"); | 268 | printf("parallax mapping: %s\n", parallax ? "on" : "off"); |
| 280 | } | ||
| 281 | if (key == GLFW_KEY_K) { | ||
| 282 | // 太陽の向き(0.5, 1, 0.35)の反対側から、電線越しに見上げる / look up through the wires from the side opposite the | ||
| 283 | // sun (direction (0.5, 1, 0.35)) | ||
| 284 | useOrbit = false; | ||
| 285 | fps.position = {-3.2f, 1.7f, -7.4f}; | ||
| 286 | fps.yaw = radians(125.0f); | ||
| 287 | fps.pitch = radians(42.0f); | ||
| 288 | } | ||
| 289 | if (key == GLFW_KEY_O) { | ||
| 290 | postSettings.view = (postSettings.view + 1) % 4; | ||
| 291 | printf("post view: %s\n", kPostViewNames[postSettings.view]); | ||
| 292 | } | 269 | } |
| 270 | if (key == GLFW_KEY_L) movingLight = !movingLight; | ||
| 293 | if (key == GLFW_KEY_N) night = !night; | 271 | if (key == GLFW_KEY_N) night = !night; |
| 294 | if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; | 272 | if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; |
| 295 | if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; | 273 | if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; |
| @@ -310,14 +288,31 @@ int main() { | |||
| 310 | grassMaterial.specular = {0.04f, 0.04f, 0.04f}; | 288 | grassMaterial.specular = {0.04f, 0.04f, 0.04f}; |
| 311 | grassMaterial.shininess = 8.0f; | 289 | grassMaterial.shininess = 8.0f; |
| 312 | 290 | ||
| 313 | std::vector<Mat4> fence = makeFence(); | ||
| 314 | std::vector<Mat4> wires = makeWires(); | 291 | std::vector<Mat4> wires = makeWires(); |
| 315 | Material woodMaterial; | 292 | // レンガの壁(5 × 2.5 m、厚さ0.3 m)、柱、球。箱のUVはメートル単位で、1 mごとにテクスチャ1枚 |
| 293 | // 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 | ||
| 294 | Mesh wallMesh = makeBox({5.0f, 2.5f, 0.3f}); | ||
| 295 | Mesh pillarMesh = makeBox({0.6f, 3.0f, 0.6f}); | ||
| 296 | Mesh brickSphere = makeSphere(48, 24); | ||
| 297 | Material brickMaterial; | ||
| 298 | brickMaterial.diffuseMap = &*brickTexture; | ||
| 299 | brickMaterial.normalMap = &*brickNormal; | ||
| 300 | brickMaterial.specular = {0.08f, 0.08f, 0.08f}; | ||
| 301 | brickMaterial.shininess = 24.0f; | ||
| 302 | brickMaterial.parallaxScale = 0.04f; // 1枚(1 m)の4% = 4 cm の深さ / 4 % of a tile (1 m) = 4 cm deep | ||
| 303 | struct Piece { | ||
| 304 | const Mesh *mesh; | ||
| 305 | Mat4 model; | ||
| 306 | }; | ||
| 307 | const Piece bricks[] = { | ||
| 308 | {&wallMesh, translate({-1.6f, 1.25f, 4.2f})}, | ||
| 309 | {&pillarMesh, translate({1.6f, 1.5f, 4.4f}) * rotateY(0.3f)}, | ||
| 310 | {&brickSphere, translate({-2.3f, 0.6f, 6.9f}) * scale({1.2f, 1.2f, 1.2f})}, | ||
| 311 | }; | ||
| 312 | // 樽の置き場所 / where the barrels stand | ||
| 313 | 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}}; | ||
| 316 | // 手で選んだ色はsRGBの値(カラーピッカーの値):シェーダーはリニアで計算するので変換する | 314 | // 手で選んだ色はsRGBの値(カラーピッカーの値):シェーダーはリニアで計算するので変換する |
| 317 | // Hand-picked colours are sRGB values (what a colour picker shows): the shaders compute in linear space, so convert | 315 | // Hand-picked colours are sRGB values (what a colour picker shows): the shaders compute in linear space, so convert |
| 318 | woodMaterial.diffuse = srgbToLinear(Vec3{0.42f, 0.3f, 0.2f}); | ||
| 319 | woodMaterial.specular = {0.05f, 0.05f, 0.05f}; | ||
| 320 | woodMaterial.shininess = 8.0f; | ||
| 321 | Material wireMaterial; | 316 | Material wireMaterial; |
| 322 | wireMaterial.diffuse = srgbToLinear(Vec3{0.04f, 0.04f, 0.045f}); | 317 | wireMaterial.diffuse = srgbToLinear(Vec3{0.04f, 0.04f, 0.045f}); |
| 323 | wireMaterial.specular = {0.3f, 0.3f, 0.3f}; | 318 | wireMaterial.specular = {0.3f, 0.3f, 0.3f}; |
| @@ -328,6 +323,8 @@ int main() { | |||
| 328 | std::vector<Lantern> lanterns = makeLanterns(); | 323 | std::vector<Lantern> lanterns = makeLanterns(); |
| 329 | Mesh sphereMesh = makeSphere(24, 12); | 324 | Mesh sphereMesh = makeSphere(24, 12); |
| 330 | constexpr float kLanternGlow = 6.0f; | 325 | constexpr float kLanternGlow = 6.0f; |
| 326 | const Vec3 kMovingLightColor = {1.0f, 0.75f, 0.45f}; | ||
| 327 | Vec3 movingLightPos; | ||
| 331 | 328 | ||
| 332 | FullscreenTriangle fullscreen; | 329 | FullscreenTriangle fullscreen; |
| 333 | glEnable(GL_CULL_FACE); | 330 | glEnable(GL_CULL_FACE); |
| @@ -342,6 +339,8 @@ int main() { | |||
| 342 | 339 | ||
| 343 | phong->use(); | 340 | phong->use(); |
| 344 | phong->set("uViewMode", viewMode); | 341 | phong->set("uViewMode", viewMode); |
| 342 | phong->set("uNormalMapping", normalMaps ? 1 : 0); | ||
| 343 | phong->set("uParallaxMapping", parallax ? 1 : 0); | ||
| 345 | phong->set("uEnvironmentTint", environmentTint); | 344 | phong->set("uEnvironmentTint", environmentTint); |
| 346 | phong->set("uModel", Mat4::identity()); | 345 | phong->set("uModel", Mat4::identity()); |
| 347 | phong->set("uNormalMatrix", normalMatrix(Mat4::identity())); | 346 | phong->set("uNormalMatrix", normalMatrix(Mat4::identity())); |
| @@ -360,13 +359,28 @@ int main() { | |||
| 360 | phong->set("uNormalMatrix", normalMatrix(model)); | 359 | phong->set("uNormalMatrix", normalMatrix(model)); |
| 361 | sphereMesh.draw(); | 360 | sphereMesh.draw(); |
| 362 | } | 361 | } |
| 363 | for (const std::vector<Mat4> *list : {&fence, &wires}) { | 362 | wireMaterial.apply(*phong, white); |
| 364 | (list == &fence ? woodMaterial : wireMaterial).apply(*phong, white); | 363 | for (const Mat4 &m : wires) { |
| 365 | for (const Mat4 &m : *list) { | 364 | phong->set("uModel", m); |
| 366 | phong->set("uModel", m); | 365 | phong->set("uNormalMatrix", normalMatrix(m)); |
| 367 | phong->set("uNormalMatrix", normalMatrix(m)); | 366 | cubeMesh.draw(); |
| 368 | cubeMesh.draw(); | 367 | } |
| 369 | } | 368 | // レンガ(法線マップ+視差) / the bricks (normal map + parallax) |
| 369 | brickMaterial.apply(*phong, white); | ||
| 370 | for (const Piece &b : bricks) { | ||
| 371 | phong->set("uModel", b.model); | ||
| 372 | phong->set("uNormalMatrix", normalMatrix(b.model)); | ||
| 373 | b.mesh->draw(); | ||
| 374 | } | ||
| 375 | for (const Placement &b : barrels) barrel->draw(*phong, translate(b.position) * rotateY(b.angle), white, ModelPass::Opaque); | ||
| 376 | // 回る点光源の目印(HDRで光る) / the marker of the circling point light (glows in HDR) | ||
| 377 | if (movingLight) { | ||
| 378 | unlit->use(); | ||
| 379 | unlit->set("uColor", 8.0f * kMovingLightColor); | ||
| 380 | Mat4 model = translate(movingLightPos) * scale({0.08f, 0.08f, 0.08f}); | ||
| 381 | unlit->set("uModel", model); | ||
| 382 | sphereMesh.draw(); | ||
| 383 | phong->use(); | ||
| 370 | } | 384 | } |
| 371 | 385 | ||
| 372 | // 草:アルファトゥカバレッジならdiscardの代わりにサンプルの一部だけを覆う(MSAAのときだけ意味がある) | 386 | // 草:アルファトゥカバレッジならdiscardの代わりにサンプルの一部だけを覆う(MSAAのときだけ意味がある) |
| @@ -426,6 +440,9 @@ int main() { | |||
| 426 | Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; | 440 | Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; |
| 427 | 441 | ||
| 428 | float aspect = static_cast<float>(sceneFbo.width()) / static_cast<float>(sceneFbo.height()); | 442 | float aspect = static_cast<float>(sceneFbo.width()) / static_cast<float>(sceneFbo.height()); |
| 443 | // 壁の前を回る光:壁すれすれの角度から照らすと凹凸がよく見える / the light circling in front of the wall: light from | ||
| 444 | // grazing angles shows the bumps best | ||
| 445 | movingLightPos = {-1.6f + 1.8f * std::cos(0.7f * windmillTime), 1.3f + 0.6f * std::sin(1.3f * windmillTime), 4.75f}; | ||
| 429 | CameraBlock camera; | 446 | CameraBlock camera; |
| 430 | camera.view = useOrbit ? orbit.view() : fps.view(); | 447 | camera.view = useOrbit ? orbit.view() : fps.view(); |
| 431 | camera.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect); | 448 | camera.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect); |
| @@ -451,12 +468,23 @@ int main() { | |||
| 451 | for (size_t i = 3; i < 6; ++i) | 468 | for (size_t i = 3; i < 6; ++i) |
| 452 | lights.points.push_back({.position = lanterns[i].position, .color = 1.5f * lanterns[i].color, .attenuation = kMediumRange}); | 469 | lights.points.push_back({.position = lanterns[i].position, .color = 1.5f * lanterns[i].color, .attenuation = kMediumRange}); |
| 453 | } | 470 | } |
| 471 | if (movingLight) | ||
| 472 | lights.points.push_back({.position = movingLightPos, .color = 2.5f * kMovingLightColor, .attenuation = kMediumRange}); | ||
| 454 | if (flashlightOn) | 473 | if (flashlightOn) |
| 455 | lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); | 474 | lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); |
| 456 | lightsUbo.update(lights.toBlock()); | 475 | lightsUbo.update(lights.toBlock()); |
| 457 | environmentTint = night ? Vec3{0.02f, 0.025f, 0.05f} : Vec3{1.0f, 1.0f, 1.0f}; | 476 | environmentTint = night ? Vec3{0.02f, 0.025f, 0.05f} : Vec3{1.0f, 1.0f, 1.0f}; |
| 458 | postSettings.exposure = std::exp2(exposureEv); | 477 | postSettings.exposure = std::exp2(exposureEv); |
| 459 | postSettings.bloomStrength = bloomOn ? 0.08f : 0.0f; | 478 | postSettings.bloomStrength = 0.08f; |
| 479 | // ベクトルの表示(法線・接線)は値をそのまま見せる:トーンマッピングなし、露出1(phong.fragが逆変換して出す) | ||
| 480 | // The vector views (normals, tangents) show the raw values: no tone mapping, exposure 1 (phong.frag outputs them | ||
| 481 | // pre-decoded) | ||
| 482 | if (viewMode >= kFirstVectorView) { | ||
| 483 | postSettings.exposure = 1.0f; | ||
| 484 | postSettings.toneMapper = static_cast<int>(ToneMapper::Clamp); | ||
| 485 | } else { | ||
| 486 | postSettings.toneMapper = static_cast<int>(ToneMapper::Aces); | ||
| 487 | } | ||
| 460 | postUbo.update(postSettings); | 488 | postUbo.update(postSettings); |
| 461 | 489 | ||
| 462 | //------------------------------------------------------------------ | 490 | //------------------------------------------------------------------ |
ファイル: a/src/material.cc | b/src/material.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -16,4 +16,7 @@ void Material::apply(const Shader &shader, const Texture2D &white) const { | |||
| 16 | (diffuseMap ? diffuseMap : &white)->bind(0); | 16 | (diffuseMap ? diffuseMap : &white)->bind(0); |
| 17 | (specularMap ? specularMap : &white)->bind(1); | 17 | (specularMap ? specularMap : &white)->bind(1); |
| 18 | (emissionMap ? emissionMap : &white)->bind(2); | 18 | (emissionMap ? emissionMap : &white)->bind(2); |
| 19 | shader.set("uMaterial.normalScale", normalMap ? normalScale : 0.0f); | ||
| 20 | shader.set("uMaterial.parallaxScale", normalMap ? parallaxScale : 0.0f); | ||
| 21 | (normalMap ? normalMap : &white)->bind(4); | ||
| 19 | } | 22 | } |
ファイル: a/src/material.hh | b/src/material.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -35,8 +35,17 @@ struct Material { | |||
| 35 | const Texture2D *diffuseMap = nullptr; // テクスチャユニット0 / texture unit 0 | 35 | const Texture2D *diffuseMap = nullptr; // テクスチャユニット0 / texture unit 0 |
| 36 | const Texture2D *specularMap = nullptr; // テクスチャユニット1 / texture unit 1 | 36 | const Texture2D *specularMap = nullptr; // テクスチャユニット1 / texture unit 1 |
| 37 | const Texture2D *emissionMap = nullptr; // テクスチャユニット2 / texture unit 2 | 37 | const Texture2D *emissionMap = nullptr; // テクスチャユニット2 / texture unit 2 |
| 38 | // 法線マップ(第22章):接線空間の法線(RGB、リニア)。Aは視差マッピング用の高さ(1 = 一番高い) | ||
| 39 | // Normal map (chapter 22): tangent-space normals (RGB, linear). A = height for parallax mapping (1 = highest) | ||
| 40 | const Texture2D *normalMap = nullptr; // テクスチャユニット4 / texture unit 4 | ||
| 41 | float normalScale = 1.0f; // 凹凸の強さ(glTFのnormalTexture.scale:xyに掛ける) / bump strength (glTF's | ||
| 42 | // normalTexture.scale: multiplies x and y) | ||
| 43 | float parallaxScale = 0.0f; // 視差の深さ(UVの単位、0 = なし)。OpenGLのUV(vが上)の物だけ / parallax depth (in UV | ||
| 44 | // units, 0 = none). Only for OpenGL-convention UVs (v up) | ||
| 38 | 45 | ||
| 39 | // シェーダーのuMaterialを設定し、マップをユニット0〜2に繋ぐ。nullptrのマップの代わりにwhiteを繋ぐ。 | 46 | // シェーダーのuMaterialを設定し、マップをユニット0〜2と4に繋ぐ。nullptrのマップの代わりにwhiteを繋ぐ。 |
| 40 | // Sets the shader's uMaterial and binds the maps to units 0..2. Binds `white` in place of a nullptr map. | 47 | // 法線マップがなければnormalScaleを0にする:白(1,1,1)の法線は(0,0,1)になり、凹凸なし(フラグは要らない)。 |
| 48 | // Sets the shader's uMaterial and binds the maps to units 0..2 and 4. Binds `white` in place of a nullptr map. | ||
| 49 | // Without a normal map normalScale is set to 0: the white (1,1,1) normal becomes (0,0,1), no bumps (no flag needed). | ||
| 41 | void apply(const Shader &shader, const Texture2D &white) const; | 50 | void apply(const Shader &shader, const Texture2D &white) const; |
| 42 | }; | 51 | }; |
ファイル: a/src/mesh.hh | b/src/mesh.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -23,8 +23,9 @@ struct VertexAttrib { | |||
| 23 | GLboolean normalized = GL_FALSE; // 整数を0〜1にするか / map integers to 0..1? | 23 | GLboolean normalized = GL_FALSE; // 整数を0〜1にするか / map integers to 0..1? |
| 24 | }; | 24 | }; |
| 25 | 25 | ||
| 26 | // 3Dの標準の頂点:位置・法線・UV。シェーダーではlocation 0, 1, 2。 | 26 | // 3Dの標準の頂点:位置・法線・UV。シェーダーではlocation 0, 1, 2。第22章からshapes.ccは接線付きのModelVertexを使う。 |
| 27 | // The standard 3D vertex: position, normal, UV. Locations 0, 1, 2 in the shaders. | 27 | // The standard 3D vertex: position, normal, UV. Locations 0, 1, 2 in the shaders. From chapter 22 shapes.cc uses |
| 28 | // ModelVertex, which also has a tangent. | ||
| 28 | struct Vertex3D { | 29 | struct Vertex3D { |
| 29 | Vec3 position; | 30 | Vec3 position; |
| 30 | Vec3 normal; // 面の向き(第10章のライティングで使う) / which way the surface faces (used for lighting in chapter 10) | 31 | Vec3 normal; // 面の向き(第10章のライティングで使う) / which way the surface faces (used for lighting in chapter 10) |
ファイル: a/src/model.cc | b/src/model.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,5 +1,7 @@ | |||
| 1 | #include "model.hh" | 1 | #include "model.hh" |
| 2 | 2 | ||
| 3 | #include "tangents.hh" | ||
| 4 | |||
| 3 | #include <algorithm> | 5 | #include <algorithm> |
| 4 | #include <cmath> | 6 | #include <cmath> |
| 5 | #include <cstdio> | 7 | #include <cstdio> |
| @@ -128,6 +130,14 @@ static std::optional<Model::Primitive> loadPrimitive(const Gltf &g, const GltfPr | |||
| 128 | indices.clear(); | 130 | indices.clear(); |
| 129 | } | 131 | } |
| 130 | 132 | ||
| 133 | // 法線マップがあるのにTANGENTがなければ自分で計算する(glTFの仕様はMikkTSpaceを勧めるが、ここでは簡単な方法、第22章) | ||
| 134 | // A normal map but no TANGENT: compute them ourselves (the glTF spec recommends MikkTSpace; we use the simple | ||
| 135 | // method, chapter 22) | ||
| 136 | bool normalMapped = p.material >= 0 && static_cast<size_t>(p.material) < g.materials.size() && | ||
| 137 | g.materials[static_cast<size_t>(p.material)].normalTexture.index >= 0; | ||
| 138 | if (normalMapped && !tangents && uvs && p.mode == kGltfTriangles) | ||
| 139 | computeTangents(vertices, indices, UvConvention::Gltf); | ||
| 140 | |||
| 131 | Model::Primitive out; | 141 | Model::Primitive out; |
| 132 | out.material = p.material; | 142 | out.material = p.material; |
| 133 | out.boundsMin = out.boundsMax = vertices.empty() ? Vec3{} : vertices[0].position; | 143 | out.boundsMin = out.boundsMax = vertices.empty() ? Vec3{} : vertices[0].position; |
| @@ -357,6 +367,8 @@ void Model::drawItems(const std::vector<DrawItem> &items, const Shader &shader, | |||
| 357 | Material m = md.phong; | 367 | Material m = md.phong; |
| 358 | m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture | 368 | m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture |
| 359 | m.emissionMap = texture(md.pbr.emissiveTexture.index); | 369 | m.emissionMap = texture(md.pbr.emissiveTexture.index); |
| 370 | m.normalMap = texture(md.pbr.normalTexture.index); // 第22章 / chapter 22 | ||
| 371 | m.normalScale = md.pbr.normalTexture.scale; | ||
| 360 | m.apply(shader, *white); | 372 | m.apply(shader, *white); |
| 361 | } | 373 | } |
| 362 | // 両面のマテリアル(葉、ガラス、帆)は裏からも見えるようにカリングを切る | 374 | // 両面のマテリアル(葉、ガラス、帆)は裏からも見えるようにカリングを切る |
ファイル: a/src/shapes.cc | b/src/shapes.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,25 +1,45 @@ | |||
| 1 | #include "shapes.hh" | 1 | #include "shapes.hh" |
| 2 | 2 | ||
| 3 | #include "tangents.hh" | ||
| 4 | |||
| 3 | #include <cmath> | 5 | #include <cmath> |
| 4 | #include <vector> | 6 | #include <vector> |
| 5 | 7 | ||
| 6 | // 一つの面(正方形)を足す。normal = 外向き、right × up = normal になるように選ぶ。 | 8 | // 一つの面(正方形)を足す。normal = 外向き、right × up = normal になるように選ぶ。 |
| 7 | // Adds one face (a square). normal points outwards; choose right and up so that right × up = normal. | 9 | // Adds one face (a square). normal points outwards; choose right and up so that right × up = normal. |
| 8 | static void addFace(std::vector<Vertex3D> &vertices, std::vector<std::uint32_t> &indices, Vec3 normal, Vec3 right, | 10 | static void addFace(std::vector<ModelVertex> &vertices, std::vector<std::uint32_t> &indices, Vec3 normal, Vec3 right, |
| 9 | Vec3 up) { | 11 | Vec3 up, Vec3 half = {0.5f, 0.5f, 0.5f}, float tile = 0.0f) { |
| 10 | std::uint32_t first = static_cast<std::uint32_t>(vertices.size()); | 12 | std::uint32_t first = static_cast<std::uint32_t>(vertices.size()); |
| 11 | Vec3 c = 0.5f * normal; // 面の中心 / centre of the face | 13 | auto extent = [&](Vec3 axis) { return std::fabs(axis.x) * half.x + std::fabs(axis.y) * half.y + std::fabs(axis.z) * half.z; }; |
| 12 | Vec3 r = 0.5f * right, u = 0.5f * up; | 14 | Vec3 c = extent(normal) * normal; // 面の中心 / centre of the face |
| 13 | vertices.push_back({c - r - u, normal, {0.0f, 0.0f}}); // 左下 / bottom left | 15 | Vec3 r = extent(right) * right, u = extent(up) * up; |
| 14 | vertices.push_back({c + r - u, normal, {1.0f, 0.0f}}); // 右下 / bottom right | 16 | // tile > 0:UVはメートル÷tile(面の大きさに合わせて繰り返す)、0:面ごとに0〜1 / tile > 0: UV = metres ÷ tile |
| 15 | vertices.push_back({c + r + u, normal, {1.0f, 1.0f}}); // 右上 / top right | 17 | // (repeats with the face size); 0: 0..1 per face |
| 16 | vertices.push_back({c - r + u, normal, {0.0f, 1.0f}}); // 左上 / top left | 18 | float su = tile > 0.0f ? 2.0f * extent(right) / tile : 1.0f, sv = tile > 0.0f ? 2.0f * extent(up) / tile : 1.0f; |
| 19 | vertices.push_back({c - r - u, normal, {0.0f, 0.0f}, {}}); // 左下 / bottom left | ||
| 20 | vertices.push_back({c + r - u, normal, {su, 0.0f}, {}}); // 右下 / bottom right | ||
| 21 | vertices.push_back({c + r + u, normal, {su, sv}, {}}); // 右上 / top right | ||
| 22 | vertices.push_back({c - r + u, normal, {0.0f, sv}, {}}); // 左上 / top left | ||
| 17 | // 反時計回りの三角形2つ / two counter-clockwise triangles | 23 | // 反時計回りの三角形2つ / two counter-clockwise triangles |
| 18 | indices.insert(indices.end(), {first, first + 1, first + 2, first + 2, first + 3, first}); | 24 | indices.insert(indices.end(), {first, first + 1, first + 2, first + 2, first + 3, first}); |
| 19 | } | 25 | } |
| 20 | 26 | ||
| 27 | Mesh makeBox(Vec3 size, float tileSize) { | ||
| 28 | std::vector<ModelVertex> vertices; | ||
| 29 | std::vector<std::uint32_t> indices; | ||
| 30 | Vec3 h = 0.5f * size; | ||
| 31 | addFace(vertices, indices, {0, 0, 1}, {1, 0, 0}, {0, 1, 0}, h, tileSize); | ||
| 32 | addFace(vertices, indices, {0, 0, -1}, {-1, 0, 0}, {0, 1, 0}, h, tileSize); | ||
| 33 | addFace(vertices, indices, {1, 0, 0}, {0, 0, -1}, {0, 1, 0}, h, tileSize); | ||
| 34 | addFace(vertices, indices, {-1, 0, 0}, {0, 0, 1}, {0, 1, 0}, h, tileSize); | ||
| 35 | addFace(vertices, indices, {0, 1, 0}, {1, 0, 0}, {0, 0, -1}, h, tileSize); | ||
| 36 | addFace(vertices, indices, {0, -1, 0}, {1, 0, 0}, {0, 0, 1}, h, tileSize); | ||
| 37 | computeTangents(vertices, indices, UvConvention::OpenGl); | ||
| 38 | return Mesh(vertices, indices, kModelVertexLayout); | ||
| 39 | } | ||
| 40 | |||
| 21 | Mesh makeCube() { | 41 | Mesh makeCube() { |
| 22 | std::vector<Vertex3D> vertices; | 42 | std::vector<ModelVertex> vertices; |
| 23 | std::vector<std::uint32_t> indices; | 43 | std::vector<std::uint32_t> indices; |
| 24 | addFace(vertices, indices, {0, 0, 1}, {1, 0, 0}, {0, 1, 0}); // 前 +Z / front | 44 | addFace(vertices, indices, {0, 0, 1}, {1, 0, 0}, {0, 1, 0}); // 前 +Z / front |
| 25 | addFace(vertices, indices, {0, 0, -1}, {-1, 0, 0}, {0, 1, 0}); // 後 -Z / back | 45 | addFace(vertices, indices, {0, 0, -1}, {-1, 0, 0}, {0, 1, 0}); // 後 -Z / back |
| @@ -27,24 +47,27 @@ Mesh makeCube() { | |||
| 27 | addFace(vertices, indices, {-1, 0, 0}, {0, 0, 1}, {0, 1, 0}); // 左 -X / left | 47 | addFace(vertices, indices, {-1, 0, 0}, {0, 0, 1}, {0, 1, 0}); // 左 -X / left |
| 28 | addFace(vertices, indices, {0, 1, 0}, {1, 0, 0}, {0, 0, -1}); // 上 +Y / top | 48 | addFace(vertices, indices, {0, 1, 0}, {1, 0, 0}, {0, 0, -1}); // 上 +Y / top |
| 29 | addFace(vertices, indices, {0, -1, 0}, {1, 0, 0}, {0, 0, 1}); // 下 -Y / bottom | 49 | addFace(vertices, indices, {0, -1, 0}, {1, 0, 0}, {0, 0, 1}); // 下 -Y / bottom |
| 30 | return Mesh(vertices, indices, kVertex3DLayout); | 50 | computeTangents(vertices, indices, UvConvention::OpenGl); |
| 51 | return Mesh(vertices, indices, kModelVertexLayout); | ||
| 31 | } | 52 | } |
| 32 | 53 | ||
| 33 | Mesh makePlane(float size, float uvRepeat) { | 54 | Mesh makePlane(float size, float uvRepeat) { |
| 34 | float h = 0.5f * size; | 55 | float h = 0.5f * size; |
| 35 | Vec3 n = {0.0f, 1.0f, 0.0f}; | 56 | Vec3 n = {0.0f, 1.0f, 0.0f}; |
| 36 | // 上から見て反時計回り / counter-clockwise seen from above | 57 | // 上から見て反時計回り / counter-clockwise seen from above |
| 37 | std::vector<Vertex3D> vertices = { | 58 | std::vector<ModelVertex> vertices = { |
| 38 | {{-h, 0.0f, h}, n, {0.0f, 0.0f}}, | 59 | {{-h, 0.0f, h}, n, {0.0f, 0.0f}, {}}, |
| 39 | {{h, 0.0f, h}, n, {uvRepeat, 0.0f}}, | 60 | {{h, 0.0f, h}, n, {uvRepeat, 0.0f}, {}}, |
| 40 | {{h, 0.0f, -h}, n, {uvRepeat, uvRepeat}}, | 61 | {{h, 0.0f, -h}, n, {uvRepeat, uvRepeat}, {}}, |
| 41 | {{-h, 0.0f, -h}, n, {0.0f, uvRepeat}}, | 62 | {{-h, 0.0f, -h}, n, {0.0f, uvRepeat}, {}}, |
| 42 | }; | 63 | }; |
| 43 | return Mesh(vertices, {0, 1, 2, 2, 3, 0}, kVertex3DLayout); | 64 | std::vector<std::uint32_t> indices = {0, 1, 2, 2, 3, 0}; |
| 65 | computeTangents(vertices, indices, UvConvention::OpenGl); | ||
| 66 | return Mesh(vertices, indices, kModelVertexLayout); | ||
| 44 | } | 67 | } |
| 45 | 68 | ||
| 46 | Mesh makeSphere(int segments, int rings) { | 69 | Mesh makeSphere(int segments, int rings) { |
| 47 | std::vector<Vertex3D> vertices; | 70 | std::vector<ModelVertex> vertices; |
| 48 | std::vector<std::uint32_t> indices; | 71 | std::vector<std::uint32_t> indices; |
| 49 | for (int r = 0; r <= rings; ++r) { | 72 | for (int r = 0; r <= rings; ++r) { |
| 50 | float phi = PI * static_cast<float>(r) / static_cast<float>(rings); // 0 = 北極、π = 南極 / 0 = north pole, π = south pole | 73 | float phi = PI * static_cast<float>(r) / static_cast<float>(rings); // 0 = 北極、π = 南極 / 0 = north pole, π = south pole |
| @@ -53,7 +76,7 @@ Mesh makeSphere(int segments, int rings) { | |||
| 53 | float theta = 2.0f * PI * static_cast<float>(s) / static_cast<float>(segments); | 76 | float theta = 2.0f * PI * static_cast<float>(s) / static_cast<float>(segments); |
| 54 | Vec3 n = {std::sin(phi) * std::sin(theta), std::cos(phi), std::sin(phi) * std::cos(theta)}; | 77 | Vec3 n = {std::sin(phi) * std::sin(theta), std::cos(phi), std::sin(phi) * std::cos(theta)}; |
| 55 | Vec2 uv = {static_cast<float>(s) / static_cast<float>(segments), 1.0f - static_cast<float>(r) / static_cast<float>(rings)}; | 78 | Vec2 uv = {static_cast<float>(s) / static_cast<float>(segments), 1.0f - static_cast<float>(r) / static_cast<float>(rings)}; |
| 56 | vertices.push_back({0.5f * n, n, uv}); | 79 | vertices.push_back({0.5f * n, n, uv, {}}); |
| 57 | } | 80 | } |
| 58 | } | 81 | } |
| 59 | // 隣り合う二つの輪の間を四角形(三角形2つ)で埋める。極の潰れた三角形は省く。 | 82 | // 隣り合う二つの輪の間を四角形(三角形2つ)で埋める。極の潰れた三角形は省く。 |
| @@ -67,22 +90,24 @@ Mesh makeSphere(int segments, int rings) { | |||
| 67 | if (r != 0) indices.insert(indices.end(), {a, b + 1, a + 1}); | 90 | if (r != 0) indices.insert(indices.end(), {a, b + 1, a + 1}); |
| 68 | } | 91 | } |
| 69 | } | 92 | } |
| 70 | return Mesh(vertices, indices, kVertex3DLayout); | 93 | computeTangents(vertices, indices, UvConvention::OpenGl); |
| 94 | return Mesh(vertices, indices, kModelVertexLayout); | ||
| 71 | } | 95 | } |
| 72 | 96 | ||
| 73 | Mesh makeCrossedQuads(int count) { | 97 | Mesh makeCrossedQuads(int count) { |
| 74 | std::vector<Vertex3D> vertices; | 98 | std::vector<ModelVertex> vertices; |
| 75 | std::vector<std::uint32_t> indices; | 99 | std::vector<std::uint32_t> indices; |
| 76 | Vec3 up = {0.0f, 1.0f, 0.0f}; | 100 | Vec3 up = {0.0f, 1.0f, 0.0f}; |
| 77 | for (int i = 0; i < count; ++i) { | 101 | for (int i = 0; i < count; ++i) { |
| 78 | float a = PI * static_cast<float>(i) / static_cast<float>(count); // 0〜180度(板は両面なので) / 0..180° (quads are two-sided) | 102 | float a = PI * static_cast<float>(i) / static_cast<float>(count); // 0〜180度(板は両面なので) / 0..180° (quads are two-sided) |
| 79 | Vec3 r = {0.5f * std::cos(a), 0.0f, -0.5f * std::sin(a)}; // 板の右半分 / half the quad, to the right | 103 | Vec3 r = {0.5f * std::cos(a), 0.0f, -0.5f * std::sin(a)}; // 板の右半分 / half the quad, to the right |
| 80 | std::uint32_t first = static_cast<std::uint32_t>(vertices.size()); | 104 | std::uint32_t first = static_cast<std::uint32_t>(vertices.size()); |
| 81 | vertices.push_back({-1.0f * r, up, {0.0f, 0.0f}}); | 105 | vertices.push_back({-1.0f * r, up, {0.0f, 0.0f}, {}}); |
| 82 | vertices.push_back({r, up, {1.0f, 0.0f}}); | 106 | vertices.push_back({r, up, {1.0f, 0.0f}, {}}); |
| 83 | vertices.push_back({r + up, up, {1.0f, 1.0f}}); | 107 | vertices.push_back({r + up, up, {1.0f, 1.0f}, {}}); |
| 84 | vertices.push_back({up - r, up, {0.0f, 1.0f}}); | 108 | vertices.push_back({up - r, up, {0.0f, 1.0f}, {}}); |
| 85 | indices.insert(indices.end(), {first, first + 1, first + 2, first + 2, first + 3, first}); | 109 | indices.insert(indices.end(), {first, first + 1, first + 2, first + 2, first + 3, first}); |
| 86 | } | 110 | } |
| 87 | return Mesh(vertices, indices, kVertex3DLayout); | 111 | computeTangents(vertices, indices, UvConvention::OpenGl); |
| 112 | return Mesh(vertices, indices, kModelVertexLayout); | ||
| 88 | } | 113 | } |
ファイル: a/src/shapes.hh | b/src/shapes.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,8 +1,15 @@ | |||
| 1 | // よく使う形のメッシュを作る / builds meshes for common shapes | 1 | // よく使う形のメッシュを作る。頂点はModelVertex(位置・法線・UV・接線、第22章から)、UVはOpenGLの決まり(vが上へ) |
| 2 | // builds meshes for common shapes. Vertices are ModelVertex (position, normal, UV, tangent; from chapter 22), UVs | ||
| 3 | // in the OpenGL convention (v grows upwards) | ||
| 2 | #pragma once | 4 | #pragma once |
| 3 | 5 | ||
| 4 | #include "mesh.hh" | 6 | #include "mesh.hh" |
| 5 | 7 | ||
| 8 | // 原点を中心とした大きさsizeの箱。UVはメートル単位でtileSizeごとに繰り返す(伸びない:壁、柱、段に。第22章) | ||
| 9 | // A box of the given size centred on the origin. UVs are in metres, repeating every tileSize (no stretching: for walls, | ||
| 10 | // pillars, steps; chapter 22) | ||
| 11 | Mesh makeBox(Vec3 size, float tileSize = 1.0f); | ||
| 12 | |||
| 6 | // 原点を中心とした1×1×1の立方体。面ごとに頂点4つ(UVと法線が面ごとに違うので共有できない)=24頂点、36インデックス。 | 13 | // 原点を中心とした1×1×1の立方体。面ごとに頂点4つ(UVと法線が面ごとに違うので共有できない)=24頂点、36インデックス。 |
| 7 | // 外から見て反時計回り(第16章のカリング用)。 | 14 | // 外から見て反時計回り(第16章のカリング用)。 |
| 8 | // A 1×1×1 cube centred on the origin. 4 vertices per face (UVs and normals differ per face, so corners | 15 | // A 1×1×1 cube centred on the origin. 4 vertices per face (UVs and normals differ per face, so corners |
ファイル: /dev/null | b/src/tangents.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,45 @@ | |||
| 1 | #include "tangents.hh" | ||
| 2 | |||
| 3 | #include <cmath> | ||
| 4 | |||
| 5 | void computeTangents(std::vector<ModelVertex> &vertices, const std::vector<std::uint32_t> &indices, | ||
| 6 | UvConvention convention) { | ||
| 7 | size_t n = vertices.size(); | ||
| 8 | std::vector<Vec3> tangent(n), bitangent(n); | ||
| 9 | size_t corners = indices.empty() ? n : indices.size(); | ||
| 10 | for (size_t t = 0; t + 2 < corners; t += 3) { | ||
| 11 | std::uint32_t i0 = indices.empty() ? static_cast<std::uint32_t>(t) : indices[t]; | ||
| 12 | std::uint32_t i1 = indices.empty() ? static_cast<std::uint32_t>(t + 1) : indices[t + 1]; | ||
| 13 | std::uint32_t i2 = indices.empty() ? static_cast<std::uint32_t>(t + 2) : indices[t + 2]; | ||
| 14 | const ModelVertex &a = vertices[i0], &b = vertices[i1], &c = vertices[i2]; | ||
| 15 | Vec3 e1 = b.position - a.position, e2 = c.position - a.position; | ||
| 16 | Vec2 d1 = b.uv - a.uv, d2 = c.uv - a.uv; | ||
| 17 | // e1 = d1.x T + d1.y B、e2 = d2.x T + d2.y B を T(∂P/∂u)と B(∂P/∂v)について解く(2×2の逆行列) | ||
| 18 | // Solve e1 = d1.x T + d1.y B, e2 = d2.x T + d2.y B for T (∂P/∂u) and B (∂P/∂v) (a 2 × 2 inverse) | ||
| 19 | float det = d1.x * d2.y - d2.x * d1.y; | ||
| 20 | if (std::fabs(det) < 1e-12f) continue; // UVが潰れた三角形 / a triangle with degenerate UVs | ||
| 21 | float r = 1.0f / det; | ||
| 22 | Vec3 tu = r * (d2.y * e1 - d1.y * e2); | ||
| 23 | Vec3 bv = r * (d1.x * e2 - d2.x * e1); | ||
| 24 | // 正規化せずに足す:テクスチャを大きく引き伸ばす三角形ほど重みが大きい / summed unnormalized: triangles that | ||
| 25 | // stretch the texture more weigh more | ||
| 26 | for (std::uint32_t i : {i0, i1, i2}) { | ||
| 27 | tangent[i] = tangent[i] + tu; | ||
| 28 | bitangent[i] = bitangent[i] + bv; | ||
| 29 | } | ||
| 30 | } | ||
| 31 | for (size_t i = 0; i < n; ++i) { | ||
| 32 | Vec3 nrm = vertices[i].normal; | ||
| 33 | // グラム・シュミット:法線の成分を引いて垂直にする / Gram-Schmidt: remove the normal component | ||
| 34 | Vec3 t = tangent[i] - dot(nrm, tangent[i]) * nrm; | ||
| 35 | if (dot(t, t) < 1e-12f) { | ||
| 36 | // UVがない・潰れている:法線に垂直なら何でも良い / no usable UVs: any direction perpendicular to the normal | ||
| 37 | t = cross(std::fabs(nrm.y) < 0.99f ? Vec3{0.0f, 1.0f, 0.0f} : Vec3{1.0f, 0.0f, 0.0f}, nrm); | ||
| 38 | } | ||
| 39 | t = normalize(t); | ||
| 40 | // 画像の「上」:OpenGLの決まりでは+v、glTFでは-v / the image's "up": +v in the OpenGL convention, -v in glTF | ||
| 41 | Vec3 up = convention == UvConvention::OpenGl ? bitangent[i] : -bitangent[i]; | ||
| 42 | float w = dot(cross(nrm, t), up) < 0.0f ? -1.0f : 1.0f; // 鏡像のUVなら-1 / -1 for mirrored UVs | ||
| 43 | vertices[i].tangent = {t.x, t.y, t.z, w}; | ||
| 44 | } | ||
| 45 | } | ||
ファイル: /dev/null | b/src/tangents.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,24 @@ | |||
| 1 | // 接線の計算(第22章):法線マップの「右」と「上」が、表面のどの向きかを頂点ごとに求める | ||
| 2 | // Computing tangents (chapter 22): for every vertex, which surface directions a normal map's "right" and "up" are | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include "mesh.hh" | ||
| 6 | |||
| 7 | #include <cstdint> | ||
| 8 | #include <vector> | ||
| 9 | |||
| 10 | // UVの向きの決まり / which way the image's "up" runs in UV space | ||
| 11 | enum class UvConvention { | ||
| 12 | OpenGl, // vが上へ増える(stb_imageで反転して読んだ画像、shapes.cc) / v grows upwards (images loaded flipped, shapes.cc) | ||
| 13 | Gltf, // vが下へ増える(glTF:画像を反転しない) / v grows downwards (glTF: images are not flipped) | ||
| 14 | }; | ||
| 15 | |||
| 16 | // 三角形の位置とUVの変化から接線(uが増える向き)を求め、頂点ごとに足して、法線に垂直にして正規化する | ||
| 17 | // (グラム・シュミット)。wは従法線の向き:cross(normal, tangent.xyz) * w が画像の「上」を向くように±1。 | ||
| 18 | // indicesが空なら頂点を3つずつ三角形として使う。三角形(GL_TRIANGLES)だけ。 | ||
| 19 | // Computes tangents (the direction in which u grows) from each triangle's position and UV differences, sums them | ||
| 20 | // per vertex, then makes them perpendicular to the normal and normalizes them (Gram-Schmidt). w is the bitangent's | ||
| 21 | // sign: ±1 so that cross(normal, tangent.xyz) * w points to the image's "up". With empty indices, every three | ||
| 22 | // vertices form a triangle. Triangles (GL_TRIANGLES) only. | ||
| 23 | void computeTangents(std::vector<ModelVertex> &vertices, const std::vector<std::uint32_t> &indices, | ||
| 24 | UvConvention uv); | ||
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。