19. ユニフォームバッファとインスタンシング

此の章では、レンダラーを大きく出来る2つの事を扱います。
シェーダー同士でデータを共有する事と、1つの物を沢山描く事です。
第5章からずっと、ユニフォームは1つのシェーダープログラムの物でした。
其の為カメラの行列はプログラム毎に設定し直し、第12章からは光だけでプログラム毎・フレーム毎に何十回もsetを呼んでいました。
そして全ての物が少なくとも描画呼び出し1回を使っていました。
第8章では10個の立方体を10回の呼び出しで描き、第14章では「もっと良い方法がある」と約束しました。

1つ目の問題はユニフォームバッファオブジェクト(UBO)で解決します。
カメラと全ての光を2つのメモリの塊に移し、フレーム毎に1回書いて、全部のシェーダーが其れを読みます。
其の為にはstd140のレイアウトの規則を覚える必要があります。
C++の構造体のバイトが、GPUが読む位置と揃わなければならないからです。
2つ目の問題はインスタンシングで解決します。
何千個もの岩の環を描画呼び出し1回で描き、其々が自分の位置、大きさ、回転、色を持ち、小さな太陽系の様な速さでシーンの周りを回ります。
最後に違いを測りますが、あたし達の測定で何が分かり、何が分からないかについては正直に話します。

19.1 此の章で作る物

第14章のジオラマが、大きな平たい岩に乗って空に浮かんでいます。
其の周りを岩の環が回り、内側の岩程速く動きます。
既定では岩は4000個で、=と−で250から64 000迄変えられます。

空に浮かぶジオラマ。風車の島が大きな平たい岩の上に乗り、大きさの違う灰色と茶色の岩の広い環に囲まれている

操作:

  • W、A、S、D、スペース、左Ctrl、Shift、マウス、ホイール:今迄通り移動と見回し
  • I:インスタンシング(描画呼び出し1回) ⇔ 岩1つに付き描画呼び出し1回(新規)
  • =と−:岩の数を倍又は半分に、250〜64 000(新規)
  • P:風車と環を止める・動かす(環も止まる様になりました)
  • 1〜6:第17章のポストプロセスの効果
  • C:FPS ⇔ オービットカメラ、V:表示モード、N:昼 ⇔ 夜、F:懐中電灯
  • Tab:カーソルの解放、R:シェーダーを読み直す、Esc:終了

60フレーム毎に、岩の数、描画呼び出しの数、2つの時間がウィンドウのタイトルとターミナルに出ます。

第18章からの変更:

  • src/uniforms.hh(新規):結合点の番号、CameraBlock、UniformBufferクラス
  • src/lights.hhとsrc/lights.cc:std140に合わせた構造体、LightsBlock、apply(shader)の代わりのLightSet::toBlock()
  • src/buffer.hhとsrc/buffer.cc:update()とbindBase()
  • src/shader.hhとsrc/shader.cc:uniformBlockSize()とcheckUniformBlock()
  • src/mesh.hhとsrc/mesh.cc:InstanceData、kInstanceLayout、setInstanceBuffer()、drawInstanced()
  • src/model.hhとsrc/model.cc:モデル全体の為の同じ2つの関数
  • src/gpu_timer.hhとsrc/gpu_timer.cc(新規):タイマークエリ
  • shaders/phong_instanced.vert(新規)。カメラを使う全てのシェーダーがCameraブロックを宣言する様に
  • src/main.cc:新しいシーン。カメラと光はフレーム毎に1回だけ書く
  • assets/models/rock.glb(新規、6.8 KB):ゴツゴツした岩、頂点162個、三角形320枚(完成したファイルは章のZIPとアセットのZIPのch19/に入っています)

シーンが新しいので、床、木箱、第18章のガラス・金・クロムの物は無くなり、キーのM、K、Xも一緒に無くなりました。
スカイボックス、テクスチャユニット3からの金属の映り込み、ポストプロセスのパスは残っています。
envmap.frag、depth.frag、unlit.vertはまだshaders/にあるので、後の章で又使えます。
envmap.fragとunlit.vertはカメラのブロックに書き換えてあります(depth.fragはカメラのユニフォームを読みません)。

19.2 ユニフォームはプログラムの物

第18章が1フレームを描く方法を、カメラだけに絞ると此うなります:

    phong->use();
    phong->set("uView", v.view);
    phong->set("uProj", v.proj);
    phong->set("uViewPos", v.position);

同じ行がenvmapでも(最初の2行はskyboxでも)繰り返され、lights.apply(*phong)が更に5〜14回(12個の光を全部使うと53回)のsetを、毎回文字列の検索付きで呼んでいました。
其れは普通のユニフォームが1つのプログラムオブジェクトの状態だからです。
値はプログラムと一緒に保存され、同じ名前のユニフォームを宣言する別のプログラムは、全く別の自分の値を持っています。
カメラが必要なプログラムが2つあれば、カメラを2回アップロードする必要があります。
3つ目のシェーダーを足して其の行列を設定し忘れると、其のシェーダーは前に入っていた値(大抵は0なので何も映りません)で描きます。

ユニフォームバッファオブジェクトは此れを逆にします。
データは普通のバッファオブジェクトに入ります。
第3章からの頂点バッファと同じ種類のオブジェクトです。
シェーダーはユニフォームブロックを宣言します。
ユニフォームの名前付きのまとまりで、値はプログラムに保存されず、バッファから読まれます。
2つの間にあるのが、OpenGLのコンテキストの中の小さな表、GL_UNIFORM_BUFFERターゲットの結合点(バインディングポイント)で、0から番号が付いています。
バッファを結合点0に繋ぎ、シェーダーが「あたしのCameraブロックは結合点0から読む」と言えば、繋がりは其れだけです。

左の2つのバッファ、144バイトのcameraUboと704バイトのlightsUboが、glBindBufferBaseで真ん中のユニフォームバッファの結合点0と1に繋がる。右では、phong、rocksShader、skyboxのプログラムのCameraブロックが全部結合点0を読み、phongとrocksShaderのLightsブロックが結合点1を読む。結合点2と3は後の章の為に予約してある

此れでカメラはフレーム毎に1回だけアップロードされ、ブロックを宣言する全てのプログラムが新しい値を見ます。
まだ書いていないプログラムも含めてです。
右側の矢印は変わりません。
ブロックの結合点はシェーダーのソースで決まっています。
フレーム毎に変わるのは、左側のバッファの中身です。

知っておくと良い限界が幾つかあります。
OpenGL 4.6は、ユニフォームバッファの結合点を少なくとも84個(GL_MAX_UNIFORM_BUFFER_BINDINGS)、シェーダーのステージ毎にブロックを少なくとも14個(GL_MAX_VERTEX_UNIFORM_BLOCKS等)、ブロック1つに少なくとも16 KB(GL_MAX_UNIFORM_BLOCK_SIZE)保証しています。
デスクトップのGPUでは大抵64 KB迄使えます。
あたし達の2つのブロックは144バイトと704バイトなので、どの限界にも全く届きません。

19.3 GLSLでブロックを宣言する

カメラが必要な全てのシェーダーに、今は丁度此の文が入っています:

// カメラ(ユニフォームバッファ、結合点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)
};

1つずつ見ていきます:

  • uniform Camera { … };はCameraという名前のユニフォームブロックを宣言します。ブロック名はC++側が其れを探す為の名前です(glGetUniformBlockIndex、19.7節)。GLSLの他の場所で使える型ではありません。
  • 閉じ括弧の後にインスタンス名が無いので、メンバーはグローバルな名前になります。シェーダーは今迄通りuView、uProj、uViewPosと書けて、ライティングのコードは1行も変える必要がありませんでした。インスタンス名を付けて} camera;とすると、camera.uViewと書く事になります。どちらでも良いですが、古いコードに触らない方を選びました。
  • std140は決まったメモリのレイアウトを選びます。仕様でバイト単位迄定義されているので、同じ形のC++の構造体が書けます。既定のレイアウトのsharedはドライバーが決めるので、実行時に全てのメンバーのオフセットを問い合わせる必要があります。packedはシェーダーが使わないメンバーを消す事さえあります。ユニフォームブロックにはstd140を使って下さい。
  • binding = 0が結合点です。此の書き方はGLSL 4.20からです。古いコードはリンクの後でglUniformBlockBinding(program, blockIndex, 0)を呼び、C++から同じ事をします。多くのチュートリアルで見掛けるはずです。
  • uTimeは新しいメンバーで、アニメーションの時間(秒)です(Pで止めている間は進みません)。19.11節で、インスタンスの岩が此れから公転を計算します。

phong.vertが一番簡単な形の書き換えを見せてくれます:

#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;

// カメラ(ユニフォームバッファ、結合点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;
// インスタンスごとの色(第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;
  vTint = uTint;
  gl_Position = uProj * uView * world;
}

uniform mat4 uView;とuniform mat4 uProj;は消え、ブロックが其の代わりになりました。
uModelとuNormalMatrixは普通のユニフォームのままです。
物毎に変わるので、フレーム毎のブロックに入れるのは間違いです。
最後の方の色合い(tint)はインスタンシングの為の物で、19.11節で説明します。
= vec3(1.0)というユニフォームの初期化子に注目して下さい。
プログラムをリンクした瞬間からユニフォームに値が入るので、uTintを設定しないプログラムは普通の色で描きます。

ブロックの宣言はphong.vert、phong.frag、phong_instanced.vert、skybox.vert、unlit.vert、envmap.fragにコピーしてあります。
GLSLには#includeがありません(GL_ARB_shading_language_includeという拡張はありますが、何処でも使える訳ではなく、APIの呼び出しも増えます)。
そしてブロックの宣言は全て同じでなければなりません。
メンバー、型、順番が同じという事です。
1つのプログラムの中では、頂点シェーダーとフラグメントシェーダーの両方が宣言しても構わず(phongがそうです)、リンカーは其れを1つのブロックとして扱います。
2つのプログラムが違う形でブロックを宣言しても、何も止めてくれません。
各プログラムが同じバイトを違うレイアウトで読むだけで、行列がおかしくなります。
19.7節で、丁度其れを調べる仕組みを足します。

19.4 std140のレイアウトの規則

何故規則があるのか

第12章では、GLSLの光の構造体はC++の構造体と同じレイアウトである必要がありませんでした。
全てのメンバーを名前で設定し、ドライバーが好きな場所に置いていたからです。
今はC++の構造体を生のバイトとしてバッファにコピーし、シェーダーはstd140の規則が決めたオフセットから其のバイトを読みます。
2つが4バイトでもずれれば、其れ以降のメンバーは全て隣のデータを読みます。

規則はGPUが得意な事から来ています。
揃った16バイトの塊(floatが4つ、vec41つ)を読む事です。
其の為std140は殆どの物を16バイトに揃えます。
各型には大きさと基本アラインメントがあり、各メンバーは、前のメンバーの終わり以降で、自分の基本アラインメントの倍数になる最初のオフセットから始まります:

offset=⌈end of the previous memberalignment⌉⋅alignment

表

型 大きさ(バイト) 基本アラインメント 注意
float、int、uint、bool 4 4 boolはC++の様な1バイトではなく4バイト
vec2 8 8
vec3 12 16 後ろのスカラーは其の後の4バイトに入る
vec4 16 16
mat3 48 16 列が3本で、各列はvec4の大きさに詰め物される
mat4 64 16 vec4の列が4本
スカラー又はベクトルの配列 要素毎に16 16 全ての要素が16に切り上げ:float[4]は64バイト
構造体 メンバー、16の倍数に切り上げ 16 構造体や配列の次のメンバーも16の倍数から始まる

(此のシリーズでは何処でも行列は列優先です。row_majorの修飾子を付けると、詰め物されるベクトルは行になります。)

誰もが一度は引っ掛かる結果が3つあります:

  • vec3は16バイトに揃うのに、大きさは12バイトしか無い。 vec3を2つ並べると始まりから終わり迄32バイトで、其々の後ろに4バイトの穴が空きます。vec3の直後のfloat(又はint)は、其の穴をただで埋めます。
  • mat3は36バイトではなく48バイト。 第10章のC++のMat3は隙間無く並んだfloat 9個なので、其のままブロックにコピーする事は出来ません。第10章で既に注意した通りです。其の為多くのエンジンは法線行列をmat4として送ります。
  • 小さな物の配列は場所を無駄にする。 float weights[4]は64バイトで、16バイトの枠毎にfloatが1つです。此の様なデータはvec4に詰めるか、スカラーの配列が隙間無く並ぶstd430のレイアウトのSSBO(19.15節)を使います。

例:Cameraブロック

規則をCameraに当てはめます:

  • mat4 uView:アラインメント16、オフセット0、64バイト、64で終わる。
  • mat4 uProj:64は16の倍数なのでオフセット64、128で終わる。
  • vec3 uViewPos:オフセット128、12バイト、140で終わる。
  • float uTime:アラインメント4で、140は4の倍数なので、オフセットは140、つまりvec3の後ろの穴です。144で終わります。

ブロックは144バイトで、無駄なバイトは1つもありません。
もしuTimeが最初にあったら、0に置かれ、mat4は16迄待つ必要があるので12バイトの穴が空きます。
メンバーは156で終わり、切り上げて160バイトのブロックになります。
順番は大事で、スカラーをvec3の直後に置くのが穴を使う定番の方法です。

左:16バイト毎の行で見たCameraブロック。uViewがオフセット0〜48の行、uProjが64〜112の行を使い、128の最後の行ではuViewPosが3マス、uTimeが4マス目に入り、全部で144バイト。右上:64バイトのSpotLight構造体。position+cosInner、direction+cosOuter、color+詰め物、attenuation+詰め物。右下:vec3の罠。GLSLでは2つのvec3が0と16から始まるが、詰め物の無いC++の構造体では2つ目が12から始まる

vec3の罠

図の右下は、一番良く起きる間違いです。
GLSLではvec3 a; vec3 b;のbはオフセット16にあります。
C++のVec3はアラインメント4のfloat 3つなので、struct { Vec3 a; Vec3 b; }は24バイトで、bはオフセット12に来ます。
其の構造体をバッファにコピーすると、シェーダーはbをバイト16〜27から読みますが、其処にはC++がb.y、b.z、そしてbの次にある物を書いています。
シェーダーのb.xは本当はb.yで、b.yはb.zで、b.zは次のメンバーの物です。
何もエラーを出しません。
色がおかしくなったり、光が変な場所にあったりするだけで、bの後のメンバーも全部ずれます。

対策は3つあり、あたし達は全部使います:

  1. C++の構造体に詰め物を明示的に書く(枠を分け合う相手の無いVec3の後にfloat pad0;)。
  2. 全てのオフセットをstatic_assert(offsetof(…) == …)で確かめ、間違いがあればコンパイルが通らない様にする。
  3. プログラムの起動時に、ドライバーが計算した大きさとsizeofを比べる(19.7節)。

C++のメンバーにalignas(16)を付ける人もいます。
Vec3の始まりには効きますが、後ろのfloatを穴に入れる事は出来ず、型自体に付けるとsizeof(Vec3)が変わって頂点の構造体が壊れます。
明示的な詰め物の方が打つ文字は多いですが、ずっと読み易いです。

例:Lightsブロック

第12章の光は、今はphong.fragの此のブロックに入っています:

// 平行光源:向きだけ / directional light: a direction only
struct DirectionalLight {
  vec3 direction; // 光が進む向き(単位ベクトル) / the direction the light travels (unit vector)
  vec3 color;     // 0 = オフ / 0 = off
};

// 点光源:位置と減衰 / point light: a position and attenuation
struct PointLight {
  vec3 position;
  vec3 color;
  vec3 attenuation; // 定数項・一次・二次 / constant, linear, quadratic
};

// スポットライト:点光源+円錐。floatはvec3の後ろの隙間に入れる(詰め物が減る)
// spotlight: a point light + a cone. The floats sit in the gaps after the vec3s (less padding)
struct SpotLight {
  vec3 position;
  float cosInner; // 内側の円錐の半角のコサイン / cosine of the inner cone's half angle
  vec3 direction; // 円錐の軸(単位ベクトル) / the cone's axis (unit vector)
  float cosOuter; // 外側の円錐の半角のコサイン / cosine of the outer cone's half angle
  vec3 color;
  vec3 attenuation;
};

// C++側の kMaxPointLights、kMaxSpotLights と同じ / same as kMaxPointLights and kMaxSpotLights in C++
#define MAX_POINT_LIGHTS 8
#define MAX_SPOT_LIGHTS 4

// 全部の光(ユニフォームバッファ、結合点1) / all lights (uniform buffer, binding 1)
layout(std140, binding = 1) uniform Lights {
  DirectionalLight uDirLight;
  PointLight uPointLights[MAX_POINT_LIGHTS];
  SpotLight uSpotLights[MAX_SPOT_LIGHTS];
  vec3 uAmbient;        // 環境光の色と明るさ / ambient light colour and brightness
  int uPointLightCount; // 使っている数 / how many are in use
  int uSpotLightCount;
};

メンバーの名前は第12章と同じなので、ライティングの関数は変わっていません。
SpotLightの中の順番だけが変わりました。
其の理由を見る為に、まず構造体を計算します:

  • DirectionalLight:directionは0(12で終わる)、colorは16(28で終わる)。構造体の大きさは16に切り上げなので、32バイト。
  • PointLight:positionは0、colorは16、attenuationは32で、44で終わり、切り上げて48バイト。
  • 第12章の順番(position、direction、color、cosInner、cosOuter、attenuation)のSpotLight:positionは0、directionは16、colorは32、cosInnerは44(colorの後ろの穴)、cosOuterは48、attenuationは64(vec3は16の倍数から始まる必要がある)、76で終わり、切り上げて80バイト。
  • 新しい順番のSpotLight:positionは0、cosInnerは12、directionは16、cosOuterは28、colorは32、attenuationは48、60で終わり、切り上げて64バイト。

各floatをvec3の後ろに移すと、スポットライト1つに付き16バイト節約出来ます。
次はブロックです:

メンバー オフセット 大きさ 理由
uDirLight 0 32 構造体、0から始まる
uPointLights[8] 32 8 × 48 = 384 配列のストライド48、416で終わる
uSpotLights[4] 416 4 × 64 = 256 配列のストライド64、672で終わる
uAmbient 672 12 vec3、684で終わる
uPointLightCount 684 4 vec3の後ろの穴に入るint
uSpotLightCount 688 4 692で終わる

メンバーは692で終わり、Mesaが報告するブロックの大きさは704です。
構造体と同じく、16(vec4の大きさ)の倍数に切り上げられています。
但し、最後の切り上げは全てのドライバーがする訳ではなく、692を報告するドライバーもあります。
19.7節の検査は其のどちらも受け入れます。
此の章のコードを作った時、計算を信用せず、ドライバー(Mesa)にglGetUniformIndicesとglGetActiveUniformsiv(…, GL_UNIFORM_OFFSET, …)で全てのメンバーのオフセットを聞きました。
課題2で、此の一覧を自分で出して貰います:

ドライバーが報告するオフセットを並べたターミナルの出力。uView 0、uProj 64、uViewPos 128、uTime 140、uDirLight.direction 0、uDirLight.color 16、uPointLights 0のposition 32、color 48、attenuation 64、uPointLights 1のposition 80、uSpotLights 0のposition 416、cosInner 428、direction 432、cosOuter 444、color 448、attenuation 464、uSpotLights 1のposition 480、uAmbient 672、uPointLightCount 684、uSpotLightCount 688。大きさはCamera 144、Lights 704で、C++と同じ

全ての数字が手計算と合っています。
2つ目の点光源は1つ目の48バイト後(80 − 32)、2つ目のスポットライトは1つ目の64バイト後(480 − 416)から始まります。
ブロックの中のオフセットはブロックの先頭からの相対値です。
uDirLight.directionとuViewが両方0なのは、別のブロックにあるからです。

19.5 C++側の写し

CameraBlock

