14. Loading Models

In chapter 13 we turned a glTF or GLB file into plain C++ structs: accessors we can read with readFloats and readIndices, embedded images we can fetch with imageData, materials, and a tree of nodes, each with its localTransform().
Nothing was drawn yet.
In this chapter the data finally reaches the GPU.

We write a Model class that uploads every primitive into a Mesh, decodes the embedded PNG textures, converts glTF's PBR materials into the Blinn-Phong Material from chapter 11, and draws the node hierarchy with the right matrix for every node.
Then we replace chapter 12's hand-placed cubes with a little windmill diorama and a few crates, all of them loaded from files, and we animate the windmill by changing one number in one node.

14.1 What we're building

A round grass diorama on the stone floor from chapter 9: a windmill whose sails turn, a tree, two rocks, a street lamp and a stack of crates, plus five more crates loaded from a second file and placed around it.
By day the sun lights the scene; at night the moon is weak and the street lamp is a real point light.

The diorama by day: a windmill with turning sails, a tree, two rocks, a street lamp and a stack of crates on a round lawn, with more crates on the stone floor around it

The controls are chapter 12's, with four changes (and the 1, 2 and 3 keys for the light groups are gone):

  • W, A, S, D, Space, Left Ctrl, Shift, mouse, wheel: move and look around as before
  • C: FPS camera ⇔ orbit camera, V: view modes (all, ambient, diffuse, specular, emission, normals)
  • N: day ⇔ night (new)
  • F: flashlight on and off (now off at the start)
  • P: stop and restart the windmill (new meaning)
  • H: node hierarchy on and off, to see what happens without parent × child (new)
  • Tab: release the cursor, R: reload the shaders, Esc: quit

The program also takes an optional file name: ./build/game assets/models/crate.glb puts that model in the middle of the scene instead of the diorama.

Starting from chapter 13, the changes are:

  • src/model.hh and src/model.cc (new): the Model class
  • src/mesh.hh: ModelVertex with a tangent and its layout
  • src/texture.hh and src/texture.cc: Image and decodeImage() for images held in memory
  • src/main.cc: the new scene, day and night, the animated windmill
  • CMakeLists.txt: game now compiles json.cc, gltf.cc and model.cc as well

The shaders don't change at all.
The models are drawn with chapter 12's phong.vert and phong.frag, and that's the whole point of the material conversion in section 14.6.
The assets/models/ files are the ones chapter 13 generated and inspected with gltf_dump.

14.2 The plan: what goes where

A glTF file and our renderer organize things differently.
glTF has meshes made of primitives (each with its own attributes, indices and material), materials that point at textures, textures that point at images and samplers, and nodes that point at meshes.
Our renderer has Mesh (one VAO, one draw call), Texture2D and Material.
The mapping is direct:

glTF Model used for
primitive Primitive holding a Mesh one draw call
mesh MeshData (a list of primitives) what a node draws
texture + image + sampler Texture2D diffuse and emission maps
material MaterialData (PBR original + Blinn-Phong copy) Material::apply
node GltfNode (kept as is) the scene graph

Here is the whole header, src/model.hh:

// 読み込んだモデル:メッシュ(VAO)、テクスチャ、マテリアル、ノードの階層(RAII、コピー不可・移動可)。
// 描くときは、ノードごとに 親のワールド行列 × 自分のローカル行列 をたどる。
// A loaded model: meshes (VAOs), textures, materials and the node hierarchy (RAII, non-copyable, movable).
// Drawing walks the nodes, each with world = parent's world × its own local matrix.
class Model {
public:
  // プリミティブ一つ=描画呼び出し一回 / one primitive = one draw call
  struct Primitive {
    Mesh mesh;
    int material = -1;   // materialsの番号、-1 = 既定 / index into materials, -1 = the default
    Vec3 boundsMin, boundsMax; // モデル座標の箱 / box in model space
  };
  struct MeshData {
    std::string name;
    std::vector<Primitive> primitives;
  };
  // glTFのPBRマテリアルと、それを近似したBlinn-Phongのマテリアル(マップは描くときに繋ぐ)
  // The glTF PBR material and the Blinn-Phong material approximating it (maps are attached at draw time)
  struct MaterialData {
    GltfMaterial pbr;
    Material phong;
  };

  Model() = default;
  Model(const Model &) = delete;
  Model &operator=(const Model &) = delete;
  Model(Model &&) noexcept = default;
  Model &operator=(Model &&) noexcept = default;

  // .glb/.gltfを読み、GPUに載せる。失敗したらエラーを表示してstd::nullopt。
  // Loads a .glb/.gltf and uploads it to the GPU. On failure prints the error and returns std::nullopt.
  static std::optional<Model> load(const std::string &path);

  // transform(モデル全体の置き場所)で描く。マップのないマテリアルにはwhiteを繋ぐ。
  // hierarchy = falseなら親の変換を無視する(なぜ親×子が必要かを見せるため)。
  // Draws with transform (where the whole model goes). Binds `white` for missing maps.
  // hierarchy = false ignores the parents' transforms (to show why parent × child is needed).
  void draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, bool hierarchy = true) const;

  // 名前でノードを探す。なければ-1 / finds a node by name; -1 if none
  int findNode(std::string_view name) const;
  // ノードのモデル座標での行列(ルートからの積)。描く場所はtransform × これ
  // A node's matrix in model space (the product from the root). It is drawn at transform × this
  Mat4 nodeTransform(int node) const;

  // ノードは公開:translation・rotation・scaleを書き換えると動かせる(行列のノードは動かせない)
  // The nodes are public: change translation / rotation / scale to animate them (matrix nodes cannot be animated)
  std::vector<GltfNode> nodes;
  std::vector<int> roots;            // 描き始めるノード / the nodes drawing starts from
  Vec3 boundsMin, boundsMax;         // モデル全体の箱(読み込んだときの姿勢) / box around the whole model (as loaded)

  size_t meshCount() const { return meshes.size(); }
  size_t primitiveCount() const;
  size_t materialCount() const { return materials.size(); }
  size_t textureCount() const { return textures.size(); }

private:
  void drawNode(int node, const Mat4 &parentWorld, const Mat4 &transform, const Shader &shader,
                const Texture2D &white, bool hierarchy) const;
  const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing

  std::vector<MeshData> meshes;
  std::vector<Texture2D> textures; // glTFのtexturesと同じ番号 / same indices as the glTF textures
  std::vector<MaterialData> materials;
  MaterialData defaultMaterial;
};

A few decisions worth pointing out:

  • The glTF indices stay valid. textures[i] is glTF's textures[i], materials[i] is materials[i], meshes[i] is meshes[i], and nodes is a straight copy. So a primitive's material and a node's mesh can be used as they are, with no translation tables.
  • Non-copyable, movable, like every GL wrapper since chapter 3. All members (Mesh, Texture2D, vectors) are already movable, so = default is enough. load returns std::optional<Model>, the same pattern as Shader::load and Texture2D::load.
  • The nodes are public. The CPU-side GltfNodes are our scene graph. To animate something, you change a node's translation, rotation or scale and the next draw picks it up (section 14.9).
  • MaterialData keeps the original PBR material. We draw with an approximation for now, and chapter 24 needs the real values.

14.3 A vertex for models

glTF primitives can carry tangents (TANGENT, a VEC4), which normal mapping needs in chapter 22.
Rather than change the vertex format of every model again then, mesh.hh gets a model vertex now:

// モデル(glTF)の頂点:Vertex3Dに接線を足したもの。接線は第22章の法線マッピングで使う。
// wは従法線の向き(±1):従法線 = cross(normal, tangent.xyz) * tangent.w。接線がなければ (0, 0, 0, 0)。
// A model (glTF) vertex: Vertex3D plus a tangent, used for normal mapping in chapter 22.
// w is the bitangent's sign (±1): bitangent = cross(normal, tangent.xyz) * tangent.w. (0, 0, 0, 0) if there is none.
struct ModelVertex {
  Vec3 position;
  Vec3 normal;
  Vec2 uv;
  Vec4 tangent;
};

constexpr VertexAttrib kModelVertexLayout[] = {
  {0, 3, offsetof(ModelVertex, position)}, // layout(location = 0) in vec3 aPosition
  {1, 3, offsetof(ModelVertex, normal)},   // layout(location = 1) in vec3 aNormal
  {2, 2, offsetof(ModelVertex, uv)},       // layout(location = 2) in vec2 aUv
  {3, 4, offsetof(ModelVertex, tangent)},  // layout(location = 3) in vec4 aTangent(第22章 / chapter 22)
};

Locations 0 to 2 are exactly Vertex3D's, so phong.vert reads a ModelVertex without any change.
Location 3 is enabled in the VAO, but no shader has an input there yet, and that's fine: OpenGL simply doesn't fetch an attribute that the vertex shader doesn't use.
A ModelVertex is 48 bytes (12 + 12 + 8 + 16), and Mesh's template constructor from chapter 4 accepts it like any other vertex struct, taking the stride from sizeof(ModelVertex).

14.4 Uploading a primitive

model.cc starts with a function that turns one glTF primitive into a Model::Primitive.
It's static (only Model::load uses it) and returns std::nullopt when the primitive can't be drawn.

Reading the attributes

static std::optional<Model::Primitive> loadPrimitive(const Gltf &g, const GltfPrimitive &p, const std::string &where) {
  // 属性を読む。型が合わないものは無視する / read the attributes; ignore those with an unexpected type
  auto read = [&](const char *name, int components) -> std::optional<std::vector<float>> {
    int accessor = p.attribute(name);
    if (accessor < 0) return std::nullopt;
    if (g.accessors[static_cast<size_t>(accessor)].components != components) {
      fprintf(stderr, "%s: %s: %s の型が違うので無視 / unexpected type, ignored\n", g.path.c_str(), where.c_str(), name);
      return std::nullopt;
    }
    return g.readFloats(accessor);
  };

  std::optional<std::vector<float>> positions = read("POSITION", 3);
  if (!positions) {
    fprintf(stderr, "%s: %s: POSITIONがないので描かない / no POSITION, skipped\n", g.path.c_str(), where.c_str());
    return std::nullopt;
  }
  std::optional<std::vector<float>> normals = read("NORMAL", 3);
  std::optional<std::vector<float>> uvs = read("TEXCOORD_0", 2);
  std::optional<std::vector<float>> tangents = read("TANGENT", 4);

All the hard work was done in chapter 13.
readFloats handles any component type (floats, normalized bytes and shorts from KHR_mesh_quantization), any byteStride and sparse accessors, and the loader has already checked that every accessor lies inside its buffer.
What's left here is a type check: the spec says POSITION and NORMAL are VEC3, TEXCOORD_0 is VEC2 and TANGENT is VEC4, and a file that breaks that rule gets a warning instead of a crash.
where is a string like meshes[2].primitives[1] so the messages say exactly which primitive was the problem.

Then the attributes go into one interleaved array:

  // 交互に並んだ頂点の配列を作る(ファイルの並び方に関係なく同じ形になる)
  // Build an interleaved vertex array (the same layout whatever the file's layout was)
  size_t count = positions->size() / 3;
  std::vector<ModelVertex> vertices(count);
  for (size_t i = 0; i < count; ++i) {
    ModelVertex &v = vertices[i];
    const float *f = positions->data() + i * 3;
    v.position = {f[0], f[1], f[2]};
    v.normal = {0.0f, 1.0f, 0.0f};
    if (normals) v.normal = {(*normals)[i * 3], (*normals)[i * 3 + 1], (*normals)[i * 3 + 2]};
    if (uvs) v.uv = {(*uvs)[i * 2], (*uvs)[i * 2 + 1]};
    if (tangents) v.tangent = {(*tangents)[i * 4], (*tangents)[i * 4 + 1], (*tangents)[i * 4 + 2], (*tangents)[i * 4 + 3]};
  }

In the diorama, the tower's attributes are already interleaved in the file (one bufferView with a stride of 48 bytes) while every other mesh stores each attribute separately.
After this loop both look the same, so the GPU side only ever sees one format.
glTF guarantees that all attributes of a primitive have the same count (chapter 13 checks it), so indexing normals and uvs with the position index is safe.
A missing attribute keeps a default: UV (0, 0), tangent (0, 0, 0, 0), and an up-pointing normal that we'll replace in a moment.
The lantern glass is such a case: it has POSITION and NORMAL only, no UVs.
Its material has no texture, so its UVs sample the 1×1 white texture, where every coordinate gives the same white.

Checking the indices

  // インデックス:u8・u16・u32はすべてu32になる / indices: u8, u16 and u32 all become u32
  std::vector<std::uint32_t> indices;
  if (p.indices >= 0) {
    std::optional<std::vector<std::uint32_t>> read32 = g.readIndices(p.indices);
    if (!read32) return std::nullopt;
    indices = std::move(*read32);
    // 範囲外のインデックスはGPUで範囲外の読み込みになる:必ず調べる
    // an out-of-range index would make the GPU read out of bounds: always check
    for (std::uint32_t i : indices) {
      if (i >= count) {
        fprintf(stderr, "%s: %s: インデックスが頂点数を超える / index exceeds the vertex count\n", g.path.c_str(),
                where.c_str());
        return std::nullopt;
      }
    }
  }

readIndices turns u8, u16 and u32 indices into u32 (our Mesh always draws with GL_UNSIGNED_INT, a decision from chapter 4).
The loop afterwards is a check that chapter 13 couldn't do, because it needs the vertex count of this primitive: every index must be smaller than count.

This one is not optional.
glDrawElements doesn't check anything: an index of 70000 into a buffer of 24 vertices makes the GPU read 70000 × 48 bytes past the start of the vertex buffer.
What happens then depends on the driver: garbage triangles, zeros (with "robust buffer access"), a crash, or a lost GPU context that takes your whole program down.
WebGL validates indices for exactly this reason; desktop OpenGL leaves it to you.
A model file is input from the outside world, so we check it once at load time and never again while drawing.

Flat normals for primitives without NORMAL

The diorama's rocks are a test case: their mesh has POSITION only, no normals and no indices, 240 vertices that form 80 triangles.
Without normals the lighting can't work, and the glTF specification says what to do: when normals are not specified, client implementations must calculate flat normals.
"Flat" means every triangle gets one normal, perpendicular to its own plane, so the faces look faceted like cut stone.

The normal of a triangle with corners 𝐚,𝐛,𝐜 is the cross product of two of its edges (Linear Algebra chapter 5):

𝐧=normalize((𝐛−𝐚)×(𝐜−𝐚))

For example, with 𝐚=(0,0,0), 𝐛=(1,0,0), 𝐜=(0,1,0): (1,0,0)×(0,1,0)=(0⋅0−0⋅1,0⋅0−1⋅0,1⋅1−0⋅0)=(0,0,1).
The corners go counter-clockwise when you look at them from +Z, and the normal points to +Z, towards you.
glTF's front faces are counter-clockwise, so this formula gives the outward normal, the one lighting needs.

There is one catch.
In an indexed mesh, a corner shared by several triangles is one vertex, and one vertex can only have one normal.
Flat shading needs a different normal for the same position in every triangle, so the shared vertices have to be split up: every triangle gets three vertices of its own, and the indices are no longer needed.

  // 法線がなければ、glTFの仕様どおり平らな法線を作る。三角形ごとに頂点を分ける(インデックスなしにする)
  // Without normals, make flat normals as the glTF spec requires. Each triangle gets its own vertices (no indices)
  if (!normals && p.mode == kGltfTriangles) {
    size_t corners = indices.empty() ? count : indices.size();
    std::vector<ModelVertex> flat;
    flat.reserve(corners / 3 * 3);
    for (size_t t = 0; t + 2 < corners; t += 3) {
      ModelVertex a = vertices[indices.empty() ? t : indices[t]];
      ModelVertex b = vertices[indices.empty() ? t + 1 : indices[t + 1]];
      ModelVertex c = vertices[indices.empty() ? t + 2 : indices[t + 2]];
      Vec3 n = normalize(cross(b.position - a.position, c.position - a.position)); // 反時計回りなら外向き / CCW = outwards
      a.normal = b.normal = c.normal = n;
      flat.insert(flat.end(), {a, b, c});
    }
    vertices = std::move(flat);
    indices.clear();
  }

The vertices are copied by value (ModelVertex a = …), so the UVs and tangents travel along with the positions.
This "de-indexing" is also why the index check comes first: vertices[indices[t]] must never read past the end.
Only TRIANGLES gets flat normals; for strips, fans, lines and points the vertices keep the default normal (0, 1, 0), which is rarely a problem since those modes are almost never used without normals.
Press V five times to see the normals as colors: the tower and the tree are smooth, the rocks are a patchwork of flat facets.

The normals view mode: smooth color gradients on the tower, the tree and the lamp post, flat single-colored facets on the two rocks

Bounds and the Mesh

  Model::Primitive out;
  out.material = p.material;
  out.boundsMin = out.boundsMax = vertices.empty() ? Vec3{} : vertices[0].position;
  for (const ModelVertex &v : vertices) {
    const Vec3 &q = v.position;
    out.boundsMin = {q.x < out.boundsMin.x ? q.x : out.boundsMin.x, q.y < out.boundsMin.y ? q.y : out.boundsMin.y,
                     q.z < out.boundsMin.z ? q.z : out.boundsMin.z};
    out.boundsMax = {q.x > out.boundsMax.x ? q.x : out.boundsMax.x, q.y > out.boundsMax.y ? q.y : out.boundsMax.y,
                     q.z > out.boundsMax.z ? q.z : out.boundsMax.z};
  }
  // glTFのmode(0〜6)はGL_POINTS〜GL_TRIANGLE_FANと同じ値 / glTF modes 0..6 equal GL_POINTS..GL_TRIANGLE_FAN
  out.mesh = Mesh(vertices, indices, kModelVertexLayout, static_cast<GLenum>(p.mode));
  return out;
}

