diff --git a/shaders/phong.frag b/shaders/phong.frag index ecafdbe..a5d9a97 100644 --- a/shaders/phong.frag +++ b/shaders/phong.frag @@ -80,6 +80,12 @@ layout(std140, binding = 0) uniform Camera { // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals uniform int uViewMode; +// アルファトゥカバレッジ(第20章):マスクのマテリアルを捨てる代わりに、アルファをMSAAのサンプルの割合にする。 +// C++でglEnable(GL_SAMPLE_ALPHA_TO_COVERAGE)をしているときだけtrueにする +// Alpha to coverage (chapter 20): instead of discarding, mask materials turn alpha into the fraction of MSAA samples +// covered. Set it to true only while glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) is on in C++ +uniform bool uAlphaToCoverage = false; + // C++のAlphaModeと同じ / same as AlphaMode in C++ #define ALPHA_OPAQUE 0 #define ALPHA_MASK 1 @@ -115,10 +121,20 @@ 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; + // アルファが1ピクセルでどれだけ変わるか(分岐の前に:fwidthは隣のピクセルと一緒に計算する) + // How much alpha changes across one pixel (before any branch: fwidth is computed together with the neighbours) + float alphaWidth = fwidth(alpha); + if (uMaterial.alphaMode == ALPHA_MASK && uAlphaToCoverage) { + // しきい値の前後1ピクセルで0→1になるように鋭くする(そのままだとテクスチャのぼけた縁で半透明が広がる) + // Sharpen so that it goes 0 → 1 within one pixel around the threshold (the texture's soft edge would otherwise + // spread a wide translucent band) + alpha = (alpha - uMaterial.alphaCutoff) / max(alphaWidth, 1e-4) + 0.5; + if (alpha <= 0.0) discard; + } else if (uMaterial.alphaMode == ALPHA_MASK && alpha < uMaterial.alphaCutoff) { + // マスク:しきい値未満は捨てる(色も深度も書かない) / mask: discard below the threshold (writes neither colour nor depth) + discard; + } + // ブレンド:完全に透明なら深度も書かないように捨てる / blend: discard fully transparent pixels so they do not write depth if (uMaterial.alphaMode == ALPHA_BLEND && alpha < 1.0 / 255.0) discard; Surface s; @@ -172,6 +188,9 @@ 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; - // 不透明とマスクはアルファ1。ブレンドだけ本当のアルファを出す / opaque and mask output alpha 1; only blend outputs its alpha - out_color = vec4(color, uMaterial.alphaMode == ALPHA_BLEND ? alpha : 1.0); + // 不透明とマスクはアルファ1。ブレンドだけ本当のアルファを出す。アルファトゥカバレッジのときは、このアルファが + // 覆うサンプルの数になる / opaque and mask output alpha 1; only blend outputs its alpha. With alpha to coverage this + // alpha becomes the number of samples covered + bool coverage = uMaterial.alphaMode == ALPHA_MASK && uAlphaToCoverage; + out_color = vec4(color, uMaterial.alphaMode == ALPHA_BLEND || coverage ? clamp(alpha, 0.0, 1.0) : 1.0); } diff --git a/shaders/post.frag b/shaders/post.frag index 54d0622..e226a17 100644 --- a/shaders/post.frag +++ b/shaders/post.frag @@ -1,6 +1,7 @@ #version 460 core -// ポストプロセス:フレームバッファに描いた画像を加工して画面に出す -// Post-processing: take the image drawn into a framebuffer, change it, and put it on the screen +// ポストプロセス:フレームバッファに描いた画像を加工して画面に出す。MSAAなら解決(resolve)した後の画像(第20章) +// Post-processing: take the image drawn into a framebuffer, change it, and put it on the screen. With MSAA this is +// the resolved image (chapter 20) in vec2 vUv; layout(binding = 0) uniform sampler2D uScene; @@ -8,22 +9,63 @@ layout(binding = 0) uniform sampler2D uScene; // 0 = なし / none, 1 = 反転 / invert, 2 = グレースケール / grayscale, 3 = シャープ / sharpen, // 4 = ぼかし / blur, 5 = エッジ検出 / edge detection uniform int uEffect; +uniform bool uFxaa; // FXAA風のアンチエイリアス(第20章) / FXAA-like anti-aliasing (chapter 20) +uniform bool uMagnifier; // 右下に画面の中央を4倍に拡大して見せる / shows the centre of the screen 4× enlarged, bottom right layout(location = 0) out vec4 out_color; +// 明るさ(FXAAは色ではなく明るさの差で輪郭を探す) / brightness (FXAA looks for edges in brightness, not colour) +float luma(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); } + +// FXAA風(Timothy LottesのFXAA 3.11「コンソール版」を簡単にしたもの):斜めの4ピクセルの明るさから輪郭の向きを求め、 +// 輪郭に沿って何点か読んで平均する。MSAAと違って、描き終わった画像だけから作る(深度もサンプルも要らない) +// FXAA-like (a simplified version of Timothy Lottes' FXAA 3.11 "console"): estimate the edge direction from the +// brightness of the four diagonal neighbours, then average a few samples along the edge. Unlike MSAA it only needs +// the finished image (no depth, no samples) +vec3 fxaa(vec2 uv) { + vec2 texel = 1.0 / vec2(textureSize(uScene, 0)); + vec3 rgbM = texture(uScene, uv).rgb; + // OpenGLのUVは上が+y / OpenGL UVs have +y up + float lumaNW = luma(texture(uScene, uv + vec2(-1.0, 1.0) * texel).rgb); + float lumaNE = luma(texture(uScene, uv + vec2(1.0, 1.0) * texel).rgb); + float lumaSW = luma(texture(uScene, uv + vec2(-1.0, -1.0) * texel).rgb); + float lumaSE = luma(texture(uScene, uv + vec2(1.0, -1.0) * texel).rgb); + float lumaM = luma(rgbM); + float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE))); + float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE))); + // 明るさの差が小さければ輪郭ではない:そのまま(ほとんどのピクセルはここで終わる) + // Little contrast: not an edge, keep the pixel (most pixels stop here) + if (lumaMax - lumaMin < max(0.0312, lumaMax * 0.125)) return rgbM; + + // 明るさの勾配に垂直な向き=輪郭に沿った向き / perpendicular to the brightness gradient = along the edge + vec2 dir = vec2((lumaNW + lumaNE) - (lumaSW + lumaSE), (lumaNW + lumaSW) - (lumaNE + lumaSE)); + float reduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 / 8.0), 1.0 / 128.0); + float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + reduce); + dir = clamp(dir * rcpDirMin, vec2(-8.0), vec2(8.0)) * texel; // 最大8ピクセル / at most 8 pixels + + // 輪郭に沿って近い2点と遠い2点 / two near and two far samples along the edge + vec3 rgbA = 0.5 * (texture(uScene, uv + dir * (1.0 / 3.0 - 0.5)).rgb + texture(uScene, uv + dir * (2.0 / 3.0 - 0.5)).rgb); + vec3 rgbB = rgbA * 0.5 + 0.25 * (texture(uScene, uv - dir * 0.5).rgb + texture(uScene, uv + dir * 0.5).rgb); + // 遠い点が輪郭の向こう側だった(明るさが範囲外)なら近い2点だけ / if the far samples crossed the edge (brightness out + // of range), use only the near ones + float lumaB = luma(rgbB); + return (lumaB < lumaMin || lumaB > lumaMax) ? rgbA : rgbB; +} + // 3×3のカーネル(畳み込み):周りの9ピクセルに重みを掛けて足す // A 3×3 kernel (convolution): multiply the 9 surrounding pixels by weights and add them up -vec3 convolve(float k[9]) { +vec3 convolve(vec2 uv, 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 + sum += k[(1 - y) * 3 + (x + 1)] * texture(uScene, uv + vec2(x, y) * texel).rgb; // 上の行から / top row first return sum; } -void main() { - vec3 color = texture(uScene, vUv).rgb; +// UVの位置の最終的な色(効果をかけた後) / the final colour at a UV position (after the effect) +vec3 shade(vec2 uv) { + vec3 color = uFxaa ? fxaa(uv) : texture(uScene, uv).rgb; if (uEffect == 1) { color = 1.0 - color; } else if (uEffect == 2) { @@ -33,18 +75,45 @@ void main() { float k[9] = float[](-1, -1, -1, -1, 9, -1, -1, -1, -1); // 合計1:明るさは変わらない / sums to 1: brightness unchanged - color = convolve(k); + color = convolve(uv, 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); + color = convolve(uv, 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); + color = convolve(uv, k); + } + return color; +} + +void main() { + vec2 uv = vUv; + vec3 frame = vec3(-1.0); // 拡大鏡の枠の色(-1 = 枠ではない) / magnifier frame colour (-1 = not a frame pixel) + if (uMagnifier) { + // 画面の中央の96×54ピクセルを、右下の384×216ピクセルに4倍で(最近傍:1ピクセルが4×4の四角になる) + // The central 96 × 54 pixels, shown 4× in 384 × 216 pixels at the bottom right (nearest: each pixel becomes a + // 4 × 4 block) + vec2 size = vec2(textureSize(uScene, 0)); + vec2 source = vec2(96.0, 54.0); + vec2 inset0 = vec2(size.x - 16.0 - 4.0 * source.x, 16.0); + vec2 local = (gl_FragCoord.xy - inset0) / 4.0; + vec2 source0 = floor(0.5 * (size - source)); + if (all(greaterThanEqual(local, vec2(0.0))) && all(lessThan(local, source))) { + uv = (source0 + floor(local) + 0.5) / size; + } else if (all(greaterThanEqual(local, vec2(-0.75))) && all(lessThan(local, source + 0.75))) { + frame = vec3(1.0); // 拡大部分の白い枠 / white frame around the inset + } + // 拡大している場所の枠(黄色) / a yellow frame around the enlarged region + vec2 p = gl_FragCoord.xy - source0; + if (all(greaterThanEqual(p, vec2(-2.0))) && all(lessThan(p, source + 2.0)) && + !(all(greaterThanEqual(p, vec2(0.0))) && all(lessThan(p, source)))) + frame = vec3(1.0, 0.85, 0.2); } + vec3 color = frame.x >= 0.0 ? frame : shade(uv); // アルファは必ず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/src/framebuffer.cc b/src/framebuffer.cc index cf2abd2..1622f49 100644 --- a/src/framebuffer.cc +++ b/src/framebuffer.cc @@ -10,7 +10,17 @@ Framebuffer::Framebuffer(int width, int height, const FramebufferSpec &s) : w(wi } void Framebuffer::createAttachments() { - if (spec.colorFormat != 0) { + actualSamples = 0; + if (spec.colorFormat != 0 && spec.samples > 0) { + // マルチサンプルの色:ピクセルごとにsamples個の色を持つレンダーバッファ。テクスチャのように読めない + // Multisampled colour: a renderbuffer with `samples` colours per pixel. It cannot be read like a texture + glCreateRenderbuffers(1, &colorSamples); + glNamedRenderbufferStorageMultisample(colorSamples, spec.samples, spec.colorFormat, w, h); + glNamedFramebufferRenderbuffer(fbo, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorSamples); + // ドライバーは要求以上で一番近い数を選ぶ(llvmpipeは4だけ:2を頼んでも4になる) + // The driver picks the nearest supported count at or above the request (llvmpipe has only 4: asking for 2 gives 4) + glGetNamedRenderbufferParameteriv(colorSamples, GL_RENDERBUFFER_SAMPLES, &actualSamples); + } else 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); @@ -24,7 +34,16 @@ void Framebuffer::createAttachments() { } if (spec.depthStencilFormat != 0) { glCreateRenderbuffers(1, &depthStencil); - glNamedRenderbufferStorage(depthStencil, spec.depthStencilFormat, w, h); + // 色と深度のサンプル数は同じでなければならない(違うとフレームバッファが不完全)。要求ではなく、色が実際に + // 貰った数を使う(色が無ければ要求の数) / colour and depth must have the same number of samples (otherwise the + // framebuffer is incomplete): use the count the colour actually got, not the request (the request if no colour) + int depthSamples = actualSamples > 0 ? actualSamples : spec.samples; + if (depthSamples > 0) glNamedRenderbufferStorageMultisample(depthStencil, depthSamples, spec.depthStencilFormat, w, h); + else glNamedRenderbufferStorage(depthStencil, spec.depthStencilFormat, w, h); + // 深度だけのマルチサンプル:本当の数は深度のレンダーバッファに聞く / depth-only multisampling: ask the depth + // renderbuffer for the actual count + if (depthSamples > 0 && actualSamples == 0) + glGetNamedRenderbufferParameteriv(depthStencil, GL_RENDERBUFFER_SAMPLES, &actualSamples); // 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, @@ -35,7 +54,8 @@ void Framebuffer::createAttachments() { void Framebuffer::destroyAttachments() { colorTexture = Texture2D(); // 古いテクスチャを消す / deletes the old texture if (depthStencil) glDeleteRenderbuffers(1, &depthStencil); - depthStencil = 0; + if (colorSamples) glDeleteRenderbuffers(1, &colorSamples); + depthStencil = colorSamples = 0; } bool Framebuffer::resize(int width, int height) { @@ -54,6 +74,13 @@ bool Framebuffer::complete() const { return glCheckNamedFramebufferStatus(fbo, GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; } +void Framebuffer::blitTo(const Framebuffer &target, GLbitfield mask, GLenum filter) const { + // 読む側の四角形 → 書く側の四角形。読む色はglNamedFramebufferReadBuffer(既定はGL_COLOR_ATTACHMENT0) + // source rectangle → destination rectangle. The colour read comes from glNamedFramebufferReadBuffer + // (GL_COLOR_ATTACHMENT0 by default) + glBlitNamedFramebuffer(fbo, target.fbo, 0, 0, w, h, 0, 0, target.w, target.h, mask, filter); +} + void Framebuffer::bind() const { glBindFramebuffer(GL_FRAMEBUFFER, fbo); glViewport(0, 0, w, h); // ビューポートはフレームバッファごとではない:毎回設定する / the viewport is not per framebuffer @@ -71,7 +98,8 @@ Framebuffer::~Framebuffer() { 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) {} + colorSamples(std::exchange(other.colorSamples, 0)), colorTexture(std::move(other.colorTexture)), w(other.w), + h(other.h), actualSamples(other.actualSamples), spec(other.spec) {} Framebuffer &Framebuffer::operator=(Framebuffer &&other) noexcept { if (this != &other) { @@ -79,9 +107,11 @@ Framebuffer &Framebuffer::operator=(Framebuffer &&other) noexcept { if (fbo) glDeleteFramebuffers(1, &fbo); fbo = std::exchange(other.fbo, 0); depthStencil = std::exchange(other.depthStencil, 0); + colorSamples = std::exchange(other.colorSamples, 0); colorTexture = std::move(other.colorTexture); w = other.w; h = other.h; + actualSamples = other.actualSamples; spec = other.spec; } return *this; diff --git a/src/framebuffer.hh b/src/framebuffer.hh index 7ef98c9..6f5e8c0 100644 --- a/src/framebuffer.hh +++ b/src/framebuffer.hh @@ -13,10 +13,19 @@ struct FramebufferSpec { // 深度・ステンシルのレンダーバッファの形式(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; + // マルチサンプル(MSAA、第20章):1ピクセルあたりのサンプル数。0 = 普通のフレームバッファ(色はテクスチャ)。 + // 1以上なら色も深度もマルチサンプルのレンダーバッファになり、サンプラーでは読めない:blitToで普通の + // フレームバッファに解決(resolve)してから使う。ドライバーは要求以上の数を選ぶことがある(samples()で確かめる)。 + // Multisampling (MSAA, chapter 20): samples per pixel. 0 = an ordinary framebuffer (the colour is a texture). + // 1 or more makes both colour and depth multisampled renderbuffers, which cannot be sampled: resolve them into + // an ordinary framebuffer with blitTo first. The driver may pick more samples than requested (check samples()). + int samples = 0; }; // フレームバッファオブジェクト(FBO):色のテクスチャ+深度・ステンシルのレンダーバッファ(RAII、コピー不可・移動可)。DSAで作る。 +// マルチサンプル(spec.samples > 0)なら色もレンダーバッファ。 // A framebuffer object (FBO): a colour texture + a depth-stencil renderbuffer (RAII, non-copyable, movable), built with DSA. +// When multisampled (spec.samples > 0) the colour is a renderbuffer too. class Framebuffer { public: Framebuffer() = default; @@ -38,13 +47,26 @@ public: // 画面(既定のフレームバッファ、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 + // 描いた結果。シェーダーでサンプリングできる(マルチサンプルなら空:id() == 0) + // The result; can be sampled in a shader (empty for a multisampled framebuffer: id() == 0) const Texture2D &color() const { return colorTexture; } Texture2D &color() { return colorTexture; } + // 別のフレームバッファへコピーする(glBlitNamedFramebuffer)。マルチサンプルから普通のフレームバッファへなら + // サンプルの平均を取る:これがMSAAの「解決(resolve)」。大きさが違えば拡大・縮小する(filter = GL_LINEARなど。 + // マルチサンプルからは同じ大きさだけ)。mask = GL_COLOR_BUFFER_BIT、GL_DEPTH_BUFFER_BIT…(深度はGL_NEARESTだけ) + // Copies into another framebuffer (glBlitNamedFramebuffer). From a multisampled into an ordinary framebuffer it + // averages the samples: this is the MSAA "resolve". Different sizes are scaled (filter = GL_LINEAR etc.; only + // the same size is allowed from a multisampled source). mask = GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT... (depth + // only with GL_NEAREST) + void blitTo(const Framebuffer &target, GLbitfield mask = GL_COLOR_BUFFER_BIT, GLenum filter = GL_NEAREST) const; + GLuint id() const { return fbo; } int width() const { return w; } int height() const { return h; } + // 本当のサンプル数(0 = マルチサンプルでない)。ドライバーが選んだ数で、要求と違うことがある + // The actual number of samples (0 = not multisampled): what the driver chose, which may differ from the request + int samples() const { return actualSamples; } bool complete() const; // glCheckNamedFramebufferStatus == GL_FRAMEBUFFER_COMPLETE private: @@ -52,9 +74,11 @@ private: void destroyAttachments(); GLuint fbo = 0; - GLuint depthStencil = 0; // レンダーバッファ / renderbuffer + GLuint depthStencil = 0; // レンダーバッファ / renderbuffer + GLuint colorSamples = 0; // マルチサンプルの色のレンダーバッファ(第20章) / multisampled colour renderbuffer (chapter 20) Texture2D colorTexture; int w = 0, h = 0; + int actualSamples = 0; FramebufferSpec spec; }; diff --git a/src/main.cc b/src/main.cc index d8848e8..d8192b7 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,5 +1,5 @@ -// 第19章:ユニフォームバッファとインスタンシング -// Chapter 19: uniform buffers and instancing +// 第20章:アンチエイリアス +// Chapter 20: anti-aliasing // // 操作 / Controls: // WASD 前後左右に移動 / move forward, back, left, right @@ -7,25 +7,30 @@ // Shift 速く動く / move faster // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit // ホイール / wheel ズーム / zoom -// I 岩:インスタンシング(描画呼び出し1回) ⇔ 一つずつ(岩の数だけ呼び出し) -// rocks: instancing (one draw call) ⇔ one by one (one draw call per rock) -// = / - 岩の数を倍に・半分に(250〜64000) / double / halve the number of rocks (250..64000) +// M アンチエイリアス:なし → MSAA 2× → 4× → 8× → SSAA 2×2(GL_MAX_SAMPLESを超える数は飛ばす) +// anti-aliasing: off → MSAA 2× → 4× → 8× → SSAA 2×2 (counts above GL_MAX_SAMPLES are skipped) +// X FXAA風の後処理のオン・オフ / FXAA-like post-process on / off +// T 草のアルファトゥカバレッジのオン・オフ(MSAAのときだけ効く) / alpha to coverage for the grass on / off +// (only works with MSAA) +// Z 拡大鏡(画面の中央を4倍で右下に) / magnifier (the centre of the screen 4× at the bottom right) // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 // effect: none / invert / grayscale / sharpen / blur / edge detection // 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 and the ring of rocks +// P 風車を止める・動かす / pause / resume the windmill // Tab カーソルのキャプチャ切り替え / toggle cursor capture // R シェーダーを読み直す / reload the shaders // Esc 終了 / quit // -// 時間はウィンドウのタイトルと標準出力に出る(60フレームごと) / timings go to the window title and stdout (every 60 frames) +// ./build/game --direct [samples] フレームバッファを使わず、GLFW_SAMPLESでマルチサンプルにした画面に直接描く +// (後処理なし)。本物のGPUで画面のMSAAを試す用 +// draws straight into a screen made multisampled with GLFW_SAMPLES, without our +// framebuffers (no post-processing). For trying screen MSAA on a real GPU #include "camera.hh" #include "cubemap.hh" #include "framebuffer.hh" -#include "gpu_timer.hh" #include "lights.hh" #include "material.hh" #include "mathx.hh" @@ -37,62 +42,43 @@ #include "uniforms.hh" #include "window.hh" -#include #include #include #include +#include +#include #include #include +// 物を置く場所:位置(底の中心)とY軸周りの回転 / where things go: position (bottom centre) and yaw struct Placement { Vec3 position; float angle; }; +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}, +}; + +// アンチエイリアスの方法 / the anti-aliasing methods +struct AaMode { + const char *name; + int samples; // MSAAのサンプル数(0 = MSAAなし) / MSAA samples (0 = no MSAA) + bool ssaa; // 縦横2倍で描いて縮める(スーパーサンプリング) / draw at twice the width and height, then shrink +}; +static const AaMode kAaModes[] = { + {"off", 0, false}, {"MSAA 2x", 2, false}, {"MSAA 4x", 4, false}, {"MSAA 8x", 8, false}, {"SSAA 2x2", 0, true}, +}; + static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; -constexpr int kMaxRocks = 64000; -constexpr float kOrbitSpeed = 0.25f; // 半径8 mでの公転の角速度(ラジアン毎秒) / orbital angular speed at radius 8 m (rad/s) - static float random01(std::uint32_t &state) { state = state * 1664525u + 1013904223u; return static_cast(state >> 8) / 16777216.0f; } -// 公転の角度:内側ほど速い(ケプラー:角速度 ∝ 半径^-1.5)。phong_instanced.vertと同じ式 -// The orbit angle: inner rocks move faster (Kepler: angular speed ∝ radius^-1.5). Same formula as phong_instanced.vert -static float orbitAngle(const Mat4 &instance, float time) { - float radius = std::sqrt(instance.c[3].x * instance.c[3].x + instance.c[3].z * instance.c[3].z); - return time * kOrbitSpeed * std::pow(8.0f / radius, 1.5f); -} - -// 浮島の周りの岩の環。位置・回転・大きさ・色は決まった乱数で / the ring of rocks around the floating island; -// position, rotation, size and colour from a fixed pseudo-random sequence -static std::vector makeRing() { - std::vector rocks; - rocks.reserve(kMaxRocks); - std::uint32_t seed = 19; - for (int i = 0; i < kMaxRocks; ++i) { - // 半径:二つの乱数の平均で真ん中を濃く / radius: the mean of two randoms makes the middle denser - float radius = 8.0f + 6.5f * 0.5f * (random01(seed) + random01(seed)); - float angle = 2.0f * PI * random01(seed); - float height = 2.0f + 0.45f * (random01(seed) + random01(seed) + random01(seed) - 1.5f) / 1.5f; - float u = random01(seed); - float size = 0.08f + 0.4f * u * u * u; // 小さい岩が多い / mostly small rocks - Vec3 axis = normalize(Vec3{random01(seed) - 0.5f, random01(seed) - 0.5f, random01(seed) - 0.5f}); - float spin = 2.0f * PI * random01(seed); - float shade = 0.7f + 0.45f * random01(seed); - float warm = 0.12f * (random01(seed) - 0.5f); - InstanceData d; - d.model = translate({radius * std::cos(angle), height, radius * std::sin(angle)}) * rotate(axis, spin) * - scale({size, size, size}); - d.color = {shade + warm, shade, shade - warm}; - rocks.push_back(d); - } - return rocks; -} - static std::vector makeGrass() { std::vector grass; std::uint32_t seed = 16; @@ -104,32 +90,93 @@ 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)}); } + const Placement front[] = {{{1.5f, 0, 6.2f}, 0.3f}, {{-4.0f, 0, 7.6f}, 1.2f}, {{3.9f, 0, 5.4f}, 2.0f}, + {{1.4f, 0, 8.9f}, 0.7f}, {{-1.6f, 0, 8.6f}, 2.6f}, {{0.2f, 0, 10.0f}, 1.9f}}; + for (const Placement &p : front) grass.push_back(p); return grass; } -int main() { +// aからbへの細い角材(makeCubeを伸ばす)。電線や柵に / a thin beam from a to b (a stretched makeCube), for wires +// and fences +static Mat4 beam(Vec3 a, Vec3 b, float thickness) { + Vec3 d = b - a; + float len = length(d); + Vec3 z = d / len; + Vec3 x = normalize(cross(std::fabs(z.y) > 0.99f ? Vec3{1, 0, 0} : Vec3{0, 1, 0}, z)); + Vec3 y = cross(z, x); + Mat4 m; + m.c[0] = {thickness * x.x, thickness * x.y, thickness * x.z, 0.0f}; + m.c[1] = {thickness * y.x, thickness * y.y, thickness * y.z, 0.0f}; + m.c[2] = {len * z.x, len * z.y, len * z.z, 0.0f}; + Vec3 mid = 0.5f * (a + b); + m.c[3] = {mid.x, mid.y, mid.z, 1.0f}; + return m; +} + +// 柵と電柱と電線:細いものほどエイリアスが目立つ / a fence, poles and wires: the thinner, the worse the aliasing +static std::vector makeFence() { + std::vector fence; + Vec3 a = {-5.4f, 0.0f, 5.0f}, b = {-1.9f, 0.0f, 8.3f}; + Vec3 along = normalize(b - a); + int pickets = static_cast(length(b - a) / 0.2f); + for (int i = 0; i <= pickets; ++i) { + Vec3 p = a + (0.2f * static_cast(i)) * along; + fence.push_back(beam(p, p + Vec3{0.0f, 0.95f, 0.0f}, 0.05f)); + } + for (float y : {0.3f, 0.75f}) fence.push_back(beam(a + Vec3{0, y, 0}, b + Vec3{0, y, 0}, 0.04f)); + return fence; +} + +static std::vector makeWires() { + std::vector wires; + const Vec3 poles[] = {{-9.0f, 0.0f, -3.0f}, {-3.0f, 0.0f, -5.5f}, {4.0f, 0.0f, -5.0f}, {10.0f, 0.0f, -2.0f}}; + for (Vec3 p : poles) { + wires.push_back(beam(p, p + Vec3{0.0f, 4.2f, 0.0f}, 0.12f)); // 電柱 / pole + wires.push_back(beam(p + Vec3{-0.7f, 4.0f, 0.0f}, p + Vec3{0.7f, 4.0f, 0.0f}, 0.08f)); // 腕木 / cross-arm + } + // 電柱の間に3本ずつ、少したるませて(8本の直線でつなぐ) / three wires between neighbouring poles, sagging a little + // (each made of 8 straight pieces) + for (size_t i = 0; i + 1 < std::size(poles); ++i) { + for (float side : {-0.6f, 0.0f, 0.6f}) { + Vec3 from = poles[i] + Vec3{side, 4.04f, 0.0f}, to = poles[i + 1] + Vec3{side, 4.04f, 0.0f}; + for (int k = 0; k < 8; ++k) { + float t0 = static_cast(k) / 8.0f, t1 = static_cast(k + 1) / 8.0f; + Vec3 p0 = lerp(from, to, t0) - Vec3{0.0f, 1.6f * t0 * (1.0f - t0), 0.0f}; + Vec3 p1 = lerp(from, to, t1) - Vec3{0.0f, 1.6f * t1 * (1.0f - t1), 0.0f}; + wires.push_back(beam(p0, p1, 0.015f)); + } + } + } + return wires; +} + +int main(int argc, char **argv) { + // --direct [samples]:画面のMSAA(GLFW_SAMPLES)を試す / try screen MSAA (GLFW_SAMPLES) + bool direct = argc > 1 && std::strcmp(argv[1], "--direct") == 0; + int windowSamples = direct ? (argc > 2 ? std::atoi(argv[2]) : 4) : 0; + Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 19")) return 1; + // 普段は画面をマルチサンプルにしない:場面は自分のマルチサンプルのフレームバッファに描き、解決してから後処理する。 + // 画面がマルチサンプルでも、全画面の三角形一つには意味がない + // Normally the screen is not multisampled: the scene goes into our own multisampled framebuffer, which is + // resolved and then post-processed. A multisampled screen would be wasted on one fullscreen triangle + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 20", windowSamples)) return 1; std::optional phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); - // インスタンシング用:頂点シェーダーだけ違う / for instancing: only the vertex shader differs - std::optional rocksShader = Shader::load("shaders/phong_instanced.vert", "shaders/phong.frag"); std::optional skybox = Shader::load("shaders/skybox.vert", "shaders/skybox.frag"); std::optional post = Shader::load("shaders/post.vert", "shaders/post.frag"); std::optional sky = Cubemap::loadDirectory("assets/textures/sky"); + std::optional floorTexture = Texture2D::load("assets/textures/floor.png"); std::optional grassTexture = Texture2D::load("assets/textures/grass_blades.png"); - if (!phong || !rocksShader || !skybox || !post || !sky || !grassTexture) return 1; + if (!phong || !skybox || !post || !sky || !floorTexture || !grassTexture) return 1; grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); - - // C++の構造体とGLSLのブロックの大きさが合うか確かめる(std140の詰め物を間違えると違う) - // Check that the C++ structs and the GLSL blocks have the same size (they differ if the std140 padding is wrong) - for (const Shader *s : {&*phong, &*rocksShader, &*skybox}) + for (const Shader *s : {&*phong, &*skybox}) if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock))) return 1; std::optional scene = Model::load("assets/models/diorama.glb"); - std::optional rock = Model::load("assets/models/rock.glb"); - if (!scene || !rock) return 1; + std::optional crate = Model::load("assets/models/crate.glb"); + if (!scene || !crate) return 1; const unsigned char whitePixel[4] = {255, 255, 255, 255}; Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); @@ -138,51 +185,68 @@ int main() { int lanternNode = scene->findNode("LanternLight"); Quat rotorStart = rotor >= 0 ? scene->nodes[static_cast(rotor)].rotation : Quat{}; - // ユニフォームバッファ:作ったときに結合点0と1に繋がる。シェーダーはlayout(binding = …)で同じ番号を読む - // Uniform buffers: attached to binding points 0 and 1 when created. The shaders read the same numbers through - // layout(binding = ...) UniformBuffer cameraUbo(kCameraBinding); UniformBuffer lightsUbo(kLightsBinding); - // インスタンスのバッファ:全部の岩を一度だけアップロード。描く数を変えても作り直さない(先頭からcount個使う) - // The instance buffer: every rock uploaded once. Changing the count does not rebuild it (the first `count` are used) - std::vector ring = makeRing(); - Buffer instanceBuffer(ring.data(), static_cast(ring.size() * sizeof(InstanceData))); - rock->setInstanceBuffer(instanceBuffer, sizeof(InstanceData), kInstanceLayout); + // このGPUで使えるサンプル数の上限(llvmpipeは4) / the most samples this GPU supports (4 on llvmpipe) + GLint maxSamples = 0; + glGetIntegerv(GL_MAX_SAMPLES, &maxSamples); + printf("GL_MAX_SAMPLES = %d\n", maxSamples); + std::vector aaModes; + for (const AaMode &m : kAaModes) + if (m.samples <= maxSamples) aaModes.push_back(m); + size_t aaMode = 0; + for (size_t i = 0; i < aaModes.size(); ++i) + if (aaModes[i].samples == 4) aaMode = i; // 既定はMSAA 4× / MSAA 4× by default + + // 場面を描くフレームバッファ:MSAAなら msaaFbo に描いて sceneFbo に解決する。SSAAなら縦横2倍の ssaaFbo に描いて + // 縮める。なしなら sceneFbo に直接。後処理はいつも sceneFbo の色のテクスチャを読む + // The framebuffers the scene is drawn into: with MSAA into msaaFbo, resolved into sceneFbo; with SSAA into the + // double-size ssaaFbo, then shrunk; without AA straight into sceneFbo. Post-processing always reads sceneFbo's + // colour texture + Framebuffer sceneFbo(window.width(), window.height()); + Framebuffer msaaFbo, ssaaFbo; + auto createAaFramebuffer = [&] { + const AaMode &m = aaModes[aaMode]; + msaaFbo = Framebuffer(); + ssaaFbo = Framebuffer(); + if (m.samples > 0) { + msaaFbo = Framebuffer(window.width(), window.height(), {.samples = m.samples}); + printf("anti-aliasing: %s (requested %d samples, got %d)\n", m.name, m.samples, msaaFbo.samples()); + } else if (m.ssaa) { + ssaaFbo = Framebuffer(2 * window.width(), 2 * window.height()); + printf("anti-aliasing: %s (%d x %d)\n", m.name, ssaaFbo.width(), ssaaFbo.height()); + } else { + printf("anti-aliasing: %s\n", m.name); + } + }; + if (!direct) createAaFramebuffer(); + window.onResize = [&](int width, int height) { + sceneFbo.resize(width, height); + if (msaaFbo.id()) msaaFbo.resize(width, height); // サンプル数はそのまま / keeps the sample count + if (ssaaFbo.id()) ssaaFbo.resize(2 * width, 2 * height); + }; + glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); Camera fps; - fps.position = {0.0f, 6.5f, 24.0f}; - fps.pitch = radians(-12.0f); + fps.position = {0.0f, 2.0f, 12.5f}; + fps.pitch = radians(-4.0f); OrbitCamera orbit; - orbit.target = {0.0f, 1.5f, 0.0f}; - orbit.distance = 24.0f; + orbit.target = {0.0f, 1.0f, 2.0f}; + orbit.distance = 11.0f; orbit.yaw = radians(20.0f); - bool useOrbit = false, instanced = true; - int viewMode = 0, effect = 0, rockCount = 4000; - bool night = false, flashlightOn = false, moving = true; - float animTime = 0.0f; + bool useOrbit = false, fxaa = false, alphaToCoverage = false, magnifier = false; + int viewMode = 0, effect = 0; + bool night = false, flashlightOn = false, windmillMoving = true; + float windmillTime = 0.0f; window.setCursorCaptured(true); - Framebuffer sceneFbo(window.width(), window.height()); - if (!sceneFbo.complete()) return 1; - window.onResize = [&](int width, int height) { sceneFbo.resize(width, height); }; - glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); - - // 時間の集計(60フレームの平均) / timing statistics (averaged over 60 frames) - GpuTimer gpuTimer; - double cpuSum = 0.0, gpuSum = 0.0; - int cpuFrames = 0, gpuFrames = 0; - auto resetStats = [&] { - cpuSum = gpuSum = 0.0; - cpuFrames = gpuFrames = 0; - }; - 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() && rocksShader->reload() && skybox->reload() && post->reload()) + if (key == GLFW_KEY_R && phong->reload() && skybox->reload() && post->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); if (key == GLFW_KEY_C) { @@ -198,22 +262,31 @@ int main() { effect = key - GLFW_KEY_1; printf("effect: %s\n", kEffectNames[effect]); } - if (key == GLFW_KEY_I) { - instanced = !instanced; - resetStats(); - printf("rocks: %s\n", instanced ? "instanced" : "one draw call per rock"); + if (key == GLFW_KEY_M && !direct) { + aaMode = (aaMode + 1) % aaModes.size(); + createAaFramebuffer(); + } + if (key == GLFW_KEY_X) { + fxaa = !fxaa; + printf("FXAA: %s\n", fxaa ? "on" : "off"); } - if (key == GLFW_KEY_EQUAL && rockCount < kMaxRocks) rockCount *= 2; - if (key == GLFW_KEY_MINUS && rockCount > 250) rockCount /= 2; - if (key == GLFW_KEY_EQUAL || key == GLFW_KEY_MINUS) { - resetStats(); - printf("rocks: %d\n", rockCount); + if (key == GLFW_KEY_T) { + alphaToCoverage = !alphaToCoverage; + printf("alpha to coverage: %s\n", alphaToCoverage ? "on" : "off"); } + if (key == GLFW_KEY_Z) magnifier = !magnifier; if (key == GLFW_KEY_N) night = !night; if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; - if (key == GLFW_KEY_P) moving = !moving; + if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; }; + Mesh floorMesh = makePlane(160.0f, 40.0f); + Mesh cubeMesh = makeCube(); + Material floorMaterial; + floorMaterial.diffuseMap = &*floorTexture; + floorMaterial.specular = {0.15f, 0.15f, 0.15f}; + floorMaterial.shininess = 16.0f; + Mesh tuftMesh = makeCrossedQuads(3); std::vector grass = makeGrass(); Material grassMaterial; @@ -221,12 +294,75 @@ int main() { grassMaterial.alphaMode = AlphaMode::Mask; grassMaterial.specular = {0.04f, 0.04f, 0.04f}; grassMaterial.shininess = 8.0f; - Mesh cubeMesh = makeCube(); - FullscreenTriangle fullscreen; + std::vector fence = makeFence(); + std::vector wires = makeWires(); + Material woodMaterial; + woodMaterial.diffuse = {0.42f, 0.3f, 0.2f}; + woodMaterial.specular = {0.05f, 0.05f, 0.05f}; + woodMaterial.shininess = 8.0f; + Material wireMaterial; + wireMaterial.diffuse = {0.04f, 0.04f, 0.045f}; + wireMaterial.specular = {0.3f, 0.3f, 0.3f}; + wireMaterial.shininess = 32.0f; + + FullscreenTriangle fullscreen; glEnable(GL_CULL_FACE); - int frame = 0; + // 場面全体を今のフレームバッファに描く(ビューポートは呼ぶ側) / draws the whole scene into the current framebuffer + // (the caller sets the viewport) + Vec3 environmentTint; + auto drawScene = [&] { + glEnable(GL_DEPTH_TEST); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + sky->bind(3); + + phong->use(); + phong->set("uViewMode", viewMode); + phong->set("uEnvironmentTint", environmentTint); + 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 std::vector *list : {&fence, &wires}) { + (list == &fence ? woodMaterial : wireMaterial).apply(*phong, white); + for (const Mat4 &m : *list) { + phong->set("uModel", m); + phong->set("uNormalMatrix", normalMatrix(m)); + cubeMesh.draw(); + } + } + + // 草:アルファトゥカバレッジならdiscardの代わりにサンプルの一部だけを覆う(MSAAのときだけ意味がある) + // Grass: with alpha to coverage, a fragment covers only some of the samples instead of being discarded (only + // meaningful with MSAA) + bool coverage = alphaToCoverage && !direct && aaModes[aaMode].samples > 0; + if (direct) coverage = alphaToCoverage && window.samples() > 0; + if (coverage) glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); + phong->set("uAlphaToCoverage", coverage ? 1 : 0); + grassMaterial.apply(*phong, white); + glDisable(GL_CULL_FACE); + 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); + phong->set("uAlphaToCoverage", 0); + glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); + + glDepthFunc(GL_LEQUAL); + glDisable(GL_CULL_FACE); + skybox->use(); + skybox->set("uEnvironmentTint", environmentTint); + cubeMesh.draw(); + glEnable(GL_CULL_FACE); + glDepthFunc(GL_LESS); + }; + double lastTime = window.time(); while (!window.shouldClose()) { double now = window.time(); @@ -252,19 +388,17 @@ int main() { fps.move(dir, dt); } - if (moving) animTime += dt; + if (windmillMoving) windmillTime += dt; if (rotor >= 0) scene->nodes[static_cast(rotor)].rotation = - Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * animTime) * rotorStart; + Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; - // カメラのブロック:フレームに一度書けば、全部のシェーダーが読む(シェーダーごとのset()は要らない) - // The camera block: written once per frame, read by every shader (no per-shader set() any more) - float aspect = static_cast(sceneFbo.width()) / static_cast(sceneFbo.height()); + float aspect = window.aspect(); CameraBlock camera; camera.view = useOrbit ? orbit.view() : fps.view(); camera.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect); camera.viewPos = useOrbit ? orbit.position() : fps.position; - camera.time = animTime; + camera.time = windmillTime; cameraUbo.update(camera); Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); @@ -282,98 +416,52 @@ int main() { } if (flashlightOn) lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); - lightsUbo.update(lights.toBlock()); // 光のブロックも一度だけ / the lights block, also just once - Vec3 environmentTint = night ? Vec3{0.05f, 0.06f, 0.11f} : Vec3{1.0f, 1.0f, 1.0f}; + lightsUbo.update(lights.toBlock()); + environmentTint = night ? Vec3{0.05f, 0.06f, 0.11f} : Vec3{1.0f, 1.0f, 1.0f}; + + if (direct) { + // 画面に直接(GLFW_SAMPLESのMSAAは描くときに自動、解決はglfwSwapBuffersの中) / straight to the screen (the + // GLFW_SAMPLES MSAA happens while drawing; the resolve happens inside glfwSwapBuffers) + Framebuffer::bindDefault(window.width(), window.height()); + drawScene(); + window.swapBuffers(); + continue; + } //------------------------------------------------------------------ - // 1. 場面をフレームバッファに / 1. the scene into the framebuffer + // 1. 場面を描き、1サンプルの sceneFbo にまとめる / 1. draw the scene and bring it into the single-sample sceneFbo //------------------------------------------------------------------ - sceneFbo.bind(); - glEnable(GL_DEPTH_TEST); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); - sky->bind(3); - - // ビュー・射影・光はもう設定しない:ブロックから来る / no view, projection or lights to set: they come from the blocks - phong->use(); - phong->set("uViewMode", viewMode); - phong->set("uEnvironmentTint", environmentTint); - scene->draw(*phong, Mat4::identity(), white, ModelPass::Opaque); - // 浮島の下の岩:同じ岩のモデルを平たく大きく / the rock under the floating island: the same rock model, wide and flat - rock->draw(*phong, translate({0.0f, -1.7f, 0.0f}) * scale({10.0f, 3.4f, 10.0f}), white); - grassMaterial.apply(*phong, white); - glDisable(GL_CULL_FACE); - 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 ring of rocks: only this part is timed - gpuTimer.begin(); - auto cpuStart = std::chrono::steady_clock::now(); - if (instanced) { - // インスタンシング:プリミティブ1つにつき描画呼び出し1回。公転はシェーダーがuTimeで計算する - // Instancing: one draw call per primitive. The shader computes the orbit from uTime - rocksShader->use(); - rocksShader->set("uViewMode", viewMode); - rocksShader->set("uEnvironmentTint", environmentTint); - rocksShader->set("uOrbitSpeed", kOrbitSpeed); - rock->drawInstanced(*rocksShader, white, rockCount); + const AaMode &aa = aaModes[aaMode]; + if (aa.samples > 0) { + // MSAA:マルチサンプルのフレームバッファに描き、ブリットで解決(各ピクセルのサンプルを平均) + // MSAA: draw into the multisampled framebuffer, then resolve it with a blit (average each pixel's samples) + msaaFbo.bind(); + drawScene(); + msaaFbo.blitTo(sceneFbo); + } else if (aa.ssaa) { + // SSAA:縦横2倍(4倍のピクセル)で描き、GL_LINEARで半分に縮める=2×2ピクセルの平均 + // SSAA: draw at twice the width and height (4× the pixels) and shrink with GL_LINEAR = the mean of 2 × 2 pixels + ssaaFbo.bind(); + drawScene(); + ssaaFbo.blitTo(sceneFbo, GL_COLOR_BUFFER_BIT, GL_LINEAR); } else { - // 一つずつ:岩ごとにuModel・uNormalMatrix・マテリアル・uTintを設定して描画呼び出し。公転はCPUで計算 - // One by one: per rock set uModel, uNormalMatrix, the material and uTint, then a draw call. The orbit is - // computed on the CPU - phong->use(); - for (int i = 0; i < rockCount; ++i) { - const InstanceData &d = ring[static_cast(i)]; - phong->set("uTint", d.color); - rock->draw(*phong, rotateY(orbitAngle(d.model, animTime)) * d.model, white); - } - phong->set("uTint", Vec3{1.0f, 1.0f, 1.0f}); + sceneFbo.bind(); + drawScene(); } - double cpuMs = std::chrono::duration(std::chrono::steady_clock::now() - cpuStart).count(); - gpuTimer.end(); - - // 空(第18章) / the sky (chapter 18) - glDepthFunc(GL_LEQUAL); - glDisable(GL_CULL_FACE); - skybox->use(); - skybox->set("uEnvironmentTint", environmentTint); - cubeMesh.draw(); - glEnable(GL_CULL_FACE); - glDepthFunc(GL_LESS); //------------------------------------------------------------------ - // 2. 画面へ(第17章) / 2. to the screen (chapter 17) + // 2. 画面へ:後処理は解決した後の画像に / 2. to the screen: post-processing works on the resolved image //------------------------------------------------------------------ Framebuffer::bindDefault(window.width(), window.height()); glDisable(GL_DEPTH_TEST); post->use(); post->set("uEffect", effect); post->set("uFlipX", 0); + post->set("uFxaa", fxaa ? 1 : 0); + post->set("uMagnifier", magnifier ? 1 : 0); sceneFbo.color().bind(0); fullscreen.draw(); - // 時間の集計:60フレームごとにタイトルと標準出力へ / timing: every 60 frames to the title and stdout - cpuSum += cpuMs; - ++cpuFrames; - if (std::optional gpu = gpuTimer.latestMs()) { - gpuSum += *gpu; - ++gpuFrames; - } - if (++frame % 60 == 0) { - int calls = instanced ? 1 : rockCount; - char text[256]; - snprintf(text, sizeof text, "OpenGL Tutorial - Chapter 19 | %d rocks, %s: %d draw call%s, CPU %.2f ms, GPU %.2f ms", - rockCount, instanced ? "instanced" : "one by one", calls, calls == 1 ? "" : "s", cpuSum / cpuFrames, - gpuFrames > 0 ? gpuSum / gpuFrames : 0.0); - window.setTitle(text); - printf("%s\n", text + 31); // 「OpenGL Tutorial - Chapter 19 | 」の後ろ / after "OpenGL Tutorial - Chapter 19 | " - resetStats(); - } - window.swapBuffers(); } return 0; diff --git a/src/window.cc b/src/window.cc index dc1dc50..6cf0772 100644 --- a/src/window.cc +++ b/src/window.cc @@ -16,7 +16,7 @@ Window::~Window() { if (glfwStarted) glfwTerminate(); } -bool Window::create(int width, int height, const char *title) { +bool Window::create(int width, int height, const char *title, int samples) { #ifdef _WIN32 // コンソールの出力をUTF-8にする(日本語のメッセージが文字化けしない様に) // switch the console output to UTF-8 (so the Japanese messages are not garbled) @@ -34,6 +34,9 @@ bool Window::create(int width, int height, const char *title) { glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE); + // 画面のマルチサンプル(MSAA)。0 = なし。ドライバーが無視することもある(後でGL_SAMPLESを確かめる) + // Multisampling (MSAA) for the screen. 0 = none. Drivers may ignore it (GL_SAMPLES is checked below) + glfwWindowHint(GLFW_SAMPLES, samples); glfwWindow = glfwCreateWindow(width, height, title, nullptr, nullptr); if (!glfwWindow) { @@ -58,6 +61,10 @@ bool Window::create(int width, int height, const char *title) { enableGlDebugOutput(); + // 実際に付いたサンプル数(GL_MULTISAMPLEは既定で有効) / the samples actually given (GL_MULTISAMPLE is on by default) + glGetIntegerv(GL_SAMPLES, &fbSamples); + if (samples > 0) printf("画面のサンプル数 / screen samples: %d (requested %d)\n", fbSamples, samples); + glfwGetFramebufferSize(glfwWindow, &fbWidth, &fbHeight); glViewport(0, 0, fbWidth, fbHeight); glfwGetCursorPos(glfwWindow, &cursorX, &cursorY); diff --git a/src/window.hh b/src/window.hh index d75aa00..72825b8 100644 --- a/src/window.hh +++ b/src/window.hh @@ -23,8 +23,11 @@ public: Window &operator=(const Window &) = delete; // ウィンドウとOpenGL 4.6コアのデバッグコンテキストを作る。失敗したらfalse。 + // samples > 0なら画面(既定のフレームバッファ)をマルチサンプルにする(GLFW_SAMPLES、第20章)。後から変えられない。 // Creates the window and an OpenGL 4.6 core debug context. Returns false on failure. - bool create(int width, int height, const char *title); + // samples > 0 makes the screen (the default framebuffer) multisampled (GLFW_SAMPLES, chapter 20); this cannot + // change later. + bool create(int width, int height, const char *title, int samples = 0); bool shouldClose() const; void close(); @@ -42,6 +45,8 @@ public: int width() const { return fbWidth; } int height() const { return fbHeight; } float aspect() const; // 幅÷高さ / width ÷ height + // 画面の本当のサンプル数(GL_SAMPLES、0 = マルチサンプルでない) / the screen's actual sample count (GL_SAMPLES, 0 = none) + int samples() const { return fbSamples; } // ポーリング:今押されているか / polling: is it held down right now? bool keyDown(int key) const; @@ -77,6 +82,7 @@ private: GLFWwindow *glfwWindow = nullptr; bool glfwStarted = false; int fbWidth = 0, fbHeight = 0; + int fbSamples = 0; double cursorX = 0.0, cursorY = 0.0; Vec2 frameMouseDelta; float frameScroll = 0.0f;