src/uniforms.hhには結合点の番号、カメラの構造体、そして規則の短い覚え書きが入っています:

// 結合点の番号。シェーダーの layout(std140, binding = N) と同じにすること
// Binding point numbers. Must match layout(std140, binding = N) in the shaders
constexpr GLuint kCameraBinding = 0; // Camera:ビュー・射影・カメラの位置・時間 / view, projection, camera position, time
constexpr GLuint kLightsBinding = 1; // Lights:全部の光(lights.hhのLightsBlock) / all lights (LightsBlock in lights.hh)
// 2 = 影(第23章:光から見た行列) / shadows (chapter 23: light-space matrices)
// 3 = 後処理の設定(第21章:露出、ブルーム) / post-processing settings (chapter 21: exposure, bloom)

結合点はコンテキスト全体の番号なので、1つのヘッダーの定数にし、ブロックを足す章は次の空いている番号を取ります。
2と3は、第23章と第21章の影とポストプロセスのブロックの為に既に予約してあります。

// GLSL:
//   layout(std140, binding = 0) uniform Camera {
//     mat4 uView;     // offset 0
//     mat4 uProj;     // offset 64
//     vec3 uViewPos;  // offset 128
//     float uTime;    // offset 140(vec3の後ろの隙間) / (the gap after the vec3)
//   };                // 144 bytes
struct CameraBlock {
  Mat4 view;
  Mat4 proj;
  Vec3 viewPos;
  float time = 0.0f; // アニメーションの時間(秒) / animation time (seconds)
};
static_assert(offsetof(CameraBlock, proj) == 64);
static_assert(offsetof(CameraBlock, viewPos) == 128);
static_assert(offsetof(CameraBlock, time) == 140);
static_assert(sizeof(CameraBlock) == 144);

カメラのブロックには詰め物が全く要りません。
Mat4はfloat 16個(64バイト、GLSLのmat4と同じ列優先)で、timeは丁度viewPosの後ろの穴に入ります。
其れでもstatic_assertには意味があります。
誰かが間違った場所にメンバーを足せば、ビルドが間違った行で止まります。
構造体が標準レイアウト(単純な型の公開データメンバーだけ)なので、offsetofが使えます。

LightsBlock

lights.hhには3つの光の構造体のstd140版が加わり、全ての穴を手で埋めています:

struct DirectionalLightStd140 {
  Vec3 direction;
  float pad0;
  Vec3 color;
  float pad1;
};
struct PointLightStd140 {
  Vec3 position;
  float pad0;
  Vec3 color;
  float pad1;
  Vec3 attenuation;
  float pad2;
};
struct SpotLightStd140 {
  Vec3 position;
  float cosInner; // vec3の後ろの隙間に入る / fits in the gap after the vec3
  Vec3 direction;
  float cosOuter;
  Vec3 color;
  float pad0;
  Vec3 attenuation;
  float pad1;
};
struct LightsBlock {
  DirectionalLightStd140 directional;
  PointLightStd140 points[kMaxPointLights];
  SpotLightStd140 spots[kMaxSpotLights];
  Vec3 ambient;
  int pointCount;
  int spotCount;
  int pad[3];
};
static_assert(sizeof(DirectionalLightStd140) == 32 && sizeof(PointLightStd140) == 48 && sizeof(SpotLightStd140) == 64);
static_assert(offsetof(LightsBlock, points) == 32);
static_assert(offsetof(LightsBlock, spots) == 416);
static_assert(offsetof(LightsBlock, ambient) == 672);
static_assert(offsetof(LightsBlock, pointCount) == 684);
static_assert(offsetof(LightsBlock, spotCount) == 688);
static_assert(sizeof(LightsBlock) == 704);

各構造体の最後のpad0、pad1、pad2は「16の倍数に切り上げ」の規則を書き出した物です。
此れが無いと、C++のPointLightStd140の配列のストライドは48ではなく44になります。
最後のint pad[3]で構造体は704バイトになり、16の倍数で、Mesaが報告する大きさと揃います。
数はintで、決してboolやsize_tにしません。
両側が4バイトで一致しなければならないからです。

使う側のPointLight、SpotLight、LightSet(第12章)は変わりません。
便利なままです(角度はラジアン、向きの長さは自由、std::vectorの数も自由)。
std140の構造体は別の、見た目は悪いけれど正確なアップロード用の形式で、1つの関数が両者を変換します。
全てのメンバーを名前で設定していた第12章のapply(shader)の代わりです:

LightsBlock LightSet::toBlock() const {
  LightsBlock b{}; // 全部0(詰め物も) / all zero (the padding too)
  b.directional.direction = normalize(directional.direction);
  b.directional.color = directional.color;

  int pointCount = static_cast<int>(points.size());
  if (pointCount > kMaxPointLights) {
    fprintf(stderr, "点光源が多すぎる / too many point lights: %d (max %d)\n", pointCount, kMaxPointLights);
    pointCount = kMaxPointLights;
  }
  for (int i = 0; i < pointCount; ++i) {
    const PointLight &p = points[static_cast<size_t>(i)];
    b.points[i].position = p.position;
    b.points[i].color = p.color;
    b.points[i].attenuation = p.attenuation;
  }
  b.pointCount = pointCount;

  int spotCount = static_cast<int>(spots.size());
  if (spotCount > kMaxSpotLights) {
    fprintf(stderr, "スポットライトが多すぎる / too many spotlights: %d (max %d)\n", spotCount, kMaxSpotLights);
    spotCount = kMaxSpotLights;
  }
  for (int i = 0; i < spotCount; ++i) {
    const SpotLight &s = spots[static_cast<size_t>(i)];
    b.spots[i].position = s.position;
    b.spots[i].direction = normalize(s.direction);
    b.spots[i].color = s.color;
    // シェーダーは角度ではなくコサインを比べる(acosを毎ピクセル計算しないため)
    // The shader compares cosines, not angles (so it does not need acos for every pixel)
    b.spots[i].cosInner = std::cos(s.innerAngle);
    b.spots[i].cosOuter = std::cos(s.outerAngle);
    b.spots[i].attenuation = s.attenuation;
  }
  b.spotCount = spotCount;
  b.ambient = ambient;
  return b;
}

LightsBlock b{}は詰め物も含めて全てを値初期化するので、使わない光は0になり、スタックのゴミがGPUに届く事はありません。
残りは第12章のコードのshader.set(std::format(…))を普通の構造体への代入に置き換えた物で、其の為lights.ccはもう<format>を必要としません(Debian 12のGCC 12の問題が1つ減ります)。
ブロック(704バイト)を値で返すのは安い処理です。
コンパイラーは呼び出し側で直接其れを作ります。

19.6 C++のユニフォームバッファ

Bufferへの2つの追加

第4章のBufferは不変のストレージを作り、1回だけ中身を入れます。
ユニフォームバッファは毎フレーム書き直すので、小さな関数が2つ加わります:

  // 中身の一部を書き換える(作るときにGL_DYNAMIC_STORAGE_BITが必要) / replaces part of the contents
  // (needs GL_DYNAMIC_STORAGE_BIT at creation)
  void update(const void *data, GLsizeiptr byteCount, GLintptr offset = 0) const;
  // 番号付きの結合点に繋ぐ(ユニフォームバッファなど、第19章) / attaches to an indexed binding point
  // (uniform buffers etc., chapter 19)
  void bindBase(GLenum target, GLuint index) const { glBindBufferBase(target, index, handle); }

void Buffer::update(const void *data, GLsizeiptr byteCount, GLintptr offset) const {
  glNamedBufferSubData(handle, offset, byteCount, data);
}

glNamedBufferSubData(buffer, offset, size, data)は、dataからsizeバイトを、バッファの先頭からoffsetバイトの位置にコピーします:

  • buffer:バッファオブジェクト(DSAなので結合は要りません)。
  • offset、size:置き換えるバイトの範囲。バッファの中に収まっていないとGL_INVALID_VALUEになります。
  • data:コピー元のCPUのメモリ。(アプリケーションから見て)呼び出しが戻る前にコピーされるので、直ぐ後でdataを変えたり解放したりして構いません。

落とし穴は第4章のフラグです。
フラグ0のglNamedBufferStorageは中身を変えられなくし、そんなバッファへのglNamedBufferSubDataはGL_INVALID_OPERATIONになります(第2章のデバッグコールバックが表示します)。
此の方法で更新したいバッファは、GL_DYNAMIC_STORAGE_BITを付けて作る必要があります。
GPUがまだ前のフレームのカメラを読んでいる間に上書きしたらどうなるでしょうか?
其れはドライバーが面倒を見ます。
待つか、又は(数百バイトなら其の方がずっとありそうですが)こっそりデータを新しい場所にコピーし、古いフレームには古い中身で終わらせます。
毎フレーム変わる大きなバッファでは此の隠れた作業が高く付くので、第25章のスプライトバッチャーは永続的にマップしたバッファを使います。

glBindBufferBase(target, index, buffer)は、番号付きのターゲットの結合点indexにbufferを繋ぎます:

  • target:此処ではGL_UNIFORM_BUFFER。番号付きの結合点を持つ他のターゲットはGL_SHADER_STORAGE_BUFFER(19.15節)、GL_ATOMIC_COUNTER_BUFFER、GL_TRANSFORM_FEEDBACK_BUFFERです。
  • index:結合点の番号。0〜GL_MAX_UNIFORM_BUFFER_BINDINGS − 1で、layout(binding = …)と同じ番号です。
  • buffer:バッファ全体が繋がります。glBindBufferRange(target, index, buffer, offset, size)は一部だけを繋ぐので、沢山のブロックを1つのバッファに詰められます。其の場合オフセットはGL_UNIFORM_BUFFER_OFFSET_ALIGNMENT(どの実装でも最大256バイト)の倍数でなければなりません。

glBindBufferBaseにはDSA版が無く、必要もありません。
バッファを編集するのではなく、コンテキストの結合点の表を編集するからです。
其の表はグローバルです。
結合点0に繋がっている物が、別の物が繋がれる迄、全てのプログラムのCameraブロックが読む物です。

UniformBuffer

Bufferの上に、ブロックを1つ持つ小さなテンプレートを載せます:

// 一つのブロックの中身を持つユニフォームバッファ(RAII、コピー不可・移動可)。作るときに結合点に繋ぐ。
// A uniform buffer holding one block (RAII, non-copyable, movable). Attached to its binding point when created.
template <typename Block>
class UniformBuffer {
public:
  explicit UniformBuffer(GLuint bindingPoint)
      : buffer(nullptr, sizeof(Block), GL_DYNAMIC_STORAGE_BIT), binding(bindingPoint) {
    bind();
  }
  // 中身を全部書き換える(毎フレーム) / replaces the whole contents (every frame)
  void update(const Block &block) const { buffer.update(&block, sizeof(Block)); }
  // 結合点に繋ぎ直す(同じ番号に別のバッファを繋いだ後で) / re-attach to the binding point (after another
  // buffer was attached to the same number)
  void bind() const { buffer.bindBase(GL_UNIFORM_BUFFER, binding); }
  GLuint bindingPoint() const { return binding; }

private:
  Buffer buffer;
  GLuint binding;
};

型引数がバッファの大きさを構造体に結び付けます。
UniformBuffer<CameraBlock>は丁度144バイトで、updateはCameraBlockしか受け付けないので、うっかり光をカメラのバッファにアップロードする事はありません。
データにnullptrを渡すと、中身を入れずにストレージだけを確保します。
最初の描画の前に、最初のupdateが中身を入れます。
コンストラクターは直ぐにバッファを結合点に繋ぎます。
あたし達のプログラムでは、結合点0と1を他に使う物が無いからです。
bind()は其れが変わる日の為にあります。
2つ目のカメラで鏡を描くなら(第17章の考え方です)、2つ目のカメラのバッファを結合点0に繋いで描き、cameraUbo.bind()で元のカメラに戻します。
Bufferが移動可能なので移動は出来、Bufferのコピーコンストラクターが削除されているので、此方のも暗黙に削除されます。

19.7 起動時にレイアウトを確かめる

static_assertは、C++側を自分で打った数字と比べます。
其の数字をシェーダーと比べる事は出来ません。
其の為にShaderに関数が2つ加わります:

GLint Shader::uniformBlockSize(const char *blockName) const {
  GLuint index = glGetUniformBlockIndex(program, blockName);
  if (index == GL_INVALID_INDEX) return -1;
  GLint size = 0;
  glGetActiveUniformBlockiv(program, index, GL_UNIFORM_BLOCK_DATA_SIZE, &size);
  return size;
}

bool Shader::checkUniformBlock(const char *blockName, size_t cppSize) const {
  GLint size = uniformBlockSize(blockName);
  // ドライバーによっては最後のメンバーの終わり(例:692)を、ほかは16の倍数に切り上げた値(704)を返す。
  // 16の倍数に切り上げて比べる / some drivers report where the last member ends (e.g. 692), others round up to a
  // multiple of 16 (704): compare after rounding up to 16
  if (size < 0 || ((static_cast<size_t>(size) + 15) / 16) * 16 == cppSize) return true;
  fprintf(stderr, "%s + %s: ブロック「%s」は%dバイト、C++の構造体は%zuバイト / block \"%s\" is %d bytes, the C++ struct %zu\n",
          vertexPath.c_str(), fragmentPath.c_str(), blockName, size, cppSize, blockName, size, cppSize);
  return false;
}

  • glGetUniformBlockIndex(program, name)はブロック名(インスタンス名やメンバー名ではなく"Camera")でブロックを探し、プログラムの中の番号を返します。其の名前の有効なブロックが無ければGL_INVALID_INDEXです。プログラムのどのステージも使わないブロックは最適化で消える事があり、其の時も無い物として扱われます。unlit.fragは光を見ないので、unlitから作ったプログラムにはLightsブロックがありません。
  • glGetActiveUniformBlockiv(program, index, pname, params)は其のブロックについて質問します。GL_UNIFORM_BLOCK_DATA_SIZEは、ブロックがバッファの中で必要とするバイト数です。他に便利なpnameはGL_UNIFORM_BLOCK_BINDING(読む結合点)とGL_UNIFORM_BLOCK_ACTIVE_UNIFORMS(メンバーの数)です。

checkUniformBlockは、ブロックが無い時(調べる物が無い)か大きさが合う時にtrueを返し、そうでなければ両方の大きさを表示します。
コメントの通り、「合う」とはドライバーの大きさを16の倍数に切り上げた上での事です。
ブロックの終わりについてはドライバー毎に答えが違い、MesaはLightsに704を返しますが、uSpotLightCountが終わる692を返すドライバーもあります。
どちらも同じレイアウトなので、両方受け入れる必要があります。
其の代わり少し甘くなり、Lightsの最後にfloatを1つ足しただけのシェーダー(696、切り上げて704)は見逃されます。
宣言を全く同じに保つ事が大事な理由が又1つ増えました。
裏を返すと、sizeofが16の倍数でないC++の写しは決して検査を通らないので、LightsBlockの様に全てのブロックの構造体の最後を詰め物して下さい。
mainはシェーダーを読み込んだ直後に、全てのプログラムについて其れを呼びます:

  // C++の構造体とGLSLのブロックの大きさが合うか確かめる(std140の詰め物を間違えると違う)
  // Check that the C++ structs and the GLSL blocks have the same size (they differ if the std140 padding is wrong)
  for (const Shader *s : {&*phong, &*rocksShader, &*skybox})
    if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)))
      return 1;

大きさの比較は完全な証明ではありません。
大きさが同じでオフセットが違うレイアウトもあり得ます。
実際には、殆ど全てのレイアウトの間違い(詰め物の忘れ、C++側がfloat 3つなのにvec3、片側だけに足したメンバー)は大きさを変えます。
static_assertと合わせれば、あたしがユニフォームブロックでした間違いは全て此れで見付かりました。
完全に調べたいなら、glGetUniformIndicesとglGetActiveUniformsiv(…, GL_UNIFORM_OFFSET, …)で全てのメンバーのオフセットが分かります。
19.4節のスクリーンショットの通りです。

19.8 フレーム毎に1回ブロックを書く

mainでは、2つのバッファをシェーダーの後に作ります:

  // ユニフォームバッファ:作ったときに結合点0と1に繋がる。シェーダーはlayout(binding = …)で同じ番号を読む
  // Uniform buffers: attached to binding points 0 and 1 when created. The shaders read the same numbers through
  // layout(binding = ...)
  UniformBuffer<CameraBlock> cameraUbo(kCameraBinding);
  UniformBuffer<LightsBlock> lightsUbo(kLightsBinding);

そしてフレームのループの中で、カメラと光を丁度1回だけ書きます:

    // カメラのブロック:フレームに一度書けば、全部のシェーダーが読む(シェーダーごとのset()は要らない)
    // The camera block: written once per frame, read by every shader (no per-shader set() any more)
    float aspect = static_cast<float>(sceneFbo.width()) / static_cast<float>(sceneFbo.height());
    CameraBlock camera;
    camera.view = useOrbit ? orbit.view() : fps.view();
    camera.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect);
    camera.viewPos = useOrbit ? orbit.position() : fps.position;
    camera.time = animTime;
    cameraUbo.update(camera);

    if (flashlightOn)
      lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}});
    lightsUbo.update(lights.toBlock()); // 光のブロックも一度だけ / the lights block, also just once

第17章と第18章のView構造体とdrawSceneのラムダは無くなりました。
其れらは、行列を各プログラムに渡して、違うカメラからシーンを描く為にありました。
今はカメラとは単に「結合点0に入っている物」です。
島を描くコードは此うなり、カメラや光のユニフォームは1つもありません:

    // ビュー・射影・光はもう設定しない:ブロックから来る / no view, projection or lights to set: they come from the blocks
    phong->use();
    phong->set("uViewMode", viewMode);
    phong->set("uEnvironmentTint", environmentTint);
    scene->draw(*phong, Mat4::identity(), white, ModelPass::Opaque);
    // 浮島の下の岩:同じ岩のモデルを平たく大きく / the rock under the floating island: the same rock model, wide and flat
    rock->draw(*phong, translate({0.0f, -1.7f, 0.0f}) * scale({10.0f, 3.4f, 10.0f}), white);

浮島は環と同じrock.glbを10 × 3.4 × 10に拡大した物です。
一様でない拡大縮小ですが、Model::drawがノード毎に正しい法線行列を計算するので(第10章)問題ありません。
19.11節で、インスタンスの岩が近道をする時に此れを思い出して下さい。

順番は1つの点で大事です。
バッファは、其れを読む描画呼び出しの前に新しい値を持っていなければなりません。
OpenGLはコマンドを順番に実行するので、updateの後に描くのは常に正しく、フレームの途中でブロックを更新しても正しく、其の後の描画だけに影響します。

19.9 インスタンシングの考え方

描画呼び出しのコスト

glDrawElementsの様な描画呼び出しは安く見えます。
引数は少しだけです。
仕事は其の裏に隠れています。
GPUが始める前に、ドライバーは描画が依存する全ての物が有効で、ハードウェアが欲しい形になっているかを確かめる必要があります。
プログラム、VAOの属性の形式とバッファ、繋がっている全てのテクスチャとサンプラー、前の描画から変わったユニフォームの値、深度・ブレンド・カリングの状態、フレームバッファです。
其れを全部GPUのコマンドに翻訳し、コマンドバッファに追加します。
其の殆どはCPUの仕事で、描画呼び出し毎に行われ、OpenGLではドライバーが何が変わったかを知らないので毎回やり直されます。

1フレームに描画呼び出しが数百回なら問題になりません。
小さな物が何千個もあると、CPUはフレームの全部を、小さな仕事を一瞬で終えて次を待つGPUに仕事を説明する事に使ってしまいます。
此れをCPUボトルネック又は描画呼び出しボトルネックと呼び、昔からゲームが表示出来る物の数の限界でした。

1回の呼び出しで沢山のコピー