The bounding box of every primitive is remembered for later (the whole model's box in section 14.7, and challenge 5).
The comparisons are written out instead of using std::min/std::max because of the Windows macro problem from chapter 8.

glTF's primitive mode was designed to match OpenGL: 0 to 6 are GL_POINTS, GL_LINES, GL_LINE_LOOP, GL_LINE_STRIP, GL_TRIANGLES, GL_TRIANGLE_STRIP and GL_TRIANGLE_FAN, with exactly those enum values.
So the mode goes straight into Mesh, which calls glDrawElements when there are indices and glDrawArrays when there aren't (the rocks).
No new OpenGL function appears in this chapter: Mesh creates the VAO and buffers with the DSA calls from chapters 3 and 4.

14.5 Textures from memory

decodeImage

Chapter 6's Texture2D::load(path) reads a file with stbi_load.
A GLB's images are not files, though: they are byte ranges inside the BIN chunk, and imageData from chapter 13 hands them to us as a std::vector<std::uint8_t> holding a complete PNG or JPEG file.
stb_image can decode those directly from memory.
texture.hh gets a small struct and a function:

// デコードした画像:RGBA8、上の行から順に / a decoded image: RGBA8, rows from the top
struct Image {
  int width = 0, height = 0;
  std::vector<unsigned char> rgba;
};

// メモリ上の画像ファイル(PNG、JPEG…)をデコードする。flipY = trueなら上下を反転する。失敗したらstd::nullopt。
// Decodes an image file held in memory (PNG, JPEG, ...). flipY = true flips it upside down. std::nullopt on failure.
std::optional<Image> decodeImage(const unsigned char *bytes, size_t size, bool flipY);

and texture.cc the implementation:

std::optional<Image> decodeImage(const unsigned char *bytes, size_t size, bool flipY) {
  stbi_set_flip_vertically_on_load(flipY ? 1 : 0);
  int width = 0, height = 0, channels = 0;
  // ファイルからではなくメモリから(GLBに埋め込まれた画像など) / from memory instead of a file (e.g. images embedded in a GLB)
  unsigned char *pixels = stbi_load_from_memory(bytes, static_cast<int>(size), &width, &height, &channels, 4);
  if (!pixels) {
    fprintf(stderr, "画像をデコードできない / cannot decode image: %s\n", stbi_failure_reason());
    return std::nullopt;
  }
  Image image;
  image.width = width;
  image.height = height;
  image.rgba.assign(pixels, pixels + static_cast<size_t>(width) * static_cast<size_t>(height) * 4);
  stbi_image_free(pixels);
  return image;
}

stbi_load_from_memory(buffer, len, &x, &y, &channelsInFile, desiredChannels) is stbi_load with a byte buffer instead of a path:

  • buffer, len: the encoded file in memory (PNG, JPEG, BMP, TGA…; glTF itself only allows PNG and JPEG without extensions). The length is an int, which is why we cast.
  • x, y: receive the size in pixels.
  • channelsInFile: receives how many channels the file had (1 for gray, 3 for RGB…). We don't need it.
  • desiredChannels: 4 converts everything to RGBA, so the rest of the code never has to care about the source format.

The result is malloc'd memory owned by stb, so we copy it into the std::vector and give it back with stbi_image_free right away; forgetting that is the classic leak with stb_image.
stbi_set_flip_vertically_on_load is global state, as we saw in chapter 6, which is why decodeImage sets it on every call.
Returning an Image instead of a Texture2D keeps decoding separate from uploading: the loader needs to look at the pixels before uploading them (the averages in section 14.6), and a later chapter might want to decode on another thread, where there is no GL context.

Why glTF textures are never flipped

In chapter 6 we flipped every image while loading it.
Image files store their top row first; OpenGL puts the first uploaded row at v=0; and the UVs we typed by hand for our quad and cube used OpenGL's convention, where v=0 is the bottom of the picture.
To make the picture's bottom row the first row in memory, stb had to reverse the rows.

glTF defines its UVs the other way round: (0,0) is the top-left corner of the image and v grows downwards, the same convention as Direct3D, Vulkan and Metal.
Exporters such as Blender convert their own UVs into this convention when they write the file.
So in a glTF file, v=0 means "the image's first row", and the first row of the file is exactly what OpenGL puts at v=0 if we upload the rows in the order the file stores them.
The two conventions meet without any help: no flip on load, no 1−v in the UVs, nothing in the shader.

Left: hand-written UVs with v equals 0 at the bottom of the picture need stb&

The orange numbers in the picture are the uploaded rows.
In both cases uploaded row 0 is at v=0 (OpenGL doesn't care what is "up"; it only maps row 0 to t=0), and in both cases the picture comes out the right way round.
What differs is which row of the file has to become row 0, and that is decided by the convention the UVs were written in, not by the API.

This is why the loader calls decodeImage(…, false) and why Texture2D::fromPixels never flips (chapter 6 already documented that it uploads rows in the order given).
It's also the most common bug when people first load glTF in OpenGL: reuse the file loader with its default flipY = true, and every texture on every model is upside down.
On our crate you'd notice it at once: the diagonal brace would run the other way.

Uploading and samplers

Here is the texture part of Model::load:

  // テクスチャ:埋め込まれたPNG/JPEGをデコードしてアップロード。glTFのUVは画像の左上が原点なので反転しない
  // Textures: decode the embedded PNG/JPEG and upload it. glTF UVs start at the image's top-left: no flipping
  std::vector<Vec4> averages(g.textures.size(), Vec4{1.0f, 1.0f, 1.0f, 1.0f});
  model.textures.resize(g.textures.size()); // 読めなかったものは空(id 0)=白 / ones that fail stay empty (id 0) = white
  for (size_t i = 0; i < g.textures.size(); ++i) {
    const GltfTexture &t = g.textures[i];
    if (t.source < 0) continue;
    std::optional<std::vector<std::uint8_t>> bytes = g.imageData(t.source);
    if (!bytes) continue;
    std::optional<Image> image = decodeImage(bytes->data(), bytes->size(), false);
    if (!image) {
      fprintf(stderr, "%s: images[%d] をデコードできない / cannot decode images[%d]\n", path.c_str(), t.source, t.source);
      continue;
    }
    // 各チャンネルの平均(金属・粗さテクスチャの近似に使う) / average of each channel (for the metallic-roughness approximation)
    double sum[4] = {0, 0, 0, 0};
    for (size_t p = 0; p < image->rgba.size(); ++p) sum[p % 4] += image->rgba[p];
    double pixels = static_cast<double>(image->width) * image->height * 255.0;
    averages[i] = {static_cast<float>(sum[0] / pixels), static_cast<float>(sum[1] / pixels),
                   static_cast<float>(sum[2] / pixels), static_cast<float>(sum[3] / pixels)};

    // 色のテクスチャは本当はsRGB(第21章で直す) / colour textures are really sRGB (fixed in chapter 21)
    Texture2D texture = Texture2D::fromPixels(image->rgba.data(), image->width, image->height,
                                              {.flipY = false, .mipmaps = true});
    if (t.sampler >= 0) {
      // 値はGLのenumそのもの(読み込み時に検査済み)。0 = 指定なし / the values are GL enums (validated); 0 = not given
      const GltfSampler &s = g.samplers[static_cast<size_t>(t.sampler)];
      texture.setWrap(static_cast<GLenum>(s.wrapS), static_cast<GLenum>(s.wrapT));
      texture.setFilter(s.minFilter ? static_cast<GLenum>(s.minFilter) : GL_LINEAR_MIPMAP_LINEAR,
                        s.magFilter ? static_cast<GLenum>(s.magFilter) : GL_LINEAR);
    }
    model.textures[i] = std::move(texture);
  }

A glTF texture is the pair (image, sampler), so we make one Texture2D per glTF texture.
model.textures is resized first so that its indices match glTF's; a texture that fails to decode stays an empty Texture2D (id 0), and texture(index) later turns that into nullptr, which Material::apply replaces with the white texture.
A broken image makes a model white in one place instead of refusing to load the whole file.

Samplers are just as direct as primitive modes: glTF stores magFilter, minFilter, wrapS and wrapT as OpenGL enum values (9729 is GL_LINEAR, 9987 is GL_LINEAR_MIPMAP_LINEAR, 10497 is GL_REPEAT, 33071 is GL_CLAMP_TO_EDGE), and chapter 13 has already rejected anything that isn't a legal value.
So they go straight into chapter 6's setWrap and setFilter, which call glTextureParameteri.
The filters are optional in glTF ("0 = not given"); then we use trilinear filtering, and a texture without a sampler keeps the defaults of our Texture2D (repeat, trilinear), which fits what glTF asks for: repeat wrapping and filtering left to the implementation.
In the diorama the grass uses a GL_REPEAT sampler and the sail cloth GL_CLAMP_TO_EDGE, so the stripe at the sail's edge doesn't bleed over to the other side.

We always build mipmaps.
A glTF minFilter of GL_LINEAR or GL_NEAREST just means the extra levels go unused.

Two things in this code are there for later chapters.
The textures are uploaded as GL_RGBA8 although color images are really sRGB; chapter 21 switches base color and emissive textures to GL_SRGB8_ALPHA8 (the loader knows which is which from the material references), and until then models look slightly darker and more saturated than in a glTF viewer.
And the per-channel averages are needed by the material conversion, which is next.

14.6 PBR materials in a Blinn-Phong world

Two different descriptions of a surface

Our lighting since chapter 10 is Blinn-Phong: a surface has a diffuse color, a specular color and a shininess exponent, chosen by eye.
glTF describes surfaces with the metallic-roughness model of physically based rendering (PBR):

  • baseColorFactor (RGBA) times baseColorTexture: the color of the material
  • metallicFactor (0 = dielectric like wood, plastic, stone; 1 = metal) and roughnessFactor (0 = mirror-smooth, 1 = completely rough), times the blue and green channels of metallicRoughnessTexture
  • emissiveFactor (RGB) times emissiveTexture, times emissiveStrength from KHR_materials_emissive_strength
  • plus normal, occlusion, alpha mode and double-sided, which we load but don't use yet

These are physical quantities, not artistic knobs, and the real way to render them is the Cook–Torrance BRDF of chapter 24.
Until then we need something that makes a glTF model look roughly right with the shader we already have.
The function phongFromPbr is that something, and I want to be honest about it: it's a temporary bridge, not a correct translation.

The conversion

For a material with base color 𝐛, metallic m and roughness r:

𝐤d=(1−m)𝐛𝐅0=(1−m)(0.04,0.04,0.04)+m𝐛α=r2,n=2α2−2(clamped to 1…1024)𝐤s=n+88𝐅0

𝐤d becomes Material::diffuse, 𝐤s becomes specular and n becomes shininess.
Line by line:

  • Metals have no diffuse reflection. Light that enters a metal is absorbed almost immediately; everything you see of a metal is reflection from its surface. Dielectrics reflect a little at the surface and scatter the rest back out as diffuse color. So the diffuse color fades to black as m goes to 1.
  • 𝐅0 is the reflectance at normal incidence, how much light the surface reflects when you look straight at it. Almost all dielectrics are close to 4%; metals reflect 50–100% and tint the reflection with their own color (that's why gold reflections are golden). glTF says: blend between 0.04 and the base color by metallic, which is lerp from linalg.hh.
  • Roughness to shininess. A rough surface spreads its highlight wide, a smooth one concentrates it. glTF's roughness is "perceptual"; the microfacet distributions use α=r2. Walter et al. (2007) showed that a Blinn-Phong lobe with exponent n=2/α2−2 closely matches the Beckmann microfacet distribution with roughness α, which gives us a principled mapping instead of a guess. The clamp keeps rough materials at a broad lobe (n ≥ 1) and mirrors at a finite one.
  • The normalization (n+8)/8. In plain Blinn-Phong a higher exponent makes the highlight smaller and leaves its peak brightness unchanged, so the total reflected light shrinks; a shiny surface would reflect less light than a dull one. The energy-conserving Blinn-Phong lobe is multiplied by (n+8)/(8π). Our diffuse term has no 1/π either (the light colors absorb it), so relative to diffuse the factor is (n+8)/8: a sharp highlight is small but bright, a broad one large but dim.

Here is the code:

static float clamp01(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; }

// metallicScale・roughnessScale:金属・粗さテクスチャの平均(テクスチャがなければ1)。
// Blinn-Phongはピクセルごとの金属度を扱えないので、テクスチャの平均で係数を代表させる。
// metallicScale, roughnessScale: the averages of the metallic-roughness texture (1 without a texture).
// Our Blinn-Phong cannot vary metallic per pixel, so the texture's average stands in for it.
static Material phongFromPbr(const GltfMaterial &m, float metallicScale, float roughnessScale) {
  float metallic = clamp01(m.metallicFactor * metallicScale);
  float roughness = clamp01(m.roughnessFactor * roughnessScale);
  Vec3 base = {m.baseColorFactor.x, m.baseColorFactor.y, m.baseColorFactor.z};

  Material p;
  // 金属は拡散反射をしない / metals have no diffuse reflection
  p.diffuse = (1.0f - metallic) * base;
  // 正面から見た反射率F0:非金属は約4%、金属は自分の色 / reflectance at normal incidence F0: ~4% for non-metals,
  // the base colour for metals
  Vec3 f0 = lerp({0.04f, 0.04f, 0.04f}, base, metallic);
  // 粗さ → 光沢度:Blinn-Phongとベックマン分布の対応 n = 2/α² − 2(α = 粗さ²)
  // roughness → shininess: the Blinn-Phong / Beckmann correspondence n = 2/α² − 2 (α = roughness²)
  float alpha = roughness * roughness;
  float n = alpha > 0.0f ? 2.0f / (alpha * alpha) - 2.0f : 1024.0f;
  n = n < 1.0f ? 1.0f : n > 1024.0f ? 1024.0f : n;
  // 正規化 (n + 8) / 8:鋭いハイライトほど明るく(反射する光の総量がほぼ一定になる)
  // normalization (n + 8) / 8: sharper highlights get brighter (the total reflected light stays about the same)
  p.specular = ((n + 8.0f) / 8.0f) * f0;
  p.shininess = n;
  p.emission = m.emissiveStrength * m.emissiveFactor;
  return p;
}

Worked examples from the diorama

Plaster (the tower): 𝐛=(0.86,0.82,0.74), m=0, r=0.9.
𝐤d=𝐛, 𝐅0=0.04.
α=0.81, α2=0.6561, n=2/0.6561−2≈1.048.
𝐤s=(9.048/8)⋅0.04≈0.045: a very broad, very faint sheen, which is what rough plaster looks like.

Brass (the windmill hub): 𝐛=(0.78,0.6,0.25), m=1, r=0.35.
𝐤d=(0,0,0) and 𝐅0=𝐛.
α=0.1225, α2≈0.01501, n≈133.28−2=131.28.
(n+8)/8≈17.41, so 𝐤s≈(13.58,10.45,4.35).
Specular colors above 1 look alarming, but the highlight with n=131 is tiny, and that's where the brightness goes.
(The framebuffer clamps the result to 1 until chapter 21 brings HDR.)

The default material for primitives without one is m=0, r=0.5 and white: α=0.25, n=2/0.0625−2=30, 𝐤s=4.75⋅0.04=0.19, a plain plastic.
We deliberately don't use glTF's defaults here: they are metallic 1 and roughness 1, which in our shader means no diffuse color at all and one huge, flat highlight (n=1): a featureless pale blob where a light hits it and black everywhere else.

Metallic-roughness textures: an average

phongFromPbr takes two extra parameters, metallicScale and roughnessScale.
In a metallic-roughness texture the green channel is the roughness and the blue channel the metallic value, per pixel, and the final value is factor × texture.
Our Blinn-Phong material has one diffuse color and one shininess per draw call; it can't change from metal to wood in the middle of a triangle.
The next best thing is the texture's average, which is what the loop in section 14.5 computed for every texture:

  // マテリアル / materials
  for (const GltfMaterial &m : g.materials) {
    Vec4 mr = {1.0f, 1.0f, 1.0f, 1.0f};
    int t = m.metallicRoughnessTexture.index;
    if (t >= 0 && model.textures[static_cast<size_t>(t)].id() != 0) mr = averages[static_cast<size_t>(t)];
    model.materials.push_back({m, phongFromPbr(m, mr.z, mr.y)}); // B = 金属度 / metallic、G = 粗さ / roughness
  }
  // マテリアルのないプリミティブ用。glTFの既定(金属度1、粗さ1)だと拡散色の無い淡い塊になるので、白いプラスチックにする
  // For primitives without a material. glTF's default (metallic 1, roughness 1) would be a pale blob with no diffuse
  // colour here, so use white plastic
  model.defaultMaterial.pbr.name = "(default)";
  model.defaultMaterial.pbr.metallicFactor = 0.0f;
  model.defaultMaterial.pbr.roughnessFactor = 0.5f;
  model.defaultMaterial.phong = phongFromPbr(model.defaultMaterial.pbr, 1.0f, 1.0f);

Why not simply use the factors?
Because of how files are actually made: when an artist connects a metallic or roughness texture in Blender, the exporter writes factors of 1 and 1 and puts all the information in the texture.
Our crate is built the same way, and with the factors alone it would be a perfectly rough white metal: 𝐤d=0 throws the wood texture away and leaves a featureless pale box.
With the averages, the crate works out like this: its metallic-roughness texture averages B¯≈0.288 (the steel frame is metal, the wood isn't) and G¯≈0.719.
So m≈0.288 and r≈0.719, 𝐤d≈0.712 times the base color texture, 𝐅0≈0.04+0.96⋅0.288≈0.317, α≈0.517, α2≈0.268, n≈5.47 and 𝐤s≈1.684⋅0.317≈0.533.
The whole crate becomes "slightly metallic, fairly rough": a little darker than chapter 12's crate and with a dull sheen everywhere, where chapter 11's specular map made only the frame shine.
Challenge 7 does it properly, per pixel.

What the bridge doesn't carry

At draw time the material gets its maps: diffuseMap is the base color texture (so the diffuse color is (1−m) × factor × texture, as it should be), emissionMap is the emissive texture, and specularMap stays white.
Everything else is lost or approximated:

  • Metallic and roughness are constant per material (the average above).
  • 𝐅0 uses the base color factor, not the texture, so a metal's highlight ignores its texture's color.
  • There is no Fresnel effect: real surfaces reflect much more at grazing angles, and PBR models that; our specular is the same from every angle.
  • Occlusion and normal textures are ignored (normal maps come in chapter 22).

The biggest visible consequence is this: metals look almost black.
Look at the hub in the middle of the sails and at the lamp post in the screenshots.
A real metal is bright because it reflects its surroundings: the sky, the grass, the sun.
Our renderer has no surroundings to reflect; the only things a metal can show are the highlights of our few lights.
And since 𝐤d=0, the ambient term uAmbient⋅𝐤d is zero too, so wherever there's no highlight a metal is black.
That is not a bug in the conversion, it's the honest result of a lighting model without reflections.
Chapter 18 shows reflections of a cubemap, and chapter 24 fixes it properly with image-based lighting.
At night you can see the one thing the brass hub can do: catch the orange highlight of the street lamp.

Left: the diorama at night, lit by the moon and the street lamp at the LanternLight node; the brass hub catches an orange highlight. Right: the same with the flashlight on

Emission works as before: the lantern glass has emissive (1, 0.62, 0.25) with an emissive strength of 2, so emission is (2, 1.24, 0.5), and it glows even when no light reaches it.

14.7 Putting Model::load together

After textures and materials come the meshes, the nodes and the bounding box:

  // メッシュ / meshes
  for (size_t i = 0; i < g.meshes.size(); ++i) {
    MeshData mesh;
    mesh.name = g.meshes[i].name;
    for (size_t k = 0; k < g.meshes[i].primitives.size(); ++k) {
      std::string where = "meshes[" + std::to_string(i) + "].primitives[" + std::to_string(k) + "]";
      std::optional<Primitive> prim = loadPrimitive(g, g.meshes[i].primitives[k], where);
      if (prim) mesh.primitives.push_back(std::move(*prim)); // 描けないものは飛ばす / skip what cannot be drawn
    }
    model.meshes.push_back(std::move(mesh));
  }

  model.nodes = g.nodes;
  model.roots = g.rootNodes();

  // 全体の箱:メッシュのある全部のノードについて、プリミティブの箱を変換する
  // The whole box: transform each primitive's box for every node that has a mesh
  bool first = true;
  for (size_t i = 0; i < model.nodes.size(); ++i) {
    if (model.nodes[i].mesh < 0) continue;
    Mat4 m = model.nodeTransform(static_cast<int>(i));
    for (const Primitive &p : model.meshes[static_cast<size_t>(model.nodes[i].mesh)].primitives)
      growBounds(model.boundsMin, model.boundsMax, first, m, p.boundsMin, p.boundsMax);
  }
  return model;
}

A mesh is pushed even if all its primitives were skipped, so meshes[i] still lines up with glTF's meshes[i]; an empty mesh simply draws nothing.
rootNodes() (chapter 13) returns the default scene's nodes, or the first scene's, or every node without a parent for files without scenes.
The Gltf object itself is a local variable: once everything is on the GPU and the nodes are copied, its buffers (the whole BIN chunk) are freed at the end of load.

The bounding box transforms the 8 corners of each primitive's box with its node's matrix (growBounds, a short helper in model.cc) and grows the model's box around them.
Transforming only the min and max corners would be wrong as soon as there's a rotation: a box turned by 45° sticks out further than its two transformed corners.
main prints the result:

assets/models/diorama.glb: 20 nodes, 8 meshes, 11 primitives, 11 materials, 4 textures, bounds (-4.60, 0.00, -4.60) - (4.60, 4.05, 4.60)
assets/models/crate.glb: 1 nodes, 1 meshes, 1 primitives, 1 materials, 2 textures, bounds (-0.50, 0.00, -0.50) - (0.50, 1.00, 0.50)

The lawn is 9.2 m across and the windmill's top sail reaches 4.05 m.
Both boxes start at y=0: all our models have their origin on the floor, so translate(position) stands a model on the ground (unlike makeCube, which is centered and had to be lifted by half its size in chapter 9).
Our other conventions match glTF's: 1 unit = 1 meter, +Y up, the front faces +Z.

14.8 The node hierarchy

Parent × child

The diorama's 20 nodes form a tree.
Here is the part of it that matters for this chapter:

The node tree: Diorama has the children Windmill and Lamp among others. Windmill holds TowerMesh and Rotor, Rotor holds the four blades. Lamp holds the empty node LanternLight. The world matrix of Blade.1 is M Diorama times M Windmill times M Rotor times M Blade.1

Every node's transform (TRS or a matrix, localTransform() from chapter 13) is relative to its parent.
The blades are placed relative to the rotor, the rotor relative to the windmill, the windmill relative to the diorama.
To draw a blade we need its matrix relative to the world, and that's the product of all the matrices on the path from the root:

𝐖node=𝐖parent𝐋node,𝐖root=𝐓model𝐋root

where 𝐋 is a node's local matrix and 𝐓model is where we place the whole model.
This is matrix multiplication composing transforms, read right to left, exactly as in Linear Algebra chapter 7: a point of the blade is first moved by the blade's own local transform into the rotor's space, then by the rotor's into the windmill's space, then into the diorama's space, then into the world.
The order matters: 𝐋node𝐖parent would apply the parent's transform in the child's space, and the parts would scatter.

Worked example: where is the lantern light?

The lamp uses a matrix instead of TRS.
Its columns are a rotation of −30° about Y and the translation (2.2,0.12,1.6); its child LanternLight has only a translation (0,1.9,0), and the diorama root is the identity.
The light's position is the child's origin (0,0,0,1) transformed by the parent's matrix times the child's.
The child's translation turns the origin into (0,1.9,0,1), and multiplying a matrix with a vector is a linear combination of its columns:

𝐌Lamp[01.901]=0[0.86600.50]+1.9[0100]+0[−0.500.8660]+1[2.20.121.61]=[2.22.021.61]

The light sits 1.9 m above the lamp's foot, inside the lantern, at (2.2,2.02,1.6).
The rotation doesn't change anything here because the point lies on the Y axis, which a rotation about Y leaves alone.

Worked example: a blade

The same for Blade.0, which is three levels deep.
Its local transform is a translation (0,0,0.22) (in front of the hub), so its origin in rotor space is (0,0,0.22).
The rotor rotates about Z and moves by (0,2.3,0.62).
A rotation about Z leaves points on the Z axis where they are, so in windmill space the blade's origin is (0,2.3,0.84), whatever angle the rotor has: the blades turn around this point.
The windmill rotates by 25° about Y and moves by (−1.4,0.12,−1.2).
The rotation about Y gives x′=xcosθ+zsinθ and z′=−xsinθ+zcosθ (chapter 8 of the Linear Algebra series):

x′=0.84⋅sin25°≈0.84⋅0.4226≈0.3550,z′=0.84⋅cos25°≈0.84⋅0.9063≈0.7613

Adding the translation: (−1.4+0.3550,0.12+2.3,−1.2+0.7613)=(−1.0450,2.42,−0.4387), the front of the windmill, at the hub, 2.42 m up.

Drawing the tree

draw starts a recursion at every root node:

void Model::draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, bool hierarchy) const {
  for (int root : roots) drawNode(root, transform, transform, shader, white, hierarchy);
}

void Model::drawNode(int node, const Mat4 &parentWorld, const Mat4 &transform, const Shader &shader,
                     const Texture2D &white, bool hierarchy) const {
  const GltfNode &n = nodes[static_cast<size_t>(node)];
  // ワールド行列 = 親のワールド行列 × 自分のローカル行列 / world = the parent's world matrix × our local matrix
  Mat4 world = (hierarchy ? parentWorld : transform) * n.localTransform();
  if (n.mesh >= 0) {
    shader.set("uModel", world);
    shader.set("uNormalMatrix", normalMatrix(world));
    for (const Primitive &p : meshes[static_cast<size_t>(n.mesh)].primitives) {
      const MaterialData &md = p.material >= 0 ? materials[static_cast<size_t>(p.material)] : defaultMaterial;
      Material m = md.phong;
      m.diffuseMap = texture(md.pbr.baseColorTexture.index);  // 色 = 係数 × テクスチャ / colour = factor × texture
      m.emissionMap = texture(md.pbr.emissiveTexture.index);
      m.apply(shader, white);
      p.mesh.draw();
    }
  }
  for (int child : n.children) drawNode(child, world, transform, shader, white, hierarchy);
}

The parent's world matrix is passed down as a parameter, so each matrix is computed once per frame per node, and no node needs to know who its parent is while drawing.
Nodes without a mesh (the windmill, the rotor, Crates, LanternLight) draw nothing but still pass their world matrix on to their children.
A mesh used by several nodes (four crates share one "Crate" mesh, four blades share one "Blade" mesh) is simply drawn several times with different matrices; its vertices are on the GPU once.
The recursion can't loop forever: chapter 13 rejected files where a node has two parents or the tree has a cycle.

The normal matrix is computed from each node's own world matrix, as in chapter 10 (Linear Algebra chapter 10).
Using the model's transform instead would be wrong for Crate.Flat, which is scaled by (1.6,0.45,0.8): with a non-uniform scale only the inverse transpose keeps normals perpendicular to the faces.

texture(index) returns nullptr for "no texture" (index −1) and for textures that failed to load, and Material::apply binds the 1×1 white texture in their place, the chapter 11 trick that saves us any "has texture" flags in the shader.

What the H key shows

With hierarchy = false every node is drawn at transform × local, ignoring all its parents:

Left: the normal diorama, world equals parent times local. Right: parents ignored; the tower stands in the middle of the lawn, the sails have fallen to the origin and the stacked crates are inside and next to the tower, while the lamp, tree and rocks have not moved

The lamp, the tree and the rocks don't move, because their only parent is the diorama root, whose matrix is the identity.
The tower jumps to the middle of the lawn: its own local transform is the identity, and all of its placement came from the Windmill node.
The hub and the blades fall to the origin, mostly into the ground, and the crates lose their Crates group's offset and pile up around the tower.
That's exactly the information the parent × child product carries.

14.9 Using models in main

Loading

main loads two models after the shaders:

  // モデル:真ん中の場面(引数で別のファイルにできる)と木箱 / models: the scene in the middle (or a file given
  // on the command line) and the crate
  const char *scenePath = argc > 1 ? argv[1] : "assets/models/diorama.glb";
  std::optional<Model> scene = Model::load(scenePath);
  std::optional<Model> crate = Model::load("assets/models/crate.glb");
  if (!scene || !crate) return 1;
  printModel(scenePath, *scene);
  printModel("assets/models/crate.glb", *crate);

The models are std::optional<Model> in main, declared after the Window, so they're destroyed before it: their VAOs, buffers and textures must be deleted while the OpenGL context still exists (the rule from chapter 2).
main is now int main(int argc, char **argv) so you can try other files.
Chapter 12's crates, spheres and light markers are gone; the unlit shader files stay in shaders/ but aren't loaded any more.

Drawing the floor and the models then takes four lines:

    phong->set("uModel", Mat4::identity());
    phong->set("uNormalMatrix", normalMatrix(Mat4::identity()));
    floorMaterial.apply(*phong, white);
    floorMesh.draw();

    // モデルは自分でノードごとにuModelとマテリアルを設定する / the model sets uModel and the material per node itself
    scene->draw(*phong, Mat4::identity(), white, hierarchy);
    for (const CrateInfo &c : kCrates) crate->draw(*phong, translate(c.position) * rotateY(c.angle), white, hierarchy);

The five extra crates are one model drawn five times with five transforms (chapter 9's bottom-center positions, now without a size).
Each draw call sets uModel, uNormalMatrix and the material itself; the camera and lights are set once per frame before it, as in chapter 12.
Drawing many copies this way costs one draw call per primitive per copy; chapter 19 draws thousands with instancing.

Finding nodes by name, and sockets

  // 動かすノードと、光を置くノードを名前で探す(ないファイルでは-1) / find the node to animate and the node
  // that carries the light by name (-1 in files that do not have them)
  int rotor = scene->findNode("Rotor");
  int lanternNode = scene->findNode("LanternLight");
  Quat rotorStart = rotor >= 0 ? scene->nodes[static_cast<size_t>(rotor)].rotation : Quat{};

findNode is a linear search over the node names, done once at start-up; the indices are what we use every frame.
With another file (game assets/models/crate.glb) both lookups return −1, and every piece of code that uses them checks for that.

LanternLight is a node with no mesh at all.
It exists only to mark a place: "the light of this lamp is here".
Such empty nodes are called sockets (or attachment points, or empties in Blender), and they are how games connect code to art: the artist decides where the muzzle of a gun is, where a character holds a sword, where the camera pivots, and moves it in the modeling tool; the code asks for the node by name and never contains a hard-coded offset.
We'll use sockets for exactly those things in the third-person shooter.
At night the street lamp's light is placed at the socket:

    // 昼は太陽、夜は月と街灯 / the sun by day, the moon and the street lamp by night
    LightSet lights;
    if (!night) {
      lights.ambient = {0.28f, 0.30f, 0.34f};
      lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {0.95f, 0.9f, 0.8f}};
    } else {
      lights.ambient = {0.03f, 0.035f, 0.05f};
      lights.directional = {.direction = {-0.4f, -1.0f, -0.6f}, .color = {0.15f, 0.18f, 0.28f}};
      // 光の位置=空のノード「LanternLight」のワールド座標 / the light sits at the world position of the empty node
      if (lanternNode >= 0) {
        Vec4 p = scene->nodeTransform(lanternNode) * Vec4{0.0f, 0.0f, 0.0f, 1.0f};
        lights.points.push_back({.position = {p.x, p.y, p.z}, .color = {2.6f, 1.6f, 0.7f}, .attenuation = kMediumRange});
      }
    }
    if (flashlightOn) lights.spots.push_back({.position = viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}});

nodeTransform computes the same product as the drawing recursion, but for one node, by walking up the parent links that chapter 13 computed:

Mat4 Model::nodeTransform(int node) const {
  if (node < 0 || static_cast<size_t>(node) >= nodes.size()) return Mat4::identity();
  // 親をたどって左から掛ける:ルート × … × 親 × 自分 / walk up the parents multiplying from the left
  Mat4 m = nodes[static_cast<size_t>(node)].localTransform();
  for (int p = nodes[static_cast<size_t>(node)].parent; p >= 0; p = nodes[static_cast<size_t>(p)].parent)
    m = nodes[static_cast<size_t>(p)].localTransform() * m;
  return m;
}

Each parent is multiplied in from the left, so after the loop m is root × … × parent × node, the same order as in the formula.
The result is in model space; transforming the origin (0,0,0,1) gives the socket's position, the (2.2,2.02,1.6) we computed by hand.
Because the scene is drawn with the identity, model space is world space here.
If you placed the diorama somewhere else, the light would have to be at transform * nodeTransform(lanternNode) * origin; forgetting the model's own transform is the usual socket bug.
The point light uses the medium range attenuation from chapter 12 and a warm color brighter than 1, so it lights the lawn around the lamp.

Animating a node

The windmill's sails turn because one node changes every frame:

    // 風車の羽根:Rotorノードの回転だけを変える。子ノード(ハブと羽根4枚)は一緒に回る
    // The windmill: change only the Rotor node's rotation. Its children (the hub and four blades) turn with it
    if (windmillMoving) windmillTime += dt;
    if (rotor >= 0)
      scene->nodes[static_cast<size_t>(rotor)].rotation =
          Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart;

We write a new rotation into the Rotor node, and the next draw recomposes its 𝐓𝐑𝐒 matrix.
The hub and the four blades are children of the rotor, so they all turn together; the code never touches them.
That's the real power of the hierarchy: animating a complex object means changing a few numbers in a few nodes.

The rotation is a quaternion (Linear Algebra chapter 13).
rotorStart is the rotation from the file (17.2° about Z), and the animation is multiplied in front of it.
The product q1q2 rotates by q2 first, then by q1; multiplying from the left turns the node about its parent's axis, multiplying from the right about its own already-rotated axis.
Here both rotations are about Z, so the order doesn't matter, but for an arbitrary axis it does.
−0.8 radians per second is one turn in about 7.9 seconds, clockwise seen from the front (+Z), and windmillTime only advances while the windmill isn't paused (P).
We store the time instead of adding a little rotation every frame so that no rounding error builds up.

Two things don't work this way.
A node that uses matrix can't be animated by writing TRS, because localTransform() returns the matrix and ignores TRS; the glTF specification requires animated nodes to use TRS for this reason (our lamp uses a matrix and stays still).
And Model::boundsMin/boundsMax describe the model as loaded; they don't follow the animation.

Platform notes

  • Windows (Visual Studio): to pass a file to the program, open the project properties of game → Debugging → Command Arguments and enter assets\models\crate.glb, or run build\Debug\game.exe assets\models\crate.glb from the project root in a terminal. Both slash directions work in the path.
  • Linux and FreeBSD: ./build/game assets/models/crate.glb from the project root, as with every chapter.
  • Your own models: in Blender, File → Export → glTF 2.0 with the format "glTF Binary (.glb)". The exporter converts Blender's Z-up to glTF's Y-up for you (the "+Y Up" option is on by default). Apply the scale before exporting (Ctrl+A), and check the result with gltf_dump. Textures you painted show up the right way round without any flipping, for the reason in section 14.5.

14.10 What the loader doesn't do yet

The loader skips several glTF features without failing (chapter 13 counts or flags them):

  • Alpha. alphaMode MASK and BLEND and doubleSided are loaded but ignored; chapter 16 brings discard, blending and face culling (the sail cloth is marked double-sided, which matters once culling is on).
  • Normal and occlusion maps. The tangents are already in the vertex buffer at location 3; chapter 22 uses them.
  • sRGB. Base color and emissive textures should be GL_SRGB8_ALPHA8, the others linear; chapter 21.
  • Real PBR in chapter 24, with the original values kept in MaterialData::pbr.
  • Skins, animation channels, morph targets, cameras, KHR_lights_punctual, KHR_texture_transform, TEXCOORD_1 and COLOR_0. Our games animate rigid parts by editing node TRS, as with the windmill. Skinned characters are a topic of their own.
  • Shared images. If two glTF textures use the same image, it's decoded and uploaded twice. Challenge 6 adds a cache.

14.11 How real engines do it

  • Import once, load fast. Engines rarely read glTF at run time. An import step converts it into the engine's own format: vertices already in the final layout, indices optimized for the GPU's vertex cache (meshoptimizer is the usual library), textures compressed into a GPU format (BC7, ASTC, or KTX2 with Basis Universal) with mipmaps precomputed. Loading is then little more than a memory copy. glTF is an exchange format; it's also perfectly fine as a run-time format for small projects like ours.
  • Caching world matrices. We recompute every node's world matrix every frame. Engines keep a cached world matrix and a "dirty" flag per node and recompute only what changed, which matters with thousands of nodes. Many also flatten static parts of the tree at import time.
  • Batching. Our diorama costs 18 draw calls (11 primitives, some of them drawn by several nodes) plus 5 for the crates. Engines merge static meshes that share a material, use instancing for repeated objects (chapter 19) and sort draws by shader and material to reduce state changes.
  • Materials. A real material system has per-pixel PBR, several shader variants (with or without normal map, alpha test, skinning), and textures that are streamed in at the resolution that's needed.

14.12 Summary

  • Model::load = Gltf::load (chapter 13) + GPU upload. glTF's indices are kept, so textures, materials, meshes and nodes line up with the file.
  • Every primitive becomes an interleaved ModelVertex array (position, normal, UV, tangent at locations 0 to 3) in one Mesh. glTF's mode values are OpenGL's primitive enums.
  • Indices are checked against the vertex count before upload; an out-of-range index is an out-of-bounds GPU read.
  • Primitives without NORMAL get flat normals from (𝐛−𝐚)×(𝐜−𝐚), which needs every triangle to have its own vertices.
  • Embedded images are decoded with stbi_load_from_memory and never flipped: glTF's UV origin is the image's top-left, and the file's first row uploaded as row 0 is exactly glTF's v=0. Our own textures in chapter 6 needed the flip because our UVs used the opposite convention.
  • glTF samplers store OpenGL enums and go straight into glTextureParameteri.
  • PBR → Blinn-Phong is a temporary bridge: diffuse = (1−m)𝐛, 𝐅0 = mix(0.04, 𝐛, m), n=2/α2−2 with α=r2, specular = 𝐅0(n+8)/8, metallic and roughness from the texture's average. Metals look dark until chapter 24 because there is nothing for them to reflect.
  • World matrix = parent's world matrix × local matrix, from the root down. The normal matrix comes from each node's world matrix.
  • Empty nodes are sockets: nodeTransform(findNode("…")) gives their position. Animate by editing a node's TRS; its children follow.

14.13 Challenges

  1. ★ Load the crate as the scene: ./build/game assets/models/crate.glb. One crate should stand in the middle among the five others, and the windmill and lantern code should do nothing (no rotation, no lamp light at night) because findNode returns −1.
  2. ★ Spin the whole windmill: also animate the Windmill node's rotation about Y (keep its original rotation as with rotorStart). The tower should turn on its spot while the sails, being its grandchildren, keep spinning and turn with it.
  3. ★ Rotate every Blade.n node about its own Y axis as well (multiply from the right). The blades should twist like propellers while the rotor turns them, which shows that each node composes with all its parents.
  4. ★★ Draw a small marker cube at the LanternLight socket with the unlit shader (load it again, use makeCube() and translate(p) * scale({0.1f, 0.1f, 0.1f})). The cube should sit inside the lantern glass. Then change the lamp node's matrix at run time (for example its translation column matrix.c[3]): the lamp, the cube and the night light should all move together.
  5. ★★ Draw every primitive's bounding box as 12 lines (GL_LINES, the unlit shader, model matrix = nodeTransform(node)). You should see boxes around the tower, the roof, each blade and each crate; the flat crate's box should be flat and turned with it, and the blade boxes should spin with the sails.
  6. ★★ Cache decoded images by GltfTexture::source, so that an image used by several glTF textures is decoded and uploaded once (keep a map from image index to Texture2D index, or let textures refer to images). Count the glTextureStorage2D calls before and after on a file where two textures share an image (for example chapter 13's challenge 6 diorama as .gltf, edited so that two textures point at the same image): the picture should be identical with one call fewer.
  7. ★★★ Use the metallic-roughness texture per pixel: bind it to texture unit 3 as uMetallicRoughnessMap, pass the base color factor and the material's factors as uniforms, and compute diffuse, 𝐅0, shininess and specular in the fragment shader with the formulas of phongFromPbr. The crate's steel frame should become shiny and its wood dull, much like chapter 11's specular map, while the averaged version looked evenly dull. This is a small preview of chapter 24.

Download the diff

Download the project (ZIP)

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

前新
@@ -37,7 +37,10 @@ add_executable(game
37 src/shapes.cc 37 src/shapes.cc
38 src/camera.cc 38 src/camera.cc
39 src/material.cc 39 src/material.cc
40 src/lights.cc) 40 src/lights.cc
    41 src/json.cc
    42 src/gltf.cc
    43 src/model.cc)
41 target_include_directories(game PRIVATE src external/stb external/linalg) 44 target_include_directories(game PRIVATE src external/stb external/linalg)
42 target_link_libraries(game PRIVATE glad stb_image glfw) 45 target_link_libraries(game PRIVATE glad stb_image glfw)
43   46  

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

前新
@@ -1,5 +1,5 @@
1 // 第13章:glTFとGLB:ファイルの読み込み(このプログラムは第12章と同じ。新しいのは gltf_dump) 1 // 第14章:モデルの読み込み
2 // Chapter 13: glTF and GLB: reading the file (this program is the same as in chapter 12; the new part is gltf_dump) 2 // Chapter 14: loading models
3 // 3 //
4 // 操作 / Controls: 4 // 操作 / Controls:
5 // WASD 前後左右に移動 / move forward, back, left, right 5 // WASD 前後左右に移動 / move forward, back, left, right
@@ -9,19 +9,21 @@
9 // ホイール / wheel ズーム / zoom 9 // ホイール / wheel ズーム / zoom
10 // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera 10 // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera
11 // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals 11 // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals
12 // P 点光源を止める・動かす / pause / resume the point lights 12 // N 昼 ⇔ 夜 / day ⇔ night
13 // 1 平行光源(月)のオン・オフ / directional light (the moon) on / off    
14 // 2 点光源のオン・オフ / point lights on / off    
15 // 3 スポットライトのオン・オフ / spotlights on / off    
16 // F 懐中電灯のオン・オフ / flashlight on / off 13 // F 懐中電灯のオン・オフ / flashlight on / off
    14 // P 風車を止める・回す / pause / resume the windmill
    15 // H ノードの階層のオン・オフ(オフ=親の変換を無視) / node hierarchy on / off (off = ignore the parents)
17 // Tab カーソルのキャプチャ切り替え / toggle cursor capture 16 // Tab カーソルのキャプチャ切り替え / toggle cursor capture
18 // R シェーダーを読み直す / reload the shaders 17 // R シェーダーを読み直す / reload the shaders
19 // Esc 終了 / quit 18 // Esc 終了 / quit
    19 //
    20 // 使い方 / usage: game [model.glb] (指定すれば、そのモデルを場面の真ん中に置く / puts that model in the middle of the scene)
20 #include "camera.hh" 21 #include "camera.hh"
21 #include "lights.hh" 22 #include "lights.hh"
22 #include "material.hh" 23 #include "material.hh"
23 #include "mathx.hh" 24 #include "mathx.hh"
24 #include "mesh.hh" 25 #include "mesh.hh"
    26 #include "model.hh"
25 #include "shader.hh" 27 #include "shader.hh"
26 #include "shapes.hh" 28 #include "shapes.hh"
27 #include "texture.hh" 29 #include "texture.hh"
@@ -29,115 +31,74 @@
29   31  
30 #include <cmath> 32 #include <cmath>
31 #include <cstdio> 33 #include <cstdio>
32 #include <iterator>    
33 #include <optional> 34 #include <optional>
34   35  
35 // 床に置いた箱:位置(底の中心)、大きさ、Y軸周りの回転 / crates on the floor: position (bottom centre), size, yaw 36 // 木箱のモデルを置く場所:位置(底の中心)とY軸周りの回転 / where the crate models go: position (bottom centre) and yaw
36 struct CrateInfo { 37 struct CrateInfo {
37 Vec3 position; 38 Vec3 position;
38 float size;    
39 float angle; 39 float angle;
40 }; 40 };
41   41  
42 static const CrateInfo kCrates[] = { 42 static const CrateInfo kCrates[] = {
43 {{0.0f, 0.0f, 0.0f}, 1.0f, 0.0f}, {{1.1f, 0.0f, 0.2f}, 1.0f, 0.3f}, 43 {{5.5f, 0.0f, 1.5f}, 0.4f}, {{6.3f, 0.0f, 2.6f}, -0.3f}, {{5.9f, 1.0f, 2.0f}, 0.1f},
44 {{0.5f, 1.0f, 0.1f}, 1.0f, -0.2f}, {{-3.0f, 0.0f, -2.0f}, 2.0f, 0.6f}, 44 {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f},
45 {{-3.0f, 2.0f, -2.0f}, 1.0f, 0.1f}, {{4.0f, 0.0f, -4.0f}, 1.5f, -0.5f},    
46 {{-6.0f, 0.0f, 3.0f}, 1.0f, 0.9f}, {{6.5f, 0.0f, 2.5f}, 1.0f, 0.2f},    
47 {{2.0f, 0.0f, -9.0f}, 3.0f, 0.4f}, {{-8.0f, 0.0f, -8.0f}, 2.0f, -0.3f},    
48 {{9.0f, 0.0f, -12.0f}, 2.5f, 0.7f}, {{-2.5f, 0.0f, 5.5f}, 0.6f, 0.5f},    
49 };    
50      
51 // 色だけのマテリアル(古典的なOpenGLのマテリアル表から。表のambientは使わない:環境光 = uAmbient × diffuse)    
52 // Colour-only materials (from the classic OpenGL material table; its ambient column is not used:    
53 // our ambient light is uAmbient × diffuse)    
54 struct NamedMaterial {    
55 const char *name;    
56 Material material;    
57 };    
58      
59 static const NamedMaterial kMaterialSamples[] = {    
60 {"gold", {.diffuse = {0.75164f, 0.60648f, 0.22648f},    
61 .specular = {0.628281f, 0.555802f, 0.366065f},    
62 .shininess = 51.2f}},    
63 {"silver", {.diffuse = {0.50754f, 0.50754f, 0.50754f},    
64 .specular = {0.508273f, 0.508273f, 0.508273f},    
65 .shininess = 51.2f}},    
66 {"copper", {.diffuse = {0.7038f, 0.27048f, 0.0828f},    
67 .specular = {0.256777f, 0.137622f, 0.086014f},    
68 .shininess = 12.8f}},    
69 {"jade", {.diffuse = {0.54f, 0.89f, 0.63f},    
70 .specular = {0.316228f, 0.316228f, 0.316228f},    
71 .shininess = 12.8f}},    
72 {"ruby", {.diffuse = {0.61424f, 0.04136f, 0.04136f},    
73 .specular = {0.727811f, 0.626959f, 0.626959f},    
74 .shininess = 76.8f}},    
75 {"cyan plastic", {.diffuse = {0.0f, 0.50980392f, 0.50980392f},    
76 .specular = {0.50196078f, 0.50196078f, 0.50196078f},    
77 .shininess = 32.0f}},    
78 };    
79      
80 // 点光源(提灯)の中心と色 / centres and colours of the point lights (lanterns)    
81 struct LanternInfo {    
82 Vec3 centre;    
83 Vec3 color;    
84 }; 45 };
85   46  
86 static const LanternInfo kLanterns[] = {    
87 {{2.6f, 1.2f, 0.2f}, {2.4f, 1.0f, 0.35f}}, // 橙 / orange    
88 {{-1.8f, 1.0f, 0.8f}, {0.4f, 2.0f, 0.7f}}, // 緑 / green    
89 {{4.5f, 1.6f, -4.5f}, {0.6f, 0.9f, 2.6f}}, // 青 / blue    
90 {{-5.5f, 1.4f, -3.5f}, {2.2f, 0.5f, 1.8f}}, // 紫 / purple    
91 };    
92      
93 // 箱の山を上から照らすスポットライト / the spotlight shining down on the pile of crates    
94 constexpr Vec3 kStageSpotPos = {2.0f, 6.0f, 1.5f};    
95 constexpr Vec3 kStageSpotTarget = {0.3f, 0.5f, -0.2f};    
96      
97 static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; 47 static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"};
98   48  
99 int main() { 49 static void printModel(const char *path, const Model &m) {
    50 printf("%s: %zu nodes, %zu meshes, %zu primitives, %zu materials, %zu textures, bounds (%.2f, %.2f, %.2f) - (%.2f, "
    51 "%.2f, %.2f)\n",
    52 path, m.nodes.size(), m.meshCount(), m.primitiveCount(), m.materialCount(), m.textureCount(), m.boundsMin.x,
    53 m.boundsMin.y, m.boundsMin.z, m.boundsMax.x, m.boundsMax.y, m.boundsMax.z);
    54 }
    55  
    56 int main(int argc, char **argv) {
100 Window window; 57 Window window;
101 if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 13")) return 1; 58 if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 14")) return 1;
102   59  
103 std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); 60 std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag");
104 std::optional<Shader> unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag");    
105 std::optional<Texture2D> crate = Texture2D::load("assets/textures/crate.png");    
106 std::optional<Texture2D> crateSpecular = Texture2D::load("assets/textures/crate_specular.png");    
107 std::optional<Texture2D> crateEmission = Texture2D::load("assets/textures/crate_emission.png");    
108 std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png"); 61 std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png");
109 if (!phong || !unlit || !crate || !crateSpecular || !crateEmission || !floorTexture) return 1; 62 if (!phong || !floorTexture) return 1;
    63  
    64 // モデル:真ん中の場面(引数で別のファイルにできる)と木箱 / models: the scene in the middle (or a file given
    65 // on the command line) and the crate
    66 const char *scenePath = argc > 1 ? argv[1] : "assets/models/diorama.glb";
    67 std::optional<Model> scene = Model::load(scenePath);
    68 std::optional<Model> crate = Model::load("assets/models/crate.glb");
    69 if (!scene || !crate) return 1;
    70 printModel(scenePath, *scene);
    71 printModel("assets/models/crate.glb", *crate);
