diff --git a/games/invaders/CMakeLists.txt b/games/invaders/CMakeLists.txt new file mode 100644 index 0000000..eacf467 --- /dev/null +++ b/games/invaders/CMakeLists.txt @@ -0,0 +1,12 @@ +# Invaders(第27〜29章):エンジンだけを使う一つの実行ファイル。プロジェクトのルートから ./build/games/invaders/invaders +# Invaders (chapters 27-29): one executable that only uses the engine. Run ./build/games/invaders/invaders from the +# project root +add_executable(invaders + src/main.cc + src/play_scene.cc + src/formation.cc + src/formation_renderer.cc) +target_include_directories(invaders PRIVATE src) +target_link_libraries(invaders PRIVATE engine) +enable_warnings(invaders) +set_working_directory(invaders) diff --git a/games/invaders/README.md b/games/invaders/README.md new file mode 100644 index 0000000..40554ad --- /dev/null +++ b/games/invaders/README.md @@ -0,0 +1,26 @@ +# Invaders(第27〜29章 / chapters 27-29) + +エンジン(`engine`)だけを使うスペースインベーダー風のゲーム。 / A Space Invaders style game that uses only the engine. + +```sh +cmake --build build -j8 +./build/games/invaders/invaders # プロジェクトのルートから / from the project root +``` +Visual Studio: `build\games\invaders\Debug\invaders.exe`(作業ディレクトリはルートに設定済み / the working directory +is already the project root)。 + +## 操作 / Controls +| キー / Key | | +|---|---| +| ← → / A D | 移動 / move | +| I | 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch | +| = / - | 行進を速く・遅く / march faster / slower | +| Esc | 終了 / quit | + +## ファイル / Files +* `src/main.cc` ウィンドウ、読み込み、行動、ゲームループ / window, loading, actions, game loop +* `src/game.hh` 共有データ・画面の寸法・シーン / shared data, layout, scenes +* `src/play_scene.cc` 遊ぶ場面 / the play scene +* `src/formation.hh/.cc` 隊列と行進(GLなし) / the formation and its march (no GL) +* `src/formation_renderer.hh/.cc`, `shaders/formation.vert` インスタンシングで隊列を描く / instanced formation drawing +* `assets/` 絵(作者の自作スクリプトで生成。スクリプトはダウンロードに含まれない) / art (generated by the author's own script, not part of the download) diff --git a/games/invaders/assets/LICENSE.txt b/games/invaders/assets/LICENSE.txt new file mode 100644 index 0000000..d62e089 --- /dev/null +++ b/games/invaders/assets/LICENSE.txt @@ -0,0 +1,6 @@ +games/invaders/assets/ のファイルはこのチュートリアルのために作者が自作したもの(作者のPythonのスクリプトで生成。スクリプトはこのプロジェクトには含まれない)。自由に使ってよい。 +The files in games/invaders/assets/ were made for this tutorial by the author (generated with the author's own Python scripts, which are not part of this project). Free to use for any purpose. + +sprites.png/.atlas 宇宙人3種(各2コマ)・爆発・自機・円盤・弾・着弾・防壁・ロゴ / three aliens (2 poses each), + explosions, the ship, the saucer, bullets, an impact, a shield, the logo + (chapter 27) diff --git a/games/invaders/assets/sprites.atlas b/games/invaders/assets/sprites.atlas new file mode 100644 index 0000000..05b5fb5 --- /dev/null +++ b/games/invaders/assets/sprites.atlas @@ -0,0 +1,30 @@ +# Invaders sprites (chapters 27-29), generated by the author's own script +image sprites.png +sprite jelly_0 1 1 14 10 +sprite jelly_1 17 1 14 10 +sprite beetle_0 33 1 14 10 +sprite beetle_1 49 1 14 10 +sprite blob_0 65 1 14 10 +sprite blob_1 81 1 14 10 +sprite alien_boom_0 97 1 14 10 +sprite alien_boom_1 113 1 14 10 +sprite ship 1 13 15 9 +sprite ship_boom_0 18 13 15 9 +sprite ship_boom_1 35 13 15 9 +sprite ufo 52 13 18 8 +sprite shot 72 13 1 5 +sprite zig_0 75 13 3 7 +sprite zig_1 80 13 3 7 +sprite zig_2 85 13 3 7 +sprite zig_3 90 13 3 7 +sprite bolt_0 95 13 3 7 +sprite bolt_1 100 13 3 7 +sprite bolt_2 105 13 3 7 +sprite bolt_3 110 13 3 7 +sprite splat 115 13 6 8 +sprite shield 1 24 22 16 +sprite logo 25 24 64 11 +clip alien_boom 8 once alien_boom_0 alien_boom_1 +clip ship_boom 8 loop ship_boom_0 ship_boom_1 +clip zig 12 loop zig_0 zig_1 zig_2 zig_3 +clip bolt 12 loop bolt_0 bolt_1 bolt_2 bolt_3 diff --git a/games/invaders/assets/sprites.png b/games/invaders/assets/sprites.png new file mode 100644 index 0000000..42eba20 Binary files /dev/null and b/games/invaders/assets/sprites.png differ diff --git a/games/invaders/shaders/formation.vert b/games/invaders/shaders/formation.vert new file mode 100644 index 0000000..e590fff --- /dev/null +++ b/games/invaders/shaders/formation.vert @@ -0,0 +1,27 @@ +#version 460 core +// 隊列のインスタンシング(第27章):頂点は四隅(0〜1)だけ。どこに・どのコマで・何色で描くかはインスタンスごとの属性 +// Formation instancing (chapter 27): the vertices are only the corners (0..1). Where, which frame and which color +// come from per-instance attributes +// フラグメントシェーダーはSpriteBatchと同じ engine/shaders/sprite.frag(vUv・vColorを受け取る) +// The fragment shader is SpriteBatch's engine/shaders/sprite.frag (it takes vUv and vColor) + +layout(location = 0) in vec2 aCorner; // 頂点ごと:(0,0) (1,0) (0,1) (1,1) / per vertex +layout(location = 8) in vec4 aInstanceColor; // インスタンスごと:RGBA8 → 0〜1(sRGB、乗算前) / per instance +layout(location = 9) in vec2 aInstanceOffset; // インスタンスごと:左上(ワールド座標) / per instance: top left +layout(location = 10) in uint aInstanceFrame; // インスタンスごと:コマ番号(整数の属性) / per instance: frame (integer) + +uniform mat4 uViewProjection; +// スプライトシートの各コマ:UVの四角 (x, y, w, h) と大きさ(ピクセル) / every sheet frame: UV rect and size in pixels +uniform vec4 uFrameUv[32]; +uniform vec2 uFrameSize[32]; + +out vec2 vUv; +out vec4 vColor; + +void main() { + vec4 uv = uFrameUv[aInstanceFrame]; + vUv = uv.xy + aCorner * uv.zw; + vColor = vec4(aInstanceColor.rgb * aInstanceColor.a, aInstanceColor.a); // 乗算済みに / premultiplied + vec2 world = aInstanceOffset + aCorner * uFrameSize[aInstanceFrame]; + gl_Position = uViewProjection * vec4(world, 0.0, 1.0); +} diff --git a/games/invaders/src/formation.cc b/games/invaders/src/formation.cc new file mode 100644 index 0000000..5cee312 --- /dev/null +++ b/games/invaders/src/formation.cc @@ -0,0 +1,84 @@ +#include "formation.hh" + +#include + +Rect Alien::box() const { return {position.x, position.y, kAlienSize.x, kAlienSize.y}; } + +void Formation::reset(float left, float top) { + aliens.clear(); + // 下の行から:行進は一番下の左端から始まる / bottom row first: the march starts at the bottom left + for (int row = kRows - 1; row >= 0; --row) + for (int col = 0; col < kColumns; ++col) { + AlienKind kind = row == 0 ? AlienKind::Jelly : row <= 2 ? AlienKind::Beetle : AlienKind::Blob; + aliens.push_back({.kind = kind, .column = col, .row = row, + .position = {left + kColumnSpacing * static_cast(col), + top + kRowSpacing * static_cast(row)}}); + } + direction = 1; + dropping = false; + passes = 0; + cursor = 0; + budget = 0.0f; +} + +int Formation::alive() const { + return static_cast(std::count_if(aliens.begin(), aliens.end(), [](const Alien &a) { return a.alive; })); +} + +Rect Formation::bounds() const { + bool any = false; + float l = 0, t = 0, r = 0, b = 0; + for (const Alien &a : aliens) { + if (!a.alive) continue; + Rect box = a.box(); + if (!any) { + l = box.left(), t = box.top(), r = box.right(), b = box.bottom(); + any = true; + } + l = std::min(l, box.left()), t = std::min(t, box.top()); + r = std::max(r, box.right()), b = std::max(b, box.bottom()); + } + return {l, t, r - l, b - t}; +} + +void Formation::update(float dt) { + if (alive() == 0) return; + // 1ステップ(1/60秒)にrate/60匹。予算は浮動小数点数の和なので少し許す(60 × (1/60)は丁度1.0fだが、 + // 1/50秒のステップでは5回目の更新の予算が2ではなく1.99999964になる) + // rate/60 aliens per 1/60 s step. The budget is a float sum, so allow a little (60 × (1/60) is exactly 1.0f, + // but with a 1/50 s step the fifth update's budget is 1.99999964, not 2) + budget += rate * dt; + while (budget > 0.999f) { + budget -= 1.0f; + moveOne(); + } +} + +void Formation::moveOne() { + // 死んだ宇宙人は飛ばす(順番を待たない) / skip dead aliens (they do not take a turn) + while (!aliens[cursor].alive) advanceCursor(); + Alien &a = aliens[cursor]; + if (dropping) a.position.y += stepY; + else a.position.x += stepX * static_cast(direction); + a.pose ^= 1; + advanceCursor(); +} + +void Formation::advanceCursor() { + if (++cursor < aliens.size()) return; + cursor = 0; + endPass(); +} + +// 一巡が終わった:下がり終えたなら向きを変え、端に届きそうなら次の一巡は下へ +// A pass is complete: after a drop, turn around; if the next step would cross an edge, the next pass drops +void Formation::endPass() { + ++passes; + if (dropping) { + dropping = false; + direction = -direction; + return; + } + Rect b = bounds(); + if ((direction > 0 && b.right() + stepX > maxX) || (direction < 0 && b.left() - stepX < minX)) dropping = true; +} diff --git a/games/invaders/src/formation.hh b/games/invaders/src/formation.hh new file mode 100644 index 0000000..d8e2366 --- /dev/null +++ b/games/invaders/src/formation.hh @@ -0,0 +1,56 @@ +// 宇宙人の隊列(第27章):11列 × 5行。行進は「一度に一匹」:更新ごとに次の一匹だけが動く(GLは使わない) +// The alien formation (chapter 27): 11 columns × 5 rows. The march moves "one alien at a time": each move shifts only +// the next alien (no GL in here) +#pragma once + +#include "engine/rect.hh" + +#include + +// 宇宙人の種類(上の行から):クラゲ、甲虫、丸い奴 / alien kinds (from the top row): jelly, beetle, blob +enum class AlienKind { Jelly = 0, Beetle = 1, Blob = 2 }; + +struct Alien { + AlienKind kind = AlienKind::Blob; + int column = 0, row = 0; // row 0 = 一番上 / the top row + Vec2 position; // 左上、整数のピクセル / top left, whole pixels + int pose = 0; // 0か1:動くたびに入れ替わる(足踏み) / 0 or 1: flips every time it moves (the walk) + bool alive = true; + Rect box() const; // 当たり判定 = 絵の枠 / the collision box = the sprite cell +}; + +constexpr int kColumns = 11, kRows = 5; +constexpr Vec2 kAlienSize = {14.0f, 10.0f}; // スプライトの枠 / the sprite cell +constexpr float kColumnSpacing = 16.0f, kRowSpacing = 14.0f; + +class Formation { +public: + // 全員を生き返らせ、左上の宇宙人の位置を(left, top)にして、右向きに歩き始める + // Brings everyone back, puts the top-left alien at (left, top) and starts marching right + void reset(float left, float top); + // 行進:1秒にrate匹ずつ、次の一匹を動かす。全員が一回ずつ動いたら(一巡)、端に着いていれば次の一巡で下がり、 + // 向きを変える。生き残りが少ないほど一人あたりの順番が早く回ってくる = 自然に速くなる + // The march: moves the next alien, `rate` aliens per second. When everyone has moved once (a pass) and the + // formation touches an edge, the next pass moves everyone down, then the direction flips. The fewer aliens are left, + // the sooner each one's turn comes around = the formation speeds up by itself + void update(float dt); + + int alive() const; + Rect bounds() const; // 生きている宇宙人を囲む箱(全滅なら大きさ0) / box around the living aliens (empty if none) + + std::vector aliens; // 行進の順番:下の行の左から右へ、それから上の行 / march order: bottom row left to right, + // then the row above + float rate = 60.0f; // 1秒に動く宇宙人の数 / aliens moved per second + float stepX = 2.0f, stepY = 6.0f; + float minX = 0.0f, maxX = 320.0f; // 行進できる範囲 / where the formation may go + int direction = 1; // +1 = 右 / right, -1 = 左 / left + bool dropping = false; // この一巡は下へ / this pass moves down + int passes = 0; // 終わった一巡の数 / completed passes + +private: + void moveOne(); + void advanceCursor(); + void endPass(); + size_t cursor = 0; // 次に動く宇宙人 / the alien that moves next + float budget = 0.0f; // 動かしてよい数(端数を持ち越す) / moves owed (fractions carry over) +}; diff --git a/games/invaders/src/formation_renderer.cc b/games/invaders/src/formation_renderer.cc new file mode 100644 index 0000000..3d7fe0a --- /dev/null +++ b/games/invaders/src/formation_renderer.cc @@ -0,0 +1,118 @@ +#include "formation_renderer.hh" + +#include +#include +#include +#include +#include +#include + +std::uint32_t packRgba8(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 FormationRenderer::create(const SpriteSheet &sheet, int capacity) { + if (sheet.count() > kMaxFrames) { + fprintf(stderr, "FormationRenderer: コマが多すぎる / too many frames (%d > %d)\n", sheet.count(), kMaxFrames); + return std::nullopt; + } + FormationRenderer r; + r.shader = Shader::load("games/invaders/shaders/formation.vert", "engine/shaders/sprite.frag"); + if (!r.shader) return std::nullopt; + r.texture = &sheet.texture(); + r.capacity = capacity; + + // コマの表:配列のユニフォームは要素0の場所に、まとめて何個でも送れる(glProgramUniform4fvのcount) + // The frame table: a uniform array is set in one call at the location of element 0 (the count of + // glProgramUniform4fv) + std::vector uvs; + std::vector sizes; + for (int i = 0; i < sheet.count(); ++i) { + Rect uv = sheet.uv(i); + uvs.push_back({uv.x, uv.y, uv.w, uv.h}); + sizes.push_back(sheet.size(i)); + } + GLuint program = r.shader->id(); + glProgramUniform4fv(program, glGetUniformLocation(program, "uFrameUv"), sheet.count(), &uvs[0].x); + glProgramUniform2fv(program, glGetUniformLocation(program, "uFrameSize"), sheet.count(), &sizes[0].x); + + // 頂点(バインディング0):四角形の四隅。GL_TRIANGLE_STRIPなので4つで三角形2枚 + // The vertices (binding 0): the quad's corners. With GL_TRIANGLE_STRIP four of them make two triangles + const Vec2 corners[4] = {{0, 0}, {1, 0}, {0, 1}, {1, 1}}; + r.corners = Buffer(corners, sizeof corners); + // インスタンス(バインディング1):毎フレーム書き換える / the instances (binding 1): rewritten every frame + r.instances = Buffer(nullptr, static_cast(capacity) * static_cast(sizeof(AlienInstance)), + GL_DYNAMIC_STORAGE_BIT); + + glCreateVertexArrays(1, &r.vao); + glVertexArrayVertexBuffer(r.vao, 0, r.corners.id(), 0, sizeof(Vec2)); + glEnableVertexArrayAttrib(r.vao, 0); + glVertexArrayAttribFormat(r.vao, 0, 2, GL_FLOAT, GL_FALSE, 0); + glVertexArrayAttribBinding(r.vao, 0, 0); + + glVertexArrayVertexBuffer(r.vao, 1, r.instances.id(), 0, sizeof(AlienInstance)); + // divisor 1:バインディング1は頂点ごとではなく、インスタンスごとに一つ進む(第19章と同じ) + // divisor 1: binding 1 advances once per instance instead of once per vertex (as in chapter 19) + glVertexArrayBindingDivisor(r.vao, 1, 1); + glEnableVertexArrayAttrib(r.vao, 9); + glVertexArrayAttribFormat(r.vao, 9, 2, GL_FLOAT, GL_FALSE, offsetof(AlienInstance, position)); + glVertexArrayAttribBinding(r.vao, 9, 1); + // 整数の属性はglVertexArrayAttribIFormat(Iが付く)。Formatのほうだとfloatに変換されてしまい、`in uint`では読めない + // Integer attributes need glVertexArrayAttribIFormat (with the I). The plain Format converts to float, which an + // `in uint` cannot read + glEnableVertexArrayAttrib(r.vao, 10); + glVertexArrayAttribIFormat(r.vao, 10, 1, GL_UNSIGNED_INT, offsetof(AlienInstance, frame)); + glVertexArrayAttribBinding(r.vao, 10, 1); + glEnableVertexArrayAttrib(r.vao, 8); + glVertexArrayAttribFormat(r.vao, 8, 4, GL_UNSIGNED_BYTE, GL_TRUE, offsetof(AlienInstance, color)); + glVertexArrayAttribBinding(r.vao, 8, 1); + return r; +} + +void FormationRenderer::release() { + if (vao) glDeleteVertexArrays(1, &vao); + vao = 0; +} + +FormationRenderer::~FormationRenderer() { release(); } + +FormationRenderer::FormationRenderer(FormationRenderer &&other) noexcept { *this = std::move(other); } + +FormationRenderer &FormationRenderer::operator=(FormationRenderer &&other) noexcept { + if (this != &other) { + release(); + shader = std::move(other.shader); + corners = std::move(other.corners); + instances = std::move(other.instances); + vao = std::exchange(other.vao, 0); + texture = other.texture; + capacity = other.capacity; + bytes = other.bytes; + drawCalls = other.drawCalls; + } + return *this; +} + +void FormationRenderer::draw(const Mat4 &viewProjection, std::span list) { + const GLsizei count = static_cast(std::min(list.size(), static_cast(capacity))); + bytes = count * static_cast(sizeof(AlienInstance)); + drawCalls = count > 0 ? 1 : 0; + if (count == 0) return; + instances.update(list.data(), bytes); + + // SpriteBatchと同じ2Dの状態:深度なし、カリングなし、乗算済みアルファ / the same 2D state as SpriteBatch: no depth, + // no culling, premultiplied alpha + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + shader->set("uViewProjection", viewProjection); + shader->use(); + texture->bind(0); + glBindVertexArray(vao); + // 4頂点 × count個のインスタンス。gl_InstanceIDが0〜count-1、属性9・10・8はその番号の要素 + // 4 vertices × count instances. gl_InstanceID runs 0..count-1 and attributes 9, 10, 8 read that element + glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, count); + glBindVertexArray(0); +} diff --git a/games/invaders/src/formation_renderer.hh b/games/invaders/src/formation_renderer.hh new file mode 100644 index 0000000..8444022 --- /dev/null +++ b/games/invaders/src/formation_renderer.hh @@ -0,0 +1,65 @@ +// 隊列をインスタンシングで描く(第27章):四隅4つの頂点を全員で共有し、宇宙人ごとのデータ(位置・コマ・色)を +// インスタンスのバッファから読む。一回のglDrawArraysInstancedで全員 +// Drawing the formation with instancing (chapter 27): every alien shares the same 4 corner vertices and reads its own +// data (position, frame, color) from an instance buffer. One glDrawArraysInstanced for all of them +// +// SpriteBatchとの違い:バッチは一枚ごとに4頂点(80バイト)をCPUで計算して送る。ここでは一匹16バイトだけ送り、 +// 四隅はGPUが作る。代わりにできることは少ない(回転なし、一枚のテクスチャ、layerでバッチと混ぜられない) +// Compared with SpriteBatch: the batch computes 4 vertices (80 bytes) per sprite on the CPU and uploads them. Here +// only 16 bytes per alien are sent and the GPU builds the corners. In exchange it can do less (no rotation, one +// texture, cannot be interleaved with batch sprites by layer) +#pragma once + +#include "engine/buffer.hh" +#include "engine/mathx.hh" +#include "engine/shader.hh" +#include "engine/sprite_sheet.hh" + +#include +#include +#include + +// 一匹分のインスタンスデータ(16バイト)。attribute location 9・10・8に繋ぐ +// One alien's instance data (16 bytes), connected to attribute locations 9, 10 and 8 +struct AlienInstance { + Vec2 position; // 左上(ワールド座標) / top left (world space) → location 9, vec2 + std::uint32_t frame; // スプライトシートのコマ番号 / sprite sheet frame → location 10, uint (整数のまま / stays an integer) + std::uint32_t color; // RGBA8(Rが下位バイト) / RGBA8 (R lowest byte) → location 8, vec4 (0..1に正規化 / normalized) +}; +static_assert(sizeof(AlienInstance) == 16); + +// 色(0〜1、sRGBの値)→ RGBA8。SpriteBatchと同じ丸め方(同じ絵になるように) / a 0..1 color → RGBA8, rounded like +// SpriteBatch does (so both paths give the same image) +std::uint32_t packRgba8(Vec4 color); + +class FormationRenderer { +public: + // games/invaders/shaders/formation.vert + engine/shaders/sprite.frag(フラグメント側はバッチと同じ)。 + // シートの全コマのUVと大きさをユニフォームの配列に入れる(最大kMaxFrames) + // games/invaders/shaders/formation.vert + engine/shaders/sprite.frag (the fragment stage is the batch's). The UV + // rectangle and size of every sheet frame go into uniform arrays (at most kMaxFrames) + static std::optional create(const SpriteSheet &sheet, int capacity = 64); + ~FormationRenderer(); + FormationRenderer(const FormationRenderer &) = delete; + FormationRenderer &operator=(const FormationRenderer &) = delete; + FormationRenderer(FormationRenderer &&other) noexcept; + FormationRenderer &operator=(FormationRenderer &&other) noexcept; + + // インスタンスを送って(glNamedBufferSubData)一回で描く。状態はSpriteBatch::end()の後と同じにする + // Uploads the instances (glNamedBufferSubData) and draws them in one call. Leaves the same state as SpriteBatch::end() + void draw(const Mat4 &viewProjection, std::span instances); + int lastBytes() const { return bytes; } // 直前のdrawで送ったバイト数 / bytes uploaded by the last draw + int lastDrawCalls() const { return drawCalls; } + + static constexpr int kMaxFrames = 32; // formation.vertの配列の大きさ / the array size in formation.vert + +private: + FormationRenderer() = default; + void release(); + std::optional shader; + Buffer corners; // バインディング0:四隅 (0,0) (1,0) (0,1) (1,1)、頂点ごと / binding 0: the corners, per vertex + Buffer instances; // バインディング1:AlienInstance、インスタンスごと(divisor 1) / binding 1: per instance + GLuint vao = 0; + const Texture2D *texture = nullptr; + int capacity = 0, bytes = 0, drawCalls = 0; +}; diff --git a/games/invaders/src/game.hh b/games/invaders/src/game.hh new file mode 100644 index 0000000..655b4f8 --- /dev/null +++ b/games/invaders/src/game.hh @@ -0,0 +1,73 @@ +// Invaders:どのシーンからも使う共有データ、画面の寸法、シーン +// Invaders: the data every scene shares, the screen layout, the scenes +#pragma once + +#include "formation.hh" +#include "formation_renderer.hh" + +#include "engine/camera2d.hh" +#include "engine/font.hh" +#include "engine/game_loop.hh" +#include "engine/input.hh" +#include "engine/rng.hh" +#include "engine/scene.hh" +#include "engine/sprite_batch.hh" +#include "engine/sprite_sheet.hh" + +#include + +// 仮想解像度320 × 180(ウィンドウ1280 × 720で4倍)。真ん中の224ピクセル幅が戦場、左右48ピクセルは脇の板 +// Virtual resolution 320 × 180 (× 4 in the 1280 × 720 window). The middle 224 pixels are the arena, 48 pixels on +// each side are side panels +constexpr Vec2 kView = {320.0f, 180.0f}; +constexpr float kArenaLeft = 48.0f, kArenaRight = 272.0f; +constexpr float kFormationTop = 28.0f; // 最初の隊列の一番上 / the first formation's top row +constexpr float kPlayerY = 158.0f; // 自機の上端 / the ship's top +constexpr float kGroundY = 170.0f; // 地面の線 / the ground line +constexpr float kPlayerSpeed = 60.0f; // ピクセル毎秒(1ステップ1ピクセル) / pixels per second (1 px per step) + +// ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference +struct Game { + Window &window; + Input &input; + GameLoop &loop; + SpriteBatch &batch; + FormationRenderer &formationRenderer; + const Font &ui; // mono16:画面の解像度の文字 / text at screen resolution + const SpriteSheet &sprites; // games/invaders/assets/sprites.atlas + Camera2D world; // 320 × 180のキャンバス / the 320 × 180 canvas + Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI + Viewport uiViewport; + Rng rng{27}; + bool instanced = true; // 隊列をインスタンシングで(I) / draw the formation instanced (I) +}; + +// 遊ぶ場面:自機と行進する隊列 / the play scene: the ship and the marching formation +class PlayScene : public Scene { +public: + explicit PlayScene(Game &game); + void pause() override; + void update(float dt) override; + void draw(float alpha) override; + void drawUi(float alpha) override; + +private: + struct Star { + Vec2 position; + float phase; + }; + int alienFrame(const Alien &a) const; + void drawBackground(); + void drawFormation(); + + Game &g; + Formation formation; + float playerX = 0.0f, playerPrevX = 0.0f; // 自機の左端(補間用に前のステップも) / the ship's left edge (+ the + // previous step's, for interpolation) + std::vector stars; + float time = 0.0f; + int frames[3][2] = {}; // 種類 × 足踏み → シートのコマ / kind × pose → sheet frame + int shipFrame = 0; + int formationDrawCalls = 0, formationBytes = 0; + int landings = 0; +}; diff --git a/games/invaders/src/main.cc b/games/invaders/src/main.cc new file mode 100644 index 0000000..b403cf7 --- /dev/null +++ b/games/invaders/src/main.cc @@ -0,0 +1,62 @@ +// Invaders 第1部(第27章):自機、インスタンシングで描く宇宙人の隊列、行進、操作 +// Invaders part 1 (chapter 27): the player's ship, the alien formation drawn with instancing, the march, the controls +// +// 操作 / Controls: +// ← → / A D 移動 / move +// I 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch +// = / - 行進を速く・遅く / march faster / slower +// Esc 終了 / quit +#include "game.hh" + +#include "engine/pixel_canvas.hh" +#include "engine/window.hh" + +#include +#include + +int main() { + Window window; + if (!window.create(1280, 720, "OpenGL Tutorial - Invaders")) return 1; + + std::optional batch = SpriteBatch::create(); + std::optional ui = Font::load("assets/fonts/mono16.fnt"); + std::optional sprites = SpriteSheet::loadAtlas("games/invaders/assets/sprites.atlas"); + if (!batch || !ui || !sprites) return 1; + std::optional formationRenderer = FormationRenderer::create(*sprites); + if (!formationRenderer) return 1; + + // 行動に名前を付ける(キーを変えるならここだけ) / name the actions (to change keys, edit only this) + Input input; + input.attach(window); + input.bind("left", {InputBinding::key(GLFW_KEY_LEFT), InputBinding::key(GLFW_KEY_A)}); + input.bind("right", {InputBinding::key(GLFW_KEY_RIGHT), InputBinding::key(GLFW_KEY_D)}); + + // 固定ステップ:ゲームの動きは1/60秒ごとの更新の中だけ / fixed step: the game only changes in the 1/60 s updates + GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); + PixelCanvas canvas(static_cast(kView.x), static_cast(kView.y)); + Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .formationRenderer = *formationRenderer, + .ui = *ui, .sprites = *sprites, .world = Camera2D::screen(kView), + .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}}; + + SceneManager scenes; + scenes.push(std::make_unique(game)); + + loop.run( + window, input, + [&](float dt) { + scenes.update(dt); + if (scenes.empty()) window.close(); + }, + [&](float alpha) { + // 1. 世界:320 × 180のキャンバスに描いて4倍で画面へ / 1. the world: into the 320 × 180 canvas, shown × 4 + canvas.begin(hexColor(0x0c0a1aff)); + scenes.draw(alpha); + canvas.present(window.width(), window.height()); + // 2. UI:1280 × 720の文字 / 2. the UI: text at 1280 × 720 + game.uiViewport = letterbox(window.width(), window.height(), game.screen.viewSize, false); + game.uiViewport.apply(); + scenes.drawUi(alpha); + scenes.drawFade(*batch, game.screen.matrix(), game.screen.viewSize); + }); + return 0; +} diff --git a/games/invaders/src/play_scene.cc b/games/invaders/src/play_scene.cc new file mode 100644 index 0000000..ebe3ef0 --- /dev/null +++ b/games/invaders/src/play_scene.cc @@ -0,0 +1,167 @@ +// 遊ぶ場面(第27章):自機の操作、隊列の行進、隊列の描き方の比較(インスタンシング ⇔ SpriteBatch) +// The play scene (chapter 27): steering the ship, the formation's march, two ways to draw the formation (instancing +// ⇔ SpriteBatch) +#include "game.hh" + +#include +#include +#include + +PlayScene::PlayScene(Game &game) : g(game) { + const char *names[3][2] = {{"jelly_0", "jelly_1"}, {"beetle_0", "beetle_1"}, {"blob_0", "blob_1"}}; + for (int k = 0; k < 3; ++k) + for (int p = 0; p < 2; ++p) frames[k][p] = g.sprites.find(names[k][p]); + shipFrame = g.sprites.find("ship"); + + // 隊列:幅 = 10 × 16 + 14 = 174ピクセル、戦場の真ん中 / the formation: 10 × 16 + 14 = 174 px wide, centered in the arena + formation.minX = kArenaLeft + 2.0f; + formation.maxX = kArenaRight - 2.0f; + formation.reset(std::round(0.5f * (kArenaLeft + kArenaRight - 174.0f)), kFormationTop); + + playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f); + // 星:自分の種で作るので、場面を作り直しても同じ空 / stars: made with their own seed, so the sky stays the same when + // the scene is created again + Rng sky(1978); + for (int i = 0; i < 40; ++i) + stars.push_back({{std::round(sky.range(kArenaLeft + 2.0f, kArenaRight - 2.0f)), std::round(sky.range(4.0f, 150.0f))}, + sky.unit()}); +} + +// 一時停止の間は補間しない(第26章) / no interpolation while paused (chapter 26) +void PlayScene::pause() { playerPrevX = playerX; } + +int PlayScene::alienFrame(const Alien &a) const { return frames[static_cast(a.kind)][a.pose]; } + +void PlayScene::update(float dt) { + time += dt; + Input &in = g.input; + if (in.pressed(GLFW_KEY_ESCAPE)) { + scenes().pop(); // スタックが空になる → main が終わらせる / the stack becomes empty → main quits + return; + } + if (in.pressed(GLFW_KEY_I)) { + g.instanced = !g.instanced; + printf("formation: %s\n", g.instanced ? "instanced" : "SpriteBatch"); + } + // 行進の速さを変える(説明用):1秒に動く宇宙人の数を2倍・半分 / change the march speed (for the demo): double or + // halve the number of aliens moved per second + if (in.pressed(GLFW_KEY_EQUAL)) formation.rate = std::min(formation.rate * 2.0f, 960.0f); + if (in.pressed(GLFW_KEY_MINUS)) formation.rate = std::max(formation.rate * 0.5f, 15.0f); + + // 自機:左右の行動の軸で動き、戦場からは出ない / the ship: moves along the left/right action axis, stays inside the + // arena + playerPrevX = playerX; + playerX += in.axis("left", "right") * kPlayerSpeed * dt; + playerX = std::clamp(playerX, kArenaLeft + 2.0f, kArenaRight - 2.0f - 15.0f); + + formation.update(dt); + // 第27章では撃てないので、地面まで下りてきたら上からやり直す(第28章で「侵略された」になる) + // There is no shooting in chapter 27 yet, so when the formation reaches the ship's row it starts again at the top + // (chapter 28 turns this into "invaded") + if (formation.bounds().bottom() > kPlayerY) { + ++landings; + printf("formation landed after %d passes: reset\n", formation.passes); + formation.reset(std::round(0.5f * (kArenaLeft + kArenaRight - 174.0f)), kFormationTop); + } +} + +void PlayScene::drawBackground() { + SpriteBatch &b = g.batch; + // 脇の板と枠 / the side panels and their borders + b.drawRect({0.0f, 0.0f, kArenaLeft, kView.y}, hexColor(0x16132aff)); + b.drawRect({kArenaRight, 0.0f, kView.x - kArenaRight, kView.y}, hexColor(0x16132aff)); + b.drawRect({kArenaLeft - 1.0f, 0.0f, 1.0f, kView.y}, hexColor(0x3a3460ff)); + b.drawRect({kArenaRight, 0.0f, 1.0f, kView.y}, hexColor(0x3a3460ff)); + // 瞬く星 / twinkling stars + for (const Star &s : stars) { + float t = 0.5f + 0.5f * std::sin(2.0f * time + 6.283f * s.phase); + b.drawRect({s.position.x, s.position.y, 1.0f, 1.0f}, {0.62f, 0.64f, 0.8f, 0.25f + 0.5f * t}); + } + // 地面 / the ground + b.drawRect({kArenaLeft, kGroundY, kArenaRight - kArenaLeft, 1.0f}, hexColor(0x68c454ff)); +} + +void PlayScene::drawFormation() { + if (g.instanced) { + // インスタンシング:生きている宇宙人を16バイトずつ並べて、一回で描く / instancing: 16 bytes per living alien, one + // draw call + std::vector list; + for (const Alien &a : formation.aliens) + if (a.alive) + list.push_back({a.position, static_cast(alienFrame(a)), packRgba8(kWhite)}); + g.formationRenderer.draw(g.world.matrix(), list); + formationDrawCalls = g.formationRenderer.lastDrawCalls(); + formationBytes = g.formationRenderer.lastBytes(); + } else { + // 比べるため:同じ宇宙人をSpriteBatchで(一枚4頂点 × 20バイト) / for comparison: the same aliens through + // SpriteBatch (4 vertices × 20 bytes per sprite) + g.batch.begin(g.world.matrix()); + for (const Alien &a : formation.aliens) + if (a.alive) g.batch.draw(g.sprites.sprite(alienFrame(a), a.position)); + g.batch.end(); + formationDrawCalls = g.batch.stats().drawCalls; + formationBytes = g.batch.stats().sprites * 4 * static_cast(sizeof(SpriteVertex)); + } +} + +void PlayScene::draw(float alpha) { + // 奥から:背景(バッチ)→ 隊列(インスタンシングかバッチ)→ 自機(バッチ) / back to front: background (batch) → + // formation (instanced or batch) → ship (batch) + g.batch.begin(g.world.matrix()); + drawBackground(); + g.batch.end(); + + drawFormation(); + + // 宇宙人は飛び飛びに動くので補間しない。自機は滑らかに動くので補間する(第26章) + // Aliens move in jumps, so they are not interpolated. The ship moves smoothly, so it is (chapter 26) + float x = std::round(playerPrevX + (playerX - playerPrevX) * alpha); + g.batch.begin(g.world.matrix()); + g.batch.draw(g.sprites.sprite(shipFrame, {x, kPlayerY})); + g.batch.end(); +} + +void PlayScene::drawUi(float /*alpha*/) { + SpriteBatch &b = g.batch; + b.begin(g.screen.matrix()); + TextStyle head = {.color = hexColor(0xf2c14eff), .shadow = hexColor(0x000000ff)}; + TextStyle body = {.color = hexColor(0xd8dcefff), .shadow = hexColor(0x000000ff)}; + char line[64]; + // 左の板:隊列の描き方と、その値段 / the left panel: how the formation is drawn and what it costs + float y = 24.0f; + auto text = [&](const char *s, const TextStyle &st) { + g.ui.draw(b, s, {14.0f, y}, st); + y += 22.0f; + }; + text("FORMATION (I)", head); + text(g.instanced ? "instanced" : "SpriteBatch", body); + snprintf(line, sizeof line, "draw calls %d", formationDrawCalls); + text(line, body); + snprintf(line, sizeof line, "%d B/frame", formationBytes); + text(line, body); + text(g.instanced ? "(16 B/alien)" : "(80 B/alien)", body); + y += 16.0f; + text("MARCH (= -)", head); + snprintf(line, sizeof line, "%.0f aliens/s", static_cast(formation.rate)); + text(line, body); + snprintf(line, sizeof line, "alive %d", formation.alive()); + text(line, body); + snprintf(line, sizeof line, "passes %d", formation.passes); + text(line, body); + snprintf(line, sizeof line, "landed %d", landings); + text(line, body); + + // 右の板:操作 / the right panel: controls + y = 24.0f; + auto right = [&](const char *s, const TextStyle &st) { + g.ui.draw(b, s, {1102.0f, y}, st); + y += 22.0f; + }; + right("CONTROLS", head); + right("A D / arrows", body); + right(" move", body); + right("I formation", body); + right("= - march", body); + right("Esc quit", body); + b.end(); +}