diff --git a/assets/LICENSE.txt b/assets/LICENSE.txt index 11531cd..c9fefd7 100644 --- a/assets/LICENSE.txt +++ b/assets/LICENSE.txt @@ -7,5 +7,6 @@ textures/crate.png 木箱 / wooden crate textures/floor.png 石の床 / stone floor tiles textures/crate_specular.png 木箱の鏡面反射マップ / crate specular map textures/crate_emission.png 木箱の発光マップ / crate emission map +textures/rug.png 敷物 / a runner rug (chapter 15) models/crate.glb 木箱のモデル / crate model models/diorama.glb 小さな場面 / a small diorama scene diff --git a/assets/textures/rug.png b/assets/textures/rug.png new file mode 100644 index 0000000..8061e99 Binary files /dev/null and b/assets/textures/rug.png differ diff --git a/shaders/depth.frag b/shaders/depth.frag new file mode 100644 index 0000000..aa59ee9 --- /dev/null +++ b/shaders/depth.frag @@ -0,0 +1,24 @@ +#version 460 core +// 深度バッファの値を灰色で見せる(頂点シェーダーはunlit.vert) / shows depth-buffer values as grey (vertex shader: unlit.vert) + +uniform int uDepthMode; // 1 = そのままの値(非線型) / the raw value (non-linear), 2 = 線型にした距離 / linearised distance +uniform float uNearPlane; // カメラのnearPlane / the camera's nearPlane +uniform float uFarPlane; // カメラのfarPlane / the camera's farPlane +uniform float uDisplayRange; // 線型の距離はこの距離(m)で割って見せる / the linear distance is shown divided by this (m) + +layout(location = 0) out vec4 out_color; + +// 深度バッファの値(0〜1)→ カメラからの距離。線型代数 第12章:NDCのzは -A - B/z で、1/zに比例する。それを逆に解く +// depth-buffer value (0..1) → distance from the camera. Linear Algebra chapter 12: NDC z is -A - B/z (it follows 1/z); +// this solves it backwards +float linearDepth(float depth) { + float ndc = depth * 2.0 - 1.0; // 0..1 → -1..1(glDepthRangeの既定値) / 0..1 → -1..1 (the default glDepthRange) + return 2.0 * uNearPlane * uFarPlane / (uFarPlane + uNearPlane - ndc * (uFarPlane - uNearPlane)); +} + +void main() { + // gl_FragCoord.z = このピクセルが深度バッファに書く値 / the value this fragment writes to the depth buffer + float depth = gl_FragCoord.z; + float v = uDepthMode == 2 ? linearDepth(depth) / uDisplayRange : depth; + out_color = vec4(vec3(clamp(v, 0.0, 1.0)), 1.0); +} diff --git a/src/main.cc b/src/main.cc index 7118129..f70cad1 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,5 +1,5 @@ -// 第14章:モデルの読み込み -// Chapter 14: loading models +// 第15章:深度テストとステンシルテスト +// Chapter 15: depth and stencil testing // // 操作 / Controls: // WASD 前後左右に移動 / move forward, back, left, right @@ -7,17 +7,23 @@ // Shift 速く動く / move faster // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit // ホイール / wheel ズーム / zoom +// クリック / click 物を選ぶ(FPSは左ボタンで画面の真ん中、オービットは右ボタンでカーソルの位置) +// select an object (FPS: left button, at the centre of the screen; orbit: right button, at the cursor) +// E 次の物を選ぶ / select the next object +// T 選んだ物の輪郭を壁越しに見せる(X線)オン・オフ / show the selection outline through walls (x-ray) on / off +// Z 表示:色 → 深度(そのまま) → 深度(線型) / view: colour → depth (raw) → depth (linear) +// G 深度関数:GL_LESS → GL_ALWAYS → GL_GREATER / depth function: GL_LESS → GL_ALWAYS → GL_GREATER +// X Zファイティングの対策:なし → ポリゴンオフセット → 3 mm持ち上げる +// z-fighting fix: none → polygon offset → lift by 3 mm +// M ニアプレーン:0.1 m ⇔ 0.1 mm / near plane: 0.1 m ⇔ 0.1 mm // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals // N 昼 ⇔ 夜 / day ⇔ night // F 懐中電灯のオン・オフ / flashlight on / off // P 風車を止める・回す / pause / resume the windmill -// H ノードの階層のオン・オフ(オフ=親の変換を無視) / node hierarchy on / off (off = ignore the parents) // Tab カーソルのキャプチャ切り替え / toggle cursor capture // R シェーダーを読み直す / reload the shaders // Esc 終了 / quit -// -// 使い方 / usage: game [model.glb] (指定すれば、そのモデルを場面の真ん中に置く / puts that model in the middle of the scene) #include "camera.hh" #include "lights.hh" #include "material.hh" @@ -29,6 +35,7 @@ #include "texture.hh" #include "window.hh" +#include #include #include #include @@ -43,45 +50,51 @@ static const CrateInfo kCrates[] = { {{5.5f, 0.0f, 1.5f}, 0.4f}, {{6.3f, 0.0f, 2.6f}, -0.3f}, {{5.9f, 1.0f, 2.0f}, 0.1f}, {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f}, }; +constexpr int kCrateCount = static_cast(sizeof kCrates / sizeof kCrates[0]); + +// ステンシルに書く物の番号。0 = 何もない(床と敷物) / the object numbers written to the stencil buffer. 0 = nothing +// (the floor and the rug) +constexpr int kDioramaId = kCrateCount + 1; // 木箱は1〜5 / the crates are 1..5 static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; +static const char *const kDepthViewNames[] = {"colour", "depth (raw, non-linear)", "depth (linear)"}; +static const GLenum kDepthFuncs[] = {GL_LESS, GL_ALWAYS, GL_GREATER}; +static const char *const kDepthFuncNames[] = {"GL_LESS", "GL_ALWAYS", "GL_GREATER"}; +static const char *const kZFixNames[] = {"none (z-fighting)", "polygon offset", "lifted by 3 mm"}; -static void printModel(const char *path, const Model &m) { - printf("%s: %zu nodes, %zu meshes, %zu primitives, %zu materials, %zu textures, bounds (%.2f, %.2f, %.2f) - (%.2f, " - "%.2f, %.2f)\n", - path, m.nodes.size(), m.meshCount(), m.primitiveCount(), m.materialCount(), m.textureCount(), m.boundsMin.x, - m.boundsMin.y, m.boundsMin.z, m.boundsMax.x, m.boundsMax.y, m.boundsMax.z); +// 選んだ物の輪郭用:モデルの箱の中心を基準に、各辺がwidthずつ大きくなるように拡大する行列 +// For the selection outline: a matrix that scales a model about the centre of its box so that every side grows by width +static Mat4 outlineScale(const Model &m, float width) { + Vec3 size = m.boundsMax - m.boundsMin; + Vec3 centre = 0.5f * (m.boundsMin + m.boundsMax); + Vec3 k = {(size.x + 2.0f * width) / size.x, (size.y + 2.0f * width) / size.y, (size.z + 2.0f * width) / size.z}; + return translate(centre) * scale(k) * translate(-centre); } -int main(int argc, char **argv) { +int main() { Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 14")) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 15")) return 1; std::optional phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); + std::optional unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag"); + std::optional depthView = Shader::load("shaders/unlit.vert", "shaders/depth.frag"); std::optional floorTexture = Texture2D::load("assets/textures/floor.png"); - if (!phong || !floorTexture) return 1; + std::optional rugTexture = Texture2D::load("assets/textures/rug.png"); + if (!phong || !unlit || !depthView || !floorTexture || !rugTexture) return 1; - // モデル:真ん中の場面(引数で別のファイルにできる)と木箱 / 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 scene = Model::load(scenePath); + std::optional scene = Model::load("assets/models/diorama.glb"); std::optional crate = Model::load("assets/models/crate.glb"); if (!scene || !crate) return 1; - printModel(scenePath, *scene); - printModel("assets/models/crate.glb", *crate); - glEnable(GL_DEPTH_TEST); const unsigned char whitePixel[4] = {255, 255, 255, 255}; Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); - // 動かすノードと、光を置くノードを名前で探す(ないファイルでは-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(rotor)].rotation : Quat{}; Camera fps; - fps.position = {0.0f, 2.6f, 9.0f}; + fps.position = {0.0f, 2.4f, 13.0f}; fps.pitch = radians(-12.0f); OrbitCamera orbit; @@ -90,15 +103,19 @@ int main(int argc, char **argv) { orbit.yaw = radians(30.0f); bool useOrbit = false; - int viewMode = 0; - bool night = false, flashlightOn = false, windmillMoving = true, hierarchy = true; + int viewMode = 0, depthViewMode = 0, depthFunc = 0, zFix = 0; + bool night = false, flashlightOn = false, windmillMoving = true, xray = false, tinyNear = false; + int selected = 0; // 選んでいる物の番号(0 = なし) / the selected object's number (0 = none) + bool pickRequested = false; // 次のフレームでステンシルを読む / read the stencil buffer this frame + double pickX = 0.0, pickY = 0.0; float windmillTime = 0.0f; window.setCursorCaptured(true); window.onKey = [&](int key, int action, int /*mods*/) { if (action != GLFW_PRESS) return; if (key == GLFW_KEY_ESCAPE) window.close(); - if (key == GLFW_KEY_R && phong->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); + if (key == GLFW_KEY_R && phong->reload() && unlit->reload() && depthView->reload()) + printf("シェーダーを読み直した / shaders reloaded\n"); if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); if (key == GLFW_KEY_C) { useOrbit = !useOrbit; @@ -109,13 +126,49 @@ int main(int argc, char **argv) { viewMode = (viewMode + 1) % 6; printf("view: %s\n", kViewModeNames[viewMode]); } + if (key == GLFW_KEY_Z) { + depthViewMode = (depthViewMode + 1) % 3; + printf("view: %s\n", kDepthViewNames[depthViewMode]); + } + if (key == GLFW_KEY_G) { + depthFunc = (depthFunc + 1) % 3; + printf("depth function: %s\n", kDepthFuncNames[depthFunc]); + } + if (key == GLFW_KEY_X) { + zFix = (zFix + 1) % 3; + printf("z-fighting fix: %s\n", kZFixNames[zFix]); + } + if (key == GLFW_KEY_M) { + tinyNear = !tinyNear; + fps.nearPlane = orbit.nearPlane = tinyNear ? 0.0001f : 0.1f; + printf("near plane: %g m\n", static_cast(fps.nearPlane)); + } + if (key == GLFW_KEY_E) { + selected = selected % kDioramaId + 1; // 1 → 2 → … → 6 → 1 + printf("selected: %d\n", selected); + } + if (key == GLFW_KEY_T) { + xray = !xray; + printf("outline through walls: %s\n", xray ? "on" : "off"); + } if (key == GLFW_KEY_N) night = !night; if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; - if (key == GLFW_KEY_H) { - hierarchy = !hierarchy; - printf("hierarchy: %s\n", hierarchy ? "on (world = parent x local)" : "off (world = local)"); - } + }; + window.onMouseButton = [&](int button, int action, int /*mods*/) { + if (action != GLFW_PRESS) return; + bool fpsPick = !useOrbit && button == GLFW_MOUSE_BUTTON_LEFT; + if (!fpsPick && button != GLFW_MOUSE_BUTTON_RIGHT) return; + pickRequested = true; + // FPSでカーソルを隠しているときは画面の真ん中(照準)、それ以外はカーソルの位置 + // With the cursor captured in FPS mode: the centre of the screen (the crosshair); otherwise the cursor position + bool centre = !useOrbit && window.cursorCaptured(); + // マウスはウィンドウ座標、glReadPixelsはフレームバッファのピクセル。高DPIでは違うので換算する + // The mouse is in window coordinates, glReadPixels wants framebuffer pixels; they differ on high-DPI screens + int winW = 1, winH = 1; + glfwGetWindowSize(window.handle(), &winW, &winH); + pickX = centre ? window.width() / 2.0 : window.mouseX() * window.width() / std::max(winW, 1); + pickY = centre ? window.height() / 2.0 : window.mouseY() * window.height() / std::max(winH, 1); }; Mesh floorMesh = makePlane(40.0f, 10.0f); @@ -124,6 +177,26 @@ int main(int argc, char **argv) { floorMaterial.specular = {0.15f, 0.15f, 0.15f}; floorMaterial.shininess = 16.0f; + // 敷物:1×1の板を2.6 m × 5.2 mに拡大。床とまったく同じ平面(y = 0)にある / the rug: the 1 × 1 plane scaled to + // 2.6 m × 5.2 m. It lies in exactly the same plane as the floor (y = 0) + Mesh rugMesh = makePlane(1.0f, 1.0f); + Material rugMaterial; + rugMaterial.diffuseMap = &*rugTexture; + rugMaterial.specular = {0.05f, 0.05f, 0.05f}; + rugMaterial.shininess = 8.0f; + + // ステンシルテストを有効にする。各物は描くときに自分の番号をステンシルに書く(下のsetStencilId) + // Enable the stencil test. Each object writes its number to the stencil buffer while it is drawn (setStencilId below) + glEnable(GL_DEPTH_TEST); + glEnable(GL_STENCIL_TEST); + // 失敗したとき(ステンシル、深度)はそのまま、両方通ったら参照値で置き換える + // keep the value when the stencil or depth test fails, replace it with the reference value when both pass + glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); + + auto setStencilId = [](int id) { + glStencilFunc(GL_ALWAYS, id, 0xFF); // いつも通す。参照値 = id / always pass; reference value = id + }; + double lastTime = window.time(); while (!window.shouldClose()) { double now = window.time(); @@ -149,8 +222,6 @@ int main(int argc, char **argv) { fps.move(dir, dt); } - // 風車の羽根: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(rotor)].rotation = @@ -160,8 +231,9 @@ int main(int argc, char **argv) { Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect()); Vec3 viewPos = useOrbit ? orbit.position() : fps.position; Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); + float nearPlane = useOrbit ? orbit.nearPlane : fps.nearPlane; + float farPlane = useOrbit ? orbit.farPlane : fps.farPlane; - // 昼は太陽、夜は月と街灯 / the sun by day, the moon and the street lamp by night LightSet lights; if (!night) { lights.ambient = {0.28f, 0.30f, 0.34f}; @@ -169,7 +241,6 @@ int main(int argc, char **argv) { } 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}); @@ -177,25 +248,118 @@ int main(int argc, char **argv) { } if (flashlightOn) lights.spots.push_back({.position = viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); - if (night) glClearColor(0.02f, 0.03f, 0.06f, 1.0f); + // 深度関数。GL_GREATERでは深度バッファを0(一番手前)でクリアしないと何も通らない + // The depth function. With GL_GREATER the depth buffer must be cleared to 0 (the nearest value), or nothing passes + glDepthFunc(kDepthFuncs[depthFunc]); + glClearDepth(kDepthFuncs[depthFunc] == GL_GREATER ? 0.0 : 1.0); + glClearStencil(0); + // glClearはマスクを守る:ステンシルのマスクが0x00のままだとステンシルがクリアされない + // glClear obeys the write masks: with the stencil mask left at 0x00 the stencil buffer would not be cleared + glStencilMask(0xFF); + if (depthViewMode != 0) { + float c = depthFunc == 2 ? 0.0f : 1.0f; // 深度をクリアした値と同じ灰色 / the same grey as the cleared depth + glClearColor(c, c, c, 1.0f); + } + else if (night) glClearColor(0.02f, 0.03f, 0.06f, 1.0f); else glClearColor(0.45f, 0.62f, 0.85f, 1.0f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - phong->use(); - phong->set("uView", view); - phong->set("uProj", proj); - phong->set("uViewPos", viewPos); - phong->set("uViewMode", viewMode); - lights.apply(*phong); - - 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); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + + // 色か深度か。どちらでも同じ順番で同じ物を描く / colour or depth: either way the same objects in the same order + const Shader &s = depthViewMode == 0 ? *phong : *depthView; + bool lit = depthViewMode == 0; + s.use(); + s.set("uView", view); + s.set("uProj", proj); + if (lit) { + s.set("uViewPos", viewPos); + s.set("uViewMode", viewMode); + lights.apply(s); + } else { + s.set("uDepthMode", depthViewMode); + s.set("uNearPlane", nearPlane); + s.set("uFarPlane", farPlane); + s.set("uDisplayRange", 30.0f); + } + + // 一つの板(床・敷物)を描く / draws one flat mesh (the floor or the rug) + auto drawFlat = [&](const Mesh &mesh, const Material &material, const Mat4 &model) { + s.set("uModel", model); + if (lit) { + s.set("uNormalMatrix", normalMatrix(model)); + material.apply(s, white); + } + mesh.draw(); + }; + + setStencilId(0); + drawFlat(floorMesh, floorMaterial, Mat4::identity()); + + // 敷物は床と同じ平面:どちらの深度が勝つかはピクセルごとの丸め誤差で決まる(Zファイティング) + // The rug lies in the floor's plane: which depth wins is decided by per-pixel rounding (z-fighting) + Mat4 rugModel = translate({0.0f, zFix == 2 ? 0.003f : 0.0f, 7.6f}) * scale({2.6f, 1.0f, 5.2f}); + if (zFix == 1) { + // 深度を少しカメラ側にずらす:factor × 斜面の傾き + units × 深度バッファの最小単位。負 = 手前へ + // shift the depth slightly towards the camera: factor × slope + units × the smallest depth step. negative = closer + glEnable(GL_POLYGON_OFFSET_FILL); + glPolygonOffset(-1.0f, -1.0f); + } + drawFlat(rugMesh, rugMaterial, rugModel); + glDisable(GL_POLYGON_OFFSET_FILL); + + setStencilId(kDioramaId); + if (lit) scene->draw(s, Mat4::identity(), white); + else scene->drawGeometry(s, Mat4::identity()); + for (int i = 0; i < kCrateCount; ++i) { + setStencilId(i + 1); + Mat4 m = translate(kCrates[i].position) * rotateY(kCrates[i].angle); + if (lit) crate->draw(s, m, white); + else crate->drawGeometry(s, m); + } + + // クリックした場所のステンシルの値=そこに見えている物の番号 / the stencil value under the click = the number of + // the object visible there + if (pickRequested) { + pickRequested = false; + unsigned char id = 0; + // glReadPixelsの原点は左下、マウスは左上 / glReadPixels starts at the bottom left, the mouse at the top left + int px = static_cast(pickX), py = window.height() - 1 - static_cast(pickY); + glReadPixels(px, py, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, &id); + selected = id; + printf("picked at (%d, %d): %d%s\n", px, py, selected, selected == 0 ? " (nothing)" : ""); + } + + // 輪郭:拡大した物を、ステンシルがその物の番号「ではない」ところだけに一色で描く + // The outline: draw the enlarged object in one colour, only where the stencil is NOT that object's number + if (selected > 0) { + glStencilFunc(GL_NOTEQUAL, selected, 0xFF); + glStencilMask(0x00); // 輪郭はステンシルに書かない / the outline does not write to the stencil buffer + if (xray) glDisable(GL_DEPTH_TEST); // 他の物の後ろでも見える / visible even behind other objects + unlit->use(); + unlit->set("uView", view); + unlit->set("uProj", proj); + unlit->set("uColor", Vec3{1.0f, 0.55f, 0.1f}); + if (selected == kDioramaId) { + scene->drawGeometry(*unlit, outlineScale(*scene, 0.06f)); + } else { + const CrateInfo &c = kCrates[selected - 1]; + crate->drawGeometry(*unlit, translate(c.position) * rotateY(c.angle) * outlineScale(*crate, 0.04f)); + } + glEnable(GL_DEPTH_TEST); + glStencilMask(0xFF); + } + + // 照準:シザーテストで小さな長方形を二つクリアするだけ(シェーダーなし) + // The crosshair: just clear two small rectangles with the scissor test (no shader) + if (!useOrbit && window.cursorCaptured()) { + int cx = window.width() / 2, cy = window.height() / 2; + glEnable(GL_SCISSOR_TEST); + glClearColor(1.0f, 1.0f, 1.0f, 1.0f); + glScissor(cx - 8, cy - 1, 17, 3); + glClear(GL_COLOR_BUFFER_BIT); + glScissor(cx - 1, cy - 8, 3, 17); + glClear(GL_COLOR_BUFFER_BIT); + glDisable(GL_SCISSOR_TEST); + } window.swapBuffers(); } diff --git a/src/model.cc b/src/model.cc index 7e5fcbc..cb0cadc 100644 --- a/src/model.cc +++ b/src/model.cc @@ -256,25 +256,32 @@ Mat4 Model::nodeTransform(int node) const { } 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); + for (int root : roots) drawNode(root, transform, transform, shader, &white, hierarchy, true); +} + +void Model::drawGeometry(const Shader &shader, const Mat4 &transform) const { + bool normals = shader.has("uNormalMatrix"); + for (int root : roots) drawNode(root, transform, transform, shader, nullptr, true, normals); } void Model::drawNode(int node, const Mat4 &parentWorld, const Mat4 &transform, const Shader &shader, - const Texture2D &white, bool hierarchy) const { + const Texture2D *white, bool hierarchy, bool normals) const { const GltfNode &n = nodes[static_cast(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)); + if (normals) shader.set("uNormalMatrix", normalMatrix(world)); for (const Primitive &p : meshes[static_cast(n.mesh)].primitives) { - const MaterialData &md = p.material >= 0 ? materials[static_cast(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); + if (white) { + const MaterialData &md = p.material >= 0 ? materials[static_cast(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); + for (int child : n.children) drawNode(child, world, transform, shader, white, hierarchy, normals); } diff --git a/src/model.hh b/src/model.hh index 108c2aa..d414cd8 100644 --- a/src/model.hh +++ b/src/model.hh @@ -50,6 +50,11 @@ public: // 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; + // 形だけを描く:マテリアルもテクスチャも設定せず、ノードごとにuModelだけ(シェーダーが使っていればuNormalMatrixも)。 + // 深度の表示、輪郭、のちの影(第23章)のように、色を使わないパス用。 + // Draws the shape only: no materials or textures, just uModel per node (and uNormalMatrix if the shader uses it). + // For passes that need no colour: the depth view, outlines, and later shadows (chapter 23). + void drawGeometry(const Shader &shader, const Mat4 &transform) const; // 名前でノードを探す。なければ-1 / finds a node by name; -1 if none int findNode(std::string_view name) const; @@ -69,8 +74,9 @@ public: size_t textureCount() const { return textures.size(); } private: + // white == nullptrなら形だけ(drawGeometry) / white == nullptr: shape only (drawGeometry) void drawNode(int node, const Mat4 &parentWorld, const Mat4 &transform, const Shader &shader, - const Texture2D &white, bool hierarchy) const; + const Texture2D *white, bool hierarchy, bool normals) const; const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing std::vector meshes; diff --git a/src/shader.hh b/src/shader.hh index a3d9856..46b8562 100644 --- a/src/shader.hh +++ b/src/shader.hh @@ -41,6 +41,9 @@ public: void set(const char *name, const Mat3 &value) const; void set(const char *name, const Mat4 &value) const; + // そのユニフォームがプログラムで使われているか(警告は出さない) / does the program use that uniform? (no warning) + bool has(const char *name) const { return glGetUniformLocation(program, name) >= 0; } + private: GLint location(const char *name) const;