110 glEnable(GL_DEPTH_TEST); 72 glEnable(GL_DEPTH_TEST);
111   73  
112 // 1×1の白いテクスチャ:マップのないマテリアルの代わり(白を掛けても色は変わらない)    
113 // A 1×1 white texture: stands in for missing maps (multiplying by white changes nothing)    
114 const unsigned char whitePixel[4] = {255, 255, 255, 255}; 74 const unsigned char whitePixel[4] = {255, 255, 255, 255};
115 Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); 75 Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false});
116   76  
    77 // 動かすノードと、光を置くノードを名前で探す(ないファイルでは-1) / find the node to animate and the node
    78 // that carries the light by name (-1 in files that do not have them)
    79 int rotor = scene->findNode("Rotor");
    80 int lanternNode = scene->findNode("LanternLight");
    81 Quat rotorStart = rotor >= 0 ? scene->nodes[static_cast<size_t>(rotor)].rotation : Quat{};
    82  
117 Camera fps; 83 Camera fps;
118 fps.position = {0.5f, 2.4f, 8.5f}; 84 fps.position = {0.0f, 2.6f, 9.0f};
119 fps.pitch = radians(-14.0f); 85 fps.pitch = radians(-12.0f);
120   86  
121 OrbitCamera orbit; 87 OrbitCamera orbit;
122 orbit.target = {0.0f, 0.8f, 0.0f}; 88 orbit.target = {0.0f, 1.2f, 0.0f};
123 orbit.distance = 9.0f; 89 orbit.distance = 10.0f;
124 orbit.yaw = radians(30.0f); 90 orbit.yaw = radians(30.0f);
125   91  
126 bool useOrbit = false; 92 bool useOrbit = false;
127 int viewMode = 0; 93 int viewMode = 0;
128 bool lightMoving = true; 94 bool night = false, flashlightOn = false, windmillMoving = true, hierarchy = true;
129 bool directionalOn = true, pointsOn = true, spotsOn = true, flashlightOn = true; 95 float windmillTime = 0.0f;
130 float lightTime = 0.0f; // 点光源の動きの時間(止められる) / time for the point lights' motion (can be paused)    
131 window.setCursorCaptured(true); 96 window.setCursorCaptured(true);
132   97  
133 window.onKey = [&](int key, int action, int /*mods*/) { 98 window.onKey = [&](int key, int action, int /*mods*/) {
134 if (action != GLFW_PRESS) return; 99 if (action != GLFW_PRESS) return;
135 if (key == GLFW_KEY_ESCAPE) window.close(); 100 if (key == GLFW_KEY_ESCAPE) window.close();
136 if (key == GLFW_KEY_R) { 101 if (key == GLFW_KEY_R && phong->reload()) printf("シェーダーを読み直した / shaders reloaded\n");
137 bool ok = phong->reload();    
138 ok = unlit->reload() && ok; // 両方とも読み直す / reload both, even if the first one failed    
139 if (ok) printf("シェーダーを読み直した / shaders reloaded\n");    
140 }    
141 if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); 102 if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured());
142 if (key == GLFW_KEY_C) { 103 if (key == GLFW_KEY_C) {
143 useOrbit = !useOrbit; 104 useOrbit = !useOrbit;
@@ -148,40 +109,21 @@ int main() {
148 viewMode = (viewMode + 1) % 6; 109 viewMode = (viewMode + 1) % 6;
149 printf("view: %s\n", kViewModeNames[viewMode]); 110 printf("view: %s\n", kViewModeNames[viewMode]);
150 } 111 }
151 if (key == GLFW_KEY_P) lightMoving = !lightMoving; 112 if (key == GLFW_KEY_N) night = !night;
152 if (key == GLFW_KEY_1) directionalOn = !directionalOn;    
153 if (key == GLFW_KEY_2) pointsOn = !pointsOn;    
154 if (key == GLFW_KEY_3) spotsOn = !spotsOn;    
155 if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; 113 if (key == GLFW_KEY_F) flashlightOn = !flashlightOn;
156 if (key >= GLFW_KEY_1 && key <= GLFW_KEY_3) 114 if (key == GLFW_KEY_P) windmillMoving = !windmillMoving;
157 printf("directional %s, points %s, spots %s\n", directionalOn ? "on" : "off", pointsOn ? "on" : "off", 115 if (key == GLFW_KEY_H) {
158 spotsOn ? "on" : "off"); 116 hierarchy = !hierarchy;
    117 printf("hierarchy: %s\n", hierarchy ? "on (world = parent x local)" : "off (world = local)");
    118 }
159 }; 119 };
160   120  
161 printf("material spheres (left to right):");    
162 for (const NamedMaterial &m : kMaterialSamples) printf(" %s", m.name);    
163 printf("\n");    
164      
165 Mesh cube = makeCube();    
166 Mesh sphere = makeSphere();    
167 Mesh floorMesh = makePlane(40.0f, 10.0f); 121 Mesh floorMesh = makePlane(40.0f, 10.0f);
168      
169 // 床:石は少しだけ光る / the floor: stone is only slightly shiny    
170 Material floorMaterial; 122 Material floorMaterial;
171 floorMaterial.diffuseMap = &*floorTexture; 123 floorMaterial.diffuseMap = &*floorTexture;
172 floorMaterial.specular = {0.15f, 0.15f, 0.15f}; 124 floorMaterial.specular = {0.15f, 0.15f, 0.15f};
173 floorMaterial.shininess = 16.0f; 125 floorMaterial.shininess = 16.0f;
174   126  
175 // 箱:三枚のマップ。鏡面反射マップで金属の枠だけが光り、発光マップで隙間が光る    
176 // The crate: three maps. The specular map makes only the metal frame shiny, the emission map lights the gaps    
177 Material crateMaterial;    
178 crateMaterial.diffuseMap = &*crate;    
179 crateMaterial.specular = {1.0f, 1.0f, 1.0f};    
180 crateMaterial.shininess = 48.0f;    
181 crateMaterial.specularMap = &*crateSpecular;    
182 crateMaterial.emissionMap = &*crateEmission;    
183 crateMaterial.emission = {1.0f, 1.0f, 1.0f};    
184      
185 double lastTime = window.time(); 127 double lastTime = window.time();
186 while (!window.shouldClose()) { 128 while (!window.shouldClose()) {
187 double now = window.time(); 129 double now = window.time();
@@ -207,52 +149,38 @@ int main() {
207 fps.move(dir, dt); 149 fps.move(dir, dt);
208 } 150 }
209   151  
    152 // 風車の羽根:Rotorノードの回転だけを変える。子ノード(ハブと羽根4枚)は一緒に回る
    153 // The windmill: change only the Rotor node's rotation. Its children (the hub and four blades) turn with it
    154 if (windmillMoving) windmillTime += dt;
    155 if (rotor >= 0)
    156 scene->nodes[static_cast<size_t>(rotor)].rotation =
    157 Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart;
    158  
210 Mat4 view = useOrbit ? orbit.view() : fps.view(); 159 Mat4 view = useOrbit ? orbit.view() : fps.view();
211 Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect()); 160 Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect());
212 Vec3 viewPos = useOrbit ? orbit.position() : fps.position; 161 Vec3 viewPos = useOrbit ? orbit.position() : fps.position;
213 Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); 162 Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front();
214   163  
215 // 夜の場面:弱い環境光と青白い月 / a night scene: weak ambient light and a pale blue moon 164 // 昼は太陽、夜は月と街灯 / the sun by day, the moon and the street lamp by night
216 if (lightMoving) lightTime += dt;    
217 LightSet lights; 165 LightSet lights;
218 lights.ambient = {0.03f, 0.035f, 0.05f}; 166 if (!night) {
219 if (directionalOn) lights.directional = {.direction = {-0.4f, -1.0f, -0.6f}, .color = {0.22f, 0.27f, 0.4f}}; 167 lights.ambient = {0.28f, 0.30f, 0.34f};
220   168 lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {0.95f, 0.9f, 0.8f}};
221 // 色の違う点光源四つ。それぞれ自分の中心の周りをゆっくり回る 169 } else {
222 // Four coloured point lights, each slowly circling its own centre 170 lights.ambient = {0.03f, 0.035f, 0.05f};
223 if (pointsOn) { 171 lights.directional = {.direction = {-0.4f, -1.0f, -0.6f}, .color = {0.15f, 0.18f, 0.28f}};
224 for (int i = 0; i < 4; ++i) { 172 // 光の位置=空のノード「LanternLight」のワールド座標 / the light sits at the world position of the empty node
225 float a = lightTime * (0.5f + 0.15f * static_cast<float>(i)) + static_cast<float>(i) * 1.7f; 173 if (lanternNode >= 0) {
226 lights.points.push_back({.position = kLanterns[i].centre + Vec3{1.2f * std::cos(a), 0.3f * std::sin(2.0f * a), 174 Vec4 p = scene->nodeTransform(lanternNode) * Vec4{0.0f, 0.0f, 0.0f, 1.0f};
227 1.2f * std::sin(a)}, 175 lights.points.push_back({.position = {p.x, p.y, p.z}, .color = {2.6f, 1.6f, 0.7f}, .attenuation = kMediumRange});
228 .color = kLanterns[i].color,    
229 .attenuation = kMediumRange});    
230 } 176 }
231 } 177 }
    178 if (flashlightOn) lights.spots.push_back({.position = viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}});