インスタンシングは同じメッシュを1回の呼び出しで何度も描きます。
glDrawElementsInstancedはglDrawElementsの引数にインスタンスの数を足した物です。
頂点シェーダーは全てのインスタンスの全ての頂点について実行され、組み込みのgl_InstanceID(0〜インスタンス数 − 1)が、今の頂点がどのインスタンスの物かを教えます。
其れだけでは全てのインスタンスが同じ場所に描かれるので、各インスタンスに自分のデータ、少なくともモデル行列が必要です。
シェーダーに渡す一般的な方法は3つあります:

  • gl_InstanceIDで引くユニフォームの配列。 簡単ですが、ブロックの大きさで制限されます。16 KBではmat4が256個しか入りません。
  • インスタンス毎の頂点属性(インスタンス配列とも呼ぶ)。普通の頂点バッファですが、其の属性は頂点毎ではなくインスタンス毎に進みます。メモリ以外に大きさの制限は無く、OpenGL 3.3から使えます。あたし達が使うのは此れです。
  • gl_InstanceIDで引くシェーダーストレージバッファ(SSBO)。一番柔軟で、19.15節で触れます。

19.10 インスタンスの属性

データ

mesh.hhにインスタンス毎の構造体と其の属性のレイアウトが加わります:

// インスタンスごとのデータ(第19章):モデル行列(列4本をlocation 4〜7)と色(location 8)
// Per-instance data (chapter 19): the model matrix (its four columns at locations 4..7) and a colour (location 8)
struct InstanceData {
  Mat4 model;
  Vec3 color;
};

constexpr VertexAttrib kInstanceLayout[] = {
  {4, 4, offsetof(InstanceData, model) + 0},  // layout(location = 4) in mat4 aInstanceModel(列0 / column 0)
  {5, 4, offsetof(InstanceData, model) + 16}, // 列1 / column 1
  {6, 4, offsetof(InstanceData, model) + 32}, // 列2 / column 2
  {7, 4, offsetof(InstanceData, model) + 48}, // 列3 / column 3
  {8, 3, offsetof(InstanceData, color)},      // layout(location = 8) in vec3 aInstanceColor
};

第4章から頂点に使ってきたのと同じVertexAttribの記述です。
ロケーション、成分の数、バイトオフセットです。
新しい点が2つあります。

mat4の属性はロケーションを4つ使います。
1つの属性のロケーションには最大4成分(vec4)しか入らないので、シェーダーのlayout(location = 4) in mat4 aInstanceModelは列毎に1つ、ロケーション4、5、6、7を使います。
C++側では各列がfloat 4つの別々の属性で、前の列から16バイト後ろにあります。
Mat4は列を順番に並べて保存している(m.c[0]〜m.c[3])ので、丁度其のレイアウトです。
mat3ならロケーション3つ、dmat4(double)なら8つも使います。

ロケーションは頂点の属性の後に続きます。
0〜2は位置、法線、UVで、3はModelVertexの接線です(第22章で使います)。
インスタンスのデータは4から始まり、色は8です。
9以降はインスタンス毎のデータを足す為に空いています(課題6で9を使います)。
VAOには少なくとも16個の属性のロケーション(GL_MAX_VERTEX_ATTRIBS)があるので、余裕があります。

InstanceDataは76バイト(64 + 12)で、其れがストライドでもあります。
ユニフォームブロックと違い、頂点属性は4バイトに揃っていれば良いので、詰め物は要りません。
64 000個全部の岩で4.86 MB、既定の4000個は最初の304 000バイトを使います。

上:バインディング0の頂点バッファで、頂点v0〜v161、ストライド48、divisor 0。下:バインディング1のインスタンスバッファで、ストライド76、divisor 1。インスタンス0はロケーション4〜7の行列の4本の列とロケーション8の色に分かれ、インスタンス1、インスタンス2…インスタンス3999と続く。真ん中:頂点シェーダーはまずインスタンス0についてv0、v1…v161で実行され、全てインスタンス0を読む。次にインスタンス1についてv0、v1…v161で実行され、全てインスタンス1を読む

バインディングのdivisor

第3章では頂点の入力を属性(形式、ロケーション)とバインディング(バッファ、オフセット、ストライド)に分け、第19章でバインディングにdivisorを付けると言いました。
其れが此れです。
mesh.cc:

void Mesh::setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span<const VertexAttrib> layout) {
  constexpr GLuint kInstanceBinding = 1; // 頂点はバインディング0 / the vertices are binding 0
  glVertexArrayVertexBuffer(vertexArray, kInstanceBinding, buffer.id(), 0, stride);
  for (const VertexAttrib &a : layout) {
    glEnableVertexArrayAttrib(vertexArray, a.location);
    glVertexArrayAttribFormat(vertexArray, a.location, a.components, a.type, a.normalized, a.offset);
    glVertexArrayAttribBinding(vertexArray, a.location, kInstanceBinding);
  }
  // 1 = インスタンス1つごとに1要素進む(0なら頂点ごと) / 1 = advance one element per instance (0 = per vertex)
  glVertexArrayBindingDivisor(vertexArray, kInstanceBinding, 1);
}

前半は第4章のコンストラクターのループと同じで、バインディングが0ではなく1です。
インスタンスバッファをストライド76でバインディング1に繋ぎ、各インスタンス属性を有効にし、形式を決め、其のバインディングに繋ぎます。
新しいのは最後の呼び出しです。

glVertexArrayBindingDivisor(vaobj, bindingindex, divisor)は、バインディングの属性がどの位の頻度で進むかを決めます:

  • vaobj:VAO。
  • bindingindex:バインディング。インスタンスバッファなので1です。其のバインディングに繋がった全ての属性(あたし達の5つ全部)に効きます。
  • divisor:0(既定)は「頂点毎に1つ進む」で、普通の動作です。1は「インスタンス毎に1つ進む」で、インスタンス0の全ての頂点が要素0を読み、インスタンス1の全ての頂点が要素1を読み、と続きます。Nは「Nインスタンス毎に1つ進む」で、使い道は余りありません(例えば2にして、インスタンス2つずつに同じ色を付ける)。

インスタンス番号iについて、divisor d>0の属性は要素⌊i/d⌋を読み、頂点の番号は全く関係ありません。
divisor 0なら、何時も通り今の頂点の要素を読みます。

古いコードはglVertexAttribDivisor(attribute, divisor)を使い、divisorを属性毎に設定します。
行列なら列のロケーション毎に、4回呼ぶ事になります。
OpenGL 4.3で此の関数は新しいモデルで定義し直された(属性と同じ番号のバインディングのdivisorを設定し、2つを繋ぐ)ので、どちらも動きますが、1つのVAOで混ぜないで下さい。

良くある間違いは、どれもエラーメッセージではなく、爆発した形になって現れます:

  • divisorを忘れる。 するとインスタンスの属性は頂点毎に進みます。頂点0は岩0の行列、頂点1は岩1の行列を使い、全ての三角形が3つの別々の岩の角を結びます。空が長い破片で一杯になります。
  • 列のオフセットの間違い。 列は0、16、32、48バイトにあります。4つ全部に同じオフセットを与えると、全ての列が最初の列になります。
  • ロケーションの重なり。 ロケーション3のインスタンス属性は接線を置き換え、頂点バッファの其のロケーションのデータは読まれなくなります。
  • 整数のデータにglVertexArrayAttribFormat。 floatに変換されてしまいます。整数の属性(インスタンスのID、マテリアルの番号)にはglVertexArrayAttribIFormatと、GLSLのint/uintの入力が必要です。

描画の関数は短いです:

void Mesh::drawInstanced(GLsizei count) const {
  glBindVertexArray(vertexArray);
  if (indexCount > 0) glDrawElementsInstanced(primitive, indexCount, GL_UNSIGNED_INT, nullptr, count);
  else glDrawArraysInstanced(primitive, 0, vertexCount, count);
}

glDrawElementsInstanced(mode, count, type, indices, instancecount)はglDrawElementsに引数を1つ足した物です。
countは今迄通り1つのインスタンスのインデックスの数(岩なら960)で、instancecountがインスタンスの数です。
glDrawArraysInstanced(mode, first, count, instancecount)はインデックスの無いメッシュの為の同じ物です。
instancecountが1ならインスタンスでない呼び出しと全く同じ物を描き、0なら何も描きません。
インスタンスの属性を指定した要素から始める…BaseInstance版(glDrawElementsInstancedBaseInstance)もあります。
其の場合もgl_InstanceIDは0から始まり、GLSL 4.60のgl_BaseInstanceがシェーダーに其の始まりを教えます。
マルチドローインダイレクト(19.15節)で大事になります。

モデル全体

glTFのモデルはプリミティブ毎にVAOを持つので、Modelは両方の関数を其々に渡します:

void Model::setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span<const VertexAttrib> layout) {
  for (MeshData &m : meshes)
    for (Primitive &p : m.primitives) p.mesh.setInstanceBuffer(buffer, stride, layout);
}

void Model::drawInstanced(const Shader &shader, const Texture2D &white, GLsizei count) const {
  std::vector<DrawItem> items;
  for (int root : roots) collect(root, Mat4::identity(), Mat4::identity(), true, ModelPass::All, {}, items);
  drawItems(items, shader, &white, shader.has("uNormalMatrix"), count);
}

drawInstancedはdraw(第16章)と同じ様にプリミティブを集めますが、モデルの変換は単位行列です。
其の為uModelはモデルの中のノードの行列になり、インスタンスの行列はシェーダーで其の上に掛けます。
drawItemsは既定値0のinstances引数を貰い、呼び出しを選びます:

    if (instances > 0) p.mesh.drawInstanced(instances);
    else p.mesh.draw();

従ってマテリアル、テクスチャ、両面のカリングは、インスタンスのモデルでも普通のモデルと全く同じ様に動き、描画呼び出しはコピー毎・プリミティブ毎ではなくプリミティブ毎に1回になります。
岩のプリミティブは1つなので、環全体が描画呼び出し1回です。
1つのインスタンスバッファは幾つものVAOに同時にデータを渡せます。
岩にプリミティブが幾つかあっても、全部が同じバッファを読みます。

19.11 インスタンス用の頂点シェーダー

shaders/phong_instanced.vertの全体です:

#version 460 core
// インスタンシング用のphong.vert:インスタンスごとの行列と色を頂点属性で受け取る(フラグメントシェーダーはphong.frag)
// phong.vert for instancing: the per-instance matrix and colour arrive as vertex attributes (fragment shader: phong.frag)
layout(location = 0) in vec3 aPosition;
layout(location = 1) in vec3 aNormal;
layout(location = 2) in vec2 aUv;
// location 3は接線(第22章) / location 3 is the tangent (chapter 22)
layout(location = 4) in mat4 aInstanceModel; // mat4はlocationを4つ使う(4〜7) / a mat4 takes four locations (4..7)
layout(location = 8) in vec3 aInstanceColor;

// カメラ(ユニフォームバッファ、結合点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;        // モデルの中のノードの行列 / the node's matrix inside the model
uniform mat3 uNormalMatrix; // その法線行列 / its normal matrix
uniform float uOrbitSpeed;  // 環の公転の速さ(半径8 mで、ラジアン毎秒) / orbit speed of the ring (rad/s at radius 8 m)

out vec3 vWorldPos;
out vec3 vNormal;
out vec2 vUv;
out vec3 vTint;

// Y軸周りの回転 / rotation about the Y axis
mat4 rotationY(float a) {
  float c = cos(a), s = sin(a);
  return mat4(c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0);
}

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;
  vTint = aInstanceColor;
  gl_Position = uProj * uView * world;
}

出力はphong.vertと同じなので、フラグメントシェーダーは色合い以外変わらないphong.fragです。
mainは此のプログラムをShader::load("shaders/phong_instanced.vert", "shaders/phong.frag")で読み込みます。

GPUで計算する公転

インスタンスバッファは1回アップロードされ、2度と触られません。
其れでも岩が動くのは、シェーダーがカメラのブロックの時間に依存する角度で、各岩をY軸の周りに回すからです。
角度は、岩の中心からの距離rに依存する角速度で時間と共に増えます:

θ(t)=t⋅ω8⋅(8r)1.5,ω8=0.25rad/s

指数はケプラーの第3法則です。
軌道の周期の2乗は半径の3乗に比例する(T2∝r3)ので、角速度ω=2π/Tはr−1.5に比例します。
環の半径は8〜14.5 mなので:

  • r=8ではω=0.25⋅1=0.25 rad/sで、1周に2π/0.25≈25.1秒。
  • r=14.5では(8/14.5)1.5≈0.410なのでω≈0.102 rad/sで、1周に約61.3秒。

内側の縁が外側の縁を追い越すのが、動画で見えます。
半径はインスタンスの行列自身から取ります。
最後の列aInstanceModel[3]が平行移動で(GLSLは行列を列で引きます)、length(….xz)がY軸からの水平な距離です。
Y軸周りの回転は軸からの距離も高さも変えないので、元の行列で式を計算出来、岩は何時迄も自分の軌道に留まります。

rotationYはlinalg.hhのrotateY(線型代数 第8章)と同じ行列を作ります。
mat4のコンストラクターは16個の数を列毎に受け取るので、最初の4つ(cosa,0,−sina,0)が第1列、つまりX軸の行き先です:

𝐑y(a)=[cosa0sina00100−sina0cosa00001]

行列の連鎖

model = orbit * aInstanceModel * uModelは何時も通り右から左へ読みます:

  1. uModelはrock.glbの中のノードの行列(此のファイルでは単位行列ですが、ノードが幾つもあるモデルには必要です)。
  2. aInstanceModelは環の中での此の岩の場所。拡大縮小、ランダムな回転、其の場所への平行移動で、19.12節のmakeRingがCPUで全部まとめた物です。
  3. orbitは置かれた岩をワールドのY軸の周りに回します。

最後の2つを入れ替えると、公転の回転は外へ動かされる前の岩自身の空間で行われ、各岩は島の周りを旅する代わりに其の場で回ります。

法線と色合い

法線はuNormalMatrix(ノードの物)を通り、次にorbit * aInstanceModelの3×3の部分を通ります。
其の逆行列の転置ではありません。
此れが正しいのは、全ての岩が一様に拡大縮小されている(scale({size, size, size}))からに過ぎません。
回転は自分自身の逆行列の転置と同じで、一様な拡大縮小は法線の長さしか変えず、其れはphong.fragの正規化で消えます。
インスタンス毎の一様でない拡大縮小があると法線が間違って傾きます。
丁度第10章で解決した問題です。
其の場合は、インスタンス毎に法線行列を保存する(ロケーションが更に3つ)か、頂点毎にtranspose(inverse(mat3(m)))を計算します。
後者は、全てのインスタンスの全ての頂点で逆行列を計算する事になります。

vTintはインスタンスの色をフラグメントシェーダーに運び、其処で1行だけ変わりました:

  s.diffuse = uMaterial.diffuse * vTint * base.rgb;

岩は1つのマテリアルを共有し、色合いが各岩の拡散色を灰色から暖かい茶色の間で変えます。
phong.fragがvTintを読む様になったので、此れと組む全ての頂点シェーダーが其れを書かなければなりません。
書かないとプログラムのリンクに失敗します。
phong.vertはuTintユニフォームを書き、初期化子のお陰で既定値は白なので、ジオラマはC++を何も変えずに前と全く同じに見えます。
19.12節の1つずつ描く方法は、インスタンシング無しで同じ色を得る為に、岩毎にuTintを設定します。

19.12 mainの中の環

インスタンスを作る

makeRingは起動時に64 000個の枠を全部、決まった疑似乱数の列で1回だけ埋めます(第16章から草を置いているrandom01と同じ生成器です):

// 浮島の周りの岩の環。位置・回転・大きさ・色は決まった乱数で / the ring of rocks around the floating island;
// position, rotation, size and colour from a fixed pseudo-random sequence
static std::vector<InstanceData> makeRing() {
  std::vector<InstanceData> rocks;
  rocks.reserve(kMaxRocks);
  std::uint32_t seed = 19;
  for (int i = 0; i < kMaxRocks; ++i) {
    // 半径:二つの乱数の平均で真ん中を濃く / radius: the mean of two randoms makes the middle denser
    float radius = 8.0f + 6.5f * 0.5f * (random01(seed) + random01(seed));
    float angle = 2.0f * PI * random01(seed);
    float height = 2.0f + 0.45f * (random01(seed) + random01(seed) + random01(seed) - 1.5f) / 1.5f;
    float u = random01(seed);
    float size = 0.08f + 0.4f * u * u * u; // 小さい岩が多い / mostly small rocks
    Vec3 axis = normalize(Vec3{random01(seed) - 0.5f, random01(seed) - 0.5f, random01(seed) - 0.5f});
    float spin = 2.0f * PI * random01(seed);
    float shade = 0.7f + 0.45f * random01(seed);
    float warm = 0.12f * (random01(seed) - 0.5f);
    InstanceData d;
    d.model = translate({radius * std::cos(angle), height, radius * std::sin(angle)}) * rotate(axis, spin) *
              scale({size, size, size});
    d.color = {shade + warm, shade, shade - warm};
    rocks.push_back(d);
  }
  return rocks;
}

環の形を作る小さな工夫が幾つかあります:

  • 2つの乱数の平均は両端より真ん中に近い値になり易い(三角分布)ので、環は半径11.25 mで一番濃く、8 mと14.5 mに向かって薄くなります。
  • 高さは3つの乱数の平均を2 ± 0.45 mに広げた物です。殆どベルの形の曲線なので、環は平たい帯になり、はみ出す岩が少しだけあります。
  • 大きさにはu3を使います。u3の値は殆どが小さいので、殆どの岩は8 cmの小石で、少しだけ最大48 cmの大岩があります。
  • ランダムな軸の周りの回転(linalg.hhのrotate(axis, angle))で、全ての岩が同じメッシュである事を隠します。

列が決まっているので環は毎回同じで、64 000個の最初の1000個は4000個の最初の1000個でもあります。
=と−は、他の岩を並べ直さずに岩を足したり減らしたりします。

バッファはフラグ0(不変、更新しない)で1回だけ作り、岩のモデルの全てのプリミティブに繋ぎます:

  // インスタンスのバッファ:全部の岩を一度だけアップロード。描く数を変えても作り直さない(先頭からcount個使う)
  // The instance buffer: every rock uploaded once. Changing the count does not rebuild it (the first `count` are used)
  std::vector<InstanceData> ring = makeRing();
  Buffer instanceBuffer(ring.data(), static_cast<GLsizeiptr>(ring.size() * sizeof(InstanceData)));
  rock->setInstanceBuffer(instanceBuffer, sizeof(InstanceData), kInstanceLayout);

岩の数を変えても変わるのはinstancecountだけで、バッファには常に最大数が入っています。
CPU側のringのvectorも残しておきます。
1つずつ描くモードが其れを読むからです。

環の2つの描き方

環は島と草の後、スカイボックスの前に描きます(第18章のフレームの順番は今も有効です):

    if (instanced) {
      // インスタンシング:プリミティブ1つにつき描画呼び出し1回。公転はシェーダーがuTimeで計算する
      // Instancing: one draw call per primitive. The shader computes the orbit from uTime
      rocksShader->use();
      rocksShader->set("uViewMode", viewMode);
      rocksShader->set("uEnvironmentTint", environmentTint);
      rocksShader->set("uOrbitSpeed", kOrbitSpeed);
      rock->drawInstanced(*rocksShader, white, rockCount);
    } else {
      // 一つずつ:岩ごとにuModel・uNormalMatrix・マテリアル・uTintを設定して描画呼び出し。公転はCPUで計算
      // One by one: per rock set uModel, uNormalMatrix, the material and uTint, then a draw call. The orbit is
      // computed on the CPU
      phong->use();
      for (int i = 0; i < rockCount; ++i) {
        const InstanceData &d = ring[static_cast<size_t>(i)];
        phong->set("uTint", d.color);
        rock->draw(*phong, rotateY(orbitAngle(d.model, animTime)) * d.model, white);
      }
      phong->set("uTint", Vec3{1.0f, 1.0f, 1.0f});
    }

