diff --git a/games/tps/CMakeLists.txt b/games/tps/CMakeLists.txt index 5ba4f08..e89207d 100644 --- a/games/tps/CMakeLists.txt +++ b/games/tps/CMakeLists.txt @@ -8,6 +8,8 @@ add_executable(tps src/renderer.cc src/character.cc src/third_person_camera.cc + src/enemy.cc + src/effects.cc src/play_scene.cc) target_include_directories(tps PRIVATE src) target_link_libraries(tps PRIVATE engine) diff --git a/games/tps/README.md b/games/tps/README.md index fa0c91c..f8944a5 100644 --- a/games/tps/README.md +++ b/games/tps/README.md @@ -7,7 +7,7 @@ ./build/games/tps/tps games/tps/assets/levels/pieces.level # 部品を並べたレベル / every piece in a row ``` -## 操作 / Controls(第36・37章 / chapters 36-37) +## 操作 / Controls(第36〜38章 / chapters 36-38) | キー / key | | |---|---| @@ -15,14 +15,18 @@ | マウス / mouse | 見回す / look around | | Shift | 走る(前へ) / run (forwards) | | Space | ジャンプ / jump | +| 左ボタン / LMB | 撃つ(押し続けると連射) / fire (hold for automatic fire) | +| 右ボタン / RMB | 狙う(肩に寄る、拡散が小さい) / aim (closer, less spread) | +| R | 弾を込め直す / reload | | Q | 右肩 ⇔ 左肩 / right ⇔ left shoulder | -| B | 当たり判定の箱・カプセル・軌跡・ソケット / collision boxes, capsule, trail, sockets | +| B | 当たり判定の箱・カプセル・軌跡・ソケット・敵のAI / collision boxes, capsule, trail, sockets, enemy AI | | O | 上から見下ろす(デバッグ) / view from above (debugging) | | L | 壁ずり ⇔ 壁で止まる / wall sliding ⇔ stopping at walls | | C | カメラだけ回す(キャラクターを前から見る) / turn only the camera (look at the character) | | K | カメラの当たり判定のオン・オフ / camera collision on / off | | P | 手続き的な姿勢のオン・オフ / procedural pose on / off | | F3 | 時間と描いた数 / timings and draw counts | +| F8 | 毎フレームの状態を標準出力へ(台本作り用) / log the state every frame to stdout (for scripting) | | F4 | 視錐台カリングのオン・オフ / frustum culling on / off | | Tab | カーソルのキャプチャ / cursor capture | | Esc | 終了 / quit | @@ -36,6 +40,10 @@ src/play_scene.* 遊ぶシーン / the play scene src/level.* レベルのファイル、インスタンシング、カリング / level file, instancing, culling src/collision3d.* AABB、レイ、スフィアキャスト、カプセルと箱 / AABBs, rays, sphere casts, capsule vs box src/character_body.* 当たり判定・重力・壁ずり・段差 / collision, gravity, wall sliding, steps +src/enemy.* 敵の状態機械のAI / the enemies' state-machine AI +src/effects.* 銃口の光・トレーサー・火花 / muzzle flash, tracers, sparks +src/angles.hh 角度の小道具 / angle helpers +shaders/particle.vert/.frag 火花のビルボード / spark billboards src/frustum.* 視錐台の平面 / frustum planes src/renderer.* 影 → 場面(PBR + IBL) → 後処理 / shadows → scene (PBR + IBL) → post src/character.* 関節の姿勢と腕のIK / joint poses and arm IK diff --git a/games/tps/assets/LICENSE.txt b/games/tps/assets/LICENSE.txt index 54d4c13..5fe291a 100644 --- a/games/tps/assets/LICENSE.txt +++ b/games/tps/assets/LICENSE.txt @@ -8,6 +8,7 @@ models/pillar.glb 柱と照明 / a pillar with a lamp models/platform.glb 台(縞鋼板の上面) / a platform with a diamond-plate top models/stairs.glb 階段 / stairs models/player.glb プレイヤー:部品の階層とソケット / the player: parts in a node hierarchy + sockets +models/enemy.glb 敵(同じ骨組み) / the enemy (same skeleton) (chapter 38) models/rifle.glb ライフル(Muzzle・Foregripソケット) / the rifle (Muzzle and Foregrip sockets) levels/arena.level レベル(手で書いたテキスト) / the level (hand-written text) levels/pieces.level 部品を並べた確認用のレベル / every piece in a row, for checking (hand-written text) diff --git a/games/tps/assets/levels/arena.level b/games/tps/assets/levels/arena.level index ebd13bb..d034dd5 100644 --- a/games/tps/assets/levels/arena.level +++ b/games/tps/assets/levels/arena.level @@ -7,6 +7,7 @@ # row x y z yaw dx dz count count pieces, (dx, dz) apart # grid x y z yaw step nx nz nx × nz pieces, step apart # spawn x y z yaw the player's start (yaw 0 = facing north, -Z) +# enemy x y z yaw x1 z1 x2 z2 ... an enemy: start + patrol points (chapter 38) model floor games/tps/assets/models/floor_tile.glb noshadow nocollide vary=0.06 model wall games/tps/assets/models/wall.glb vary=0.05 @@ -85,3 +86,10 @@ place barrel -12.2 0 -13.6 90 place barrel 6.9 0 0.3 0 spawn 0 0 11.5 0 + +# 敵(第38章):enemy x y z yaw 巡回の点 x z ... / enemies (chapter 38): enemy x y z yaw patrol points x z ... +enemy -14 0 -13 180 -14 -13 -14 -3 +enemy -6 0 -14.5 90 -6 -14.5 6 -14.5 +enemy 0 1.5 -3 180 0 -3 0 3 +enemy 13.5 0 -9 180 13.5 -9 13.5 7 +enemy -6 0 -8.5 90 -6 -8.5 6 -8.5 diff --git a/games/tps/assets/models/enemy.glb b/games/tps/assets/models/enemy.glb new file mode 100644 index 0000000..5b9c648 Binary files /dev/null and b/games/tps/assets/models/enemy.glb differ diff --git a/games/tps/shaders/particle.frag b/games/tps/shaders/particle.frag new file mode 100644 index 0000000..1ac6133 --- /dev/null +++ b/games/tps/shaders/particle.frag @@ -0,0 +1,37 @@ +#version 460 core +// 火花:丸く柔らかい光の点。加算合成(glBlendFunc(GL_ONE, GL_ONE))なので、描く順番は関係ない +// Sparks: soft round dots of light. Additive blending (glBlendFunc(GL_ONE, GL_ONE)), so the draw order does not matter +in vec2 vCorner; +in vec3 vColor; + +layout(location = 0) out vec4 out_color; + +// 後処理の設定(ユニフォームバッファ、結合点3、std140、第21章)。使う全部のシェーダーで同じ宣言(C++ではPostBlock) +// Post-processing settings (uniform buffer, binding 3, std140, chapter 21). The same declaration in every shader that +// uses it (PostBlock in C++) +layout(std140, binding = 3) uniform Post { + float uExposure; // 明るさの倍率 / brightness multiplier + float uBloomStrength; // ブルームの強さ / bloom strength + float uBloomThreshold; // これより明るい部分が光る(リニアのHDR値) / brighter than this glows (linear HDR value) + int uToneMapper; // 0 = クランプ / clamp, 1 = Reinhard, 2 = ACES + int uGammaMode; // 0 = シェーダー / shader, 1 = GL_FRAMEBUFFER_SRGB, 2 = なし / none, 3 = 二重 / double + int uPostView; // 0 = 完成 / final, 1 = ブルームなし / no bloom, 2 = 明るい部分 / bright part, 3 = ブルーム / bloom + int uPostPad0, uPostPad1; // std140の大きさを32バイトにそろえる / pads the block to 32 bytes +}; + +// ブルーム用の2つ目の出力(MRT、GL_COLOR_ATTACHMENT1) / the second output for bloom (MRT, GL_COLOR_ATTACHMENT1) +layout(location = 1) out vec4 out_bright; +vec3 brightPart(vec3 c) { + float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); // 輝度 / luminance + return c * (max(l - uBloomThreshold, 0.0) / max(l, 1e-4)); +} + +void main() { + float d = dot(vCorner, vCorner); + if (d > 1.0) discard; + float a = (1.0 - d) * (1.0 - d); // 真ん中ほど明るい / brighter towards the center + vec3 c = vColor * a; + // アルファ0:加算でも行き先のアルファは変わらない / alpha 0: the destination alpha stays as it is + out_color = vec4(c, 0.0); + out_bright = vec4(brightPart(c), 0.0); +} diff --git a/games/tps/shaders/particle.vert b/games/tps/shaders/particle.vert new file mode 100644 index 0000000..4895bd7 --- /dev/null +++ b/games/tps/shaders/particle.vert @@ -0,0 +1,34 @@ +#version 460 core +// 火花(第38章):インスタンスごとに一枚の四角形をカメラに向けて描く(ビルボード)。頂点バッファはなく、 +// gl_VertexIDから角を作る(第17章の全画面三角形と同じ考え) +// Sparks (chapter 38): one camera-facing quad per instance (a billboard). There is no vertex buffer: the corners come +// from gl_VertexID (the same idea as chapter 17's fullscreen triangle) +layout(location = 4) in vec4 aParticle; // xyz = 位置 / position, w = 半分の大きさ(m) / half size (m) +layout(location = 5) in vec4 aColor; // rgb = HDRの色(消えていく分を掛け済み) / HDR color (fade applied) + +// カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock) +// The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++) +layout(std140, binding = 0) uniform Camera { + mat4 uView; + mat4 uProj; + vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space) + float uTime; // アニメーションの時間(秒) / animation time (seconds) +}; + +out vec2 vCorner; +out vec3 vColor; + +const vec2 kCorners[6] = vec2[](vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), + vec2(1.0, 1.0), vec2(-1.0, 1.0), vec2(-1.0, -1.0)); + +void main() { + vec2 c = kCorners[gl_VertexID]; + // ビュー行列の行0・行1 = カメラの右と上(ワールド座標) / rows 0 and 1 of the view matrix = the camera's right and + // up in world space + vec3 right = vec3(uView[0][0], uView[1][0], uView[2][0]); + vec3 up = vec3(uView[0][1], uView[1][1], uView[2][1]); + vec3 p = aParticle.xyz + (c.x * right + c.y * up) * aParticle.w; + vCorner = c; + vColor = aColor.rgb; + gl_Position = uProj * uView * vec4(p, 1.0); +} diff --git a/games/tps/src/angles.hh b/games/tps/src/angles.hh new file mode 100644 index 0000000..60db1b1 --- /dev/null +++ b/games/tps/src/angles.hh @@ -0,0 +1,21 @@ +// 角度と、なめらかに近づく計算(第36〜38章のあちこちで使う) / angles and smooth approach (used all over ch. 36-38) +#pragma once + +#include + +#include + +// 角度を −π〜π に / wraps an angle into −π..π +inline float wrapAngle(float a) { + while (a > PI) a -= 2.0f * PI; + while (a < -PI) a += 2.0f * PI; + return a; +} +// 指数的に近づく割合:毎秒rateで目標へ(ステップの長さによらない) / exponential smoothing factor: approaches the +// target at `rate` per second, independent of the step length +inline float approach(float rate, float dt) { return 1.0f - std::exp(-rate * dt); } +// 目標の角度へ短い方の向きで近づく / approaches a target angle the short way round +inline float approachAngle(float current, float target, float k) { return current + wrapAngle(target - current) * k; } +// 水平の前(カメラのyawと同じ決まり:0 = −Z) / horizontal forward (camera-yaw convention: 0 = −Z) +inline Vec3 headingForward(float heading) { return {std::sin(heading), 0.0f, -std::cos(heading)}; } +inline Vec3 headingRight(float heading) { return {std::cos(heading), 0.0f, std::sin(heading)}; } diff --git a/games/tps/src/character.cc b/games/tps/src/character.cc index ee04804..e07a532 100644 --- a/games/tps/src/character.cc +++ b/games/tps/src/character.cc @@ -1,5 +1,7 @@ #include "character.hh" +#include "angles.hh" + #include #include #include @@ -30,6 +32,33 @@ std::optional CharacterRig::find(const Model &model) { return rig; } +void updateLocomotion(CharacterPose &pose, Vec3 velocity, float heading, bool grounded, float dt, float walkSpeed, + float runSpeed) { + float speed = length(Vec3{velocity.x, 0.0f, velocity.z}); + float legTarget = 0.0f, direction = 1.0f; + if (speed > 0.2f) { + // 速度をキャラクターの座標へ:+Zが前、+Xが左(右手系で+Zを向くと+Xは左) / velocity in character space: +Z is + // forward, +X is LEFT (facing +Z in a right-handed system, +X is on the left) + float mz = dot(velocity, headingForward(heading)), mx = -dot(velocity, headingRight(heading)); + legTarget = std::atan2(mx, mz); + if (std::fabs(legTarget) > radians(100.0f)) { // 後ろ歩き:脚は前を向いたまま逆に回す / walking backwards + legTarget = wrapAngle(legTarget - PI); + direction = -1.0f; + } + legTarget = std::clamp(legTarget, radians(-70.0f), radians(70.0f)); + } + pose.legYaw = approachAngle(pose.legYaw, legTarget, approach(10.0f, dt)); + // 歩きの周期は進んだ距離に比例:足が地面を滑らない / the walk cycle advances with distance: feet do not skate + float run = std::clamp((speed - walkSpeed) / (runSpeed - walkSpeed), 0.0f, 1.0f); + float cycleLength = 1.5f + 0.9f * run; // 1周期(2歩)のm / meters per cycle (two steps) + pose.walkPhase = std::fmod(pose.walkPhase + direction * 2.0f * PI * speed * dt / cycleLength, 2.0f * PI); + pose.walkAmount = std::clamp(speed / walkSpeed, 0.0f, 1.0f); + pose.stride = 1.0f + 0.5f * run; + // 空中の姿勢へなめらかに(着地で戻る) / blend into the airborne pose (and back on landing) + pose.air += ((grounded ? 0.0f : 1.0f) - pose.air) * approach(12.0f, dt); + if (!grounded) pose.walkAmount *= 1.0f - pose.air; +} + Mat4 characterMatrix(Vec3 position, float heading) { return translate(position) * rotateY(PI - heading); } // X軸周りの回転 / rotation about X diff --git a/games/tps/src/character.hh b/games/tps/src/character.hh index 2c939b4..bef1dbd 100644 --- a/games/tps/src/character.hh +++ b/games/tps/src/character.hh @@ -34,6 +34,14 @@ struct CharacterPose { // chapter 37) }; +// 速度と向きから歩きのパラメーターを進める(プレイヤーも敵も同じ、第38章でplay_sceneから移した): +// 歩きの周期は進んだ距離に比例、脚は移動の向きへ(後ろ歩きは逆回し)、空中では脚を縮める +// Advances the walking parameters from velocity and heading (player and enemies alike; moved out of play_scene in +// chapter 38): the cycle advances with distance, the legs turn towards the movement (backwards runs the cycle in +// reverse), airborne tucks the legs +void updateLocomotion(CharacterPose &pose, Vec3 velocity, float heading, bool grounded, float dt, float walkSpeed, + float runSpeed); + // ゲームの中の位置と向き → モデル行列。headingはカメラのyawと同じ決まり(0 = −Zを向く、正 = 右へ回る)で、 // モデルの正面は+Z(第14章の決まり)なので rotateY(π − heading) // Position and heading in the game → model matrix. heading uses the camera's yaw convention (0 = facing −Z, positive diff --git a/games/tps/src/collision3d.cc b/games/tps/src/collision3d.cc index 3982008..beeb097 100644 --- a/games/tps/src/collision3d.cc +++ b/games/tps/src/collision3d.cc @@ -131,3 +131,43 @@ std::optional deepestContact(const Capsule &capsule, std::span raySphere(const Ray &ray, Vec3 centre, float radius, float maxT) { + // |o + t·d − c|² = r² → t² + 2(m·d)t + (m·m − r²) = 0 (m = o − c、|d| = 1) / (m = o − c, |d| = 1) + Vec3 m = ray.origin - centre; + float b = dot(m, ray.direction), c = dot(m, m) - radius * radius; + if (c > 0.0f && b > 0.0f) return std::nullopt; // 外にいて遠ざかる / outside and moving away + float disc = b * b - c; + if (disc < 0.0f) return std::nullopt; // 外れ / a miss + float t = std::fmax(-b - std::sqrt(disc), 0.0f); + if (t > maxT) return std::nullopt; + Vec3 p = ray.origin + t * ray.direction; + return RayHit{t, normalize(p - centre), -1}; +} + +std::optional rayCapsule(const Ray &ray, const Capsule &capsule, float maxT) { + std::optional best; + auto keep = [&](std::optional h) { + if (h && (!best || h->t < best->t)) best = h; + }; + float y0 = capsule.bottomY(), y1 = capsule.topY(); + keep(raySphere(ray, {capsule.base.x, y0, capsule.base.z}, capsule.radius, maxT)); + keep(raySphere(ray, {capsule.base.x, y1, capsule.base.z}, capsule.radius, maxT)); + // 側面:xzだけで円と交差させ、当たった高さが線分の範囲なら当たり / the side: intersect the circle in xz only; a hit + // counts if its height is within the segment + float ox = ray.origin.x - capsule.base.x, oz = ray.origin.z - capsule.base.z; + float dx = ray.direction.x, dz = ray.direction.z; + float a = dx * dx + dz * dz; + if (a > 1e-8f) { + float b = ox * dx + oz * dz, c = ox * ox + oz * oz - capsule.radius * capsule.radius; + float disc = b * b - a * c; + if (disc >= 0.0f) { + float t = (-b - std::sqrt(disc)) / a; + if (t >= 0.0f && t <= maxT) { + Vec3 p = ray.origin + t * ray.direction; + if (p.y >= y0 && p.y <= y1) keep(RayHit{t, normalize(Vec3{p.x - capsule.base.x, 0.0f, p.z - capsule.base.z}), -1}); + } + } + } + return best; +} diff --git a/games/tps/src/collision3d.hh b/games/tps/src/collision3d.hh index fa7ad6b..f842dfd 100644 --- a/games/tps/src/collision3d.hh +++ b/games/tps/src/collision3d.hh @@ -1,7 +1,8 @@ -// 3Dの当たり判定(第36・37章):軸に平行な箱(AABB)、レイ・球を飛ばすテスト(カメラ、第36章)、 -// 縦のカプセル・球と箱のめり込み(キャラクター、第37章) -// 3D collision (chapters 36-37): axis-aligned boxes (AABBs), ray / sphere casts (the camera, chapter 36) and the -// penetration of upright capsules / spheres into boxes (the characters, chapter 37) +// 3Dの当たり判定(第36〜38章):軸に平行な箱(AABB)、レイ・球を飛ばすテスト(カメラ、第36章)、 +// 縦のカプセル・球と箱のめり込み(キャラクター、第37章)、レイと球・カプセル(弾、第38章) +// 3D collision (chapters 36-38): axis-aligned boxes (AABBs), ray / sphere casts (the camera, chapter 36), the +// penetration of upright capsules / spheres into boxes (the characters, chapter 37) and rays against spheres and +// capsules (the bullets, chapter 38) #pragma once #include "engine/mathx.hh" @@ -88,3 +89,12 @@ struct Capsule { std::optional capsuleAabb(const Capsule &capsule, const Aabb &box); // 一番深いめり込み(なければnullopt) / the deepest penetration among the boxes (nullopt if none) std::optional deepestContact(const Capsule &capsule, std::span boxes); + +// レイと球(第38章:敵の当たり判定は頭・胸・腰・脚の球)。始点が球の中ならt = 0 +// Ray against sphere (chapter 38: an enemy's hit volumes are spheres for head, chest, hips and legs). Origin inside → +// t = 0 +std::optional raySphere(const Ray &ray, Vec3 centre, float radius, float maxT); +// レイと縦のカプセル(第38章:敵の弾とプレイヤー):円柱の側面(xz平面の円との交差)と上下の球 +// Ray against an upright capsule (chapter 38: enemy bullets against the player): the cylinder's side (a circle +// intersection in the xz plane) and the two end spheres +std::optional rayCapsule(const Ray &ray, const Capsule &capsule, float maxT); diff --git a/games/tps/src/effects.cc b/games/tps/src/effects.cc new file mode 100644 index 0000000..0db4d1c --- /dev/null +++ b/games/tps/src/effects.cc @@ -0,0 +1,127 @@ +#include "effects.hh" + +#include "engine/uniforms.hh" + +#include +#include + +Effects::Effects() { + shader = Shader::load("games/tps/shaders/particle.vert", "games/tps/shaders/particle.frag"); + if (shader && (!shader->checkUniformBlock("Camera", sizeof(CameraBlock)) || + !shader->checkUniformBlock("Post", sizeof(PostBlock)))) + shader.reset(); + // 頂点の属性はインスタンスごとの2つだけ(バインディング0、divisor 1)。角はシェーダーがgl_VertexIDから作る + // Only two per-instance attributes (binding 0, divisor 1). The shader makes the corners from gl_VertexID + instances = Buffer(nullptr, kMaxParticles * static_cast(sizeof(ParticleInstance)), GL_DYNAMIC_STORAGE_BIT); + glCreateVertexArrays(1, &vao); + glVertexArrayVertexBuffer(vao, 0, instances.id(), 0, sizeof(ParticleInstance)); + glVertexArrayBindingDivisor(vao, 0, 1); + for (GLuint location : {4u, 5u}) { + glEnableVertexArrayAttrib(vao, location); + glVertexArrayAttribFormat(vao, location, 4, GL_FLOAT, GL_FALSE, location == 4 ? 0 : sizeof(Vec4)); + glVertexArrayAttribBinding(vao, location, 0); + } +} + +Effects::~Effects() { + if (vao) glDeleteVertexArrays(1, &vao); +} + +void Effects::sparks(Vec3 at, Vec3 normal, Vec3 color, int count, Rng &rng) { + for (int i = 0; i < count && particles.size() < kMaxParticles; ++i) { + // 球の中の向きを一つ選び、法線の側へ折り返し、法線の向きを少し足す(面から跳ね返る) / a random direction, folded + // to the normal's side, plus a bit of the normal (bouncing off the surface) + Vec3 d = {rng.range(-1.0f, 1.0f), rng.range(-1.0f, 1.0f), rng.range(-1.0f, 1.0f)}; + if (dot(d, normal) < 0.0f) d = d - 2.0f * dot(d, normal) * normal; + d = normalize(d + 0.6f * normal); + float life = rng.range(0.18f, 0.45f); + particles.push_back({at + 0.02f * normal, rng.range(2.0f, 6.5f) * d, life, life, rng.range(0.015f, 0.035f), + color * rng.range(0.6f, 1.4f)}); + } +} + +void Effects::tracer(Vec3 from, Vec3 to, Vec3 color) { streaks.push_back({from, to, 0.06f, 0.06f, color}); } + +void Effects::muzzleFlash(Vec3 at, Vec3 direction) { flashes.push_back({at, direction, 0.05f}); } + +void Effects::update(float dt) { + for (Particle &p : particles) { + p.velocity.y -= 9.8f * dt; // 火花も落ちる / sparks fall too + p.velocity = (1.0f - 2.0f * dt) * p.velocity; // 空気抵抗 / air drag + p.position = p.position + dt * p.velocity; + p.life -= dt; + } + std::erase_if(particles, [](const Particle &p) { return p.life <= 0.0f; }); + for (Streak &s : streaks) s.life -= dt; + std::erase_if(streaks, [](const Streak &s) { return s.life <= 0.0f; }); + for (Flash &f : flashes) f.life -= dt; + std::erase_if(flashes, [](const Flash &f) { return f.life <= 0.0f; }); +} + +void Effects::addLights(LightSet &lights) const { + int n = 0; + for (const Flash &f : flashes) { + if (n++ == 4) break; + float k = f.life / 0.05f; + lights.points.push_back({.position = f.position, .color = k * Vec3{3.0f, 1.9f, 0.9f}, .attenuation = kShortRange}); + } +} + +Mat4 beamMatrix(Vec3 a, Vec3 b, float thickness) { + Vec3 d = b - a; + float len = std::fmax(length(d), 1e-4f); + Vec3 z = d / len; + Vec3 x = normalize(cross(std::fabs(z.y) > 0.99f ? Vec3{1, 0, 0} : Vec3{0, 1, 0}, z)); + Vec3 y = cross(z, x); + Mat4 m; + m.c[0] = {thickness * x.x, thickness * x.y, thickness * x.z, 0.0f}; + m.c[1] = {thickness * y.x, thickness * y.y, thickness * y.z, 0.0f}; + m.c[2] = {len * z.x, len * z.y, len * z.z, 0.0f}; + Vec3 mid = 0.5f * (a + b); + m.c[3] = {mid.x, mid.y, mid.z, 1.0f}; + return m; +} + +void Effects::drawStreaks(const Renderer &r) const { + if (streaks.empty() && flashes.empty()) return; + const Shader &s = *r.unlit; + s.use(); + for (const Streak &t : streaks) { + float k = t.life / t.maxLife; + s.set("uColor", k * t.color); + s.set("uModel", beamMatrix(t.from, t.to, 0.02f)); + r.cube.draw(); + } + // 銃口の光:銃の向きに伸ばした明るい球を2つ(十字に見える) / the muzzle flash: two bright spheres stretched along + // the barrel (reads as a star) + for (const Flash &f : flashes) { + float k = f.life / 0.05f; + s.set("uColor", k * Vec3{16.0f, 9.0f, 3.5f}); + s.set("uModel", beamMatrix(f.position, f.position + 0.28f * f.direction, 0.09f)); + r.sphere.draw(); + s.set("uModel", translate(f.position + 0.06f * f.direction) * scale({0.16f, 0.16f, 0.16f})); + r.sphere.draw(); + } +} + +void Effects::drawParticles() { + if (particles.empty() || !shader) return; + scratch.clear(); + for (const Particle &p : particles) { + float k = p.life / p.maxLife; // 消えていく / fading out + Vec3 c = k * p.color; + scratch.push_back({{p.position.x, p.position.y, p.position.z, p.size * (0.5f + 0.5f * k)}, {c.x, c.y, c.z, 1.0f}}); + } + instances.update(scratch.data(), static_cast(scratch.size() * sizeof(ParticleInstance))); + shader->use(); + glBindVertexArray(vao); + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE); // 加算 / additive + glDepthMask(GL_FALSE); // 光は後ろの物を隠さない / light does not hide what is behind it + glDisable(GL_CULL_FACE); + glDrawArraysInstanced(GL_TRIANGLES, 0, 6, static_cast(scratch.size())); + glDepthMask(GL_TRUE); + glDisable(GL_BLEND); + glEnable(GL_CULL_FACE); + glBindVertexArray(0); +} diff --git a/games/tps/src/effects.hh b/games/tps/src/effects.hh new file mode 100644 index 0000000..79e7106 --- /dev/null +++ b/games/tps/src/effects.hh @@ -0,0 +1,79 @@ +// 撃ったときの見た目(第38章):銃口の光(発光する形+点光源)、弾の軌跡(トレーサー)、火花(パーティクル)。 +// エンジンにはパーティクルの仕組みがないので、ゲームの中に小さく作る(後でエンジンへ移せる) +// What a shot looks like (chapter 38): the muzzle flash (an emissive shape + a point light), the bullet's trail (a +// tracer) and sparks (particles). The engine has no particle system, so a small one lives in the game (it could move +// into the engine later) +#pragma once + +#include "renderer.hh" + +#include "engine/buffer.hh" +#include "engine/lights.hh" +#include "engine/rng.hh" +#include "engine/shader.hh" + +#include +#include + +// aからbへの細い角材(立方体を伸ばす行列):トレーサーとデバッグの線 / a thin beam from a to b (a matrix stretching the +// unit cube): tracers and debug lines +Mat4 beamMatrix(Vec3 a, Vec3 b, float thickness); + +class Effects { +public: + Effects(); // GLのものを作る(コンテキストが必要) / creates the GL objects (needs the context) + ~Effects(); + Effects(const Effects &) = delete; + Effects &operator=(const Effects &) = delete; + bool ok() const { return shader.has_value(); } + + // 当たった所から法線の側へ火花を飛ばす / sparks flying from a hit point, towards the normal's side + void sparks(Vec3 at, Vec3 normal, Vec3 color, int count, Rng &rng); + // 銃口から当たった所までの光の筋 / a streak of light from the muzzle to the hit + void tracer(Vec3 from, Vec3 to, Vec3 color); + // 銃口の光(形と点光源) / the muzzle flash (shape and point light) + void muzzleFlash(Vec3 at, Vec3 direction); + + void update(float dt); + // 銃口の光を点光源として足す(最大4つ) / adds the muzzle flashes as point lights (4 at most) + void addLights(LightSet &lights) const; + // 不透明のパスの後:トレーサーと銃口の光(unlit、HDRの色でブルーム) / after the opaque pass: tracers and flashes + // (unlit, HDR colors → bloom) + void drawStreaks(const Renderer &r) const; + // 最後に:火花を加算合成で(深度テストあり、深度は書かない) / last: sparks with additive blending (depth test on, + // no depth writes) + void drawParticles(); + + int particleCount() const { return static_cast(particles.size()); } + +private: + struct Particle { + Vec3 position, velocity; + float life, maxLife, size; + Vec3 color; + }; + struct Streak { + Vec3 from, to; + float life, maxLife; + Vec3 color; + }; + struct Flash { + Vec3 position, direction; + float life; + }; + // GPUへ送る一つ分(location 4 = 位置と大きさ、5 = 色) / one instance for the GPU (location 4 = position + size, + // 5 = color) + struct ParticleInstance { + Vec4 positionSize; + Vec4 color; + }; + static constexpr int kMaxParticles = 1024; + + std::optional shader; + GLuint vao = 0; + Buffer instances; + std::vector particles; + std::vector streaks; + std::vector flashes; + std::vector scratch; +}; diff --git a/games/tps/src/enemy.cc b/games/tps/src/enemy.cc new file mode 100644 index 0000000..74fc884 --- /dev/null +++ b/games/tps/src/enemy.cc @@ -0,0 +1,222 @@ +#include "enemy.hh" + +#include "angles.hh" + +#include +#include + +constexpr float kPatrolSpeed = 1.8f; // m/s +constexpr float kChaseSpeed = 3.4f; // m/s +constexpr float kSightRange = 22.0f; // 気づく前に見える距離 / sight range before noticing anything +constexpr float kAlertRange = 32.0f; // 気づいた後(どの向きでも) / once alert (any direction) +constexpr float kViewCos = 0.42f; // 視野の半分の角度 65°のcos / cos of half the field of view (65°) +constexpr float kAttackRange = 15.0f; // これより近く、見えていれば撃つ / closer than this and visible: shoot +constexpr float kReaction = 0.55f; // 気づいてから撃ち始めるまで / from noticing to the first shot +constexpr float kGravity = 20.0f; + +const char *enemyStateName(EnemyState s) { + switch (s) { + case EnemyState::Patrol: return "patrol"; + case EnemyState::Alert: return "alert"; + case EnemyState::Chase: return "chase"; + case EnemyState::Attack: return "attack"; + case EnemyState::Search: return "search"; + case EnemyState::Dead: return "dead"; + } + return "?"; +} + +Enemy::Enemy(const EnemySpawn &spawn) : heading(spawn.yaw), prevHeading(spawn.yaw), patrol(spawn.patrol) { + body.position = prevPosition = lastSeen = spawn.position; + body.grounded = true; +} + +void Enemy::setState(EnemyState s) { + state = s; + stateTime = 0.0f; +} + +void Enemy::alert(Vec3 playerPosition, float damage) { + if (!alive()) return; + lastSeen = playerPosition; + if (damage > 0.0f) { + health -= damage; + flash = 0.12f; + if (health <= 0.0f) { + health = 0.0f; + setState(EnemyState::Dead); + body.velocity = {0.0f, 0.0f, 0.0f}; + return; + } + } + // 巡回中・探している途中なら、すぐにそちらを向く / patrolling or searching: turn that way at once + if (state == EnemyState::Patrol || state == EnemyState::Search) setState(EnemyState::Alert); +} + +void Enemy::face(Vec3 target, float dt, float rate) { + Vec3 d = target - body.position; + if (d.x * d.x + d.z * d.z < 1e-4f) return; + float want = std::atan2(d.x, -d.z); // headingForward(want) = d の向き / so that headingForward(want) points along d + heading = approachAngle(heading, want, approach(rate, dt)); +} + +bool Enemy::walkTo(Vec3 target, float speed, float dt) { + Vec3 d = target - body.position; + d.y = 0.0f; + float dist = length(d); + Vec3 want = dist > 0.4f ? (speed / dist) * d : Vec3{}; + // 引っかかったら(壁に当たって進めない)、少しの間だけ横へ回り込む。本物の経路探索(ナビメッシュ+A*)の代わりの + // 一番簡単なもの + // Stuck (blocked by a wall)? Side-step for a moment. The simplest stand-in for real path finding (a navigation mesh + // + A*) + float moved = length(Vec3{body.velocity.x, 0.0f, body.velocity.z}); + if (detour <= 0.0f && dist > 0.4f && body.hitWall && moved < 0.3f * speed) { + side = -side; + detourDir = side * normalize(Vec3{-d.z, 0.0f, d.x}); + detour = 0.7f; + } + if (detour > 0.0f) { + detour -= dt; + want = speed * detourDir; + } + float k = approach(8.0f, dt); + body.velocity.x += k * (want.x - body.velocity.x); + body.velocity.z += k * (want.z - body.velocity.z); + if (dist > 0.4f) face(target, dt); + return dist <= 0.5f; +} + +void Enemy::stop(float dt) { + float k = approach(10.0f, dt); + body.velocity.x -= k * body.velocity.x; + body.velocity.z -= k * body.velocity.z; +} + +bool Enemy::update(float dt, const EnemySenses &senses, Rng &rng, Vec3 &aim) { + prevPosition = body.position; + prevHeading = heading; + stateTime += dt; + flash = std::fmax(flash - dt, 0.0f); + fireCooldown -= dt; + if (state == EnemyState::Dead) { + deathTime += dt; + seesPlayer = false; + pose.walkAmount = 0.0f; + return false; + } + + // 1. 見る:距離・視野の角度・視線(目からプレイヤーの胸へのレイがレベルの箱に当たらないか) + // 1. look: distance, field-of-view angle, line of sight (does the ray from the eyes to the player's chest hit a box?) + Vec3 eye = body.position + Vec3{0.0f, 1.6f, 0.0f}; + Vec3 chest = senses.playerPosition + Vec3{0.0f, 1.3f, 0.0f}; + Vec3 to = chest - eye; + float dist = length(to); + bool alerted = state != EnemyState::Patrol; + bool inView = senses.playerAlive && dist > 0.01f && + (alerted ? dist < kAlertRange + : dist < kSightRange && dot(headingForward(heading), normalize(Vec3{to.x, 0.0f, to.z})) > kViewCos); + seesPlayer = inView && !raycast({eye, to / dist}, senses.solids, dist).has_value(); + if (seesPlayer) { + lastSeen = senses.playerPosition; + lostTime = 0.0f; + } else { + lostTime += dt; + } + + // 2. 状態機械 / 2. the state machine + bool fire = false; + switch (state) { + case EnemyState::Patrol: + if (seesPlayer) { + setState(EnemyState::Alert); + break; + } + // 巡回の点で1秒止まってから次へ / stop for a second at each patrol point, then go on + if (walkTo(patrol[static_cast(nextPoint)], kPatrolSpeed, dt)) { + stop(dt); + if (stateTime > 1.0f) { + nextPoint = (nextPoint + 1) % static_cast(patrol.size()); + stateTime = 0.0f; + } + } else { + stateTime = 0.0f; + } + break; + case EnemyState::Alert: // 気づいた:止まってそちらを向く(反応時間) / noticed: stop and turn (reaction time) + stop(dt); + face(lastSeen, dt, 8.0f); + if (stateTime > kReaction) setState(seesPlayer && dist < kAttackRange ? EnemyState::Attack : EnemyState::Chase); + break; + case EnemyState::Attack: + stop(dt); + face(lastSeen, dt, 8.0f); + if (!senses.playerAlive) { + setState(EnemyState::Search); + } else if (!seesPlayer && lostTime > 0.6f) { + setState(EnemyState::Chase); + } else if (dist > kAttackRange + 2.0f) { + setState(EnemyState::Chase); + } else if (seesPlayer && fireCooldown <= 0.0f) { + // 撃つのは正面を向いてから / fire only when facing the player + Vec3 f = headingForward(heading); + if (dot(f, normalize(Vec3{to.x, 0.0f, to.z})) > 0.97f) { + fire = true; + aim = chest; + fireCooldown = rng.range(0.55f, 0.95f); + } + } + break; + case EnemyState::Chase: + if (seesPlayer && dist < kAttackRange) { + setState(EnemyState::Attack); + break; + } + if (walkTo(lastSeen, kChaseSpeed, dt) || stateTime > 8.0f) setState(EnemyState::Search); + break; + case EnemyState::Search: // 見回して、3秒で巡回へ戻る / look around, back to patrolling after 3 s + stop(dt); + heading += 1.6f * dt; + if (seesPlayer) { + setState(EnemyState::Alert); + } else if (stateTime > 3.0f) { + // 一番近い巡回の点から / from the nearest patrol point + float best = 1e9f; + for (size_t i = 0; i < patrol.size(); ++i) { + float d = length(patrol[i] - body.position); + if (d < best) { + best = d; + nextPoint = static_cast(i); + } + } + setState(EnemyState::Patrol); + } + break; + case EnemyState::Dead: break; + } + + // 3. 体を動かす(プレイヤーと同じ重力・当たり判定・壁ずり・段差) / 3. move the body (the player's gravity, + // collision, wall sliding and steps) + body.velocity.y -= kGravity * dt; + body.move(dt, senses.solids); + + // 4. 姿勢:歩き、狙うときは銃をプレイヤーの胸へ / 4. pose: walking, and the gun towards the player's chest when + // aiming + updateLocomotion(pose, body.velocity, heading, body.grounded, dt, kPatrolSpeed, kChaseSpeed); + float pitch = 0.0f; + if (state == EnemyState::Attack || state == EnemyState::Alert) { + Vec3 d = lastSeen + Vec3{0.0f, 1.3f, 0.0f} - eye; + pitch = std::atan2(d.y, std::sqrt(d.x * d.x + d.z * d.z)); + } + pose.aimPitch += (pitch - pose.aimPitch) * approach(8.0f, dt); + return fire; +} + +Mat4 Enemy::matrix(float alpha) const { + Mat4 m = characterMatrix(lerp(prevPosition, body.position, alpha), approachAngle(prevHeading, heading, alpha)); + if (state != EnemyState::Dead) return m; + // 倒れる:足元を軸に後ろへ90°(0.6秒)、背中の厚みの分だけ持ち上げる + // Falling: 90° backwards about the feet (0.6 s), lifted by the thickness of the back + float t = std::clamp(deathTime / 0.6f, 0.0f, 1.0f); + float fall = t * t * (3.0f - 2.0f * t); + return m * translate({0.0f, 0.15f * fall, 0.0f}) * rotateX(-0.5f * PI * fall); +} diff --git a/games/tps/src/enemy.hh b/games/tps/src/enemy.hh new file mode 100644 index 0000000..8893257 --- /dev/null +++ b/games/tps/src/enemy.hh @@ -0,0 +1,76 @@ +// 敵(第38章):状態機械のAI。巡回 → 気づく → 追う / 撃つ → 見失ったら探す → 巡回へ戻る。撃たれると気づき、 +// 体力が0で倒れる。体はプレイヤーと同じCharacterBody、見た目は同じ骨組みのenemy.glb +// An enemy (chapter 38): a state-machine AI. Patrol → notice → chase / shoot → search when the player is lost → back to +// patrolling. Being shot alerts it; at 0 health it falls. The body is the same CharacterBody as the player's, the look +// is enemy.glb with the same skeleton +#pragma once + +#include "character.hh" +#include "character_body.hh" +#include "level.hh" + +#include "engine/rng.hh" + +#include + +enum class EnemyState { Patrol, Alert, Chase, Attack, Search, Dead }; +const char *enemyStateName(EnemyState s); + +// AIが世界について知ること(毎ステップ) / what the AI knows about the world (every step) +struct EnemySenses { + std::span solids; + Vec3 playerPosition; // 足元 / feet + bool playerAlive = true; +}; + +// 当たり判定の球(頭・胸・腰・脚):足元からの高さ、半径、ダメージの倍率 / hit spheres (head, chest, hips, legs): +// height above the feet, radius, damage multiplier +struct HitSphere { + float height, radius, damage; +}; +inline constexpr HitSphere kHitSpheres[] = {{1.62f, 0.17f, 2.5f}, {1.25f, 0.30f, 1.0f}, {0.88f, 0.25f, 1.0f}, + {0.45f, 0.24f, 0.7f}}; + +class Enemy { +public: + explicit Enemy(const EnemySpawn &spawn); + + // 1ステップ。撃ちたいときはtrueを返し、aimに狙う点(プレイヤーの胸)を入れる + // One step. Returns true when it wants to fire, with aim = the point it aims at (the player's chest) + bool update(float dt, const EnemySenses &senses, Rng &rng, Vec3 &aim); + // 撃たれた(damage)・銃声を聞いた(damage 0)。どちらもプレイヤーの居場所に気づく + // Shot (damage) or heard a shot (damage 0). Either way it learns where the player is + void alert(Vec3 playerPosition, float damage = 0.0f); + bool alive() const { return state != EnemyState::Dead; } + + // 描くとき:補間した行列(倒れる回転込み)と姿勢 / for drawing: the interpolated matrix (including the fall) and pose + Mat4 matrix(float alpha) const; + + CharacterBody body; + float heading = 0.0f, prevHeading = 0.0f; + Vec3 prevPosition; + CharacterPose pose; + EnemyState state = EnemyState::Patrol; + float health = 100.0f; + float flash = 0.0f; // 撃たれて光る残り時間 / time left of the hit flash + float stateTime = 0.0f; + Vec3 lastSeen; // 最後にプレイヤーを見た(聞いた)所 / where the player was last seen (heard) + bool seesPlayer = false; + std::vector patrol; + int nextPoint = 0; + +private: + void setState(EnemyState s); + // 目標へ歩く(水平の速度を決める)。着いたらtrue / walks towards a target (sets the horizontal velocity); true when + // arrived + bool walkTo(Vec3 target, float speed, float dt); + void stop(float dt); + void face(Vec3 target, float dt, float rate = 6.0f); + + float fireCooldown = 0.0f; + float lostTime = 0.0f; // 見失ってからの時間 / time since the player was last seen + float deathTime = 0.0f; + float detour = 0.0f; // 回り込みの残り時間 / time left of a side-step + Vec3 detourDir; + float side = 1.0f; // 回り込む向き(交互に) / which way to side-step (alternating) +}; diff --git a/games/tps/src/game.hh b/games/tps/src/game.hh index 0e57845..411c418 100644 --- a/games/tps/src/game.hh +++ b/games/tps/src/game.hh @@ -25,6 +25,8 @@ struct Game { Model &player; // player.glb(姿勢を書き込むので非const) / non-const: poses are written into it Model &rifle; const CharacterRig &playerRig; + Model &enemy; // enemy.glb:全部の敵がこれ一つを使う(第38章) / every enemy shares this one (chapter 38) + const CharacterRig &enemyRig; Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI Viewport uiViewport; int frame = 0; // 描いたフレームの数 / frames drawn so far diff --git a/games/tps/src/level.cc b/games/tps/src/level.cc index b402619..2f9aa61 100644 --- a/games/tps/src/level.cc +++ b/games/tps/src/level.cc @@ -119,6 +119,21 @@ std::optional Level::load(const std::string &path) { float yaw = 0.0f; if (!(in >> level.spawn.x >> level.spawn.y >> level.spawn.z >> yaw)) return fail("spawn x y z yaw"); level.spawnYaw = radians(yaw); + } else if (command == "enemy") { + // enemy x y z yaw x1 z1 x2 z2 ...:出発点と巡回の点(第38章) / start and patrol points (chapter 38) + EnemySpawn e; + float yaw = 0.0f; + if (!(in >> e.position.x >> e.position.y >> e.position.z >> yaw)) return fail("enemy x y z yaw [x z]..."); + e.yaw = radians(yaw); + std::vector xz; + float value = 0.0f; + while (in >> value) xz.push_back(value); + // 数でない物が残っている、または数が奇数(zのないx)なら書き間違い / something that is not a number, or an odd + // count (an x without its z), is a typo + if (!in.eof() || xz.size() % 2 != 0) return fail("巡回の点は x z の組 / patrol points are x z pairs"); + for (size_t i = 0; i < xz.size(); i += 2) e.patrol.push_back({xz[i], e.position.y, xz[i + 1]}); + if (e.patrol.empty()) e.patrol.push_back(e.position); // 立って見張る / stands guard + level.enemies.push_back(e); } else { return fail("知らない命令 / unknown command"); } @@ -159,8 +174,8 @@ std::optional Level::load(const std::string &path) { GL_DYNAMIC_STORAGE_BIT); type.model->setInstanceBuffer(type.instances, sizeof(InstanceData), kInstanceLayout); } - printf("%s: %zu piece types, %zu pieces, %zu collision boxes\n", path.c_str(), level.types.size(), - level.pieces.size(), level.solids.size()); + printf("%s: %zu piece types, %zu pieces, %zu collision boxes, %zu enemies\n", path.c_str(), level.types.size(), + level.pieces.size(), level.solids.size(), level.enemies.size()); return level; } diff --git a/games/tps/src/level.hh b/games/tps/src/level.hh index 7ad0112..ff9ec99 100644 --- a/games/tps/src/level.hh +++ b/games/tps/src/level.hh @@ -41,6 +41,13 @@ struct Piece { float sphereRadius = 0.0f; }; +// 敵の出発点と巡回の道(第38章) / an enemy's start and patrol route (chapter 38) +struct EnemySpawn { + Vec3 position; + float yaw = 0.0f; // ラジアン、0 = −Zを向く / radians, 0 = facing −Z + std::vector patrol; // 巡回の点(高さは出発点と同じ) / patrol points (at the start's height) +}; + // 描いた数(画面の数字とNOTES用) / how much was drawn (for the overlay and the notes) struct LevelDrawStats { int visible = 0, total = 0, drawCalls = 0; @@ -67,6 +74,7 @@ public: std::vector solids; // ワールドの当たり判定の箱 / world-space collision boxes Vec3 spawn; // プレイヤーの出発点 / the player's start float spawnYaw = 0.0f; // ラジアン、0 = −Zを向く / radians, 0 = facing −Z + std::vector enemies; // 第38章 / chapter 38 Aabb bounds; // 全部を囲む箱 / box around everything private: diff --git a/games/tps/src/main.cc b/games/tps/src/main.cc index ec6cd55..8d9bb4f 100644 --- a/games/tps/src/main.cc +++ b/games/tps/src/main.cc @@ -1,13 +1,16 @@ // 第36〜39章:三人称シューティング(TPS)。第36章:レベル、キャラクター、三人称カメラ。第37章:当たり判定、重力、 -// ジャンプ、壁ずり +// ジャンプ、壁ずり。第38章:射撃、敵、体力、当たったときの効果 // 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 37: collision, gravity, jumping, wall sliding. Chapter 38: shooting, enemies, health, hit effects // // 操作 / Controls: // WASD カメラの向きに対して移動 / move relative to the camera // マウス / mouse 見回す / look around // Shift 走る(前へ) / run (forwards) // Space ジャンプ / jump +// 左ボタン / LMB 撃つ(押し続けると連射) / fire (hold for automatic fire) +// 右ボタン / RMB 狙う(肩に寄って視野が狭まる) / aim (closer over the shoulder, narrower view) +// R 弾を込め直す / reload // Q 右肩 ⇔ 左肩 / right ⇔ left shoulder // B 当たり判定の箱・カプセル・ソケット・軌跡 / collision boxes, capsule, sockets, trail // F3 時間と描いた数 / timings and draw counts @@ -15,6 +18,7 @@ // C カメラだけ回す(キャラクターを前から見る) / turn only the camera (look at the character) // K カメラの当たり判定のオン・オフ / camera collision on / off // O 上から見下ろす(デバッグ) / view from above (debugging) +// F8 毎フレームの状態を標準出力へ(台本を作る用) / log the state every frame to stdout (for scripting) // L 壁ずり ⇔ 壁で止まる(比べる) / wall sliding ⇔ stopping at walls (to compare) // P 手続き的な姿勢のオン・オフ(読み込んだままの姿勢) / procedural pose on / off (the pose as loaded) // Tab カーソルのキャプチャ / cursor capture @@ -43,9 +47,11 @@ int main(int argc, char **argv) { std::optional level = Level::load(argc > 1 ? argv[1] : "games/tps/assets/levels/arena.level"); std::optional player = Model::load("games/tps/assets/models/player.glb"); std::optional rifle = Model::load("games/tps/assets/models/rifle.glb"); - if (!level || !player || !rifle) return 1; + std::optional enemy = Model::load("games/tps/assets/models/enemy.glb"); + if (!level || !player || !rifle || !enemy) return 1; std::optional playerRig = CharacterRig::find(*player); - if (!playerRig) return 1; + std::optional enemyRig = CharacterRig::find(*enemy); + if (!playerRig || !enemyRig) return 1; // HUDと文字(第25・26章の2Dの道具を3Dの絵の上に) / HUD and text (the chapter 25-26 2D toolkit over the 3D image) std::optional batch = SpriteBatch::create(); @@ -62,10 +68,14 @@ int main(int argc, char **argv) { input.bind("right", {InputBinding::key(GLFW_KEY_D), InputBinding::key(GLFW_KEY_RIGHT)}); input.bind("run", {InputBinding::key(GLFW_KEY_LEFT_SHIFT)}); input.bind("jump", {InputBinding::key(GLFW_KEY_SPACE)}); + 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)}); GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); Game game{.window = window, .input = input, .loop = loop, .renderer = *renderer, .batch = *batch, .ui = *ui, .level = *level, .player = *player, .rifle = *rifle, .playerRig = *playerRig, + .enemy = *enemy, .enemyRig = *enemyRig, .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}}; SceneManager scenes; diff --git a/games/tps/src/play_scene.cc b/games/tps/src/play_scene.cc index 838eb9f..0959b0b 100644 --- a/games/tps/src/play_scene.cc +++ b/games/tps/src/play_scene.cc @@ -1,20 +1,12 @@ #include "play_scene.hh" +#include "angles.hh" + #include #include #include #include -// 角度を −π〜π に / wraps an angle into −π..π -static float wrapAngle(float a) { - while (a > PI) a -= 2.0f * PI; - while (a < -PI) a += 2.0f * PI; - return a; -} -// 目標の角度へ短い方の向きで近づく / approaches a target angle the short way round -static float approachAngle(float current, float target, float k) { return current + wrapAngle(target - current) * k; } -static float approach(float rate, float dt) { return 1.0f - std::exp(-rate * dt); } - constexpr float kWalkSpeed = 3.2f; // m/s constexpr float kRunSpeed = 6.0f; // m/s(Shift) constexpr float kAcceleration = 12.0f; // 速度が目標に近づく割合(毎秒) / how fast the velocity approaches its target @@ -27,7 +19,29 @@ constexpr float kCoyoteTime = 0.1f; // 足場を離れてからまだ跳べ constexpr float kJumpBuffer = 0.1f; // 着地の少し前に押したジャンプを覚えておく時間 / a jump pressed just before // landing is remembered this long -PlayScene::PlayScene(Game &game) : g(game) {} +// 武器と体力(第38章) / weapon and health (chapter 38) +constexpr float kFireInterval = 0.11f; // 秒:60 Hzでは7ステップごと、毎秒約8.6発 / s: every 7 steps at 60 Hz, ≈ 8.6 rounds/s +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 +static Vec3 spreadDirection(Vec3 axis, float angle, Rng &rng) { + Vec3 u = normalize(cross(std::fabs(axis.y) > 0.99f ? Vec3{1, 0, 0} : Vec3{0, 1, 0}, axis)); + Vec3 v = cross(axis, u); + float r = std::tan(angle) * std::sqrt(rng.unit()); // 円の中で一様 / uniform inside the disc + float a = 2.0f * PI * rng.unit(); + return normalize(axis + (r * std::cos(a)) * u + (r * std::sin(a)) * v); +} + +static Vec3 origin(const Mat4 &m) { return {m.c[3].x, m.c[3].y, m.c[3].z}; } + +PlayScene::PlayScene(Game &game) : g(game) { + for (const EnemySpawn &spawn : g.level.enemies) enemies.emplace_back(spawn); +} Vec3 PlayScene::cameraPivot() const { // CameraPivotソケット(空のノード)のワールドの位置:モデル行列 × ノードの行列の原点 @@ -74,6 +88,7 @@ void PlayScene::update(float dt) { if (in.pressed(GLFW_KEY_F4)) culling = !culling; 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; // 1. 見回す(マウスの動きはフレームごと:最初のステップだけが使う) / 1. look around (mouse movement is per frame: // only the first step uses it) @@ -84,12 +99,13 @@ void PlayScene::update(float dt) { // 2. movement relative to the camera: the input (right, forward) times the camera's horizontal right and forward // vectors (not the world axes) Vec2 stick = {in.axis("left", "right"), in.axis("back", "forward")}; - if (inspect) stick = {0.0f, 0.0f}; // C:キャラクターの周りを見るだけ / C: only look around the character + if (inspect || !alive) stick = {0.0f, 0.0f}; // C:周りを見るだけ / C: only look around; dead: no input Vec3 wish = stick.x * camera.right() + stick.y * camera.flatForward(); float wishLength = length(wish); if (wishLength > 1.0f) wish = wish / wishLength; // 斜めでも同じ速さ / same speed diagonally - bool running = in.actionHeld("run") && stick.y > 0.0f; - Vec3 target = (running ? kRunSpeed : kWalkSpeed) * wish; + bool running = in.actionHeld("run") && stick.y > 0.0f && aimBlend < 0.5f; + // 狙っている間は歩くだけ / walk only while aiming + Vec3 target = (running ? kRunSpeed : kWalkSpeed * (1.0f - 0.35f * aimBlend)) * wish; // 水平の速度だけを目標へ(上下は重力とジャンプ)。空中ではゆっくり / only the horizontal velocity approaches the // target (vertical = gravity and jumps); slowly in the air Vec3 &v = body.velocity; @@ -102,7 +118,7 @@ void PlayScene::update(float dt) { // 3. gravity and jumping. Coyote time (just after leaving a ledge) and a jump buffer (just before landing) make sure // a press is never lost coyote = body.grounded ? kCoyoteTime : coyote - dt; - jumpBuffer = in.actionPressed("jump") ? kJumpBuffer : jumpBuffer - dt; + jumpBuffer = in.actionPressed("jump") && alive ? kJumpBuffer : jumpBuffer - dt; bool jumped = false; if (jumpBuffer > 0.0f && coyote > 0.0f) { v.y = kJumpSpeed; @@ -133,42 +149,220 @@ void PlayScene::update(float dt) { // 4. キャラクターはカメラの向きを向く(肩越しの撃ち合いの決まり)。脚は移動の向きへ // 4. the character faces where the camera looks (the over-the-shoulder shooter convention); the legs turn towards // the movement - if (!inspect) heading = approachAngle(heading, camera.yaw, approach(14.0f, dt)); - float speed = length(Vec3{velocity.x, 0.0f, velocity.z}); - float legTarget = 0.0f, direction = 1.0f; - if (speed > 0.2f) { - // 速度をキャラクターの座標へ:+Zが前、+Xが左(右手系で+Zを向くと+Xは左) / velocity in character space: +Z is - // forward, +X is LEFT (facing +Z in a right-handed system, +X is on the left) - Vec3 fwd = {std::sin(heading), 0.0f, -std::cos(heading)}, rgt = {std::cos(heading), 0.0f, std::sin(heading)}; - float mz = dot(velocity, fwd), mx = -dot(velocity, rgt); - legTarget = std::atan2(mx, mz); - if (std::fabs(legTarget) > radians(100.0f)) { // 後ろ歩き:脚は前を向いたまま逆に回す / walking backwards - legTarget = wrapAngle(legTarget - PI); - direction = -1.0f; - } - legTarget = std::clamp(legTarget, radians(-70.0f), radians(70.0f)); - } - pose.legYaw = approachAngle(pose.legYaw, legTarget, approach(10.0f, dt)); - // 歩きの周期は進んだ距離に比例:足が地面を滑らない / the walk cycle advances with distance: feet do not skate - float run = std::clamp((speed - kWalkSpeed) / (kRunSpeed - kWalkSpeed), 0.0f, 1.0f); - float cycleLength = 1.5f + 0.9f * run; // 1周期(2歩)のm / meters per cycle (two steps) - pose.walkPhase = std::fmod(pose.walkPhase + direction * 2.0f * PI * speed * dt / cycleLength, 2.0f * PI); - pose.walkAmount = std::clamp(speed / kWalkSpeed, 0.0f, 1.0f); - pose.stride = 1.0f + 0.5f * run; - if (!inspect) pose.aimPitch = camera.pitch; - // 空中の姿勢へなめらかに(着地で戻る) / blend into the airborne pose (and back on landing) - pose.air += ((body.grounded ? 0.0f : 1.0f) - pose.air) * approach(12.0f, dt); - if (!body.grounded) pose.walkAmount *= 1.0f - pose.air; + if (!inspect && alive) heading = approachAngle(heading, camera.yaw, approach(14.0f, dt)); + updateLocomotion(pose, velocity, heading, body.grounded, dt, kWalkSpeed, kRunSpeed); + if (!inspect && alive) pose.aimPitch = camera.pitch; // 5. カメラ:CameraPivotソケットを追う / 5. the camera follows the CameraPivot socket // (Kで当たり判定なしのカメラと比べられる) / (K compares with a camera that ignores the walls) + // 右ボタンで狙う:肩に寄り、視野を狭める(なめらかに) / right button aims: closer to the shoulder, narrower view + // (smoothly) + aimBlend += ((in.actionHeld("aim") && alive ? 1.0f : 0.0f) - aimBlend) * approach(12.0f, dt); + camera.distance = 3.6f - 1.2f * aimBlend; + camera.shoulderOffset = 0.7f + 0.15f * aimBlend; + camera.fovY = radians(55.0f - 13.0f * aimBlend); camera.update(cameraPivot(), cameraCollision ? std::span(g.level.solids) : std::span(), dt); + + // 6. 撃つ・込め直す(第38章) / 6. fire and reload (chapter 38) + fireTimer -= dt; + hitMarker -= dt; + if (reloadTime > 0.0f && (reloadTime -= dt) <= 0.0f) ammo = kMagazine; + if (alive && reloadTime <= 0.0f) { + if (in.actionPressed("reload") && ammo < kMagazine) reloadTime = kReloadTime; + else if (in.actionHeld("fire") && fireTimer <= 0.0f) { + if (ammo > 0) shoot(); + else reloadTime = kReloadTime; // 空なら自動で / automatically when empty + } + } + + // 7. 敵(状態機械のAI)と、敵の射撃 / 7. the enemies (state-machine AI) and their shots + EnemySenses senses{g.level.solids, position, alive}; + for (Enemy &e : enemies) { + Vec3 aim; + if (e.update(dt, senses, rng, aim)) enemyFire(e, aim); + } + 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) + 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(); + } +} + +std::optional PlayScene::hitEnemy(const Ray &ray, float maxT, int &index, float &multiplier) const { + std::optional best; + for (size_t i = 0; i < enemies.size(); ++i) { + const Enemy &e = enemies[i]; + if (!e.alive()) continue; + for (const HitSphere &h : kHitSpheres) { + std::optional hit = + raySphere(ray, e.body.position + Vec3{0.0f, h.height, 0.0f}, h.radius, best ? best->t : maxT); + if (hit && (!best || hit->t < best->t)) { + best = hit; + index = static_cast(i); + multiplier = h.damage; + } + } + } + return best; +} + +void PlayScene::shoot() { + fireTimer = kFireInterval; + --ammo; + ++shotsFired; + // 銃口はモデルのソケット:今の姿勢を書いてから求める / the muzzle is a socket of the model: apply the current pose, + // then ask for it + applyPose(g.player, g.rifle, g.playerRig, pose); + Mat4 w = weaponMatrix(g.player, g.playerRig, characterMatrix(position, heading)); + int muzzleNode = g.rifle.findNode("Muzzle"); + Vec3 muzzle = origin(w * g.rifle.nodeTransform(muzzleNode)); + Vec3 barrel = normalize(Vec3{w.c[2].x, w.c[2].y, w.c[2].z}); + + // 1. 画面の真ん中(照準)が指している所:カメラから前へのレイ。カメラと体の間の物に当たらないよう、 + // 体の深さから始める + // 1. what the screen center (the crosshair) points at: a ray forwards from the camera. It starts at the body's depth + // so that things between the camera and the character are not hit + Vec3 eye = camera.eye(), f = camera.forward(); + float t0 = std::fmax(dot(camera.shoulder() - eye, f), 0.0f); + Ray aimRay{eye + t0 * f, f}; + float range = 120.0f; + Vec3 target = aimRay.origin + range * f; + int index = -1; + float multiplier = 1.0f; + if (std::optional h = raycast(aimRay, g.level.solids, range)) target = aimRay.origin + h->t * f; + if (std::optional h = hitEnemy(aimRay, length(target - aimRay.origin), index, multiplier)) + target = aimRay.origin + h->t * f; + + // 2. 弾は銃口からその点へ(拡散を足して)。銃口が壁の向こうに突き出ていたら、その壁に当たる + // 2. the bullet flies from the muzzle to that point (plus spread). If the muzzle pokes through a wall, the bullet + // hits that wall + float moving = length(Vec3{body.velocity.x, 0.0f, body.velocity.z}) > 0.5f ? 1.0f : 0.0f; + float spread = radians(1.4f - 1.0f * aimBlend + 1.2f * moving); + // 照準の点が銃の後ろ側(カメラだけ大きく回したとき)なら銃身の向きへ:弾が体を通って後ろへ飛ばない + // If the aim point is behind the gun (the camera alone was turned far), use the barrel: no bullets flying backwards + // through the body + Vec3 toTarget = normalize(target - muzzle); + Vec3 dir = spreadDirection(dot(toTarget, barrel) > 0.5f ? toTarget : barrel, spread, rng); + Ray bullet{muzzle, dir}; + Vec3 pivot = cameraPivot(); + float toMuzzle = length(muzzle - pivot); + std::optional blocked = raycast({pivot, (muzzle - pivot) / toMuzzle}, g.level.solids, toMuzzle); + std::optional wall = blocked ? std::optional(RayHit{0.0f, blocked->normal, blocked->index}) + : raycast(bullet, g.level.solids, range); + Vec3 start = blocked ? pivot + blocked->t * (muzzle - pivot) / toMuzzle : muzzle; + index = -1; + std::optional enemyHit = + blocked ? std::nullopt : hitEnemy(bullet, wall ? wall->t : range, index, multiplier); + + effects.muzzleFlash(muzzle, barrel); + Vec3 end = start + range * dir; + if (enemyHit) { + end = muzzle + enemyHit->t * dir; + Enemy &e = enemies[static_cast(index)]; + bool wasAlive = e.alive(); + e.alert(position, kDamage * multiplier); + if (wasAlive && !e.alive()) ++kills; + ++shotsHit; + hitMarker = 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; + effects.sparks(end, wall->normal, {5.0f, 3.2f, 1.2f}, 10, rng); // 黄色い火花 / yellow sparks + } + effects.tracer(muzzle, end, {5.0f, 3.6f, 1.6f}); + // 銃声:近くの敵が気づく / the noise: enemies nearby notice + for (Enemy &e : enemies) + if (length(e.body.position - position) < kHearing) e.alert(position); +} + +void PlayScene::enemyFire(Enemy &e, Vec3 aim) { + applyPose(g.enemy, g.rifle, g.enemyRig, e.pose); + Mat4 w = weaponMatrix(g.enemy, g.enemyRig, e.matrix(1.0f)); + Vec3 muzzle = origin(w * g.rifle.nodeTransform(g.rifle.findNode("Muzzle"))); + // 敵の弾は外れやすく:動いているプレイヤーにはもっと / enemy shots spread more, even more against a moving player + float moving = length(Vec3{body.velocity.x, 0.0f, body.velocity.z}); + Vec3 dir = spreadDirection(normalize(aim - muzzle), radians(2.2f + 0.5f * moving), rng); + Ray bullet{muzzle, dir}; + float range = 60.0f; + std::optional wall = raycast(bullet, g.level.solids, range); + std::optional hit = alive ? rayCapsule(bullet, playerCapsule(), wall ? wall->t : range) : std::nullopt; + Vec3 end = muzzle + (hit ? hit->t : wall ? wall->t : range) * dir; + effects.muzzleFlash(muzzle, normalize(Vec3{w.c[2].x, w.c[2].y, w.c[2].z})); + effects.tracer(muzzle, end, {6.0f, 1.4f, 0.5f}); + if (hit) { + hurtPlayer(kEnemyDamage); + 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); + } +} + +void PlayScene::hurtPlayer(float damage) { + if (!alive) return; + health -= damage; + hurt = 0.35f; + sinceHurt = 0.0f; + if (health <= 0.0f) { + health = 0.0f; + alive = false; + deadTime = 0.0f; + ++deaths; + reloadTime = 0.0f; + } +} + +void PlayScene::separateCharacters() { + // 体どうしは水平に押し合う(円と円)。押した後の壁へのめり込みは次のステップのmoveが直す + // Bodies push each other apart horizontally (circle against circle); any wall penetration this causes is fixed by + // the next step's move + std::vector bodies = {&body}; + for (Enemy &e : enemies) + if (e.alive()) bodies.push_back(&e.body); + for (size_t i = 0; i < bodies.size(); ++i) + for (size_t j = i + 1; j < bodies.size(); ++j) { + Vec3 d = bodies[j]->position - bodies[i]->position; + d.y = 0.0f; + float dist = length(d), minDist = bodies[i]->radius + bodies[j]->radius; + if (dist >= minDist || dist < 1e-5f) continue; + Vec3 push = (0.5f * (minDist - dist) / dist) * d; + bodies[i]->position = bodies[i]->position - push; + bodies[j]->position = bodies[j]->position + push; + } + position = body.position; +} + +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, + 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, + e.body.position.z, e.health, e.seesPlayer ? " sees" : ""); + printf("\n"); } void PlayScene::drawCharacters(const Shader &shader, bool depthOnly, Vec3 eye) { // 前のステップと今のステップの間をdrawAlphaで補間(第26章) / interpolate between the last and the current step // with drawAlpha (chapter 26) Mat4 m = characterMatrix(lerp(prevPosition, position, drawAlpha), approachAngle(prevHeading, heading, drawAlpha)); + if (!alive) { // 倒れる(敵と同じ) / falling over (like the enemies) + float t = std::clamp(deadTime / 0.6f, 0.0f, 1.0f), fall = t * t * (3.0f - 2.0f * t); + m = m * translate({0.0f, 0.15f * fall, 0.0f}) * rotateX(-0.5f * PI * fall); + } if (posing) applyPose(g.player, g.rifle, g.playerRig, pose); else g.player.nodes = g.playerRig.rest; // P:読み込んだままの姿勢 / P: the pose as loaded Mat4 w = weaponMatrix(g.player, g.playerRig, m); @@ -181,6 +375,34 @@ void PlayScene::drawCharacters(const Shader &shader, bool depthOnly, Vec3 eye) { } } +void PlayScene::drawEnemies(const Shader &shader, bool depthOnly, Vec3 eye, const Frustum *frustum) { + // 一つのenemy.glbを全員で使う:描く直前にその敵の姿勢を書く / all enemies share one enemy.glb: write each one's pose + // right before drawing it + for (const Enemy &e : enemies) { + Mat4 m = e.matrix(drawAlpha); + // カリングの球:体の真ん中(足元から0.9 m)を姿勢の行列で動かすので、倒れて横になっても体を包む + // The culling sphere: the body's middle (0.9 m above the feet) goes through the pose's matrix, so it still + // encloses the body once it lies on the ground + Vec4 middle = m * Vec4{0.0f, 0.9f, 0.0f, 1.0f}; + if (frustum && !frustum->sphereVisible({middle.x, middle.y, middle.z}, 1.3f)) continue; + applyPose(g.enemy, g.rifle, g.enemyRig, e.pose); + Mat4 w = weaponMatrix(g.enemy, g.enemyRig, m); + if (depthOnly) { + g.enemy.drawDepth(shader, m, g.renderer.white); + g.rifle.drawDepth(shader, w, g.renderer.white); + continue; + } + // 撃たれた光:pbr.fragがベースカラーに掛けるuTint(phong.vert → vTint)を一瞬明るい赤に + // The hit flash: uTint (phong.vert → vTint, which pbr.frag multiplies into the base color) becomes a bright red + // for a moment + float f = e.flash / 0.12f; + shader.set("uTint", Vec3{1.0f + 7.0f * f, 1.0f + 1.5f * f, 1.0f + 1.0f * f}); + g.enemy.draw(shader, m, g.renderer.white, ModelPass::Opaque, eye, Shading::Pbr); + shader.set("uTint", Vec3{1.0f, 1.0f, 1.0f}); + g.rifle.draw(shader, w, g.renderer.white, ModelPass::Opaque, eye, Shading::Pbr); + } +} + void PlayScene::drawDebugBoxes() { // 当たり判定の箱を線で(unlit、HDRの色) / the collision boxes as lines (unlit, HDR color) const Shader &s = *g.renderer.unlit; @@ -223,6 +445,38 @@ void PlayScene::drawDebugBoxes() { marker(m * g.player.nodeTransform(rig.hand[1]), {2.0f, 2.0f, 0.0f}); int muzzle = g.rifle.findNode("Muzzle"); if (muzzle >= 0) marker(weaponMatrix(g.player, rig, m) * g.rifle.nodeTransform(muzzle), {3.0f, 0.1f, 0.1f}); + // 敵のAI:頭の上に状態の色(緑 巡回、黄 気づいた・探す、橙 追う、赤 撃つ)、巡回の点、見えているときは視線 + // The enemy AI: a state color above the head (green patrol, yellow alert / search, orange chase, red attack), + // the patrol points, and the line of sight while it sees the player + for (const Enemy &e : enemies) { + if (!e.alive()) continue; + Vec3 p = lerp(e.prevPosition, e.body.position, drawAlpha); + Vec3 c = e.state == EnemyState::Patrol ? Vec3{0.2f, 2.0f, 0.3f} + : e.state == EnemyState::Chase ? Vec3{3.0f, 0.25f, 0.02f} + : e.state == EnemyState::Attack ? Vec3{3.0f, 0.1f, 0.1f} + : Vec3{2.5f, 2.2f, 0.2f}; + s.set("uColor", c); + s.set("uModel", translate(p + Vec3{0.0f, 2.2f, 0.0f}) * scale({0.2f, 0.2f, 0.2f})); + g.renderer.cube.draw(); + // 当たり判定の球(ray–球):頭・胸・腰・脚 / the hit spheres (ray–sphere): head, chest, hips, legs + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); + s.set("uColor", Vec3{2.0f, 0.5f, 1.6f}); + for (const HitSphere &h : kHitSpheres) { + s.set("uModel", translate(p + Vec3{0.0f, h.height, 0.0f}) * scale({2.0f * h.radius, 2.0f * h.radius, 2.0f * h.radius})); + g.renderer.sphere.draw(); + } + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + s.set("uColor", Vec3{0.2f, 1.0f, 0.3f}); + for (Vec3 q : e.patrol) { + s.set("uModel", translate(q + Vec3{0.0f, 0.1f, 0.0f}) * scale({0.25f, 0.2f, 0.25f})); + g.renderer.cube.draw(); + } + if (e.seesPlayer) { + s.set("uColor", Vec3{3.0f, 0.3f, 0.2f}); + s.set("uModel", beamMatrix(p + Vec3{0.0f, 1.6f, 0.0f}, feet + Vec3{0.0f, 1.3f, 0.0f}, 0.03f)); + g.renderer.cube.draw(); + } + } glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); } @@ -249,7 +503,9 @@ void PlayScene::draw(float alpha) { LightSet lights; lights.ambient = {0.20f, 0.24f, 0.33f}; lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {2.6f, 2.45f, 2.2f}}; + effects.addLights(lights); // 銃口の光が周りを照らす / muzzle flashes light their surroundings r.beginFrame(view, lights); + if (logging) logState(); // カメラが体の中に入ったら(壁際で寄せられて)自分を描かない:頭や胴の内側が映る。肩へずらしているので、 // 距離が短いだけでは入らない:体の軸からの水平距離で決める @@ -264,6 +520,7 @@ void PlayScene::draw(float alpha) { if (r.beginShadows()) { shadowStats = g.level.drawShadows(*r.shadow, r.white, r.lightFrustum()); drawCharacters(*r.shadow, true, view.eye); + drawEnemies(*r.shadow, true, view.eye, &r.lightFrustum()); r.endShadows(); } // 2. 場面 / 2. the scene @@ -271,14 +528,20 @@ void PlayScene::draw(float alpha) { // 手前の物から:キャラクター → レベル(床は最後) / nearest first: the character → the level (floor last) r.pbr->use(); if (drawPlayer) drawCharacters(*r.pbr, false, view.eye); + drawEnemies(*r.pbr, false, view.eye, &r.viewFrustum()); r.pbrInstanced->use(); // F4:カリングなし(全部の部品をインスタンスのバッファへ)と比べる。平面(0, 0, 0, 1)なら全部が内側 // F4: compare with no culling (every piece goes into the instance buffers). Planes (0, 0, 0, 1) keep everything in Frustum everything; for (Vec4 &plane : everything.planes) plane = {0.0f, 0.0f, 0.0f, 1.0f}; levelStats = g.level.draw(*r.pbrInstanced, r.white, culling ? r.viewFrustum() : everything); - if (g.showBoxes) drawDebugBoxes(); + effects.drawStreaks(r); // トレーサーと銃口の光(HDRで明るい → ブルーム) / tracers and flashes (bright HDR → bloom) r.drawSky(); + // デバッグ表示は空の後:深度テストなしで描く印(頭の上の状態の立方体など)を空が上書きしない様に + // The debug view after the sky, so the sky does not paint over the markers drawn without the depth test (such as + // the state cubes above the heads) + if (g.showBoxes) drawDebugBoxes(); + effects.drawParticles(); // 火花:空の後、加算で / sparks: after the sky, additive r.endScene(); // 3. 後処理 → 画面 / 3. post-processing → the screen r.present(g.window.width(), g.window.height()); @@ -294,7 +557,8 @@ void PlayScene::drawUi(float /*alpha*/) { "CPU frame {:.1f} ms (wall clock) llvmpipe raster: shadow {:.1f} ms, scene {:.1f} ms, post {:.1f} ms\n" "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 {}", + "body: {} {}{}{} contacts {} y {:.2f} m velocity ({:.1f}, {:.1f}, {:.1f}) jumps {} wall slide {}\n" + "particles {} kills {} deaths {}", 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)" : "", @@ -302,12 +566,46 @@ 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)"); - batch.drawRect({0.0f, 0.0f, 1280.0f, 88.0f}, {0.0f, 0.0f, 0.0f, 0.45f}); + 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); } - g.ui.draw(batch, "WASD 移動 / move マウス / mouse: look Shift 走る / run Space 跳ぶ / jump Q 肩 / shoulder " - "B 箱 / boxes F3", + // 照準(第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); + } + 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) + 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) + 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 c140301..068e8a7 100644 --- a/games/tps/src/play_scene.hh +++ b/games/tps/src/play_scene.hh @@ -1,14 +1,20 @@ -// 遊ぶシーン(第36章):レベルの中をキャラクターで歩き回る。カメラの向きに対して動き、カメラは壁を避けて付いてくる -// The play scene (chapter 36): walk a character around the level. It moves relative to the camera, and the camera -// follows without entering walls +// 遊ぶシーン(第36〜38章):レベルの中をキャラクターで歩き回り(カメラに対する移動、壁を避けるカメラ、第36章)、 +// 跳び、壁をずり(第37章)、撃ち合う(第38章) +// The play scene (chapters 36-38): walk a character around the level (camera-relative movement, a camera that avoids +// walls, chapter 36), jump and slide along walls (chapter 37), and fight (chapter 38) #pragma once #include "character_body.hh" +#include "effects.hh" +#include "enemy.hh" #include "game.hh" #include "third_person_camera.hh" +#include "engine/rng.hh" #include "engine/scene.hh" +#include + class PlayScene : public Scene { public: explicit PlayScene(Game &game); @@ -22,8 +28,19 @@ private: // 見えるもの全部(影のパスと場面のパスで同じ物を描く) / everything visible (the shadow and the scene pass draw // the same things) void drawCharacters(const Shader &shader, bool depthOnly, Vec3 eye); + void drawEnemies(const Shader &shader, bool depthOnly, Vec3 eye, const Frustum *frustum); void drawDebugBoxes(); Vec3 cameraPivot() const; + // 射撃(第38章) / shooting (chapter 38) + void shoot(); + void enemyFire(Enemy &enemy, Vec3 aim); + // 一番近い敵の当たり(ray–球):敵の番号と、当たった球のダメージの倍率 / the nearest enemy hit (ray–sphere): the + // enemy's index and the hit sphere's damage multiplier + std::optional hitEnemy(const Ray &ray, float maxT, int &index, float &multiplier) const; + Capsule playerCapsule() const { return body.capsule(); } + void hurtPlayer(float damage); + void separateCharacters(); + void logState() const; Game &g; ThirdPersonCamera camera; @@ -48,5 +65,22 @@ private: bool overhead = false; // O:上からの視点 / view from above bool posing = true; // P:手続き的な姿勢 / procedural pose float drawAlpha = 1.0f; // drawの補間の割合 / draw's interpolation factor + bool logging = false; // F8 + + // 戦い(第38章) / combat (chapter 38) + std::vector enemies; + Effects effects; + Rng rng{38}; // 決まった種:同じ入力なら毎回同じ戦い / fixed seed: the same input gives the same fight + float health = 100.0f; + float hurt = 0.0f; // 撃たれた赤い光の残り / remaining red hurt flash + float sinceHurt = 10.0f; // 最後に撃たれてから(回復用) / time since the last hit (for regeneration) + bool alive = true; + float deadTime = 0.0f; + static constexpr int kMagazine = 24; + int ammo = kMagazine; + float fireTimer = 0.0f, reloadTime = 0.0f; + 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; LevelDrawStats levelStats, shadowStats; };