232   179  
233 // スポットライト:カメラの懐中電灯と、箱の山を上から照らすライト 180 if (night) glClearColor(0.02f, 0.03f, 0.06f, 1.0f);
234 // Spotlights: the camera's flashlight and a light shining down on the pile of crates 181 else glClearColor(0.45f, 0.62f, 0.85f, 1.0f);
235 if (spotsOn) {    
236 if (flashlightOn)    
237 lights.spots.push_back({.position = viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}});    
238 lights.spots.push_back({.position = kStageSpotPos,    
239 .direction = kStageSpotTarget - kStageSpotPos,    
240 .color = {2.0f, 1.9f, 1.6f},    
241 .innerAngle = radians(16.0f),    
242 .outerAngle = radians(24.0f)});    
243 }    
244      
245 glClearColor(0.02f, 0.03f, 0.06f, 1.0f);    
246 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 182 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
247   183  
248 // 一つの物を描く:モデル行列、法線行列、マテリアル / draws one object: model matrix, normal matrix, material    
249 auto drawLit = [&](const Mesh &mesh, const Mat4 &model, const Material &material) {    
250 phong->set("uModel", model);    
251 phong->set("uNormalMatrix", normalMatrix(model));    
252 material.apply(*phong, white);    
253 mesh.draw();    
254 };    
255      
256 phong->use(); 184 phong->use();
257 phong->set("uView", view); 185 phong->set("uView", view);
258 phong->set("uProj", proj); 186 phong->set("uProj", proj);
@@ -260,34 +188,14 @@ int main() {
260 phong->set("uViewMode", viewMode); 188 phong->set("uViewMode", viewMode);
261 lights.apply(*phong); 189 lights.apply(*phong);
262   190  
263 drawLit(floorMesh, Mat4::identity(), floorMaterial); 191 phong->set("uModel", Mat4::identity());
264   192 phong->set("uNormalMatrix", normalMatrix(Mat4::identity()));
265 for (const CrateInfo &c : kCrates) { 193 floorMaterial.apply(*phong, white);
266 Vec3 centre = c.position + Vec3{0.0f, 0.5f * c.size, 0.0f}; 194 floorMesh.draw();
267 drawLit(cube, translate(centre) * rotateY(c.angle) * scale({c.size, c.size, c.size}), crateMaterial);    
268 }    
269   195  
270 // マテリアル見本の球を一列に / a row of sample spheres, one per material 196 // モデルは自分でノードごとにuModelとマテリアルを設定する / the model sets uModel and the material per node itself
271 for (size_t i = 0; i < std::size(kMaterialSamples); ++i) { 197 scene->draw(*phong, Mat4::identity(), white, hierarchy);
272 float x = (static_cast<float>(i) - 2.5f) * 1.25f; 198 for (const CrateInfo &c : kCrates) crate->draw(*phong, translate(c.position) * rotateY(c.angle), white, hierarchy);
273 drawLit(sphere, translate({x, 0.5f, 2.6f}), kMaterialSamples[i].material);    
274 }    
275      
276 // 光源の目印:点光源は小さな球、スポットライトは小さな箱(懐中電灯は自分の目の位置なので描かない)    
277 // Light markers: small spheres for point lights, small cubes for spotlights (not the flashlight: it is at our eye)    
278 unlit->use();    
279 unlit->set("uView", view);    
280 unlit->set("uProj", proj);    
281 for (const PointLight &p : lights.points) {    
282 unlit->set("uModel", translate(p.position) * scale({0.15f, 0.15f, 0.15f}));    
283 unlit->set("uColor", p.color);    
284 sphere.draw();    
285 }    
286 if (spotsOn) {    
287 unlit->set("uModel", translate(kStageSpotPos) * scale({0.2f, 0.2f, 0.2f}));    
288 unlit->set("uColor", Vec3{1.0f, 1.0f, 0.9f});    
289 cube.draw();    
290 }    
291   199  
292 window.swapBuffers(); 200 window.swapBuffers();
293 } 201 }

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