インスタンシングの方はユニフォームを3つ設定し、数に関係無く描画呼び出しを1回します。
1つずつの方は、此の章が無ければ環をどう描くかを示しています。
岩毎に、シェーダーと同じ式でCPUで公転を計算し、

// 公転の角度:内側ほど速い(ケプラー:角速度 ∝ 半径^-1.5)。phong_instanced.vertと同じ式
// The orbit angle: inner rocks move faster (Kepler: angular speed ∝ radius^-1.5). Same formula as phong_instanced.vert
static float orbitAngle(const Mat4 &instance, float time) {
  float radius = std::sqrt(instance.c[3].x * instance.c[3].x + instance.c[3].z * instance.c[3].z);
  return time * kOrbitSpeed * std::pow(8.0f / radius, 1.5f);
}

色合いを設定してModel::drawを呼びます。
Model::drawはuModelを設定し、法線行列を計算して(4×4の逆行列)設定し、マテリアルを適用し(ユニフォーム10個とテクスチャの結合3回)、glDrawElementsを呼びます。
岩1つに付き、名前の検索付きのユニフォームの呼び出しが13回と描画呼び出しです。
最後にuTintを白に戻します。
そうしないと、次のフレームのジオラマが最後の岩の色に染まります。

どちらの方法でも同じ絵になります。
コードを作った時にピクセル毎に比べました。
921 600ピクセルの内、違うのは127ピクセルで、差は最大で255の内13です。
公転と法線の計算の浮動小数点の丸めの為です(CPUとシェーダーは同じ式を違う丸めと違う順番で計算します):

左:インスタンシングで描画呼び出し1回で描いた環。右:同じフレームを4000回の描画呼び出しで1つずつ描いた物。2つの絵は同じに見える

そして此れが、全てインスタンシングの呼び出し1回で描いた、1000、4000、16 000、64 000個の岩の環です:

シーンの4つの眺め。岩が1000個だと環はまばらで、4000個(既定)だとはっきりした帯、16000個だと濃く、64000個だと島の周りの殆ど隙間の無い岩の絨毯になる

19.13 正直に測る

2つの時計

プログラムは環だけを2つの違う時計で測ります:

    // 岩の環:ここだけ時間を測る / the ring of rocks: only this part is timed
    gpuTimer.begin();
    auto cpuStart = std::chrono::steady_clock::now();

    double cpuMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - cpuStart).count();
    gpuTimer.end();

std::chrono::steady_clockはコマンドを出すのに掛かったCPUの時間を測ります。
あたし達のコードとドライバーが、其の分岐を通り抜けるのにどれだけ掛かったかです。
OpenGLの呼び出しはGPUが仕事をするずっと前に戻るので、GPUが何時実際に描くかについては何も分かりません。

GPU側については、OpenGLにタイマークエリがあり、src/gpu_timer.hhで包んでいます:

class GpuTimer {
public:
  GpuTimer();
  ~GpuTimer();
  GpuTimer(const GpuTimer &) = delete;
  GpuTimer &operator=(const GpuTimer &) = delete;

  void begin();
  void end();
  // 一番新しく届いた結果(ミリ秒)。まだ一つも届いていなければstd::nullopt
  // The most recent result that has arrived (milliseconds). std::nullopt if none has arrived yet
  std::optional<double> latestMs();

private:
  static constexpr int kQueries = 4; // 4フレーム分まで遅れて良い / results may lag up to 4 frames
  GLuint queries[kQueries] = {};
  bool pending[kQueries] = {};
  int next = 0;
  bool running = false;
  std::optional<double> latest;
};

GpuTimer::GpuTimer() { glCreateQueries(GL_TIME_ELAPSED, kQueries, queries); }

GpuTimer::~GpuTimer() { glDeleteQueries(kQueries, queries); }

void GpuTimer::begin() {
  // 使おうとしているクエリの結果がまだなら、今回は測らない(待つとCPUとGPUが同期して遅くなる)
  // If the query we would use still has no result, skip this measurement (waiting would stall CPU and GPU)
  latestMs();
  if (pending[next]) return;
  glBeginQuery(GL_TIME_ELAPSED, queries[next]);
  running = true;
}

void GpuTimer::end() {
  if (!running) return;
  glEndQuery(GL_TIME_ELAPSED);
  pending[next] = true;
  next = (next + 1) % kQueries;
  running = false;
}

std::optional<double> GpuTimer::latestMs() {
  // 古い順に、届いた結果を読む / read the results that have arrived, oldest first
  for (int k = 0; k < kQueries; ++k) {
    int i = (next + k) % kQueries;
    if (!pending[i]) continue;
    GLint available = 0;
    glGetQueryObjectiv(queries[i], GL_QUERY_RESULT_AVAILABLE, &available);
    if (!available) continue;
    GLuint64 ns = 0;
    glGetQueryObjectui64v(queries[i], GL_QUERY_RESULT, &ns); // ナノ秒 / nanoseconds
    latest = static_cast<double>(ns) / 1.0e6;
    pending[i] = false;
  }
  return latest;
}

関数:

  • glCreateQueries(target, n, ids)はtarget用のクエリオブジェクトをn個作ります(DSA。古いglGenQueriesはターゲット無しの名前を作ります)。GL_TIME_ELAPSEDは時間を測ります。他のターゲットは深度テストを通ったサンプル(GL_SAMPLES_PASSED、GL_ANY_SAMPLES_PASSED)やプリミティブを数えます。
  • glBeginQuery(GL_TIME_ELAPSED, id)とglEndQuery(GL_TIME_ELAPSED)で、測るコマンドを囲みます。1つのターゲットで同時に有効なクエリは1つだけなので、タイマークエリは入れ子に出来ません。
  • glGetQueryObjectiv(id, GL_QUERY_RESULT_AVAILABLE, &available)は、囲んだ仕事をGPUが終えたかを、待たずに聞きます。
  • glGetQueryObjectui64v(id, GL_QUERY_RESULT, &ns)は結果を読みます。64ビット整数のナノ秒です。結果がまだ無ければ、此の呼び出しは結果が出る迄待ちます。

最後の点が、GpuTimerがクエリを4つ持つ理由です。
GPUはCPUより1〜2フレーム遅れて動きます。
glEndQueryの直後に結果を読むと、CPUは毎フレームGPUが追い付く迄座って待ち、測りたかった並列性其の物を壊してしまいます。
其の代わりにクエリを順番に使い、GL_QUERY_RESULT_AVAILABLEが良いと言った時だけ結果を読み、次のクエリがまだ使用中なら其のフレームは測りません。

数字の正体

此のシリーズの全てのスクリーンショットを作ったスクリプト付きのハーネスで記録した、3つの岩の数と両方のモードでの、フレーム61〜120の平均です:

ターミナルの出力。1000個:インスタンシング、描画呼び出し1回、CPU 28.33 ms、GPU 12.15 ms。1つずつ、描画呼び出し1000回、CPU 32.70 ms、GPU 12.68 ms。4000個:インスタンシング CPU 107.57 ms、GPU 91.25 ms。1つずつ CPU 118.80 ms、GPU 97.21 ms。16000個:インスタンシング CPU 395.81 ms、GPU 375.04 ms。1つずつ CPU 433.94 ms、GPU 412.90 ms。注意書き:Mesa llvmpipe、GPUはCPU、GPUの数字ではない

此れを読み解く前に、何処から来た数字かを見て下さい。
此のマシンにはGPUがありません。
Mesaのllvmpipeというソフトウェアラスタライザーで動いていて、頂点シェーダーもラスタライズもフラグメントシェーダーも全てCPUのスレッドで実行されます。
llvmpipeでは描画呼び出しのシェーディングの多くが描画呼び出しの中で行われます。
其の為インスタンシングの呼び出し1回でさえ、4000個で約108 msのCPU時間が「掛かり」、GL_TIME_ELAPSEDは此処ではグラフィックスカードではなくソフトウェアラスタライザーを測っています。
此れらのミリ秒は、本物のハードウェアでどれだけ速く動くかについて何も語りませんし、あたしもそうでない振りはしません。

数字がはっきり見せてくれる事が1つだけあります。
別々の描画呼び出しの余分なコストです。
シェーディングの仕事はどちらのモードでも同じなので、差を取ると消えるからです:

岩 インスタンシングのCPU 1つずつのCPU 差 余分な描画呼び出し1回当たり
1 000 28.33 ms 32.70 ms 4.37 ms 4.4 µs
4 000 107.57 ms 118.80 ms 11.23 ms 2.8 µs
16 000 395.81 ms 433.94 ms 38.13 ms 2.4 µs

別々に描く岩1つに付き約2.4〜4.4マイクロ秒です。
此れに何が含まれているかを忘れないで下さい。
glDrawElementsだけでなく、名前の検索付きの13回のユニフォームの呼び出し、テクスチャの結合3回、逆行列、Model::drawの小さなstd::vectorが含まれていて、しかも最適化フラグの無いビルド(ビルドの種類を指定しない時のCMakeの既定)です。
あたし達のエンジンのやり方で「物1つに描画呼び出し1回」とした時の値段であって、OpenGL一般の性質ではありません。

本物のGPUでは何が変わるか

デスクトップのGPUにとって、4000 × 320 = 128万枚の小さな三角形のシェーディングは小さな仕事で、16 000個でもまだ大した事はありません。
でもCPU側は速くなりません。
物1つ当たりの其のマイクロ秒は、あたし達のコードとドライバーの状態の検証とコマンドの組み立てに使われ、物の数に比例して積み重なります。
従って本物のハードウェアでは、釣り合いが完全に傾きます。
インスタンシングのモードでは環のCPU時間は小さいままで、数が増えても増えません。
1つずつのモードのCPU時間は岩が増える度に増え、或る数で其れがフレーム全体になります。
GPUは何もせずに、CPUが次の岩を説明するのを待つ事になります。
其処でインスタンシングが大きく勝ち、其れが全てのエンジンが繰り返す物を此の方法で描く理由です。

あなたのマシンでの測定値をあたしは示せませんし、他人のマシンの数字は誤解を招くだけです。
自分で動かしてみて下さい。
ウィンドウのタイトルに岩の数、描画呼び出しの数、両方の時間が出て、1秒程毎に更新されます。
Iでモードを切り替え、=で岩を足して、CPUの列を見て下さい。
プログラムが最初に表示する行(第2章のレンダラー)がllvmpipe又はsoftpipeなら、あなたもソフトウェアレンダラーで動いていて、上の表に似た物が見えるはずです。

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

  • 時間を測るならReleaseビルド。 DebugビルドのCPU時間は、殆どが最適化の無さを測っています。Windowsではcmake --build build --config Releaseでビルドし、プロジェクトのルートからbuild\Release\game.exeを実行します。Linux及びFreeBSDではcmake -S . -B build-release -DCMAKE_BUILD_TYPE=Releaseで別のディレクトリを設定します。両方のモードを同じビルドで比べて下さい。
  • タイマークエリは、WindowsとLinuxのNVIDIA、AMD、Intelのドライバー、及びLinuxとFreeBSD(drm-kmodのグラフィックスドライバー経由)のMesaのハードウェアドライバー(radeonsi、iris)で、本物のGPUの時間を返します。仮想マシンの中やGPUのドライバーが無い時はllvmpipeになります。glxinfo -B(Linux、FreeBSD)でもレンダラーが分かります。
  • =と−のキーはGLFWのGLFW_KEY_EQUALとGLFW_KEY_MINUSで、USキーボードでの位置で名前が付いています。日本語(JIS)キーボードでは、GLFW_KEY_EQUALは−の右の^キーです。ドイツ語のキーボードではßの右の´キーで、GLFW_KEY_MINUSはß其の物です。
  • 垂直同期(第2章)はフレームレートをモニターのリフレッシュレートに制限するので、どちらかのモードがリフレッシュ1回分より長く掛かる迄、フレームレートには違いが出ません。環のCPU時間には出ます。

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

  • シェーダーストレージバッファ(SSBO)。 OpenGL 4.3から、layout(std430, binding = N) buffer Name { … };でGL_SHADER_STORAGE_BUFFERを元にしたブロックを宣言出来ます。とても大きく出来(何メガバイトも、実際には殆どメモリで制限されます)、シェーダーから書き込め、最後のメンバーを大きさの無い配列(InstanceData instances[];)に出来、std430はスカラーとvec2の配列を隙間無く詰めます(vec3は相変わらず16バイトに揃います)。エンジンはシーン全体の物毎のデータ(行列、マテリアルの番号、バウンディングスフィア)をSSBOに入れ、gl_InstanceID又は描画コマンドに入れた番号で読みます。
  • 更新の頻度毎のブロック。 あたし達の分け方(フレーム毎:カメラ、フレーム毎:光、描画毎:普通のユニフォーム)を更に進めた物が普通です。フレーム毎、パス毎、マテリアル毎、物毎のブロックがあり、其の多くを1つの大きなバッファに詰め、GL_UNIFORM_BUFFER_OFFSET_ALIGNMENTに揃えたオフセットでglBindBufferRangeを使って選びます。バッファは永続的なマップを通じて、フレームのリングとして書きます(第25章でスプライトの為に此の技法を見せます)。
  • マルチドローインダイレクト。 glMultiDrawElementsIndirect(mode, type, indirect, drawcount, stride)は、GL_DRAW_INDIRECT_BUFFERに入れたDrawElementsIndirectCommand {count, instanceCount, firstIndex, baseVertex, baseInstance}の配列から沢山の描画を実行します。全てのメッシュを1つの大きな頂点バッファとインデックスバッファに入れれば、1回の呼び出しで違うメッシュを其々インスタンシング付きで描け、gl_DrawID(GLSL 4.60)がシェーダーにどのコマンドの物かを教えます。インスタンシングの「同じメッシュ」という制限が無くなります。
  • GPUカリング。 描画コマンドがバッファの中にあれば、GPUが自分で其れを書けます。コンピュートシェーダー(GLSL 第15章)が全てのインスタンスのバウンディングスフィアをカメラの視錐台と(多くの場合は遮蔽の為に深度のピラミッドとも)比べ、見える物をインスタンスのリストに追加し、数をインダイレクトバッファに書きます。CPUは、見える岩が幾つあるかさえ知りません。課題7で、視錐台の判定のCPU版をやります。
  • VulkanとSlang。 Vulkanにも同じブロック(ディスクリプタセットのユニフォームバッファとストレージバッファ、そして小さなプッシュ定数)があり、std140とstd430の規則も同じで、SlangのConstantBuffer<T>が其れに対応します。19.4節の内容は全て其のまま使えます。

19.16 まとめ

  • 普通のユニフォームは1つのプログラムの物です。ユニフォームブロックは、番号付きの結合点に繋いだバッファからメンバーを読みます。C++側はglBindBufferBase(GL_UNIFORM_BUFFER, N, buffer)、GLSLではlayout(std140, binding = N) uniform Block { … };です。
  • インスタンス名が無ければメンバーはグローバルな名前になるので、古いシェーダーの書き換えはユニフォームをブロックに置き換えるだけです。全てのシェーダーが同じ形でブロックを宣言しなければなりません。GLSLには#includeがありません。
  • std140:スカラーは4、vec2は8、vec3とvec4は16に揃います。vec3は12バイトで、後ろのスカラーが其の穴を埋めます。mat3は48、mat4は64バイト。配列の要素と構造体は16に切り上げです。Camera = 144バイト(uTimeは140)、Lights = 704バイト(オフセット0、32、416、672、684、688)。
  • vec3の罠:C++のVec3はアラインメント4の12バイトなので、C++の構造体には明示的な詰め物が要ります。static_assert(offsetof(…))で確かめ、起動時に16に切り上げたGL_UNIFORM_BLOCK_DATA_SIZEとsizeofを比べます。
  • glNamedBufferSubDataで更新するバッファにはGL_DYNAMIC_STORAGE_BITが必要です。結合点はコンテキスト全体の状態です。
  • インスタンシング:glDrawElementsInstanced(mode, count, type, indices, instancecount)はメッシュをinstancecount回描きます。インスタンス毎の属性はバインディング1の2つ目の頂点バッファにあり、glVertexArrayBindingDivisor(vao, 1, 1)でインスタンス毎に1つ進みます。
  • mat4の属性はロケーションを4つ使います(此処では4〜7、1列ずつ、オフセット0、16、32、48)。インスタンスの色は8です。
  • 公転はカメラのブロックのuTimeから頂点シェーダーで計算するので、インスタンスバッファは1回アップロードするだけで変えません。mat3(model)による法線は一様な拡大縮小の時だけ正しいです。
  • llvmpipeでは「GPU」はCPUなので、あたし達の時間はGPUの数字ではありません。はっきり分かるのは、余分な描画呼び出し1回当たり約2.4〜4.4 µsのCPU時間です。本物のGPUでは、インスタンシングが取り除くのは此の物毎のCPUのコストです。

19.17 課題

  1. ★ C++のCameraBlockのtimeの後にfloat exposureとfloat pad[3]を足し(160バイトになるのでstatic_assertも直します)、float uExposureは1つのシェーダー、skybox.vertのuTimeの後にだけ足して下さい。プログラムは起動を拒み、checkUniformBlockがphongのCameraブロックは144バイト、C++の構造体は160バイトだと表示するはずです。ブロックを宣言している他の5つのシェーダーにも足すと又動きます。其の後pad[3]を消すと(static_assertは148に)、シェーダーがどうであれ決して起動しなくなります。148は16の倍数ではなく、切り上げたドライバーの大きさと等しくなる事は無いからです。
  2. ★ 全てのメンバーのオフセットを自分で表示して下さい。名前("uView"、"uPointLights[1].position"…)を集め、glGetUniformIndicesで番号を、glGetActiveUniformsiv(program, n, indices, GL_UNIFORM_OFFSET, offsets)でオフセットを得ます。19.4節のスクリーンショットと全く同じ数字になるはずです。
  3. ★ PointLightStd140からfloat pad0を消し、代わりに最後にfloat pad3を足して、構造体を48バイトのままにして下さい。全てのstatic_assertも起動時の大きさの検査も通ります。夜(N)にランタンの光はより濃い橙色になり、ずっと遠く迄届くはずです。シェーダーがcolorをC++のcolor.y、color.z、pad1、つまり(1.6, 0.7, 0)から、attenuationを(0.35, 0.44, 0)から読む様になり、2次の項が消えるからです。エラーは何も出ません。大きさの検査では見付からない種類の間違いです。
  4. ★★ 色のデータ無しで岩に色を付けて下さい。phong_instanced.vertで、gl_InstanceID % 3で3色の1つを選びます。環にははっきり違う3色の岩が繰り返し並び、インスタンスの色の属性は使われなくなるはずです。
  5. ★★ 公転をCPUに移して下さい。InstanceDataのバッファをGL_DYNAMIC_STORAGE_BIT付きで作り、毎フレーム全ての行列をorbitAngleで回し、最初のrockCount個をBuffer::updateでアップロードし、シェーダーから公転を消します。絵は同じですが、ハードウェアのGPUでは、タイトルのCPU時間がインスタンシングのモードでも岩の数と共に増える様になるはずです(llvmpipeではシェーディングが描画呼び出しの中で行われるので元々増えています。増えた分のミリ秒を見て下さい)。
  6. ★★ 全ての岩を転がして下さい。InstanceDataにロケーション9のVec4 spin(xyzが軸、wが角速度)を足し、シェーダーでaInstanceModelを掛ける前に岩を自分の軸の周りに回します。岩は公転しながら転がるはずです。正しい側から掛けているか確かめて下さい。
  7. ★★★ CPUで視錐台カリングをして下さい。毎フレーム各岩のワールドの位置と半径を計算し、バウンディングスフィアを視錐台(線型代数 第12章)の6つの平面と比べ(各平面はproj · viewの4行目に1〜3行目の1つを足すか引いた物で、xyzの部分の長さで割ります)、見えるインスタンスだけを動的なインスタンスバッファに書いて其の数だけ描きます。数を表示して下さい。カメラが環の中から外を向いている時、描かれるインスタンスはrockCountよりずっと少なくなり、フレームが速くなるはずです。

