diff --git a/games/invaders/CMakeLists.txt b/games/invaders/CMakeLists.txt index eacf467..d5d31d3 100644 --- a/games/invaders/CMakeLists.txt +++ b/games/invaders/CMakeLists.txt @@ -5,7 +5,9 @@ add_executable(invaders src/main.cc src/play_scene.cc src/formation.cc - src/formation_renderer.cc) + src/formation_renderer.cc + src/shields.cc + src/effects.cc) target_include_directories(invaders PRIVATE src) target_link_libraries(invaders PRIVATE engine) enable_warnings(invaders) diff --git a/games/invaders/README.md b/games/invaders/README.md index 40554ad..db437a3 100644 --- a/games/invaders/README.md +++ b/games/invaders/README.md @@ -13,8 +13,11 @@ is already the project root)。 | キー / Key | | |---|---| | ← → / A D | 移動 / move | +| Space / ↑ / W | 撃つ / fire | | I | 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch | +| B | 当たり判定の箱 / collision boxes | | = / - | 行進を速く・遅く / march faster / slower | +| Space / Enter | ゲームオーバーの後:もう一度 / after game over: play again | | Esc | 終了 / quit | ## ファイル / Files @@ -23,4 +26,6 @@ is already the project root)。 * `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 +* `src/shields.hh/.cc` 削れる防壁(CPUのピクセル+glTextureSubImage2D) / eroding shields (CPU pixels + glTextureSubImage2D) +* `src/effects.hh/.cc` 破片と着弾 / debris particles and impact flares * `assets/` 絵(作者の自作スクリプトで生成。スクリプトはダウンロードに含まれない) / art (generated by the author's own script, not part of the download) diff --git a/games/invaders/src/effects.cc b/games/invaders/src/effects.cc new file mode 100644 index 0000000..8da169d --- /dev/null +++ b/games/invaders/src/effects.cc @@ -0,0 +1,29 @@ +#include "effects.hh" + +#include +#include + +void Particles::burst(Vec2 centre, int count, Vec4 color, float speedLo, float speedHi, Rng &rng) { + for (int i = 0; i < count; ++i) { + float life = rng.range(0.3f, 0.7f); + items.push_back({centre, rng.direction() * rng.range(speedLo, speedHi), life, life, color}); + } +} + +void Particles::update(float dt) { + for (Particle &p : items) { + p.position += p.velocity * dt; + p.velocity.y += 60.0f * dt; // 少し落ちる / falls a little + p.velocity = p.velocity * (1.0f - 1.5f * dt); // 空気抵抗のような減速 / slows down, like drag + p.life -= dt; + } + std::erase_if(items, [](const Particle &p) { return p.life <= 0.0f; }); +} + +void Particles::draw(SpriteBatch &batch, float layer) const { + for (const Particle &p : items) { + Vec4 c = p.color; + c.w *= std::min(1.0f, 2.0f * p.life / p.lifetime); // 後半で消えていく / fades during the second half + batch.drawRect({std::round(p.position.x), std::round(p.position.y), 1.0f, 1.0f}, c, layer); + } +} diff --git a/games/invaders/src/effects.hh b/games/invaders/src/effects.hh new file mode 100644 index 0000000..3565366 --- /dev/null +++ b/games/invaders/src/effects.hh @@ -0,0 +1,36 @@ +// 爆発の飾り(第28章):飛び散るピクセル(パーティクル)と、短く見せるスプライト(着弾など) +// Explosion dressing (chapter 28): flying pixels (particles) and sprites shown for a moment (impacts and such) +#pragma once + +#include "engine/rng.hh" +#include "engine/sprite_batch.hh" + +#include + +// 1ピクセルの破片。固定ステップで動き、だんだん消える / one-pixel debris: moves in the fixed step and fades out +class Particles { +public: + // centreから全方向へcount個。速さはspeedLo〜speedHi(ピクセル毎秒)、寿命は0.3〜0.7秒 + // count pieces from centre in all directions, speed speedLo..speedHi px/s, lifetime 0.3..0.7 s + void burst(Vec2 centre, int count, Vec4 color, float speedLo, float speedHi, Rng &rng); + void update(float dt); + void draw(SpriteBatch &batch, float layer = 0.0f) const; + void clear() { items.clear(); } + size_t size() const { return items.size(); } + +private: + struct Particle { + Vec2 position, velocity; + float life, lifetime; + Vec4 color; + }; + std::vector items; +}; + +// 一コマのスプライトを少しの間だけ見せる(着弾の「パッ」) / shows one sprite frame for a moment (the impact "pop") +struct Flare { + int frame; // スプライトシートのコマ / sprite sheet frame + Vec2 centre; + float life; // 残り秒 / seconds left + Vec4 color; +}; diff --git a/games/invaders/src/formation.cc b/games/invaders/src/formation.cc index 5cee312..760a31c 100644 --- a/games/invaders/src/formation.cc +++ b/games/invaders/src/formation.cc @@ -21,6 +21,26 @@ void Formation::reset(float left, float top) { budget = 0.0f; } +void Formation::kill(Alien &alien) { + alien.alive = false; + alien.dying = kAlienBoomTime; +} + +void Formation::updateExplosions(float dt) { + for (Alien &a : aliens) a.dying = std::max(0.0f, a.dying - dt); +} + +bool Formation::cleared() const { + return std::none_of(aliens.begin(), aliens.end(), [](const Alien &a) { return a.alive || a.dying > 0.0f; }); +} + +const Alien *Formation::lowestInColumn(int column) const { + const Alien *lowest = nullptr; + for (const Alien &a : aliens) + if (a.alive && a.column == column && (!lowest || a.position.y > lowest->position.y)) lowest = &a; + return lowest; +} + int Formation::alive() const { return static_cast(std::count_if(aliens.begin(), aliens.end(), [](const Alien &a) { return a.alive; })); } @@ -42,6 +62,7 @@ Rect Formation::bounds() const { } void Formation::update(float dt) { + updateExplosions(dt); if (alive() == 0) return; // 1ステップ(1/60秒)にrate/60匹。予算は浮動小数点数の和なので少し許す(60 × (1/60)は丁度1.0fだが、 // 1/50秒のステップでは5回目の更新の予算が2ではなく1.99999964になる) diff --git a/games/invaders/src/formation.hh b/games/invaders/src/formation.hh index d8e2366..b0764a0 100644 --- a/games/invaders/src/formation.hh +++ b/games/invaders/src/formation.hh @@ -16,12 +16,16 @@ struct Alien { Vec2 position; // 左上、整数のピクセル / top left, whole pixels int pose = 0; // 0か1:動くたびに入れ替わる(足踏み) / 0 or 1: flips every time it moves (the walk) bool alive = true; + float dying = 0.0f; // 爆発の残り時間(第28章):死んだ後もしばらく爆発のコマで残る / explosion time left + // (chapter 28): a dead alien stays on screen as an explosion for a moment 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; +constexpr float kAlienBoomTime = 0.25f; // 爆発のコマを見せる時間(alien_boomのクリップ:2コマ、8 fps) / how long the + // explosion shows (the alien_boom clip: 2 frames at 8 fps) class Formation { public: @@ -35,8 +39,17 @@ public: // the sooner each one's turn comes around = the formation speeds up by itself void update(float dt); + // 撃たれた:行進から外れ、爆発のコマになる / shot: leaves the march and turns into an explosion + void kill(Alien &alien); + // 爆発の時計だけ進める(自機の爆発中は行進が止まるが、宇宙人の爆発は進む) / advances only the explosion timers (the + // march stops while the ship explodes, alien explosions go on) + void updateExplosions(float dt); + int alive() const; + bool cleared() const; // 全滅して、爆発も終わった / everyone is dead and the explosions are over Rect bounds() const; // 生きている宇宙人を囲む箱(全滅なら大きさ0) / box around the living aliens (empty if none) + // その列で一番下の生きている宇宙人(撃つのはこの宇宙人) / the lowest living alien of a column (it does the shooting) + const Alien *lowestInColumn(int column) const; std::vector aliens; // 行進の順番:下の行の左から右へ、それから上の行 / march order: bottom row left to right, // then the row above diff --git a/games/invaders/src/game.hh b/games/invaders/src/game.hh index 655b4f8..9f1652f 100644 --- a/games/invaders/src/game.hh +++ b/games/invaders/src/game.hh @@ -2,9 +2,12 @@ // Invaders: the data every scene shares, the screen layout, the scenes #pragma once +#include "effects.hh" #include "formation.hh" #include "formation_renderer.hh" +#include "shields.hh" +#include "engine/animation.hh" #include "engine/camera2d.hh" #include "engine/font.hh" #include "engine/game_loop.hh" @@ -14,6 +17,7 @@ #include "engine/sprite_batch.hh" #include "engine/sprite_sheet.hh" +#include #include // 仮想解像度320 × 180(ウィンドウ1280 × 720で4倍)。真ん中の224ピクセル幅が戦場、左右48ピクセルは脇の板 @@ -22,9 +26,14 @@ 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 kShieldY = 136.0f; // 防壁の上端 / the shields' top 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) +constexpr float kShotSpeed = 240.0f; // 自機の弾:1ステップ4ピクセル / the ship's bullet: 4 px per step +constexpr float kAlienShotSpeed = 75.0f; // 宇宙人の弾 / alien bullets +constexpr int kMaxAlienShots = 3; +constexpr int kStartLives = 3; // ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference struct Game { @@ -35,14 +44,17 @@ struct Game { FormationRenderer &formationRenderer; const Font &ui; // mono16:画面の解像度の文字 / text at screen resolution const SpriteSheet &sprites; // games/invaders/assets/sprites.atlas + const Image &shieldArt; // 防壁の絵(CPU側、削る元) / the shield art (CPU side, what gets eroded) 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) + bool showBoxes = false; // 当たり判定の箱(B) / collision boxes (B) }; -// 遊ぶ場面:自機と行進する隊列 / the play scene: the ship and the marching formation +// 遊ぶ場面:自機、行進する隊列、弾、防壁、爆発 / the play scene: the ship, the marching formation, bullets, +// shields, explosions class PlayScene : public Scene { public: explicit PlayScene(Game &game); @@ -56,18 +68,44 @@ private: Vec2 position; float phase; }; + // 弾:当たり判定の箱と、補間用の前のステップのy / a bullet: its collision box and last step's y (interpolation) + struct Bullet { + Rect box; + float prevY; + Animator anim; // 宇宙人の弾は4コマのクリップ / alien bullets play a 4-frame clip + }; int alienFrame(const Alien &a) const; + Rect shipBox() const; + void fire(); + void alienFire(float dt); + void updateShot(float dt); + void updateAlienShots(float dt); + void killShip(); + void flare(Vec2 centre, Vec4 color, float life = 0.12f); void drawBackground(); void drawFormation(); + void drawBoxes(); Game &g; Formation formation; + std::optional shields; float playerX = 0.0f, playerPrevX = 0.0f; // 自機の左端(補間用に前のステップも) / the ship's left edge (+ the // previous step's, for interpolation) + std::optional shot; // 自機の弾は一度に一発(元のゲームと同じ) / one ship bullet at a time + // (as in the original) + std::vector alienShots; + float fireTimer = 1.0f; // 宇宙人が次に撃つまで / until the aliens fire next + float shipDying = 0.0f; // 自機の爆発の残り時間(> 0 の間は隊列も止まる) / ship explosion time + // left (the march stops meanwhile) + Animator shipBoom; + Particles particles; + std::vector flares; 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; + int shipFrame = 0, shotFrame = 0, splatFrame = 0, boomFrames[2] = {}; + const AnimationClip *zigClip = nullptr, *boltClip = nullptr, *shipBoomClip = nullptr; + int formationDrawCalls = 0, formationBytes = 0, shieldBytes = 0; + int lives = kStartLives, kills = 0, shotsFired = 0, waves = 1; + bool gameOver = false; }; diff --git a/games/invaders/src/main.cc b/games/invaders/src/main.cc index b403cf7..263386e 100644 --- a/games/invaders/src/main.cc +++ b/games/invaders/src/main.cc @@ -1,9 +1,11 @@ -// Invaders 第1部(第27章):自機、インスタンシングで描く宇宙人の隊列、行進、操作 -// Invaders part 1 (chapter 27): the player's ship, the alien formation drawn with instancing, the march, the controls +// Invaders 第2部(第28章):弾、AABBの当たり判定、宇宙人の弾、削れる防壁、爆発 +// Invaders part 2 (chapter 28): bullets, AABB collisions, alien bullets, shields that erode, explosions // // 操作 / Controls: // ← → / A D 移動 / move +// Space / ↑ 撃つ / fire // I 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch +// B 当たり判定の箱 / collision boxes // = / - 行進を速く・遅く / march faster / slower // Esc 終了 / quit #include "game.hh" @@ -23,19 +25,24 @@ int main() { 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; + // 防壁の絵はCPUにも要る(削るため):同じPNGをもう一度デコードして切り出す / the shield art is needed on the CPU + // too (to erode it): decode the same PNG again and cut it out + std::optional shieldArt = loadSpriteImage("games/invaders/assets/sprites.png", *sprites, "shield"); + if (!formationRenderer || !shieldArt) 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)}); + input.bind("fire", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_UP), InputBinding::key(GLFW_KEY_W)}); + input.bind("confirm", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_ENTER)}); // 固定ステップ:ゲームの動きは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), + .ui = *ui, .sprites = *sprites, .shieldArt = *shieldArt, .world = Camera2D::screen(kView), .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}}; SceneManager scenes; diff --git a/games/invaders/src/play_scene.cc b/games/invaders/src/play_scene.cc index ebe3ef0..2496b19 100644 --- a/games/invaders/src/play_scene.cc +++ b/games/invaders/src/play_scene.cc @@ -1,22 +1,49 @@ -// 遊ぶ場面(第27章):自機の操作、隊列の行進、隊列の描き方の比較(インスタンシング ⇔ SpriteBatch) -// The play scene (chapter 27): steering the ship, the formation's march, two ways to draw the formation (instancing -// ⇔ SpriteBatch) +// 遊ぶ場面(第28章):自機の弾と宇宙人の弾、AABBの当たり判定、削れる防壁、爆発 +// The play scene (chapter 28): the ship's and the aliens' bullets, AABB collisions, eroding shields, explosions #include "game.hh" +#include "engine/collision.hh" + #include #include #include +#include + +// 宇宙人の色(破片の色) / alien colors (for the debris) +static const Vec4 kAlienColors[3] = {hexColor(0xf06292ff), hexColor(0x5dbce6ff), hexColor(0x9adc48ff)}; +constexpr float kFormationWidth = (kColumns - 1) * kColumnSpacing + kAlienSize.x; // 174 +constexpr float kShipBoomTime = 1.4f; + +static float formationStartX() { return std::round(0.5f * (kArenaLeft + kArenaRight - kFormationWidth)); } 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"); + shotFrame = g.sprites.find("shot"); + splatFrame = g.sprites.find("splat"); + boomFrames[0] = g.sprites.find("alien_boom_0"); + boomFrames[1] = g.sprites.find("alien_boom_1"); + zigClip = g.sprites.clip("zig"); + boltClip = g.sprites.clip("bolt"); + shipBoomClip = g.sprites.clip("ship_boom"); - // 隊列:幅 = 10 × 16 + 14 = 174ピクセル、戦場の真ん中 / the formation: 10 × 16 + 14 = 174 px wide, centered in the arena + // 隊列:幅174ピクセル、戦場の真ん中 / the formation: 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); + formation.reset(formationStartX(), kFormationTop); + + // 防壁4つを戦場に等間隔で(中心 76, 132, 188, 244) / four shields evenly across the arena (centers 76, 132, 188, 244) + Vec2 shieldPos[kShieldCount]; + for (int i = 0; i < kShieldCount; ++i) + shieldPos[i] = {kArenaLeft + (kArenaRight - kArenaLeft) * (static_cast(i) + 0.5f) / kShieldCount - kShieldW / 2, + kShieldY}; + shields = Shields::create(g.shieldArt, shieldPos); + if (!shields) { // 防壁が無いと遊べない(理由はcreateが書いた) / no game without shields (create logged why) + fprintf(stderr, "防壁を作れないので終了 / cannot create the shields: quitting\n"); + g.window.close(); // 防壁を使う関数は何もしない / the functions that use the shields do nothing + } playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f); // 星:自分の種で作るので、場面を作り直しても同じ空 / stars: made with their own seed, so the sky stays the same when @@ -28,11 +55,130 @@ PlayScene::PlayScene(Game &game) : g(game) { } // 一時停止の間は補間しない(第26章) / no interpolation while paused (chapter 26) -void PlayScene::pause() { playerPrevX = playerX; } +void PlayScene::pause() { + playerPrevX = playerX; + if (shot) shot->prevY = shot->box.y; + for (Bullet &b : alienShots) b.prevY = b.box.y; +} -int PlayScene::alienFrame(const Alien &a) const { return frames[static_cast(a.kind)][a.pose]; } +int PlayScene::alienFrame(const Alien &a) const { + if (!a.alive) return boomFrames[a.dying > 0.5f * kAlienBoomTime ? 0 : 1]; + return frames[static_cast(a.kind)][a.pose]; +} + +// 自機の当たり判定:輪郭を除いた船体(13 × 7) / the ship's collision box: the hull without the outline (13 × 7) +Rect PlayScene::shipBox() const { return {playerX + 1.0f, kPlayerY + 1.0f, 13.0f, 7.0f}; } + +void PlayScene::flare(Vec2 centre, Vec4 color, float life) { flares.push_back({splatFrame, centre, life, color}); } + +void PlayScene::fire() { + // 画面に自機の弾がない時だけ撃てる:連打より狙いが大事(元のゲームの決まり) + // Only when no ship bullet is on screen: aiming beats mashing (the original's rule) + if (shot || shipDying > 0.0f || gameOver || !g.input.actionPressed("fire")) return; + float y = kPlayerY - 4.0f; + shot = Bullet{.box = {playerX + 7.0f, y, 1.0f, 5.0f}, .prevY = y, .anim = {}}; + ++shotsFired; +} + +void PlayScene::killShip() { + --lives; + shipDying = kShipBoomTime; + shipBoom.play(shipBoomClip, true); + Vec2 c = shipBox().centre(); + particles.burst(c, 24, hexColor(0x4fc0a5ff), 20.0f, 70.0f, g.rng); + particles.burst(c, 12, hexColor(0xffa040ff), 30.0f, 90.0f, g.rng); + alienShots.clear(); // 元のゲームと同じく、飛んでいる弾は消える / bullets in flight vanish, as in the original + printf("ship hit: lives %d\n", lives); +} + +void PlayScene::updateShot(float dt) { + if (!shot) return; + shot->prevY = shot->box.y; + shot->box.y -= kShotSpeed * dt; + // 1ステップ4ピクセル、弾の長さ5ピクセル:続けて見れば隙間がないので、すり抜けない(第26章のトンネリング)。 + // 宇宙人の弾とも:近づく速さは1ステップ5.25ピクセル < 5 + 7 + // 4 px per step with a 5 px bullet: consecutive boxes leave no gap, so nothing is skipped (ch26's tunneling). + // Against alien bullets too: they close in at 5.25 px per step < 5 + 7 + const Rect &box = shot->box; + for (size_t i = 0; i < alienShots.size(); ++i) + if (overlaps(box, alienShots[i].box)) { + flare(box.centre(), hexColor(0xfff4d6ff)); + alienShots.erase(alienShots.begin() + static_cast(i)); + shot.reset(); + return; + } + for (Alien &a : formation.aliens) + if (a.alive && overlaps(box, a.box())) { + formation.kill(a); + particles.burst(a.box().centre(), 10, kAlienColors[static_cast(a.kind)], 15.0f, 50.0f, g.rng); + ++kills; + shot.reset(); + return; + } + if (std::optional p = shields->hit(box, true)) { + shields->erode(*p, g.rng); + flare(*p, hexColor(0x68c454ff)); + shot.reset(); + return; + } + if (box.top() < 6.0f) { // 戦場の上の端 / the top of the arena + flare({box.x, 6.0f}, hexColor(0xfff4d6ff)); + shot.reset(); + } +} + +void PlayScene::alienFire(float dt) { + fireTimer -= dt; + if (fireTimer > 0.0f) return; + fireTimer = g.rng.range(0.5f, 1.1f); + if (static_cast(alienShots.size()) >= kMaxAlienShots) return; + // 撃つ列:3回に1回は自機の真上の列、それ以外は生きている宇宙人をランダムに選んでその列。撃つのはその列の一番下 + // The firing column: one time in three the column above the ship, otherwise the column of a random living alien. + // The lowest alien of that column shoots + std::vector living; + for (const Alien &a : formation.aliens) + if (a.alive) living.push_back(&a); + if (living.empty()) return; + int column = living[static_cast(g.rng.range(0, static_cast(living.size()) - 1))]->column; + if (g.rng.chance(1.0f / 3.0f)) { + float shipX = shipBox().centre().x, best = 1e9f; + for (const Alien *a : living) + if (float d = std::fabs(a->box().centre().x - shipX); d < best) best = d, column = a->column; + } + const Alien *shooter = formation.lowestInColumn(column); + if (!shooter) return; + Bullet b{.box = {shooter->position.x + 5.0f, shooter->position.y + kAlienSize.y, 3.0f, 7.0f}, + .prevY = shooter->position.y + kAlienSize.y, .anim = {}}; + b.anim.play(g.rng.chance(0.5f) ? zigClip : boltClip); + alienShots.push_back(b); +} + +void PlayScene::updateAlienShots(float dt) { + for (size_t i = 0; i < alienShots.size();) { + Bullet &b = alienShots[i]; + b.prevY = b.box.y; + b.box.y += kAlienShotSpeed * dt; + b.anim.update(dt); + if (shipDying <= 0.0f && overlaps(b.box, shipBox())) { + killShip(); // 全部の弾を消す / clears every bullet + return; + } + bool gone = false; + if (std::optional p = shields->hit(b.box, false)) { + shields->erode(*p, g.rng); + flare(*p, hexColor(0x68c454ff)); + gone = true; + } else if (b.box.bottom() >= kGroundY) { + flare({b.box.centre().x, kGroundY - 2.0f}, hexColor(0xffa040ff)); + gone = true; + } + if (gone) alienShots.erase(alienShots.begin() + static_cast(i)); + else ++i; + } +} void PlayScene::update(float dt) { + if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor) time += dt; Input &in = g.input; if (in.pressed(GLFW_KEY_ESCAPE)) { @@ -43,25 +189,73 @@ void PlayScene::update(float dt) { 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_B)) g.showBoxes = !g.showBoxes; 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 + // 飾りはいつでも動く / the dressing always moves + particles.update(dt); + for (Flare &f : flares) f.life -= dt; + std::erase_if(flares, [](const Flare &f) { return f.life <= 0.0f; }); + + if (gameOver) { + formation.updateExplosions(dt); + // やり直し:この場面を新しい場面と入れ替える(全部が最初の状態に戻る) / play again: replace this scene with a + // new one (everything starts from scratch) + if (in.actionPressed("confirm")) scenes().replace(std::make_unique(g)); + return; + } + playerPrevX = playerX; + if (shipDying > 0.0f) { + // 自機の爆発中:隊列も宇宙人の弾も止まる(元のゲームと同じ)。終わったら真ん中に戻るか、ゲームオーバー + // While the ship explodes the formation and the alien fire stop (as in the original). Afterwards the ship comes + // back in the middle, or the game is over + shipBoom.update(dt); + formation.updateExplosions(dt); + updateShot(dt); + shipDying -= dt; + if (shipDying <= 0.0f) { + shipDying = 0.0f; + if (lives > 0) { + playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f); + } else { + gameOver = true; + printf("game over: %d kills\n", kills); + } + } + return; + } + + // 自機 / the ship playerX += in.axis("left", "right") * kPlayerSpeed * dt; playerX = std::clamp(playerX, kArenaLeft + 2.0f, kArenaRight - 2.0f - 15.0f); + fire(); 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); + updateShot(dt); + alienFire(dt); + updateAlienShots(dt); + if (shipDying > 0.0f) return; + + // 防壁まで下りてきた宇宙人は防壁を食べる / aliens that reach the shields eat them + for (const Alien &a : formation.aliens) + if (a.alive && a.box().bottom() > kShieldY) shields->eraseRect(a.box()); + // 自機の高さまで来たら侵略された:残りの自機に関係なくゲームオーバー / reaching the ship's row is an invasion: + // game over whatever lives are left + if (formation.alive() > 0 && formation.bounds().bottom() > kPlayerY) { + printf("invaded\n"); + lives = 1; + killShip(); + return; + } + // 全滅させたら次の隊列(第29章で場面ごと読み直す) / when the formation is wiped out, a new one comes (chapter 29 + // reloads the whole scene) + if (formation.cleared()) { + ++waves; + printf("wave cleared: %d kills\n", kills); + formation.reset(formationStartX(), kFormationTop); + fireTimer = 1.0f; } } @@ -82,52 +276,79 @@ void PlayScene::drawBackground() { } void PlayScene::drawFormation() { + // 生きている宇宙人と、爆発中の宇宙人(爆発のコマ) / living aliens and exploding ones (explosion frames) 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) + if (a.alive || a.dying > 0.0f) 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)); + if (a.alive || a.dying > 0.0f) 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::drawBoxes() { + // 当たり判定の箱(B):宇宙人 = 赤、自機 = 緑、弾 = 黄、防壁 = 青(防壁はさらにピクセル単位で調べる) + // The collision boxes (B): aliens red, ship green, bullets yellow, shields blue (shields are then tested per pixel) + SpriteBatch &b = g.batch; + for (const Alien &a : formation.aliens) + if (a.alive) b.drawRectOutline(a.box(), hexColor(0xff4040c0)); + for (int i = 0; i < kShieldCount; ++i) b.drawRectOutline(shields->bounds(i), hexColor(0x40a0ffc0)); + if (shipDying <= 0.0f && !gameOver) b.drawRectOutline(shipBox(), hexColor(0x40ff60ff)); + if (shot) b.drawRectOutline(shot->box, hexColor(0xffe040ff)); + for (const Bullet &s : alienShots) b.drawRectOutline(s.box, hexColor(0xffe040ff)); +} + void PlayScene::draw(float alpha) { - // 奥から:背景(バッチ)→ 隊列(インスタンシングかバッチ)→ 自機(バッチ) / back to front: background (batch) → - // formation (instanced or batch) → ship (batch) + if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor) + // 防壁:変わった所だけGPUへ(描く前に) / shields: send only the changed part to the GPU (before drawing) + shields->upload(); + if (shields->lastUploadBytes() > 0) shieldBytes = shields->lastUploadBytes(); + + // 奥から:背景と防壁(バッチ)→ 隊列(インスタンシングかバッチ)→ 自機・弾・爆発(バッチ) + // Back to front: background and shields (batch) → formation (instanced or batch) → ship, bullets, explosions (batch) g.batch.begin(g.world.matrix()); drawBackground(); + shields->draw(g.batch); g.batch.end(); drawFormation(); - // 宇宙人は飛び飛びに動くので補間しない。自機は滑らかに動くので補間する(第26章) - // Aliens move in jumps, so they are not interpolated. The ship moves smoothly, so it is (chapter 26) + SpriteBatch &b = g.batch; + b.begin(g.world.matrix()); 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(); + if (shipDying > 0.0f) b.draw(g.sprites.sprite(shipBoom.frame(), {x, kPlayerY})); + else if (!gameOver) b.draw(g.sprites.sprite(shipFrame, {x, kPlayerY})); + // 弾は滑らかに動くので補間する / bullets move smoothly, so they are interpolated + if (shot) b.draw(g.sprites.sprite(shotFrame, {shot->box.x, std::round(shot->prevY + (shot->box.y - shot->prevY) * alpha)})); + for (const Bullet &s : alienShots) + b.draw(g.sprites.sprite(s.anim.frame(), {s.box.x, std::round(s.prevY + (s.box.y - s.prevY) * alpha)})); + for (const Flare &f : flares) { + Sprite s = g.sprites.sprite(f.frame, {std::round(f.centre.x), std::round(f.centre.y)}, {0.5f, 0.5f}); + s.color = f.color; + b.draw(s); + } + particles.draw(b); + if (g.showBoxes) drawBoxes(); + b.end(); } void PlayScene::drawUi(float /*alpha*/) { + if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor) 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 + // 左の板:隊列の描き方と、戦いの数字 / the left panel: how the formation is drawn, and the battle numbers float y = 24.0f; auto text = [&](const char *s, const TextStyle &st) { g.ui.draw(b, s, {14.0f, y}, st); @@ -135,20 +356,27 @@ void PlayScene::drawUi(float /*alpha*/) { }; 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); + y += 16.0f; + text("BATTLE", head); + snprintf(line, sizeof line, "lives %d", lives); + text(line, body); + snprintf(line, sizeof line, "kills %d", kills); text(line, body); - snprintf(line, sizeof line, "landed %d", landings); + snprintf(line, sizeof line, "shots %d", shotsFired); + text(line, body); + snprintf(line, sizeof line, "wave %d", waves); + text(line, body); + y += 16.0f; + text("SHIELDS", head); + snprintf(line, sizeof line, "%d px left", shields->pixelsLeft()); + text(line, body); + snprintf(line, sizeof line, "upload %d B", shieldBytes); text(line, body); // 右の板:操作 / the right panel: controls @@ -160,8 +388,18 @@ void PlayScene::drawUi(float /*alpha*/) { right("CONTROLS", head); right("A D / arrows", body); right(" move", body); + right("Space fire", body); right("I formation", body); + right("B boxes", body); right("= - march", body); right("Esc quit", body); + + if (gameOver) { + b.drawRect({192.0f, 300.0f, 896.0f, 110.0f}, hexColor(0x0c0a1ad0)); + g.ui.draw(b, "GAME OVER", {640.0f, 316.0f}, + {.color = hexColor(0xd9474bff), .scale = 3.0f, .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); + g.ui.draw(b, "Space / Enter: play again", {640.0f, 378.0f}, + {.color = hexColor(0xd8dcefff), .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); + } b.end(); } diff --git a/games/invaders/src/shields.cc b/games/invaders/src/shields.cc new file mode 100644 index 0000000..e8cbb50 --- /dev/null +++ b/games/invaders/src/shields.cc @@ -0,0 +1,158 @@ +#include "shields.hh" + +#include "engine/file_util.hh" + +#include +#include +#include + +// 着弾の形(スプライトシートのsplatと同じ形):'W' = 消すピクセル / the impact shape (the same shape as the +// sheet's splat sprite): 'W' = a pixel to clear +static const char *const kSplat[] = { + "W..W.W", + "..WW..", + ".WWWW.", + "WWWWW.", + ".WWWWW", + "WWWWW.", + "..WW..", + "W..W.W", +}; +constexpr int kSplatW = 6, kSplatH = 8; + +std::optional loadSpriteImage(const std::string &pngPath, const SpriteSheet &sheet, const char *name) { + int index = sheet.find(name); + std::optional> bytes = readBinaryFile(pngPath); + if (index < 0 || !bytes) { + fprintf(stderr, "%s: スプライト %s がない / no sprite %s\n", pngPath.c_str(), name, name); + return std::nullopt; + } + std::optional sheetImage = decodeImage(bytes->data(), bytes->size(), false); + if (!sheetImage) return std::nullopt; + Rect r = sheet.pixels(index); + Image out; + out.width = static_cast(r.w); + out.height = static_cast(r.h); + out.rgba.resize(static_cast(out.width * out.height * 4)); + for (int y = 0; y < out.height; ++y) + for (int x = 0; x < out.width; ++x) + for (int c = 0; c < 4; ++c) { + size_t src = static_cast(4 * ((static_cast(r.y) + y) * sheetImage->width + static_cast(r.x) + x) + c); + out.rgba[static_cast(4 * (y * out.width + x) + c)] = sheetImage->rgba[src]; + } + // 乗算済みアルファにする(loadSpriteTextureが自動でやっていること)。PNGの透明なピクセルには、にじみ止めの色 + // (隣の不透明なピクセルの色)が入っているので、そのまま送ると (r, g, b, 0) が加算されて縁が光る + // Premultiply (what loadSpriteTexture does for you). The PNG's transparent pixels carry the nearest opaque color + // against fringes; sent as is, (r, g, b, 0) would be *added* by the premultiplied blend and the edges would glow + for (size_t i = 0; i < out.rgba.size(); i += 4) + for (size_t c = 0; c < 3; ++c) out.rgba[i + c] = static_cast(out.rgba[i + c] * out.rgba[i + 3] / 255); + return out; +} + +std::optional Shields::create(const Image &art, const Vec2 (&positions)[kShieldCount]) { + if (art.width != kShieldW || art.height != kShieldH) { + fprintf(stderr, "防壁の絵が %d × %d でない / the shield art is not %d × %d\n", kShieldW, kShieldH, kShieldW, kShieldH); + return std::nullopt; + } + Shields s; + s.pixels.resize(static_cast(kTexW * kTexH * 4)); + for (int i = 0; i < kShieldCount; ++i) { + s.topLeft[i] = positions[i]; + for (int y = 0; y < kShieldH; ++y) + std::copy_n(art.rgba.begin() + 4 * y * kShieldW, 4 * kShieldW, + s.pixels.begin() + 4 * (y * kTexW + i * kShieldW)); + } + // 中身は後で書き換えるので、空のストレージを作ってから全体を一度送る / the contents change later, so allocate + // empty storage and send everything once + s.tex = Texture2D(kTexW, kTexH, GL_RGBA8, 1); + s.tex.setFilter(GL_NEAREST, GL_NEAREST); + s.tex.setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); + s.tex.upload(s.pixels.data()); + return s; +} + +void Shields::clearPixel(int x, int y) { + if (x < 0 || y < 0 || x >= kTexW || y >= kTexH || !solid(x, y)) return; + std::fill_n(pixels.begin() + 4 * (y * kTexW + x), 4, std::uint8_t{0}); + dirtyX0 = std::min(dirtyX0, x), dirtyY0 = std::min(dirtyY0, y); + dirtyX1 = std::max(dirtyX1, x + 1), dirtyY1 = std::max(dirtyY1, y + 1); +} + +std::optional Shields::hit(const Rect &box, bool fromBelow) const { + for (int i = 0; i < kShieldCount; ++i) { + Rect s = bounds(i); + // boxが重なるピクセルの範囲(防壁の中の座標) / the pixels the box covers (shield coordinates) + int x0 = std::max(0, static_cast(std::floor(box.left() - s.x))); + int x1 = std::min(kShieldW, static_cast(std::ceil(box.right() - s.x))); + int y0 = std::max(0, static_cast(std::floor(box.top() - s.y))); + int y1 = std::min(kShieldH, static_cast(std::ceil(box.bottom() - s.y))); + if (x0 >= x1 || y0 >= y1) continue; + for (int n = 0; n < y1 - y0; ++n) { + int y = fromBelow ? y1 - 1 - n : y0 + n; + for (int x = x0; x < x1; ++x) + if (solid(i * kShieldW + x, y)) + return Vec2{s.x + static_cast(x) + 0.5f, s.y + static_cast(y) + 0.5f}; + } + } + return std::nullopt; +} + +void Shields::erode(Vec2 point, Rng &rng) { + bool mirror = rng.chance(0.5f); + for (int i = 0; i < kShieldCount; ++i) { + Rect s = bounds(i); + // 着弾の形の左上(防壁の中の座標) / the impact shape's top left (shield coordinates) + int ox = static_cast(std::floor(point.x - s.x)) - kSplatW / 2; + int oy = static_cast(std::floor(point.y - s.y)) - kSplatH / 2; + if (ox >= kShieldW || oy >= kShieldH || ox + kSplatW <= 0 || oy + kSplatH <= 0) continue; + for (int y = 0; y < kSplatH; ++y) + for (int x = 0; x < kSplatW; ++x) { + int sx = ox + x, sy = oy + y; + char c = kSplat[y][mirror ? kSplatW - 1 - x : x]; + if (c == 'W' && sx >= 0 && sx < kShieldW && sy >= 0 && sy < kShieldH) clearPixel(i * kShieldW + sx, sy); + } + } +} + +void Shields::eraseRect(const Rect &box) { + for (int i = 0; i < kShieldCount; ++i) { + Rect s = bounds(i); + int x0 = std::max(0, static_cast(std::floor(box.left() - s.x))); + int x1 = std::min(kShieldW, static_cast(std::ceil(box.right() - s.x))); + int y0 = std::max(0, static_cast(std::floor(box.top() - s.y))); + int y1 = std::min(kShieldH, static_cast(std::ceil(box.bottom() - s.y))); + for (int y = y0; y < y1; ++y) + for (int x = x0; x < x1; ++x) clearPixel(i * kShieldW + x, y); + } +} + +void Shields::upload() { + uploadBytes = 0; + if (dirtyX0 >= dirtyX1 || dirtyY0 >= dirtyY1) return; // 変わっていない / nothing changed + int w = dirtyX1 - dirtyX0, h = dirtyY1 - dirtyY0; + // CPUの配列の一部(四角)を送る:行の長さ(GL_UNPACK_ROW_LENGTH)を配列全体の幅にすると、GLは一行ごとに + // kTexWピクセル先へ進む。ポインターは四角の左上。送ったら0(= 幅と同じ)に戻す + // Send a rectangle out of the CPU array: with GL_UNPACK_ROW_LENGTH = the whole array's width, the GL steps kTexW + // pixels for every row. The pointer is the rectangle's top left. Reset it to 0 (= the width) afterwards + glPixelStorei(GL_UNPACK_ROW_LENGTH, kTexW); + glTextureSubImage2D(tex.id(), 0, dirtyX0, dirtyY0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, + pixels.data() + 4 * (dirtyY0 * kTexW + dirtyX0)); + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + uploadBytes = w * h * 4; + dirtyX0 = kTexW, dirtyY0 = kTexH, dirtyX1 = 0, dirtyY1 = 0; +} + +void Shields::draw(SpriteBatch &batch, float layer) const { + for (int i = 0; i < kShieldCount; ++i) + batch.draw({.texture = &tex, + .position = topLeft[i], + .size = {kShieldW, kShieldH}, + .uv = {static_cast(i) / kShieldCount, 0.0f, 1.0f / kShieldCount, 1.0f}, + .layer = layer}); +} + +int Shields::pixelsLeft() const { + int n = 0; + for (size_t i = 3; i < pixels.size(); i += 4) n += pixels[i] != 0; + return n; +} diff --git a/games/invaders/src/shields.hh b/games/invaders/src/shields.hh new file mode 100644 index 0000000..b5a2192 --- /dev/null +++ b/games/invaders/src/shields.hh @@ -0,0 +1,64 @@ +// 削れる防壁(第28章):ピクセルの絵をCPUに持ち、弾が当たった所を消して、変わった四角だけを +// glTextureSubImage2Dでテクスチャに送り直す +// Shields that erode (chapter 28): the pixels live on the CPU; an impact clears pixels there, and only the changed +// rectangle is sent to the texture again with glTextureSubImage2D +#pragma once + +#include "engine/rect.hh" +#include "engine/rng.hh" +#include "engine/sprite_batch.hh" +#include "engine/sprite_sheet.hh" +#include "engine/texture.hh" + +#include +#include +#include +#include + +constexpr int kShieldCount = 4; +constexpr int kShieldW = 22, kShieldH = 16; + +// スプライトシートのPNGをCPUでもう一度デコードして、名前の絵だけを切り出す(RGBA8、上の行から)。 +// 透明なピクセルのRGBは0にする(乗算済みアルファ:GPUに送るときに要る) +// Decodes the sprite sheet's PNG again on the CPU and cuts out one named sprite (RGBA8, rows from the top). +// Transparent pixels get RGB 0 (premultiplied alpha: needed when they are sent to the GPU) +std::optional loadSpriteImage(const std::string &pngPath, const SpriteSheet &sheet, const char *name); + +class Shields { +public: + // 4つの防壁を一枚のテクスチャ(88 × 16)に並べる。topLeft[i] = 画面での防壁iの左上 + // Puts the 4 shields side by side in one texture (88 × 16). topLeft[i] = where shield i goes on screen + static std::optional create(const Image &art, const Vec2 (&topLeft)[kShieldCount]); + + // boxの中に残っている防壁のピクセルがあるか。あれば、弾の進む向きで最初に当たるピクセル(の中心) + // (下から来る弾 = 一番下、上から来る弾 = 一番上) + // Is any shield pixel left inside box? If so, the pixel a bullet meets first (its center): the lowest for a + // bullet coming from below, the highest for one coming from above + std::optional hit(const Rect &box, bool fromBelow) const; + // 着弾の形(kSplat、6 × 8)でピクセルを消す。左右はランダムに反転 / clears pixels in the impact shape (kSplat, + // 6 × 8), mirrored at random + void erode(Vec2 point, Rng &rng); + // 四角の中を全部消す(防壁まで下りてきた宇宙人) / clears everything inside the box (aliens that reach the shields) + void eraseRect(const Rect &box); + + // 変わった所だけをアップロードする(描く前に一度) / uploads only what changed (once, before drawing) + void upload(); + void draw(SpriteBatch &batch, float layer = 0.0f) const; + Rect bounds(int i) const { return {topLeft[i].x, topLeft[i].y, kShieldW, kShieldH}; } + int lastUploadBytes() const { return uploadBytes; } + int pixelsLeft() const; + const Texture2D &texture() const { return tex; } + +private: + static constexpr int kTexW = kShieldW * kShieldCount, kTexH = kShieldH; + Shields() = default; + void clearPixel(int x, int y); // テクスチャのピクセル座標 / texture pixel coordinates + bool solid(int x, int y) const { return pixels[static_cast(4 * (y * kTexW + x) + 3)] != 0; } + + std::vector pixels; // kTexW × kTexH × RGBA8(CPUの正本) / the CPU master copy + Texture2D tex; + Vec2 topLeft[kShieldCount]; + int dirtyX0 = kTexW, dirtyY0 = kTexH, dirtyX1 = 0, dirtyY1 = 0; // 変わった四角(x1・y1は含まない) / the changed + // rectangle (x1, y1 exclusive) + int uploadBytes = 0; +};