前新
@@ -37,6 +37,24 @@ constexpr VertexAttrib kVertex3DLayout[] = {
37 {2, 2, offsetof(Vertex3D, uv)}, // layout(location = 2) in vec2 aUv 37 {2, 2, offsetof(Vertex3D, uv)}, // layout(location = 2) in vec2 aUv
38 }; 38 };
39   39  
    40 // モデル(glTF)の頂点:Vertex3Dに接線を足したもの。接線は第22章の法線マッピングで使う。
    41 // wは従法線の向き(±1):従法線 = cross(normal, tangent.xyz) * tangent.w。接線がなければ (0, 0, 0, 0)。
    42 // A model (glTF) vertex: Vertex3D plus a tangent, used for normal mapping in chapter 22.
    43 // w is the bitangent's sign (±1): bitangent = cross(normal, tangent.xyz) * tangent.w. (0, 0, 0, 0) if there is none.
    44 struct ModelVertex {
    45 Vec3 position;
    46 Vec3 normal;
    47 Vec2 uv;
    48 Vec4 tangent;
    49 };
    50  
    51 constexpr VertexAttrib kModelVertexLayout[] = {
    52 {0, 3, offsetof(ModelVertex, position)}, // layout(location = 0) in vec3 aPosition
    53 {1, 3, offsetof(ModelVertex, normal)}, // layout(location = 1) in vec3 aNormal
    54 {2, 2, offsetof(ModelVertex, uv)}, // layout(location = 2) in vec2 aUv
    55 {3, 4, offsetof(ModelVertex, tangent)}, // layout(location = 3) in vec4 aTangent(第22章 / chapter 22)
    56 };
    57  