DIFFをダウンロード

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

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

前新
@@ -42,7 +42,8 @@ add_executable(game
42 src/gltf.cc 42 src/gltf.cc
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 target_include_directories(game PRIVATE src external/stb external/linalg) 47 target_include_directories(game PRIVATE src external/stb external/linalg)
47 target_link_libraries(game PRIVATE glad stb_image glfw) 48 target_link_libraries(game PRIVATE glad stb_image glfw)
48   49  

ファイル: a/assets/LICENSE.txt | b/assets/LICENSE.txt

前新
@@ -11,5 +11,6 @@ textures/rug.png 敷物 / a runner rug (chapter 15)
11 textures/grass_blades.png 草の葉(アルファ付き) / grass blades with alpha (chapter 16) 11 textures/grass_blades.png 草の葉(アルファ付き) / grass blades with alpha (chapter 16)
12 textures/sky/*.png 空のキューブマップの6面 / the six sky cube-map faces (chapter 18) 12 textures/sky/*.png 空のキューブマップの6面 / the six sky cube-map faces (chapter 18)
13 models/window.glb 花箱つきの窓 / a window with a flower box (chapter 16) 13 models/window.glb 花箱つきの窓 / a window with a flower box (chapter 16)
    14 models/rock.glb 岩(インスタンシング用) / a rock for instancing (chapter 19)
14 models/crate.glb 木箱のモデル / crate model 15 models/crate.glb 木箱のモデル / crate model
15 models/diorama.glb 小さな場面 / a small diorama scene 16 models/diorama.glb 小さな場面 / a small diorama scene

ファイル: /dev/null | b/assets/models/rock.glb

新しいファイル:100644 / バイナリファイル

ファイル: a/shaders/envmap.frag | b/shaders/envmap.frag

前新
@@ -6,7 +6,14 @@ in vec3 vNormal;
6   6  
7 layout(binding = 3) uniform samplerCube uEnvironment; 7 layout(binding = 3) uniform samplerCube uEnvironment;
8   8  
9 uniform vec3 uViewPos; 9 // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
    10 // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
    11 layout(std140, binding = 0) uniform Camera {
    12 mat4 uView;
    13 mat4 uProj;
    14 vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
    15 float uTime; // アニメーションの時間(秒) / animation time (seconds)
    16 };
10 uniform int uEnvMode; // 0 = 反射 / reflection, 1 = 屈折 / refraction, 2 = フレネル(ガラス) / Fresnel (glass) 17 uniform int uEnvMode; // 0 = 反射 / reflection, 1 = 屈折 / refraction, 2 = フレネル(ガラス) / Fresnel (glass)
11 uniform float uIor; // 屈折率(ガラス1.52、水1.33) / index of refraction (glass 1.52, water 1.33) 18 uniform float uIor; // 屈折率(ガラス1.52、水1.33) / index of refraction (glass 1.52, water 1.33)
12 uniform vec3 uTint; // 反射・屈折の色 / colour of the reflection / refraction 19 uniform vec3 uTint; // 反射・屈折の色 / colour of the reflection / refraction

ファイル: a/shaders/phong.frag | b/shaders/phong.frag

前新
@@ -2,6 +2,7 @@
2 in vec3 vWorldPos; 2 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   6  
6 // 表面の性質。色はそれぞれのマップと掛け合わされる / surface properties; each colour is multiplied with its map 7 // 表面の性質。色はそれぞれのマップと掛け合わされる / surface properties; each colour is multiplied with its map
7 struct Material { 8 struct Material {
@@ -25,6 +26,9 @@ layout(binding = 2) uniform sampler2D uEmissionMap;
25 layout(binding = 3) uniform samplerCube uEnvironmentMap; 26 layout(binding = 3) uniform samplerCube uEnvironmentMap;
26 uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) 27 uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night)
27   28  
    29 // 光の構造体。std140では各vec3が16バイトの境目から始まる:C++のLightsBlockと同じ並び(lights.hh)
    30 // The light structs. In std140 each vec3 starts on a 16-byte boundary: the same layout as LightsBlock in C++ (lights.hh)
    31  
28 // 平行光源:向きだけ / directional light: a direction only 32 // 平行光源:向きだけ / directional light: a direction only
29 struct DirectionalLight { 33 struct DirectionalLight {
30 vec3 direction; // 光が進む向き(単位ベクトル) / the direction the light travels (unit vector) 34 vec3 direction; // 光が進む向き(単位ベクトル) / the direction the light travels (unit vector)
@@ -38,13 +42,14 @@ struct PointLight {
38 vec3 attenuation; // 定数項・一次・二次 / constant, linear, quadratic 42 vec3 attenuation; // 定数項・一次・二次 / constant, linear, quadratic
39 }; 43 };
40   44  
41 // スポットライト:点光源+円錐 / spotlight: a point light + a cone 45 // スポットライト:点光源+円錐。floatはvec3の後ろの隙間に入れる(詰め物が減る)
    46 // spotlight: a point light + a cone. The floats sit in the gaps after the vec3s (less padding)
42 struct SpotLight { 47 struct SpotLight {
43 vec3 position; 48 vec3 position;
44 vec3 direction; // 円錐の軸(単位ベクトル) / the cone's axis (unit vector)    
45 vec3 color;    
46 float cosInner; // 内側の円錐の半角のコサイン / cosine of the inner cone's half angle 49 float cosInner; // 内側の円錐の半角のコサイン / cosine of the inner cone's half angle
    50 vec3 direction; // 円錐の軸(単位ベクトル) / the cone's axis (unit vector)
47 float cosOuter; // 外側の円錐の半角のコサイン / cosine of the outer cone's half angle 51 float cosOuter; // 外側の円錐の半角のコサイン / cosine of the outer cone's half angle
    52 vec3 color;
48 vec3 attenuation; 53 vec3 attenuation;
49 }; 54 };
50   55  
@@ -52,14 +57,24 @@ struct SpotLight {
52 #define MAX_POINT_LIGHTS 8 57 #define MAX_POINT_LIGHTS 8
53 #define MAX_SPOT_LIGHTS 4 58 #define MAX_SPOT_LIGHTS 4
54   59  
55 uniform DirectionalLight uDirLight; 60 // 全部の光(ユニフォームバッファ、結合点1) / all lights (uniform buffer, binding 1)
56 uniform PointLight uPointLights[MAX_POINT_LIGHTS]; 61 layout(std140, binding = 1) uniform Lights {
57 uniform int uPointLightCount; // 使っている数 / how many are in use 62 DirectionalLight uDirLight;
58 uniform SpotLight uSpotLights[MAX_SPOT_LIGHTS]; 63 PointLight uPointLights[MAX_POINT_LIGHTS];
59 uniform int uSpotLightCount; 64 SpotLight uSpotLights[MAX_SPOT_LIGHTS];
    65 vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness
    66 int uPointLightCount; // 使っている数 / how many are in use
    67 int uSpotLightCount;
    68 };
60   69  
61 uniform vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness 70 // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
62 uniform vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space) 71 // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
    72 layout(std140, binding = 0) uniform Camera {
    73 mat4 uView;
    74 mat4 uProj;
    75 vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
    76 float uTime; // アニメーションの時間(秒) / animation time (seconds)
    77 };
63   78  
64 // 0 = 全部、1 = 環境光、2 = 拡散反射、3 = 鏡面反射、4 = 発光、5 = 法線 79 // 0 = 全部、1 = 環境光、2 = 拡散反射、3 = 鏡面反射、4 = 発光、5 = 法線
65 // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals 80 // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals
@@ -112,7 +127,7 @@ void main() {
112 // 両面のマテリアルを裏から見ているなら、法線は裏を向く / seen from behind, a double-sided surface's normal points the other way 127 // 両面のマテリアルを裏から見ているなら、法線は裏を向く / seen from behind, a double-sided surface's normal points the other way
113 if (uMaterial.doubleSided && !gl_FrontFacing) s.normal = -s.normal; 128 if (uMaterial.doubleSided && !gl_FrontFacing) s.normal = -s.normal;
114 s.view = normalize(uViewPos - vWorldPos); 129 s.view = normalize(uViewPos - vWorldPos);
115 s.diffuse = uMaterial.diffuse * base.rgb; 130 s.diffuse = uMaterial.diffuse * vTint * base.rgb;
116 s.specular = uMaterial.specular * texture(uSpecularMap, vUv).rgb; 131 s.specular = uMaterial.specular * texture(uSpecularMap, vUv).rgb;
117 s.shininess = uMaterial.shininess; 132 s.shininess = uMaterial.shininess;
118 vec3 emission = uMaterial.emission * texture(uEmissionMap, vUv).rgb; 133 vec3 emission = uMaterial.emission * texture(uEmissionMap, vUv).rgb;

ファイル: a/shaders/phong.vert | b/shaders/phong.vert

前新
@@ -3,20 +3,32 @@ 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   5  
    6 // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
    7 // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
    8 layout(std140, binding = 0) uniform Camera {
    9 mat4 uView;
    10 mat4 uProj;
    11 vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
    12 float uTime; // アニメーションの時間(秒) / animation time (seconds)
    13 };
    14  
6 uniform mat4 uModel; 15 uniform mat4 uModel;
7 uniform mat4 uView;    
8 uniform mat4 uProj;    
9 uniform mat3 uNormalMatrix; // 法線をワールド座標へ(モデル行列の逆行列の転置) / normals to world space (inverse transpose of uModel) 16 uniform mat3 uNormalMatrix; // 法線をワールド座標へ(モデル行列の逆行列の転置) / normals to world space (inverse transpose of uModel)
10   17  
11 // ライティングはワールド座標で計算する / lighting is computed in world space 18 // ライティングはワールド座標で計算する / lighting is computed in world space
12 out vec3 vWorldPos; 19 out vec3 vWorldPos;
13 out vec3 vNormal; 20 out vec3 vNormal;
14 out vec2 vUv; 21 out vec2 vUv;
    22 // インスタンスごとの色(第19章)。インスタンシングでないときはこのユニフォーム(既定値は白)
    23 // The per-instance colour (chapter 19). Without instancing it comes from this uniform (white by default)
    24 uniform vec3 uTint = vec3(1.0);
    25 out vec3 vTint;
15   26  
16 void main() { 27 void main() {
17 vec4 world = uModel * vec4(aPosition, 1.0); 28 vec4 world = uModel * vec4(aPosition, 1.0);
18 vWorldPos = world.xyz; 29 vWorldPos = world.xyz;
19 vNormal = uNormalMatrix * aNormal; // 正規化はフラグメントシェーダーで / normalized in the fragment shader 30 vNormal = uNormalMatrix * aNormal; // 正規化はフラグメントシェーダーで / normalized in the fragment shader
20 vUv = aUv; 31 vUv = aUv;
    32 vTint = uTint;
21 gl_Position = uProj * uView * world; 33 gl_Position = uProj * uView * world;
22 } 34 }

ファイル: /dev/null | b/shaders/phong_instanced.vert

前新
@@ -0,0 +1,49 @@
    1 #version 460 core
    2 // インスタンシング用のphong.vert:インスタンスごとの行列と色を頂点属性で受け取る(フラグメントシェーダーはphong.frag)
    3 // phong.vert for instancing: the per-instance matrix and colour arrive as vertex attributes (fragment shader: phong.frag)
    4 layout(location = 0) in vec3 aPosition;
    5 layout(location = 1) in vec3 aNormal;
    6 layout(location = 2) in vec2 aUv;
    7 // location 3は接線(第22章) / location 3 is the tangent (chapter 22)
    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;
    10  
    11 // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
    12 // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
    13 layout(std140, binding = 0) uniform Camera {
    14 mat4 uView;
    15 mat4 uProj;
    16 vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
    17 float uTime; // アニメーションの時間(秒) / animation time (seconds)
    18 };
    19  
    20 uniform mat4 uModel; // モデルの中のノードの行列 / the node's matrix inside the model
    21 uniform mat3 uNormalMatrix; // その法線行列 / its normal matrix
    22 uniform float uOrbitSpeed; // 環の公転の速さ(半径8 mで、ラジアン毎秒) / orbit speed of the ring (rad/s at radius 8 m)
    23  
    24 out vec3 vWorldPos;
    25 out vec3 vNormal;
    26 out vec2 vUv;
    27 out vec3 vTint;
    28  
    29 // Y軸周りの回転 / rotation about the Y axis
    30 mat4 rotationY(float a) {
    31 float c = cos(a), s = sin(a);
    32 return mat4(c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0);
    33 }
    34  
    35 void main() {
    36 // 公転:内側ほど速い(ケプラーの法則:角速度 ∝ 半径^-1.5)。C++のorbitAngle()と同じ式
    37 // Orbit: inner rocks are faster (Kepler: angular speed ∝ radius^-1.5). The same formula as orbitAngle() in C++
    38 float radius = length(aInstanceModel[3].xz);
    39 mat4 orbit = rotationY(uTime * uOrbitSpeed * pow(8.0 / radius, 1.5));
    40 mat4 model = orbit * aInstanceModel * uModel;
    41 vec4 world = model * vec4(aPosition, 1.0);
    42 vWorldPos = world.xyz;
    43 // 岩の拡大縮小は一様なので、法線は行列の3×3で回すだけで良い(長さはphong.fragで正規化)
    44 // 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 vUv = aUv;
    47 vTint = aInstanceColor;
    48 gl_Position = uProj * uView * world;
    49 }

ファイル: a/shaders/skybox.vert | b/shaders/skybox.vert

前新
@@ -3,8 +3,14 @@
3 // The sky box: a cube around the camera, textured from the inside by direction 3 // The sky box: a cube around the camera, textured from the inside by direction
4 layout(location = 0) in vec3 aPosition; // makeCube()の頂点(±0.5) / makeCube()'s vertices (±0.5) 4 layout(location = 0) in vec3 aPosition; // makeCube()の頂点(±0.5) / makeCube()'s vertices (±0.5)
5   5  
6 uniform mat4 uView; 6 // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
7 uniform mat4 uProj; 7 // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
    8 layout(std140, binding = 0) uniform Camera {
    9 mat4 uView;
    10 mat4 uProj;
    11 vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
    12 float uTime; // アニメーションの時間(秒) / animation time (seconds)
    13 };
8   14  
9 out vec3 vDirection; // キューブマップを引く方向 / the direction to look up the cube map with 15 out vec3 vDirection; // キューブマップを引く方向 / the direction to look up the cube map with
10   16  

ファイル: a/shaders/unlit.vert | b/shaders/unlit.vert

前新
@@ -1,9 +1,16 @@
1 #version 460 core 1 #version 460 core
2 layout(location = 0) in vec3 aPosition; 2 layout(location = 0) in vec3 aPosition;
3   3  
    4 // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
    5 // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
    6 layout(std140, binding = 0) uniform Camera {
    7 mat4 uView;
    8 mat4 uProj;
    9 vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
    10 float uTime; // アニメーションの時間(秒) / animation time (seconds)
    11 };
    12  
4 uniform mat4 uModel; 13 uniform mat4 uModel;
5 uniform mat4 uView;    
6 uniform mat4 uProj;    
7   14  
8 void main() { 15 void main() {
9 gl_Position = uProj * uView * uModel * vec4(aPosition, 1.0); 16 gl_Position = uProj * uView * uModel * vec4(aPosition, 1.0);

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

前新
@@ -7,6 +7,10 @@ Buffer::Buffer(const void *data, GLsizeiptr byteCount, GLbitfield flags) : bytes
7 glNamedBufferStorage(handle, byteCount, data, flags); 7 glNamedBufferStorage(handle, byteCount, data, flags);
8 } 8 }
9   9  
    10 void Buffer::update(const void *data, GLsizeiptr byteCount, GLintptr offset) const {
    11 glNamedBufferSubData(handle, offset, byteCount, data);
    12 }
    13  
10 Buffer::~Buffer() { 14 Buffer::~Buffer() {
11 if (handle) glDeleteBuffers(1, &handle); 15 if (handle) glDeleteBuffers(1, &handle);
12 } 16 }

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

前新
@@ -18,6 +18,13 @@ public:
18 Buffer(Buffer &&other) noexcept; 18 Buffer(Buffer &&other) noexcept;
19 Buffer &operator=(Buffer &&other) noexcept; 19 Buffer &operator=(Buffer &&other) noexcept;
20   20  
    21 // 中身の一部を書き換える(作るときにGL_DYNAMIC_STORAGE_BITが必要) / replaces part of the contents
    22 // (needs GL_DYNAMIC_STORAGE_BIT at creation)
    23 void update(const void *data, GLsizeiptr byteCount, GLintptr offset = 0) const;
    24 // 番号付きの結合点に繋ぐ(ユニフォームバッファなど、第19章) / attaches to an indexed binding point
    25 // (uniform buffers etc., chapter 19)
    26 void bindBase(GLenum target, GLuint index) const { glBindBufferBase(target, index, handle); }
    27  
21 GLuint id() const { return handle; } 28 GLuint id() const { return handle; }
22 GLsizeiptr size() const { return bytes; } 29 GLsizeiptr size() const { return bytes; }
23   30  

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

前新
@@ -0,0 +1,38 @@
    1 #include "gpu_timer.hh"
    2  
    3 GpuTimer::GpuTimer() { glCreateQueries(GL_TIME_ELAPSED, kQueries, queries); }
    4  
    5 GpuTimer::~GpuTimer() { glDeleteQueries(kQueries, queries); }
    6  
    7 void GpuTimer::begin() {
    8 // 使おうとしているクエリの結果がまだなら、今回は測らない(待つとCPUとGPUが同期して遅くなる)
    9 // If the query we would use still has no result, skip this measurement (waiting would stall CPU and GPU)
    10 latestMs();
    11 if (pending[next]) return;
    12 glBeginQuery(GL_TIME_ELAPSED, queries[next]);
    13 running = true;
    14 }
    15  
    16 void GpuTimer::end() {
    17 if (!running) return;
    18 glEndQuery(GL_TIME_ELAPSED);
    19 pending[next] = true;
    20 next = (next + 1) % kQueries;
    21 running = false;
    22 }
    23  
    24 std::optional<double> GpuTimer::latestMs() {
    25 // 古い順に、届いた結果を読む / read the results that have arrived, oldest first
    26 for (int k = 0; k < kQueries; ++k) {
    27 int i = (next + k) % kQueries;
    28 if (!pending[i]) continue;
    29 GLint available = 0;
    30 glGetQueryObjectiv(queries[i], GL_QUERY_RESULT_AVAILABLE, &available);
    31 if (!available) continue;
    32 GLuint64 ns = 0;
    33 glGetQueryObjectui64v(queries[i], GL_QUERY_RESULT, &ns); // ナノ秒 / nanoseconds
    34 latest = static_cast<double>(ns) / 1.0e6;
    35 pending[i] = false;
    36 }
    37 return latest;
    38 }

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

前新
@@ -0,0 +1,33 @@
    1 // GPUの時間を測る:タイマークエリ(GL_TIME_ELAPSED) / measuring GPU time with timer queries (GL_TIME_ELAPSED)
    2 #pragma once
    3  
    4 #include <glad/glad.h>
    5  
    6 #include <optional>
    7  
    8 // begin()〜end()の間のコマンドをGPUが実行するのにかかった時間。結果は数フレーム後に届くので、クエリを
    9 // 何個か順番に使い、届いたものから読む(待たない)。RAII、コピー不可・移動不可。
    10 // How long the GPU took to execute the commands between begin() and end(). The result arrives a few frames
    11 // later, so several queries are used in turn and the ones that have arrived are read (no waiting).
    12 // RAII, non-copyable, non-movable.
    13 class GpuTimer {
    14 public:
    15 GpuTimer();
    16 ~GpuTimer();
    17 GpuTimer(const GpuTimer &) = delete;
    18 GpuTimer &operator=(const GpuTimer &) = delete;
    19  
    20 void begin();
    21 void end();
    22 // 一番新しく届いた結果(ミリ秒)。まだ一つも届いていなければstd::nullopt
    23 // The most recent result that has arrived (milliseconds). std::nullopt if none has arrived yet
    24 std::optional<double> latestMs();
    25  
    26 private:
    27 static constexpr int kQueries = 4; // 4フレーム分まで遅れて良い / results may lag up to 4 frames
    28 GLuint queries[kQueries] = {};
    29 bool pending[kQueries] = {};
    30 int next = 0;
    31 bool running = false;
    32 std::optional<double> latest;
    33 };

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

前新
@@ -2,14 +2,12 @@
2   2  
3 #include <cmath> 3 #include <cmath>
4 #include <cstdio> 4 #include <cstdio>
5 #include <format>    
6   5  
7 void LightSet::apply(const Shader &shader) const { 6 LightsBlock LightSet::toBlock() const {
8 shader.set("uAmbient", ambient); 7 LightsBlock b{}; // 全部0(詰め物も) / all zero (the padding too)
9 shader.set("uDirLight.direction", normalize(directional.direction)); 8 b.directional.direction = normalize(directional.direction);
10 shader.set("uDirLight.color", directional.color); 9 b.directional.color = directional.color;
11   10  
12 // 配列の要素のメンバーは「名前[番号].メンバー」で設定する / array elements: "name[index].member"    
13 int pointCount = static_cast<int>(points.size()); 11 int pointCount = static_cast<int>(points.size());
14 if (pointCount > kMaxPointLights) { 12 if (pointCount > kMaxPointLights) {
15 fprintf(stderr, "点光源が多すぎる / too many point lights: %d (max %d)\n", pointCount, kMaxPointLights); 13 fprintf(stderr, "点光源が多すぎる / too many point lights: %d (max %d)\n", pointCount, kMaxPointLights);
@@ -17,11 +15,11 @@ void LightSet::apply(const Shader &shader) const {
17 } 15 }
18 for (int i = 0; i < pointCount; ++i) { 16 for (int i = 0; i < pointCount; ++i) {
19 const PointLight &p = points[static_cast<size_t>(i)]; 17 const PointLight &p = points[static_cast<size_t>(i)];
20 shader.set(std::format("uPointLights[{}].position", i).c_str(), p.position); 18 b.points[i].position = p.position;
21 shader.set(std::format("uPointLights[{}].color", i).c_str(), p.color); 19 b.points[i].color = p.color;
22 shader.set(std::format("uPointLights[{}].attenuation", i).c_str(), p.attenuation); 20 b.points[i].attenuation = p.attenuation;
23 } 21 }
24 shader.set("uPointLightCount", pointCount); 22 b.pointCount = pointCount;
25   23  
26 int spotCount = static_cast<int>(spots.size()); 24 int spotCount = static_cast<int>(spots.size());
27 if (spotCount > kMaxSpotLights) { 25 if (spotCount > kMaxSpotLights) {
@@ -30,14 +28,16 @@ void LightSet::apply(const Shader &shader) const {
30 } 28 }
31 for (int i = 0; i < spotCount; ++i) { 29 for (int i = 0; i < spotCount; ++i) {
32 const SpotLight &s = spots[static_cast<size_t>(i)]; 30 const SpotLight &s = spots[static_cast<size_t>(i)];
33 shader.set(std::format("uSpotLights[{}].position", i).c_str(), s.position); 31 b.spots[i].position = s.position;
34 shader.set(std::format("uSpotLights[{}].direction", i).c_str(), normalize(s.direction)); 32 b.spots[i].direction = normalize(s.direction);
35 shader.set(std::format("uSpotLights[{}].color", i).c_str(), s.color); 33 b.spots[i].color = s.color;
36 // シェーダーは角度ではなくコサインを比べる(acosを毎ピクセル計算しないため) 34 // シェーダーは角度ではなくコサインを比べる(acosを毎ピクセル計算しないため)
37 // The shader compares cosines, not angles (so it does not need acos for every pixel) 35 // The shader compares cosines, not angles (so it does not need acos for every pixel)
38 shader.set(std::format("uSpotLights[{}].cosInner", i).c_str(), std::cos(s.innerAngle)); 36 b.spots[i].cosInner = std::cos(s.innerAngle);
39 shader.set(std::format("uSpotLights[{}].cosOuter", i).c_str(), std::cos(s.outerAngle)); 37 b.spots[i].cosOuter = std::cos(s.outerAngle);
40 shader.set(std::format("uSpotLights[{}].attenuation", i).c_str(), s.attenuation); 38 b.spots[i].attenuation = s.attenuation;
41 } 39 }
42 shader.set("uSpotLightCount", spotCount); 40 b.spotCount = spotCount;
    41 b.ambient = ambient;
    42 return b;
43 } 43 }

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

前新
@@ -3,6 +3,7 @@
3   3  
4 #include "mathx.hh" 4 #include "mathx.hh"
5 #include "shader.hh" 5 #include "shader.hh"
    6 #include "uniforms.hh"
6   7  
7 #include <vector> 8 #include <vector>
8   9  
@@ -42,6 +43,61 @@ struct SpotLight {
42 Vec3 attenuation = kLongRange; 43 Vec3 attenuation = kLongRange;
43 }; 44 };
44   45  
    46 // ユニフォームバッファの中の光(std140の並び、第19章)。GLSLのLightsブロックと同じ:
    47 // The lights inside the uniform buffer (std140 layout, chapter 19). Same as the GLSL Lights block:
    48 // struct DirectionalLight { vec3 direction; vec3 color; }; // 32 bytes
    49 // struct PointLight { vec3 position; vec3 color; vec3 attenuation; }; // 48 bytes
    50 // struct SpotLight { vec3 position; float cosInner; vec3 direction; float cosOuter;
    51 // vec3 color; vec3 attenuation; }; // 64 bytes
    52 // layout(std140, binding = 1) uniform Lights {
    53 // DirectionalLight uDirLight; // offset 0
    54 // PointLight uPointLights[MAX_POINT_LIGHTS]; // offset 32 (8 × 48)
    55 // SpotLight uSpotLights[MAX_SPOT_LIGHTS]; // offset 416 (4 × 64)
    56 // vec3 uAmbient; // offset 672
    57 // int uPointLightCount; // offset 684
    58 // int uSpotLightCount; // offset 688
    59 // }; // 692 → 704 bytes (a multiple of 16)
    60 struct DirectionalLightStd140 {
    61 Vec3 direction;
    62 float pad0;
    63 Vec3 color;
    64 float pad1;
    65 };
    66 struct PointLightStd140 {
    67 Vec3 position;
    68 float pad0;
    69 Vec3 color;
    70 float pad1;
    71 Vec3 attenuation;
    72 float pad2;
    73 };
    74 struct SpotLightStd140 {
    75 Vec3 position;
    76 float cosInner; // vec3の後ろの隙間に入る / fits in the gap after the vec3
    77 Vec3 direction;
    78 float cosOuter;
    79 Vec3 color;
    80 float pad0;
    81 Vec3 attenuation;
    82 float pad1;
    83 };
    84 struct LightsBlock {
    85 DirectionalLightStd140 directional;
    86 PointLightStd140 points[kMaxPointLights];
    87 SpotLightStd140 spots[kMaxSpotLights];
    88 Vec3 ambient;
    89 int pointCount;
    90 int spotCount;
    91 int pad[3];
    92 };
    93 static_assert(sizeof(DirectionalLightStd140) == 32 && sizeof(PointLightStd140) == 48 && sizeof(SpotLightStd140) == 64);
    94 static_assert(offsetof(LightsBlock, points) == 32);
    95 static_assert(offsetof(LightsBlock, spots) == 416);
    96 static_assert(offsetof(LightsBlock, ambient) == 672);
    97 static_assert(offsetof(LightsBlock, pointCount) == 684);
    98 static_assert(offsetof(LightsBlock, spotCount) == 688);
    99 static_assert(sizeof(LightsBlock) == 704);
    100  
45 // シーンの全部の光 / all the lights of a scene 101 // シーンの全部の光 / all the lights of a scene
46 struct LightSet { 102 struct LightSet {
47 Vec3 ambient = {0.05f, 0.05f, 0.05f}; 103 Vec3 ambient = {0.05f, 0.05f, 0.05f};
@@ -49,7 +105,8 @@ struct LightSet {
49 std::vector<PointLight> points; 105 std::vector<PointLight> points;
50 std::vector<SpotLight> spots; 106 std::vector<SpotLight> spots;
51   107  
52 // 全部の光をシェーダーのユニフォームに設定する。最大数を超えた分は使わない。 108 // ユニフォームバッファに書く形にする(第19章。以前のapply(shader)の代わり)。最大数を超えた分は使わない。
53 // Sets all lights as shader uniforms. Lights beyond the maximum count are ignored. 109 // Converts to the uniform-buffer layout (chapter 19; replaces the former apply(shader)). Lights beyond the
54 void apply(const Shader &shader) const; 110 // maximum count are ignored.
    111 LightsBlock toBlock() const;
55 }; 112 };

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

前新
@@ -1,5 +1,5 @@
1 // 第18章:キューブマップ 1 // 第19章:ユニフォームバッファとインスタンシング
2 // Chapter 18: cubemaps 2 // Chapter 19: uniform buffers and instancing
3 // 3 //
4 // 操作 / Controls: 4 // 操作 / Controls:
5 // WASD 前後左右に移動 / move forward, back, left, right 5 // WASD 前後左右に移動 / move forward, back, left, right
@@ -7,24 +7,25 @@
7 // Shift 速く動く / move faster 7 // Shift 速く動く / move faster
8 // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit 8 // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit
9 // ホイール / wheel ズーム / zoom 9 // ホイール / wheel ズーム / zoom
10 // M 手前の3つ:いろいろ → 全部反射 → 全部屈折 → 全部フレネル 10 // I 岩:インスタンシング(描画呼び出し1回) ⇔ 一つずつ(岩の数だけ呼び出し)
11 // the three objects in front: mixed → all reflection → all refraction → all Fresnel 11 // rocks: instancing (one draw call) ⇔ one by one (one draw call per rock)
12 // K 空(スカイボックス)のオン・オフ / sky box on / off 12 // = / - 岩の数を倍に・半分に(250〜64000) / double / halve the number of rocks (250..64000)
13 // X 継ぎ目のないキューブマップの補間(GL_TEXTURE_CUBE_MAP_SEAMLESS)のオン・オフ    
14 // seamless cube-map filtering (GL_TEXTURE_CUBE_MAP_SEAMLESS) on / off    
15 // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 13 // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出
16 // effect: none / invert / grayscale / sharpen / blur / edge detection 14 // effect: none / invert / grayscale / sharpen / blur / edge detection
17 // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera 15 // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera
18 // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals 16 // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals
19 // N 昼 ⇔ 夜 / day ⇔ night 17 // N 昼 ⇔ 夜 / day ⇔ night
20 // F 懐中電灯のオン・オフ / flashlight on / off 18 // F 懐中電灯のオン・オフ / flashlight on / off
21 // P 風車と金色の木箱を止める・回す / pause / resume the windmill and the golden crate 19 // P 風車と岩の環を止める・動かす / pause / resume the windmill and the ring of rocks
22 // Tab カーソルのキャプチャ切り替え / toggle cursor capture 20 // Tab カーソルのキャプチャ切り替え / toggle cursor capture
23 // R シェーダーを読み直す / reload the shaders 21 // R シェーダーを読み直す / reload the shaders
24 // Esc 終了 / quit 22 // Esc 終了 / quit
    23 //
    24 // 時間はウィンドウのタイトルと標準出力に出る(60フレームごと) / timings go to the window title and stdout (every 60 frames)
25 #include "camera.hh" 25 #include "camera.hh"
26 #include "cubemap.hh" 26 #include "cubemap.hh"
27 #include "framebuffer.hh" 27 #include "framebuffer.hh"
    28 #include "gpu_timer.hh"
28 #include "lights.hh" 29 #include "lights.hh"
29 #include "material.hh" 30 #include "material.hh"
30 #include "mathx.hh" 31 #include "mathx.hh"
@@ -33,49 +34,65 @@
33 #include "shader.hh" 34 #include "shader.hh"
34 #include "shapes.hh" 35 #include "shapes.hh"
35 #include "texture.hh" 36 #include "texture.hh"
    37 #include "uniforms.hh"
36 #include "window.hh" 38 #include "window.hh"
37   39  
38 #include <algorithm> 40 #include <chrono>
39 #include <cmath> 41 #include <cmath>
40 #include <cstdint> 42 #include <cstdint>
41 #include <cstdio> 43 #include <cstdio>
42 #include <optional> 44 #include <optional>
43 #include <vector> 45 #include <vector>
44   46  
45 // 物を置く場所:位置(底の中心)とY軸周りの回転 / where things go: position (bottom centre) and yaw    
46 struct Placement { 47 struct Placement {
47 Vec3 position; 48 Vec3 position;
48 float angle; 49 float angle;
49 }; 50 };
50   51  
51 static const Placement kCrates[] = {    
52 {{5.5f, 0.0f, 1.5f}, 0.4f}, {{6.3f, 0.0f, 2.6f}, -0.3f}, {{5.9f, 1.0f, 2.0f}, 0.1f},    
53 {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f},    
54 };    
55      
56 // 手前の環境マッピングの物:球二つと、木箱のモデル / the environment-mapped objects in front: two spheres and the    
57 // crate model    
58 enum EnvMode { kReflect = 0, kRefract = 1, kFresnel = 2 };    
59 struct EnvObject {    
60 Vec3 position;    
61 int mode; // 「いろいろ」のときのモード / the mode in "mixed"    
62 Vec3 tint; // 反射の色(金属の色) / reflection colour (the metal's colour)    
63 };    
64 static const EnvObject kEnvObjects[] = {    
65 {{-2.8f, 0.75f, 7.0f}, kFresnel, {1.0f, 1.0f, 1.0f}}, // ガラスの球 / glass sphere    
66 {{0.0f, 1.0f, 7.6f}, kReflect, {0.95f, 0.8f, 0.55f}}, // 金色の木箱(宙に浮いて回る) / a golden crate (hovers, tumbling)    
67 {{2.8f, 0.75f, 7.0f}, kReflect, {0.95f, 0.95f, 0.97f}}, // クロムの球 / chrome sphere    
68 };    
69      
70 static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; 52 static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"};
71 static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; 53 static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"};
72 static const char *const kEnvModeNames[] = {"mixed", "all reflection", "all refraction", "all Fresnel"}; 54  
    55 constexpr int kMaxRocks = 64000;
    56 constexpr float kOrbitSpeed = 0.25f; // 半径8 mでの公転の角速度(ラジアン毎秒) / orbital angular speed at radius 8 m (rad/s)
73   57  
74 static float random01(std::uint32_t &state) { 58 static float random01(std::uint32_t &state) {
75 state = state * 1664525u + 1013904223u; 59 state = state * 1664525u + 1013904223u;
76 return static_cast<float>(state >> 8) / 16777216.0f; 60 return static_cast<float>(state >> 8) / 16777216.0f;
77 } 61 }
78   62  
    63 // 公転の角度:内側ほど速い(ケプラー:角速度 ∝ 半径^-1.5)。phong_instanced.vertと同じ式
    64 // The orbit angle: inner rocks move faster (Kepler: angular speed ∝ radius^-1.5). Same formula as phong_instanced.vert
    65 static float orbitAngle(const Mat4 &instance, float time) {
    66 float radius = std::sqrt(instance.c[3].x * instance.c[3].x + instance.c[3].z * instance.c[3].z);
    67 return time * kOrbitSpeed * std::pow(8.0f / radius, 1.5f);
    68 }
    69  
    70 // 浮島の周りの岩の環。位置・回転・大きさ・色は決まった乱数で / the ring of rocks around the floating island;
    71 // position, rotation, size and colour from a fixed pseudo-random sequence
    72 static std::vector<InstanceData> makeRing() {
    73 std::vector<InstanceData> rocks;
    74 rocks.reserve(kMaxRocks);
    75 std::uint32_t seed = 19;
    76 for (int i = 0; i < kMaxRocks; ++i) {
    77 // 半径:二つの乱数の平均で真ん中を濃く / radius: the mean of two randoms makes the middle denser
    78 float radius = 8.0f + 6.5f * 0.5f * (random01(seed) + random01(seed));
    79 float angle = 2.0f * PI * random01(seed);
    80 float height = 2.0f + 0.45f * (random01(seed) + random01(seed) + random01(seed) - 1.5f) / 1.5f;
    81 float u = random01(seed);
    82 float size = 0.08f + 0.4f * u * u * u; // 小さい岩が多い / mostly small rocks
    83 Vec3 axis = normalize(Vec3{random01(seed) - 0.5f, random01(seed) - 0.5f, random01(seed) - 0.5f});
    84 float spin = 2.0f * PI * random01(seed);
    85 float shade = 0.7f + 0.45f * random01(seed);
    86 float warm = 0.12f * (random01(seed) - 0.5f);
    87 InstanceData d;
    88 d.model = translate({radius * std::cos(angle), height, radius * std::sin(angle)}) * rotate(axis, spin) *
    89 scale({size, size, size});
    90 d.color = {shade + warm, shade, shade - warm};
    91 rocks.push_back(d);
    92 }
    93 return rocks;
    94 }
    95  
79 static std::vector<Placement> makeGrass() { 96 static std::vector<Placement> makeGrass() {
80 std::vector<Placement> grass; 97 std::vector<Placement> grass;
81 std::uint32_t seed = 16; 98 std::uint32_t seed = 16;
@@ -87,37 +104,32 @@ static std::vector<Placement> makeGrass() {
87 for (Vec3 q : avoid) ok = ok && length(Vec3{p.x - q.x, 0, p.z - q.z}) > 1.1f; 104 for (Vec3 q : avoid) ok = ok && length(Vec3{p.x - q.x, 0, p.z - q.z}) > 1.1f;
88 if (ok) grass.push_back({p, 2.0f * PI * random01(seed)}); 105 if (ok) grass.push_back({p, 2.0f * PI * random01(seed)});
89 } 106 }
90 const Placement front[] = {{{1.5f, 0, 6.2f}, 0.3f}, {{-4.0f, 0, 7.6f}, 1.2f}, {{3.9f, 0, 5.4f}, 2.0f},    
91 {{1.4f, 0, 8.9f}, 0.7f}, {{-1.6f, 0, 8.6f}, 2.6f}};    
92 for (const Placement &p : front) grass.push_back(p);    
93 return grass; 107 return grass;
94 } 108 }
95   109  
96 // 一つのカメラから見た場面を描くのに必要なもの / what is needed to draw the scene from one camera    
97 struct View {    
98 Mat4 view, proj;    
99 Vec3 position;    
100 };    
101      
102 int main() { 110 int main() {
103 Window window; 111 Window window;
104 if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 18")) return 1; 112 if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 19")) return 1;
105   113  
106 std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); 114 std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag");
107 std::optional<Shader> post = Shader::load("shaders/post.vert", "shaders/post.frag"); 115 // インスタンシング用:頂点シェーダーだけ違う / for instancing: only the vertex shader differs
    116 std::optional<Shader> rocksShader = Shader::load("shaders/phong_instanced.vert", "shaders/phong.frag");
108 std::optional<Shader> skybox = Shader::load("shaders/skybox.vert", "shaders/skybox.frag"); 117 std::optional<Shader> skybox = Shader::load("shaders/skybox.vert", "shaders/skybox.frag");
109 // 環境マッピング:頂点シェーダーはphongと同じ(ワールド座標の位置と法線) / environment mapping: the same vertex 118 std::optional<Shader> post = Shader::load("shaders/post.vert", "shaders/post.frag");
110 // shader as phong (world-space position and normal)    
111 std::optional<Shader> envmap = Shader::load("shaders/phong.vert", "shaders/envmap.frag");    
112 std::optional<Cubemap> sky = Cubemap::loadDirectory("assets/textures/sky"); 119 std::optional<Cubemap> sky = Cubemap::loadDirectory("assets/textures/sky");
113 std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png");    
114 std::optional<Texture2D> grassTexture = Texture2D::load("assets/textures/grass_blades.png"); 120 std::optional<Texture2D> grassTexture = Texture2D::load("assets/textures/grass_blades.png");
115 if (!phong || !post || !skybox || !envmap || !sky || !floorTexture || !grassTexture) return 1; 121 if (!phong || !rocksShader || !skybox || !post || !sky || !grassTexture) return 1;
116 grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); 122 grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
117   123  
    124 // C++の構造体とGLSLのブロックの大きさが合うか確かめる(std140の詰め物を間違えると違う)
    125 // Check that the C++ structs and the GLSL blocks have the same size (they differ if the std140 padding is wrong)
    126 for (const Shader *s : {&*phong, &*rocksShader, &*skybox})
    127 if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)))
    128 return 1;
    129  
118 std::optional<Model> scene = Model::load("assets/models/diorama.glb"); 130 std::optional<Model> scene = Model::load("assets/models/diorama.glb");
119 std::optional<Model> crate = Model::load("assets/models/crate.glb"); 131 std::optional<Model> rock = Model::load("assets/models/rock.glb");
120 if (!scene || !crate) return 1; 132 if (!scene || !rock) return 1;
121   133  
122 const unsigned char whitePixel[4] = {255, 255, 255, 255}; 134 const unsigned char whitePixel[4] = {255, 255, 255, 255};
123 Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); 135 Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false});
@@ -126,34 +138,51 @@ int main() {
126 int lanternNode = scene->findNode("LanternLight"); 138 int lanternNode = scene->findNode("LanternLight");
127 Quat rotorStart = rotor >= 0 ? scene->nodes[static_cast<size_t>(rotor)].rotation : Quat{}; 139 Quat rotorStart = rotor >= 0 ? scene->nodes[static_cast<size_t>(rotor)].rotation : Quat{};
128   140  
    141 // ユニフォームバッファ:作ったときに結合点0と1に繋がる。シェーダーはlayout(binding = …)で同じ番号を読む
    142 // Uniform buffers: attached to binding points 0 and 1 when created. The shaders read the same numbers through
    143 // layout(binding = ...)
    144 UniformBuffer<CameraBlock> cameraUbo(kCameraBinding);
    145 UniformBuffer<LightsBlock> lightsUbo(kLightsBinding);
    146  
    147 // インスタンスのバッファ:全部の岩を一度だけアップロード。描く数を変えても作り直さない(先頭からcount個使う)
    148 // The instance buffer: every rock uploaded once. Changing the count does not rebuild it (the first `count` are used)
    149 std::vector<InstanceData> ring = makeRing();
    150 Buffer instanceBuffer(ring.data(), static_cast<GLsizeiptr>(ring.size() * sizeof(InstanceData)));
    151 rock->setInstanceBuffer(instanceBuffer, sizeof(InstanceData), kInstanceLayout);
    152  
129 Camera fps; 153 Camera fps;
130 fps.position = {0.0f, 2.0f, 12.5f}; 154 fps.position = {0.0f, 6.5f, 24.0f};
131 fps.pitch = radians(-6.0f); 155 fps.pitch = radians(-12.0f);
132   156  
133 OrbitCamera orbit; 157 OrbitCamera orbit;
134 orbit.target = {0.0f, 1.0f, 4.0f}; 158 orbit.target = {0.0f, 1.5f, 0.0f};
135 orbit.distance = 9.0f; 159 orbit.distance = 24.0f;
136 orbit.yaw = radians(20.0f); 160 orbit.yaw = radians(20.0f);
137   161  
138 bool useOrbit = false; 162 bool useOrbit = false, instanced = true;
139 int viewMode = 0, effect = 0, envMode = 0; 163 int viewMode = 0, effect = 0, rockCount = 4000;
140 bool night = false, flashlightOn = false, windmillMoving = true, skyOn = true, seamless = true; 164 bool night = false, flashlightOn = false, moving = true;
141 float windmillTime = 0.0f; 165 float animTime = 0.0f;
142 window.setCursorCaptured(true); 166 window.setCursorCaptured(true);
143   167  
144 // 場面を描くフレームバッファ(ウィンドウと同じ大きさ) / the framebuffer the scene is drawn into (window size)    
145 Framebuffer sceneFbo(window.width(), window.height()); 168 Framebuffer sceneFbo(window.width(), window.height());
146 if (!sceneFbo.complete()) return 1; 169 if (!sceneFbo.complete()) return 1;
147 window.onResize = [&](int width, int height) { sceneFbo.resize(width, height); }; 170 window.onResize = [&](int width, int height) { sceneFbo.resize(width, height); };
148      
149 // キューブマップの面の境目でも隣の面と補間する(GL 3.2から、全体の設定) / filter across the edges between    
150 // cube-map faces too (since GL 3.2, a global switch)    
151 glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); 171 glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
152   172  
    173 // 時間の集計(60フレームの平均) / timing statistics (averaged over 60 frames)
    174 GpuTimer gpuTimer;
    175 double cpuSum = 0.0, gpuSum = 0.0;
    176 int cpuFrames = 0, gpuFrames = 0;
    177 auto resetStats = [&] {
    178 cpuSum = gpuSum = 0.0;
    179 cpuFrames = gpuFrames = 0;
    180 };
    181  
153 window.onKey = [&](int key, int action, int /*mods*/) { 182 window.onKey = [&](int key, int action, int /*mods*/) {
154 if (action != GLFW_PRESS) return; 183 if (action != GLFW_PRESS) return;
155 if (key == GLFW_KEY_ESCAPE) window.close(); 184 if (key == GLFW_KEY_ESCAPE) window.close();
156 if (key == GLFW_KEY_R && phong->reload() && post->reload() && skybox->reload() && envmap->reload()) 185 if (key == GLFW_KEY_R && phong->reload() && rocksShader->reload() && skybox->reload() && post->reload())
157 printf("シェーダーを読み直した / shaders reloaded\n"); 186 printf("シェーダーを読み直した / shaders reloaded\n");
158 if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); 187 if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured());
159 if (key == GLFW_KEY_C) { 188 if (key == GLFW_KEY_C) {
@@ -169,32 +198,22 @@ int main() {
169 effect = key - GLFW_KEY_1; 198 effect = key - GLFW_KEY_1;
170 printf("effect: %s\n", kEffectNames[effect]); 199 printf("effect: %s\n", kEffectNames[effect]);
171 } 200 }
172 if (key == GLFW_KEY_M) { 201 if (key == GLFW_KEY_I) {
173 envMode = (envMode + 1) % 4; 202 instanced = !instanced;
174 printf("environment objects: %s\n", kEnvModeNames[envMode]); 203 resetStats();
    204 printf("rocks: %s\n", instanced ? "instanced" : "one draw call per rock");
175 } 205 }
176 if (key == GLFW_KEY_K) skyOn = !skyOn; 206 if (key == GLFW_KEY_EQUAL && rockCount < kMaxRocks) rockCount *= 2;
177 if (key == GLFW_KEY_X) { 207 if (key == GLFW_KEY_MINUS && rockCount > 250) rockCount /= 2;
178 seamless = !seamless; 208 if (key == GLFW_KEY_EQUAL || key == GLFW_KEY_MINUS) {
179 if (seamless) glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); 209 resetStats();
180 else glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); 210 printf("rocks: %d\n", rockCount);
181 printf("seamless cube-map filtering: %s\n", seamless ? "on" : "off");    
182 } 211 }
183 if (key == GLFW_KEY_N) night = !night; 212 if (key == GLFW_KEY_N) night = !night;
184 if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; 213 if (key == GLFW_KEY_F) flashlightOn = !flashlightOn;
185 if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; 214 if (key == GLFW_KEY_P) moving = !moving;
186 }; 215 };
187   216  
188 // 床は空の地平線まで届くように広く(遠くはfarPlaneで切れる) / the floor is wide so it reaches the sky's horizon    
189 // (the far plane cuts it off in the distance)    
190 Mesh floorMesh = makePlane(160.0f, 40.0f);    
191 Mesh sphereMesh = makeSphere(48, 24);    
192 Mesh cubeMesh = makeCube(); // 空の箱 / the sky box    
193 Material floorMaterial;    
194 floorMaterial.diffuseMap = &*floorTexture;    
195 floorMaterial.specular = {0.15f, 0.15f, 0.15f};    
196 floorMaterial.shininess = 16.0f;    
197      
198 Mesh tuftMesh = makeCrossedQuads(3); 217 Mesh tuftMesh = makeCrossedQuads(3);
199 std::vector<Placement> grass = makeGrass(); 218 std::vector<Placement> grass = makeGrass();
200 Material grassMaterial; 219 Material grassMaterial;
@@ -202,95 +221,12 @@ int main() {
202 grassMaterial.alphaMode = AlphaMode::Mask; 221 grassMaterial.alphaMode = AlphaMode::Mask;
203 grassMaterial.specular = {0.04f, 0.04f, 0.04f}; 222 grassMaterial.specular = {0.04f, 0.04f, 0.04f};
204 grassMaterial.shininess = 8.0f; 223 grassMaterial.shininess = 8.0f;
205   224 Mesh cubeMesh = makeCube();
206 // 全画面の三角形(中身は空のVAOだけ) / the fullscreen triangle (just an empty VAO inside)    
207 FullscreenTriangle fullscreen; 225 FullscreenTriangle fullscreen;
208   226  
209 glEnable(GL_CULL_FACE); 227 glEnable(GL_CULL_FACE);
210   228  
211 LightSet lights; 229 int frame = 0;
212      
213 Vec3 environmentTint;    
214      
215 // 場面全体を今のフレームバッファに描く / draws the whole scene into the current framebuffer    
216 auto drawScene = [&](const View &v) {    
217 glEnable(GL_DEPTH_TEST);    
218 if (night) glClearColor(0.02f, 0.03f, 0.06f, 1.0f);    
219 else glClearColor(0.45f, 0.62f, 0.85f, 1.0f);    
220 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);    
221      
222 // 空はユニット3。phong(金属の映り込み)、envmap、skyboxのどれもここから読む    
223 // The sky is on unit 3: phong (metal reflections), envmap and skybox all read it from there    
224 sky->bind(3);    
225      
226 phong->use();    
227 phong->set("uView", v.view);    
228 phong->set("uProj", v.proj);    
229 phong->set("uViewPos", v.position);    
230 phong->set("uViewMode", viewMode);    
231 phong->set("uEnvironmentTint", environmentTint);    
232 lights.apply(*phong);    
233      
234 phong->set("uModel", Mat4::identity());    
235 phong->set("uNormalMatrix", normalMatrix(Mat4::identity()));    
236 floorMaterial.apply(*phong, white);    
237 floorMesh.draw();    
238 scene->draw(*phong, Mat4::identity(), white, ModelPass::Opaque);    
239 for (const Placement &c : kCrates) crate->draw(*phong, translate(c.position) * rotateY(c.angle), white, ModelPass::Opaque);    
240 grassMaterial.apply(*phong, white);    
241 glDisable(GL_CULL_FACE); // 草は両面 / grass is two-sided    
242 for (const Placement &g : grass) {    
243 Mat4 model = translate(g.position) * rotateY(g.angle) * scale({0.75f, 0.75f, 0.75f});    
244 phong->set("uModel", model);    
245 phong->set("uNormalMatrix", normalMatrix(model));    
246 tuftMesh.draw();    
247 }    
248 glEnable(GL_CULL_FACE);    
249      
250 // 環境マッピングの物 / the environment-mapped objects    
251 envmap->use();    
252 envmap->set("uView", v.view);    
253 envmap->set("uProj", v.proj);    
254 envmap->set("uViewPos", v.position);    
255 envmap->set("uEnvironmentTint", environmentTint);    
256 envmap->set("uIor", 1.52f);    
257 for (size_t i = 0; i < std::size(kEnvObjects); ++i) {    
258 const EnvObject &o = kEnvObjects[i];    
259 envmap->set("uEnvMode", envMode == 0 ? o.mode : envMode - 1);    
260 envmap->set("uTint", o.tint);    
261 if (i == 1) {    
262 // 平らな面は一つの方向しか映さない:回すと映る空が変わる。木箱の原点は底なので、中心(0, 0.5, 0)の周りで回す    
263 // A flat face reflects only one direction: turning it changes the sky it shows. The crate's origin is at its    
264 // bottom, so it turns about its centre (0, 0.5, 0)    
265 Mat4 model = translate(o.position) * rotate(normalize(Vec3{1.0f, 1.0f, 0.3f}), 0.6f * windmillTime + 0.8f) *    
266 translate({0.0f, -0.5f, 0.0f});    
267 crate->drawGeometry(*envmap, model); // uModelとuNormalMatrixだけ / only uModel and uNormalMatrix    
268 } else {    
269 Mat4 model = translate(o.position) * scale({1.5f, 1.5f, 1.5f});    
270 envmap->set("uModel", model);    
271 envmap->set("uNormalMatrix", normalMatrix(model));    
272 sphereMesh.draw();    
273 }    
274 }    
275      
276 // 空は不透明な物の後に:見えているピクセルだけ塗る(深度1のところ)。半透明な物があればその前    
277 // The sky after the opaque objects: it only fills pixels nothing covers (depth 1). Before any transparent ones    
278 if (skyOn) {    
279 // 空の深度はちょうど1.0。クリアした値も1.0なので、GL_LESSでは通らない:GL_LEQUALにする    
280 // The sky's depth is exactly 1.0, the same as the cleared value, so GL_LESS would reject it: use GL_LEQUAL    
281 glDepthFunc(GL_LEQUAL);    
282 // 箱を内側から見るので、見えるのは裏面:カリングを切る / we see the box from inside, i.e. its back faces: no culling    
283 glDisable(GL_CULL_FACE);    
284 skybox->use();    
285 skybox->set("uView", v.view);    
286 skybox->set("uProj", v.proj);    
287 skybox->set("uEnvironmentTint", environmentTint);    
288 cubeMesh.draw();    
289 glEnable(GL_CULL_FACE);    
290 glDepthFunc(GL_LESS);    
291 }    
292 };    
293      
294 double lastTime = window.time(); 230 double lastTime = window.time();
295 while (!window.shouldClose()) { 231 while (!window.shouldClose()) {
296 double now = window.time(); 232 double now = window.time();
@@ -316,22 +252,23 @@ int main() {
316 fps.move(dir, dt); 252 fps.move(dir, dt);
317 } 253 }
318   254  
319 if (windmillMoving) windmillTime += dt; 255 if (moving) animTime += dt;
320 if (rotor >= 0) 256 if (rotor >= 0)
321 scene->nodes[static_cast<size_t>(rotor)].rotation = 257 scene->nodes[static_cast<size_t>(rotor)].rotation =
322 Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; 258 Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * animTime) * rotorStart;
323   259  
324 // アスペクト比は描き込むフレームバッファのもの(ウィンドウとは限らない) 260 // カメラのブロック:フレームに一度書けば、全部のシェーダーが読む(シェーダーごとのset()は要らない)
325 // The aspect ratio is that of the framebuffer drawn into (not necessarily the window) 261 // The camera block: written once per frame, read by every shader (no per-shader set() any more)
326 float aspect = static_cast<float>(sceneFbo.width()) / static_cast<float>(sceneFbo.height()); 262 float aspect = static_cast<float>(sceneFbo.width()) / static_cast<float>(sceneFbo.height());
327 View main; 263 CameraBlock camera;
328 main.view = useOrbit ? orbit.view() : fps.view(); 264 camera.view = useOrbit ? orbit.view() : fps.view();
329 main.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect); 265 camera.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect);
330 main.position = useOrbit ? orbit.position() : fps.position; 266 camera.viewPos = useOrbit ? orbit.position() : fps.position;
    267 camera.time = animTime;
    268 cameraUbo.update(camera);
