diff --git a/assets/LICENSE.txt b/assets/LICENSE.txt index c9fefd7..0207210 100644 --- a/assets/LICENSE.txt +++ b/assets/LICENSE.txt @@ -8,5 +8,7 @@ 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) +textures/grass_blades.png 草の葉(アルファ付き) / grass blades with alpha (chapter 16) +models/window.glb 花箱つきの窓 / a window with a flower box (chapter 16) models/crate.glb 木箱のモデル / crate model models/diorama.glb 小さな場面 / a small diorama scene diff --git a/assets/models/window.glb b/assets/models/window.glb new file mode 100644 index 0000000..aec6443 Binary files /dev/null and b/assets/models/window.glb differ diff --git a/assets/textures/grass_blades.png b/assets/textures/grass_blades.png new file mode 100644 index 0000000..edcc1c8 Binary files /dev/null and b/assets/textures/grass_blades.png differ diff --git a/shaders/phong.frag b/shaders/phong.frag index b44d791..1cf41bf 100644 --- a/shaders/phong.frag +++ b/shaders/phong.frag @@ -9,6 +9,10 @@ struct Material { vec3 specular; // 鏡面反射の色と強さ / specular colour and strength vec3 emission; // 発光の色 / emission colour float shininess; // 光沢度 / shininess + float alpha; // 不透明度(diffuseマップのアルファと掛ける) / opacity (multiplied with the diffuse map's alpha) + int alphaMode; // 0 = 不透明 / opaque, 1 = マスク / mask (discard), 2 = ブレンド / blend + float alphaCutoff; // マスクのしきい値 / the mask threshold + bool doubleSided; // 裏面では法線を反転する / flip the normal on back faces }; uniform Material uMaterial; @@ -56,6 +60,11 @@ uniform vec3 uViewPos; // カメラの位置(ワールド座標) / camera po // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals uniform int uViewMode; +// C++のAlphaModeと同じ / same as AlphaMode in C++ +#define ALPHA_OPAQUE 0 +#define ALPHA_MASK 1 +#define ALPHA_BLEND 2 + layout(location = 0) out vec4 out_color; // このピクセルの表面:どの光の計算にも同じものを使う / this pixel's surface: the same for every light @@ -84,11 +93,21 @@ float attenuate(float d, vec3 k) { } void main() { + vec4 base = texture(uDiffuseMap, vUv); + float alpha = uMaterial.alpha * base.a; + // マスク:しきい値未満は捨てる(色も深度も書かない)。ブレンド:完全に透明なら深度も書かないように捨てる + // Mask: discard below the threshold (writes neither colour nor depth). Blend: discard fully transparent pixels so + // they do not write depth either + if (uMaterial.alphaMode == ALPHA_MASK && alpha < uMaterial.alphaCutoff) discard; + if (uMaterial.alphaMode == ALPHA_BLEND && alpha < 1.0 / 255.0) discard; + Surface s; s.position = vWorldPos; s.normal = normalize(vNormal); + // 両面のマテリアルを裏から見ているなら、法線は裏を向く / seen from behind, a double-sided surface's normal points the other way + if (uMaterial.doubleSided && !gl_FrontFacing) s.normal = -s.normal; s.view = normalize(uViewPos - vWorldPos); - s.diffuse = uMaterial.diffuse * texture(uDiffuseMap, vUv).rgb; + s.diffuse = uMaterial.diffuse * base.rgb; s.specular = uMaterial.specular * texture(uSpecularMap, vUv).rgb; s.shininess = uMaterial.shininess; vec3 emission = uMaterial.emission * texture(uEmissionMap, vUv).rgb; @@ -125,5 +144,6 @@ void main() { else if (uViewMode == 3) color = specular; else if (uViewMode == 4) color = emission; else if (uViewMode == 5) color = s.normal * 0.5 + 0.5; - out_color = vec4(color, 1.0); + // 不透明とマスクはアルファ1。ブレンドだけ本当のアルファを出す / opaque and mask output alpha 1; only blend outputs its alpha + out_color = vec4(color, uMaterial.alphaMode == ALPHA_BLEND ? alpha : 1.0); } diff --git a/src/main.cc b/src/main.cc index f70cad1..c2c6d86 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,5 +1,5 @@ -// 第15章:深度テストとステンシルテスト -// Chapter 15: depth and stencil testing +// 第16章:ブレンディングとフェイスカリング +// Chapter 16: blending and face culling // // 操作 / Controls: // WASD 前後左右に移動 / move forward, back, left, right @@ -7,15 +7,12 @@ // 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 +// K カリング:裏面 → なし → 表面 → 裏面だがglFrontFace(GL_CW) +// culling: back faces → off → front faces → back faces but glFrontFace(GL_CW) +// O 半透明の物を遠い順に並べる・並べない / sort transparent objects back to front, or not +// B 半透明の物が深度を書く・書かない(glDepthMask) / transparent objects write depth or not (glDepthMask) +// G 草:アルファテスト → ブレンド(ストレートアルファ) → ブレンド(乗算済みアルファ) +// grass: alpha test → blending (straight alpha) → blending (premultiplied alpha) // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals // N 昼 ⇔ 夜 / day ⇔ night @@ -37,54 +34,85 @@ #include #include +#include #include +#include #include +#include -// 木箱のモデルを置く場所:位置(底の中心)とY軸周りの回転 / where the crate models go: position (bottom centre) and yaw -struct CrateInfo { +// 物を置く場所:位置(底の中心)とY軸周りの回転 / where things go: position (bottom centre) and yaw +struct Placement { Vec3 position; float angle; }; -static const CrateInfo kCrates[] = { +static const Placement 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 +// 窓はカメラから見て重なるように並べる。配列は手前の窓から:並べ替えないと順番が逆になる +// The windows overlap as seen from the camera. The array starts with the nearest one: without sorting the order is wrong +static const Placement kWindows[] = { + {{-0.75f, 0.0f, 8.7f}, 0.15f}, {{2.6f, 0.0f, 7.4f}, -0.3f}, {{-0.3f, 0.0f, 7.3f}, 0.1f}, {{0.25f, 0.0f, 5.9f}, 0.05f}, +}; 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"}; - -// 選んだ物の輪郭用:モデルの箱の中心を基準に、各辺が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); +static const char *const kCullNames[] = {"back faces (glCullFace(GL_BACK), glFrontFace(GL_CCW))", "off", + "front faces (glCullFace(GL_FRONT))", + "back faces, but glFrontFace(GL_CW) (= wrong winding)"}; +static const char *const kGrassNames[] = {"alpha test (discard)", "blending, straight alpha", + "blending, premultiplied alpha"}; + +// 決まった乱数(どのコンパイラでも同じ数列。std::uniform_real_distributionは標準ライブラリごとに違う) +// A fixed pseudo-random sequence (the same with every compiler; std::uniform_real_distribution differs between +// standard libraries) +static float random01(std::uint32_t &state) { + state = state * 1664525u + 1013904223u; + return static_cast(state >> 8) / 16777216.0f; +} + +// 草の株を置く:ジオラマの地面の上(風車・木・木箱・街灯を避ける)と、手前の床に少し +// Places grass tufts: on the diorama's ground (avoiding the windmill, tree, crates and lamp) and a few on the floor +static std::vector makeGrass() { + std::vector grass; + std::uint32_t seed = 16; + const Vec3 avoid[] = {{-1.4f, 0, -1.2f}, {-2.7f, 0, 1.7f}, {1.5f, 0, -1.4f}, {2.2f, 0, 1.6f}, {0.4f, 0, 2.5f}}; + while (grass.size() < 46) { + float r = 4.2f * std::sqrt(random01(seed)), a = 2.0f * PI * random01(seed); + Vec3 p = {r * std::cos(a), 0.12f, r * std::sin(a)}; + bool ok = true; + for (Vec3 q : avoid) ok = ok && length(Vec3{p.x - q.x, 0, p.z - q.z}) > 1.1f; + if (ok) grass.push_back({p, 2.0f * PI * random01(seed)}); + } + // 手前の床:窓の間と、カメラのすぐ近くに一つ(近くで縁を見るため) / on the floor in front: between the windows, + // and one right in front of the camera (to look at its edges up close) + const Placement front[] = {{{1.5f, 0, 6.2f}, 0.3f}, {{-2.9f, 0, 7.0f}, 1.2f}, {{3.6f, 0, 5.4f}, 2.0f}, + {{1.2f, 0, 8.9f}, 0.7f}, {{-2.6f, 0, 9.6f}, 2.6f}, {{0.6f, 0, 10.7f}, 0.5f}}; + for (const Placement &p : front) grass.push_back(p); + return grass; } int main() { Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 15")) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 16")) 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"); - std::optional rugTexture = Texture2D::load("assets/textures/rug.png"); - if (!phong || !unlit || !depthView || !floorTexture || !rugTexture) return 1; + // 同じ草の画像を二通りに:そのまま(ストレートアルファ)と、乗算済みアルファ + // The same grass image twice: as it is (straight alpha) and premultiplied + std::optional grassStraight = Texture2D::load("assets/textures/grass_blades.png"); + std::optional grassPremultiplied = + Texture2D::load("assets/textures/grass_blades.png", {.premultiplyAlpha = true}); + if (!phong || !floorTexture || !grassStraight || !grassPremultiplied) return 1; + // 草の画像は端まで描かれているので繰り返さない / the grass image reaches its edges: no repeat + grassStraight->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); + grassPremultiplied->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); std::optional scene = Model::load("assets/models/diorama.glb"); std::optional crate = Model::load("assets/models/crate.glb"); - if (!scene || !crate) return 1; + std::optional windowModel = Model::load("assets/models/window.glb"); + if (!scene || !crate || !windowModel) return 1; const unsigned char whitePixel[4] = {255, 255, 255, 255}; Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); @@ -94,28 +122,24 @@ int main() { Quat rotorStart = rotor >= 0 ? scene->nodes[static_cast(rotor)].rotation : Quat{}; Camera fps; - fps.position = {0.0f, 2.4f, 13.0f}; - fps.pitch = radians(-12.0f); + fps.position = {0.0f, 2.1f, 13.0f}; + fps.pitch = radians(-9.0f); OrbitCamera orbit; - orbit.target = {0.0f, 1.2f, 0.0f}; - orbit.distance = 10.0f; - orbit.yaw = radians(30.0f); + orbit.target = {0.0f, 1.0f, 4.0f}; + orbit.distance = 9.0f; + orbit.yaw = radians(20.0f); bool useOrbit = false; - 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; + int viewMode = 0, cullMode = 0, grassMode = 0; + bool night = false, flashlightOn = false, windmillMoving = true, sortTransparent = true, blendDepthWrite = true; 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() && unlit->reload() && depthView->reload()) - printf("シェーダーを読み直した / shaders reloaded\n"); + if (key == GLFW_KEY_R && phong->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); if (key == GLFW_KEY_C) { useOrbit = !useOrbit; @@ -126,50 +150,26 @@ int main() { 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_K) { + cullMode = (cullMode + 1) % 4; + printf("culling: %s\n", kCullNames[cullMode]); } - if (key == GLFW_KEY_X) { - zFix = (zFix + 1) % 3; - printf("z-fighting fix: %s\n", kZFixNames[zFix]); + if (key == GLFW_KEY_O) { + sortTransparent = !sortTransparent; + printf("sort transparent objects: %s\n", sortTransparent ? "on (back to front)" : "off (array order)"); } - 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_B) { + blendDepthWrite = !blendDepthWrite; + printf("transparent objects write depth: %s\n", blendDepthWrite ? "yes" : "no (glDepthMask(GL_FALSE))"); } - 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_G) { + grassMode = (grassMode + 1) % 3; + printf("grass: %s\n", kGrassNames[grassMode]); } if (key == GLFW_KEY_N) night = !night; if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; }; - 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); Material floorMaterial; @@ -177,25 +177,16 @@ int main() { 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; + Mesh tuftMesh = makeCrossedQuads(3); + std::vector grass = makeGrass(); + Material grassMaterial; + grassMaterial.specular = {0.04f, 0.04f, 0.04f}; + grassMaterial.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 - }; + // 裏面のカリング:画面上で時計回りに見える三角形(=裏)を描かない + // Back-face culling: triangles that appear clockwise on screen (= seen from behind) are not drawn + glEnable(GL_CULL_FACE); double lastTime = window.time(); while (!window.shouldClose()) { @@ -231,8 +222,6 @@ int main() { 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; LightSet lights; if (!night) { @@ -248,118 +237,106 @@ int main() { } if (flashlightOn) lights.spots.push_back({.position = viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); - // 深度関数。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 | 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); - } + // カリングの設定 / the culling setup + if (cullMode == 1) glDisable(GL_CULL_FACE); + else glEnable(GL_CULL_FACE); + glCullFace(cullMode == 2 ? GL_FRONT : GL_BACK); + glFrontFace(cullMode == 3 ? GL_CW : GL_CCW); // GL_CCW = 反時計回りが表(既定) / counter-clockwise is the front (default) - // 一つの板(床・敷物)を描く / 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(); + 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); + + // 草の株を一つ描く。両面から見える板なのでカリングを切る / draws one grass tuft. The quads are seen from both + // sides, so culling is turned off + auto drawTuft = [&](const Placement &g) { + Mat4 model = translate(g.position) * rotateY(g.angle) * scale({0.75f, 0.75f, 0.75f}); + phong->set("uModel", model); + phong->set("uNormalMatrix", normalMatrix(model)); + GLboolean culling = glIsEnabled(GL_CULL_FACE); + glDisable(GL_CULL_FACE); + tuftMesh.draw(); + if (culling) glEnable(GL_CULL_FACE); }; - 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); + //------------------------------------------------------------------ + // 1. 不透明な物(とアルファテストの物):順番は自由。深度テストが前後を決める + // 1. Opaque objects (and alpha-tested ones): any order; the depth test sorts them out + //------------------------------------------------------------------ + phong->set("uModel", Mat4::identity()); + phong->set("uNormalMatrix", normalMatrix(Mat4::identity())); + floorMaterial.apply(*phong, white); + floorMesh.draw(); + scene->draw(*phong, Mat4::identity(), white, ModelPass::Opaque); + for (const Placement &c : kCrates) crate->draw(*phong, translate(c.position) * rotateY(c.angle), white, ModelPass::Opaque); + for (const Placement &w : kWindows) + windowModel->draw(*phong, translate(w.position) * rotateY(w.angle), white, ModelPass::Opaque); + if (grassMode == 0) { + // アルファテスト:アルファ < 0.5のピクセルを捨てる。ブレンドではないので並べ替えは要らない + // Alpha test: discard pixels with alpha < 0.5. This is not blending, so no sorting is needed + grassMaterial.diffuseMap = &*grassStraight; + grassMaterial.alphaMode = AlphaMode::Mask; + grassMaterial.apply(*phong, white); + for (const Placement &g : grass) drawTuft(g); } - // クリックした場所のステンシルの値=そこに見えている物の番号 / 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)" : ""); + //------------------------------------------------------------------ + // 2. 半透明の物:不透明な物の後で、カメラから遠い順に / 2. Transparent objects: after the opaque ones, + // farthest from the camera first + //------------------------------------------------------------------ + // 描く物の一覧:カメラからの距離、乗算済みアルファか、描く関数 / the list of things to draw: distance from the + // camera, whether it is premultiplied, and a draw function + struct Transparent { + float distance; + bool premultiplied; + std::function draw; + }; + std::vector transparent; + for (const Placement &w : kWindows) { + Mat4 m = translate(w.position) * rotateY(w.angle); + Vec3 centre = w.position + Vec3{0.0f, 0.8f, 0.0f}; // 窓の真ん中 / the middle of the window + transparent.push_back({length(centre - viewPos), false, [&, m] { + windowModel->draw(*phong, m, white, ModelPass::Transparent, viewPos); + }}); } - - // 輪郭:拡大した物を、ステンシルがその物の番号「ではない」ところだけに一色で描く - // 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)); + if (grassMode != 0) { + grassMaterial.diffuseMap = grassMode == 2 ? &*grassPremultiplied : &*grassStraight; + grassMaterial.alphaMode = AlphaMode::Blend; + for (const Placement &g : grass) { + Vec3 centre = g.position + Vec3{0.0f, 0.35f, 0.0f}; + transparent.push_back({length(centre - viewPos), grassMode == 2, [&, g] { + grassMaterial.apply(*phong, white); // 窓が別のマテリアルを設定したかも / a window may have set another material + drawTuft(g); + }}); } - 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); + if (sortTransparent) + std::stable_sort(transparent.begin(), transparent.end(), + [](const Transparent &a, const Transparent &b) { return a.distance > b.distance; }); + + glEnable(GL_BLEND); + // 結果 = src × srcの係数 + dst × dstの係数(glBlendEquationの既定はGL_FUNC_ADD) + // result = src × src factor + dst × dst factor (glBlendEquation defaults to GL_FUNC_ADD) + glBlendEquation(GL_FUNC_ADD); + if (!blendDepthWrite) glDepthMask(GL_FALSE); // 深度テストはするが、書かない / still depth-test, but do not write + for (const Transparent &t : transparent) { + // ストレートアルファ:色 × α + 後ろ × (1 − α)。乗算済み:色(もう × α済み) + 後ろ × (1 − α)。 + // アルファチャンネル自体は後半の2つの係数で1のまま:既定のフレームバッファが半透明にならないように + // Straight alpha: colour × α + behind × (1 − α). Premultiplied: colour (already × α) + behind × (1 − α). + // The last two factors keep the alpha channel at 1, so the default framebuffer does not turn translucent + if (t.premultiplied) glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + else glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + t.draw(); } + glDepthMask(GL_TRUE); + glDisable(GL_BLEND); window.swapBuffers(); } diff --git a/src/material.cc b/src/material.cc index 3edff0c..4553e35 100644 --- a/src/material.cc +++ b/src/material.cc @@ -7,6 +7,10 @@ void Material::apply(const Shader &shader, const Texture2D &white) const { shader.set("uMaterial.specular", specular); shader.set("uMaterial.emission", emission); shader.set("uMaterial.shininess", shininess); + shader.set("uMaterial.alpha", alpha); + shader.set("uMaterial.alphaMode", static_cast(alphaMode)); + shader.set("uMaterial.alphaCutoff", alphaCutoff); + shader.set("uMaterial.doubleSided", doubleSided ? 1 : 0); // boolのユニフォームはintで設定する / bool uniforms are set as int (diffuseMap ? diffuseMap : &white)->bind(0); (specularMap ? specularMap : &white)->bind(1); (emissionMap ? emissionMap : &white)->bind(2); diff --git a/src/material.hh b/src/material.hh index b2b211d..f32bf54 100644 --- a/src/material.hh +++ b/src/material.hh @@ -5,6 +5,14 @@ #include "shader.hh" #include "texture.hh" +// アルファ(不透明度)の使い方。glTFのalphaModeと同じ。シェーダーでは0/1/2 +// How alpha (opacity) is used. Same as glTF's alphaMode; 0/1/2 in the shader +enum class AlphaMode { + Opaque = 0, // アルファを無視して不透明に描く / ignore alpha, draw opaque + Mask = 1, // alphaCutoff未満のピクセルを捨てる(discard)。草、葉、金網 / discard pixels below alphaCutoff: grass, leaves, fences + Blend = 2, // 後ろの色と混ぜる(ブレンディング)。ガラス、煙 / mix with what is behind (blending): glass, smoke +}; + // Blinn-Phongのマテリアル。色とマップ(テクスチャ)は掛け合わされる。マップがなければ白(=色だけ)。 // A Blinn-Phong material. Each colour is multiplied with its map (texture); no map means white (= the colour alone). struct Material { @@ -13,6 +21,12 @@ struct Material { Vec3 emission = {0.0f, 0.0f, 0.0f}; // 発光の色:光が当たらなくても見える / emission colour: visible even without light float shininess = 32.0f; // 光沢度 / shininess + float alpha = 1.0f; // 不透明度。diffuseMapのアルファと掛ける / opacity, multiplied with diffuseMap's alpha + AlphaMode alphaMode = AlphaMode::Opaque; + float alphaCutoff = 0.5f; // Maskのしきい値 / the Mask threshold + bool doubleSided = false; // 両面:裏面では法線を反転する(カリングはModelが切る) / double-sided: + // the normal is flipped on back faces (Model turns culling off) + const Texture2D *diffuseMap = nullptr; // テクスチャユニット0 / texture unit 0 const Texture2D *specularMap = nullptr; // テクスチャユニット1 / texture unit 1 const Texture2D *emissionMap = nullptr; // テクスチャユニット2 / texture unit 2 diff --git a/src/model.cc b/src/model.cc index cb0cadc..75eb929 100644 --- a/src/model.cc +++ b/src/model.cc @@ -1,5 +1,6 @@ #include "model.hh" +#include #include #include @@ -35,6 +36,13 @@ static Material phongFromPbr(const GltfMaterial &m, float metallicScale, float r p.specular = ((n + 8.0f) / 8.0f) * f0; p.shininess = n; p.emission = m.emissiveStrength * m.emissiveFactor; + // 透明の扱いはglTFのまま(第16章) / alpha handling straight from glTF (chapter 16) + p.alpha = m.baseColorFactor.w; + p.alphaMode = m.alphaMode == GltfAlphaMode::Mask ? AlphaMode::Mask + : m.alphaMode == GltfAlphaMode::Blend ? AlphaMode::Blend + : AlphaMode::Opaque; + p.alphaCutoff = m.alphaCutoff; + p.doubleSided = m.doubleSided; return p; } @@ -256,32 +264,70 @@ 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, true); + std::vector items; + for (int root : roots) collect(root, transform, transform, hierarchy, ModelPass::All, {}, items); + drawItems(items, shader, &white, true); +} + +void Model::draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, ModelPass pass, + Vec3 viewPos) const { + std::vector items; + for (int root : roots) collect(root, transform, transform, true, pass, viewPos, items); + if (pass == ModelPass::Transparent) { + // 遠いものから描く:手前の半透明が、もう描かれた後ろの色と混ざるように + // Draw the farthest first, so each nearer transparent surface mixes with what is already behind it + std::stable_sort(items.begin(), items.end(), + [](const DrawItem &a, const DrawItem &b) { return a.distance > b.distance; }); + } + drawItems(items, shader, &white, 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); + std::vector items; + for (int root : roots) collect(root, transform, transform, true, ModelPass::All, {}, items); + drawItems(items, shader, nullptr, shader.has("uNormalMatrix")); +} + +const Model::MaterialData &Model::materialOf(const Primitive &p) const { + return p.material >= 0 ? materials[static_cast(p.material)] : defaultMaterial; } -void Model::drawNode(int node, const Mat4 &parentWorld, const Mat4 &transform, const Shader &shader, - const Texture2D *white, bool hierarchy, bool normals) const { +void Model::collect(int node, const Mat4 &parentWorld, const Mat4 &transform, bool hierarchy, ModelPass pass, + Vec3 viewPos, std::vector &out) 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); - if (normals) shader.set("uNormalMatrix", normalMatrix(world)); for (const Primitive &p : meshes[static_cast(n.mesh)].primitives) { - 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(); + bool blend = materialOf(p).phong.alphaMode == AlphaMode::Blend; + if ((pass == ModelPass::Opaque && blend) || (pass == ModelPass::Transparent && !blend)) continue; + Vec3 c = 0.5f * (p.boundsMin + p.boundsMax); + Vec4 centre = world * Vec4{c.x, c.y, c.z, 1.0f}; + out.push_back({&p, world, length(Vec3{centre.x, centre.y, centre.z} - viewPos)}); + } + } + for (int child : n.children) collect(child, world, transform, hierarchy, pass, viewPos, out); +} + +void Model::drawItems(const std::vector &items, const Shader &shader, const Texture2D *white, + bool normals) const { + bool culling = glIsEnabled(GL_CULL_FACE); // 呼ぶ側の設定を覚えておく / remember the caller's setting + for (const DrawItem &item : items) { + const Primitive &p = *item.primitive; + const MaterialData &md = materialOf(p); + shader.set("uModel", item.world); + if (normals) shader.set("uNormalMatrix", normalMatrix(item.world)); + if (white) { + 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); } + // 両面のマテリアル(葉、ガラス、帆)は裏からも見えるようにカリングを切る + // Double-sided materials (leaves, glass, sails) must be visible from behind: no culling for them + bool noCull = culling && md.phong.doubleSided; + if (noCull) glDisable(GL_CULL_FACE); + p.mesh.draw(); + if (noCull) glEnable(GL_CULL_FACE); } - for (int child : n.children) drawNode(child, world, transform, shader, white, hierarchy, normals); } diff --git a/src/model.hh b/src/model.hh index d414cd8..4d58138 100644 --- a/src/model.hh +++ b/src/model.hh @@ -12,6 +12,14 @@ #include #include +// どのプリミティブを描くか(マテリアルのalphaModeで分ける) / which primitives to draw (split by the material's alphaMode) +enum class ModelPass { + All, // 全部、ファイルの順に / everything, in file order + Opaque, // OpaqueとMask / Opaque and Mask + Transparent, // Blendだけ、カメラから遠い順(ブレンドの設定は呼ぶ側) / Blend only, farthest from the camera first + // (the caller sets up blending) +}; + // 読み込んだモデル:メッシュ(VAO)、テクスチャ、マテリアル、ノードの階層(RAII、コピー不可・移動可)。 // 描くときは、ノードごとに 親のワールド行列 × 自分のローカル行列 をたどる。 // A loaded model: meshes (VAOs), textures, materials and the node hierarchy (RAII, non-copyable, movable). @@ -50,6 +58,12 @@ 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; + // passのプリミティブだけを描く。Transparentでは、viewPosから各プリミティブの箱の中心までの距離で遠い順に並べる。 + // 両面(doubleSided)のマテリアルは、その間だけフェイスカリングを切って描く。 + // Draws only the primitives of `pass`. Transparent sorts them back to front by the distance from viewPos to the + // centre of each primitive's box. Double-sided materials are drawn with face culling turned off for that draw. + void draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, ModelPass pass, + Vec3 viewPos = {}) const; // 形だけを描く:マテリアルもテクスチャも設定せず、ノードごとにuModelだけ(シェーダーが使っていればuNormalMatrixも)。 // 深度の表示、輪郭、のちの影(第23章)のように、色を使わないパス用。 // Draws the shape only: no materials or textures, just uModel per node (and uNormalMatrix if the shader uses it). @@ -74,9 +88,18 @@ public: size_t textureCount() const { return textures.size(); } private: + // 描くもの一つ:プリミティブとそのワールド行列 / one thing to draw: a primitive and its world matrix + struct DrawItem { + const Primitive *primitive; + Mat4 world; + float distance; // カメラからの距離(Transparentの並べ替え用) / distance from the camera (for sorting) + }; + // ノードの階層をたどってpassのプリミティブを集める / walks the node hierarchy collecting the primitives of `pass` + void collect(int node, const Mat4 &parentWorld, const Mat4 &transform, bool hierarchy, ModelPass pass, + Vec3 viewPos, std::vector &out) const; // 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, bool normals) const; + void drawItems(const std::vector &items, const Shader &shader, const Texture2D *white, bool normals) const; + const MaterialData &materialOf(const Primitive &p) const; const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing std::vector meshes; diff --git a/src/shapes.cc b/src/shapes.cc index cb622a8..f3d35b1 100644 --- a/src/shapes.cc +++ b/src/shapes.cc @@ -69,3 +69,20 @@ Mesh makeSphere(int segments, int rings) { } return Mesh(vertices, indices, kVertex3DLayout); } + +Mesh makeCrossedQuads(int count) { + std::vector vertices; + std::vector indices; + Vec3 up = {0.0f, 1.0f, 0.0f}; + for (int i = 0; i < count; ++i) { + float a = PI * static_cast(i) / static_cast(count); // 0〜180度(板は両面なので) / 0..180° (quads are two-sided) + Vec3 r = {0.5f * std::cos(a), 0.0f, -0.5f * std::sin(a)}; // 板の右半分 / half the quad, to the right + std::uint32_t first = static_cast(vertices.size()); + vertices.push_back({-1.0f * r, up, {0.0f, 0.0f}}); + vertices.push_back({r, up, {1.0f, 0.0f}}); + vertices.push_back({r + up, up, {1.0f, 1.0f}}); + vertices.push_back({up - r, up, {0.0f, 1.0f}}); + indices.insert(indices.end(), {first, first + 1, first + 2, first + 2, first + 3, first}); + } + return Mesh(vertices, indices, kVertex3DLayout); +} diff --git a/src/shapes.hh b/src/shapes.hh index 7281f93..60e41d7 100644 --- a/src/shapes.hh +++ b/src/shapes.hh @@ -18,3 +18,10 @@ Mesh makePlane(float size, float uvRepeat); // A sphere of diameter 1 centred on the origin (a UV sphere). segments = divisions around, rings = from pole to pole. // The normals point outwards from the centre. Counter-clockwise seen from outside, like the cube. Mesh makeSphere(int segments = 32, int rings = 16); + +// 縦の1×1の板をcount枚、Y軸の周りに等間隔で回して重ねたもの(草の株)。原点は下の辺の真ん中、UVのv = 0が下。 +// 法線はすべて上(+Y):草を地面と同じように照らすための定番のごまかし。両面から見えるのでカリングを切って描く。 +// count vertical 1 × 1 quads turned evenly about the Y axis (a tuft of grass). Origin at the middle of the bottom +// edge, v = 0 at the bottom. All normals point up (+Y): the usual trick to light grass like the ground it grows on. +// Seen from both sides, so draw it with face culling off. +Mesh makeCrossedQuads(int count = 3); diff --git a/src/texture.cc b/src/texture.cc index 502aa9d..4d8b98d 100644 --- a/src/texture.cc +++ b/src/texture.cc @@ -42,7 +42,16 @@ Texture2D &Texture2D::operator=(Texture2D &&other) noexcept { Texture2D Texture2D::fromPixels(const unsigned char *rgba, int width, int height, const TextureOptions &options) { int levels = options.mipmaps ? mipLevelCount(width, height) : 1; Texture2D texture(width, height, options.srgb ? GL_SRGB8_ALPHA8 : GL_RGBA8, levels); - texture.upload(rgba); + if (options.premultiplyAlpha) { + // 乗算済みアルファ:色 × アルファ。透明なピクセルの色は(何色でも)0になる + // premultiplied alpha: colour × alpha. Transparent pixels become 0 whatever colour they had + std::vector pm(rgba, rgba + static_cast(width) * static_cast(height) * 4); + for (size_t i = 0; i < pm.size(); i += 4) + for (size_t c = 0; c < 3; ++c) pm[i + c] = static_cast((pm[i + c] * pm[i + 3] + 127) / 255); + texture.upload(pm.data()); + } else { + texture.upload(rgba); + } if (options.mipmaps) texture.generateMipmaps(); return texture; } diff --git a/src/texture.hh b/src/texture.hh index badf6b9..d118af9 100644 --- a/src/texture.hh +++ b/src/texture.hh @@ -12,6 +12,9 @@ struct TextureOptions { bool flipY = true; // 画像は上から、OpenGLのUVは下から / images start at the top, OpenGL UVs at the bottom bool mipmaps = true; // ミップマップを作る / build mipmaps bool srgb = false; // 色の画像はsRGB(正しい扱いは第21章) / colour images are sRGB (handled properly in chapter 21) + // RGBにアルファを掛けてからアップロードする(乗算済みアルファ、第16章)。ミップマップもその値から作られる。 + // Multiply RGB by alpha before uploading (premultiplied alpha, chapter 16). Mipmaps are then built from those values. + bool premultiplyAlpha = false; }; // デコードした画像:RGBA8、上の行から順に / a decoded image: RGBA8, rows from the top