40 // 一つの描画単位(RAII、コピー不可・移動可)。インデックスが空ならglDrawArraysで描く。 58 // 一つの描画単位(RAII、コピー不可・移動可)。インデックスが空ならglDrawArraysで描く。
41 // One drawable unit (RAII, non-copyable, movable). With no indices it draws with glDrawArrays. 59 // One drawable unit (RAII, non-copyable, movable). With no indices it draws with glDrawArrays.
42 class Mesh { 60 class Mesh {

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

前新
@@ -0,0 +1,280 @@
    1 #include "model.hh"
    2  
    3 #include <cmath>
    4 #include <cstdio>
    5  
    6 //------------------------------------------
    7 // PBRマテリアル → Blinn-Phong(第24章で本物のPBRにするまでの近似)
    8 // PBR material → Blinn-Phong (an approximation until chapter 24 does real PBR)
    9 //------------------------------------------
    10  
    11 static float clamp01(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; }
    12  
    13 // metallicScale・roughnessScale:金属・粗さテクスチャの平均(テクスチャがなければ1)。
    14 // Blinn-Phongはピクセルごとの金属度を扱えないので、テクスチャの平均で係数を代表させる。
    15 // metallicScale, roughnessScale: the averages of the metallic-roughness texture (1 without a texture).
    16 // Our Blinn-Phong cannot vary metallic per pixel, so the texture's average stands in for it.
    17 static Material phongFromPbr(const GltfMaterial &m, float metallicScale, float roughnessScale) {
    18 float metallic = clamp01(m.metallicFactor * metallicScale);
    19 float roughness = clamp01(m.roughnessFactor * roughnessScale);
    20 Vec3 base = {m.baseColorFactor.x, m.baseColorFactor.y, m.baseColorFactor.z};
    21  
    22 Material p;
    23 // 金属は拡散反射をしない / metals have no diffuse reflection
    24 p.diffuse = (1.0f - metallic) * base;
    25 // 正面から見た反射率F0:非金属は約4%、金属は自分の色 / reflectance at normal incidence F0: ~4% for non-metals,
    26 // the base colour for metals
    27 Vec3 f0 = lerp({0.04f, 0.04f, 0.04f}, base, metallic);
    28 // 粗さ → 光沢度:Blinn-Phongとベックマン分布の対応 n = 2/α² − 2(α = 粗さ²)
    29 // roughness → shininess: the Blinn-Phong / Beckmann correspondence n = 2/α² − 2 (α = roughness²)
    30 float alpha = roughness * roughness;
    31 float n = alpha > 0.0f ? 2.0f / (alpha * alpha) - 2.0f : 1024.0f;
    32 n = n < 1.0f ? 1.0f : n > 1024.0f ? 1024.0f : n;
    33 // 正規化 (n + 8) / 8:鋭いハイライトほど明るく(反射する光の総量がほぼ一定になる)
    34 // normalization (n + 8) / 8: sharper highlights get brighter (the total reflected light stays about the same)
    35 p.specular = ((n + 8.0f) / 8.0f) * f0;
    36 p.shininess = n;
    37 p.emission = m.emissiveStrength * m.emissiveFactor;
    38 return p;
    39 }
    40  
    41 //------------------------------------------
    42 // 読み込み / loading
    43 //------------------------------------------
    44  
    45 // glTFのプリミティブ一つを頂点の配列にしてGPUに載せる。描けなければstd::nullopt。
    46 // Turns one glTF primitive into a vertex array and uploads it. std::nullopt if it cannot be drawn.
    47 static std::optional<Model::Primitive> loadPrimitive(const Gltf &g, const GltfPrimitive &p, const std::string &where) {
    48 // 属性を読む。型が合わないものは無視する / read the attributes; ignore those with an unexpected type
    49 auto read = [&](const char *name, int components) -> std::optional<std::vector<float>> {
    50 int accessor = p.attribute(name);
    51 if (accessor < 0) return std::nullopt;
    52 if (g.accessors[static_cast<size_t>(accessor)].components != components) {
    53 fprintf(stderr, "%s: %s: %s の型が違うので無視 / unexpected type, ignored\n", g.path.c_str(), where.c_str(), name);
    54 return std::nullopt;
    55 }
    56 return g.readFloats(accessor);
    57 };
    58  
    59 std::optional<std::vector<float>> positions = read("POSITION", 3);
    60 if (!positions) {
    61 fprintf(stderr, "%s: %s: POSITIONがないので描かない / no POSITION, skipped\n", g.path.c_str(), where.c_str());
    62 return std::nullopt;
    63 }
    64 std::optional<std::vector<float>> normals = read("NORMAL", 3);
    65 std::optional<std::vector<float>> uvs = read("TEXCOORD_0", 2);
    66 std::optional<std::vector<float>> tangents = read("TANGENT", 4);
    67  
    68 // 交互に並んだ頂点の配列を作る(ファイルの並び方に関係なく同じ形になる)
    69 // Build an interleaved vertex array (the same layout whatever the file's layout was)
    70 size_t count = positions->size() / 3;
    71 std::vector<ModelVertex> vertices(count);
    72 for (size_t i = 0; i < count; ++i) {
    73 ModelVertex &v = vertices[i];
    74 const float *f = positions->data() + i * 3;
    75 v.position = {f[0], f[1], f[2]};
    76 v.normal = {0.0f, 1.0f, 0.0f};
    77 if (normals) v.normal = {(*normals)[i * 3], (*normals)[i * 3 + 1], (*normals)[i * 3 + 2]};
    78 if (uvs) v.uv = {(*uvs)[i * 2], (*uvs)[i * 2 + 1]};
    79 if (tangents) v.tangent = {(*tangents)[i * 4], (*tangents)[i * 4 + 1], (*tangents)[i * 4 + 2], (*tangents)[i * 4 + 3]};
    80 }
    81  
    82 // インデックス:u8・u16・u32はすべてu32になる / indices: u8, u16 and u32 all become u32
    83 std::vector<std::uint32_t> indices;
    84 if (p.indices >= 0) {
    85 std::optional<std::vector<std::uint32_t>> read32 = g.readIndices(p.indices);
    86 if (!read32) return std::nullopt;
    87 indices = std::move(*read32);
    88 // 範囲外のインデックスはGPUで範囲外の読み込みになる:必ず調べる
    89 // an out-of-range index would make the GPU read out of bounds: always check
    90 for (std::uint32_t i : indices) {
    91 if (i >= count) {
    92 fprintf(stderr, "%s: %s: インデックスが頂点数を超える / index exceeds the vertex count\n", g.path.c_str(),
    93 where.c_str());
    94 return std::nullopt;
    95 }
    96 }
    97 }
    98  
    99 // 法線がなければ、glTFの仕様どおり平らな法線を作る。三角形ごとに頂点を分ける(インデックスなしにする)
    100 // Without normals, make flat normals as the glTF spec requires. Each triangle gets its own vertices (no indices)
    101 if (!normals && p.mode == kGltfTriangles) {
    102 size_t corners = indices.empty() ? count : indices.size();
    103 std::vector<ModelVertex> flat;
    104 flat.reserve(corners / 3 * 3);
    105 for (size_t t = 0; t + 2 < corners; t += 3) {
    106 ModelVertex a = vertices[indices.empty() ? t : indices[t]];
    107 ModelVertex b = vertices[indices.empty() ? t + 1 : indices[t + 1]];
    108 ModelVertex c = vertices[indices.empty() ? t + 2 : indices[t + 2]];
    109 Vec3 n = normalize(cross(b.position - a.position, c.position - a.position)); // 反時計回りなら外向き / CCW = outwards
    110 a.normal = b.normal = c.normal = n;
    111 flat.insert(flat.end(), {a, b, c});
    112 }
    113 vertices = std::move(flat);
    114 indices.clear();
    115 }
    116  
    117 Model::Primitive out;
    118 out.material = p.material;
    119 out.boundsMin = out.boundsMax = vertices.empty() ? Vec3{} : vertices[0].position;
    120 for (const ModelVertex &v : vertices) {
    121 const Vec3 &q = v.position;
    122 out.boundsMin = {q.x < out.boundsMin.x ? q.x : out.boundsMin.x, q.y < out.boundsMin.y ? q.y : out.boundsMin.y,
    123 q.z < out.boundsMin.z ? q.z : out.boundsMin.z};
    124 out.boundsMax = {q.x > out.boundsMax.x ? q.x : out.boundsMax.x, q.y > out.boundsMax.y ? q.y : out.boundsMax.y,
    125 q.z > out.boundsMax.z ? q.z : out.boundsMax.z};
    126 }
    127 // glTFのmode(0〜6)はGL_POINTS〜GL_TRIANGLE_FANと同じ値 / glTF modes 0..6 equal GL_POINTS..GL_TRIANGLE_FAN
    128 out.mesh = Mesh(vertices, indices, kModelVertexLayout, static_cast<GLenum>(p.mode));
    129 return out;
    130 }
    131  
    132 // 箱の8つの角を変換して、boundsを広げる / transforms the 8 corners of a box and grows the bounds
    133 static void growBounds(Vec3 &lo, Vec3 &hi, bool &first, const Mat4 &m, Vec3 bmin, Vec3 bmax) {
    134 for (int i = 0; i < 8; ++i) {
    135 Vec4 c = m * Vec4{i & 1 ? bmax.x : bmin.x, i & 2 ? bmax.y : bmin.y, i & 4 ? bmax.z : bmin.z, 1.0f};
    136 if (first) {
    137 lo = hi = {c.x, c.y, c.z};
    138 first = false;
    139 }
    140 lo = {c.x < lo.x ? c.x : lo.x, c.y < lo.y ? c.y : lo.y, c.z < lo.z ? c.z : lo.z};
    141 hi = {c.x > hi.x ? c.x : hi.x, c.y > hi.y ? c.y : hi.y, c.z > hi.z ? c.z : hi.z};
    142 }
    143 }
    144  
    145 std::optional<Model> Model::load(const std::string &path) {
    146 std::optional<Gltf> loaded = Gltf::load(path);
    147 if (!loaded) return std::nullopt;
    148 const Gltf &g = *loaded;
    149 Model model;
    150  
    151 // テクスチャ:埋め込まれたPNG/JPEGをデコードしてアップロード。glTFのUVは画像の左上が原点なので反転しない
    152 // Textures: decode the embedded PNG/JPEG and upload it. glTF UVs start at the image's top-left: no flipping
    153 std::vector<Vec4> averages(g.textures.size(), Vec4{1.0f, 1.0f, 1.0f, 1.0f});
    154 model.textures.resize(g.textures.size()); // 読めなかったものは空(id 0)=白 / ones that fail stay empty (id 0) = white
    155 for (size_t i = 0; i < g.textures.size(); ++i) {
    156 const GltfTexture &t = g.textures[i];
    157 if (t.source < 0) continue;
    158 std::optional<std::vector<std::uint8_t>> bytes = g.imageData(t.source);
    159 if (!bytes) continue;
    160 std::optional<Image> image = decodeImage(bytes->data(), bytes->size(), false);
    161 if (!image) {
    162 fprintf(stderr, "%s: images[%d] をデコードできない / cannot decode images[%d]\n", path.c_str(), t.source, t.source);
    163 continue;
    164 }
    165 // 各チャンネルの平均(金属・粗さテクスチャの近似に使う) / average of each channel (for the metallic-roughness approximation)
    166 double sum[4] = {0, 0, 0, 0};
    167 for (size_t p = 0; p < image->rgba.size(); ++p) sum[p % 4] += image->rgba[p];
    168 double pixels = static_cast<double>(image->width) * image->height * 255.0;
    169 averages[i] = {static_cast<float>(sum[0] / pixels), static_cast<float>(sum[1] / pixels),
    170 static_cast<float>(sum[2] / pixels), static_cast<float>(sum[3] / pixels)};
    171  
    172 // 色のテクスチャは本当はsRGB(第21章で直す) / colour textures are really sRGB (fixed in chapter 21)
    173 Texture2D texture = Texture2D::fromPixels(image->rgba.data(), image->width, image->height,
    174 {.flipY = false, .mipmaps = true});
    175 if (t.sampler >= 0) {
    176 // 値はGLのenumそのもの(読み込み時に検査済み)。0 = 指定なし / the values are GL enums (validated); 0 = not given
    177 const GltfSampler &s = g.samplers[static_cast<size_t>(t.sampler)];
    178 texture.setWrap(static_cast<GLenum>(s.wrapS), static_cast<GLenum>(s.wrapT));
    179 texture.setFilter(s.minFilter ? static_cast<GLenum>(s.minFilter) : GL_LINEAR_MIPMAP_LINEAR,
    180 s.magFilter ? static_cast<GLenum>(s.magFilter) : GL_LINEAR);
    181 }
    182 model.textures[i] = std::move(texture);
    183 }
    184  
    185 // マテリアル / materials
    186 for (const GltfMaterial &m : g.materials) {
    187 Vec4 mr = {1.0f, 1.0f, 1.0f, 1.0f};
    188 int t = m.metallicRoughnessTexture.index;
    189 if (t >= 0 && model.textures[static_cast<size_t>(t)].id() != 0) mr = averages[static_cast<size_t>(t)];
    190 model.materials.push_back({m, phongFromPbr(m, mr.z, mr.y)}); // B = 金属度 / metallic、G = 粗さ / roughness
    191 }
    192 // マテリアルのないプリミティブ用。glTFの既定(金属度1、粗さ1)だと拡散色の無い淡い塊になるので、白いプラスチックにする
    193 // For primitives without a material. glTF's default (metallic 1, roughness 1) would be a pale blob with no diffuse
    194 // colour here, so use white plastic
    195 model.defaultMaterial.pbr.name = "(default)";
    196 model.defaultMaterial.pbr.metallicFactor = 0.0f;
    197 model.defaultMaterial.pbr.roughnessFactor = 0.5f;
    198 model.defaultMaterial.phong = phongFromPbr(model.defaultMaterial.pbr, 1.0f, 1.0f);
    199  
    200 // メッシュ / meshes
    201 for (size_t i = 0; i < g.meshes.size(); ++i) {
    202 MeshData mesh;
    203 mesh.name = g.meshes[i].name;
    204 for (size_t k = 0; k < g.meshes[i].primitives.size(); ++k) {
    205 std::string where = "meshes[" + std::to_string(i) + "].primitives[" + std::to_string(k) + "]";
    206 std::optional<Primitive> prim = loadPrimitive(g, g.meshes[i].primitives[k], where);
    207 if (prim) mesh.primitives.push_back(std::move(*prim)); // 描けないものは飛ばす / skip what cannot be drawn
    208 }
    209 model.meshes.push_back(std::move(mesh));
    210 }
    211  
    212 model.nodes = g.nodes;
    213 model.roots = g.rootNodes();
    214  
    215 // 全体の箱:メッシュのある全部のノードについて、プリミティブの箱を変換する
    216 // The whole box: transform each primitive's box for every node that has a mesh
    217 bool first = true;
    218 for (size_t i = 0; i < model.nodes.size(); ++i) {
    219 if (model.nodes[i].mesh < 0) continue;
    220 Mat4 m = model.nodeTransform(static_cast<int>(i));
    221 for (const Primitive &p : model.meshes[static_cast<size_t>(model.nodes[i].mesh)].primitives)
    222 growBounds(model.boundsMin, model.boundsMax, first, m, p.boundsMin, p.boundsMax);
    223 }
    224 return model;
    225 }
    226  
    227 //------------------------------------------
    228 // 描画 / drawing
    229 //------------------------------------------
    230  
    231 size_t Model::primitiveCount() const {
    232 size_t n = 0;
    233 for (const MeshData &m : meshes) n += m.primitives.size();
    234 return n;
    235 }
    236  
    237 const Texture2D *Model::texture(int index) const {
    238 if (index < 0 || static_cast<size_t>(index) >= textures.size()) return nullptr;
    239 const Texture2D &t = textures[static_cast<size_t>(index)];
    240 return t.id() != 0 ? &t : nullptr;
    241 }
    242  
    243 int Model::findNode(std::string_view name) const {
    244 for (size_t i = 0; i < nodes.size(); ++i)
    245 if (nodes[i].name == name) return static_cast<int>(i);
    246 return -1;
    247 }
    248  
    249 Mat4 Model::nodeTransform(int node) const {
    250 if (node < 0 || static_cast<size_t>(node) >= nodes.size()) return Mat4::identity();
    251 // 親をたどって左から掛ける:ルート × … × 親 × 自分 / walk up the parents multiplying from the left
    252 Mat4 m = nodes[static_cast<size_t>(node)].localTransform();
    253 for (int p = nodes[static_cast<size_t>(node)].parent; p >= 0; p = nodes[static_cast<size_t>(p)].parent)
    254 m = nodes[static_cast<size_t>(p)].localTransform() * m;
    255 return m;
    256 }
    257  
    258 void Model::draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, bool hierarchy) const {
    259 for (int root : roots) drawNode(root, transform, transform, shader, white, hierarchy);
    260 }
    261  
    262 void Model::drawNode(int node, const Mat4 &parentWorld, const Mat4 &transform, const Shader &shader,
    263 const Texture2D &white, bool hierarchy) const {
    264 const GltfNode &n = nodes[static_cast<size_t>(node)];
    265 // ワールド行列 = 親のワールド行列 × 自分のローカル行列 / world = the parent's world matrix × our local matrix
    266 Mat4 world = (hierarchy ? parentWorld : transform) * n.localTransform();
    267 if (n.mesh >= 0) {
    268 shader.set("uModel", world);
    269 shader.set("uNormalMatrix", normalMatrix(world));
    270 for (const Primitive &p : meshes[static_cast<size_t>(n.mesh)].primitives) {
    271 const MaterialData &md = p.material >= 0 ? materials[static_cast<size_t>(p.material)] : defaultMaterial;
    272 Material m = md.phong;
    273 m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture
    274 m.emissionMap = texture(md.pbr.emissiveTexture.index);
    275 m.apply(shader, white);
    276 p.mesh.draw();
    277 }
    278 }
    279 for (int child : n.children) drawNode(child, world, transform, shader, white, hierarchy);
    280 }

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

前新
@@ -0,0 +1,80 @@
    1 // glTF/GLBのモデルをGPUに載せて描く / uploads a glTF/GLB model to the GPU and draws it
    2 #pragma once
    3  
    4 #include "gltf.hh"
    5 #include "material.hh"
    6 #include "mesh.hh"
    7 #include "shader.hh"
    8 #include "texture.hh"
    9  
    10 #include <optional>
    11 #include <string>
    12 #include <string_view>
    13 #include <vector>
    14  
    15 // 読み込んだモデル:メッシュ(VAO)、テクスチャ、マテリアル、ノードの階層(RAII、コピー不可・移動可)。
    16 // 描くときは、ノードごとに 親のワールド行列 × 自分のローカル行列 をたどる。
    17 // A loaded model: meshes (VAOs), textures, materials and the node hierarchy (RAII, non-copyable, movable).
    18 // Drawing walks the nodes, each with world = parent's world × its own local matrix.
    19 class Model {
    20 public:
    21 // プリミティブ一つ=描画呼び出し一回 / one primitive = one draw call
    22 struct Primitive {
    23 Mesh mesh;
    24 int material = -1; // materialsの番号、-1 = 既定 / index into materials, -1 = the default
    25 Vec3 boundsMin, boundsMax; // モデル座標の箱 / box in model space
    26 };
    27 struct MeshData {
    28 std::string name;
    29 std::vector<Primitive> primitives;
    30 };
    31 // glTFのPBRマテリアルと、それを近似したBlinn-Phongのマテリアル(マップは描くときに繋ぐ)
    32 // The glTF PBR material and the Blinn-Phong material approximating it (maps are attached at draw time)
    33 struct MaterialData {
    34 GltfMaterial pbr;
    35 Material phong;
    36 };
    37  
    38 Model() = default;
    39 Model(const Model &) = delete;
    40 Model &operator=(const Model &) = delete;
    41 Model(Model &&) noexcept = default;
    42 Model &operator=(Model &&) noexcept = default;
    43  
    44 // .glb/.gltfを読み、GPUに載せる。失敗したらエラーを表示してstd::nullopt。
    45 // Loads a .glb/.gltf and uploads it to the GPU. On failure prints the error and returns std::nullopt.
    46 static std::optional<Model> load(const std::string &path);
    47  
    48 // transform(モデル全体の置き場所)で描く。マップのないマテリアルにはwhiteを繋ぐ。
    49 // hierarchy = falseなら親の変換を無視する(なぜ親×子が必要かを見せるため)。
    50 // Draws with transform (where the whole model goes). Binds `white` for missing maps.
    51 // hierarchy = false ignores the parents' transforms (to show why parent × child is needed).
    52 void draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, bool hierarchy = true) const;
    53  
    54 // 名前でノードを探す。なければ-1 / finds a node by name; -1 if none
    55 int findNode(std::string_view name) const;
    56 // ノードのモデル座標での行列(ルートからの積)。描く場所はtransform × これ
    57 // A node's matrix in model space (the product from the root). It is drawn at transform × this
    58 Mat4 nodeTransform(int node) const;
    59  
    60 // ノードは公開:translation・rotation・scaleを書き換えると動かせる(行列のノードは動かせない)
    61 // The nodes are public: change translation / rotation / scale to animate them (matrix nodes cannot be animated)
    62 std::vector<GltfNode> nodes;
    63 std::vector<int> roots; // 描き始めるノード / the nodes drawing starts from
    64 Vec3 boundsMin, boundsMax; // モデル全体の箱(読み込んだときの姿勢) / box around the whole model (as loaded)
    65  
    66 size_t meshCount() const { return meshes.size(); }
    67 size_t primitiveCount() const;
    68 size_t materialCount() const { return materials.size(); }
    69 size_t textureCount() const { return textures.size(); }
    70  
    71 private:
    72 void drawNode(int node, const Mat4 &parentWorld, const Mat4 &transform, const Shader &shader,
    73 const Texture2D &white, bool hierarchy) const;
    74 const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing
    75  
    76 std::vector<MeshData> meshes;
    77 std::vector<Texture2D> textures; // glTFのtexturesと同じ番号 / same indices as the glTF textures
    78 std::vector<MaterialData> materials;
    79 MaterialData defaultMaterial;
    80 };

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