331 Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); 269 Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front();
332   270  
333 environmentTint = night ? Vec3{0.05f, 0.06f, 0.11f} : Vec3{1.0f, 1.0f, 1.0f}; 271 LightSet lights;
334 lights = LightSet{};    
335 if (!night) { 272 if (!night) {
336 lights.ambient = {0.28f, 0.30f, 0.34f}; 273 lights.ambient = {0.28f, 0.30f, 0.34f};
337 lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {0.95f, 0.9f, 0.8f}}; 274 lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {0.95f, 0.9f, 0.8f}};
@@ -344,22 +281,99 @@ int main() {
344 } 281 }
345 } 282 }
346 if (flashlightOn) 283 if (flashlightOn)
347 lights.spots.push_back({.position = main.position, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); 284 lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}});
    285 lightsUbo.update(lights.toBlock()); // 光のブロックも一度だけ / the lights block, also just once
    286 Vec3 environmentTint = night ? Vec3{0.05f, 0.06f, 0.11f} : Vec3{1.0f, 1.0f, 1.0f};
348   287  
349 // 1. 場面をフレームバッファに描く / 1. draw the scene into the framebuffer 288 //------------------------------------------------------------------
    289 // 1. 場面をフレームバッファに / 1. the scene into the framebuffer
    290 //------------------------------------------------------------------
