diff --git a/CMakeLists.txt b/CMakeLists.txt index bc1b480..749e8e9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -40,7 +40,8 @@ add_executable(game src/lights.cc src/json.cc src/gltf.cc - src/model.cc) + src/model.cc + src/framebuffer.cc) target_include_directories(game PRIVATE src external/stb external/linalg) target_link_libraries(game PRIVATE glad stb_image glfw) diff --git a/shaders/post.frag b/shaders/post.frag new file mode 100644 index 0000000..54d0622 --- /dev/null +++ b/shaders/post.frag @@ -0,0 +1,50 @@ +#version 460 core +// ポストプロセス:フレームバッファに描いた画像を加工して画面に出す +// Post-processing: take the image drawn into a framebuffer, change it, and put it on the screen +in vec2 vUv; + +layout(binding = 0) uniform sampler2D uScene; + +// 0 = なし / none, 1 = 反転 / invert, 2 = グレースケール / grayscale, 3 = シャープ / sharpen, +// 4 = ぼかし / blur, 5 = エッジ検出 / edge detection +uniform int uEffect; + +layout(location = 0) out vec4 out_color; + +// 3×3のカーネル(畳み込み):周りの9ピクセルに重みを掛けて足す +// A 3×3 kernel (convolution): multiply the 9 surrounding pixels by weights and add them up +vec3 convolve(float k[9]) { + vec2 texel = 1.0 / vec2(textureSize(uScene, 0)); // 1ピクセルのUVでの大きさ / one pixel in UV units + vec3 sum = vec3(0.0); + for (int y = -1; y <= 1; ++y) + for (int x = -1; x <= 1; ++x) + sum += k[(1 - y) * 3 + (x + 1)] * texture(uScene, vUv + vec2(x, y) * texel).rgb; // 上の行から / top row first + return sum; +} + +void main() { + vec3 color = texture(uScene, vUv).rgb; + if (uEffect == 1) { + color = 1.0 - color; + } else if (uEffect == 2) { + // 目は緑に一番敏感:輝度の重み(Rec. 709) / the eye is most sensitive to green: luminance weights (Rec. 709) + color = vec3(dot(color, vec3(0.2126, 0.7152, 0.0722))); + } else if (uEffect == 3) { + float k[9] = float[](-1, -1, -1, + -1, 9, -1, + -1, -1, -1); // 合計1:明るさは変わらない / sums to 1: brightness unchanged + color = convolve(k); + } else if (uEffect == 4) { + float k[9] = float[](1.0 / 16, 2.0 / 16, 1.0 / 16, + 2.0 / 16, 4.0 / 16, 2.0 / 16, + 1.0 / 16, 2.0 / 16, 1.0 / 16); // ガウスに近い / close to a Gaussian + color = convolve(k); + } else if (uEffect == 5) { + float k[9] = float[](1, 1, 1, + 1, -8, 1, + 1, 1, 1); // 合計0:平らなところは黒、変化があるところだけ明るい / sums to 0: flat areas black + color = convolve(k); + } + // アルファは必ず1(画面が半透明にならないように) / alpha is always 1 (so the window never turns translucent) + out_color = vec4(clamp(color, 0.0, 1.0), 1.0); +} diff --git a/shaders/post.vert b/shaders/post.vert new file mode 100644 index 0000000..9d1ad58 --- /dev/null +++ b/shaders/post.vert @@ -0,0 +1,18 @@ +#version 460 core +// 画面全体を覆う三角形一つ。頂点バッファなし:gl_VertexID(0, 1, 2)から位置を作る +// One triangle that covers the whole screen. No vertex buffer: the positions come from gl_VertexID (0, 1, 2) +// 頂点は (-1,-1)、(3,-1)、(-1,3):画面(-1〜1の四角)はこの三角形の中にすっぽり入り、はみ出た部分はクリッピングで消える。 +// 四角形(三角形2つ)と違い、対角線の継ぎ目がない +// The vertices are (-1,-1), (3,-1), (-1,3): the screen (the -1..1 square) fits inside this triangle and the rest is +// clipped away. Unlike a quad (two triangles) there is no seam along the diagonal + +uniform bool uFlipX; // 左右反転(バックミラー) / mirror left-right (the rear-view mirror) + +out vec2 vUv; + +void main() { + vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2); // (0,0), (2,0), (0,2) + vUv = p; // 画面の中では0〜1 / 0..1 inside the screen + if (uFlipX) vUv.x = 1.0 - vUv.x; + gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0); // (-1,-1), (3,-1), (-1,3) +} diff --git a/src/framebuffer.cc b/src/framebuffer.cc new file mode 100644 index 0000000..cf2abd2 --- /dev/null +++ b/src/framebuffer.cc @@ -0,0 +1,113 @@ +#include "framebuffer.hh" + +#include +#include + +Framebuffer::Framebuffer(int width, int height, const FramebufferSpec &s) : w(width), h(height), spec(s) { + glCreateFramebuffers(1, &fbo); + createAttachments(); + if (!complete()) fprintf(stderr, "フレームバッファが不完全 / incomplete framebuffer (%d × %d)\n", w, h); +} + +void Framebuffer::createAttachments() { + if (spec.colorFormat != 0) { + // 色:ミップマップなしのテクスチャ。端の外を読まないようにCLAMP_TO_EDGE(ぼかしのカーネルが端で反対側を拾わない) + // Colour: a texture without mipmaps. CLAMP_TO_EDGE so blur kernels at the border do not pick up the opposite side + colorTexture = Texture2D(w, h, spec.colorFormat, 1); + colorTexture.setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); + colorTexture.setFilter(GL_LINEAR, GL_LINEAR); + glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0, colorTexture.id(), 0); // 0 = ミップマップの段 / mip level + } else { + // 色を描かない(例:影の深度だけ、第23章) / no colour drawn (e.g. shadow depth only, chapter 23) + glNamedFramebufferDrawBuffer(fbo, GL_NONE); + glNamedFramebufferReadBuffer(fbo, GL_NONE); + } + if (spec.depthStencilFormat != 0) { + glCreateRenderbuffers(1, &depthStencil); + glNamedRenderbufferStorage(depthStencil, spec.depthStencilFormat, w, h); + // GL_DEPTH24_STENCIL8なら深度とステンシルの両方に付ける / GL_DEPTH24_STENCIL8 attaches as both depth and stencil + bool stencil = spec.depthStencilFormat == GL_DEPTH24_STENCIL8 || spec.depthStencilFormat == GL_DEPTH32F_STENCIL8; + glNamedFramebufferRenderbuffer(fbo, stencil ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, + depthStencil); + } +} + +void Framebuffer::destroyAttachments() { + colorTexture = Texture2D(); // 古いテクスチャを消す / deletes the old texture + if (depthStencil) glDeleteRenderbuffers(1, &depthStencil); + depthStencil = 0; +} + +bool Framebuffer::resize(int width, int height) { + if (width <= 0 || height <= 0) return false; // 最小化中 / minimised + if (width == w && height == h) return complete(); + w = width; + h = height; + destroyAttachments(); + createAttachments(); // FBOそのものはそのまま、付け直すだけ / the FBO itself stays; only re-attach + bool ok = complete(); + if (!ok) fprintf(stderr, "フレームバッファが不完全 / incomplete framebuffer (%d × %d)\n", w, h); + return ok; +} + +bool Framebuffer::complete() const { + return glCheckNamedFramebufferStatus(fbo, GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; +} + +void Framebuffer::bind() const { + glBindFramebuffer(GL_FRAMEBUFFER, fbo); + glViewport(0, 0, w, h); // ビューポートはフレームバッファごとではない:毎回設定する / the viewport is not per framebuffer +} + +void Framebuffer::bindDefault(int width, int height) { + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glViewport(0, 0, width, height); +} + +Framebuffer::~Framebuffer() { + destroyAttachments(); + if (fbo) glDeleteFramebuffers(1, &fbo); +} + +Framebuffer::Framebuffer(Framebuffer &&other) noexcept + : fbo(std::exchange(other.fbo, 0)), depthStencil(std::exchange(other.depthStencil, 0)), + colorTexture(std::move(other.colorTexture)), w(other.w), h(other.h), spec(other.spec) {} + +Framebuffer &Framebuffer::operator=(Framebuffer &&other) noexcept { + if (this != &other) { + destroyAttachments(); + if (fbo) glDeleteFramebuffers(1, &fbo); + fbo = std::exchange(other.fbo, 0); + depthStencil = std::exchange(other.depthStencil, 0); + colorTexture = std::move(other.colorTexture); + w = other.w; + h = other.h; + spec = other.spec; + } + return *this; +} + +//------------------------------------------ +// FullscreenTriangle +//------------------------------------------ + +FullscreenTriangle::FullscreenTriangle() { glCreateVertexArrays(1, &vao); } + +FullscreenTriangle::~FullscreenTriangle() { + if (vao) glDeleteVertexArrays(1, &vao); +} + +FullscreenTriangle::FullscreenTriangle(FullscreenTriangle &&other) noexcept : vao(std::exchange(other.vao, 0)) {} + +FullscreenTriangle &FullscreenTriangle::operator=(FullscreenTriangle &&other) noexcept { + if (this != &other) { + if (vao) glDeleteVertexArrays(1, &vao); + vao = std::exchange(other.vao, 0); + } + return *this; +} + +void FullscreenTriangle::draw() const { + glBindVertexArray(vao); + glDrawArrays(GL_TRIANGLES, 0, 3); +} diff --git a/src/framebuffer.hh b/src/framebuffer.hh new file mode 100644 index 0000000..7ef98c9 --- /dev/null +++ b/src/framebuffer.hh @@ -0,0 +1,79 @@ +// フレームバッファ:画面の代わりにテクスチャへ描く / framebuffers: draw into a texture instead of the screen +#pragma once + +#include "texture.hh" + +#include + +// フレームバッファに何を付けるか / what to attach to a framebuffer +struct FramebufferSpec { + // 色のテクスチャの形式(0 = 色なし)。第21章のHDRではGL_RGBA16F + // The colour texture's format (0 = no colour). GL_RGBA16F for HDR in chapter 21 + GLenum colorFormat = GL_RGBA8; + // 深度・ステンシルのレンダーバッファの形式(0 = なし)。サンプラーで読まないのでテクスチャでなくて良い + // The depth-stencil renderbuffer's format (0 = none). It is never sampled, so it need not be a texture + GLenum depthStencilFormat = GL_DEPTH24_STENCIL8; +}; + +// フレームバッファオブジェクト(FBO):色のテクスチャ+深度・ステンシルのレンダーバッファ(RAII、コピー不可・移動可)。DSAで作る。 +// A framebuffer object (FBO): a colour texture + a depth-stencil renderbuffer (RAII, non-copyable, movable), built with DSA. +class Framebuffer { +public: + Framebuffer() = default; + Framebuffer(int width, int height, const FramebufferSpec &spec = {}); + ~Framebuffer(); + Framebuffer(const Framebuffer &) = delete; + Framebuffer &operator=(const Framebuffer &) = delete; + Framebuffer(Framebuffer &&other) noexcept; + Framebuffer &operator=(Framebuffer &&other) noexcept; + + // 大きさを変える(ウィンドウのリサイズ)。テクスチャの大きさは変えられないので、付けたものを作り直す。 + // 同じ大きさなら何もしない。完成していればtrue。 + // Changes the size (window resize). A texture's size cannot change, so the attachments are re-created. + // Does nothing for the same size. Returns true if the framebuffer is complete. + bool resize(int width, int height); + + // これに描く:glBindFramebuffer+ビューポートを全体に / draw into this: glBindFramebuffer + a full viewport + void bind() const; + // 画面(既定のフレームバッファ、0番)に戻す / back to the screen (the default framebuffer, number 0) + static void bindDefault(int width, int height); + + // 描いた結果。シェーダーでサンプリングできる / the result; can be sampled in a shader + const Texture2D &color() const { return colorTexture; } + Texture2D &color() { return colorTexture; } + + GLuint id() const { return fbo; } + int width() const { return w; } + int height() const { return h; } + bool complete() const; // glCheckNamedFramebufferStatus == GL_FRAMEBUFFER_COMPLETE + +private: + void createAttachments(); + void destroyAttachments(); + + GLuint fbo = 0; + GLuint depthStencil = 0; // レンダーバッファ / renderbuffer + Texture2D colorTexture; + int w = 0, h = 0; + FramebufferSpec spec; +}; + +// 画面全体を覆う三角形(ポストプロセス用)。頂点はシェーダーがgl_VertexIDから作る(shaders/post.vert)。 +// 頂点属性のない空のVAOを持つだけ:コアプロファイルでは描くときにVAOが必ず要る(RAII、コピー不可・移動可)。 +// A triangle covering the whole screen (for post-processing). The shader makes the vertices from gl_VertexID +// (shaders/post.vert). It only owns an empty VAO without attributes: the core profile always needs a VAO bound +// to draw (RAII, non-copyable, movable). +class FullscreenTriangle { +public: + FullscreenTriangle(); + ~FullscreenTriangle(); + FullscreenTriangle(const FullscreenTriangle &) = delete; + FullscreenTriangle &operator=(const FullscreenTriangle &) = delete; + FullscreenTriangle(FullscreenTriangle &&other) noexcept; + FullscreenTriangle &operator=(FullscreenTriangle &&other) noexcept; + + void draw() const; // glDrawArrays(GL_TRIANGLES, 0, 3) + +private: + GLuint vao = 0; +}; diff --git a/src/main.cc b/src/main.cc index c2c6d86..1e8e3c4 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,5 +1,5 @@ -// 第16章:ブレンディングとフェイスカリング -// Chapter 16: blending and face culling +// 第17章:フレームバッファとポストプロセス +// Chapter 17: framebuffers and post-processing // // 操作 / Controls: // WASD 前後左右に移動 / move forward, back, left, right @@ -7,12 +7,10 @@ // Shift 速く動く / move faster // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit // ホイール / wheel ズーム / zoom -// 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) +// 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 +// effect: none / invert / grayscale / sharpen / blur / edge detection +// M バックミラーのオン・オフ / rear-view mirror on / off +// L 低解像度(1/4、GL_NEAREST)⇔ 普通 / low resolution (1/4, GL_NEAREST) ⇔ normal // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals // N 昼 ⇔ 夜 / day ⇔ night @@ -22,6 +20,7 @@ // R シェーダーを読み直す / reload the shaders // Esc 終了 / quit #include "camera.hh" +#include "framebuffer.hh" #include "lights.hh" #include "material.hh" #include "mathx.hh" @@ -36,7 +35,6 @@ #include #include #include -#include #include #include @@ -46,34 +44,26 @@ struct Placement { float angle; }; +// 最後の3つはカメラの後ろ(バックミラーに映る) / the last three are behind the camera (seen in the rear-view mirror) 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}, + {{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}, {{-1.6f, 0.0f, 17.0f}, 0.3f}, + {{-0.5f, 0.0f, 17.6f}, -0.2f}, {{-1.1f, 1.0f, 17.3f}, 0.6f}, }; -// 窓はカメラから見て重なるように並べる。配列は手前の窓から:並べ替えないと順番が逆になる -// 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}, + {{1.8f, 0.0f, 16.4f}, 2.9f}, // カメラの後ろ / behind the camera }; static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; -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 const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; + 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; @@ -85,29 +75,29 @@ static std::vector makeGrass() { 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}}; + 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}, + {{0.4f, 0, 16.6f}, 1.0f}, {{-2.4f, 0, 16.2f}, 2.2f}}; for (const Placement &p : front) grass.push_back(p); return grass; } +// 一つのカメラから見た場面を描くのに必要なもの / what is needed to draw the scene from one camera +struct View { + Mat4 view, proj; + Vec3 position; +}; + int main() { Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 16")) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 17")) return 1; std::optional phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); + std::optional post = Shader::load("shaders/post.vert", "shaders/post.frag"); std::optional floorTexture = Texture2D::load("assets/textures/floor.png"); - // 同じ草の画像を二通りに:そのまま(ストレートアルファ)と、乗算済みアルファ - // 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 grassTexture = Texture2D::load("assets/textures/grass_blades.png"); + if (!phong || !post || !floorTexture || !grassTexture) return 1; + grassTexture->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"); @@ -131,15 +121,32 @@ int main() { orbit.yaw = radians(20.0f); bool useOrbit = false; - int viewMode = 0, cullMode = 0, grassMode = 0; - bool night = false, flashlightOn = false, windmillMoving = true, sortTransparent = true, blendDepthWrite = true; + int viewMode = 0, effect = 0; + bool night = false, flashlightOn = false, windmillMoving = true, mirrorOn = true, lowRes = false; float windmillTime = 0.0f; window.setCursorCaptured(true); + // 場面を描くフレームバッファ(ウィンドウと同じ大きさ、低解像度なら1/4)とバックミラー用 + // The framebuffer the scene is drawn into (window size, or 1/4 in low-resolution mode) and one for the mirror + auto sceneSize = [&](int size) { return std::max(1, lowRes ? size / 4 : size); }; + Framebuffer sceneFbo(sceneSize(window.width()), sceneSize(window.height())); + const int mirrorWidth = 480, mirrorHeight = 150; + Framebuffer mirrorFbo(mirrorWidth, mirrorHeight); + if (!sceneFbo.complete() || !mirrorFbo.complete()) return 1; + + // 低解像度ではGL_NEARESTで拡大:ピクセルがはっきり見える / low resolution is magnified with GL_NEAREST: crisp pixels + auto resizeScene = [&] { + sceneFbo.resize(sceneSize(window.width()), sceneSize(window.height())); + GLenum filter = lowRes ? GL_NEAREST : GL_LINEAR; + sceneFbo.color().setFilter(filter, filter); + }; + // ウィンドウの大きさが変わったら、フレームバッファも作り直す / when the window size changes, so does the framebuffer + window.onResize = [&](int, int) { resizeScene(); }; + 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() && post->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); if (key == GLFW_KEY_C) { useOrbit = !useOrbit; @@ -150,21 +157,15 @@ int main() { viewMode = (viewMode + 1) % 6; printf("view: %s\n", kViewModeNames[viewMode]); } - if (key == GLFW_KEY_K) { - cullMode = (cullMode + 1) % 4; - printf("culling: %s\n", kCullNames[cullMode]); - } - 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_B) { - blendDepthWrite = !blendDepthWrite; - printf("transparent objects write depth: %s\n", blendDepthWrite ? "yes" : "no (glDepthMask(GL_FALSE))"); + if (key >= GLFW_KEY_1 && key <= GLFW_KEY_6) { + effect = key - GLFW_KEY_1; + printf("effect: %s\n", kEffectNames[effect]); } - if (key == GLFW_KEY_G) { - grassMode = (grassMode + 1) % 3; - printf("grass: %s\n", kGrassNames[grassMode]); + if (key == GLFW_KEY_M) mirrorOn = !mirrorOn; + if (key == GLFW_KEY_L) { + lowRes = !lowRes; + resizeScene(); + printf("scene framebuffer: %d x %d\n", sceneFbo.width(), sceneFbo.height()); } if (key == GLFW_KEY_N) night = !night; if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; @@ -180,14 +181,62 @@ int main() { Mesh tuftMesh = makeCrossedQuads(3); std::vector grass = makeGrass(); Material grassMaterial; + grassMaterial.diffuseMap = &*grassTexture; + grassMaterial.alphaMode = AlphaMode::Mask; grassMaterial.specular = {0.04f, 0.04f, 0.04f}; grassMaterial.shininess = 8.0f; - glEnable(GL_DEPTH_TEST); - // 裏面のカリング:画面上で時計回りに見える三角形(=裏)を描かない - // Back-face culling: triangles that appear clockwise on screen (= seen from behind) are not drawn + // 全画面の三角形(中身は空のVAOだけ) / the fullscreen triangle (just an empty VAO inside) + FullscreenTriangle fullscreen; + glEnable(GL_CULL_FACE); + LightSet lights; + + // 場面全体を今のフレームバッファに描く(第16章の描き方:不透明 → 半透明を遠い順) + // Draws the whole scene into the current framebuffer (chapter 16's order: opaque, then transparent far to near) + auto drawScene = [&](const View &v) { + glEnable(GL_DEPTH_TEST); + 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); + + phong->use(); + phong->set("uView", v.view); + phong->set("uProj", v.proj); + phong->set("uViewPos", v.position); + phong->set("uViewMode", viewMode); + lights.apply(*phong); + + 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); + grassMaterial.apply(*phong, white); + glDisable(GL_CULL_FACE); // 草は両面 / grass is two-sided + for (const Placement &g : grass) { + Mat4 model = translate(g.position) * rotateY(g.angle) * scale({0.75f, 0.75f, 0.75f}); + phong->set("uModel", model); + phong->set("uNormalMatrix", normalMatrix(model)); + tuftMesh.draw(); + } + glEnable(GL_CULL_FACE); + + // 窓のガラス:遠い順 / the window glass, far to near + std::vector> glass; + for (const Placement &w : kWindows) + glass.push_back({length(w.position + Vec3{0.0f, 0.8f, 0.0f} - v.position), translate(w.position) * rotateY(w.angle)}); + std::sort(glass.begin(), glass.end(), [](const auto &a, const auto &b) { return a.first > b.first; }); + glEnable(GL_BLEND); + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + for (const auto &g : glass) windowModel->draw(*phong, g.second, white, ModelPass::Transparent, v.position); + glDisable(GL_BLEND); + }; + double lastTime = window.time(); while (!window.shouldClose()) { double now = window.time(); @@ -218,12 +267,16 @@ int main() { scene->nodes[static_cast(rotor)].rotation = Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; - Mat4 view = useOrbit ? orbit.view() : fps.view(); - Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect()); - Vec3 viewPos = useOrbit ? orbit.position() : fps.position; + // アスペクト比は描き込むフレームバッファのもの(ウィンドウとは限らない) + // The aspect ratio is that of the framebuffer drawn into (not necessarily the window) + float aspect = static_cast(sceneFbo.width()) / static_cast(sceneFbo.height()); + View main; + main.view = useOrbit ? orbit.view() : fps.view(); + main.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect); + main.position = useOrbit ? orbit.position() : fps.position; Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); - LightSet lights; + lights = LightSet{}; 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}}; @@ -235,108 +288,55 @@ int main() { 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}}); - - // カリングの設定 / 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) - - 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); - }; - - //------------------------------------------------------------------ - // 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); - } - - //------------------------------------------------------------------ - // 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); - }}); - } - 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); - }}); - } + if (flashlightOn) + lights.spots.push_back({.position = main.position, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); + + // 1. 場面をフレームバッファに描く / 1. draw the scene into the framebuffer + sceneFbo.bind(); + drawScene(main); + + // 2. バックミラー:後ろ向きのカメラで、もう一度場面を描く(別のフレームバッファへ) + // 2. The rear-view mirror: draw the scene again with a camera looking backwards (into another framebuffer) + if (mirrorOn) { + Vec3 forward = viewDir; + forward.y = 0.0f; + forward = length(forward) > 0.0f ? normalize(forward) : Vec3{0.0f, 0.0f, -1.0f}; + View rear; + rear.position = main.position; + // 水平な後ろ向きから少し下を見る / backwards and horizontal, tilted down a little + rear.view = lookAt(main.position, main.position - forward + Vec3{0.0f, -0.3f, 0.0f}, {0.0f, 1.0f, 0.0f}); + rear.proj = perspectiveGl(radians(30.0f), static_cast(mirrorWidth) / static_cast(mirrorHeight), 0.1f, 100.0f); + mirrorFbo.bind(); + drawScene(rear); } - 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(); + // 3. 画面へ:全画面の三角形でフレームバッファのテクスチャを貼り、効果をかける + // 3. To the screen: a fullscreen triangle samples the framebuffer's texture and applies the effect + Framebuffer::bindDefault(window.width(), window.height()); + glDisable(GL_DEPTH_TEST); // 三角形一つだけ:深度は要らない / a single triangle: no depth needed + post->use(); + post->set("uEffect", effect); + post->set("uFlipX", 0); + sceneFbo.color().bind(0); + fullscreen.draw(); + + // 4. バックミラー:画面の上の小さな長方形に。枠はシザーテストでクリアして描く。左右は反転(鏡)、効果はなし + // 4. The mirror: a small rectangle at the top of the screen. The frame is a scissored clear. Flipped left-right + // (it is a mirror), no effect + if (mirrorOn) { + int x = (window.width() - mirrorWidth) / 2, y = window.height() - mirrorHeight - 16; + glEnable(GL_SCISSOR_TEST); + glScissor(x - 4, y - 4, mirrorWidth + 8, mirrorHeight + 8); + glClearColor(0.08f, 0.08f, 0.09f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + glDisable(GL_SCISSOR_TEST); + glViewport(x, y, mirrorWidth, mirrorHeight); // 全画面の三角形がこの長方形だけを覆う / the fullscreen triangle now covers only this + post->set("uEffect", 0); + post->set("uFlipX", 1); + mirrorFbo.color().bind(0); + fullscreen.draw(); + glViewport(0, 0, window.width(), window.height()); } - glDepthMask(GL_TRUE); - glDisable(GL_BLEND); window.swapBuffers(); }