前新
@@ -82,3 +82,20 @@ void Texture2D::setWrap(GLenum wrapS, GLenum wrapT) {
82 glTextureParameteri(handle, GL_TEXTURE_WRAP_S, static_cast<GLint>(wrapS)); // 横 / horizontal (u) 82 glTextureParameteri(handle, GL_TEXTURE_WRAP_S, static_cast<GLint>(wrapS)); // 横 / horizontal (u)
83 glTextureParameteri(handle, GL_TEXTURE_WRAP_T, static_cast<GLint>(wrapT)); // 縦 / vertical (v) 83 glTextureParameteri(handle, GL_TEXTURE_WRAP_T, static_cast<GLint>(wrapT)); // 縦 / vertical (v)
84 } 84 }
    85  
    86 std::optional<Image> decodeImage(const unsigned char *bytes, size_t size, bool flipY) {
    87 stbi_set_flip_vertically_on_load(flipY ? 1 : 0);
    88 int width = 0, height = 0, channels = 0;
    89 // ファイルからではなくメモリから(GLBに埋め込まれた画像など) / from memory instead of a file (e.g. images embedded in a GLB)
    90 unsigned char *pixels = stbi_load_from_memory(bytes, static_cast<int>(size), &width, &height, &channels, 4);
    91 if (!pixels) {
    92 fprintf(stderr, "画像をデコードできない / cannot decode image: %s\n", stbi_failure_reason());
    93 return std::nullopt;
    94 }
    95 Image image;
    96 image.width = width;
    97 image.height = height;
    98 image.rgba.assign(pixels, pixels + static_cast<size_t>(width) * static_cast<size_t>(height) * 4);
    99 stbi_image_free(pixels);
    100 return image;
    101 }

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

