diff --git a/games/tps/CMakeLists.txt b/games/tps/CMakeLists.txt index e89207d..18c45c9 100644 --- a/games/tps/CMakeLists.txt +++ b/games/tps/CMakeLists.txt @@ -10,8 +10,25 @@ add_executable(tps src/third_person_camera.cc src/enemy.cc src/effects.cc - src/play_scene.cc) + src/play_scene.cc + src/hud.cc + src/menu_scenes.cc) target_include_directories(tps PRIVATE src) target_link_libraries(tps PRIVATE engine) enable_warnings(tps) set_working_directory(tps) + +# 配布(第39章):cmake --install --prefix --component tps で /tps/ に実行ファイルと使うデータを +# プロジェクトと同じ並びで置く(tpsは見つからなければ実行ファイルの隣のデータを使う)。 +# Release: cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release(Visual Studio: --config Release) +# Packaging (chapter 39): cmake --install --prefix --component tps puts the executable and the data it +# uses into /tps/, laid out like the project (tps falls back to the data next to its executable). +# Release: cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release (Visual Studio: --config Release) +install(TARGETS tps RUNTIME DESTINATION tps COMPONENT tps) +install(DIRECTORY ${PROJECT_SOURCE_DIR}/engine/shaders DESTINATION tps/engine COMPONENT tps) +install(DIRECTORY ${PROJECT_SOURCE_DIR}/assets/textures/sky DESTINATION tps/assets/textures COMPONENT tps) +install(FILES ${PROJECT_SOURCE_DIR}/assets/models/crate.glb ${PROJECT_SOURCE_DIR}/assets/models/barrel.glb + DESTINATION tps/assets/models COMPONENT tps) +install(FILES ${PROJECT_SOURCE_DIR}/assets/LICENSE.txt DESTINATION tps/assets COMPONENT tps) +install(DIRECTORY assets shaders DESTINATION tps/games/tps COMPONENT tps) +install(FILES README.md DESTINATION tps/games/tps COMPONENT tps) diff --git a/games/tps/README.md b/games/tps/README.md index f8944a5..fed471b 100644 --- a/games/tps/README.md +++ b/games/tps/README.md @@ -4,10 +4,32 @@ ```sh ./build/games/tps/tps # Windows: build\games\tps\Debug\tps.exe +./build/games/tps/tps --play # タイトルを飛ばす / skip the title +./build/games/tps/tps --msaa # エンジンの既定の後処理(4× MSAA)で比べる / compare with 4× MSAA ./build/games/tps/tps games/tps/assets/levels/pieces.level # 部品を並べたレベル / every piece in a row ``` -## 操作 / Controls(第36〜38章 / chapters 36-38) +## Release と配布 / Release build and packaging(第39章 / chapter 39) + +```sh +cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release # Visual Studio: cmake --build build --config Release +cmake --build build-release --target tps -j8 +cmake --install build-release --prefix dist --component tps +./dist/tps/tps # どこから実行しても良い / runs from any directory +``` + +`dist/tps/` にはプロジェクトと同じ並びで、実行ファイルと使うデータだけが入る(`engine/shaders/`、`assets/textures/sky/`、 +`assets/models/crate.glb`・`barrel.glb`、`games/tps/assets/`・`shaders/`)。データが今のディレクトリになければ、 +実行ファイルの隣を使う。 +`dist/tps/` holds the executable and only the data it uses, laid out like the project. If the data is not in the +current directory, the game uses the directory of its executable. + +## 次へ / Next steps + +このシリーズの次は **Slang + Vulkan**:同じレンダラー(PBR、影、IBL、後処理)をVulkanで、シェーダーはSlangで書き直す。 +The next series is **Slang + Vulkan**: the same renderer (PBR, shadows, IBL, post) rebuilt on Vulkan with shaders in Slang. + +## 操作 / Controls(第36〜39章 / chapters 36-39) | キー / key | | |---|---| @@ -28,8 +50,12 @@ | F3 | 時間と描いた数 / timings and draw counts | | F8 | 毎フレームの状態を標準出力へ(台本作り用) / log the state every frame to stdout (for scripting) | | F4 | 視錐台カリングのオン・オフ / frustum culling on / off | +| F5 | 描く解像度 100 → 75 → 50 % / render scale | +| F6 | 影のオン・オフ / shadows on / off | +| F7 | 影の地図 2048² ⇔ 1024² / shadow map size | | Tab | カーソルのキャプチャ / cursor capture | -| Esc | 終了 / quit | +| Esc | 一時停止(タイトルでは終了) / pause (quit on the title) | +| Space / Enter | タイトル・結果の画面で決定 / confirm on the title and result screens | ## ファイル / Files @@ -43,6 +69,8 @@ src/character_body.* 当たり判定・重力・壁ずり・段差 / coll src/enemy.* 敵の状態機械のAI / the enemies' state-machine AI src/effects.* 銃口の光・トレーサー・火花 / muzzle flash, tracers, sparks src/angles.hh 角度の小道具 / angle helpers +src/hud.* HUD(照準・体力・弾・敵・撃たれた向き) / the HUD +src/menu_scenes.* タイトル・結果・一時停止 / title, result and pause scenes shaders/particle.vert/.frag 火花のビルボード / spark billboards src/frustum.* 視錐台の平面 / frustum planes src/renderer.* 影 → 場面(PBR + IBL) → 後処理 / shadows → scene (PBR + IBL) → post diff --git a/games/tps/src/hud.cc b/games/tps/src/hud.cc new file mode 100644 index 0000000..790c7d6 --- /dev/null +++ b/games/tps/src/hud.cc @@ -0,0 +1,114 @@ +#include "hud.hh" + +#include +#include +#include + +constexpr Vec2 kCentre = {640.0f, 360.0f}; +constexpr Vec4 kShadow = {0.0f, 0.0f, 0.0f, 0.85f}; +constexpr Vec4 kPanel = {0.03f, 0.04f, 0.06f, 0.55f}; + +// 黒い縁つきの線(明るい床でも暗い壁でも見える) / a line with a dark outline (readable on bright floors and dark walls) +static void outlined(SpriteBatch &batch, Rect r, Vec4 color) { + batch.drawRect({r.x - 1.0f, r.y - 1.0f, r.w + 2.0f, r.h + 2.0f}, {0.0f, 0.0f, 0.0f, 0.6f * color.w}); + batch.drawRect(r, color); +} + +// 中心のまわりに回した細い四角形(当てた印、撃たれた向き) / a thin rectangle turned about the center (hit marker, +// damage direction) +static void spoke(SpriteBatch &batch, float angle, float radius, Vec2 size, Vec4 color) { + Vec2 dir = {std::sin(angle), -std::cos(angle)}; // 画面の上 = 0、時計回り / screen up = 0, clockwise + batch.draw({.position = kCentre + radius * dir, .size = size, .origin = {0.5f, 0.5f}, .rotation = angle, + .color = color}); +} + +static void crosshair(SpriteBatch &batch, const HudState &hud) { + if (!hud.alive) return; + // 4本の線:拡散が大きいほど開く(撃つ・動く・狙っていない) / four lines that open with the spread (firing, moving, + // not aiming) + float g = hud.spread; + Vec4 c = {1.0f, 1.0f, 1.0f, 0.95f}; + outlined(batch, {639.0f, 360.0f - g - 9.0f, 2.0f, 9.0f}, c); + outlined(batch, {639.0f, 360.0f + g, 2.0f, 9.0f}, c); + outlined(batch, {640.0f - g - 9.0f, 359.0f, 9.0f, 2.0f}, c); + outlined(batch, {640.0f + g, 359.0f, 9.0f, 2.0f}, c); + outlined(batch, {639.0f, 359.0f, 2.0f, 2.0f}, c); + // 当てた印:斜めの4本(倒したら赤く大きく) / hit marker: four diagonal strokes (red and bigger on a kill) + if (hud.hitMarker > 0.0f) { + float k = hud.hitMarker; + Vec4 m = hud.killMarker ? Vec4{1.0f, 0.25f, 0.2f, k} : Vec4{1.0f, 1.0f, 1.0f, k}; + float r = hud.killMarker ? 16.0f : 12.0f; + for (int i = 0; i < 4; ++i) spoke(batch, 0.25f * PI + 0.5f * PI * static_cast(i), r, {2.0f, 8.0f}, m); + } +} + +static void healthPanel(SpriteBatch &batch, const Font &font, const HudState &hud) { + batch.drawRect({20.0f, 640.0f, 300.0f, 62.0f}, kPanel); + font.draw(batch, "体力 / HEALTH", {32.0f, 646.0f}, {.color = {0.8f, 0.85f, 0.9f, 1.0f}, .shadow = kShadow}); + Rect bar = {32.0f, 672.0f, 220.0f, 16.0f}; + batch.drawRect(bar, {0.0f, 0.0f, 0.0f, 0.6f}); + float shown = std::clamp(hud.healthShown / 100.0f, 0.0f, 1.0f), now = std::clamp(hud.health / 100.0f, 0.0f, 1.0f); + batch.drawRect({bar.x, bar.y, bar.w * shown, bar.h}, {1.0f, 0.85f, 0.8f, 0.8f}); // 減った分 / what was lost + // 緑 → 黄 → 赤 / green → yellow → red + Vec4 color = now > 0.5f ? lerp(Vec4{0.95f, 0.8f, 0.2f, 1.0f}, Vec4{0.3f, 0.9f, 0.45f, 1.0f}, (now - 0.5f) * 2.0f) + : lerp(Vec4{0.95f, 0.2f, 0.15f, 1.0f}, Vec4{0.95f, 0.8f, 0.2f, 1.0f}, now * 2.0f); + batch.drawRect({bar.x, bar.y, bar.w * now, bar.h}, color); + font.draw(batch, std::format("{:.0f}", std::ceil(hud.health)), {302.0f, 668.0f}, + {.scale = 1.5f, .align = TextAlign::Right, .shadow = kShadow}); +} + +static void ammoPanel(SpriteBatch &batch, const Font &font, const HudState &hud) { + batch.drawRect({1000.0f, 640.0f, 260.0f, 62.0f}, kPanel); + font.draw(batch, "弾 / AMMO", {1012.0f, 646.0f}, {.color = {0.8f, 0.85f, 0.9f, 1.0f}, .shadow = kShadow}); + Vec4 c = hud.ammo == 0 ? Vec4{1.0f, 0.3f, 0.25f, 1.0f} : hud.ammo <= hud.magazine / 4 ? Vec4{1.0f, 0.8f, 0.3f, 1.0f} + : kWhite; + font.draw(batch, std::format("{}", hud.ammo), {1190.0f, 644.0f}, + {.color = c, .scale = 2.5f, .align = TextAlign::Right, .shadow = kShadow}); + font.draw(batch, std::format("/ {}", hud.magazine), {1196.0f, 666.0f}, {.color = {0.8f, 0.8f, 0.8f, 1.0f}, + .shadow = kShadow}); + // 弾の数だけの小さな印(1発 = 1本) / one small pip per round + for (int i = 0; i < hud.magazine; ++i) + batch.drawRect({1012.0f + 6.0f * static_cast(i), 674.0f, 4.0f, 14.0f}, + i < hud.ammo ? Vec4{0.95f, 0.85f, 0.5f, 1.0f} : Vec4{1.0f, 1.0f, 1.0f, 0.15f}); + if (hud.reload >= 0.0f) { + font.draw(batch, "装填中 / RELOADING", {640.0f, 410.0f}, + {.color = {1.0f, 0.85f, 0.4f, 1.0f}, .align = TextAlign::Centre, .shadow = kShadow}); + batch.drawRect({580.0f, 434.0f, 120.0f, 4.0f}, {0.0f, 0.0f, 0.0f, 0.6f}); + batch.drawRect({580.0f, 434.0f, 120.0f * hud.reload, 4.0f}, {1.0f, 0.85f, 0.4f, 1.0f}); + } +} + +static void enemiesPanel(SpriteBatch &batch, const Font &font, const HudState &hud) { + float w = 30.0f + 22.0f * static_cast(hud.enemiesTotal); + float x = 640.0f - 0.5f * std::fmax(w, 200.0f); + batch.drawRect({x, 16.0f, std::fmax(w, 200.0f), 52.0f}, kPanel); + font.draw(batch, std::format("敵 / ENEMIES {} / {}", hud.enemiesLeft, hud.enemiesTotal), {640.0f, 20.0f}, + {.color = {0.9f, 0.9f, 0.95f, 1.0f}, .align = TextAlign::Centre, .shadow = kShadow}); + float x0 = 640.0f - 11.0f * static_cast(hud.enemiesTotal) + 3.0f; + for (int i = 0; i < hud.enemiesTotal; ++i) { + bool alive = i < hud.enemiesLeft; + batch.drawRect({x0 + 22.0f * static_cast(i), 44.0f, 16.0f, 16.0f}, + alive ? Vec4{0.85f, 0.2f, 0.15f, 1.0f} : Vec4{1.0f, 1.0f, 1.0f, 0.18f}); + } +} + +void drawHud(SpriteBatch &batch, const Font &font, const HudState &hud) { + // 撃たれたとき:画面の縁を赤く / when hit: a red screen edge + if (hud.hurt > 0.0f) { + Vec4 red = {0.75f, 0.0f, 0.0f, 0.45f * hud.hurt}; + batch.drawRect({0.0f, 0.0f, 1280.0f, 36.0f}, red); + batch.drawRect({0.0f, 684.0f, 1280.0f, 36.0f}, red); + batch.drawRect({0.0f, 36.0f, 36.0f, 648.0f}, red); + batch.drawRect({1244.0f, 36.0f, 36.0f, 648.0f}, red); + } + // 撃たれた向き:照準のまわりの赤い弧(敵の方を指す) / where the hits came from: red arcs around the crosshair + // pointing at the shooters + for (const DamageMarker &d : hud.damage) { + Vec4 c = {1.0f, 0.15f, 0.1f, 0.9f * std::clamp(d.life, 0.0f, 1.0f)}; + for (int i = -2; i <= 2; ++i) spoke(batch, d.angle + 0.06f * static_cast(i), 120.0f, {14.0f, 5.0f}, c); + } + crosshair(batch, hud); + healthPanel(batch, font, hud); + ammoPanel(batch, font, hud); + enemiesPanel(batch, font, hud); +} diff --git a/games/tps/src/hud.hh b/games/tps/src/hud.hh new file mode 100644 index 0000000..4e48ec6 --- /dev/null +++ b/games/tps/src/hud.hh @@ -0,0 +1,36 @@ +// HUD(第39章):照準・体力・弾・残りの敵・撃たれた向き。第25・26章の2Dの道具(SpriteBatch・Font)で、 +// 後処理が終わった3Dの絵の上に描く(色はsRGBのまま、第25章の決まり)。1280 × 720の仮想画面 +// The HUD (chapter 39): crosshair, health, ammo, enemies left, where the hits came from. Drawn with the 2D toolkit of +// chapters 25-26 (SpriteBatch, Font) over the finished, post-processed 3D image (colors stay sRGB, the chapter 25 +// rule). A 1280 × 720 virtual screen +#pragma once + +#include "engine/font.hh" +#include "engine/sprite_batch.hh" + +#include + +// 撃たれた向きの印 / a damage-direction marker +struct DamageMarker { + float angle; // 画面の上 = 0、時計回り(ラジアン):カメラの向きから見た撃った敵の向き / screen up = 0, clockwise + // (radians): the shooter's direction relative to where the camera looks + float life; // 残り時間(秒) / seconds left +}; + +// HUDが描くもの全部(PlaySceneが毎フレーム詰める) / everything the HUD shows (PlayScene fills it every frame) +struct HudState { + float health = 100.0f; + float healthShown = 100.0f; // 遅れて減る薄い棒(どれだけ減ったか見える) / a lagging pale bar (shows the loss) + int ammo = 0, magazine = 0; + float reload = -1.0f; // 0〜1:込め直しの進み、−1 = していない / 0..1 reload progress, −1 = not reloading + int enemiesLeft = 0, enemiesTotal = 0; + float spread = 10.0f; // 照準の線の真ん中からの距離(px) / the crosshair lines' distance from the center (px) + float hitMarker = 0.0f; // 当てた印の残り(0〜1) / hit marker left (0..1) + bool killMarker = false; // 今の印は倒した一発 / the current marker is a kill + float hurt = 0.0f; // 画面の縁の赤(0〜1) / red screen edge (0..1) + bool alive = true; + std::vector damage; +}; + +// batch.begin(…)とend()の間で呼ぶ / call between batch.begin(...) and end() +void drawHud(SpriteBatch &batch, const Font &font, const HudState &hud); diff --git a/games/tps/src/main.cc b/games/tps/src/main.cc index 8d9bb4f..6035d12 100644 --- a/games/tps/src/main.cc +++ b/games/tps/src/main.cc @@ -1,7 +1,9 @@ // 第36〜39章:三人称シューティング(TPS)。第36章:レベル、キャラクター、三人称カメラ。第37章:当たり判定、重力、 -// ジャンプ、壁ずり。第38章:射撃、敵、体力、当たったときの効果 +// ジャンプ、壁ずり。第38章:射撃、敵、体力、当たったときの効果。第39章:HUD、タイトル → 遊ぶ → 勝ち・負け、 +// 速さの工夫、配布(インストール) // Chapters 36-39: the third-person shooter (TPS). Chapter 36: the level, the character and the third-person camera. -// Chapter 37: collision, gravity, jumping, wall sliding. Chapter 38: shooting, enemies, health, hit effects +// Chapter 37: collision, gravity, jumping, wall sliding. Chapter 38: shooting, enemies, health, hit effects. +// Chapter 39: HUD, title → play → win / lose, performance options, packaging (install) // // 操作 / Controls: // WASD カメラの向きに対して移動 / move relative to the camera @@ -12,9 +14,12 @@ // 右ボタン / RMB 狙う(肩に寄って視野が狭まる) / aim (closer over the shoulder, narrower view) // R 弾を込め直す / reload // Q 右肩 ⇔ 左肩 / right ⇔ left shoulder -// B 当たり判定の箱・カプセル・ソケット・軌跡 / collision boxes, capsule, sockets, trail +// B 当たり判定の箱・カプセル・ソケット・軌跡・敵のAI / collision boxes, capsule, sockets, trail, enemy AI // F3 時間と描いた数 / timings and draw counts // F4 視錐台カリングのオン・オフ / frustum culling on / off +// F5 描く解像度 100 → 75 → 50 % / render scale 100 → 75 → 50 % +// F6 影のオン・オフ / shadows on / off +// F7 影の地図 2048² ⇔ 1024² / shadow map 2048² ⇔ 1024² // C カメラだけ回す(キャラクターを前から見る) / turn only the camera (look at the character) // K カメラの当たり判定のオン・オフ / camera collision on / off // O 上から見下ろす(デバッグ) / view from above (debugging) @@ -22,29 +27,109 @@ // L 壁ずり ⇔ 壁で止まる(比べる) / wall sliding ⇔ stopping at walls (to compare) // P 手続き的な姿勢のオン・オフ(読み込んだままの姿勢) / procedural pose on / off (the pose as loaded) // Tab カーソルのキャプチャ / cursor capture -// Esc 終了 / quit -// 実行はプロジェクトのルートから:./build/games/tps/tps / run from the project root: ./build/games/tps/tps +// Esc 一時停止(タイトルでは終了) / pause (quit on the title) +// 引数:レベルのファイル(既定 games/tps/assets/levels/arena.level)、--play(タイトルを飛ばす)、--msaa(エンジンの +// 既定の後処理で比べる) +// Arguments: a level file (default games/tps/assets/levels/arena.level), --play (skip the title), --msaa (compare +// with the engine's default post chain) +// 実行はプロジェクトのルートから:./build/games/tps/tps。インストールした物(cmake --install)は実行ファイルの隣の +// データを自分で見つける +// Run from the project root: ./build/games/tps/tps. An installed copy (cmake --install) finds the data next to its +// executable by itself #include "game.hh" +#include "menu_scenes.hh" #include "play_scene.hh" #include "engine/scene.hh" #include #include +#include +#include #include #include +#include +#include +#include + +#if defined(__FreeBSD__) +#include +#include +#endif + +// 実行ファイルのある所。argv[0]は起動のしかたで変わり、PATHから起動すると名前(tps)だけなので、OSに聞く +// Where the executable is. argv[0] depends on how the program was started (only the name, "tps", when it was found +// through PATH), so ask the OS +static std::filesystem::path executableDirectory(const char *argv0) { + namespace fs = std::filesystem; + std::error_code ec; +#if defined(_WIN32) + char *path = nullptr; // CRTが用意するフルパス / the full path the C runtime provides + if (_get_pgmptr(&path) == 0 && path && *path) return fs::path(path).parent_path(); +#elif defined(__linux__) + fs::path self = fs::read_symlink("/proc/self/exe", ec); // 実行中のファイルへのリンク / a link to the running file + if (!ec) return self.parent_path(); +#elif defined(__FreeBSD__) + int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1}; // -1 = このプロセス / this process + char path[1024]; + size_t size = sizeof(path); + if (sysctl(mib, 4, path, &size, nullptr, 0) == 0) return fs::path(path).parent_path(); +#endif + // 他のOS、または聞けなかったとき:argv[0](ディレクトリが付いていれば使える) / other systems, or if asking failed: + // argv[0] (usable when it contains a directory) + fs::path p = fs::absolute(fs::path(argv0), ec); + return ec ? fs::path() : p.parent_path(); +} + +// データのある場所へ移る(第39章、配布)。開発中はプロジェクトのルートから実行するので、そこにデータがある。 +// インストールした物は実行ファイルの隣にengine/・assets/・games/tps/を置くので、見つからなければそこへ移る +// Move to where the data is (chapter 39, packaging). During development we run from the project root, which has the +// data. An installed copy keeps engine/, assets/ and games/tps/ next to the executable, so if the data is not found +// here, go there +static void findDataDirectory(const char *argv0) { + namespace fs = std::filesystem; + const fs::path marker = "games/tps/assets/levels/arena.level"; + std::error_code ec; + if (fs::exists(marker, ec)) return; + fs::path exeDir = executableDirectory(argv0); + if (!exeDir.empty() && fs::exists(exeDir / marker, ec)) { + fs::current_path(exeDir, ec); + printf("data: %s\n", exeDir.string().c_str()); + } else { + fprintf(stderr, "データが見つからない(プロジェクトのルートから実行する) / data not found (run from the project root)\n"); + } +} int main(int argc, char **argv) { + // 引数を先に読む:レベルのパスは起動したディレクトリから見たものなので、データの場所へ移る前に絶対パスにする + // Read the arguments first: a level path is relative to the directory we were started in, so make it absolute + // before moving to the data + std::string levelPath = "games/tps/assets/levels/arena.level"; + // --playでタイトルを飛ばしてすぐ遊ぶ(試すとき、台本で動かすとき) / --play skips the title (for testing and + // scripted runs) + bool skipTitle = false; + RenderSettings settings; + for (int i = 1; i < argc; ++i) { + if (std::string_view(argv[i]) == "--play") skipTitle = true; + // --msaa:エンジンの既定の後処理(4× MSAA、RGBA16F、ブルーム4組)と比べる / --msaa: compare with the engine's + // default post chain (4× MSAA, RGBA16F, 4 bloom pairs) + else if (std::string_view(argv[i]) == "--msaa") settings.post = PostChainSettings{}; + else { + std::error_code ec; + std::filesystem::path p = std::filesystem::absolute(argv[i], ec); + levelPath = ec ? std::string(argv[i]) : p.string(); + } + } + findDataDirectory(argv[0]); Window window; if (!window.create(1280, 720, "OpenGL Tutorial - TPS")) return 1; - - std::unique_ptr renderer = Renderer::create(window.width(), window.height()); + std::unique_ptr renderer = Renderer::create(window.width(), window.height(), settings); if (!renderer) return 1; window.onResize = [&](int width, int height) { renderer->resize(width, height); }; // 引数でほかのレベルも読める(例:部品を並べたpieces.level) / another level can be given as an argument (e.g. // pieces.level, which lines up every piece) - std::optional level = Level::load(argc > 1 ? argv[1] : "games/tps/assets/levels/arena.level"); + std::optional level = Level::load(levelPath); std::optional player = Model::load("games/tps/assets/models/player.glb"); std::optional rifle = Model::load("games/tps/assets/models/rifle.glb"); std::optional enemy = Model::load("games/tps/assets/models/enemy.glb"); @@ -71,6 +156,7 @@ int main(int argc, char **argv) { input.bind("fire", {InputBinding::mouse(GLFW_MOUSE_BUTTON_LEFT)}); input.bind("aim", {InputBinding::mouse(GLFW_MOUSE_BUTTON_RIGHT)}); input.bind("reload", {InputBinding::key(GLFW_KEY_R)}); + input.bind("confirm", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_ENTER)}); GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); Game game{.window = window, .input = input, .loop = loop, .renderer = *renderer, .batch = *batch, .ui = *ui, @@ -79,7 +165,9 @@ int main(int argc, char **argv) { .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}}; SceneManager scenes; - scenes.push(std::make_unique(game)); + // 第39章:タイトルから / chapter 39: start at the title + if (skipTitle) scenes.push(std::make_unique(game)); + else scenes.push(std::make_unique(game)); // pushは予約だけ:更新0回の最初のフレームも描けるように、ここで適用する(シーンの更新は呼ばれない) // push only queues the request: apply it now so that the first frame (which runs no update) has a scene to draw // (no scene's update is called) diff --git a/games/tps/src/menu_scenes.cc b/games/tps/src/menu_scenes.cc new file mode 100644 index 0000000..508aeb3 --- /dev/null +++ b/games/tps/src/menu_scenes.cc @@ -0,0 +1,134 @@ +#include "menu_scenes.hh" + +#include "play_scene.hh" + +#include +#include +#include + +constexpr Vec4 kShadow = {0.0f, 0.0f, 0.0f, 0.9f}; +constexpr Vec4 kGold = {1.0f, 0.82f, 0.35f, 1.0f}; +constexpr Transition kFade = {.duration = 0.8f}; + +//------------------------------------------ +// TitleScene +//------------------------------------------ + +void TitleScene::enter() { g.window.setCursorCaptured(false); } + +void TitleScene::update(float dt) { + prevTime = time; + time += dt; + if (g.input.actionPressed("confirm")) scenes().replace(std::make_unique(g), kFade); + if (g.input.pressed(GLFW_KEY_ESCAPE)) scenes().pop(); // 最後のシーン → 終了 / the last scene → quit +} + +void TitleScene::draw(float alpha) { + // 背景:レベルの上をゆっくり回るカメラ(遊ぶときと同じ3Dのフレーム:影 → 場面 → 後処理) + // Background: a camera slowly circling over the level (the same 3D frame as in play: shadows → scene → post) + Renderer &r = g.renderer; + float t = prevTime + (time - prevTime) * alpha; + float a = 0.12f * t + 0.6f; + FrameView view; + view.eye = {15.0f * std::sin(a), 5.5f, 15.0f * std::cos(a)}; + view.forward = normalize(Vec3{0.0f, 2.0f, 0.0f} - view.eye); + view.aspect = static_cast(g.window.width()) / static_cast(g.window.height()); + view.time = t; + LightSet lights; + lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {2.6f, 2.45f, 2.2f}}; + r.beginFrame(view, lights); + if (r.beginShadows()) { + g.level.drawShadows(*r.shadow, r.white, r.lightFrustum()); + r.endShadows(); + } + r.beginScene(); + r.pbrInstanced->use(); + g.level.draw(*r.pbrInstanced, r.white, r.viewFrustum()); + r.drawSky(); + r.endScene(); + r.present(g.window.width(), g.window.height()); +} + +void TitleScene::drawUi(float /*alpha*/) { + SpriteBatch &batch = g.batch; + batch.begin(g.screen.matrix()); + batch.drawRect({0.0f, 190.0f, 1280.0f, 260.0f}, {0.02f, 0.03f, 0.06f, 0.6f}); + g.ui.draw(batch, "三人称シューティング", {640.0f, 214.0f}, + {.color = {0.85f, 0.9f, 1.0f, 1.0f}, .scale = 2.0f, .align = TextAlign::Centre, .shadow = kShadow}); + g.ui.draw(batch, "THIRD-PERSON SHOOTER", {640.0f, 262.0f}, + {.color = kGold, .scale = 4.0f, .align = TextAlign::Centre, .shadow = kShadow, .shadowOffset = {1.0f, 1.0f}}); + g.ui.draw(batch, "OpenGL Tutorial 第36〜39章 / chapters 36-39", {640.0f, 350.0f}, + {.color = {0.8f, 0.8f, 0.85f, 1.0f}, .align = TextAlign::Centre, .shadow = kShadow}); + float blink = 0.55f + 0.45f * std::cos(4.0f * time); + g.ui.draw(batch, "スペースキーで開始 / PRESS SPACE", {640.0f, 392.0f}, + {.color = {1.0f, 1.0f, 1.0f, blink}, .scale = 1.5f, .align = TextAlign::Centre, .shadow = kShadow}); + g.ui.draw(batch, + "WASD 移動 / move マウス / mouse 見回す / look LMB 撃つ / fire RMB 狙う / aim R 装填 / reload\n" + "Space 跳ぶ / jump Shift 走る / run Q 肩 / shoulder Esc 一時停止 / pause F3 時間 / timings", + {640.0f, 650.0f}, {.color = {1.0f, 1.0f, 1.0f, 0.8f}, .align = TextAlign::Centre, .shadow = kShadow}); + batch.end(); +} + +//------------------------------------------ +// ResultScene +//------------------------------------------ + +// 結果の画面ではマウスを使えるように(もう一度:PlayScene::enterがまた捕まえる) / free the cursor on the result +// screen (retry: PlayScene::enter captures it again) +void ResultScene::enter() { g.window.setCursorCaptured(false); } + +void ResultScene::update(float dt) { + time += dt; + if (time < 0.5f) return; // 撃ち続けていたボタンで飛ばさない / do not skip it with a button still held from play + if (g.input.actionPressed("confirm")) scenes().replaceAll(std::make_unique(g), kFade); + if (g.input.pressed(GLFW_KEY_ESCAPE)) scenes().replaceAll(std::make_unique(g), kFade); +} + +void ResultScene::drawUi(float /*alpha*/) { + SpriteBatch &batch = g.batch; + batch.begin(g.screen.matrix()); + float k = std::fmin(time / 0.4f, 1.0f); // 0.4秒で暗くなる / darkens over 0.4 s + batch.drawRect({0.0f, 0.0f, 1280.0f, 720.0f}, {0.0f, 0.0f, 0.0f, 0.45f * k}); + batch.drawRect({340.0f, 180.0f, 600.0f, 340.0f}, {0.03f, 0.04f, 0.07f, 0.85f * k}); + Vec4 title = r.won ? kGold : Vec4{1.0f, 0.3f, 0.25f, 1.0f}; + title.w = k; + g.ui.draw(batch, r.won ? "任務完了" : "任務失敗", {640.0f, 200.0f}, + {.color = title, .scale = 2.0f, .align = TextAlign::Centre, .shadow = kShadow}); + g.ui.draw(batch, r.won ? "MISSION COMPLETE" : "MISSION FAILED", {640.0f, 244.0f}, + {.color = title, .scale = 3.0f, .align = TextAlign::Centre, .shadow = kShadow}); + int minutes = static_cast(r.seconds) / 60; + float seconds = r.seconds - 60.0f * static_cast(minutes); + float accuracy = r.shotsFired > 0 ? 100.0f * static_cast(r.shotsHit) / static_cast(r.shotsFired) : 0.0f; + std::string stats = std::format("時間 / TIME {}:{:04.1f}\n撃破 / KILLS {} / {}\n命中率 / ACCURACY {:.0f}% ({}/{})", + minutes, seconds, r.kills, r.enemies, accuracy, r.shotsHit, r.shotsFired); + g.ui.draw(batch, stats, {440.0f, 320.0f}, {.color = {0.9f, 0.9f, 0.95f, k}, .scale = 1.5f, .shadow = kShadow}); + float blink = 0.6f + 0.4f * std::cos(4.0f * time); + g.ui.draw(batch, "Space もう一度 / retry Esc タイトルへ / title", {640.0f, 470.0f}, + {.color = {1.0f, 1.0f, 1.0f, k * blink}, .align = TextAlign::Centre, .shadow = kShadow}); + batch.end(); +} + +//------------------------------------------ +// PauseScene +//------------------------------------------ + +void PauseScene::enter() { g.window.setCursorCaptured(false); } +void PauseScene::exit() { g.window.setCursorCaptured(true); } + +void PauseScene::update(float dt) { + time += dt; + if (g.input.pressed(GLFW_KEY_ESCAPE) || g.input.actionPressed("confirm")) scenes().pop(); + if (g.input.pressed(GLFW_KEY_T)) scenes().replaceAll(std::make_unique(g), kFade); +} + +void PauseScene::drawUi(float /*alpha*/) { + SpriteBatch &batch = g.batch; + batch.begin(g.screen.matrix()); + float k = std::fmin(time / 0.25f, 1.0f); + batch.drawRect({0.0f, 0.0f, 1280.0f, 720.0f}, {0.0f, 0.0f, 0.0f, 0.5f * k}); + g.ui.draw(batch, "一時停止 / PAUSED", {640.0f, 280.0f}, + {.color = {1.0f, 1.0f, 1.0f, k}, .scale = 3.0f, .align = TextAlign::Centre, .shadow = kShadow}); + g.ui.draw(batch, "Esc / Space 再開 / resume T タイトルへ / title", {640.0f, 360.0f}, + {.color = {0.9f, 0.9f, 0.95f, k}, .scale = 1.5f, .align = TextAlign::Centre, .shadow = kShadow}); + batch.end(); +} diff --git a/games/tps/src/menu_scenes.hh b/games/tps/src/menu_scenes.hh new file mode 100644 index 0000000..8d57be3 --- /dev/null +++ b/games/tps/src/menu_scenes.hh @@ -0,0 +1,62 @@ +// ゲームの流れ(第39章):タイトル → 遊ぶ → 勝ち・負けの画面、一時停止。第26章のSceneManagerで切り替える +// Game flow (chapter 39): title → play → win / lose screen, plus pause. Switched with chapter 26's SceneManager +#pragma once + +#include "game.hh" + +#include "engine/scene.hh" + +// タイトル:レベルの上をゆっくり回るカメラ+題名。Space / Enterで始める、Escで終了 +// The title: a camera slowly circling over the level + the title. Space / Enter starts, Esc quits +class TitleScene : public Scene { +public: + explicit TitleScene(Game &game) : g(game) {} + void enter() override; + void update(float dt) override; + void draw(float alpha) override; + void drawUi(float alpha) override; + +private: + Game &g; + float time = 0.0f, prevTime = 0.0f; +}; + +// 一回の結果(PlaySceneが渡す) / the outcome of one round (PlayScene hands it over) +struct RoundResult { + bool won = false; + float seconds = 0.0f; + int kills = 0, enemies = 0, shotsFired = 0, shotsHit = 0; +}; + +// 勝ち・負け:PlaySceneの上に重ねる(下の絵は止まったまま見える)。Space もう一度、Esc タイトルへ +// Win / lose: an overlay on PlayScene (the frozen picture stays visible below). Space retry, Esc back to the title +class ResultScene : public Scene { +public: + ResultScene(Game &game, RoundResult result) : g(game), r(result) {} + bool isOverlay() const override { return true; } + void enter() override; + void update(float dt) override; + void draw(float /*alpha*/) override {} + void drawUi(float alpha) override; + +private: + Game &g; + RoundResult r; + float time = 0.0f; +}; + +// 一時停止:Esc / Space 再開、T タイトルへ / pause: Esc / Space resume, T back to the title +class PauseScene : public Scene { +public: + explicit PauseScene(Game &game) : g(game) {} + bool isOverlay() const override { return true; } + void enter() override; + void exit() override; + void update(float dt) override; + void draw(float /*alpha*/) override {} + void drawUi(float alpha) override; + +private: + Game &g; + float time = 0.0f; +}; diff --git a/games/tps/src/play_scene.cc b/games/tps/src/play_scene.cc index 0959b0b..a902d99 100644 --- a/games/tps/src/play_scene.cc +++ b/games/tps/src/play_scene.cc @@ -1,6 +1,7 @@ #include "play_scene.hh" #include "angles.hh" +#include "menu_scenes.hh" #include #include @@ -25,7 +26,6 @@ constexpr float kReloadTime = 1.6f; constexpr float kDamage = 34.0f; // 胸に3発、頭に2発 / three to the chest, two to the head constexpr float kEnemyDamage = 8.0f; constexpr float kHearing = 18.0f; // 銃声が聞こえる距離 / how far a shot is heard -constexpr float kRespawnTime = 3.0f; // 円錐の中のでたらめな向き(拡散):axisから最大angleラジアン / a random direction inside a cone (spread): at most angle // radians from axis @@ -77,7 +77,9 @@ void PlayScene::update(float dt) { prevForward = camera.forward(); time += dt; - if (in.pressed(GLFW_KEY_ESCAPE)) scenes().pop(); // 最後のシーン → 終了 / the last scene → quit + // Esc:一時停止(第39章。上に重ねるので、この場面は止まったまま描かれる) / Esc: pause (chapter 39; an overlay, so + // this scene stays visible, frozen) + if (in.pressed(GLFW_KEY_ESCAPE)) scenes().push(std::make_unique(g)); if (in.pressed(GLFW_KEY_TAB)) g.window.setCursorCaptured(!g.window.cursorCaptured()); if (in.pressed(GLFW_KEY_Q)) camera.shoulderSide = -camera.shoulderSide; if (in.pressed(GLFW_KEY_B)) g.showBoxes = !g.showBoxes; @@ -89,6 +91,14 @@ void PlayScene::update(float dt) { if (in.pressed(GLFW_KEY_L)) body.slide = !body.slide; if (in.pressed(GLFW_KEY_O)) overhead = !overhead; if (in.pressed(GLFW_KEY_F8)) logging = !logging; + // 速さの工夫(第39章):F5 描く解像度 100 → 75 → 50 %、F6 影のオン・オフ、F7 影の地図 2048 ⇔ 1024 + // Performance options (chapter 39): F5 render scale 100 → 75 → 50 %, F6 shadows on / off, F7 shadow map 2048 ⇔ 1024 + if (in.pressed(GLFW_KEY_F5)) { + float s = g.renderer.renderScale(); + g.renderer.setRenderScale(s > 0.9f ? 0.75f : s > 0.6f ? 0.5f : 1.0f); + } + if (in.pressed(GLFW_KEY_F6)) g.renderer.settings.shadows = !g.renderer.settings.shadows; + if (in.pressed(GLFW_KEY_F7)) g.renderer.setShadowMapSize(g.renderer.shadowMapSize() == 2048 ? 1024 : 2048); // 1. 見回す(マウスの動きはフレームごと:最初のステップだけが使う) / 1. look around (mouse movement is per frame: // only the first step uses it) @@ -184,21 +194,35 @@ void PlayScene::update(float dt) { separateCharacters(); effects.update(dt); - // 8. 体力:撃たれなければ4秒後から回復。倒れたら3秒後に出発点から(第39章で負けの画面になる) - // 8. health: regenerates from 4 s after the last hit. When down, back at the start after 3 s (chapter 39 turns this - // into the defeat screen) + // 8. 体力:撃たれなければ4秒後から回復。0で負け(第39章:結果の画面へ) / 8. health: regenerates from 4 s after + // the last hit; 0 = defeat (chapter 39: to the result screen) hurt = std::fmax(hurt - dt, 0.0f); sinceHurt += dt; if (alive && sinceHurt > 4.0f) health = std::fmin(health + 12.0f * dt, 100.0f); - if (!alive && (deadTime += dt) > kRespawnTime) { - alive = true; - health = 100.0f; - ammo = kMagazine; - body.position = position = prevPosition = g.level.spawn; - body.velocity = {0.0f, 0.0f, 0.0f}; - camera.reset(cameraPivot(), g.level.solids); // カメラもすぐ出発点へ / the camera cuts to the spawn too - prevEye = camera.eye(); - prevForward = camera.forward(); + if (!alive) deadTime += dt; + + // 9. HUDの値(第39章) / 9. the HUD's values (chapter 39) + int left = 0; + for (const Enemy &e : enemies) left += e.alive() ? 1 : 0; + if (alive && left > 0) roundTime += dt; + // 遅れて減る棒:0.4秒待ってから毎秒40ずつ追いつく / the lagging bar waits 0.4 s, then catches up at 40 per second + if (sinceHurt > 0.4f) hud.healthShown = std::fmax(hud.healthShown - 40.0f * dt, health); + hud.healthShown = std::fmax(hud.healthShown, health); + for (DamageMarker &d : hud.damage) d.life -= dt; + std::erase_if(hud.damage, [](const DamageMarker &d) { return d.life <= 0.0f; }); + + // 10. 勝ち・負け:少し見せてから結果の画面を重ねる。敵のいないレベル(pieces.level)は勝ちにならない + // 10. win / loss: show it for a moment, then push the result screen. A level without enemies (pieces.level) is + // never won + bool cleared = left == 0 && !enemies.empty(); + if (!finished && (!alive || cleared)) { + endTimer += dt; + if (endTimer > (alive ? 2.0f : 2.5f)) { + finished = true; + RoundResult result{.won = alive, .seconds = roundTime, .kills = kills, + .enemies = static_cast(enemies.size()), .shotsFired = shotsFired, .shotsHit = shotsHit}; + scenes().push(std::make_unique(g, result)); + } } } @@ -275,9 +299,10 @@ void PlayScene::shoot() { Enemy &e = enemies[static_cast(index)]; bool wasAlive = e.alive(); e.alert(position, kDamage * multiplier); - if (wasAlive && !e.alive()) ++kills; + killed = wasAlive && !e.alive(); + if (killed) ++kills; ++shotsHit; - hitMarker = 0.15f; + hitMarker = killed ? 0.35f : 0.15f; effects.sparks(end, -1.0f * dir, {6.0f, 0.9f, 0.4f}, 14, rng); // 赤い火花 / red sparks } else if (wall) { end = blocked ? start : muzzle + wall->t * dir; @@ -305,6 +330,10 @@ void PlayScene::enemyFire(Enemy &e, Vec3 aim) { effects.tracer(muzzle, end, {6.0f, 1.4f, 0.5f}); if (hit) { hurtPlayer(kEnemyDamage); + // HUDの撃たれた向き:撃った敵の水平の向きを、カメラの向きから測る / the HUD's damage direction: the shooter's + // horizontal direction measured from where the camera looks + Vec3 d = e.body.position - position; + hud.damage.push_back({wrapAngle(std::atan2(d.x, -d.z) - camera.yaw), 1.0f}); effects.sparks(end, -1.0f * dir, {6.0f, 0.9f, 0.4f}, 8, rng); } else if (wall) { effects.sparks(end, wall->normal, {5.0f, 3.2f, 1.2f}, 8, rng); @@ -347,7 +376,7 @@ void PlayScene::separateCharacters() { void PlayScene::logState() const { Vec3 eye = camera.eye(); - printf("log frame %d pos (%.2f %.2f %.2f) eye (%.3f %.3f %.3f) yaw %.4f pitch %.4f hp %.0f ammo %d |", g.frame, + printf("log frame %d t %.4f pos (%.2f %.2f %.2f) eye (%.3f %.3f %.3f) yaw %.4f pitch %.4f hp %.0f ammo %d |", g.frame, static_cast(time), position.x, position.y, position.z, eye.x, eye.y, eye.z, camera.yaw, camera.pitch, health, ammo); for (const Enemy &e : enemies) printf(" %s (%.2f %.2f %.2f) %.0f%s |", enemyStateName(e.state), e.body.position.x, e.body.position.y, @@ -558,7 +587,7 @@ void PlayScene::drawUi(float /*alpha*/) { "level pieces drawn {}/{} ({} draw calls) shadow casters {} ({} draw calls) shadow texel {:.1f} mm\n" "camera distance {:.2f} m{}{} collision boxes {} culling {} scene fragments {:.2f} M\n" "body: {} {}{}{} contacts {} y {:.2f} m velocity ({:.1f}, {:.1f}, {:.1f}) jumps {} wall slide {}\n" - "particles {} kills {} deaths {}", + "particles {} kills {} deaths {} render scale {:.0f} % (F5) shadows {} {} px (F6/F7)", g.frameMs, r.timings.shadowMs, r.timings.sceneMs, r.timings.postMs, levelStats.visible, levelStats.total, levelStats.drawCalls, shadowStats.visible, shadowStats.drawCalls, r.shadowTexelMm(), camera.currentDistance(), camera.blocked() ? " (pulled in by a wall)" : "", @@ -566,47 +595,34 @@ void PlayScene::drawUi(float /*alpha*/) { static_cast(r.timings.sceneFragments) / 1e6, body.grounded ? "grounded" : "airborne", body.hitWall ? "wall " : "", body.steppedUp ? "stepped-up " : "", body.snappedDown ? "snapped-down " : "", body.contacts, body.position.y, body.velocity.x, body.velocity.y, body.velocity.z, jumps, - body.slide ? "on" : "OFF (L)", effects.particleCount(), kills, deaths); - batch.drawRect({0.0f, 0.0f, 1280.0f, 108.0f}, {0.0f, 0.0f, 0.0f, 0.45f}); - g.ui.draw(batch, lines, {10.0f, 6.0f}, small); - } - // 照準(第38章の簡単なもの。第39章でHUDになる):真ん中の点と4本の線。拡散が大きいほど開く。当てると赤く - // The crosshair (chapter 38's simple one; chapter 39 makes it a HUD): a center dot and four lines that open with the - // spread; red on a hit - if (alive) { - float moving = length(Vec3{body.velocity.x, 0.0f, body.velocity.z}) > 0.5f ? 1.0f : 0.0f; - float gap = 5.0f + 9.0f * (1.0f - aimBlend) + 8.0f * moving; - Vec4 c = hitMarker > 0.0f ? Vec4{1.0f, 0.25f, 0.2f, 1.0f} : Vec4{1.0f, 1.0f, 1.0f, 0.9f}; - batch.drawRect({639.0f, 359.0f, 2.0f, 2.0f}, c); - batch.drawRect({639.0f, 360.0f - gap - 8.0f, 2.0f, 8.0f}, c); - batch.drawRect({639.0f, 360.0f + gap, 2.0f, 8.0f}, c); - batch.drawRect({640.0f - gap - 8.0f, 359.0f, 8.0f, 2.0f}, c); - batch.drawRect({640.0f + gap, 359.0f, 8.0f, 2.0f}, c); - } - // 撃たれたら画面の縁を赤く / a red screen edge when hit - if (hurt > 0.0f) { - Vec4 red = {0.8f, 0.0f, 0.0f, 0.5f * hurt / 0.35f}; - batch.drawRect({0.0f, 0.0f, 1280.0f, 40.0f}, red); - batch.drawRect({0.0f, 680.0f, 1280.0f, 40.0f}, red); - batch.drawRect({0.0f, 40.0f, 40.0f, 640.0f}, red); - batch.drawRect({1240.0f, 40.0f, 40.0f, 640.0f}, red); + body.slide ? "on" : "OFF (L)", effects.particleCount(), kills, deaths, 100.0f * r.renderScale(), + r.settings.shadows ? "on" : "OFF", r.shadowMapSize()); + // HUDの敵の枠(y 16〜68)の下に / below the HUD's enemies panel (y 16-68) + batch.drawRect({0.0f, 76.0f, 1280.0f, 108.0f}, {0.0f, 0.0f, 0.0f, 0.55f}); + g.ui.draw(batch, lines, {10.0f, 82.0f}, small); } + // HUD(第39章):毎フレーム状態を詰めて描く / the HUD (chapter 39): fill in the state and draw it every frame int left = 0; for (const Enemy &e : enemies) left += e.alive() ? 1 : 0; - std::string status = std::format("体力 / HP {:3.0f} 弾 / AMMO {:2d}/{}{} 敵 / ENEMIES {}/{} hits {}/{}", health, - ammo, kMagazine, reloadTime > 0.0f ? " (装填 / reloading)" : "", left, - enemies.size(), shotsHit, shotsFired); - g.ui.draw(batch, status, {20.0f, 660.0f}, {.color = {1.0f, 1.0f, 1.0f, 0.95f}, .scale = 1.0f, - .shadow = {0.0f, 0.0f, 0.0f, 0.9f}}); - if (!alive) + float moving = length(Vec3{body.velocity.x, 0.0f, body.velocity.z}) > 0.5f ? 1.0f : 0.0f; + hud.health = health; + hud.ammo = ammo; + hud.magazine = kMagazine; + hud.reload = reloadTime > 0.0f ? 1.0f - reloadTime / kReloadTime : -1.0f; + hud.enemiesLeft = left; + hud.enemiesTotal = static_cast(enemies.size()); + hud.spread = 5.0f + 9.0f * (1.0f - aimBlend) + 8.0f * moving + (fireTimer > 0.0f ? 4.0f : 0.0f); + hud.hitMarker = std::fmax(hitMarker, 0.0f) / (killed ? 0.35f : 0.15f); + hud.killMarker = killed; + hud.hurt = hurt / 0.35f; + hud.alive = alive; + drawHud(batch, g.ui, hud); + // 結果の画面が出たら消す(重なって読めない) / hidden once the result screen is up (they would overlap) + if (!alive && !finished) g.ui.draw(batch, "倒れた / DOWN", {640.0f, 300.0f}, {.color = {1.0f, 0.3f, 0.25f, 1.0f}, .scale = 3.0f, .align = TextAlign::Centre, .shadow = {0, 0, 0, 0.9f}}); - else if (left == 0) + else if (left == 0 && !enemies.empty() && !finished) g.ui.draw(batch, "敵を全部倒した / ALL ENEMIES DOWN", {640.0f, 300.0f}, {.color = {1.0f, 0.85f, 0.3f, 1.0f}, .scale = 2.0f, .align = TextAlign::Centre, .shadow = {0, 0, 0, 0.9f}}); - g.ui.draw(batch, "LMB 撃つ / fire RMB 狙う / aim R 装填 / reload Space 跳ぶ / jump Shift 走る / run " - "Q 肩 / shoulder", - {640.0f, 694.0f}, {.color = {1.0f, 1.0f, 1.0f, 0.7f}, .align = TextAlign::Centre, - .shadow = {0.0f, 0.0f, 0.0f, 0.8f}}); batch.end(); } diff --git a/games/tps/src/play_scene.hh b/games/tps/src/play_scene.hh index 068e8a7..a45289e 100644 --- a/games/tps/src/play_scene.hh +++ b/games/tps/src/play_scene.hh @@ -8,6 +8,7 @@ #include "effects.hh" #include "enemy.hh" #include "game.hh" +#include "hud.hh" #include "third_person_camera.hh" #include "engine/rng.hh" @@ -82,5 +83,12 @@ private: float aimBlend = 0.0f; // 0 = 腰だめ、1 = 狙う(右ボタン) / 0 = hip fire, 1 = aiming (right button) float hitMarker = 0.0f; // 当てたときの印の残り / remaining hit-marker time int shotsFired = 0, shotsHit = 0, kills = 0, deaths = 0; + + // 第39章:HUD、ゲームの流れ / chapter 39: HUD, game flow + HudState hud; + bool killed = false; // 今の当てた印は倒した一発 / the current hit marker is a kill + float roundTime = 0.0f; // 遊んだ時間 / time played + float endTimer = 0.0f; // 勝ち・負けから結果の画面まで / from win / loss to the result screen + bool finished = false; // 結果の画面を出した / the result screen was shown LevelDrawStats levelStats, shadowStats; }; diff --git a/games/tps/src/renderer.cc b/games/tps/src/renderer.cc index dc2722b..bcd1bfb 100644 --- a/games/tps/src/renderer.cc +++ b/games/tps/src/renderer.cc @@ -2,6 +2,7 @@ #include "engine/shapes.hh" +#include #include #include @@ -64,6 +65,8 @@ std::unique_ptr Renderer::create(int width, int height, const RenderSe r->ibl = Ibl::build(*r->sky); r->shadowMap.emplace(settings.shadowMapSize); r->post = PostChain::create(width, height, settings.post); + r->windowW = width; + r->windowH = height; if (!r->ibl || !r->shadowMap->complete() || !r->post) return nullptr; const unsigned char whitePixel[4] = {255, 255, 255, 255}; @@ -73,6 +76,18 @@ std::unique_ptr Renderer::create(int width, int height, const RenderSe return r; } +void Renderer::resize(int width, int height) { + windowW = width; + windowH = height; + setRenderScale(scale); +} + +void Renderer::setRenderScale(float s) { + scale = s; + post->resize(std::max(1, static_cast(std::lround(s * static_cast(windowW)))), + std::max(1, static_cast(std::lround(s * static_cast(windowH))))); +} + void Renderer::beginFrame(const FrameView &view, const LightSet &lights) { current = view; sunDirection = lights.directional.direction; diff --git a/games/tps/src/renderer.hh b/games/tps/src/renderer.hh index 8ffcc77..2d881fe 100644 --- a/games/tps/src/renderer.hh +++ b/games/tps/src/renderer.hh @@ -110,7 +110,16 @@ public: void endScene(); // 画面へ(後処理)。この後は既定のフレームバッファ / to the screen (post); afterwards the default framebuffer is bound void present(int windowWidth, int windowHeight); - void resize(int width, int height) { post->resize(width, height); } + // ウィンドウの大きさが変わった / the window size changed + void resize(int width, int height); + // 描く解像度(第39章の速さの工夫):場面のFBOをウィンドウのscale倍にして、後処理で画面いっぱいに引き伸ばす。 + // フラグメントの数がscale²倍になる + // Render scale (chapter 39's performance tip): the scene FBOs are scale × the window size and the post pass + // stretches them over the screen. The fragment count goes with scale² + void setRenderScale(float scale); + float renderScale() const { return scale; } + void setShadowMapSize(int size) { shadowMap->resize(size); } + int shadowMapSize() const { return shadowMap->size(); } // ゲームが描くのに使うもの / what the game draws with std::optional pbr; // phong.vert + pbr.frag:一つずつ描く物 / single objects @@ -141,5 +150,7 @@ private: FragmentCounter sceneFragments; FrameView current; Vec3 sunDirection = {-0.5f, -1.0f, -0.35f}; + int windowW = 1280, windowH = 720; // ウィンドウの大きさ / the window size + float scale = 1.0f; Frustum lightBox, cameraFrustum; };