diff --git a/CMakeLists.txt b/CMakeLists.txt index d4814ec..226a0e6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,58 +19,63 @@ endif() add_library(glad STATIC external/glad/src/glad.c) target_include_directories(glad PUBLIC external/glad/include) -# stb_image:実装は src/stb_image_impl.cc だけ。他人のコードなので警告フラグなしの別ライブラリにする -# stb_image: the implementation lives in src/stb_image_impl.cc only. It is someone else's code, -# so it is a separate library built without our warning flags -add_library(stb_image STATIC src/stb_image_impl.cc) -target_include_directories(stb_image PUBLIC external/stb) - -add_executable(game - src/main.cc - src/window.cc - src/gl_debug.cc - src/buffer.cc - src/mesh.cc - src/file_util.cc - src/shader.cc - src/texture.cc - src/shapes.cc - src/camera.cc - src/material.cc - src/lights.cc - src/json.cc - src/gltf.cc - src/model.cc - src/framebuffer.cc - src/cubemap.cc - src/gpu_timer.cc - src/tangents.cc - src/ibl.cc - src/pbr_material.cc) -target_include_directories(game PRIVATE src external/stb external/linalg) -target_link_libraries(game PRIVATE glad stb_image glfw) - -# glTF/GLBの中身を表示する道具。GPUもウィンドウも使わないのでGLFWとGLADは要らない -# A tool that prints what is inside glTF/GLB files. It uses no GPU and no window, so no GLFW and no GLAD -add_executable(gltf_dump - src/gltf_dump.cc - src/gltf.cc - src/json.cc - src/file_util.cc) -target_include_directories(gltf_dump PRIVATE src external/linalg) - -# 警告を有効にする(自分のコードだけ) / enable warnings (our own code only) -foreach(target game gltf_dump) +# 警告を有効にする(自分のコードだけ)。エンジンとゲームの全ターゲットで使う +# Enables warnings (our own code only). Used by the engine and every game target +function(enable_warnings target) if(MSVC) target_compile_options(${target} PRIVATE /W4 /utf-8) else() target_compile_options(${target} PRIVATE -Wall -Wextra) endif() -endforeach() +endfunction() + +# シェーダーとアセットは作業ディレクトリ(= プロジェクトのルート)からの相対パスで読む: +# engine/shaders/…(エンジン)、assets/…(共有)、games/<名前>/…(各ゲーム)。 +# Visual Studioでは各実行ファイルの作業ディレクトリをルートにする。Unixではルートから ./build/game を実行。 +# Shaders and assets are loaded relative to the working directory (= the project root): +# engine/shaders/... (the engine), assets/... (shared), games//... (each game). +# Visual Studio: every executable's working directory is the root. Unix: run ./build/game from the root. +function(set_working_directory target) + set_property(TARGET ${target} PROPERTY VS_DEBUGGER_WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}") +endfunction() + +# エンジン:第1〜24章のクラス+2Dの道具(静的ライブラリ) / the engine: the classes of chapters 1-24 + the 2D toolkit +# (a static library) +add_subdirectory(engine) -# シェーダーとアセットは作業ディレクトリからの相対パスで読む。 -# Visual Studioではプロジェクトのルートを作業ディレクトリにする。Unixではルートから ./build/game を実行。 -# Shaders and assets are loaded relative to the working directory. -# Visual Studio: use the project root as the working directory. Unix: run ./build/game from the root. -set_property(TARGET game PROPERTY VS_DEBUGGER_WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") +# この章のデモ / this chapter's demo +add_executable(game demo/main.cc) +target_link_libraries(game PRIVATE engine) +enable_warnings(game) +set_working_directory(game) set_property(DIRECTORY PROPERTY VS_STARTUP_PROJECT game) + +# glTF/GLBの中身を表示する道具。GPUもウィンドウも使わないのでエンジン全体はリンクしない(GLFWもGLADも要らない) +# A tool that prints what is inside glTF/GLB files. It uses no GPU and no window, so it does not link the whole +# engine (no GLFW, no GLAD) +add_executable(gltf_dump + tools/gltf_dump.cc + engine/src/gltf.cc + engine/src/json.cc + engine/src/file_util.cc) +target_include_directories(gltf_dump PRIVATE engine/include external/linalg) +enable_warnings(gltf_dump) + +# 第24章の3D場面をエンジンで描く確認用プログラム(影・PBR・IBL・ブルーム)。TPS(第36〜39章)の土台 +# A check that draws the chapter 24 3D scene through the engine (shadows, PBR, IBL, bloom). The basis of the TPS +# (chapters 36-39) +option(BUILD_SCENE3D "Build the 3D check program scene3d" ON) +if(BUILD_SCENE3D) + add_executable(scene3d tests/scene3d/main.cc) + target_link_libraries(scene3d PRIVATE engine) + enable_warnings(scene3d) + set_working_directory(scene3d) +endif() + +# ゲーム(第27章から):games/<名前>/CMakeLists.txt があれば加える。各ゲームは自分の実行ファイル +# The games (from chapter 27): added when games//CMakeLists.txt exists. Each game is its own executable +foreach(name invaders fighter rpg tps) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/games/${name}/CMakeLists.txt") + add_subdirectory(games/${name}) + endif() +endforeach() diff --git a/README.md b/README.md index 4644691..1023352 100644 --- a/README.md +++ b/README.md @@ -41,11 +41,29 @@ build\Debug\game.exe または `build\opengl_tutorial.sln` を開いてF5(作業ディレクトリはプロジェクトのルートに設定済み)。 Or open `build\opengl_tutorial.sln` and press F5 (the working directory is already set to the project root). -glTF/GLBファイルの中身を表示する道具(第13章から) / a tool that prints what is inside a glTF/GLB file (from chapter 13): +## プロジェクトの構成 / Project layout(第25章から / from chapter 25) + +``` +engine/ エンジン(静的ライブラリ engine) / the engine (static library `engine`) + include/engine/*.hh 公開ヘッダー:#include "engine/sprite_batch.hh" / public headers + src/*.cc 実装 / implementation + shaders/ エンジンのシェーダー / the engine's shaders +demo/main.cc この章のデモ(実行ファイル game) / this chapter's demo (executable `game`) +assets/ 共有のアセット(スプライト、フォント、3Dモデル) / shared assets (sprites, fonts, 3D models) +tools/gltf_dump.cc glTF/GLBの中身を表示する道具(gltf_dump) / prints what is inside a glTF/GLB file +tests/scene3d/main.cc 3Dの確認:第24章の場面をエンジンで描く(scene3d、-DBUILD_SCENE3D=OFFで外せる) + the 3D check: the chapter 24 scene through the engine (`scene3d`; -DBUILD_SCENE3D=OFF skips it) +games/<名前>/ ゲーム(第27章から、それぞれ自分の実行ファイル) / the games (from chapter 27, one executable each) +``` ```sh -./build/gltf_dump assets/models/diorama.glb # Windows: build\Debug\gltf_dump.exe assets\models\diorama.glb +./build/game # この章のデモ / this chapter's demo +./build/scene3d # 3Dの確認 / the 3D check +./build/gltf_dump assets/models/diorama.glb # Windows: build\Debug\gltf_dump.exe assets\models\diorama.glb ``` -シェーダーとアセットは作業ディレクトリからの相対パスで読み込むので、必ずプロジェクトのルートから実行すること。 -Shaders and assets are loaded relative to the working directory, so always run from the project root. +シェーダーとアセットは作業ディレクトリからの相対パスで読み込むので、必ずプロジェクトのルートから実行すること +(engine/shaders/…、assets/…、games/<名前>/…)。Visual Studioではどの実行ファイルも作業ディレクトリがルートに設定済み。 +Shaders and assets are loaded relative to the working directory, so always run from the project root +(engine/shaders/..., assets/..., games//...). In Visual Studio every executable already uses the root as its +working directory. diff --git a/assets/LICENSE.txt b/assets/LICENSE.txt index 6d0c8dd..57842d5 100644 --- a/assets/LICENSE.txt +++ b/assets/LICENSE.txt @@ -18,3 +18,7 @@ textures/bricks.png レンガ / bricks (chapter 22) textures/bricks_normal.png レンガの法線マップ+高さ / brick normal map + height (chapter 22) models/barrel.glb 樽(PBRのテクスチャ付き) / a barrel with PBR textures (chapter 22) textures/leaves.png 葉(アルファ付き) / leaves with alpha (chapter 23) +sprites/hero.png ピクセルアートの主人公(16×16、7コマ) / pixel-art hero (16×16, 7 frames) (chapter 25) +sprites/objects.png/.atlas タイル・コイン・宝石・スライムなど / tiles, coins, gems, slime... (chapter 25) +sprites/objects_nopad.* 隙間なしのタイル(にじみの例) / tiles without gaps (the bleeding example) (chapter 25) +sprites/pixfont.png 3×5のピクセルフォント / a 3×5 pixel font (chapter 25) diff --git a/assets/sprites/hero.png b/assets/sprites/hero.png new file mode 100644 index 0000000..894bc8d Binary files /dev/null and b/assets/sprites/hero.png differ diff --git a/assets/sprites/objects.atlas b/assets/sprites/objects.atlas new file mode 100644 index 0000000..f03c848 --- /dev/null +++ b/assets/sprites/objects.atlas @@ -0,0 +1,20 @@ +# objects: tiles (extruded 1 px borders), items, slime, cloud (generated by the author's own script) +image objects.png +sprite grass 1 1 16 16 +sprite dirt 19 1 16 16 +sprite brick 37 1 16 16 +sprite stone 55 1 16 16 +sprite crate 73 1 16 16 +sprite coin_0 1 19 12 12 +sprite coin_1 15 19 12 12 +sprite coin_2 29 19 12 12 +sprite coin_3 43 19 12 12 +sprite gem 57 19 10 9 +sprite heart 69 19 9 8 +sprite saw 80 19 16 16 +sprite slime_0 98 19 16 16 +sprite slime_1 1 37 16 16 +sprite flower 19 37 8 8 +sprite cloud 29 37 32 12 +clip coin_spin 8 loop coin_0 coin_1 coin_2 coin_3 +clip slime_bounce 3 loop slime_0 slime_1 diff --git a/assets/sprites/objects.png b/assets/sprites/objects.png new file mode 100644 index 0000000..aa8b79f Binary files /dev/null and b/assets/sprites/objects.png differ diff --git a/assets/sprites/objects_nopad.atlas b/assets/sprites/objects_nopad.atlas new file mode 100644 index 0000000..a83c359 --- /dev/null +++ b/assets/sprites/objects_nopad.atlas @@ -0,0 +1,7 @@ +# the same tiles WITHOUT gaps (bleeding demo, chapter 25; generated by the author's own script) +image objects_nopad.png +sprite grass 0 0 16 16 +sprite dirt 16 0 16 16 +sprite brick 32 0 16 16 +sprite stone 48 0 16 16 +sprite crate 64 0 16 16 diff --git a/assets/sprites/objects_nopad.png b/assets/sprites/objects_nopad.png new file mode 100644 index 0000000..7491d03 Binary files /dev/null and b/assets/sprites/objects_nopad.png differ diff --git a/assets/sprites/pixfont.png b/assets/sprites/pixfont.png new file mode 100644 index 0000000..55d44e2 Binary files /dev/null and b/assets/sprites/pixfont.png differ diff --git a/demo/main.cc b/demo/main.cc new file mode 100644 index 0000000..d806725 --- /dev/null +++ b/demo/main.cc @@ -0,0 +1,427 @@ +// 第25章:2Dレンダリングとスプライト +// Chapter 25: 2D rendering and sprites +// +// 操作 / Controls: +// 1 / 2 / 3 場面:ピクセルアート(320×180のキャンバス) / 10 000スプライト / フィルタリングの比較 +// scene: pixel art (a 320 × 180 canvas) / 10 000 sprites / filtering comparison +// ← → / A D 主人公を歩かせる(場面1。押さなければ自動で歩く) / walk the hero (scene 1; walks by itself otherwise) +// T 並べ替え:なし ⇔ テクスチャごと(場面2:描画コール 約10 000 ⇔ 2) / sorting: none ⇔ by texture +// (scene 2: about 10 000 ⇔ 2 draw calls) +// U 頂点の送り方:glNamedBufferSubData ⇔ 永続マップ / vertex upload: glNamedBufferSubData ⇔ persistent +// mapping +// = / - スプライトの数を2倍・半分に(場面2) / twice / half as many sprites (scene 2) +// P アニメーションを止める・動かす / pause / resume the animation +// Esc 終了 / quit +// +// 2Dの約束(エンジン全体):仮想ピクセル、y下向き、左上が原点、正の回転は時計回り。色はsRGBの値のまま混ぜる +// The 2D conventions (engine-wide): virtual pixels, y down, origin at the top left, positive rotation is clockwise. +// Colors are blended as sRGB-encoded values +#include "engine/animation.hh" +#include "engine/camera2d.hh" +#include "engine/pixel_canvas.hh" +#include "engine/sprite_batch.hh" +#include "engine/sprite_sheet.hh" +#include "engine/window.hh" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// 第25章のHUD:3×5のピクセルフォント(格子のシート、ASCII 32〜95)で文字を描く。第26章でFontクラスになる +// The chapter 25 HUD: text drawn with the 3 × 5 pixel font (a grid sheet, ASCII 32-95). Chapter 26 turns this into +// the Font class +static void drawPixelText(SpriteBatch &batch, const SpriteSheet &font, std::string_view text, Vec2 position, + float scale, Vec4 color, float layer = 100.0f) { + Vec2 pen = position; + for (char c : text) { + if (c == '\n') { + pen = {position.x, pen.y + 6.0f * scale}; + continue; + } + if (c >= 'a' && c <= 'z') c = static_cast(c - 'a' + 'A'); // 大文字だけ / capitals only + int index = c - 32; + if (index > 0 && index < font.count()) { + Sprite s = font.sprite(index, pen, {0.0f, 0.0f}, scale); + s.color = color; + s.layer = layer; + batch.draw(s); + } + pen.x += 4.0f * scale; // 送り幅:3ピクセル+隙間1 / advance: 3 pixels + 1 gap + } +} + +// drawPixelTextが覆う大きさ(一番長い行 × 行数。最後の文字の後の隙間は数えない):HUDの箱を文字に合わせる +// The size drawPixelText covers (the longest line × the lines, without the gap after the last character): fits the +// HUD box to its text +static Vec2 pixelTextSize(std::string_view text, float scale) { + int column = 0, widest = 0, lines = 1; + for (char c : text) { + if (c == '\n') { + ++lines; + column = 0; + continue; + } + widest = std::max(widest, ++column); + } + return Vec2{4.0f * static_cast(widest) - 1.0f, 6.0f * static_cast(lines) - 1.0f} * scale; +} + +// 乱数(第26章でRngクラスになる) / random numbers (chapter 26 turns this into the Rng class) +static float random01(std::uint32_t &state) { + state = state * 1664525u + 1013904223u; + return static_cast(state >> 8) / 16777216.0f; +} + +// 場面2の一枚:位置・速さ・回転・どのシートのどのコマか / one sprite of scene 2: position, velocity, spin, which +// sheet and frame +struct Mover { + Vec2 position, velocity; + float angle, spin; + int kind; // 0 = 主人公(hero.png)、1 = コイン(objects.png) / 0 = hero (hero.png), 1 = coin (objects.png) + float phase; // アニメーションのずれ / animation offset +}; + +static std::vector makeMovers(int count, Vec2 area) { + std::vector movers; + std::uint32_t seed = 25; + for (int i = 0; i < count; ++i) { + Mover m; + m.position = {random01(seed) * area.x, random01(seed) * area.y}; + float a = 6.2831853f * random01(seed), speed = 40.0f + 120.0f * random01(seed); + m.velocity = {speed * std::cos(a), speed * std::sin(a)}; + m.angle = 6.2831853f * random01(seed); + m.spin = (random01(seed) - 0.5f) * 4.0f; + // 交互に別のテクスチャ:並べ替えなしだと1枚ごとに描画コールが要る / alternate textures: without sorting every + // sprite needs its own draw call + m.kind = i % 2; + m.phase = random01(seed); + movers.push_back(m); + } + return movers; +} + +int main() { + Window window; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 25")) return 1; + + // 二つのスプライトバッチ:頂点の送り方だけが違う(Uで切り替え) / two sprite batches that differ only in how + // vertices are uploaded (U switches) + std::optional subDataBatch = SpriteBatch::create({.upload = SpriteUpload::SubData}); + std::optional persistentBatch = SpriteBatch::create({.upload = SpriteUpload::Persistent}); + // ピクセルアートはGL_NEAREST。比較用にGL_LINEARでも読む / pixel art uses GL_NEAREST; also loaded with GL_LINEAR for + // the comparison + std::optional hero = SpriteSheet::loadGrid("assets/sprites/hero.png", 16, 16, 1, 1); + std::optional heroLinear = + SpriteSheet::loadGrid("assets/sprites/hero.png", 16, 16, 1, 1, TextureFilter::Linear); + std::optional objects = SpriteSheet::loadAtlas("assets/sprites/objects.atlas"); + std::optional objectsLinear = SpriteSheet::loadAtlas("assets/sprites/objects.atlas", TextureFilter::Linear); + std::optional noPadLinear = SpriteSheet::loadAtlas("assets/sprites/objects_nopad.atlas", TextureFilter::Linear); + std::optional font = SpriteSheet::loadGrid("assets/sprites/pixfont.png", 4, 6); + if (!subDataBatch || !persistentBatch || !hero || !heroLinear || !objects || !objectsLinear || !noPadLinear || !font) + return 1; + + // 主人公のクリップ:コマの番号はhero.pngの並び(0〜1 待機、2〜5 歩き、6 ジャンプ) + // The hero's clips: frame numbers follow hero.png (0-1 idle, 2-5 walk, 6 jump) + hero->addClip({.name = "idle", .frames = {0, 0, 0, 0, 0, 0, 1}, .fps = 6.0f}); + hero->addClip({.name = "walk", .frames = {2, 3, 4, 5}, .fps = 10.0f}); + const AnimationClip *idleClip = hero->clip("idle"); + const AnimationClip *walkClip = hero->clip("walk"); + const AnimationClip *coinClip = objects->clip("coin_spin"); + const AnimationClip *slimeClip = objects->clip("slime_bounce"); + if (!idleClip || !walkClip || !coinClip || !slimeClip) return 1; + + // 場面1:320×180の仮想解像度(1280×720にちょうど4倍) / scene 1: a 320 × 180 virtual resolution (exactly 4× in 1280 × 720) + PixelCanvas canvas(320, 180); + Camera2D canvasCamera = Camera2D::screen(canvas.size()); + // 場面2・3:ウィンドウのピクセルそのまま / scenes 2 and 3: plain window pixels + Camera2D screenCamera = Camera2D::screen({1280.0f, 720.0f}); + // 場面3のキャンバス比較用:48×48の小さなキャンバス / for scene 3's canvas comparison: a small 48 × 48 canvas + PixelCanvas smallCanvas(48, 48); + Camera2D smallCamera = Camera2D::screen(smallCanvas.size()); + + int scene = 0, spriteCount = 10000; + bool sortByTexture = true, persistent = false, paused = false; + std::vector movers = makeMovers(spriteCount, {1280.0f, 720.0f}); + window.onKey = [&](int key, int action, int /*mods*/) { + if (action != GLFW_PRESS) return; + if (key == GLFW_KEY_ESCAPE) window.close(); + if (key >= GLFW_KEY_1 && key <= GLFW_KEY_3) scene = key - GLFW_KEY_1; + if (key == GLFW_KEY_T) sortByTexture = !sortByTexture; + if (key == GLFW_KEY_U) persistent = !persistent; + if (key == GLFW_KEY_P) paused = !paused; + if (key == GLFW_KEY_EQUAL || key == GLFW_KEY_MINUS) { + spriteCount = key == GLFW_KEY_EQUAL ? std::min(spriteCount * 2, 160000) : std::max(spriteCount / 2, 10); + movers = makeMovers(spriteCount, {1280.0f, 720.0f}); + printf("sprites: %d\n", spriteCount); + } + }; + + // 主人公(場面1) / the hero (scene 1) + Animator heroAnim; + heroAnim.play(walkClip); + Vec2 heroPos = {60.0f, 144.0f}; // 足元 / feet + float heroDir = 1.0f; + Animator coinAnim, slimeAnim; + coinAnim.play(coinClip); + slimeAnim.play(slimeClip); + + float time = 0.0f; + double lastTime = window.time(); + auto lastFrame = std::chrono::steady_clock::now(); + float frameMs = 0.0f; + int frame = 0; + while (!window.shouldClose()) { + double now = window.time(); + float dt = static_cast(now - lastTime); + lastTime = now; + window.pollEvents(); + // 本当の時間(CPU):1フレームにかかったミリ秒(なめらかに) / real time (CPU): milliseconds per frame (smoothed) + auto wall = std::chrono::steady_clock::now(); + float ms = std::chrono::duration(wall - lastFrame).count(); + lastFrame = wall; + frameMs = frame == 0 ? ms : 0.9f * frameMs + 0.1f * ms; + if (paused) dt = 0.0f; + time += dt; + + SpriteBatch &batch = persistent ? *persistentBatch : *subDataBatch; + coinAnim.update(dt); + slimeAnim.update(dt); + + if (scene == 0) { + //------------------------------------------------------------------ + // 場面1:ピクセルアート。320×180のキャンバスに描いて、整数倍で画面へ + // Scene 1: pixel art. Drawn into the 320 × 180 canvas, then scaled by a whole number onto the screen + //------------------------------------------------------------------ + float input = 0.0f; + if (window.keyDown(GLFW_KEY_LEFT) || window.keyDown(GLFW_KEY_A)) input -= 1.0f; + if (window.keyDown(GLFW_KEY_RIGHT) || window.keyDown(GLFW_KEY_D)) input += 1.0f; + if (input != 0.0f) heroDir = input; + else if (heroPos.x > 290.0f) heroDir = -1.0f; // 自動で往復 / walks back and forth by itself + else if (heroPos.x < 30.0f) heroDir = 1.0f; + heroPos.x = std::clamp(heroPos.x + heroDir * 40.0f * dt, 8.0f, 312.0f); + heroAnim.play(dt > 0.0f ? walkClip : idleClip); + heroAnim.update(dt); + + canvas.begin(hexColor(0x8fd3ffff)); + batch.begin(canvasCamera.matrix(), SpriteSort::Layer); + // 雲:ゆっくり流れる(奥、layer 0) / clouds drift slowly (at the back, layer 0) + int cloud = objects->find("cloud"); + for (int i = 0; i < 3; ++i) { + float x = std::fmod(40.0f + 130.0f * static_cast(i) + 6.0f * time, 380.0f) - 40.0f; + Sprite s = objects->sprite(cloud, {std::round(x), 18.0f + 14.0f * static_cast(i % 2)}); + batch.draw(s); + } + // 地面:草の列と土の列。layer 1 / the ground: a row of grass and a row of dirt. Layer 1 + int grass = objects->find("grass"), dirt = objects->find("dirt"), brick = objects->find("brick"); + int crate = objects->find("crate"), stone = objects->find("stone"); + for (int x = 0; x < 20; ++x) { + Sprite g = objects->sprite(grass, {16.0f * static_cast(x), 144.0f}); + g.layer = 1.0f; + batch.draw(g); + for (float y : {160.0f, 176.0f}) { + Sprite d = objects->sprite(dirt, {16.0f * static_cast(x), y}); + d.layer = 1.0f; + batch.draw(d); + } + } + // レンガの足場と木箱 / a brick ledge and crates + for (int x = 0; x < 4; ++x) { + Sprite b = objects->sprite(brick, {176.0f + 16.0f * static_cast(x), 96.0f}); + b.layer = 1.0f; + batch.draw(b); + } + for (Vec2 p : {Vec2{24.0f, 128.0f}, Vec2{40.0f, 128.0f}, Vec2{32.0f, 112.0f}}) { + Sprite c = objects->sprite(crate, p); + c.layer = 1.0f; + batch.draw(c); + } + for (int y = 0; y < 3; ++y) { + Sprite s = objects->sprite(stone, {256.0f, 96.0f + 16.0f * static_cast(y)}); + s.layer = 1.0f; + batch.draw(s); + } + // 回る丸のこ(回転は中心の周り:origin = (0.5, 0.5)) / a spinning saw blade (rotates about its center: + // origin = (0.5, 0.5)) + Sprite saw = objects->sprite(objects->find("saw"), {264.0f, 84.0f}, {0.5f, 0.5f}); + saw.rotation = 3.0f * time; + saw.layer = 2.0f; + batch.draw(saw); + // コイン(アニメーション)と宝石・ハート・花 / coins (animated), a gem, a heart and flowers + for (int i = 0; i < 4; ++i) { + Sprite c = objects->sprite(coinAnim.frame(), {76.0f + 16.0f * static_cast(i), 112.0f}); + c.layer = 2.0f; + batch.draw(c); + } + Sprite gem = objects->sprite(objects->find("gem"), {150.0f, 118.0f + std::round(2.0f * std::sin(3.0f * time))}); + gem.layer = 2.0f; + batch.draw(gem); + Sprite heart = objects->sprite(objects->find("heart"), {170.0f, 120.0f}); + heart.layer = 2.0f; + batch.draw(heart); + for (float x : {96.0f, 152.0f, 228.0f, 300.0f}) { + Sprite f = objects->sprite(objects->find("flower"), {x, 136.0f}); + f.layer = 2.0f; + batch.draw(f); + } + // スライム2匹(同じクリップ、片方は左右反転) / two slimes (the same clip, one mirrored) + for (int i = 0; i < 2; ++i) { + Sprite s = objects->sprite(slimeAnim.frame(), {200.0f + 90.0f * static_cast(i), 128.0f}); + s.flipX = i == 1; + s.layer = 2.0f; + batch.draw(s); + } + // 色を掛けた主人公:赤、半透明、影(黒) / tinted heroes: red, half transparent, a black silhouette + const Vec4 tints[] = {hexColor(0xff7070ff), {1.0f, 1.0f, 1.0f, 0.45f}, hexColor(0x000000b0)}; + for (int i = 0; i < 3; ++i) { + Sprite s = hero->sprite(0, {192.0f + 20.0f * static_cast(i), 96.0f}, {0.5f, 1.0f}); + s.color = tints[i]; + s.layer = 2.0f; + batch.draw(s); + } + // 主人公:足元(下の中心)が基準。左へ歩くときは左右反転 / the hero: the pivot is the feet (bottom center). + // Mirrored when walking left + Sprite h = hero->sprite(heroAnim.frame(), {std::round(heroPos.x), heroPos.y}, {0.5f, 1.0f}); + h.flipX = heroDir < 0.0f; + h.layer = 3.0f; + batch.draw(h); + batch.end(); + SpriteStats stats = batch.stats(); + // HUD(同じキャンバス、別のbegin/end) / the HUD (same canvas, a separate begin/end) + batch.begin(canvasCamera.matrix()); + char hud[128]; + snprintf(hud, sizeof hud, "SCENE 1: PIXEL ART 320X180 X4\nSPRITES %d DRAW CALLS %d", stats.sprites, stats.drawCalls); + Vec2 hudSize = pixelTextSize(hud, 1.0f); + batch.drawRect({2.0f, 2.0f, hudSize.x + 4.0f, hudSize.y + 4.0f}, hexColor(0x1b172699)); // 2ピクセルの余白 / 2 px margin + drawPixelText(batch, *font, hud, {4.0f, 4.0f}, 1.0f, kWhite); + batch.end(); + canvas.present(window.width(), window.height()); + } else if (scene == 1) { + //------------------------------------------------------------------ + // 場面2:たくさんのスプライトを一つのバッチで / Scene 2: many sprites in one batch + //------------------------------------------------------------------ + for (Mover &m : movers) { + m.position += m.velocity * dt; + if (m.position.x < 0.0f || m.position.x > 1280.0f) m.velocity.x = -m.velocity.x; + if (m.position.y < 0.0f || m.position.y > 720.0f) m.velocity.y = -m.velocity.y; + m.angle += m.spin * dt; + } + Framebuffer::bindDefault(window.width(), window.height()); + glClearColor(0.07f, 0.08f, 0.13f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + auto start = std::chrono::steady_clock::now(); + batch.begin(screenCamera.matrix(), sortByTexture ? SpriteSort::Texture : SpriteSort::None); + for (const Mover &m : movers) { + // 主人公は歩き、コインは回る。コマはそれぞれの時間のずれで / heroes walk, coins spin, each with its own offset + int heroFrame = 2 + static_cast((time + m.phase) * 10.0f) % 4; + int coinFrame = coinClip->frames[static_cast((time + m.phase) * 8.0f) % 4]; + Sprite s = m.kind == 0 ? hero->sprite(heroFrame, m.position, {0.5f, 0.5f}, 2.0f) + : objects->sprite(coinFrame, m.position, {0.5f, 0.5f}, 2.0f); + s.rotation = m.angle; + batch.draw(s); + } + batch.end(); + float batchMs = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + SpriteStats stats = batch.stats(); + batch.begin(screenCamera.matrix()); + char hud[256]; + snprintf(hud, sizeof hud, + "SCENE 2: %d SPRITES IN ONE BATCH\nDRAW CALLS %d SORT %s (T) UPLOAD %s (U)\n" + "BATCH %.1f MS FRAME %.1f MS (CPU)", + stats.sprites, stats.drawCalls, sortByTexture ? "BY TEXTURE" : "NONE", + persistent ? "PERSISTENT MAP" : "SUBDATA", static_cast(batchMs), static_cast(frameMs)); + Vec2 hudSize = pixelTextSize(hud, 4.0f); + batch.drawRect({8.0f, 8.0f, hudSize.x + 16.0f, hudSize.y + 16.0f}, hexColor(0x000000c0)); // 余白8 / 8 px margin + drawPixelText(batch, *font, hud, {16.0f, 16.0f}, 4.0f, hexColor(0xffe08aff)); + batch.end(); + if (frame % 60 == 2) + printf("scene 2: %d sprites, %d draw calls (%s, %s), batch %.1f ms\n", stats.sprites, stats.drawCalls, + sortByTexture ? "by texture" : "unsorted", persistent ? "persistent" : "subdata", + static_cast(batchMs)); + } else { + //------------------------------------------------------------------ + // 場面3:フィルタリング:GL_NEAREST ⇔ GL_LINEAR、整数倍 ⇔ 半端な倍率と回転、直接 ⇔ キャンバス、隙間 ⇔ にじみ + // Scene 3: filtering: GL_NEAREST ⇔ GL_LINEAR, whole ⇔ fractional scale and rotation, direct ⇔ canvas, + // gaps ⇔ bleeding + //------------------------------------------------------------------ + heroAnim.play(walkClip); + heroAnim.update(dt); + float angle = 0.35f * std::sin(0.8f * time); + // 小さなキャンバスに回る主人公と丸のこ(48×48の本物のピクセル) / a turning hero and saw in the small canvas + // (real 48 × 48 pixels) + smallCanvas.begin(hexColor(0x2a3350ff)); + batch.begin(smallCamera.matrix()); + Sprite small = hero->sprite(heroAnim.frame(), {24.0f, 22.0f}, {0.5f, 0.5f}, 2.0f); + small.rotation = angle; + batch.draw(small); + Sprite smallSaw = objects->sprite(objects->find("saw"), {38.0f, 38.0f}, {0.5f, 0.5f}); + smallSaw.rotation = 2.0f * time; + batch.draw(smallSaw); + batch.end(); + + Framebuffer::bindDefault(window.width(), window.height()); + glClearColor(0.10f, 0.11f, 0.16f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + batch.begin(screenCamera.matrix()); + const Vec4 label = hexColor(0xffe08aff), panel = hexColor(0x2a3350ff); + // 上の段:×12(整数)と×7.5で回転、それぞれGL_NEARESTとGL_LINEAR / top row: ×12 (whole) and ×7.5 rotated, each + // with GL_NEAREST and GL_LINEAR + const char *names[] = {"NEAREST X12", "LINEAR X12", "NEAREST X7.5 TURNED", "LINEAR X7.5 TURNED"}; + for (int i = 0; i < 4; ++i) { + float x0 = 20.0f + 315.0f * static_cast(i); + batch.drawRect({x0, 40.0f, 300.0f, 280.0f}, panel); + drawPixelText(batch, *font, names[i], {x0 + 8.0f, 48.0f}, 3.0f, label); + const SpriteSheet &sheet = i % 2 == 0 ? *hero : *heroLinear; + Sprite s = sheet.sprite(0, {x0 + 150.0f, 190.0f}, {0.5f, 0.5f}, i < 2 ? 12.0f : 7.5f); + if (i >= 2) s.rotation = angle; + batch.draw(s); + } + // 中の段:直接(画面の細かいピクセルで回る) ⇔ キャンバス(48×48を6倍) / middle row: direct (turns with the + // screen's fine pixels) ⇔ canvas (48 × 48 enlarged 6×) + batch.drawRect({20.0f, 340.0f, 300.0f, 330.0f}, panel); + drawPixelText(batch, *font, "DIRECT X6", {28.0f, 348.0f}, 3.0f, label); + Sprite direct = hero->sprite(heroAnim.frame(), {20.0f + 6.0f * 24.0f + 6.0f, 380.0f + 6.0f * 22.0f}, {0.5f, 0.5f}, 12.0f); + direct.rotation = angle; + batch.draw(direct); + Sprite directSaw = objects->sprite(objects->find("saw"), {26.0f + 6.0f * 38.0f, 380.0f + 6.0f * 38.0f}, {0.5f, 0.5f}, 6.0f); + directSaw.rotation = 2.0f * time; + batch.draw(directSaw); + batch.drawRect({335.0f, 340.0f, 300.0f, 330.0f}, panel); + drawPixelText(batch, *font, "CANVAS X6", {343.0f, 348.0f}, 3.0f, label); + // FBOの色テクスチャは下の行がv = 0(GLの約束):y下向きの2DではflipYで描く + // An FBO's color texture has its bottom row at v = 0 (the GL convention): draw it with flipY in y-down 2D + Sprite canvasSprite = {.texture = &smallCanvas.framebuffer().color(), .position = {341.0f, 380.0f}, + .size = {288.0f, 288.0f}, .flipY = true}; + batch.draw(canvasSprite); + // 右下:タイルをGL_LINEARで×3.3に。隙間(縁の複製)あり ⇔ なし / bottom right: tiles at ×3.3 with GL_LINEAR, with + // gaps (extruded edges) ⇔ without + for (int k = 0; k < 2; ++k) { + float y0 = 340.0f + 170.0f * static_cast(k); + batch.drawRect({650.0f, y0, 610.0f, 160.0f}, panel); + drawPixelText(batch, *font, k == 0 ? "LINEAR X3.3, 1 PX EXTRUDED GAPS" : "LINEAR X3.3, NO GAPS: BLEEDING", + {658.0f, y0 + 8.0f}, 3.0f, label); + const SpriteSheet &sheet = k == 0 ? *objectsLinear : *noPadLinear; + const char *tiles[] = {"grass", "dirt", "brick", "stone", "crate"}; + for (int t = 0; t < 10; ++t) { + int index = sheet.find(tiles[t / 2]); + batch.draw(sheet.sprite(index, {660.0f + 52.8f * static_cast(t) + 0.3f, y0 + 45.0f + 0.4f}, {0.0f, 0.0f}, 3.3f)); + batch.draw(sheet.sprite(index, {660.0f + 52.8f * static_cast(t) + 0.3f, y0 + 45.0f + 52.8f + 0.4f}, {0.0f, 0.0f}, 3.3f)); + } + } + batch.end(); + } + + if (frame++ % 120 == 1) { + char title[128]; + snprintf(title, sizeof title, "OpenGL Tutorial - Chapter 25 - scene %d - %d draw calls", scene + 1, batch.stats().drawCalls); + window.setTitle(title); + } + window.swapBuffers(); + } + return 0; +} diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt new file mode 100644 index 0000000..f847830 --- /dev/null +++ b/engine/CMakeLists.txt @@ -0,0 +1,49 @@ +# エンジン:どのゲームでも使うクラスをまとめた静的ライブラリ +# The engine: a static library with the classes every game uses +# +# engine/include/engine/*.hh 公開ヘッダー(#include "engine/sprite_batch.hh") / public headers +# engine/src/*.cc 実装 / the implementation +# engine/shaders/* エンジンのシェーダー(実行時にプロジェクトのルートから読む) / the engine's shaders +# (loaded at run time, relative to the project root) + +# stb_image:実装は src/stb_image_impl.cc だけ。他人のコードなので警告フラグなしの別ライブラリにする +# stb_image: the implementation lives in src/stb_image_impl.cc only. It is someone else's code, +# so it is a separate library built without our warning flags +add_library(stb_image STATIC src/stb_image_impl.cc) +target_include_directories(stb_image PUBLIC ${PROJECT_SOURCE_DIR}/external/stb) + +add_library(engine STATIC + # 第1〜24章 / chapters 1-24 + src/window.cc + src/gl_debug.cc + src/buffer.cc + src/mesh.cc + src/file_util.cc + src/shader.cc + src/texture.cc + src/shapes.cc + src/camera.cc + src/material.cc + src/lights.cc + src/json.cc + src/gltf.cc + src/model.cc + src/framebuffer.cc + src/cubemap.cc + src/gpu_timer.cc + src/tangents.cc + src/ibl.cc + src/pbr_material.cc + src/renderer3d.cc + # 第25章:2D / chapter 25: 2D + src/camera2d.cc + src/pixel_canvas.cc + src/sprite_batch.cc + src/sprite_sheet.cc + src/animation.cc) + +# PUBLIC:エンジンを使う側(ゲーム)にも include/、linalg.hh、GLAD、GLFWが見える +# PUBLIC: whoever links the engine (the games) also sees include/, linalg.hh, GLAD and GLFW +target_include_directories(engine PUBLIC include ${PROJECT_SOURCE_DIR}/external/linalg) +target_link_libraries(engine PRIVATE stb_image PUBLIC glad glfw) +enable_warnings(engine) diff --git a/engine/include/engine/animation.hh b/engine/include/engine/animation.hh new file mode 100644 index 0000000..7c1d939 --- /dev/null +++ b/engine/include/engine/animation.hh @@ -0,0 +1,43 @@ +// コマ送りのアニメーション(第25章) / frame-by-frame animation (chapter 25) +#pragma once + +#include +#include + +// 一つの動き(歩く・待つ・回る…):スプライトシートのコマ番号の列と速さ +// One motion (walk, idle, spin...): a list of sprite-sheet frame indices and a speed +struct AnimationClip { + std::string name; + std::vector frames; // SpriteSheetの番号 / SpriteSheet indices + float fps = 10.0f; // 1秒に何コマ / frames per second + bool loop = true; // falseなら最後のコマで止まる / false: stops on the last frame + + float duration() const { return fps > 0.0f ? static_cast(frames.size()) / fps : 0.0f; } +}; + +// クリップを再生する(キャラクター一人に一つ)。クリップは指すだけ(SpriteSheetが持つ) +// Plays a clip (one per character). It only points at the clip (the SpriteSheet owns it) +class Animator { +public: + // 再生する。同じクリップならそのまま続ける(restart = trueで最初から)。nullptrで止める + // Plays a clip. The same clip keeps running (restart = true starts it over). nullptr stops + void play(const AnimationClip *clip, bool restart = false); + // 時間を進める(固定ステップの更新から呼ぶ) / advances time (call it from the fixed-step update) + void update(float dt); + + // 今のコマ:スプライトシートの番号(クリップがなければ-1) / the current frame: a sprite-sheet index (-1 without + // a clip) + int frame() const; + // クリップの中で何番目のコマか / which frame of the clip + int frameIndex() const; + // 繰り返さないクリップが最後まで行ったか / has a non-looping clip reached its end? + bool finished() const; + const AnimationClip *clip() const { return current; } + float time() const { return elapsed; } + + float speed = 1.0f; // 再生速度の倍率(負なら逆再生) / playback speed multiplier (negative plays backwards) + +private: + const AnimationClip *current = nullptr; + float elapsed = 0.0f; +}; diff --git a/src/buffer.hh b/engine/include/engine/buffer.hh similarity index 100% rename from src/buffer.hh rename to engine/include/engine/buffer.hh diff --git a/src/camera.hh b/engine/include/engine/camera.hh similarity index 100% rename from src/camera.hh rename to engine/include/engine/camera.hh diff --git a/engine/include/engine/camera2d.hh b/engine/include/engine/camera2d.hh new file mode 100644 index 0000000..44da14b --- /dev/null +++ b/engine/include/engine/camera2d.hh @@ -0,0 +1,65 @@ +// 2Dのカメラ(第25章):仮想解像度の正射影と、ウィンドウへの拡大(レターボックス) +// The 2D camera (chapter 25): an orthographic projection for a virtual resolution, and scaling it to the window +// (letterboxing) +#pragma once + +#include "engine/mathx.hh" +#include "engine/rect.hh" + +// 2Dの座標系(エンジン全体の約束): +// * 単位は仮想ピクセル。y軸は下向き、原点は左上(画像・タイルマップ・文字の並びと同じ)。 +// * 正の回転は画面上で時計回り。 +// * 画像の一番上の行がv = 0(テクスチャは上下反転せずに読む)。 +// The 2D coordinate system (an engine-wide convention): +// * Units are virtual pixels. The y axis points down, the origin is at the top left (like images, tile maps and +// lines of text). +// * A positive rotation is clockwise on screen. +// * The top row of an image is v = 0 (textures are loaded without flipping). +struct Camera2D { + // 拡大率1のときに見える広さ(仮想解像度) / what is visible at zoom 1 (the virtual resolution) + Vec2 viewSize = {320.0f, 180.0f}; + // 画面の真ん中に来るワールドの点 / the world point shown in the middle of the screen + Vec2 centre = {160.0f, 90.0f}; + float zoom = 1.0f; // 2 = 2倍に大きく / 2 = twice as large + float rotation = 0.0f; // ラジアン、画面上で時計回り / radians, clockwise on screen + // 中心を(今の拡大率での)画面のピクセルにそろえる:スクロールが画面のピクセル単位になり、絵はビューのピクセルの + // 格子に揃ったまま動く / Snap the center to whole screen pixels (at the current zoom): scrolling moves in whole view + // pixels, so the art stays on the view's pixel grid + bool pixelSnap = false; + + // ワールド → クリップ座標(SpriteBatch::beginに渡す) / world → clip space (pass it to SpriteBatch::begin) + Mat4 matrix() const; + // 仮想画面の点(0〜viewSize、左上が原点) → ワールド、とその逆 / a virtual-screen point (0..viewSize, origin top + // left) → world, and back + Vec2 toWorld(Vec2 viewPoint) const; + Vec2 toView(Vec2 worldPoint) const; + // 見えている範囲を囲むワールドの長方形(回転していれば少し広い) / the world rectangle around what is visible + // (a little larger when rotated) + Rect visibleRect() const; + + // ワールド座標 = 仮想画面のピクセル(HUD・文字・メニュー用) / world coordinates = virtual-screen pixels (for HUDs, + // text and menus) + static Camera2D screen(Vec2 size) { return {.viewSize = size, .centre = 0.5f * size}; } +}; + +// ウィンドウの中の描く場所(glViewportの値)。x, yはGLの約束どおり左下から +// Where to draw inside the window (the glViewport values). x and y count from the bottom left, as GL does +struct Viewport { + int x = 0, y = 0, width = 0, height = 0; + int top = 0; // ウィンドウの上端からの距離(マウスの変換用) / distance from the window's top (for the mouse) + float scale = 1.0f; // 仮想ピクセル1つが画面の何ピクセルか / screen pixels per virtual pixel + + void apply() const; // glViewport + // ウィンドウの座標(GLFWのマウス、左上が原点) → 仮想画面の座標 / window coordinates (the GLFW mouse, origin top + // left) → virtual-screen coordinates + Vec2 toView(Vec2 windowPoint) const { + return {(windowPoint.x - static_cast(x)) / scale, (windowPoint.y - static_cast(top)) / scale}; + } +}; + +// 仮想解像度viewSizeを縦横比を保ったまま一番大きくウィンドウに入れる。余りは上下か左右の帯(レターボックス)。 +// integerScaleなら倍率を整数に切り捨てる(ピクセルアートのピクセルがみな同じ大きさになる) +// Fits the virtual resolution viewSize into the window as large as possible without changing its aspect ratio. What +// is left becomes bars at the top and bottom or the sides (letterboxing). integerScale rounds the scale down to a +// whole number (every pixel-art pixel gets the same size) +Viewport letterbox(int windowWidth, int windowHeight, Vec2 viewSize, bool integerScale); diff --git a/src/cubemap.hh b/engine/include/engine/cubemap.hh similarity index 97% rename from src/cubemap.hh rename to engine/include/engine/cubemap.hh index 6ffacc9..c4d8035 100644 --- a/src/cubemap.hh +++ b/engine/include/engine/cubemap.hh @@ -30,7 +30,7 @@ public: // Loads six image files (order +X, -X, +Y, -Y, +Z, -Z). No vertical flip: cube-map faces start at the top row. // All must be squares of the same size. Builds mipmaps (for blurry reflections). On failure prints the error // and returns std::nullopt. - // srgb = true:色の画像なのでGL_SRGB8_ALPHA8にする(第21章。空はtrue) / srgb = true: a colour image, stored as + // srgb = true:色の画像なのでGL_SRGB8_ALPHA8にする(第21章。空はtrue) / srgb = true: a color image, stored as // GL_SRGB8_ALPHA8 (chapter 21; true for skies) static std::optional load(const std::array &paths, bool srgb = false); // dir/px.png, dir/nx.png … を読む / loads dir/px.png, dir/nx.png, ... diff --git a/src/file_util.hh b/engine/include/engine/file_util.hh similarity index 100% rename from src/file_util.hh rename to engine/include/engine/file_util.hh diff --git a/src/framebuffer.hh b/engine/include/engine/framebuffer.hh similarity index 72% rename from src/framebuffer.hh rename to engine/include/engine/framebuffer.hh index 25636a5..516f132 100644 --- a/src/framebuffer.hh +++ b/engine/include/engine/framebuffer.hh @@ -1,7 +1,7 @@ // フレームバッファ:画面の代わりにテクスチャへ描く / framebuffers: draw into a texture instead of the screen #pragma once -#include "texture.hh" +#include "engine/texture.hh" #include @@ -11,35 +11,45 @@ constexpr int kMaxColorAttachments = 4; // GLは最低8を保証する / GL guar // フレームバッファに何を付けるか / what to attach to a framebuffer struct FramebufferSpec { - // 色のテクスチャの形式(0 = 色なし)。HDRではGL_RGBA16F(第21章) - // The colour texture's format (0 = no colour). GL_RGBA16F for HDR (chapter 21) + // 色のテクスチャの形式(0 = 色なし:描く色・読む色はGL_NONE)。HDRではGL_RGBA16F(第21章)。 + // テクスチャはミップマップなし、CLAMP_TO_EDGE、GL_LINEAR + // The color texture's format (0 = no color: draw and read buffer GL_NONE). GL_RGBA16F for HDR (chapter 21). + // The textures have no mipmaps, CLAMP_TO_EDGE, GL_LINEAR GLenum colorFormat = GL_RGBA8; // 色の付け先の数(MRT、第21章):GL_COLOR_ATTACHMENT0〜。全部colorFormat。シェーダーは // layout(location = i) out … でi番目に書く(最大kMaxColorAttachments) - // The number of colour attachments (MRT, chapter 21): GL_COLOR_ATTACHMENT0... All use colorFormat. A shader writes + // The number of color attachments (MRT, chapter 21): GL_COLOR_ATTACHMENT0... All use colorFormat. A shader writes // the i-th one with layout(location = i) out ... (at most kMaxColorAttachments) int colorCount = 1; - // 深度・ステンシルのレンダーバッファの形式(0 = なし)。サンプラーで読まないのでテクスチャでなくて良い - // The depth-stencil renderbuffer's format (0 = none). It is never sampled, so it need not be a texture + // 深度・ステンシルの形式(0 = なし)。普通はレンダーバッファ(サンプラーで読まないものはテクスチャでなくて良い)、 + // depthTexture = trueならテクスチャ。GL_DEPTH24_STENCIL8・GL_DEPTH32F_STENCIL8は深度とステンシルの両方に、 + // 深度だけの形式(GL_DEPTH_COMPONENT24など)は深度にだけ付く + // The depth-stencil format (0 = none). Normally a renderbuffer (what is never sampled need not be a texture); a + // texture with depthTexture = true. GL_DEPTH24_STENCIL8 / GL_DEPTH32F_STENCIL8 attach as depth and stencil, + // depth-only formats (GL_DEPTH_COMPONENT24 etc.) as depth only 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 + // Multisampling (MSAA, chapter 20): samples per pixel. 0 = an ordinary framebuffer (the color is a texture). + // 1 or more makes both color 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; // 深度をレンダーバッファではなくテクスチャにする(影の地図、第23章)。depthStencilFormatは - // GL_DEPTH_COMPONENT24 / 32Fなど。比較モードon、GL_LINEAR、外側はGL_CLAMP_TO_BORDERで1。depth()で読む + // GL_DEPTH_COMPONENT24 / 32Fなど。比較モードon、GL_LINEAR、外側はGL_CLAMP_TO_BORDERで1。depth()で読む。 + // マルチサンプルとは一緒に使えない // Make the depth a texture instead of a renderbuffer (shadow maps, chapter 23). depthStencilFormat is - // GL_DEPTH_COMPONENT24 / 32F etc. Comparison mode on, GL_LINEAR, GL_CLAMP_TO_BORDER with 1 outside. Read it with depth() + // GL_DEPTH_COMPONENT24 / 32F etc. Comparison mode on, GL_LINEAR, GL_CLAMP_TO_BORDER with 1 outside. Read it with + // depth(). Not supported together with multisampling bool depthTexture = false; }; -// フレームバッファオブジェクト(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. +// フレームバッファオブジェクト(FBO):色のテクスチャ(MRTなら複数)+深度・ステンシル(レンダーバッファ、 +// depthTextureならテクスチャ)。RAII、コピー不可・移動可。DSAで作る。マルチサンプル(spec.samples > 0)なら色も +// レンダーバッファ。 +// A framebuffer object (FBO): color textures (several with MRT) + a depth-stencil attachment (a renderbuffer, or a +// texture with depthTexture). RAII, non-copyable, movable, built with DSA. When multisampled (spec.samples > 0) the +// color is a renderbuffer too. class Framebuffer { public: Framebuffer() = default; @@ -63,7 +73,7 @@ public: // 描いた結果。シェーダーでサンプリングできる(マルチサンプルなら空:id() == 0) // The result; can be sampled in a shader (empty for a multisampled framebuffer: id() == 0) - // index = 何番目の色の付け先か(MRT) / index = which colour attachment (MRT) + // index = 何番目の色の付け先か(MRT) / index = which color attachment (MRT) const Texture2D &color(int index = 0) const { return colorTextures[static_cast(index)]; } Texture2D &color(int index = 0) { return colorTextures[static_cast(index)]; } int colorCount() const { return spec.colorFormat != 0 ? spec.colorCount : 0; } @@ -79,8 +89,8 @@ public: // the same size is allowed from a multisampled source). mask = GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT... (depth // only with GL_NEAREST) // 色の付け先が複数あれば、一つずつ同じ番号の付け先へコピーする(ブリットは読む色を一つしか選べない) - // With several colour attachments each one is copied into the attachment with the same number (a blit can read - // only one colour buffer at a time) + // With several color attachments each one is copied into the attachment with the same number (a blit can read + // only one color buffer at a time) void blitTo(const Framebuffer &target, GLbitfield mask = GL_COLOR_BUFFER_BIT, GLenum filter = GL_NEAREST) const; GLuint id() const { return fbo; } @@ -97,7 +107,7 @@ private: GLuint fbo = 0; GLuint depthStencil = 0; // レンダーバッファ / renderbuffer - // マルチサンプルの色のレンダーバッファ(第20章) / multisampled colour renderbuffers (chapter 20) + // マルチサンプルの色のレンダーバッファ(第20章) / multisampled color renderbuffers (chapter 20) std::array colorSamples = {}; std::array colorTextures; Texture2D depthTex; // 第23章 / chapter 23 @@ -106,10 +116,10 @@ private: FramebufferSpec spec; }; -// 画面全体を覆う三角形(ポストプロセス用)。頂点はシェーダーがgl_VertexIDから作る(shaders/post.vert)。 +// 画面全体を覆う三角形(ポストプロセス用)。頂点はシェーダーがgl_VertexIDから作る(engine/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 +// (engine/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: diff --git a/src/gl_debug.hh b/engine/include/engine/gl_debug.hh similarity index 100% rename from src/gl_debug.hh rename to engine/include/engine/gl_debug.hh diff --git a/src/gltf.hh b/engine/include/engine/gltf.hh similarity index 99% rename from src/gltf.hh rename to engine/include/engine/gltf.hh index 8bb2386..2a0a6ac 100644 --- a/src/gltf.hh +++ b/engine/include/engine/gltf.hh @@ -9,7 +9,7 @@ // skins, animations, morph targets (skipped), Draco / meshopt compression #pragma once -#include "mathx.hh" +#include "engine/mathx.hh" #include #include diff --git a/src/gpu_timer.hh b/engine/include/engine/gpu_timer.hh similarity index 100% rename from src/gpu_timer.hh rename to engine/include/engine/gpu_timer.hh diff --git a/src/ibl.hh b/engine/include/engine/ibl.hh similarity index 94% rename from src/ibl.hh rename to engine/include/engine/ibl.hh index 6b5ee29..ae9c4f3 100644 --- a/src/ibl.hh +++ b/engine/include/engine/ibl.hh @@ -3,9 +3,9 @@ // at start-up #pragma once -#include "cubemap.hh" -#include "framebuffer.hh" -#include "shader.hh" +#include "engine/cubemap.hh" +#include "engine/framebuffer.hh" +#include "engine/shader.hh" #include @@ -42,5 +42,5 @@ public: private: Cubemap irradianceMap; Cubemap prefilteredMap; - Framebuffer brdfFbo; // 色のテクスチャがLUT(GL_RG16F) / its colour texture is the LUT (GL_RG16F) + Framebuffer brdfFbo; // 色のテクスチャがLUT(GL_RG16F) / its color texture is the LUT (GL_RG16F) }; diff --git a/src/json.hh b/engine/include/engine/json.hh similarity index 100% rename from src/json.hh rename to engine/include/engine/json.hh diff --git a/src/lights.hh b/engine/include/engine/lights.hh similarity index 97% rename from src/lights.hh rename to engine/include/engine/lights.hh index bfa3edf..f0fede1 100644 --- a/src/lights.hh +++ b/engine/include/engine/lights.hh @@ -1,9 +1,9 @@ // 光源:平行光源・点光源・スポットライト / light casters: directional, point and spot lights #pragma once -#include "mathx.hh" -#include "shader.hh" -#include "uniforms.hh" +#include "engine/mathx.hh" +#include "engine/shader.hh" +#include "engine/uniforms.hh" #include @@ -22,7 +22,7 @@ constexpr int kMaxSpotLights = 4; // Directional light (sun, moon): no position, comes from the same direction everywhere struct DirectionalLight { Vec3 direction = {0.0f, -1.0f, 0.0f}; // 光が進む向き(光源へ向かう向きの逆) / the direction the light travels - Vec3 color = {0.0f, 0.0f, 0.0f}; // 色と明るさ。0 = オフ / colour and brightness; 0 = off + Vec3 color = {0.0f, 0.0f, 0.0f}; // 色と明るさ。0 = オフ / color and brightness; 0 = off }; // 点光源(電球):一点から全方向へ、距離で弱くなる / point light (a bulb): all directions from one point, weaker with distance diff --git a/src/material.hh b/engine/include/engine/material.hh similarity index 89% rename from src/material.hh rename to engine/include/engine/material.hh index c6e3fd2..273fb54 100644 --- a/src/material.hh +++ b/engine/include/engine/material.hh @@ -1,9 +1,9 @@ // マテリアル:物体の表面の性質 / material: the properties of an object's surface #pragma once -#include "mathx.hh" -#include "shader.hh" -#include "texture.hh" +#include "engine/mathx.hh" +#include "engine/shader.hh" +#include "engine/texture.hh" // アルファ(不透明度)の使い方。glTFのalphaModeと同じ。シェーダーでは0/1/2 // How alpha (opacity) is used. Same as glTF's alphaMode; 0/1/2 in the shader @@ -14,11 +14,11 @@ enum class AlphaMode { }; // Blinn-Phongのマテリアル。色とマップ(テクスチャ)は掛け合わされる。マップがなければ白(=色だけ)。 -// A Blinn-Phong material. Each colour is multiplied with its map (texture); no map means white (= the colour alone). +// A Blinn-Phong material. Each color is multiplied with its map (texture); no map means white (= the color alone). struct Material { - Vec3 diffuse = {1.0f, 1.0f, 1.0f}; // 拡散反射の色(物体の色) / diffuse colour (the object's colour) - Vec3 specular = {0.5f, 0.5f, 0.5f}; // 鏡面反射の色と強さ / specular colour and strength - Vec3 emission = {0.0f, 0.0f, 0.0f}; // 発光の色:光が当たらなくても見える / emission colour: visible even without light + Vec3 diffuse = {1.0f, 1.0f, 1.0f}; // 拡散反射の色(物体の色) / diffuse color (the object's color) + Vec3 specular = {0.5f, 0.5f, 0.5f}; // 鏡面反射の色と強さ / specular color and strength + Vec3 emission = {0.0f, 0.0f, 0.0f}; // 発光の色:光が当たらなくても見える / emission color: visible even without light float shininess = 32.0f; // 光沢度 / shininess float alpha = 1.0f; // 不透明度。diffuseMapのアルファと掛ける / opacity, multiplied with diffuseMap's alpha @@ -29,7 +29,7 @@ struct Material { // 環境(ユニット3のキューブマップ)の映り込み(第18章)。金属だけ。第24章のIBLまでの簡単な代わり // Reflection of the environment (the cube map on unit 3, chapter 18). Metals only; a simple stand-in until IBL (ch24) - Vec3 reflectivity = {0.0f, 0.0f, 0.0f}; // 映り込みの色と強さ(0 = なし) / colour and strength of the reflection (0 = none) + Vec3 reflectivity = {0.0f, 0.0f, 0.0f}; // 映り込みの色と強さ(0 = なし) / color and strength of the reflection (0 = none) float reflectionBlur = 0.0f; // 0 = 鏡、1 = 一番ぼやけたミップマップ / 0 = mirror, 1 = the blurriest mip level const Texture2D *diffuseMap = nullptr; // テクスチャユニット0 / texture unit 0 diff --git a/src/mathx.hh b/engine/include/engine/mathx.hh similarity index 51% rename from src/mathx.hh rename to engine/include/engine/mathx.hh index bdedf93..26633de 100644 --- a/src/mathx.hh +++ b/engine/include/engine/mathx.hh @@ -27,7 +27,31 @@ inline Mat3 toMat3(const Mat4 &m) { inline Mat3 normalMatrix(const Mat4 &model) { return toMat3(transpose(inverse(model))); } // sRGBの色(カラーピッカーや画像編集ソフトの値、0〜1)→ リニア(第21章)。シェーダーの計算はリニアで行う -// An sRGB colour (the values of colour pickers and image editors, 0..1) → linear (chapter 21). Shaders compute in +// An sRGB color (the values of color pickers and image editors, 0..1) → linear (chapter 21). Shaders compute in // linear space inline float srgbToLinear(float c) { return c <= 0.04045f ? c / 12.92f : std::pow((c + 0.055f) / 1.055f, 2.4f); } inline Vec3 srgbToLinear(Vec3 c) { return {srgbToLinear(c.x), srgbToLinear(c.y), srgbToLinear(c.z)}; } + +// 2D(第25章):linalg.hhのVec2には足し算・引き算・スカラー倍・内積・長さしかないので足す +// 2D (chapter 25): linalg.hh's Vec2 only has addition, subtraction, scaling, dot and length, so we add the rest +inline Vec2 operator*(Vec2 v, float s) { return {v.x * s, v.y * s}; } +inline Vec2 operator/(Vec2 v, float s) { return {v.x / s, v.y / s}; } +inline Vec2 operator-(Vec2 v) { return {-v.x, -v.y}; } +// 成分ごとの掛け算(大きさの拡大など) / component-wise product (scaling a size, for example) +inline Vec2 operator*(Vec2 a, Vec2 b) { return {a.x * b.x, a.y * b.y}; } +inline Vec2 &operator+=(Vec2 &a, Vec2 b) { return a = a + b; } +inline Vec2 &operator-=(Vec2 &a, Vec2 b) { return a = a - b; } +inline Vec2 &operator*=(Vec2 &a, float s) { return a = a * s; } +inline Vec2 lerp(Vec2 a, Vec2 b, float t) { return a + t * (b - a); } +inline Vec4 lerp(Vec4 a, Vec4 b, float t) { return a + t * (b - a); } +// 長さ0なら0のまま / stays zero for a zero vector +inline Vec2 normalize(Vec2 v) { + float len = length(v); + return len > 0.0f ? v / len : Vec2{}; +} +// 回転(ラジアン)。2Dの画面座標(y下向き)では正の角度は時計回りに見える +// Rotation (radians). In 2D screen coordinates (y down) a positive angle looks clockwise +inline Vec2 rotate(Vec2 v, float angle) { + float c = std::cos(angle), s = std::sin(angle); + return {c * v.x - s * v.y, s * v.x + c * v.y}; +} diff --git a/src/mesh.hh b/engine/include/engine/mesh.hh similarity index 98% rename from src/mesh.hh rename to engine/include/engine/mesh.hh index 372adf7..b4b0cad 100644 --- a/src/mesh.hh +++ b/engine/include/engine/mesh.hh @@ -2,7 +2,7 @@ // Mesh: a vertex array object + vertex buffer + index buffer #pragma once -#include "buffer.hh" +#include "engine/buffer.hh" #include @@ -57,7 +57,7 @@ constexpr VertexAttrib kModelVertexLayout[] = { }; // インスタンスごとのデータ(第19章):モデル行列(列4本をlocation 4〜7)と色(location 8) -// Per-instance data (chapter 19): the model matrix (its four columns at locations 4..7) and a colour (location 8) +// Per-instance data (chapter 19): the model matrix (its four columns at locations 4..7) and a color (location 8) struct InstanceData { Mat4 model; Vec3 color; diff --git a/src/model.hh b/engine/include/engine/model.hh similarity index 95% rename from src/model.hh rename to engine/include/engine/model.hh index 6e42dfe..0c75cb1 100644 --- a/src/model.hh +++ b/engine/include/engine/model.hh @@ -1,12 +1,12 @@ // glTF/GLBのモデルをGPUに載せて描く / uploads a glTF/GLB model to the GPU and draws it #pragma once -#include "gltf.hh" -#include "material.hh" -#include "mesh.hh" -#include "pbr_material.hh" -#include "shader.hh" -#include "texture.hh" +#include "engine/gltf.hh" +#include "engine/material.hh" +#include "engine/mesh.hh" +#include "engine/pbr_material.hh" +#include "engine/shader.hh" +#include "engine/texture.hh" #include #include @@ -70,7 +70,7 @@ public: // 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. + // center of each primitive's box. Double-sided materials are drawn with face culling turned off for that draw. // shading = Pbrならマテリアルは金属・粗さ・遮蔽などのテクスチャごとPbrMaterialで設定する(第24章) // With shading = Pbr the materials are set as PbrMaterial, with their metallic-roughness, occlusion... maps (ch. 24) void draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, ModelPass pass, @@ -78,14 +78,14 @@ public: // 形だけを描く:マテリアルもテクスチャも設定せず、ノードごとにuModelだけ(シェーダーが使っていればuNormalMatrixも)。 // 深度の表示、輪郭、のちの影(第23章)のように、色を使わないパス用。 // Draws the shape only: no materials or textures, just uModel per node (and uNormalMatrix if the shader uses it). - // For passes that need no colour: the depth view, outlines, and later shadows (chapter 23). + // For passes that need no color: the depth view, outlines, and later shadows (chapter 23). void drawGeometry(const Shader &shader, const Mat4 &transform) const; // 影の地図の深度だけを描く(第23章)。OpaqueとMaskのプリミティブ(Blendは影を落とさない)。Maskのマテリアルは // ベースカラーのテクスチャ(なければwhite)をユニット0に繋ぎ、uAlphaMask = 1、uAlphaCutoff、uBaseAlphaを設定する // (シェーダーがdiscardで葉の形に切り抜く)。ほかはuAlphaMask = 0。両面のマテリアルはカリングを切る。 // Draws depth only, for shadow maps (chapter 23). Opaque and Mask primitives (Blend casts no shadow). For Mask - // materials the base colour texture (or white) goes on unit 0 and uAlphaMask = 1, uAlphaCutoff and uBaseAlpha are + // materials the base color texture (or white) goes on unit 0 and uAlphaMask = 1, uAlphaCutoff and uBaseAlpha are // set (the shader discards to cut out leaves); otherwise uAlphaMask = 0. Double-sided materials turn culling off. void drawDepth(const Shader &shader, const Mat4 &transform, const Texture2D &white) const; diff --git a/src/pbr_material.hh b/engine/include/engine/pbr_material.hh similarity index 94% rename from src/pbr_material.hh rename to engine/include/engine/pbr_material.hh index 670e5b8..42b3dbf 100644 --- a/src/pbr_material.hh +++ b/engine/include/engine/pbr_material.hh @@ -2,11 +2,11 @@ // glTF's metallic-roughness model #pragma once -#include "gltf.hh" -#include "material.hh" -#include "mathx.hh" -#include "shader.hh" -#include "texture.hh" +#include "engine/gltf.hh" +#include "engine/material.hh" +#include "engine/mathx.hh" +#include "engine/shader.hh" +#include "engine/texture.hh" // テクスチャはすべて「係数 × テクスチャ」。ないテクスチャには白を繋ぐ(白 × 係数 = 係数)。 // Every texture is "factor × texture". A missing texture is replaced by white (white × factor = factor). diff --git a/engine/include/engine/pixel_canvas.hh b/engine/include/engine/pixel_canvas.hh new file mode 100644 index 0000000..89e607e --- /dev/null +++ b/engine/include/engine/pixel_canvas.hh @@ -0,0 +1,34 @@ +// ピクセルアート用の低解像度のキャンバス(第25章):仮想解像度のFBOに描いて、整数倍に拡大して画面に出す +// A low-resolution canvas for pixel art (chapter 25): draw into an FBO at the virtual resolution, then scale it up by +// a whole number onto the screen +#pragma once + +#include "engine/camera2d.hh" +#include "engine/framebuffer.hh" + +// 回転や半端な位置のスプライトも、画面ではピクセルの格子に乗る(本物の低解像度)。 +// 画面の解像度で直接描く(Camera2D+letterbox)と、回転した物が細かいピクセルで描かれる:好みで選ぶ +// Rotated or sub-pixel sprites still land on the pixel grid on screen (a true low resolution). +// Drawing straight at screen resolution (Camera2D + letterbox) renders rotated things with finer pixels: pick what +// you prefer +class PixelCanvas { +public: + PixelCanvas(int width, int height); + + // キャンバスに描き始める:FBOを繋ぎ、ビューポートを全体にしてclearColorで塗る + // Starts drawing into the canvas: binds the FBO, sets a full viewport and clears it to clearColor + void begin(Vec4 clearColor) const; + // 画面へ:既定のフレームバッファをbarColorで塗り、真ん中にGL_NEARESTで拡大コピー(glBlitNamedFramebuffer)。 + // 使った場所(マウスの変換に使える)を返す。glClearColorは変わったまま + // To the screen: clears the default framebuffer to barColor and copies the canvas into the middle, scaled with + // GL_NEAREST (glBlitNamedFramebuffer). Returns where it went (useful for the mouse). Leaves glClearColor changed + Viewport present(int windowWidth, int windowHeight, bool integerScale = true, Vec4 barColor = {0, 0, 0, 1}) const; + + int width() const { return fbo.width(); } + int height() const { return fbo.height(); } + Vec2 size() const { return {static_cast(fbo.width()), static_cast(fbo.height())}; } + const Framebuffer &framebuffer() const { return fbo; } + +private: + Framebuffer fbo; +}; diff --git a/engine/include/engine/rect.hh b/engine/include/engine/rect.hh new file mode 100644 index 0000000..fd378a4 --- /dev/null +++ b/engine/include/engine/rect.hh @@ -0,0 +1,25 @@ +// 2Dの長方形(第25章):スプライトの位置と大きさ、UVの範囲、当たり判定の箱(第26章) +// A 2D rectangle (chapter 25): sprite positions and sizes, UV ranges, collision boxes (chapter 26) +#pragma once + +#include "engine/mathx.hh" + +// 軸に平行な長方形。2Dの座標はy下向き(左上が原点)なので、(x, y)が左上、x + w が右、y + h が下 +// An axis-aligned rectangle. 2D coordinates point y down (origin at the top left), so (x, y) is the top-left corner, +// x + w the right edge and y + h the bottom edge +struct Rect { + float x = 0.0f, y = 0.0f, w = 0.0f, h = 0.0f; + + float left() const { return x; } + float right() const { return x + w; } + float top() const { return y; } + float bottom() const { return y + h; } + Vec2 position() const { return {x, y}; } + Vec2 size() const { return {w, h}; } + Vec2 centre() const { return {x + 0.5f * w, y + 0.5f * h}; } + + // 中心と大きさから / from a center and a size + static Rect fromCentre(Vec2 c, Vec2 size) { return {c.x - 0.5f * size.x, c.y - 0.5f * size.y, size.x, size.y}; } + // dだけずらした長方形 / the rectangle moved by d + Rect translated(Vec2 d) const { return {x + d.x, y + d.y, w, h}; } +}; diff --git a/engine/include/engine/renderer3d.hh b/engine/include/engine/renderer3d.hh new file mode 100644 index 0000000..a23a599 --- /dev/null +++ b/engine/include/engine/renderer3d.hh @@ -0,0 +1,133 @@ +// 3Dのフレームの部品(第20〜24章のmain.ccから移したもの):影の地図とHDRの後処理の流れ +// Pieces of a 3D frame (moved from the main.cc of chapters 20-24): the shadow map and the HDR post-processing chain +#pragma once + +#include "engine/framebuffer.hh" +#include "engine/mathx.hh" +#include "engine/shader.hh" +#include "engine/uniforms.hh" + +#include + +// 平行光源の光から見た行列:centreを中心とする半径radiusの球を正射影の箱に収める(第23章)。箱は影の地図の +// 1テクセル単位で動かす(カメラが動いても影の縁がちらつかない)。depthRangeに箱の奥行き(m)を返す +// The directional light's matrix: an orthographic box enclosing the sphere (`centre`, `radius`) (chapter 23). The box +// moves in whole shadow-map texels (shadow edges do not shimmer when the camera moves). Returns the box depth (m) in +// depthRange +Mat4 lightSpaceMatrix(Vec3 lightDir, Vec3 centre, float radius, int mapSize, float &depthRange); + +// 球(光の箱を合わせる範囲) / a sphere (what the light box is fitted to) +struct BoundingSphere { + Vec3 centre; + float radius = 1.0f; +}; + +// カメラの視錐台のnearDist〜farDistの部分を囲む球(第23章のJ)。中心は8つの角の平均、半径は一番遠い角まで: +// カメラが回っても大きさが変わらないので、影の地図のテクセルの大きさも変わらない +// The sphere around the camera frustum between nearDist and farDist (chapter 23, key J). Center = the mean of the 8 +// corners, radius = to the farthest corner: its size does not change as the camera turns, so neither does the size +// of a shadow-map texel +BoundingSphere frustumSphere(Vec3 eye, Vec3 forward, float fovY, float aspect, float nearDist, float farDist); + +// 影のバイアス(第23章)。inTexelsなら値は影の地図の1テクセルのワールドでの大きさの倍数(地図の大きさを変えても +// 効き目が同じ)、そうでなければメートル。既定値は第23・24章の既定(0.5 / 1 / 3テクセル) +// The shadow biases (chapter 23). With inTexels the values are multiples of one shadow-map texel's world size (they +// work the same at any map size), otherwise meters. The defaults are those of chapters 23-24 (0.5 / 1 / 3 texels) +struct ShadowBias { + float constant = 0.5f; // 一定のバイアス / constant bias + float slope = 1.0f; // tanθ当たり / per unit of tan θ + float normalOffset = 3.0f; // 法線方向のずらし / push along the normal + bool inTexels = true; +}; + +// バイアスを0〜1の深度(正射影なので深度は距離に比例)とメートルに直してblockに書く +// Converts the biases to 0..1 depth (orthographic: depth is proportional to distance) and meters, and writes them into +// block +void applyShadowBias(ShadowBlock &block, const ShadowBias &bias, float radius, int mapSize, float depthRange); + +// 平行光源の影の地図(第23章):深度テクスチャのFBO+Shadowブロック(結合点2)。使い方: +// shadow.begin(sunDir, sphere); … 影を落とす物をshadow.vert/.frag+Model::drawDepthで描く … shadow.end(); +// end()が深度テクスチャをユニット5に繋ぐ。enabled = falseでもbegin/endを呼ぶ(UBOが「影なし」になる) +// A directional shadow map (chapter 23): a depth-texture FBO + the Shadow block (binding 2). Usage: +// shadow.begin(sunDir, sphere); ... draw the casters with shadow.vert/.frag + Model::drawDepth ... shadow.end(); +// end() binds the depth texture to unit 5. Call begin/end even when disabled (the UBO then says "no shadows") +class ShadowMap { +public: + static constexpr GLuint kUnit = 5; // テクスチャユニット / texture unit + + explicit ShadowMap(int size = 2048); + + // 光の箱を合わせてShadowブロックを更新する。enabledなら影の地図に描く準備(bind・深度クリア・深度テスト・ + // 裏面カリング)をしてtrueを返す。falseなら何も描かないこと + // Fits the light box and updates the Shadow block. When enabled, prepares drawing into the map (bind, depth clear, + // depth test, back-face culling) and returns true. When it returns false, draw nothing + bool begin(Vec3 lightDir, const BoundingSphere &fit, const ShadowBias &bias = {}, + ShadowFilter filter = ShadowFilter::Pcf3x3, bool enabled = true); + // 深度テクスチャをユニット5に繋ぐ(描き終わってから) / binds the depth texture to unit 5 (after drawing) + void end() const; + + // 地図の大きさを変える(FBOを作り直す) / changes the map size (re-creates the FBO) + void resize(int size); + int size() const { return fbo.width(); } + bool complete() const { return fbo.complete(); } + const Texture2D &depth() const { return fbo.depth(); } + const ShadowBlock &block() const { return current; } + // 1テクセルがワールドで何メートルか(最後のbeginの値) / how many meters one texel covers (from the last begin) + float metresPerTexel() const { return texelMetres; } + +private: + Framebuffer fbo; + UniformBuffer ubo{kShadowBinding}; + ShadowBlock current; + float texelMetres = 0.0f; +}; + +// HDRの後処理の流れ(第20・21章):MSAAのRGBA16F × 2(色+明るい部分、MRT)に描き → 解決 → 半分の大きさで +// ブルームのぼかし(横・縦のピンポン) → post.fragで露出・トーンマッピング・sRGB・効果を掛けて画面へ。 +// Postブロック(結合点3)も持つ:場面のシェーダーがuBloomThresholdを読むので、beginSceneの前にsettingsを決める +// The HDR post-processing chain (chapters 20-21): draw into a multisampled RGBA16F × 2 target (color + bright part, +// MRT) → resolve → bloom blur at half size (horizontal/vertical ping-pong) → post.frag applies exposure, tone mapping, +// sRGB and the effect on the way to the screen. It also owns the Post block (binding 3): the scene shaders read +// uBloomThreshold, so set `settings` before beginScene +struct PostChainSettings { + int samples = 4; // 0 = MSAAなし / no MSAA(llvmpipeで速い / faster on llvmpipe) + GLenum format = GL_RGBA16F; // GL_R11F_G11F_B10Fも可 / GL_R11F_G11F_B10F also works + int bloomPasses = 4; // 横+縦の組の数(0 = ぼかさない) / number of horizontal + vertical pairs (0 = no blur) +}; + +class PostChain { +public: + static std::optional create(int width, int height, const PostChainSettings &settings = {}); + + // ウィンドウの大きさが変わったとき / when the window size changes + void resize(int width, int height); + // Postブロックをアップロードし、場面のFBOに切り替える(ビューポートも)。クリアは呼ぶ側で + // Uploads the Post block and binds the scene FBO (and its viewport). Clearing is up to the caller + void beginScene(); + // 解決(MSAA → 普通のFBO)とブルーム。深度テストは切られる / resolve (MSAA → ordinary FBO) and bloom. Turns the + // depth test off + void endScene(); + // 画面(既定のフレームバッファ)へ:場面+ブルーム → post.frag。effectは第17章の1〜6のキー(0 = なし) + // To the screen (the default framebuffer): scene + bloom → post.frag. effect = the chapter 17 keys 1-6 (0 = none) + void present(int windowWidth, int windowHeight, int effect = 0); + // シェーダーを読み直す / reloads the shaders + bool reload(); + + PostBlock settings; // 露出・ブルーム・トーンマッピング… / exposure, bloom, tone mapping... + + const Framebuffer &scene() const { return sceneFbo; } // 解決後(色0 = 場面、色1 = 明るい部分) / after the resolve + // ぼかした明るい部分:最後の縦のパスの結果。bloomPasses = 0ならぼかす前の明るい部分(全体の大きさ) + // The blurred bright part: the result of the last vertical pass. With bloomPasses = 0 the unblurred bright part + // (full size) + const Texture2D &bloom() const { return config.bloomPasses > 0 ? bloomFbo[1].color() : sceneFbo.color(1); } + +private: + PostChain() = default; + + PostChainSettings config; + std::optional post, blur; + Framebuffer msaaFbo, sceneFbo; + Framebuffer bloomFbo[2]; + FullscreenTriangle fullscreen; + std::optional> ubo; +}; diff --git a/src/shader.hh b/engine/include/engine/shader.hh similarity index 99% rename from src/shader.hh rename to engine/include/engine/shader.hh index 9a91427..e205bdc 100644 --- a/src/shader.hh +++ b/engine/include/engine/shader.hh @@ -1,7 +1,7 @@ // シェーダープログラム / a shader program #pragma once -#include "mathx.hh" +#include "engine/mathx.hh" #include diff --git a/src/shapes.hh b/engine/include/engine/shapes.hh similarity index 83% rename from src/shapes.hh rename to engine/include/engine/shapes.hh index 32653d9..43ad8a9 100644 --- a/src/shapes.hh +++ b/engine/include/engine/shapes.hh @@ -3,16 +3,16 @@ // in the OpenGL convention (v grows upwards) #pragma once -#include "mesh.hh" +#include "engine/mesh.hh" // 原点を中心とした大きさsizeの箱。UVはメートル単位でtileSizeごとに繰り返す(伸びない:壁、柱、段に。第22章) -// A box of the given size centred on the origin. UVs are in metres, repeating every tileSize (no stretching: for walls, +// A box of the given size centered on the origin. UVs are in meters, repeating every tileSize (no stretching: for walls, // pillars, steps; chapter 22) Mesh makeBox(Vec3 size, float tileSize = 1.0f); // 原点を中心とした1×1×1の立方体。面ごとに頂点4つ(UVと法線が面ごとに違うので共有できない)=24頂点、36インデックス。 // 外から見て反時計回り(第16章のカリング用)。 -// A 1×1×1 cube centred on the origin. 4 vertices per face (UVs and normals differ per face, so corners +// A 1×1×1 cube centered on the origin. 4 vertices per face (UVs and normals differ per face, so corners // cannot be shared) = 24 vertices, 36 indices. Counter-clockwise seen from outside (for culling in chapter 16). Mesh makeCube(); @@ -22,8 +22,8 @@ Mesh makePlane(float size, float uvRepeat); // 原点を中心とした直径1の球(UV球)。segments = 経度方向の分割数、rings = 緯度方向の分割数。 // 法線は中心から外向き。立方体と同じく外から見て反時計回り。 -// 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. +// A sphere of diameter 1 centered on the origin (a UV sphere). segments = divisions around, rings = from pole to pole. +// The normals point outwards from the center. Counter-clockwise seen from outside, like the cube. Mesh makeSphere(int segments = 32, int rings = 16); // 縦の1×1の板をcount枚、Y軸の周りに等間隔で回して重ねたもの(草の株)。原点は下の辺の真ん中、UVのv = 0が下。 diff --git a/engine/include/engine/sprite_batch.hh b/engine/include/engine/sprite_batch.hh new file mode 100644 index 0000000..dd182a2 --- /dev/null +++ b/engine/include/engine/sprite_batch.hh @@ -0,0 +1,140 @@ +// スプライトバッチ(第25章):たくさんの四角形を一つの動的な頂点バッファにまとめ、テクスチャごとに一度に描く +// The sprite batch (chapter 25): collects many quads into one dynamic vertex buffer and draws them with one draw call +// per texture +#pragma once + +#include "engine/buffer.hh" +#include "engine/mathx.hh" +#include "engine/rect.hh" +#include "engine/shader.hh" +#include "engine/texture.hh" + +#include +#include +#include + +// 色:sRGBの値(画像編集ソフトと同じ)、アルファはそのまま(乗算前)。0xRRGGBBAAから作れる +// Colors: sRGB values (as in image editors), straight (not premultiplied) alpha. Can be made from 0xRRGGBBAA +constexpr Vec4 hexColor(std::uint32_t rrggbbaa) { + return {static_cast((rrggbbaa >> 24) & 0xFF) / 255.0f, static_cast((rrggbbaa >> 16) & 0xFF) / 255.0f, + static_cast((rrggbbaa >> 8) & 0xFF) / 255.0f, static_cast(rrggbbaa & 0xFF) / 255.0f}; +} +constexpr Vec4 kWhite = {1.0f, 1.0f, 1.0f, 1.0f}; + +// 一枚のスプライト(四角形)。位置・大きさはワールドの単位(ふつうは仮想ピクセル、y下向き) +// One sprite (a quad). Position and size are in world units (usually virtual pixels, y down) +struct Sprite { + const Texture2D *texture = nullptr; // nullptr = 白(色だけの四角形) / white (a plain colored rectangle) + Vec2 position; // originが来る場所 / where `origin` ends up + Vec2 size = {16.0f, 16.0f}; // 描く大きさ / drawn size + Rect uv = {0.0f, 0.0f, 1.0f, 1.0f}; // テクスチャの範囲(0〜1、左上がv = 0) / texture area (0..1, v = 0 at the top) + Vec2 origin = {0.0f, 0.0f}; // 回転と位置の基準(大きさに対する割合:(0.5, 0.5) = 中心) / pivot for rotation + // and position (fraction of the size: (0.5, 0.5) = the center) + float rotation = 0.0f; // ラジアン、画面上で時計回り / radians, clockwise on screen + Vec4 color = kWhite; // 掛ける色(sRGB、アルファ) / tint (sRGB, alpha) + float layer = 0.0f; // SpriteSort::Layerの順番:大きいほど手前 / order for SpriteSort::Layer: larger + // is in front + bool flipX = false, flipY = false; // 左右・上下反転(向きを変えたキャラクター) / mirror (a character turning round) +}; + +// end()でどう並べてから描くか / how sprites are ordered before drawing in end() +enum class SpriteSort { + None, // 描いた順のまま。テクスチャが変わるたびに描画コールが一つ増える / submission order; every texture change + // costs one more draw call + Texture, // テクスチャごとにまとめる(描画コール最少)。重なりの順番は保証しない / grouped by texture (fewest draw + // calls); overlap order is not kept + Layer, // layerの小さい順(奥から手前)。同じlayerの中ではテクスチャごと、同じテクスチャなら描いた順 + // by layer, small first (back to front); within one layer grouped by texture, then submission order +}; + +// 混ぜ方。テクスチャも色も乗算済みアルファで扱う / blending. Textures and colors are handled as premultiplied alpha +enum class SpriteBlend { + Alpha, // ふつうの半透明(GL_ONE, GL_ONE_MINUS_SRC_ALPHA) / ordinary transparency + Additive, // 足す(光・炎・爆発)(GL_ONE, GL_ONE) / adds up (light, fire, explosions) +}; + +// 頂点データの送り方 / how vertex data reaches the GPU +enum class SpriteUpload { + SubData, // glNamedBufferSubData:毎回コピー。簡単で、ドライバーが同期を面倒見る / a copy per draw call; simple, the + // driver handles synchronization + Persistent, // 永続マップ(GL_MAP_PERSISTENT_BIT):バッファに直接書く。3つの区画を回し、フェンスで待つ + // persistent mapping: write straight into the buffer; three regions in turn, guarded by fences +}; + +struct SpriteBatchSettings { + int capacity = 8192; // 一回の描画コールのスプライトの最大数 / the most sprites in one draw call + SpriteUpload upload = SpriteUpload::SubData; +}; + +// 直前のend()の結果 / what the last end() did +struct SpriteStats { + int sprites = 0; + int drawCalls = 0; +}; + +// 頂点:位置、UV、色(RGBA8、0〜1に正規化)。20バイト / a vertex: position, UV, color (RGBA8 normalized to 0..1); +// 20 bytes +struct SpriteVertex { + Vec2 position; + Vec2 uv; + std::uint32_t color; // R = 下位バイト / R = lowest byte +}; + +// スプライトバッチ(RAII、コピー不可・移動可)。使い方: +// batch.begin(camera.matrix()); batch.draw(sprite); … batch.end(); +// end()が並べ替えて描く。end()の後は:ブレンドon、深度テストoff、カリングoff(3Dに戻るときは設定し直す) +// The sprite batch (RAII, non-copyable, movable). Usage: +// batch.begin(camera.matrix()); batch.draw(sprite); ... batch.end(); +// end() sorts and draws. After end(): blending on, depth test off, culling off (set them again when going back to 3D) +class SpriteBatch { +public: + // シェーダー engine/shaders/sprite.vert/.frag を読む。失敗したらstd::nullopt + // Loads the shader engine/shaders/sprite.vert/.frag. std::nullopt on failure + static std::optional create(const SpriteBatchSettings &settings = {}); + ~SpriteBatch(); + SpriteBatch(const SpriteBatch &) = delete; + SpriteBatch &operator=(const SpriteBatch &) = delete; + SpriteBatch(SpriteBatch &&other) noexcept; + SpriteBatch &operator=(SpriteBatch &&other) noexcept; + + // viewProjection = Camera2D::matrix()(ワールド → クリップ座標) / Camera2D::matrix() (world → clip space) + void begin(const Mat4 &viewProjection, SpriteSort sort = SpriteSort::None, SpriteBlend blend = SpriteBlend::Alpha); + void draw(const Sprite &sprite); + // 色だけの長方形と、その枠(当たり判定の箱の表示など) / a plain colored rectangle and its outline (e.g. to show + // collision boxes) + void drawRect(const Rect &rect, Vec4 color, float layer = 0.0f); + void drawRectOutline(const Rect &rect, Vec4 color, float thickness = 1.0f, float layer = 0.0f); + void end(); + + const SpriteStats &stats() const { return lastStats; } + SpriteUpload upload() const { return settings.upload; } + +private: + SpriteBatch() = default; + // 頂点4つ分の四角形と、並べ替えに要る物 / one quad's 4 vertices plus what sorting needs + struct Quad { + SpriteVertex v[4]; + const Texture2D *texture; + float layer; + }; + void flush(const std::vector &order, size_t first, size_t count, const Texture2D &texture); + void release(); + + SpriteBatchSettings settings; + std::optional shader; + Buffer vertexBuffer, indexBuffer; + GLuint vao = 0; + Texture2D white; // 色だけの四角形用の1×1 / 1 × 1, for plain rectangles + + // 永続マップ / persistent mapping + static constexpr int kRegions = 3; + SpriteVertex *mapped = nullptr; + GLsync fences[kRegions] = {}; + int region = 0, regionUsed = 0; // 今の区画と、そこで使ったスプライトの数 / the current region and sprites used there + + std::vector quads; + std::vector staging; // SubData用の書き込み先 / where SubData writes first + SpriteSort sortMode = SpriteSort::None; + SpriteStats lastStats, currentStats; + bool begun = false; +}; diff --git a/engine/include/engine/sprite_sheet.hh b/engine/include/engine/sprite_sheet.hh new file mode 100644 index 0000000..c97946a --- /dev/null +++ b/engine/include/engine/sprite_sheet.hh @@ -0,0 +1,74 @@ +// スプライトシート(アトラス):一枚のテクスチャにたくさんのコマ(第25章) +// Sprite sheets (atlases): many frames in one texture (chapter 25) +#pragma once + +#include "engine/animation.hh" +#include "engine/rect.hh" +#include "engine/sprite_batch.hh" +#include "engine/texture.hh" + +#include +#include +#include +#include +#include + +enum class TextureFilter { + Nearest, // ピクセルアート:くっきり(GL_NEAREST) / pixel art: crisp (GL_NEAREST) + Linear, // 滑らか(GL_LINEAR):拡大するとぼける / smooth (GL_LINEAR): blurry when enlarged +}; + +// 2D用の画像を読む:上下反転なし(一番上の行がv = 0)、ミップマップなし、乗算済みアルファ、端はCLAMP_TO_EDGE。 +// 色の値はsRGBのまま(GL_RGBA8):2Dの色は画像編集ソフトで見たとおりに混ぜる(第25章) +// Loads an image for 2D: no flip (the top row is v = 0), no mipmaps, premultiplied alpha, CLAMP_TO_EDGE. +// The colors stay sRGB-encoded (GL_RGBA8): 2D colors blend exactly as seen in an image editor (chapter 25) +std::optional loadSpriteTexture(const std::string &path, TextureFilter filter = TextureFilter::Nearest); + +// スプライトシート(RAII、コピー不可・移動可):テクスチャを持ち、コマ(ピクセルの長方形)と名前とクリップを覚える +// A sprite sheet (RAII, non-copyable, movable): owns the texture and knows the frames (pixel rectangles), their names +// and the animation clips +class SpriteSheet { +public: + // 格子のシート:cellWidth × cellHeightのコマが左上から右へ、行ごとに並ぶ。margin = 外側の余白、spacing = コマの間の + // 隙間(にじみ防止、第25章)。コマの名前は番号 / a grid sheet: cellWidth × cellHeight frames from the top left to the + // right, row by row. margin = the outer border, spacing = the gap between frames (against bleeding, chapter 25). + // Frames are known by number + static std::optional loadGrid(const std::string &imagePath, int cellWidth, int cellHeight, int margin = 0, + int spacing = 0, TextureFilter filter = TextureFilter::Nearest); + // アトラスの説明ファイル(.atlas、テキスト)から。1行に1つ / from an atlas description file (.atlas, text), one + // entry per line: + // image <ファイル> 画像(.atlasのフォルダからの相対パス) / the image (relative to the .atlas) + // sprite <名前> <幅> <高さ> コマ(ピクセル、左上が原点) / a frame (pixels, origin top left) + // clip <名前> <コマ…> アニメーション(コマは名前で) / an animation (frames by name) + // # … コメント / comment + static std::optional loadAtlas(const std::string &atlasPath, TextureFilter filter = TextureFilter::Nearest); + + const Texture2D &texture() const { return image; } + int count() const { return static_cast(frames.size()); } + // コマの長方形。範囲外の番号(Animator::frame()の-1など)は空の長方形(大きさ0:何も描かれない)になり、 + // 最初の一回だけstderrに知らせる / a frame's rectangle. An index out of range (such as Animator::frame()'s -1) + // gives an empty rectangle (size 0: nothing is drawn), reported once on stderr + Rect pixels(int index) const; // ピクセル / pixels + Rect uv(int index) const; // 0〜1 + Vec2 size(int index) const { return pixels(index).size(); } + // 名前でコマを探す(なければ-1) / finds a frame by name (-1 if missing) + int find(std::string_view name) const; + // クリップ(なければnullptr) / a clip (nullptr if missing) + const AnimationClip *clip(std::string_view name) const; + void addClip(AnimationClip clip) { clips.push_back(std::move(clip)); } + + // そのコマのSprite:テクスチャ・UV・大きさ(ピクセル × scale)を埋める。位置などは後から変える + // A Sprite for that frame: fills in the texture, UVs and size (pixels × scale); change position etc. afterwards + Sprite sprite(int index, Vec2 position, Vec2 origin = {0.0f, 0.0f}, float scale = 1.0f) const; + +private: + SpriteSheet() = default; + + Texture2D image; + std::vector frames; + std::vector names; // framesと同じ順(格子なら空) / same order as frames (empty for grids) + // dequeは後ろに足しても要素が動かない:clip()が返したポインタはaddClipの後も使える + // A deque never moves its elements when appending: pointers returned by clip() stay valid after addClip + std::deque clips; + mutable bool warnedIndex = false; // 範囲外の番号を一度知らせた / an out-of-range index was reported +}; diff --git a/src/tangents.hh b/engine/include/engine/tangents.hh similarity index 98% rename from src/tangents.hh rename to engine/include/engine/tangents.hh index fdfdde0..1c2dfa8 100644 --- a/src/tangents.hh +++ b/engine/include/engine/tangents.hh @@ -2,7 +2,7 @@ // Computing tangents (chapter 22): for every vertex, which surface directions a normal map's "right" and "up" are #pragma once -#include "mesh.hh" +#include "engine/mesh.hh" #include #include diff --git a/src/texture.hh b/engine/include/engine/texture.hh similarity index 93% rename from src/texture.hh rename to engine/include/engine/texture.hh index 09c4b7a..ea44690 100644 --- a/src/texture.hh +++ b/engine/include/engine/texture.hh @@ -13,13 +13,13 @@ struct TextureOptions { bool mipmaps = true; // ミップマップを作る / build mipmaps // 色の画像(ベースカラー、発光)はtrue:GL_SRGB8_ALPHA8になり、読むときにGPUがリニアに直す(第21章)。 // データ(法線、金属・粗さ、遮蔽、高さ)はfalseのまま:値そのものに意味がある - // true for colour images (base colour, emission): the texture becomes GL_SRGB8_ALPHA8 and the GPU converts to + // true for color images (base color, emission): the texture becomes GL_SRGB8_ALPHA8 and the GPU converts to // linear when sampling (chapter 21). Keep false for data (normals, metallic-roughness, occlusion, height): the // values themselves mean something bool srgb = false; // RGBにアルファを掛けてからアップロードする(乗算済みアルファ、第16章)。ミップマップもその値から作られる。 // Multiply RGB by alpha before uploading (premultiplied alpha, chapter 16). Mipmaps are then built from those values. - // srgbなら、リニアに直してから掛けてsRGBに戻す(第21章) / with srgb the colour is converted to linear, multiplied and + // srgbなら、リニアに直してから掛けてsRGBに戻す(第21章) / with srgb the color is converted to linear, multiplied and // converted back to sRGB (chapter 21) bool premultiplyAlpha = false; }; @@ -63,7 +63,7 @@ public: void setFilter(GLenum minFilter, GLenum magFilter); void setWrap(GLenum wrapS, GLenum wrapT); // GL_CLAMP_TO_BORDERで外側を読んだときの色(影の地図では1 = 一番奥 = 影なし、第23章) - // The colour read outside with GL_CLAMP_TO_BORDER (1 = farthest = not in shadow for shadow maps, chapter 23) + // The color read outside with GL_CLAMP_TO_BORDER (1 = farthest = not in shadow for shadow maps, chapter 23) void setBorderColor(float r, float g, float b, float a); // 深度テクスチャの比較モード(第23章):onなら sampler2DShadow で texture(s, vec3(uv, 深さ)) が // 「深さ <= 保存された深度」の結果(0か1、GL_LINEARなら周りの4テクセルの結果の補間)を返す diff --git a/src/uniforms.hh b/engine/include/engine/uniforms.hh similarity index 99% rename from src/uniforms.hh rename to engine/include/engine/uniforms.hh index 840124f..b12838a 100644 --- a/src/uniforms.hh +++ b/engine/include/engine/uniforms.hh @@ -2,7 +2,7 @@ // Uniform buffers (UBOs): blocks of uniforms shared by many shaders (chapter 19) #pragma once -#include "buffer.hh" +#include "engine/buffer.hh" #include diff --git a/src/window.hh b/engine/include/engine/window.hh similarity index 100% rename from src/window.hh rename to engine/include/engine/window.hh diff --git a/shaders/blur.frag b/engine/shaders/blur.frag similarity index 93% rename from shaders/blur.frag rename to engine/shaders/blur.frag index ca3f446..1b1e2eb 100644 --- a/shaders/blur.frag +++ b/engine/shaders/blur.frag @@ -12,8 +12,8 @@ layout(location = 0) out vec4 out_color; void main() { // 9タップのガウス(パスカルの三角形の12段目から両端の1と12を除いた物:中央924、左右に792, 495, 220, 66、/4070)を、 // 線型補間で5回の読み込みにまとめたもの:隣り合う2テクセルの間を読めば、GPUが重み付きで平均してくれる - // A 9-tap Gaussian (row 12 of Pascal's triangle without the outer 1 and 12: centre 924, then 792, 495, 220, 66 on - // each side, /4070) folded into 5 reads with linear filtering: reading between two neighbouring texels makes the + // A 9-tap Gaussian (row 12 of Pascal's triangle without the outer 1 and 12: center 924, then 792, 495, 220, 66 on + // each side, /4070) folded into 5 reads with linear filtering: reading between two neighboring texels makes the // GPU average them with the right weights const float offsets[3] = float[](0.0, 1.3846153846, 3.2307692308); const float weights[3] = float[](0.2270270270, 0.3162162162, 0.0702702703); diff --git a/shaders/depth.frag b/engine/shaders/depth.frag similarity index 95% rename from shaders/depth.frag rename to engine/shaders/depth.frag index aa59ee9..059586b 100644 --- a/shaders/depth.frag +++ b/engine/shaders/depth.frag @@ -1,5 +1,5 @@ #version 460 core -// 深度バッファの値を灰色で見せる(頂点シェーダーはunlit.vert) / shows depth-buffer values as grey (vertex shader: unlit.vert) +// 深度バッファの値を灰色で見せる(頂点シェーダーはunlit.vert) / shows depth-buffer values as gray (vertex shader: unlit.vert) uniform int uDepthMode; // 1 = そのままの値(非線型) / the raw value (non-linear), 2 = 線型にした距離 / linearised distance uniform float uNearPlane; // カメラのnearPlane / the camera's nearPlane diff --git a/shaders/envmap.frag b/engine/shaders/envmap.frag similarity index 97% rename from shaders/envmap.frag rename to engine/shaders/envmap.frag index 769e881..f9c0c29 100644 --- a/shaders/envmap.frag +++ b/engine/shaders/envmap.frag @@ -16,7 +16,7 @@ layout(std140, binding = 0) uniform Camera { }; uniform int uEnvMode; // 0 = 反射 / reflection, 1 = 屈折 / refraction, 2 = フレネル(ガラス) / Fresnel (glass) uniform float uIor; // 屈折率(ガラス1.52、水1.33) / index of refraction (glass 1.52, water 1.33) -uniform vec3 uTint; // 反射・屈折の色 / colour of the reflection / refraction +uniform vec3 uTint; // 反射・屈折の色 / color of the reflection / refraction uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) layout(location = 0) out vec4 out_color; diff --git a/shaders/ibl_brdf.frag b/engine/shaders/ibl_brdf.frag similarity index 100% rename from shaders/ibl_brdf.frag rename to engine/shaders/ibl_brdf.frag diff --git a/shaders/ibl_irradiance.frag b/engine/shaders/ibl_irradiance.frag similarity index 98% rename from shaders/ibl_irradiance.frag rename to engine/shaders/ibl_irradiance.frag index 9ca1c90..4e903b7 100644 --- a/shaders/ibl_irradiance.frag +++ b/engine/shaders/ibl_irradiance.frag @@ -3,7 +3,7 @@ // 結果は「白い拡散面がNを向いていたら反射する明るさ」(= 放射照度E / π)。pbr.fragはベースカラーを掛けるだけ // IBL (chapter 24): the irradiance cube map. For each direction N, average the sky light arriving from the whole // hemisphere weighted by cos θ. The result is "how bright a white diffuse surface facing N looks" (= irradiance E / π); -// pbr.frag only multiplies it by the base colour +// pbr.frag only multiplies it by the base color layout(binding = 0) uniform samplerCube uEnvironment; uniform int uFace; uniform float uSize; // この面の大きさ(ピクセル) / this face's size (pixels) diff --git a/shaders/ibl_prefilter.frag b/engine/shaders/ibl_prefilter.frag similarity index 100% rename from shaders/ibl_prefilter.frag rename to engine/shaders/ibl_prefilter.frag diff --git a/shaders/pbr.frag b/engine/shaders/pbr.frag similarity index 97% rename from shaders/pbr.frag rename to engine/shaders/pbr.frag index 437a751..07fe467 100644 --- a/shaders/pbr.frag +++ b/engine/shaders/pbr.frag @@ -72,7 +72,7 @@ layout(std140, binding = 1) uniform Lights { DirectionalLight uDirLight; PointLight uPointLights[MAX_POINT_LIGHTS]; SpotLight uSpotLights[MAX_SPOT_LIGHTS]; - vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness + vec3 uAmbient; // 環境光の色と明るさ / ambient light color and brightness int uPointLightCount; // 使っている数 / how many are in use int uSpotLightCount; }; @@ -100,7 +100,7 @@ layout(std140, binding = 2) uniform Shadow { }; // 0 = 全部、1 = ベースカラー、2 = 金属度、3 = 粗さ、4 = 遮蔽、5 = 法線、6 = 直接光だけ、7 = IBLだけ、8 = 影 -// 0 = everything, 1 = base colour, 2 = metallic, 3 = roughness, 4 = occlusion, 5 = normals, 6 = direct light only, +// 0 = everything, 1 = base color, 2 = metallic, 3 = roughness, 4 = occlusion, 5 = normals, 6 = direct light only, // 7 = IBL only, 8 = shadow uniform int uViewMode; // 0 = 直接光+IBL、1 = 直接光だけ、2 = IBLだけ / 0 = direct + IBL, 1 = direct only, 2 = IBL only @@ -173,14 +173,14 @@ vec3 fresnelSchlickRoughness(float cosTheta, vec3 f0, float roughness) { struct Surface { vec3 n, v; - vec3 base; // ベースカラー(リニア) / base colour (linear) + vec3 base; // ベースカラー(リニア) / base color (linear) float metallic, roughness; vec3 f0; // 正面の反射率:非金属0.04、金属はベースカラー / reflectance at normal incidence: 0.04 for dielectrics, - // the base colour for metals + // the base color for metals }; // 一つの光の直接光。radiance = 面に届く光(光の色 × 減衰 × 影) -// Direct light from one light. radiance = the light reaching the surface (light colour × attenuation × shadow) +// Direct light from one light. radiance = the light reaching the surface (light color × attenuation × shadow) vec3 directLight(Surface s, vec3 l, vec3 radiance) { float nDotL = max(dot(s.n, l), 0.0); if (nDotL <= 0.0) return vec3(0.0); @@ -196,7 +196,7 @@ vec3 directLight(Surface s, vec3 l, vec3 radiance) { vec3 kd = (1.0 - f) * (1.0 - s.metallic); // このシリーズの光の色は「正面から照らした白い拡散面の明るさ」(Blinn-Phongと同じ意味)。物理的なランバートは // base/πなので、光の強さをπ倍して同じ明るさにする - // Our light colours mean "how bright a white diffuse surface lit head-on looks" (as with Blinn-Phong). Physical + // Our light colors mean "how bright a white diffuse surface lit head-on looks" (as with Blinn-Phong). Physical // Lambert is base/π, so the light is scaled by π to get the same brightness return (kd * s.base / PI + specular) * radiance * PI * nDotL; } @@ -276,7 +276,7 @@ void main() { uv = parallaxOcclusion(vUv, vec3(dot(toEye, tangent), dot(toEye, bitangent), dot(toEye, geometricNormal)), uvDx, uvDy); } - // ベースカラーとアルファ(第16・20章と同じ扱い) / base colour and alpha (handled as in chapters 16 and 20) + // ベースカラーとアルファ(第16・20章と同じ扱い) / base color and alpha (handled as in chapters 16 and 20) vec4 baseSample = textureGrad(uBaseColorMap, uv, uvDx, uvDy); float alpha = uMaterial.baseColor.a * baseSample.a; float alphaWidth = fwidth(alpha); @@ -328,7 +328,7 @@ void main() { //------------------------------------------------------------------ // IBL:空からの光。拡散 = 放射照度 × ベースカラー、鏡面 = ぼかした映り込み × (F0 · A + B)(スプリットサム) - // IBL: light from the sky. Diffuse = irradiance × base colour, specular = blurred reflection × (F0 · A + B) (split sum) + // IBL: light from the sky. Diffuse = irradiance × base color, specular = blurred reflection × (F0 · A + B) (split sum) //------------------------------------------------------------------ float nDotV = max(dot(s.n, s.v), 1e-4); vec3 f = fresnelSchlickRoughness(nDotV, s.f0, s.roughness); diff --git a/shaders/phong.frag b/engine/shaders/phong.frag similarity index 98% rename from shaders/phong.frag rename to engine/shaders/phong.frag index 7164965..7754c13 100644 --- a/shaders/phong.frag +++ b/engine/shaders/phong.frag @@ -2,14 +2,14 @@ in vec3 vWorldPos; in vec3 vNormal; in vec2 vUv; -in vec3 vTint; // インスタンスの色(第19章) / the instance colour (chapter 19) +in vec3 vTint; // インスタンスの色(第19章) / the instance color (chapter 19) in vec4 vTangent; // ワールド座標の接線、w = 従法線の向き(第22章) / world-space tangent, w = bitangent sign (chapter 22) -// 表面の性質。色はそれぞれのマップと掛け合わされる / surface properties; each colour is multiplied with its map +// 表面の性質。色はそれぞれのマップと掛け合わされる / surface properties; each color is multiplied with its map struct Material { - vec3 diffuse; // 拡散反射の色 / diffuse colour - vec3 specular; // 鏡面反射の色と強さ / specular colour and strength - vec3 emission; // 発光の色 / emission colour + vec3 diffuse; // 拡散反射の色 / diffuse color + vec3 specular; // 鏡面反射の色と強さ / specular color and strength + vec3 emission; // 発光の色 / emission color float shininess; // 光沢度 / shininess float alpha; // 不透明度(diffuseマップのアルファと掛ける) / opacity (multiplied with the diffuse map's alpha) int alphaMode; // 0 = 不透明 / opaque, 1 = マスク / mask (discard), 2 = ブレンド / blend @@ -73,7 +73,7 @@ layout(std140, binding = 1) uniform Lights { DirectionalLight uDirLight; PointLight uPointLights[MAX_POINT_LIGHTS]; SpotLight uSpotLights[MAX_SPOT_LIGHTS]; - vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness + vec3 uAmbient; // 環境光の色と明るさ / ambient light color and brightness int uPointLightCount; // 使っている数 / how many are in use int uSpotLightCount; }; @@ -145,8 +145,8 @@ struct Surface { vec3 position; // ワールド座標 / world space vec3 normal; // 単位ベクトル / unit vector vec3 view; // 目へ向かう単位ベクトル / unit vector towards the eye - vec3 diffuse; // マップを掛けた拡散反射の色 / diffuse colour with the map applied - vec3 specular; // マップを掛けた鏡面反射の色 / specular colour with the map applied + vec3 diffuse; // マップを掛けた拡散反射の色 / diffuse color with the map applied + vec3 specular; // マップを掛けた鏡面反射の色 / specular color with the map applied float shininess; }; @@ -244,7 +244,7 @@ void main() { vec4 base = textureGrad(uDiffuseMap, uv, uvDx, uvDy); float alpha = uMaterial.alpha * base.a; // アルファが1ピクセルでどれだけ変わるか(分岐の前に:fwidthは隣のピクセルと一緒に計算する) - // How much alpha changes across one pixel (before any branch: fwidth is computed together with the neighbours) + // How much alpha changes across one pixel (before any branch: fwidth is computed together with the neighbors) float alphaWidth = fwidth(alpha); if (uMaterial.alphaMode == ALPHA_MASK && uAlphaToCoverage) { // しきい値の前後1ピクセルで0→1になるように鋭くする(そのままだとテクスチャのぼけた縁で半透明が広がる) @@ -253,7 +253,7 @@ void main() { 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) + // マスク:しきい値未満は捨てる(色も深度も書かない) / mask: discard below the threshold (writes neither color nor depth) discard; } // ブレンド:完全に透明なら深度も書かないように捨てる / blend: discard fully transparent pixels so they do not write depth diff --git a/shaders/phong.vert b/engine/shaders/phong.vert similarity index 95% rename from shaders/phong.vert rename to engine/shaders/phong.vert index 149eb5c..4b58275 100644 --- a/shaders/phong.vert +++ b/engine/shaders/phong.vert @@ -24,7 +24,7 @@ out vec3 vNormal; out vec2 vUv; out vec4 vTangent; // ワールド座標の接線と向き / world-space tangent and sign // インスタンスごとの色(第19章)。インスタンシングでないときはこのユニフォーム(既定値は白) -// The per-instance colour (chapter 19). Without instancing it comes from this uniform (white by default) +// The per-instance color (chapter 19). Without instancing it comes from this uniform (white by default) uniform vec3 uTint = vec3(1.0); out vec3 vTint; diff --git a/shaders/phong_instanced.vert b/engine/shaders/phong_instanced.vert similarity index 95% rename from shaders/phong_instanced.vert rename to engine/shaders/phong_instanced.vert index 3c009ca..37e5491 100644 --- a/shaders/phong_instanced.vert +++ b/engine/shaders/phong_instanced.vert @@ -1,6 +1,6 @@ #version 460 core // インスタンシング用のphong.vert:インスタンスごとの行列と色を頂点属性で受け取る(フラグメントシェーダーはphong.frag) -// phong.vert for instancing: the per-instance matrix and colour arrive as vertex attributes (fragment shader: phong.frag) +// phong.vert for instancing: the per-instance matrix and color arrive as vertex attributes (fragment shader: phong.frag) layout(location = 0) in vec3 aPosition; layout(location = 1) in vec3 aNormal; layout(location = 2) in vec2 aUv; diff --git a/shaders/post.frag b/engine/shaders/post.frag similarity index 97% rename from shaders/post.frag rename to engine/shaders/post.frag index b0cd134..bc88674 100644 --- a/shaders/post.frag +++ b/engine/shaders/post.frag @@ -45,7 +45,7 @@ vec3 linearToSrgb(vec3 c) { } // UVの位置の表示用の色(0〜1)。ガンマのモード0と3ではsRGBにした後、1と2ではまだリニア -// The display colour at a UV position (0..1): sRGB-encoded in gamma modes 0 and 3, still linear in 1 and 2 +// The display color at a UV position (0..1): sRGB-encoded in gamma modes 0 and 3, still linear in 1 and 2 vec3 display(vec2 uv) { vec3 hdr = texture(uScene, uv).rgb; if (uPostView == 0) hdr += uBloomStrength * texture(uBloom, uv).rgb; diff --git a/shaders/post.vert b/engine/shaders/post.vert similarity index 100% rename from shaders/post.vert rename to engine/shaders/post.vert diff --git a/shaders/shadow.frag b/engine/shaders/shadow.frag similarity index 79% rename from shaders/shadow.frag rename to engine/shaders/shadow.frag index 8b3b409..19f65b9 100644 --- a/shaders/shadow.frag +++ b/engine/shaders/shadow.frag @@ -1,9 +1,9 @@ #version 460 core // 影の地図のフラグメントシェーダー:色は書かない(深度はGPUが書く)。葉や草は切り抜く -// Shadow-map fragment shader: no colour is written (the GPU writes the depth). Leaves and grass are cut out +// Shadow-map fragment shader: no color is written (the GPU writes the depth). Leaves and grass are cut out in vec2 vUv; -layout(binding = 0) uniform sampler2D uBaseMap; // Maskのときのベースカラー(アルファ) / base colour for Mask (alpha) +layout(binding = 0) uniform sampler2D uBaseMap; // Maskのときのベースカラー(アルファ) / base color for Mask (alpha) uniform bool uAlphaMask; // 切り抜くか / cut out? uniform float uAlphaCutoff; uniform float uBaseAlpha; // マテリアルのアルファ係数 / the material's alpha factor diff --git a/shaders/shadow.vert b/engine/shaders/shadow.vert similarity index 100% rename from shaders/shadow.vert rename to engine/shaders/shadow.vert diff --git a/shaders/shadow_debug.frag b/engine/shaders/shadow_debug.frag similarity index 91% rename from shaders/shadow_debug.frag rename to engine/shaders/shadow_debug.frag index e063ecd..20c692e 100644 --- a/shaders/shadow_debug.frag +++ b/engine/shaders/shadow_debug.frag @@ -1,6 +1,6 @@ #version 460 core // 影の地図を見せる(第23章):深度テクスチャを灰色で。比較なしのサンプラーオブジェクトで読む -// Shows the shadow map (chapter 23): the depth texture as grey. Read through a sampler object without comparison +// Shows the shadow map (chapter 23): the depth texture as gray. Read through a sampler object without comparison in vec2 vUv; layout(binding = 0) uniform sampler2D uDepth; diff --git a/shaders/skybox.frag b/engine/shaders/skybox.frag similarity index 97% rename from shaders/skybox.frag rename to engine/shaders/skybox.frag index d319e79..de4c689 100644 --- a/shaders/skybox.frag +++ b/engine/shaders/skybox.frag @@ -7,7 +7,7 @@ layout(binding = 3) uniform samplerCube uSkybox; uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) uniform float uSunRadiance = 60.0; // 太陽の円盤の明るさ(平行光源の色の倍数、第21章) / the sun disc's brightness - // (a multiple of the directional light's colour, chapter 21) + // (a multiple of the directional light's color, chapter 21) struct DirectionalLight { vec3 direction; @@ -27,7 +27,7 @@ struct SpotLight { vec3 attenuation; }; // 光(結合点1):太陽の向きと色を使う。phong.fragと同じ宣言 / the lights (binding 1): for the sun's direction and -// colour. The same declaration as phong.frag +// color. The same declaration as phong.frag layout(std140, binding = 1) uniform Lights { DirectionalLight uDirLight; PointLight uPointLights[8]; diff --git a/shaders/skybox.vert b/engine/shaders/skybox.vert similarity index 100% rename from shaders/skybox.vert rename to engine/shaders/skybox.vert diff --git a/engine/shaders/sprite.frag b/engine/shaders/sprite.frag new file mode 100644 index 0000000..f889cfc --- /dev/null +++ b/engine/shaders/sprite.frag @@ -0,0 +1,13 @@ +#version 460 core +// スプライト(第25章):テクスチャ × 色。どちらも乗算済みアルファ(ブレンドは GL_ONE, GL_ONE_MINUS_SRC_ALPHA) +// Sprites (chapter 25): texture × color, both premultiplied alpha (blending is GL_ONE, GL_ONE_MINUS_SRC_ALPHA) +in vec2 vUv; +in vec4 vColor; + +layout(binding = 0) uniform sampler2D uTexture; + +layout(location = 0) out vec4 out_color; + +void main() { + out_color = texture(uTexture, vUv) * vColor; +} diff --git a/engine/shaders/sprite.vert b/engine/shaders/sprite.vert new file mode 100644 index 0000000..a9559a6 --- /dev/null +++ b/engine/shaders/sprite.vert @@ -0,0 +1,18 @@ +#version 460 core +// スプライト(第25章):頂点はCPUでワールド座標にしてある。ここでは2Dカメラの行列を掛けるだけ +// Sprites (chapter 25): the CPU already put the vertices in world space; here we only apply the 2D camera's matrix +layout(location = 0) in vec2 aPosition; +layout(location = 1) in vec2 aUv; +layout(location = 2) in vec4 aColor; // RGBA8 → 0〜1(sRGBの値、乗算前のアルファ) / 0..1 (sRGB values, straight alpha) + +uniform mat4 uViewProjection; + +out vec2 vUv; +out vec4 vColor; + +void main() { + vUv = aUv; + // テクスチャは乗算済みアルファなので、掛ける色も乗算済みにする / the textures are premultiplied, so the tint is too + vColor = vec4(aColor.rgb * aColor.a, aColor.a); + gl_Position = uViewProjection * vec4(aPosition, 0.0, 1.0); +} diff --git a/shaders/unlit.frag b/engine/shaders/unlit.frag similarity index 94% rename from shaders/unlit.frag rename to engine/shaders/unlit.frag index 3a3d646..1766ab8 100644 --- a/shaders/unlit.frag +++ b/engine/shaders/unlit.frag @@ -1,6 +1,6 @@ #version 460 core // ライティングなしの一色(光源の目印用)。HDRなので1より明るい色も使える(第21章) -// One colour without lighting (for light markers). HDR, so colours brighter than 1 work (chapter 21) +// One color without lighting (for light markers). HDR, so colors brighter than 1 work (chapter 21) uniform vec3 uColor; layout(location = 0) out vec4 out_color; diff --git a/shaders/unlit.vert b/engine/shaders/unlit.vert similarity index 100% rename from shaders/unlit.vert rename to engine/shaders/unlit.vert diff --git a/engine/src/animation.cc b/engine/src/animation.cc new file mode 100644 index 0000000..edc1f5c --- /dev/null +++ b/engine/src/animation.cc @@ -0,0 +1,42 @@ +#include "engine/animation.hh" + +#include +#include + +void Animator::play(const AnimationClip *clip, bool restart) { + if (clip == current && !restart) return; + current = clip; + elapsed = 0.0f; +} + +void Animator::update(float dt) { + if (!current) return; + elapsed += dt * speed; + // 繰り返すクリップは時間を一周分に収める(長く動かしてもfloatの精度が落ちない)。負のspeedは逆再生: + // 繰り返すクリップは最後へ回り込み、onceのクリップは最初のコマで止まる + // Looping clips keep the time within one cycle (float precision does not degrade over long runs). A negative + // speed plays backwards: looping clips wrap around to the end, once-clips stop on the first frame + float length = current->duration(); + if (current->loop && length > 0.0f) { + elapsed = std::fmod(elapsed, length); + if (elapsed < 0.0f) elapsed += length; + } else if (elapsed < 0.0f) { + elapsed = 0.0f; + } +} + +int Animator::frameIndex() const { + if (!current || current->frames.empty()) return -1; + int count = static_cast(current->frames.size()); + int i = static_cast(std::floor(elapsed * current->fps)); + return current->loop ? i % count : std::min(i, count - 1); +} + +int Animator::frame() const { + int i = frameIndex(); + return i < 0 ? -1 : current->frames[static_cast(i)]; +} + +bool Animator::finished() const { + return current && !current->loop && elapsed * current->fps >= static_cast(current->frames.size()); +} diff --git a/src/buffer.cc b/engine/src/buffer.cc similarity index 96% rename from src/buffer.cc rename to engine/src/buffer.cc index 3262bc9..2ceb97b 100644 --- a/src/buffer.cc +++ b/engine/src/buffer.cc @@ -1,4 +1,4 @@ -#include "buffer.hh" +#include "engine/buffer.hh" #include diff --git a/src/camera.cc b/engine/src/camera.cc similarity index 98% rename from src/camera.cc rename to engine/src/camera.cc index d9ab0d8..91eb9e7 100644 --- a/src/camera.cc +++ b/engine/src/camera.cc @@ -1,4 +1,4 @@ -#include "camera.hh" +#include "engine/camera.hh" #include #include diff --git a/engine/src/camera2d.cc b/engine/src/camera2d.cc new file mode 100644 index 0000000..64f9921 --- /dev/null +++ b/engine/src/camera2d.cc @@ -0,0 +1,57 @@ +#include "engine/camera2d.hh" + +#include + +#include +#include + +Mat4 Camera2D::matrix() const { + Vec2 c = centre; + if (pixelSnap) { + // 画面のピクセル(= 仮想ピクセル × zoom)単位に丸める / round to screen pixels (= virtual pixels × zoom) + c = {std::round(c.x * zoom) / zoom, std::round(c.y * zoom) / zoom}; + } + float hw = 0.5f * viewSize.x / zoom, hh = 0.5f * viewSize.y / zoom; + // 上(top)が-hh、下(bottom)が+hh:yが下向きになる / top = -hh, bottom = +hh: y points down + Mat4 projection = orthographicGl(-hw, hw, hh, -hh, -1.0f, 1.0f); + // ビュー:中心を原点へ移し、カメラの回転の逆に回す / view: move the center to the origin and undo the camera's rotation + return projection * rotateZ(-rotation) * translate({-c.x, -c.y, 0.0f}); +} + +Vec2 Camera2D::toWorld(Vec2 viewPoint) const { + Vec2 fromCentre = (viewPoint - 0.5f * viewSize) / zoom; + return centre + ::rotate(fromCentre, rotation); +} + +Vec2 Camera2D::toView(Vec2 worldPoint) const { + Vec2 local = ::rotate(worldPoint - centre, -rotation) * zoom; + return local + 0.5f * viewSize; +} + +Rect Camera2D::visibleRect() const { + Vec2 corners[4] = {toWorld({0.0f, 0.0f}), toWorld({viewSize.x, 0.0f}), toWorld({viewSize.x, viewSize.y}), + toWorld({0.0f, viewSize.y})}; + Vec2 lo = corners[0], hi = corners[0]; + for (Vec2 p : corners) { + lo = {std::min(lo.x, p.x), std::min(lo.y, p.y)}; + hi = {std::max(hi.x, p.x), std::max(hi.y, p.y)}; + } + return {lo.x, lo.y, hi.x - lo.x, hi.y - lo.y}; +} + +void Viewport::apply() const { glViewport(x, y, width, height); } + +Viewport letterbox(int windowWidth, int windowHeight, Vec2 viewSize, bool integerScale) { + float scale = std::min(static_cast(windowWidth) / viewSize.x, static_cast(windowHeight) / viewSize.y); + // 整数倍に切り捨て。ウィンドウが仮想解像度より小さければ1未満のまま / round down to a whole number; below 1 if the + // window is smaller than the virtual resolution + if (integerScale && scale >= 1.0f) scale = std::floor(scale); + Viewport v; + v.width = static_cast(std::lround(viewSize.x * scale)); + v.height = static_cast(std::lround(viewSize.y * scale)); + v.x = (windowWidth - v.width) / 2; + v.top = (windowHeight - v.height) / 2; + v.y = windowHeight - v.top - v.height; // GLは下から数える / GL counts from the bottom + v.scale = scale; + return v; +} diff --git a/src/cubemap.cc b/engine/src/cubemap.cc similarity index 99% rename from src/cubemap.cc rename to engine/src/cubemap.cc index e17e440..f0b9ede 100644 --- a/src/cubemap.cc +++ b/engine/src/cubemap.cc @@ -1,4 +1,4 @@ -#include "cubemap.hh" +#include "engine/cubemap.hh" #include diff --git a/src/file_util.cc b/engine/src/file_util.cc similarity index 95% rename from src/file_util.cc rename to engine/src/file_util.cc index 7fb3857..aff7fbe 100644 --- a/src/file_util.cc +++ b/engine/src/file_util.cc @@ -1,4 +1,4 @@ -#include "file_util.hh" +#include "engine/file_util.hh" #include #include diff --git a/src/framebuffer.cc b/engine/src/framebuffer.cc similarity index 91% rename from src/framebuffer.cc rename to engine/src/framebuffer.cc index 0d8e107..0050b89 100644 --- a/src/framebuffer.cc +++ b/engine/src/framebuffer.cc @@ -1,4 +1,4 @@ -#include "framebuffer.hh" +#include "engine/framebuffer.hh" #include #include @@ -14,7 +14,7 @@ void Framebuffer::createAttachments() { actualSamples = 0; int count = colorCount(); if (count > kMaxColorAttachments) { - fprintf(stderr, "色の付け先が多すぎる / too many colour attachments: %d (max %d)\n", count, kMaxColorAttachments); + fprintf(stderr, "色の付け先が多すぎる / too many color attachments: %d (max %d)\n", count, kMaxColorAttachments); count = spec.colorCount = kMaxColorAttachments; } GLenum drawBuffers[kMaxColorAttachments]; @@ -23,7 +23,7 @@ void Framebuffer::createAttachments() { drawBuffers[i] = attachment; if (spec.samples > 0) { // マルチサンプルの色:ピクセルごとにsamples個の色を持つレンダーバッファ。テクスチャのように読めない - // Multisampled colour: a renderbuffer with `samples` colours per pixel. It cannot be read like a texture + // Multisampled color: a renderbuffer with `samples` colors per pixel. It cannot be read like a texture GLuint &rb = colorSamples[static_cast(i)]; glCreateRenderbuffers(1, &rb); glNamedRenderbufferStorageMultisample(rb, spec.samples, spec.colorFormat, w, h); @@ -33,7 +33,7 @@ void Framebuffer::createAttachments() { glGetNamedRenderbufferParameteriv(rb, GL_RENDERBUFFER_SAMPLES, &actualSamples); } else { // 色:ミップマップなしのテクスチャ。端の外を読まないようにCLAMP_TO_EDGE(ぼかしのカーネルが端で反対側を拾わない) - // Colour: a texture without mipmaps. CLAMP_TO_EDGE so blur kernels at the border do not pick up the opposite side + // Color: a texture without mipmaps. CLAMP_TO_EDGE so blur kernels at the border do not pick up the opposite side Texture2D &t = colorTextures[static_cast(i)]; t = Texture2D(w, h, spec.colorFormat, 1); t.setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); @@ -46,7 +46,7 @@ void Framebuffer::createAttachments() { // Fragment output location i goes to attachment i (by default only ATTACHMENT0 is written) glNamedFramebufferDrawBuffers(fbo, count, drawBuffers); } else { - // 色を描かない(例:影の深度だけ、第23章) / no colour drawn (e.g. shadow depth only, chapter 23) + // 色を描かない(例:影の深度だけ、第23章) / no color drawn (e.g. shadow depth only, chapter 23) glNamedFramebufferDrawBuffer(fbo, GL_NONE); glNamedFramebufferReadBuffer(fbo, GL_NONE); } @@ -64,8 +64,8 @@ void Framebuffer::createAttachments() { } else if (spec.depthStencilFormat != 0) { glCreateRenderbuffers(1, &depthStencil); // 色と深度のサンプル数は同じでなければならない(違うとフレームバッファが不完全)。要求ではなく、色が実際に - // 貰った数を使う(色が無ければ要求の数) / 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) + // 貰った数を使う(色が無ければ要求の数) / color and depth must have the same number of samples (otherwise the + // framebuffer is incomplete): use the count the color actually got, not the request (the request if no color) int depthSamples = actualSamples > 0 ? actualSamples : spec.samples; if (depthSamples > 0) glNamedRenderbufferStorageMultisample(depthStencil, depthSamples, spec.depthStencilFormat, w, h); else glNamedRenderbufferStorage(depthStencil, spec.depthStencilFormat, w, h); @@ -91,7 +91,7 @@ void Framebuffer::destroyAttachments() { } bool Framebuffer::resize(int width, int height) { - if (width <= 0 || height <= 0) return false; // 最小化中 / minimised + if (width <= 0 || height <= 0) return false; // 最小化中 / minimized if (width == w && height == h) return complete(); w = width; h = height; @@ -108,7 +108,7 @@ bool Framebuffer::complete() const { 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 + // source rectangle → destination rectangle. The color read comes from glNamedFramebufferReadBuffer // (GL_COLOR_ATTACHMENT0 by default) int colors = (mask & GL_COLOR_BUFFER_BIT) ? std::min(colorCount(), target.colorCount()) : 0; if (colors <= 1) { @@ -116,7 +116,7 @@ void Framebuffer::blitTo(const Framebuffer &target, GLbitfield mask, GLenum filt return; } // 複数の色:読む色(ReadBuffer)と書く色(DrawBuffer)を一つずつ選んでコピーし、最後に元に戻す - // Several colours: pick one read buffer and one draw buffer at a time, copy, and restore them afterwards + // Several colors: pick one read buffer and one draw buffer at a time, copy, and restore them afterwards for (int i = 0; i < colors; ++i) { GLenum attachment = GL_COLOR_ATTACHMENT0 + static_cast(i); glNamedFramebufferReadBuffer(fbo, attachment); diff --git a/src/gl_debug.cc b/engine/src/gl_debug.cc similarity index 98% rename from src/gl_debug.cc rename to engine/src/gl_debug.cc index 19f9df4..72fc04d 100644 --- a/src/gl_debug.cc +++ b/engine/src/gl_debug.cc @@ -1,4 +1,4 @@ -#include "gl_debug.hh" +#include "engine/gl_debug.hh" #include diff --git a/src/gltf.cc b/engine/src/gltf.cc similarity index 99% rename from src/gltf.cc rename to engine/src/gltf.cc index c71a35f..7234342 100644 --- a/src/gltf.cc +++ b/engine/src/gltf.cc @@ -1,7 +1,7 @@ -#include "gltf.hh" +#include "engine/gltf.hh" -#include "file_util.hh" -#include "json.hh" +#include "engine/file_util.hh" +#include "engine/json.hh" #include #include diff --git a/src/gpu_timer.cc b/engine/src/gpu_timer.cc similarity index 97% rename from src/gpu_timer.cc rename to engine/src/gpu_timer.cc index 9d7d506..46cb5fe 100644 --- a/src/gpu_timer.cc +++ b/engine/src/gpu_timer.cc @@ -1,4 +1,4 @@ -#include "gpu_timer.hh" +#include "engine/gpu_timer.hh" GpuTimer::GpuTimer() { glCreateQueries(GL_TIME_ELAPSED, kQueries, queries); } diff --git a/src/ibl.cc b/engine/src/ibl.cc similarity index 91% rename from src/ibl.cc rename to engine/src/ibl.cc index 8d54592..74cf2ec 100644 --- a/src/ibl.cc +++ b/engine/src/ibl.cc @@ -1,4 +1,4 @@ -#include "ibl.hh" +#include "engine/ibl.hh" #include #include @@ -8,7 +8,7 @@ namespace { -// 面ごとに描くための、色の付け先だけのFBO(RAII) / an FBO with only a colour attachment, for drawing face by face (RAII) +// 面ごとに描くための、色の付け先だけのFBO(RAII) / an FBO with only a color attachment, for drawing face by face (RAII) struct FaceTarget { GLuint fbo = 0, vao = 0; FaceTarget() { @@ -43,9 +43,9 @@ double elapsedMs(std::chrono::steady_clock::time_point start) { } // namespace std::optional Ibl::build(const Cubemap &environment, const IblSettings &settings) { - std::optional irradianceShader = Shader::load("shaders/post.vert", "shaders/ibl_irradiance.frag"); - std::optional prefilterShader = Shader::load("shaders/post.vert", "shaders/ibl_prefilter.frag"); - std::optional brdfShader = Shader::load("shaders/post.vert", "shaders/ibl_brdf.frag"); + std::optional irradianceShader = Shader::load("engine/shaders/post.vert", "engine/shaders/ibl_irradiance.frag"); + std::optional prefilterShader = Shader::load("engine/shaders/post.vert", "engine/shaders/ibl_prefilter.frag"); + std::optional brdfShader = Shader::load("engine/shaders/post.vert", "engine/shaders/ibl_brdf.frag"); if (!irradianceShader || !prefilterShader || !brdfShader) return std::nullopt; Ibl ibl; diff --git a/src/json.cc b/engine/src/json.cc similarity index 99% rename from src/json.cc rename to engine/src/json.cc index 9176837..57805a5 100644 --- a/src/json.cc +++ b/engine/src/json.cc @@ -1,4 +1,4 @@ -#include "json.hh" +#include "engine/json.hh" #include #include diff --git a/src/lights.cc b/engine/src/lights.cc similarity index 98% rename from src/lights.cc rename to engine/src/lights.cc index 516f352..70d9ea4 100644 --- a/src/lights.cc +++ b/engine/src/lights.cc @@ -1,4 +1,4 @@ -#include "lights.hh" +#include "engine/lights.hh" #include #include diff --git a/src/material.cc b/engine/src/material.cc similarity index 97% rename from src/material.cc rename to engine/src/material.cc index e011f6f..80ae5b4 100644 --- a/src/material.cc +++ b/engine/src/material.cc @@ -1,4 +1,4 @@ -#include "material.hh" +#include "engine/material.hh" void Material::apply(const Shader &shader, const Texture2D &white) const { // 構造体のユニフォームは「変数名.メンバー名」で一つずつ設定する diff --git a/src/mesh.cc b/engine/src/mesh.cc similarity index 99% rename from src/mesh.cc rename to engine/src/mesh.cc index 7142058..2d7e15d 100644 --- a/src/mesh.cc +++ b/engine/src/mesh.cc @@ -1,4 +1,4 @@ -#include "mesh.hh" +#include "engine/mesh.hh" #include diff --git a/src/model.cc b/engine/src/model.cc similarity index 98% rename from src/model.cc rename to engine/src/model.cc index 7da4552..892f745 100644 --- a/src/model.cc +++ b/engine/src/model.cc @@ -1,6 +1,6 @@ -#include "model.hh" +#include "engine/model.hh" -#include "tangents.hh" +#include "engine/tangents.hh" #include #include @@ -26,7 +26,7 @@ static Material phongFromPbr(const GltfMaterial &m, float metallicScale, float r // 金属は拡散反射をしない / metals have no diffuse reflection p.diffuse = (1.0f - metallic) * base; // 正面から見た反射率F0:非金属は約4%、金属は自分の色 / reflectance at normal incidence F0: ~4% for non-metals, - // the base colour for metals + // the base color for metals Vec3 f0 = lerp({0.04f, 0.04f, 0.04f}, base, metallic); // 粗さ → 光沢度:Blinn-Phongとベックマン分布の対応 n = 2/α² − 2(α = 粗さ²) // roughness → shininess: the Blinn-Phong / Beckmann correspondence n = 2/α² − 2 (α = roughness²) @@ -176,7 +176,7 @@ std::optional Model::load(const std::string &path) { // Textures: decode the embedded PNG/JPEG and upload it. glTF UVs start at the image's top-left: no flipping std::vector averages(g.textures.size(), Vec4{1.0f, 1.0f, 1.0f, 1.0f}); // どのテクスチャが色か(第21章):ベースカラーと発光はsRGB、ほかはデータなのでリニア(glTFの仕様どおり) - // Which textures hold colours (chapter 21): base colour and emissive are sRGB, the rest is data and linear (as the + // Which textures hold colors (chapter 21): base color and emissive are sRGB, the rest is data and linear (as the // glTF spec says) std::vector colorUse(g.textures.size(), 0), dataUse(g.textures.size(), 0); auto mark = [](std::vector &use, const GltfTextureRef &ref) { @@ -208,10 +208,10 @@ std::optional Model::load(const std::string &path) { static_cast(sum[2] / pixels), static_cast(sum[3] / pixels)}; // 同じテクスチャを色とデータの両方に使うファイルもありうる:その場合はリニアにして警告する - // A file may use the same texture both as a colour and as data: then it stays linear, with a warning + // A file may use the same texture both as a color and as data: then it stays linear, with a warning bool srgb = colorUse[i] > 0 && dataUse[i] == 0; if (colorUse[i] > 0 && dataUse[i] > 0) - fprintf(stderr, "%s: textures[%zu] は色にもデータにも使われている:リニアで読む / is used both as colour and as data: " + fprintf(stderr, "%s: textures[%zu] は色にもデータにも使われている:リニアで読む / is used both as color and as data: " "loaded as linear\n", path.c_str(), i); Texture2D texture = Texture2D::fromPixels(image->rgba.data(), image->width, image->height, {.flipY = false, .mipmaps = true, .srgb = srgb}); @@ -234,7 +234,7 @@ std::optional Model::load(const std::string &path) { } // マテリアルのないプリミティブ用。glTFの既定(金属度1、粗さ1)だと拡散色の無い淡い塊になるので、白いプラスチックにする // For primitives without a material. glTF's default (metallic 1, roughness 1) would be a pale blob with no diffuse - // colour here, so use white plastic + // color here, so use white plastic model.defaultMaterial.pbr.name = "(default)"; model.defaultMaterial.pbr.metallicFactor = 0.0f; model.defaultMaterial.pbr.roughnessFactor = 0.5f; @@ -390,7 +390,7 @@ void Model::drawItems(const std::vector &items, const Shader &shader, m.apply(shader, *white); } else if (white) { Material m = md.phong; - m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture + m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / color = factor × texture m.emissionMap = texture(md.pbr.emissiveTexture.index); m.normalMap = texture(md.pbr.normalTexture.index); // 第22章 / chapter 22 m.normalScale = md.pbr.normalTexture.scale; diff --git a/src/pbr_material.cc b/engine/src/pbr_material.cc similarity index 98% rename from src/pbr_material.cc rename to engine/src/pbr_material.cc index 3bce1a8..21fe90e 100644 --- a/src/pbr_material.cc +++ b/engine/src/pbr_material.cc @@ -1,4 +1,4 @@ -#include "pbr_material.hh" +#include "engine/pbr_material.hh" void PbrMaterial::apply(const Shader &shader, const Texture2D &white) const { shader.set("uMaterial.baseColor", baseColor); diff --git a/engine/src/pixel_canvas.cc b/engine/src/pixel_canvas.cc new file mode 100644 index 0000000..16cd4ff --- /dev/null +++ b/engine/src/pixel_canvas.cc @@ -0,0 +1,26 @@ +#include "engine/pixel_canvas.hh" + +// 色はRGBA8(2Dの色はsRGBの値のまま扱う、第25章)。スプライトは並べ替えで重ねるので深度は要らない +// The color is RGBA8 (2D colors stay sRGB-encoded values, chapter 25). Sprites are layered by sorting, so no depth +PixelCanvas::PixelCanvas(int width, int height) + : fbo(width, height, {.colorFormat = GL_RGBA8, .depthStencilFormat = 0}) { + fbo.color().setFilter(GL_NEAREST, GL_NEAREST); +} + +void PixelCanvas::begin(Vec4 clearColor) const { + fbo.bind(); + glClearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w); + glClear(GL_COLOR_BUFFER_BIT); +} + +Viewport PixelCanvas::present(int windowWidth, int windowHeight, bool integerScale, Vec4 barColor) const { + Viewport v = letterbox(windowWidth, windowHeight, size(), integerScale); + Framebuffer::bindDefault(windowWidth, windowHeight); + glClearColor(barColor.x, barColor.y, barColor.z, barColor.w); + glClear(GL_COLOR_BUFFER_BIT); + // 0 = 既定のフレームバッファ。GL_NEARESTなのでピクセルがぼけずに大きくなる + // 0 = the default framebuffer. GL_NEAREST keeps the pixels sharp while enlarging + glBlitNamedFramebuffer(fbo.id(), 0, 0, 0, fbo.width(), fbo.height(), v.x, v.y, v.x + v.width, v.y + v.height, + GL_COLOR_BUFFER_BIT, GL_NEAREST); + return v; +} diff --git a/engine/src/renderer3d.cc b/engine/src/renderer3d.cc new file mode 100644 index 0000000..3d2b316 --- /dev/null +++ b/engine/src/renderer3d.cc @@ -0,0 +1,151 @@ +#include "engine/renderer3d.hh" + +#include +#include + +Mat4 lightSpaceMatrix(Vec3 lightDir, Vec3 centre, float radius, int mapSize, float &depthRange) { + Vec3 d = normalize(lightDir); + Vec3 up = std::fabs(d.y) > 0.99f ? Vec3{0.0f, 0.0f, 1.0f} : Vec3{0.0f, 1.0f, 0.0f}; + Mat4 view = lookAt({0.0f, 0.0f, 0.0f}, d, up); // 回転だけ:光の向きを-Zに / rotation only: the light along -Z + Vec4 c = view * Vec4{centre.x, centre.y, centre.z, 1.0f}; + float texel = 2.0f * radius / static_cast(mapSize); + float cx = std::floor(c.x / texel) * texel, cy = std::floor(c.y / texel) * texel; + // 奥行き:球の手前に20 m余分に(箱の外の、光と球の間にある物も影を落とすように) + // Depth: 20 m extra in front of the sphere (so casters between the light and the sphere still cast) + float nearPlane = -c.z - radius - 20.0f, farPlane = -c.z + radius; + depthRange = farPlane - nearPlane; + return orthographicGl(cx - radius, cx + radius, cy - radius, cy + radius, nearPlane, farPlane) * view; +} + +BoundingSphere frustumSphere(Vec3 eye, Vec3 forward, float fovY, float aspect, float nearDist, float farDist) { + Vec3 f = normalize(forward); + Vec3 r = normalize(cross(f, std::fabs(f.y) > 0.99f ? Vec3{0.0f, 0.0f, -1.0f} : Vec3{0.0f, 1.0f, 0.0f})); + Vec3 u = cross(r, f); + float th = std::tan(0.5f * fovY); + Vec3 corners[8]; + int k = 0; + for (float dist : {nearDist, farDist}) + for (float sy : {-1.0f, 1.0f}) + for (float sx : {-1.0f, 1.0f}) corners[k++] = eye + dist * f + (sx * dist * th * aspect) * r + (sy * dist * th) * u; + BoundingSphere s{{0.0f, 0.0f, 0.0f}, 0.0f}; + for (Vec3 c : corners) s.centre = s.centre + 0.125f * c; + for (Vec3 c : corners) s.radius = std::max(s.radius, length(c - s.centre)); + return s; +} + +void applyShadowBias(ShadowBlock &block, const ShadowBias &bias, float radius, int mapSize, float depthRange) { + float unit = bias.inTexels ? 2.0f * radius / static_cast(mapSize) : 1.0f; // m + block.bias = bias.constant * unit / depthRange; + block.slopeBias = bias.slope * unit / depthRange; + block.normalOffset = bias.normalOffset * unit; +} + +//------------------------------------------------------------------ +// ShadowMap +//------------------------------------------------------------------ + +// 色なし、深度だけのテクスチャ(32ビット浮動小数点)。比較モード・GL_LINEAR・外側は1 +// No color, only a depth texture (32-bit float). Comparison mode, GL_LINEAR, 1 outside +static const FramebufferSpec kShadowSpec = {.colorFormat = 0, .depthStencilFormat = GL_DEPTH_COMPONENT32F, + .depthTexture = true}; + +ShadowMap::ShadowMap(int size) : fbo(size, size, kShadowSpec) {} + +void ShadowMap::resize(int size) { fbo.resize(size, size); } + +bool ShadowMap::begin(Vec3 lightDir, const BoundingSphere &fit, const ShadowBias &bias, ShadowFilter filter, + bool enabled) { + float depthRange = 1.0f; + current.lightSpace = lightSpaceMatrix(lightDir, fit.centre, fit.radius, fbo.width(), depthRange); + applyShadowBias(current, bias, fit.radius, fbo.width(), depthRange); + current.filter = static_cast(filter); + current.texel = {1.0f / static_cast(fbo.width()), 1.0f / static_cast(fbo.height())}; + current.enabled = enabled ? 1 : 0; + ubo.update(current); + texelMetres = 2.0f * fit.radius / static_cast(fbo.width()); + // 硬い影はGL_NEAREST、それ以外はGL_LINEAR(比較の結果を2×2で補間) / hard shadows use GL_NEAREST, the others + // GL_LINEAR (the comparison results are blended 2 × 2) + GLenum mode = filter == ShadowFilter::Hard ? GL_NEAREST : GL_LINEAR; + fbo.depth().setFilter(mode, mode); + if (!enabled) return false; + fbo.bind(); + glEnable(GL_DEPTH_TEST); + glDepthMask(GL_TRUE); + glClear(GL_DEPTH_BUFFER_BIT); + glEnable(GL_CULL_FACE); + glCullFace(GL_BACK); + return true; +} + +void ShadowMap::end() const { fbo.depth().bind(kUnit); } + +//------------------------------------------------------------------ +// PostChain +//------------------------------------------------------------------ + +std::optional PostChain::create(int width, int height, const PostChainSettings &settings) { + PostChain chain; + chain.config = settings; + chain.post = Shader::load("engine/shaders/post.vert", "engine/shaders/post.frag"); + chain.blur = Shader::load("engine/shaders/post.vert", "engine/shaders/blur.frag"); + if (!chain.post || !chain.blur) return std::nullopt; + if (!chain.post->checkUniformBlock("Post", sizeof(PostBlock))) return std::nullopt; + // 付け先0 = 場面の色、付け先1 = ブルームにする明るい部分(MRT) / attachment 0 = the scene color, attachment 1 = the + // bright part for bloom (MRT) + const FramebufferSpec hdrSpec = {.colorFormat = settings.format, .colorCount = 2}; + FramebufferSpec msaaSpec = hdrSpec; + msaaSpec.samples = settings.samples; + if (settings.samples > 0) chain.msaaFbo = Framebuffer(width, height, msaaSpec); + chain.sceneFbo = Framebuffer(width, height, hdrSpec); + // ブルームのぼかしは半分の大きさで(4分の1のピクセル数:速く、広くぼける)。深度は要らない + // The bloom blur runs at half size (a quarter of the pixels: faster, and it spreads further). No depth needed + const FramebufferSpec bloomSpec = {.colorFormat = settings.format, .depthStencilFormat = 0}; + for (Framebuffer &f : chain.bloomFbo) f = Framebuffer(width / 2, height / 2, bloomSpec); + if ((settings.samples > 0 && !chain.msaaFbo.complete()) || !chain.sceneFbo.complete() || + !chain.bloomFbo[0].complete() || !chain.bloomFbo[1].complete()) + return std::nullopt; + chain.ubo.emplace(kPostBinding); + return chain; +} + +void PostChain::resize(int width, int height) { + if (config.samples > 0) msaaFbo.resize(width, height); + sceneFbo.resize(width, height); + for (Framebuffer &f : bloomFbo) f.resize(width / 2, height / 2); +} + +void PostChain::beginScene() { + ubo->update(settings); + (config.samples > 0 ? msaaFbo : sceneFbo).bind(); +} + +void PostChain::endScene() { + if (config.samples > 0) msaaFbo.blitTo(sceneFbo); // 色の付け先は2つとも / both color attachments + // ブルーム:明るい部分(付け先1)を半分の大きさで、横・縦・横・縦…とぼかす(ピンポン) + // Bloom: blur the bright part (attachment 1) at half size, horizontally, vertically, ... (ping-pong) + glDisable(GL_DEPTH_TEST); + blur->use(); + for (int pass = 0; pass < 2 * config.bloomPasses; ++pass) { + bloomFbo[pass % 2].bind(); + // 最初は全体の大きさの明るい部分から(線型補間で2×2の平均も取れる)、あとは前のパスの結果から + // The first pass reads the full-size bright part (linear filtering also averages 2 × 2), later passes read the + // previous result + (pass == 0 ? sceneFbo.color(1) : bloomFbo[(pass + 1) % 2].color()).bind(0); + blur->set("uDirection", pass % 2 == 0 ? Vec2{1.0f, 0.0f} : Vec2{0.0f, 1.0f}); + fullscreen.draw(); + } +} + +void PostChain::present(int windowWidth, int windowHeight, int effect) { + Framebuffer::bindDefault(windowWidth, windowHeight); + glDisable(GL_DEPTH_TEST); + post->use(); + post->set("uEffect", effect); + post->set("uFlipX", 0); + sceneFbo.color(0).bind(0); + bloom().bind(1); + sceneFbo.color(1).bind(2); + fullscreen.draw(); +} + +bool PostChain::reload() { return post->reload() && blur->reload(); } diff --git a/src/shader.cc b/engine/src/shader.cc similarity index 99% rename from src/shader.cc rename to engine/src/shader.cc index ec27c84..d4bc602 100644 --- a/src/shader.cc +++ b/engine/src/shader.cc @@ -1,6 +1,6 @@ -#include "shader.hh" +#include "engine/shader.hh" -#include "file_util.hh" +#include "engine/file_util.hh" #include #include diff --git a/src/shapes.cc b/engine/src/shapes.cc similarity index 96% rename from src/shapes.cc rename to engine/src/shapes.cc index 927030b..51fc29e 100644 --- a/src/shapes.cc +++ b/engine/src/shapes.cc @@ -1,6 +1,6 @@ -#include "shapes.hh" +#include "engine/shapes.hh" -#include "tangents.hh" +#include "engine/tangents.hh" #include #include @@ -11,9 +11,9 @@ static void addFace(std::vector &vertices, std::vector(vertices.size()); auto extent = [&](Vec3 axis) { return std::fabs(axis.x) * half.x + std::fabs(axis.y) * half.y + std::fabs(axis.z) * half.z; }; - Vec3 c = extent(normal) * normal; // 面の中心 / centre of the face + Vec3 c = extent(normal) * normal; // 面の中心 / center of the face Vec3 r = extent(right) * right, u = extent(up) * up; - // tile > 0:UVはメートル÷tile(面の大きさに合わせて繰り返す)、0:面ごとに0〜1 / tile > 0: UV = metres ÷ tile + // tile > 0:UVはメートル÷tile(面の大きさに合わせて繰り返す)、0:面ごとに0〜1 / tile > 0: UV = meters ÷ tile // (repeats with the face size); 0: 0..1 per face float su = tile > 0.0f ? 2.0f * extent(right) / tile : 1.0f, sv = tile > 0.0f ? 2.0f * extent(up) / tile : 1.0f; vertices.push_back({c - r - u, normal, {0.0f, 0.0f}, {}}); // 左下 / bottom left @@ -80,7 +80,7 @@ Mesh makeSphere(int segments, int rings) { } } // 隣り合う二つの輪の間を四角形(三角形2つ)で埋める。極の潰れた三角形は省く。 - // Fill between neighbouring rings with quads (two triangles). Skip the degenerate triangles at the poles. + // Fill between neighboring rings with quads (two triangles). Skip the degenerate triangles at the poles. std::uint32_t row = static_cast(segments + 1); for (std::uint32_t r = 0; r < static_cast(rings); ++r) { for (std::uint32_t s = 0; s < static_cast(segments); ++s) { diff --git a/engine/src/sprite_batch.cc b/engine/src/sprite_batch.cc new file mode 100644 index 0000000..5f7b400 --- /dev/null +++ b/engine/src/sprite_batch.cc @@ -0,0 +1,231 @@ +#include "engine/sprite_batch.hh" + +#include +#include +#include +#include +#include +#include + +// 頂点の形式:location 0 = 位置、1 = UV、2 = 色(4バイトを0〜1に正規化) / the vertex format: location 0 = position, +// 1 = UV, 2 = color (4 bytes normalized to 0..1) +static void setupVertexArray(GLuint vao, GLuint vertexBuffer, GLuint indexBuffer) { + glVertexArrayVertexBuffer(vao, 0, vertexBuffer, 0, sizeof(SpriteVertex)); + glVertexArrayElementBuffer(vao, indexBuffer); + glEnableVertexArrayAttrib(vao, 0); + glVertexArrayAttribFormat(vao, 0, 2, GL_FLOAT, GL_FALSE, offsetof(SpriteVertex, position)); + glVertexArrayAttribBinding(vao, 0, 0); + glEnableVertexArrayAttrib(vao, 1); + glVertexArrayAttribFormat(vao, 1, 2, GL_FLOAT, GL_FALSE, offsetof(SpriteVertex, uv)); + glVertexArrayAttribBinding(vao, 1, 0); + glEnableVertexArrayAttrib(vao, 2); + glVertexArrayAttribFormat(vao, 2, 4, GL_UNSIGNED_BYTE, GL_TRUE, offsetof(SpriteVertex, color)); + glVertexArrayAttribBinding(vao, 2, 0); +} + +// 0〜1の色 → RGBA8(Rが下位バイト:メモリ上でR, G, B, Aの順) / a 0..1 color → RGBA8 (R in the lowest byte: R, G, B, +// A in memory order) +static std::uint32_t packColor(Vec4 c) { + auto byte = [](float v) { return static_cast(std::lround(std::clamp(v, 0.0f, 1.0f) * 255.0f)); }; + return byte(c.x) | (byte(c.y) << 8) | (byte(c.z) << 16) | (byte(c.w) << 24); +} + +std::optional SpriteBatch::create(const SpriteBatchSettings &settings) { + SpriteBatch batch; + batch.settings = settings; + batch.shader = Shader::load("engine/shaders/sprite.vert", "engine/shaders/sprite.frag"); + if (!batch.shader) return std::nullopt; + + // インデックスは変わらない:四角形iは頂点4i〜4i+3の三角形2つ(0-1-2、2-3-0) + // The indices never change: quad i is two triangles over vertices 4i..4i+3 (0-1-2, 2-3-0) + const size_t capacity = static_cast(settings.capacity); + std::vector indices(capacity * 6); + for (std::uint32_t i = 0; i < static_cast(capacity); ++i) { + const std::uint32_t q[6] = {4 * i, 4 * i + 1, 4 * i + 2, 4 * i + 2, 4 * i + 3, 4 * i}; + std::copy(q, q + 6, indices.begin() + static_cast(6 * i)); + } + batch.indexBuffer = Buffer(indices.data(), static_cast(indices.size() * sizeof(std::uint32_t))); + + const GLsizeiptr quadBytes = 4 * sizeof(SpriteVertex); + if (settings.upload == SpriteUpload::Persistent) { + // 永続マップ:3区画分のストレージを一度だけマップし、ずっと書き続ける。COHERENTなので書いた値は + // フラッシュなしでGPUに見える(ただしGPUが読み終わったかはフェンスで確かめる) + // Persistent mapping: storage for three regions, mapped once and written for the whole run. COHERENT makes + // writes visible to the GPU without explicit flushes (whether the GPU has finished reading is checked with fences) + const GLbitfield flags = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT; + const GLsizeiptr bytes = kRegions * static_cast(capacity) * quadBytes; + batch.vertexBuffer = Buffer(nullptr, bytes, flags); + batch.mapped = static_cast(glMapNamedBufferRange(batch.vertexBuffer.id(), 0, bytes, flags)); + if (!batch.mapped) { + fprintf(stderr, "スプライトの頂点バッファをマップできない / cannot map the sprite vertex buffer\n"); + return std::nullopt; + } + } else { + // 書き換え可能なストレージ(GL_DYNAMIC_STORAGE_BIT):glNamedBufferSubDataで送る + // Updatable storage (GL_DYNAMIC_STORAGE_BIT): filled with glNamedBufferSubData + batch.vertexBuffer = Buffer(nullptr, static_cast(capacity) * quadBytes, GL_DYNAMIC_STORAGE_BIT); + batch.staging.resize(capacity * 4); + } + glCreateVertexArrays(1, &batch.vao); + setupVertexArray(batch.vao, batch.vertexBuffer.id(), batch.indexBuffer.id()); + + const unsigned char whitePixel[4] = {255, 255, 255, 255}; + batch.white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); + return batch; +} + +void SpriteBatch::release() { + for (GLsync &f : fences) + if (f) glDeleteSync(std::exchange(f, nullptr)); + if (vao) glDeleteVertexArrays(1, &vao); + vao = 0; + // マップしたままのバッファは削除すれば外れる / a mapped buffer is unmapped when it is deleted + mapped = nullptr; +} + +SpriteBatch::~SpriteBatch() { release(); } + +SpriteBatch::SpriteBatch(SpriteBatch &&other) noexcept { *this = std::move(other); } + +SpriteBatch &SpriteBatch::operator=(SpriteBatch &&other) noexcept { + if (this != &other) { + release(); + settings = other.settings; + shader = std::move(other.shader); + vertexBuffer = std::move(other.vertexBuffer); + indexBuffer = std::move(other.indexBuffer); + vao = std::exchange(other.vao, 0); + white = std::move(other.white); + mapped = std::exchange(other.mapped, nullptr); + for (int i = 0; i < kRegions; ++i) fences[i] = std::exchange(other.fences[i], nullptr); + region = other.region; + regionUsed = other.regionUsed; + quads = std::move(other.quads); + staging = std::move(other.staging); + sortMode = other.sortMode; + lastStats = other.lastStats; + currentStats = other.currentStats; + begun = other.begun; + } + return *this; +} + +void SpriteBatch::begin(const Mat4 &viewProjection, SpriteSort sort, SpriteBlend blend) { + if (begun) fprintf(stderr, "SpriteBatch::begin: end()が抜けている / end() is missing\n"); + begun = true; + sortMode = sort; + quads.clear(); + currentStats = {}; + shader->set("uViewProjection", viewProjection); + // 2Dの状態:深度なし(重なりは描く順・layerで決める)、カリングなし(y下向きの射影で四角形は画面上で時計回り + // = 裏向きになる。flipXはUVを入れ替えるだけ)、乗算済みアルファのブレンド / the 2D state: no depth (overlap is + // decided by order / layer), no culling (the y-down projection makes the quads clockwise on screen, i.e. back faces; + // flipX only swaps the UVs), premultiplied-alpha blending + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glEnable(GL_BLEND); + if (blend == SpriteBlend::Additive) glBlendFunc(GL_ONE, GL_ONE); + else glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); +} + +void SpriteBatch::draw(const Sprite &s) { + // 四隅をスプライトの中で作り(originを原点に)、回して、positionへ動かす(CPUで計算:頂点はもうワールド座標) + // Build the corners inside the sprite (origin at 0), rotate them and move them to position (done on the CPU: the + // vertices are already in world space) + Vec2 o = s.origin * s.size; + Vec2 corners[4] = {{-o.x, -o.y}, {s.size.x - o.x, -o.y}, {s.size.x - o.x, s.size.y - o.y}, {-o.x, s.size.y - o.y}}; + if (s.rotation != 0.0f) { + float c = std::cos(s.rotation), sn = std::sin(s.rotation); + for (Vec2 &p : corners) p = {c * p.x - sn * p.y, sn * p.x + c * p.y}; + } + float u0 = s.uv.x, v0 = s.uv.y, u1 = s.uv.x + s.uv.w, v1 = s.uv.y + s.uv.h; + if (s.flipX) std::swap(u0, u1); + if (s.flipY) std::swap(v0, v1); + const Vec2 uvs[4] = {{u0, v0}, {u1, v0}, {u1, v1}, {u0, v1}}; + Quad q; + std::uint32_t color = packColor(s.color); + for (int i = 0; i < 4; ++i) q.v[i] = {s.position + corners[i], uvs[i], color}; + q.texture = s.texture ? s.texture : &white; + q.layer = s.layer; + quads.push_back(q); +} + +void SpriteBatch::drawRect(const Rect &rect, Vec4 color, float layer) { + draw({.position = rect.position(), .size = rect.size(), .color = color, .layer = layer}); +} + +void SpriteBatch::drawRectOutline(const Rect &r, Vec4 color, float t, float layer) { + drawRect({r.x, r.y, r.w, t}, color, layer); + drawRect({r.x, r.bottom() - t, r.w, t}, color, layer); + drawRect({r.x, r.y + t, t, r.h - 2 * t}, color, layer); + drawRect({r.right() - t, r.y + t, t, r.h - 2 * t}, color, layer); +} + +void SpriteBatch::end() { + if (!begun) return; + begun = false; + // 描く順番(quadsの番号)を決める。stable_sortなので同じキーの中では描いた順のまま + // Decide the drawing order (indices into quads). stable_sort keeps submission order among equal keys + std::vector order(quads.size()); + std::iota(order.begin(), order.end(), 0u); + auto textureId = [&](std::uint32_t i) { return quads[i].texture->id(); }; + if (sortMode == SpriteSort::Texture) { + std::stable_sort(order.begin(), order.end(), [&](std::uint32_t a, std::uint32_t b) { return textureId(a) < textureId(b); }); + } else if (sortMode == SpriteSort::Layer) { + std::stable_sort(order.begin(), order.end(), [&](std::uint32_t a, std::uint32_t b) { + if (quads[a].layer != quads[b].layer) return quads[a].layer < quads[b].layer; + return textureId(a) < textureId(b); + }); + } + + shader->use(); + glBindVertexArray(vao); + // 同じテクスチャが続く間(容量まで)を一回の描画コールにする / one draw call per run of the same texture (up to the + // capacity) + const size_t capacity = static_cast(settings.capacity); + size_t first = 0; + while (first < order.size()) { + const Texture2D *texture = quads[order[first]].texture; + size_t count = 1; + while (first + count < order.size() && count < capacity && quads[order[first + count]].texture == texture) ++count; + flush(order, first, count, *texture); + first += count; + } + glBindVertexArray(0); + currentStats.sprites = static_cast(quads.size()); + lastStats = currentStats; +} + +void SpriteBatch::flush(const std::vector &order, size_t first, size_t count, const Texture2D &texture) { + GLint baseVertex = 0; + if (settings.upload == SpriteUpload::Persistent) { + // 今の区画に入らなければ次の区画へ:今の区画にフェンスを置き、次の区画の古いフェンス(GPUがそこを読み終えたか)を待つ + // If it does not fit into the current region, move on: put a fence after the current region's draws and wait + // for the next region's old fence (has the GPU finished reading it?) + if (regionUsed + static_cast(count) > settings.capacity) { + fences[region] = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); + region = (region + 1) % kRegions; + regionUsed = 0; + if (fences[region]) { + // GL_SYNC_FLUSH_COMMANDS_BIT:フェンスがまだGPUに送られていなければ送る(でないと永久に待つ) + // GL_SYNC_FLUSH_COMMANDS_BIT: sends the fence to the GPU if it is not yet (otherwise we could wait forever) + while (glClientWaitSync(fences[region], GL_SYNC_FLUSH_COMMANDS_BIT, 1'000'000) == GL_TIMEOUT_EXPIRED) { + } + glDeleteSync(std::exchange(fences[region], nullptr)); + } + } + int start = region * settings.capacity + regionUsed; + SpriteVertex *out = mapped + static_cast(start) * 4; + for (size_t i = 0; i < count; ++i) std::memcpy(out + 4 * i, quads[order[first + i]].v, sizeof(Quad::v)); + baseVertex = 4 * start; + regionUsed += static_cast(count); + } else { + for (size_t i = 0; i < count; ++i) std::memcpy(&staging[4 * i], quads[order[first + i]].v, sizeof(Quad::v)); + vertexBuffer.update(staging.data(), static_cast(count * 4 * sizeof(SpriteVertex))); + } + texture.bind(0); + // baseVertex:インデックスに足す数。インデックスバッファは0から始まるまま使える + // baseVertex: added to every index, so the index buffer can always start at 0 + glDrawElementsBaseVertex(GL_TRIANGLES, static_cast(count * 6), GL_UNSIGNED_INT, nullptr, baseVertex); + ++currentStats.drawCalls; +} diff --git a/engine/src/sprite_sheet.cc b/engine/src/sprite_sheet.cc new file mode 100644 index 0000000..2dc83f4 --- /dev/null +++ b/engine/src/sprite_sheet.cc @@ -0,0 +1,144 @@ +#include "engine/sprite_sheet.hh" + +#include "engine/file_util.hh" + +#include +#include +#include + +std::optional loadSpriteTexture(const std::string &path, TextureFilter filter) { + // flipY = false:y下向きの2Dでは画像の一番上の行がv = 0のままで良い / with y-down 2D the image's top row can stay v = 0 + std::optional texture = + Texture2D::load(path, {.flipY = false, .mipmaps = false, .srgb = false, .premultiplyAlpha = true}); + if (!texture) return std::nullopt; + GLenum f = filter == TextureFilter::Nearest ? GL_NEAREST : GL_LINEAR; + texture->setFilter(f, f); + // 繰り返さない:端のコマが反対側の端を読まないように / no repeat: frames at the edge must not read the opposite edge + texture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); + return texture; +} + +std::optional SpriteSheet::loadGrid(const std::string &imagePath, int cellWidth, int cellHeight, + int margin, int spacing, TextureFilter filter) { + std::optional texture = loadSpriteTexture(imagePath, filter); + if (!texture) return std::nullopt; + SpriteSheet sheet; + sheet.image = std::move(*texture); + for (int y = margin; y + cellHeight <= sheet.image.height() - margin; y += cellHeight + spacing) + for (int x = margin; x + cellWidth <= sheet.image.width() - margin; x += cellWidth + spacing) + sheet.frames.push_back({static_cast(x), static_cast(y), static_cast(cellWidth), + static_cast(cellHeight)}); + if (sheet.frames.empty()) { + fprintf(stderr, "%s: コマが一つもない / no frames fit (%d x %d cells)\n", imagePath.c_str(), cellWidth, cellHeight); + return std::nullopt; + } + return sheet; +} + +std::optional SpriteSheet::loadAtlas(const std::string &atlasPath, TextureFilter filter) { + std::optional text = readTextFile(atlasPath); + if (!text) { + fprintf(stderr, "%s: 読めない / cannot read (プロジェクトのルートから実行した? / running from the project root?)\n", + atlasPath.c_str()); + return std::nullopt; + } + SpriteSheet sheet; + std::string imageFile; + struct PendingClip { + AnimationClip clip; + std::vector frameNames; + int line; + }; + std::vector pending; + std::istringstream lines(*text); + std::string line; + int lineNumber = 0; + auto fail = [&](const char *what) { + fprintf(stderr, "%s:%d: %s\n", atlasPath.c_str(), lineNumber, what); + return std::nullopt; + }; + while (std::getline(lines, line)) { + ++lineNumber; + std::istringstream in(line); + std::string keyword; + if (!(in >> keyword) || keyword[0] == '#') continue; + if (keyword == "image") { + if (!(in >> imageFile)) return fail("image <ファイル> / image "); + } else if (keyword == "sprite") { + std::string name; + Rect r; + if (!(in >> name >> r.x >> r.y >> r.w >> r.h)) return fail("sprite "); + sheet.frames.push_back(r); + sheet.names.push_back(name); + } else if (keyword == "clip") { + PendingClip p; + std::string mode; + if (!(in >> p.clip.name >> p.clip.fps >> mode) || (mode != "loop" && mode != "once")) + return fail("clip "); + p.clip.loop = mode == "loop"; + for (std::string f; in >> f;) p.frameNames.push_back(f); + p.line = lineNumber; + pending.push_back(std::move(p)); + } else { + return fail("知らないキーワード / unknown keyword"); + } + } + if (imageFile.empty()) return fail("imageの行がない / no image line"); + // クリップのコマの名前を番号にする(spriteより前に書いても良い) / turn clip frame names into indices (clips may come + // before the sprites they use) + for (PendingClip &p : pending) { + for (const std::string &f : p.frameNames) { + int index = sheet.find(f); + if (index < 0) { + lineNumber = p.line; + return fail(("そのコマはない / no such sprite: " + f).c_str()); + } + p.clip.frames.push_back(index); + } + sheet.clips.push_back(std::move(p.clip)); + } + // 画像は.atlasと同じフォルダ / the image lives next to the .atlas file + size_t slash = atlasPath.find_last_of("/\\"); + std::string folder = slash == std::string::npos ? "" : atlasPath.substr(0, slash + 1); + std::optional texture = loadSpriteTexture(folder + imageFile, filter); + if (!texture) return std::nullopt; + sheet.image = std::move(*texture); + for (const Rect &r : sheet.frames) + if (r.x < 0 || r.y < 0 || r.right() > static_cast(sheet.image.width()) || + r.bottom() > static_cast(sheet.image.height())) { + fprintf(stderr, "%s: コマが画像の外にはみ出す / a sprite lies outside the image\n", atlasPath.c_str()); + return std::nullopt; + } + return sheet; +} + +Rect SpriteSheet::pixels(int index) const { + if (index < 0 || index >= count()) { + if (!warnedIndex) + fprintf(stderr, "SpriteSheet: 範囲外のコマ / frame index out of range: %d (count %d)\n", index, count()); + warnedIndex = true; + return {}; + } + return frames[static_cast(index)]; +} + +Rect SpriteSheet::uv(int index) const { + Rect r = pixels(index); + float w = static_cast(image.width()), h = static_cast(image.height()); + return {r.x / w, r.y / h, r.w / w, r.h / h}; +} + +int SpriteSheet::find(std::string_view name) const { + auto it = std::find(names.begin(), names.end(), name); + return it == names.end() ? -1 : static_cast(it - names.begin()); +} + +const AnimationClip *SpriteSheet::clip(std::string_view name) const { + for (const AnimationClip &c : clips) + if (c.name == name) return &c; + return nullptr; +} + +Sprite SpriteSheet::sprite(int index, Vec2 position, Vec2 origin, float scale) const { + return {.texture = &image, .position = position, .size = size(index) * scale, .uv = uv(index), .origin = origin}; +} diff --git a/src/stb_image_impl.cc b/engine/src/stb_image_impl.cc similarity index 100% rename from src/stb_image_impl.cc rename to engine/src/stb_image_impl.cc diff --git a/src/tangents.cc b/engine/src/tangents.cc similarity index 98% rename from src/tangents.cc rename to engine/src/tangents.cc index fcbe3f7..7ed08f1 100644 --- a/src/tangents.cc +++ b/engine/src/tangents.cc @@ -1,4 +1,4 @@ -#include "tangents.hh" +#include "engine/tangents.hh" #include diff --git a/src/texture.cc b/engine/src/texture.cc similarity index 98% rename from src/texture.cc rename to engine/src/texture.cc index 8b6788d..5cafeb1 100644 --- a/src/texture.cc +++ b/engine/src/texture.cc @@ -1,4 +1,4 @@ -#include "texture.hh" +#include "engine/texture.hh" #include @@ -57,7 +57,7 @@ Texture2D Texture2D::fromPixels(const unsigned char *rgba, int width, int height Texture2D texture(width, height, options.srgb ? GL_SRGB8_ALPHA8 : GL_RGBA8, levels); if (options.premultiplyAlpha) { // 乗算済みアルファ:色 × アルファ。透明なピクセルの色は(何色でも)0になる - // premultiplied alpha: colour × alpha. Transparent pixels become 0 whatever colour they had + // premultiplied alpha: color × alpha. Transparent pixels become 0 whatever color they had std::vector pm(rgba, rgba + static_cast(width) * static_cast(height) * 4); // sRGBの値にそのまま掛けると、暗い縁が暗くなりすぎる:リニアで掛ける / multiplying the sRGB-encoded values directly // makes dark edges too dark: multiply in linear space diff --git a/src/window.cc b/engine/src/window.cc similarity index 98% rename from src/window.cc rename to engine/src/window.cc index 6cf0772..6c69a24 100644 --- a/src/window.cc +++ b/engine/src/window.cc @@ -5,9 +5,9 @@ #define NOMINMAX #include #endif -#include "window.hh" +#include "engine/window.hh" -#include "gl_debug.hh" +#include "engine/gl_debug.hh" #include @@ -54,7 +54,7 @@ bool Window::create(int width, int height, const char *title, int samples) { glfwMakeContextCurrent(glfwWindow); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { - fprintf(stderr, "GLADの初期化に失敗 / failed to initialise GLAD\n"); + fprintf(stderr, "GLADの初期化に失敗 / failed to initialize GLAD\n"); return false; } printf("OpenGL %s / %s\n", (const char *)glGetString(GL_VERSION), (const char *)glGetString(GL_RENDERER)); @@ -99,7 +99,7 @@ void Window::setVsync(bool on) { double Window::time() const { return glfwGetTime(); } float Window::aspect() const { - // 最小化するとサイズが0になる / the size becomes 0 when minimised + // 最小化するとサイズが0になる / the size becomes 0 when minimized return fbHeight > 0 ? static_cast(fbWidth) / static_cast(fbHeight) : 1.0f; } diff --git a/src/main.cc b/tests/scene3d/main.cc similarity index 62% rename from src/main.cc rename to tests/scene3d/main.cc index 6ac219a..ef7e66b 100644 --- a/src/main.cc +++ b/tests/scene3d/main.cc @@ -1,5 +1,7 @@ -// 第24章:物理ベースレンダリング -// Chapter 24: physically based rendering +// 3Dの確認:第24章の場面(PBR・IBL・影・HDR・ブルーム・MSAA)をエンジンの部品で描く(第25章から)。 +// TPS(第36〜39章)を作る前に、3Dのクラスが動くことをここで確かめる +// The 3D check: the chapter 24 scene (PBR, IBL, shadows, HDR, bloom, MSAA) drawn with the engine's pieces (from +// chapter 25). Before building the TPS (chapters 36-39), this shows that the 3D classes work // // 操作 / Controls: // WASD 前後左右に移動 / move forward, back, left, right @@ -12,7 +14,7 @@ // K 見る場所:場面 → 球の格子(金属度 × 粗さ) → 見本の球 / look at: the scene → the sphere grid // (metallic × roughness) → the sample spheres // V 表示(PBR):全部 → ベースカラー → 金属度 → 粗さ → 遮蔽 → 法線 → 直接光 → IBL → 影 -// view (PBR): all → base colour → metallic → roughness → occlusion → normals → direct → IBL → shadow +// view (PBR): all → base color → metallic → roughness → occlusion → normals → direct → IBL → shadow // H 影のオン・オフ / shadows on / off // = / - 露出を上げる・下げる / exposure up / down // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 @@ -24,21 +26,22 @@ // Tab カーソルのキャプチャ切り替え / toggle cursor capture // R シェーダーを読み直す / reload the shaders // Esc 終了 / quit -#include "camera.hh" -#include "cubemap.hh" -#include "framebuffer.hh" -#include "ibl.hh" -#include "lights.hh" -#include "material.hh" -#include "mathx.hh" -#include "mesh.hh" -#include "model.hh" -#include "pbr_material.hh" -#include "shader.hh" -#include "shapes.hh" -#include "texture.hh" -#include "uniforms.hh" -#include "window.hh" +#include "engine/camera.hh" +#include "engine/cubemap.hh" +#include "engine/framebuffer.hh" +#include "engine/ibl.hh" +#include "engine/lights.hh" +#include "engine/material.hh" +#include "engine/mathx.hh" +#include "engine/mesh.hh" +#include "engine/model.hh" +#include "engine/pbr_material.hh" +#include "engine/renderer3d.hh" +#include "engine/shader.hh" +#include "engine/shapes.hh" +#include "engine/texture.hh" +#include "engine/uniforms.hh" +#include "engine/window.hh" #include #include @@ -48,7 +51,7 @@ #include #include -// 物を置く場所:位置(底の中心)とY軸周りの回転 / where things go: position (bottom centre) and yaw +// 物を置く場所:位置(底の中心)とY軸周りの回転 / where things go: position (bottom center) and yaw struct Placement { Vec3 position; float angle; @@ -59,53 +62,13 @@ static const Placement kCrates[] = { {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f}, }; -constexpr int kMsaaSamples = 4; // 第20章 / chapter 20 -constexpr int kBloomPasses = 4; // 横+縦の組の数 / number of horizontal + vertical pairs - -static const char *const kPbrViewNames[] = {"all", "base colour", "metallic", "roughness", "occlusion", +static const char *const kPbrViewNames[] = {"all", "base color", "metallic", "roughness", "occlusion", "normals", "direct only", "IBL only", "shadow"}; static const char *const kPhongViewNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals", "vertex normals", "tangents", "bitangents", "shadow"}; static const char *const kLightingNames[] = {"direct + IBL", "direct only", "IBL only"}; -// 影のバイアスの方法 / the shadow bias methods -struct BiasMode { - const char *name; - float constant; // m(inTexelsならテクセルの大きさの倍数) / m (multiples of the texel size if inTexels) - float slope; // tanθ当たり / per unit of tan θ - float normalOffset; // 法線方向のずらし / push along the normal - bool polygonOffset; // 影の地図を描くときにglPolygonOffset / glPolygonOffset while drawing the shadow map - bool inTexels; // 値を影の地図の1テクセルのワールドでの大きさで測る:地図の大きさを変えても効き目が同じ - // values measured in the world size of one shadow-map texel: works the same at any map size -}; -static const BiasMode kBiasModes[] = { - {"none (shadow acne)", 0.0f, 0.0f, 0.0f, false, false}, - {"constant 1 cm", 0.01f, 0.0f, 0.0f, false, false}, - {"slope-scaled + normal offset (in texels)", 0.5f, 1.0f, 3.0f, false, true}, - {"glPolygonOffset(2, 4) only", 0.0f, 0.0f, 0.0f, true, false}, - {"too large: 40 cm (peter-panning)", 0.4f, 0.0f, 0.0f, false, false}, -}; -constexpr size_t kDefaultBias = 2; -constexpr int kShadowSizes[] = {512, 1024, 2048, 4096}; - -// 平行光源の光から見た行列:centreを中心とする半径radiusの球を正射影の箱に収める。箱は影の地図の1テクセル単位で -// 動かす(カメラが動いても影の縁がちらつかない)。depthRangeに箱の奥行き(m)を返す -// The directional light's matrix: an orthographic box enclosing the sphere (centre, radius). The box moves in whole -// shadow-map texels (shadow edges do not shimmer when the camera moves). Returns the box depth (m) in depthRange -static Mat4 lightSpaceMatrix(Vec3 lightDir, Vec3 centre, float radius, int mapSize, float &depthRange) { - Vec3 d = normalize(lightDir); - Vec3 up = std::fabs(d.y) > 0.99f ? Vec3{0.0f, 0.0f, 1.0f} : Vec3{0.0f, 1.0f, 0.0f}; - Mat4 view = lookAt({0.0f, 0.0f, 0.0f}, d, up); // 回転だけ:光の向きを-Zに / rotation only: the light along -Z - Vec4 c = view * Vec4{centre.x, centre.y, centre.z, 1.0f}; - float texel = 2.0f * radius / static_cast(mapSize); - float cx = std::floor(c.x / texel) * texel, cy = std::floor(c.y / texel) * texel; - // 奥行き:球の手前に20 m余分に(箱の外の、光と球の間にある物も影を落とすように) - // Depth: 20 m extra in front of the sphere (so casters between the light and the sphere still cast) - float nearPlane = -c.z - radius - 20.0f, farPlane = -c.z + radius; - depthRange = farPlane - nearPlane; - return orthographicGl(cx - radius, cx + radius, cy - radius, cy + radius, nearPlane, farPlane) * view; -} -constexpr int kFirstVectorView = 5; // ここからはベクトルを色で見せる / from here on, vectors are shown as colours +constexpr int kFirstVectorView = 5; // ここからはベクトルを色で見せる / from here on, vectors are shown as colors static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; static float random01(std::uint32_t &state) { @@ -155,7 +118,7 @@ static std::vector makeWires() { 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 + // 電柱の間に3本ずつ、少したるませて(8本の直線でつなぐ) / three wires between neighboring 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}) { @@ -171,7 +134,7 @@ static std::vector makeWires() { return wires; } -// 電線に吊るした提灯:発光する球。位置と色 / paper lanterns hanging from the wires: emissive spheres, position + colour +// 電線に吊るした提灯:発光する球。位置と色 / paper lanterns hanging from the wires: emissive spheres, position + color struct Lantern { Vec3 position; Vec3 color; @@ -193,7 +156,7 @@ static std::vector makeLanterns() { int main() { Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 24")) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - 3D check")) return 1; // 画面(既定のフレームバッファ)がsRGBか:GL_FRAMEBUFFER_SRGBが効くのはsRGBのときだけ // Is the screen (the default framebuffer) sRGB? GL_FRAMEBUFFER_SRGB only has an effect if it is @@ -201,31 +164,28 @@ int main() { glGetNamedFramebufferAttachmentParameteriv(0, GL_BACK_LEFT, GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, &encoding); printf("default framebuffer encoding: %s\n", encoding == GL_SRGB ? "sRGB" : "linear"); - std::optional phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); + std::optional phong = Shader::load("engine/shaders/phong.vert", "engine/shaders/phong.frag"); // PBR:頂点シェーダーはphongと同じ / PBR: the same vertex shader as phong - std::optional pbr = Shader::load("shaders/phong.vert", "shaders/pbr.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 blur = Shader::load("shaders/post.vert", "shaders/blur.frag"); - std::optional unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag"); - // 色の画像はsRGB(第21章):GPUが読むときにリニアに直す / colour images are sRGB (chapter 21): the GPU converts them + std::optional pbr = Shader::load("engine/shaders/phong.vert", "engine/shaders/pbr.frag"); + std::optional skybox = Shader::load("engine/shaders/skybox.vert", "engine/shaders/skybox.frag"); + std::optional unlit = Shader::load("engine/shaders/unlit.vert", "engine/shaders/unlit.frag"); + // 色の画像はsRGB(第21章):GPUが読むときにリニアに直す / color images are sRGB (chapter 21): the GPU converts them // to linear when sampling std::optional sky = Cubemap::loadDirectory("assets/textures/sky", ".png", true); std::optional floorTexture = Texture2D::load("assets/textures/floor.png", {.srgb = true}); std::optional grassTexture = Texture2D::load("assets/textures/grass_blades.png", {.srgb = true}); - // レンガ:色はsRGB、法線マップはデータなのでリニア(Aは高さ) / bricks: the colour is sRGB, the normal map is data and + // レンガ:色はsRGB、法線マップはデータなのでリニア(Aは高さ) / bricks: the color is sRGB, the normal map is data and // stays linear (A = height) std::optional brickTexture = Texture2D::load("assets/textures/bricks.png", {.srgb = true}); std::optional brickNormal = Texture2D::load("assets/textures/bricks_normal.png"); std::optional leavesTexture = Texture2D::load("assets/textures/leaves.png", {.srgb = true}); - // 影の地図を描くシェーダーと、それを見せるシェーダー / the shader that draws the shadow map and the one that shows it - std::optional shadowShader = Shader::load("shaders/shadow.vert", "shaders/shadow.frag"); - std::optional shadowDebug = Shader::load("shaders/post.vert", "shaders/shadow_debug.frag"); - if (!phong || !pbr || !skybox || !post || !blur || !unlit || !sky || !floorTexture || !grassTexture || !brickTexture || - !brickNormal || !leavesTexture || !shadowShader || !shadowDebug) + // 影の地図を描くシェーダー / the shader that draws the shadow map + std::optional shadowShader = Shader::load("engine/shaders/shadow.vert", "engine/shaders/shadow.frag"); + if (!phong || !pbr || !skybox || !unlit || !sky || !floorTexture || !grassTexture || !brickTexture || + !brickNormal || !leavesTexture || !shadowShader) return 1; grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); - for (const Shader *s : {&*phong, &*pbr, &*skybox, &*post, &*unlit, &*shadowShader}) + for (const Shader *s : {&*phong, &*pbr, &*skybox, &*unlit, &*shadowShader}) if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)) || !s->checkUniformBlock("Post", sizeof(PostBlock)) || !s->checkUniformBlock("Shadow", sizeof(ShadowBlock))) return 1; @@ -233,7 +193,7 @@ int main() { std::optional scene = Model::load("assets/models/diorama.glb"); std::optional crate = Model::load("assets/models/crate.glb"); // 樽:色・金属と粗さ・法線・遮蔽のテクスチャ付き。蓋にはTANGENTがない(Modelが計算する) - // The barrel: colour, metallic-roughness, normal and occlusion textures. The lid has no TANGENT (Model computes it) + // The barrel: color, metallic-roughness, normal and occlusion textures. The lid has no TANGENT (Model computes it) std::optional barrel = Model::load("assets/models/barrel.glb"); if (!scene || !crate || !barrel) return 1; @@ -254,45 +214,15 @@ int main() { UniformBuffer cameraUbo(kCameraBinding); UniformBuffer lightsUbo(kLightsBinding); - UniformBuffer postUbo(kPostBinding); - UniformBuffer shadowUbo(kShadowBinding); - - // 影の地図:色なし、深度だけのテクスチャ(32ビット浮動小数点)。比較モード・GL_LINEAR・外側は1 - // The shadow map: no colour, only a depth texture (32-bit float). Comparison mode, GL_LINEAR, 1 outside - size_t shadowSizeIndex = 2; - const FramebufferSpec shadowSpec = {.colorFormat = 0, .depthStencilFormat = GL_DEPTH_COMPONENT32F, .depthTexture = true}; - Framebuffer shadowFbo(kShadowSizes[shadowSizeIndex], kShadowSizes[shadowSizeIndex], shadowSpec); - if (!shadowFbo.complete()) return 1; - // 影の地図を「見る」ためのサンプラーオブジェクト:比較なし。ユニットに繋ぐとテクスチャ自身の設定より優先される - // A sampler object for *looking at* the shadow map: no comparison. Bound to a unit, it overrides the texture's own - // sampling state - GLuint rawDepthSampler = 0; - glCreateSamplers(1, &rawDepthSampler); - glSamplerParameteri(rawDepthSampler, GL_TEXTURE_COMPARE_MODE, GL_NONE); - glSamplerParameteri(rawDepthSampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glSamplerParameteri(rawDepthSampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - - // HDRのフレームバッファ(第21章):色はGL_RGBA16F(1より明るい値も負の値も持てる半精度の浮動小数点)。 - // 付け先0 = 場面の色、付け先1 = ブルームにする明るい部分(MRT)。MSAA(第20章)で描いて sceneFbo に解決する - // HDR framebuffers (chapter 21): the colour is GL_RGBA16F (half floats that can hold values above 1, and negative - // ones). Attachment 0 = the scene colour, attachment 1 = the bright part for bloom (MRT). Drawn with MSAA - // (chapter 20) and resolved into sceneFbo - const FramebufferSpec hdrSpec = {.colorFormat = GL_RGBA16F, .colorCount = 2}; - FramebufferSpec msaaSpec = hdrSpec; - msaaSpec.samples = kMsaaSamples; - Framebuffer msaaFbo(window.width(), window.height(), msaaSpec); - Framebuffer sceneFbo(window.width(), window.height(), hdrSpec); - // ブルームのぼかしは半分の大きさで(4分の1のピクセル数:速く、広くぼける)。深度は要らない - // The bloom blur runs at half size (a quarter of the pixels: faster, and it spreads further). No depth needed - const FramebufferSpec bloomSpec = {.colorFormat = GL_RGBA16F, .depthStencilFormat = 0}; - Framebuffer bloomFbo[2] = {Framebuffer(window.width() / 2, window.height() / 2, bloomSpec), - Framebuffer(window.width() / 2, window.height() / 2, bloomSpec)}; - if (!msaaFbo.complete() || !sceneFbo.complete() || !bloomFbo[0].complete()) return 1; - window.onResize = [&](int width, int height) { - msaaFbo.resize(width, height); - sceneFbo.resize(width, height); - for (Framebuffer &f : bloomFbo) f.resize(width / 2, height / 2); - }; + + // 影の地図(第23章、結合点2のShadowブロックも持つ)と、HDR・MSAA・ブルームの後処理(第20・21章、結合点3の + // Postブロックも持つ):第25章でエンジンの部品になった + // The shadow map (chapter 23; it also owns the Shadow block, binding 2) and the HDR / MSAA / bloom post-processing + // (chapters 20-21; it also owns the Post block, binding 3): engine pieces since chapter 25 + ShadowMap shadowMap(2048); + std::optional postChain = PostChain::create(window.width(), window.height()); + if (!shadowMap.complete() || !postChain) return 1; + window.onResize = [&](int width, int height) { postChain->resize(width, height); }; Camera fps; fps.position = {0.6f, 3.6f, 12.5f}; @@ -305,13 +235,8 @@ int main() { bool useOrbit = false, shadowsOn = true, usePbr = true; int lighting = 0, place = 0; - // 第23章の影の設定(この章では固定。キーは第23章) / the chapter 23 shadow settings (fixed here; the keys are in ch23) - const bool fitFrustum = false, showShadowMap = false; - const size_t biasMode = kDefaultBias; - const int cullMode = 0, shadowFilter = static_cast(ShadowFilter::Pcf3x3); int viewMode = 0, effect = 0; float exposureEv = 0.0f; // 露出(段、EV):倍率は2^EV / exposure in stops (EV): the multiplier is 2^EV - PostBlock postSettings; bool night = false, flashlightOn = false, windmillMoving = true; float windmillTime = 0.0f; window.setCursorCaptured(true); @@ -322,8 +247,8 @@ int main() { // IBLのシェーダー(ibl_*.frag)は作るときだけ使う:読み直す = IBLを作り直す(失敗したら前のIBLのまま) // The IBL shaders (ibl_*.frag) are only used while building: reloading them = rebuilding the IBL (the old one stays // if that fails) - if (key == GLFW_KEY_R && phong->reload() && pbr->reload() && skybox->reload() && post->reload() && blur->reload() && - unlit->reload() && shadowShader->reload() && shadowDebug->reload()) { + if (key == GLFW_KEY_R && phong->reload() && pbr->reload() && skybox->reload() && postChain->reload() && + unlit->reload() && shadowShader->reload()) { if (std::optional rebuilt = Ibl::build(*sky)) { ibl = std::move(rebuilt); printf("シェーダーを読み直した / shaders reloaded\n"); @@ -378,7 +303,7 @@ int main() { // 手で作るマテリアルはすべてPbrMaterial(第24章)。Blinn-Phongで描くときはtoBlinnPhongで変換する。 // 手で選んだ色はsRGBの値なのでsrgbToLinearでリニアに // Every hand-made material is a PbrMaterial (chapter 24); for Blinn-Phong they are converted with toBlinnPhong. - // Hand-picked colours are sRGB values, so srgbToLinear makes them linear + // Hand-picked colors are sRGB values, so srgbToLinear makes them linear auto rgb = [](float r, float g, float b, float a = 1.0f) { Vec3 c = srgbToLinear(Vec3{r, g, b}); return Vec4{c.x, c.y, c.z, a}; @@ -425,7 +350,7 @@ int main() { constexpr float kLanternGlow = 6.0f; // 見本の球:磨いた金、クロム、粗い銅、赤いプラスチック(glTFの値で、金属のベースカラー = F0) - // Sample spheres: polished gold, chrome, rough copper, red plastic (glTF values; a metal's base colour = its F0) + // Sample spheres: polished gold, chrome, rough copper, red plastic (glTF values; a metal's base color = its F0) struct Showcase { Vec3 position; PbrMaterial material; @@ -443,7 +368,6 @@ int main() { const Vec3 kGridCentre = {0.0f, 5.5f, 24.0f}; const Vec4 kGridColor = rgb(0.9f, 0.35f, 0.15f); - FullscreenTriangle fullscreen; glEnable(GL_CULL_FACE); // 場面全体を今のフレームバッファに描く。litはpbr(PBR)かphong(比較用のBlinn-Phong) @@ -588,7 +512,7 @@ int main() { scene->nodes[static_cast(rotor)].rotation = Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; - float aspect = static_cast(sceneFbo.width()) / static_cast(sceneFbo.height()); + float aspect = static_cast(postChain->scene().width()) / static_cast(postChain->scene().height()); CameraBlock camera; camera.view = useOrbit ? orbit.view() : fps.view(); @@ -620,138 +544,44 @@ int main() { lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); lightsUbo.update(lights.toBlock()); environmentTint = night ? Vec3{0.02f, 0.025f, 0.05f} : Vec3{1.0f, 1.0f, 1.0f}; - postSettings.exposure = std::exp2(exposureEv); - postSettings.bloomStrength = 0.08f; + postChain->settings.exposure = std::exp2(exposureEv); + postChain->settings.bloomStrength = 0.08f; // ベクトルの表示(法線・接線)は値をそのまま見せる:トーンマッピングなし、露出1(phong.fragが逆変換して出す) // The vector views (normals, tangents) show the raw values: no tone mapping, exposure 1 (phong.frag outputs them // pre-decoded) if (usePbr ? (viewMode >= 2 && viewMode <= 5) || viewMode == 8 : viewMode >= kFirstVectorView) { - postSettings.exposure = 1.0f; - postSettings.toneMapper = static_cast(ToneMapper::Clamp); + postChain->settings.exposure = 1.0f; + postChain->settings.toneMapper = static_cast(ToneMapper::Clamp); } else { - postSettings.toneMapper = static_cast(ToneMapper::Aces); + postChain->settings.toneMapper = static_cast(ToneMapper::Aces); } - postUbo.update(postSettings); //------------------------------------------------------------------ - // 0. 影の地図:太陽から見た深度(第23章) / 0. the shadow map: depth as seen from the sun (chapter 23) + // 0. 影の地図:太陽から見た深度(第23章)。光の箱は場面全体を囲む球 + // 0. the shadow map: depth as seen from the sun (chapter 23). The light box is a sphere around the whole scene //------------------------------------------------------------------ - // 光の箱:場面全体を囲む球か、カメラの視錐台の手前8 mを囲む球 / the light box: a sphere around the whole scene, - // or a sphere around the first 8 m of the camera frustum - Vec3 fitCentre = {0.0f, 1.0f, 2.5f}; - float fitRadius = 9.5f; - if (fitFrustum) { - float nearPlane = 0.1f, farPlane = 8.0f, fov = useOrbit ? orbit.fov : fps.fov; - Vec3 f = viewDir, r = normalize(cross(f, Vec3{0.0f, 1.0f, 0.0f})), u = cross(r, f); - float th = std::tan(0.5f * fov); - Vec3 corners[8]; - int k = 0; - for (float dist : {nearPlane, farPlane}) - for (float sy : {-1.0f, 1.0f}) - for (float sx : {-1.0f, 1.0f}) - corners[k++] = camera.viewPos + dist * f + (sx * dist * th * aspect) * r + (sy * dist * th) * u; - // 中心は8つの角の平均、半径は一番遠い角まで(カメラが回っても大きさは変わらない) - // Centre = the mean of the 8 corners, radius = to the farthest corner (its size does not change as the camera turns) - fitCentre = {0.0f, 0.0f, 0.0f}; - for (Vec3 c : corners) fitCentre = fitCentre + 0.125f * c; - fitRadius = 0.0f; - for (Vec3 c : corners) fitRadius = std::max(fitRadius, length(c - fitCentre)); - } - if (frame++ % 60 == 5) printf("light box radius %.2f m: %.1f mm per shadow texel\n", fitRadius, 2000.0f * fitRadius / static_cast(shadowFbo.width())); - const BiasMode &bias = kBiasModes[biasMode]; - float depthRange = 1.0f; - ShadowBlock shadowBlock; - shadowBlock.lightSpace = lightSpaceMatrix(lights.directional.direction, fitCentre, fitRadius, shadowFbo.width(), depthRange); - // バイアスはメートルで決めて、0〜1の深度に直す(正射影なので深度は距離に比例) / biases are chosen in metres and - // converted to 0..1 depth (orthographic: depth is proportional to distance) - float unit = bias.inTexels ? 2.0f * fitRadius / static_cast(shadowFbo.width()) : 1.0f; // m - shadowBlock.bias = bias.constant * unit / depthRange; - shadowBlock.slopeBias = bias.slope * unit / depthRange; - shadowBlock.normalOffset = bias.normalOffset * unit; - shadowBlock.filter = shadowFilter; - shadowBlock.texel = {1.0f / static_cast(shadowFbo.width()), 1.0f / static_cast(shadowFbo.height())}; - shadowBlock.enabled = shadowsOn ? 1 : 0; - shadowUbo.update(shadowBlock); - // 硬い影はGL_NEAREST、それ以外はGL_LINEAR(比較の結果を2×2で補間) / hard shadows use GL_NEAREST, the others - // GL_LINEAR (the comparison results are blended 2 × 2) - GLenum shadowFilterMode = shadowFilter == static_cast(ShadowFilter::Hard) ? GL_NEAREST : GL_LINEAR; - shadowFbo.depth().setFilter(shadowFilterMode, shadowFilterMode); - - if (shadowsOn) { - shadowFbo.bind(); - glEnable(GL_DEPTH_TEST); - glClear(GL_DEPTH_BUFFER_BIT); - if (cullMode == 1) glCullFace(GL_FRONT); // 表面を捨て、裏面の深度を保存する / keep the back faces' depth - if (cullMode == 2) glDisable(GL_CULL_FACE); - if (bias.polygonOffset) { - // ハードウェアの傾きバイアス:深度 += factor × 傾き + units × 最小の深度の差 / hardware slope bias: - // depth += factor × slope + units × the smallest depth step - glEnable(GL_POLYGON_OFFSET_FILL); - glPolygonOffset(2.0f, 4.0f); - } + const BoundingSphere fit = {{0.0f, 1.0f, 2.5f}, 9.5f}; + if (shadowMap.begin(lights.directional.direction, fit, ShadowBias{}, ShadowFilter::Pcf3x3, shadowsOn)) drawShadowCasters(); - glDisable(GL_POLYGON_OFFSET_FILL); - glCullFace(GL_BACK); - glEnable(GL_CULL_FACE); - } - // 影の地図はユニット5(描き終わってから繋ぐ) / the shadow map goes on unit 5 (after it has been drawn) - shadowFbo.depth().bind(5); + glEnable(GL_CULL_FACE); + shadowMap.end(); // 深度テクスチャをユニット5へ / the depth texture goes on unit 5 + if (frame++ % 60 == 5) + printf("light box radius %.2f m: %.1f mm per shadow texel\n", fit.radius, 1000.0f * shadowMap.metresPerTexel()); //------------------------------------------------------------------ - // 1. 場面をHDR・MSAAで描き、解決する(色の付け先は2つとも) / 1. draw the scene in HDR with MSAA and resolve it - // (both colour attachments) + // 1. 場面をHDR・MSAAで描き、解決してブルーム / 1. draw the scene in HDR with MSAA, resolve it and bloom //------------------------------------------------------------------ - msaaFbo.bind(); + postChain->beginScene(); drawScene(); - msaaFbo.blitTo(sceneFbo); + postChain->endScene(); //------------------------------------------------------------------ - // 2. ブルーム:明るい部分(付け先1)を半分の大きさで、横・縦・横・縦…とぼかす(ピンポン) - // 2. Bloom: blur the bright part (attachment 1) at half size, horizontally, vertically, ... (ping-pong) - //------------------------------------------------------------------ - glDisable(GL_DEPTH_TEST); - blur->use(); - for (int pass = 0; pass < 2 * kBloomPasses; ++pass) { - bloomFbo[pass % 2].bind(); - // 最初は全体の大きさの明るい部分から(線型補間で2×2の平均も取れる)、あとは前のパスの結果から - // The first pass reads the full-size bright part (linear filtering also averages 2 × 2), later passes read the - // previous result - (pass == 0 ? sceneFbo.color(1) : bloomFbo[(pass + 1) % 2].color()).bind(0); - blur->set("uDirection", pass % 2 == 0 ? Vec2{1.0f, 0.0f} : Vec2{0.0f, 1.0f}); - fullscreen.draw(); - } - - //------------------------------------------------------------------ - // 3. 画面へ:場面+ブルーム、露出、トーンマッピング、sRGB / 3. to the screen: scene + bloom, exposure, tone + // 2. 画面へ:場面+ブルーム、露出、トーンマッピング、sRGB / 2. to the screen: scene + bloom, exposure, tone // mapping, sRGB //------------------------------------------------------------------ - Framebuffer::bindDefault(window.width(), window.height()); - post->use(); - post->set("uEffect", effect); - post->set("uFlipX", 0); - sceneFbo.color(0).bind(0); - bloomFbo[1].color().bind(1); // 最後の縦のパスの結果 / the result of the last vertical pass - sceneFbo.color(1).bind(2); - fullscreen.draw(); - - // 影の地図を左下に(比較なしのサンプラーで深度を読む) / the shadow map at the bottom left (depth read through the - // sampler without comparison) - if (showShadowMap) { - glViewport(16, 16, 320, 320); - shadowDebug->use(); - shadowFbo.depth().bind(0); - glBindSampler(0, rawDepthSampler); - fullscreen.draw(); - glBindSampler(0, 0); // ユニット0はテクスチャ自身の設定に戻る / unit 0 goes back to the texture's own state - // 影の地図をユニット0から外す:次のシャドウパスではshadow.fragのuBaseMapがユニット0で、描き込み中の深度を - // 読むとフィードバックループになる / take the shadow map off unit 0: in the next shadow pass shadow.frag's - // uBaseMap is on unit 0, and reading the depth being written would be a feedback loop - white.bind(0); - glViewport(0, 0, window.width(), window.height()); - } + postChain->present(window.width(), window.height(), effect); window.swapBuffers(); } - glDeleteSamplers(1, &rawDepthSampler); return 0; } diff --git a/src/gltf_dump.cc b/tools/gltf_dump.cc similarity index 98% rename from src/gltf_dump.cc rename to tools/gltf_dump.cc index d00be55..32c4d67 100644 --- a/src/gltf_dump.cc +++ b/tools/gltf_dump.cc @@ -12,7 +12,7 @@ #define NOMINMAX #include #endif -#include "gltf.hh" +#include "engine/gltf.hh" #include #include @@ -214,7 +214,7 @@ static bool dump(const std::string &path, bool all) { for (size_t i = 0; i < g.materials.size(); ++i) { const GltfMaterial &m = g.materials[i]; const Vec4 &b = m.baseColorFactor; - printf(" [%zu] \"%s\": base colour (%g, %g, %g, %g), metallic %g, roughness %g", i, m.name.c_str(), b.x, b.y, b.z, + printf(" [%zu] \"%s\": base color (%g, %g, %g, %g), metallic %g, roughness %g", i, m.name.c_str(), b.x, b.y, b.z, b.w, m.metallicFactor, m.roughnessFactor); if (m.emissiveFactor.x > 0.0f || m.emissiveFactor.y > 0.0f || m.emissiveFactor.z > 0.0f) printf(", emissive (%g, %g, %g) x %g", m.emissiveFactor.x, m.emissiveFactor.y, m.emissiveFactor.z,