前新
@@ -3,8 +3,10 @@
3   3  
4 #include <glad/glad.h> 4 #include <glad/glad.h>
5   5  
    6 #include <cstddef>
6 #include <optional> 7 #include <optional>
7 #include <string> 8 #include <string>
    9 #include <vector>
8   10  
9 struct TextureOptions { 11 struct TextureOptions {
10 bool flipY = true; // 画像は上から、OpenGLのUVは下から / images start at the top, OpenGL UVs at the bottom 12 bool flipY = true; // 画像は上から、OpenGLのUVは下から / images start at the top, OpenGL UVs at the bottom
@@ -12,6 +14,16 @@ struct TextureOptions {
12 bool srgb = false; // 色の画像はsRGB(正しい扱いは第21章) / colour images are sRGB (handled properly in chapter 21) 14 bool srgb = false; // 色の画像はsRGB(正しい扱いは第21章) / colour images are sRGB (handled properly in chapter 21)
13 }; 15 };
14   16  
    17 // デコードした画像:RGBA8、上の行から順に / a decoded image: RGBA8, rows from the top
    18 struct Image {
    19 int width = 0, height = 0;
    20 std::vector<unsigned char> rgba;
    21 };
    22  
    23 // メモリ上の画像ファイル(PNG、JPEG…)をデコードする。flipY = trueなら上下を反転する。失敗したらstd::nullopt。
    24 // Decodes an image file held in memory (PNG, JPEG, ...). flipY = true flips it upside down. std::nullopt on failure.
    25 std::optional<Image> decodeImage(const unsigned char *bytes, size_t size, bool flipY);
    26  
15 // 2Dテクスチャ(RAII、コピー不可・移動可)。DSAで作る。 27 // 2Dテクスチャ(RAII、コピー不可・移動可)。DSAで作る。
16 // A 2D texture (RAII, non-copyable, movable), created with DSA. 28 // A 2D texture (RAII, non-copyable, movable), created with DSA.
17 class Texture2D { 29 class Texture2D {


コメント(0)

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