350 sceneFbo.bind(); 291 sceneFbo.bind();
351 drawScene(main); 292 glEnable(GL_DEPTH_TEST);
    293 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    294 sky->bind(3);
    295  
    296 // ビュー・射影・光はもう設定しない:ブロックから来る / no view, projection or lights to set: they come from the blocks
    297 phong->use();
    298 phong->set("uViewMode", viewMode);
    299 phong->set("uEnvironmentTint", environmentTint);
    300 scene->draw(*phong, Mat4::identity(), white, ModelPass::Opaque);
    301 // 浮島の下の岩:同じ岩のモデルを平たく大きく / the rock under the floating island: the same rock model, wide and flat
    302 rock->draw(*phong, translate({0.0f, -1.7f, 0.0f}) * scale({10.0f, 3.4f, 10.0f}), white);
    303 grassMaterial.apply(*phong, white);
    304 glDisable(GL_CULL_FACE);
    305 for (const Placement &g : grass) {
    306 Mat4 model = translate(g.position) * rotateY(g.angle) * scale({0.75f, 0.75f, 0.75f});
    307 phong->set("uModel", model);
    308 phong->set("uNormalMatrix", normalMatrix(model));
    309 tuftMesh.draw();
    310 }
    311 glEnable(GL_CULL_FACE);
352   312  
353 // 2. 画面へ:全画面の三角形でフレームバッファのテクスチャを貼り、効果をかける 313 // 岩の環:ここだけ時間を測る / the ring of rocks: only this part is timed
354 // 3. To the screen: a fullscreen triangle samples the framebuffer's texture and applies the effect 314 gpuTimer.begin();
    315 auto cpuStart = std::chrono::steady_clock::now();
    316 if (instanced) {
    317 // インスタンシング:プリミティブ1つにつき描画呼び出し1回。公転はシェーダーがuTimeで計算する
    318 // Instancing: one draw call per primitive. The shader computes the orbit from uTime
    319 rocksShader->use();
    320 rocksShader->set("uViewMode", viewMode);
    321 rocksShader->set("uEnvironmentTint", environmentTint);
    322 rocksShader->set("uOrbitSpeed", kOrbitSpeed);
    323 rock->drawInstanced(*rocksShader, white, rockCount);
    324 } else {
    325 // 一つずつ:岩ごとにuModel・uNormalMatrix・マテリアル・uTintを設定して描画呼び出し。公転はCPUで計算
    326 // One by one: per rock set uModel, uNormalMatrix, the material and uTint, then a draw call. The orbit is
    327 // computed on the CPU
    328 phong->use();
    329 for (int i = 0; i < rockCount; ++i) {
    330 const InstanceData &d = ring[static_cast<size_t>(i)];
    331 phong->set("uTint", d.color);
    332 rock->draw(*phong, rotateY(orbitAngle(d.model, animTime)) * d.model, white);
    333 }
    334 phong->set("uTint", Vec3{1.0f, 1.0f, 1.0f});
    335 }
    336 double cpuMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - cpuStart).count();
    337 gpuTimer.end();
    338  
    339 // 空(第18章) / the sky (chapter 18)
    340 glDepthFunc(GL_LEQUAL);
    341 glDisable(GL_CULL_FACE);
    342 skybox->use();
    343 skybox->set("uEnvironmentTint", environmentTint);
    344 cubeMesh.draw();
    345 glEnable(GL_CULL_FACE);
    346 glDepthFunc(GL_LESS);
    347  
    348 //------------------------------------------------------------------
    349 // 2. 画面へ(第17章) / 2. to the screen (chapter 17)
    350 //------------------------------------------------------------------
355 Framebuffer::bindDefault(window.width(), window.height()); 351 Framebuffer::bindDefault(window.width(), window.height());
356 glDisable(GL_DEPTH_TEST); // 三角形一つだけ:深度は要らない / a single triangle: no depth needed 352 glDisable(GL_DEPTH_TEST);
357 post->use(); 353 post->use();
358 post->set("uEffect", effect); 354 post->set("uEffect", effect);
359 post->set("uFlipX", 0); 355 post->set("uFlipX", 0);
360 sceneFbo.color().bind(0); 356 sceneFbo.color().bind(0);
361 fullscreen.draw(); 357 fullscreen.draw();
362   358  
    359 // 時間の集計:60フレームごとにタイトルと標準出力へ / timing: every 60 frames to the title and stdout
    360 cpuSum += cpuMs;
    361 ++cpuFrames;
    362 if (std::optional<double> gpu = gpuTimer.latestMs()) {
    363 gpuSum += *gpu;
    364 ++gpuFrames;
    365 }
    366 if (++frame % 60 == 0) {
    367 int calls = instanced ? 1 : rockCount;
    368 char text[256];
    369 snprintf(text, sizeof text, "OpenGL Tutorial - Chapter 19 | %d rocks, %s: %d draw call%s, CPU %.2f ms, GPU %.2f ms",
    370 rockCount, instanced ? "instanced" : "one by one", calls, calls == 1 ? "" : "s", cpuSum / cpuFrames,
    371 gpuFrames > 0 ? gpuSum / gpuFrames : 0.0);
    372 window.setTitle(text);
    373 printf("%s\n", text + 31); // 「OpenGL Tutorial - Chapter 19 | 」の後ろ / after "OpenGL Tutorial - Chapter 19 | "
    374 resetStats();
    375 }
    376  
363 window.swapBuffers(); 377 window.swapBuffers();
364 } 378 }
365 return 0; 379 return 0;

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

前新
@@ -56,3 +56,21 @@ void Mesh::draw() const {
56 glDrawArrays(primitive, 0, vertexCount); 56 glDrawArrays(primitive, 0, vertexCount);
57 } 57 }
58 } 58 }
    59  
    60 void Mesh::setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span<const VertexAttrib> layout) {
    61 constexpr GLuint kInstanceBinding = 1; // 頂点はバインディング0 / the vertices are binding 0
    62 glVertexArrayVertexBuffer(vertexArray, kInstanceBinding, buffer.id(), 0, stride);
    63 for (const VertexAttrib &a : layout) {
    64 glEnableVertexArrayAttrib(vertexArray, a.location);
    65 glVertexArrayAttribFormat(vertexArray, a.location, a.components, a.type, a.normalized, a.offset);
    66 glVertexArrayAttribBinding(vertexArray, a.location, kInstanceBinding);
    67 }
    68 // 1 = インスタンス1つごとに1要素進む(0なら頂点ごと) / 1 = advance one element per instance (0 = per vertex)
    69 glVertexArrayBindingDivisor(vertexArray, kInstanceBinding, 1);
    70 }
    71  
    72 void Mesh::drawInstanced(GLsizei count) const {
    73 glBindVertexArray(vertexArray);
    74 if (indexCount > 0) glDrawElementsInstanced(primitive, indexCount, GL_UNSIGNED_INT, nullptr, count);
    75 else glDrawArraysInstanced(primitive, 0, vertexCount, count);
    76 }

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

前新
@@ -55,6 +55,21 @@ constexpr VertexAttrib kModelVertexLayout[] = {
55 {3, 4, offsetof(ModelVertex, tangent)}, // layout(location = 3) in vec4 aTangent(第22章 / chapter 22) 55 {3, 4, offsetof(ModelVertex, tangent)}, // layout(location = 3) in vec4 aTangent(第22章 / chapter 22)
56 }; 56 };
57   57  
    58 // インスタンスごとのデータ(第19章):モデル行列(列4本をlocation 4〜7)と色(location 8)
    59 // Per-instance data (chapter 19): the model matrix (its four columns at locations 4..7) and a colour (location 8)
    60 struct InstanceData {
    61 Mat4 model;
    62 Vec3 color;
    63 };
    64  
    65 constexpr VertexAttrib kInstanceLayout[] = {
    66 {4, 4, offsetof(InstanceData, model) + 0}, // layout(location = 4) in mat4 aInstanceModel(列0 / column 0)
    67 {5, 4, offsetof(InstanceData, model) + 16}, // 列1 / column 1
    68 {6, 4, offsetof(InstanceData, model) + 32}, // 列2 / column 2
    69 {7, 4, offsetof(InstanceData, model) + 48}, // 列3 / column 3
    70 {8, 3, offsetof(InstanceData, color)}, // layout(location = 8) in vec3 aInstanceColor
    71 };
    72  
58 // 一つの描画単位(RAII、コピー不可・移動可)。インデックスが空ならglDrawArraysで描く。 73 // 一つの描画単位(RAII、コピー不可・移動可)。インデックスが空ならglDrawArraysで描く。
59 // One drawable unit (RAII, non-copyable, movable). With no indices it draws with glDrawArrays. 74 // One drawable unit (RAII, non-copyable, movable). With no indices it draws with glDrawArrays.
60 class Mesh { 75 class Mesh {
@@ -75,6 +90,14 @@ public:
75 Mesh &operator=(Mesh &&other) noexcept; 90 Mesh &operator=(Mesh &&other) noexcept;
76   91  
77 void draw() const; 92 void draw() const;
    93 // 同じメッシュをcount回描く(インスタンシング、第19章)。インスタンスごとのデータはsetInstanceBufferで繋ぐ
    94 // Draws the same mesh count times (instancing, chapter 19). Per-instance data comes from setInstanceBuffer
    95 void drawInstanced(GLsizei count) const;
    96 // インスタンスごとの属性のバッファをバインディング1に繋ぐ:頂点ごとではなく、インスタンスごとに次の要素へ進む
    97 // (divisor = 1)。layoutのlocationは頂点の属性(0〜3)と重ならないこと。
    98 // Attaches a buffer of per-instance attributes to binding 1: it advances once per instance instead of once per
    99 // vertex (divisor = 1). The layout's locations must not overlap the vertex attributes (0..3).
    100 void setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span<const VertexAttrib> layout);
78   101  
79 GLuint vao() const { return vertexArray; } 102 GLuint vao() const { return vertexArray; }
80   103  

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

前新
@@ -315,8 +315,19 @@ void Model::collect(int node, const Mat4 &parentWorld, const Mat4 &transform, bo
315 for (int child : n.children) collect(child, world, transform, hierarchy, pass, viewPos, out); 315 for (int child : n.children) collect(child, world, transform, hierarchy, pass, viewPos, out);
316 } 316 }
317   317  
    318 void Model::setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span<const VertexAttrib> layout) {
    319 for (MeshData &m : meshes)
    320 for (Primitive &p : m.primitives) p.mesh.setInstanceBuffer(buffer, stride, layout);
    321 }
    322  
    323 void Model::drawInstanced(const Shader &shader, const Texture2D &white, GLsizei count) const {
    324 std::vector<DrawItem> items;
    325 for (int root : roots) collect(root, Mat4::identity(), Mat4::identity(), true, ModelPass::All, {}, items);
    326 drawItems(items, shader, &white, shader.has("uNormalMatrix"), count);
    327 }
    328  
318 void Model::drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white, 329 void Model::drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white,
319 bool normals) const { 330 bool normals, GLsizei instances) const {
320 bool culling = glIsEnabled(GL_CULL_FACE); // 呼ぶ側の設定を覚えておく / remember the caller's setting 331 bool culling = glIsEnabled(GL_CULL_FACE); // 呼ぶ側の設定を覚えておく / remember the caller's setting
321 for (const DrawItem &item : items) { 332 for (const DrawItem &item : items) {
322 const Primitive &p = *item.primitive; 333 const Primitive &p = *item.primitive;
@@ -333,7 +344,8 @@ void Model::drawItems(const std::vector<DrawItem> &items, const Shader &shader,
333 // Double-sided materials (leaves, glass, sails) must be visible from behind: no culling for them 344 // Double-sided materials (leaves, glass, sails) must be visible from behind: no culling for them
334 bool noCull = culling && md.phong.doubleSided; 345 bool noCull = culling && md.phong.doubleSided;
335 if (noCull) glDisable(GL_CULL_FACE); 346 if (noCull) glDisable(GL_CULL_FACE);
336 p.mesh.draw(); 347 if (instances > 0) p.mesh.drawInstanced(instances);
    348 else p.mesh.draw();
337 if (noCull) glEnable(GL_CULL_FACE); 349 if (noCull) glEnable(GL_CULL_FACE);
338 } 350 }
339 } 351 }

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

前新
@@ -8,6 +8,7 @@
8 #include "texture.hh" 8 #include "texture.hh"
9   9  
10 #include <optional> 10 #include <optional>
    11 #include <span>
11 #include <string> 12 #include <string>
12 #include <string_view> 13 #include <string_view>
13 #include <vector> 14 #include <vector>
@@ -70,6 +71,15 @@ public:
70 // For passes that need no colour: the depth view, outlines, and later shadows (chapter 23). 71 // For passes that need no colour: the depth view, outlines, and later shadows (chapter 23).
71 void drawGeometry(const Shader &shader, const Mat4 &transform) const; 72 void drawGeometry(const Shader &shader, const Mat4 &transform) const;
72   73  
    74 // インスタンシング(第19章):全部のプリミティブのVAOにインスタンスのバッファを繋ぐ(Mesh::setInstanceBuffer)
    75 // Instancing (chapter 19): attaches the instance buffer to every primitive's VAO (Mesh::setInstanceBuffer)
    76 void setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span<const VertexAttrib> layout);
    77 // count個のインスタンスを、プリミティブごとに描画呼び出し1回で描く。uModelはノードのモデル座標の行列で、
    78 // インスタンスの行列はシェーダーで掛ける(phong_instanced.vert:world = aInstanceModel × uModel × 位置)。
    79 // Draws count instances with one draw call per primitive. uModel is the node's model-space matrix; the shader
    80 // multiplies the instance matrix on top (phong_instanced.vert: world = aInstanceModel × uModel × position).
    81 void drawInstanced(const Shader &shader, const Texture2D &white, GLsizei count) const;
    82  
73 // 名前でノードを探す。なければ-1 / finds a node by name; -1 if none 83 // 名前でノードを探す。なければ-1 / finds a node by name; -1 if none
74 int findNode(std::string_view name) const; 84 int findNode(std::string_view name) const;
75 // ノードのモデル座標での行列(ルートからの積)。描く場所はtransform × これ 85 // ノードのモデル座標での行列(ルートからの積)。描く場所はtransform × これ
@@ -98,7 +108,8 @@ private:
98 void collect(int node, const Mat4 &parentWorld, const Mat4 &transform, bool hierarchy, ModelPass pass, 108 void collect(int node, const Mat4 &parentWorld, const Mat4 &transform, bool hierarchy, ModelPass pass,
99 Vec3 viewPos, std::vector<DrawItem> &out) const; 109 Vec3 viewPos, std::vector<DrawItem> &out) const;
100 // white == nullptrなら形だけ(drawGeometry) / white == nullptr: shape only (drawGeometry) 110 // white == nullptrなら形だけ(drawGeometry) / white == nullptr: shape only (drawGeometry)
101 void drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white, bool normals) const; 111 void drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white, bool normals,
    112 GLsizei instances = 0) const;
102 const MaterialData &materialOf(const Primitive &p) const; 113 const MaterialData &materialOf(const Primitive &p) const;
103 const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing 114 const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing
104   115  

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

前新
@@ -183,3 +183,22 @@ void Shader::set(const char *name, const Mat4 &m) const {
183 // linalg.hhは列優先なので転置しない(GL_FALSE) / linalg.hh is column-major, so no transpose (GL_FALSE) 183 // linalg.hhは列優先なので転置しない(GL_FALSE) / linalg.hh is column-major, so no transpose (GL_FALSE)
184 glProgramUniformMatrix4fv(program, location(name), 1, GL_FALSE, &m.c[0].x); 184 glProgramUniformMatrix4fv(program, location(name), 1, GL_FALSE, &m.c[0].x);
185 } 185 }
    186  
    187 GLint Shader::uniformBlockSize(const char *blockName) const {
    188 GLuint index = glGetUniformBlockIndex(program, blockName);
    189 if (index == GL_INVALID_INDEX) return -1;
    190 GLint size = 0;
    191 glGetActiveUniformBlockiv(program, index, GL_UNIFORM_BLOCK_DATA_SIZE, &size);
    192 return size;
    193 }
    194  
    195 bool Shader::checkUniformBlock(const char *blockName, size_t cppSize) const {
    196 GLint size = uniformBlockSize(blockName);
    197 // ドライバーによっては最後のメンバーの終わり(例:692)を、ほかは16の倍数に切り上げた値(704)を返す。
    198 // 16の倍数に切り上げて比べる / some drivers report where the last member ends (e.g. 692), others round up to a
    199 // multiple of 16 (704): compare after rounding up to 16
    200 if (size < 0 || ((static_cast<size_t>(size) + 15) / 16) * 16 == cppSize) return true;
    201 fprintf(stderr, "%s + %s: ブロック「%s」は%dバイト、C++の構造体は%zuバイト / block \"%s\" is %d bytes, the C++ struct %zu\n",
    202 vertexPath.c_str(), fragmentPath.c_str(), blockName, size, cppSize, blockName, size, cppSize);
    203 return false;
    204 }

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

前新
@@ -41,6 +41,14 @@ public:
41 void set(const char *name, const Mat3 &value) const; 41 void set(const char *name, const Mat3 &value) const;
42 void set(const char *name, const Mat4 &value) const; 42 void set(const char *name, const Mat4 &value) const;
43   43  
    44 // ユニフォームブロックの大きさ(GLが決めたバイト数)。プログラムになければ-1(第19章)
    45 // The size of a uniform block in bytes, as the GL laid it out. -1 if the program has no such block (chapter 19)
    46 GLint uniformBlockSize(const char *blockName) const;
    47 // ブロックの大きさがC++の構造体と合うか確かめる。違えばエラーを表示してfalse。ブロックがなければtrue。
    48 // Checks that a block's size matches the C++ struct. Prints an error and returns false if not; true if the
    49 // program has no such block.
    50 bool checkUniformBlock(const char *blockName, size_t cppSize) const;
    51  
44 // そのユニフォームがプログラムで使われているか(警告は出さない) / does the program use that uniform? (no warning) 52 // そのユニフォームがプログラムで使われているか(警告は出さない) / does the program use that uniform? (no warning)
45 bool has(const char *name) const { return glGetUniformLocation(program, name) >= 0; } 53 bool has(const char *name) const { return glGetUniformLocation(program, name) >= 0; }
46   54  

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

前新
@@ -0,0 +1,66 @@
    1 // ユニフォームバッファ(UBO):いくつものシェーダーで共有するユニフォームのまとまり(第19章)
    2 // Uniform buffers (UBOs): blocks of uniforms shared by many shaders (chapter 19)
    3 #pragma once
    4  
    5 #include "buffer.hh"
    6  
    7 #include <linalg.hh>
    8  
    9 #include <cstddef>
    10  
    11 // 結合点の番号。シェーダーの layout(std140, binding = N) と同じにすること
    12 // Binding point numbers. Must match layout(std140, binding = N) in the shaders
    13 constexpr GLuint kCameraBinding = 0; // Camera:ビュー・射影・カメラの位置・時間 / view, projection, camera position, time
    14 constexpr GLuint kLightsBinding = 1; // Lights:全部の光(lights.hhのLightsBlock) / all lights (LightsBlock in lights.hh)
    15 // 2 = 影(第23章:光から見た行列) / shadows (chapter 23: light-space matrices)
    16 // 3 = 後処理の設定(第21章:露出、ブルーム) / post-processing settings (chapter 21: exposure, bloom)
    17  
    18 // std140の規則(よく使うものだけ) / the std140 rules (the common ones)
    19 // float, int, bool : 4バイト、4の倍数に置く / 4 bytes, at a multiple of 4
    20 // vec2 : 8バイト、8の倍数 / 8 bytes, at a multiple of 8
    21 // vec3, vec4 : 12・16バイト、16の倍数(vec3の後ろの4バイトにはfloatが一つ入る)
    22 // 12 / 16 bytes, at a multiple of 16 (one float fits in the 4 bytes after a vec3)
    23 // mat4 : vec4の列が4本、64バイト、16の倍数 / four vec4 columns, 64 bytes, at a multiple of 16
    24 // 配列 / arrays : 要素ごとに16の倍数に切り上げ(float[4]でも64バイト) / every element rounded up to 16 (even float[4] is 64 bytes)
    25 // 構造体 / structs : 16の倍数に置き、大きさも16の倍数に切り上げ / start at a multiple of 16, size rounded up to 16
    26 // C++の構造体は同じ並びになるように、詰め物(pad)を自分で入れる。static_assertで確かめる。
    27 // The C++ structs get explicit padding so they have the same layout; static_assert checks it.
    28  
    29 // GLSL:
    30 // layout(std140, binding = 0) uniform Camera {
    31 // mat4 uView; // offset 0
    32 // mat4 uProj; // offset 64
    33 // vec3 uViewPos; // offset 128
    34 // float uTime; // offset 140(vec3の後ろの隙間) / (the gap after the vec3)
    35 // }; // 144 bytes
    36 struct CameraBlock {
    37 Mat4 view;
    38 Mat4 proj;
    39 Vec3 viewPos;
    40 float time = 0.0f; // アニメーションの時間(秒) / animation time (seconds)
    41 };
    42 static_assert(offsetof(CameraBlock, proj) == 64);
    43 static_assert(offsetof(CameraBlock, viewPos) == 128);
    44 static_assert(offsetof(CameraBlock, time) == 140);
    45 static_assert(sizeof(CameraBlock) == 144);
    46  
    47 // 一つのブロックの中身を持つユニフォームバッファ(RAII、コピー不可・移動可)。作るときに結合点に繋ぐ。
    48 // A uniform buffer holding one block (RAII, non-copyable, movable). Attached to its binding point when created.
    49 template <typename Block>
    50 class UniformBuffer {
    51 public:
    52 explicit UniformBuffer(GLuint bindingPoint)
    53 : buffer(nullptr, sizeof(Block), GL_DYNAMIC_STORAGE_BIT), binding(bindingPoint) {
    54 bind();
    55 }
    56 // 中身を全部書き換える(毎フレーム) / replaces the whole contents (every frame)
    57 void update(const Block &block) const { buffer.update(&block, sizeof(Block)); }
    58 // 結合点に繋ぎ直す(同じ番号に別のバッファを繋いだ後で) / re-attach to the binding point (after another
    59 // buffer was attached to the same number)
    60 void bind() const { buffer.bindBase(GL_UNIFORM_BUFFER, binding); }
    61 GLuint bindingPoint() const { return binding; }
    62  
    63 private:
    64 Buffer buffer;
    65 GLuint binding;
    66 };


コメント(0)

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