diff --git a/games/tps/CMakeLists.txt b/games/tps/CMakeLists.txt index 59b2053..5ba4f08 100644 --- a/games/tps/CMakeLists.txt +++ b/games/tps/CMakeLists.txt @@ -2,6 +2,7 @@ add_executable(tps src/main.cc src/collision3d.cc + src/character_body.cc src/frustum.cc src/level.cc src/renderer.cc diff --git a/games/tps/README.md b/games/tps/README.md index c4e4af1..fa0c91c 100644 --- a/games/tps/README.md +++ b/games/tps/README.md @@ -7,15 +7,18 @@ ./build/games/tps/tps games/tps/assets/levels/pieces.level # 部品を並べたレベル / every piece in a row ``` -## 操作 / Controls(第36章 / chapter 36) +## 操作 / Controls(第36・37章 / chapters 36-37) | キー / key | | |---|---| | WASD / ↑↓←→ | カメラの向きに対して移動 / move relative to the camera | | マウス / mouse | 見回す / look around | | Shift | 走る(前へ) / run (forwards) | +| Space | ジャンプ / jump | | Q | 右肩 ⇔ 左肩 / right ⇔ left shoulder | -| B | 当たり判定の箱とソケット / collision boxes and sockets | +| B | 当たり判定の箱・カプセル・軌跡・ソケット / collision boxes, capsule, trail, sockets | +| 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 | @@ -31,7 +34,8 @@ src/main.cc ウィンドウ、読み込み、ゲームループ src/game.hh シーンが共有するデータ / data the scenes share src/play_scene.* 遊ぶシーン / the play scene src/level.* レベルのファイル、インスタンシング、カリング / level file, instancing, culling -src/collision3d.* AABB、レイ、スフィアキャスト / AABBs, rays, sphere casts +src/collision3d.* AABB、レイ、スフィアキャスト、カプセルと箱 / AABBs, rays, sphere casts, capsule vs box +src/character_body.* 当たり判定・重力・壁ずり・段差 / collision, gravity, wall sliding, steps 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/src/character.cc b/games/tps/src/character.cc index 242a6db..ee04804 100644 --- a/games/tps/src/character.cc +++ b/games/tps/src/character.cc @@ -117,11 +117,16 @@ void applyPose(Model &model, const Model &weapon, const CharacterRig &rig, const // 脚:太ももを前後に振り、前へ出ていく脚の膝を曲げる(足を持ち上げる) / legs: swing the thighs back and forth and // bend the knee of the leg that swings forward (lifting the foot) float swing = 0.5f * pose.stride * w * std::sin(phase); + // 空中(第37章):左の太ももを前へ、右を後ろへ、両膝を曲げる。地面の姿勢とairで混ぜる + // Airborne (chapter 37): left thigh forward, right thigh back, both knees bent; mixed with the ground pose by `air` + const float airThigh[2] = {-0.55f, 0.25f}, airKnee[2] = {0.9f, 0.6f}; for (int s = 0; s < 2; ++s) { float sign = s == 0 ? 1.0f : -1.0f; // 左右は逆位相 / left and right are in opposite phase - node(rig.leg[s]).rotation = rest(rig.leg[s]).rotation * rotX(-sign * swing); + float thigh = -sign * swing * (1.0f - pose.air) + airThigh[s] * pose.air; + node(rig.leg[s]).rotation = rest(rig.leg[s]).rotation * rotX(thigh); float forwardSwing = std::fmax(0.0f, sign * std::cos(phase)); // この脚が前へ動いている / this leg moves forward - node(rig.knee[s]).rotation = rest(rig.knee[s]).rotation * rotX(w * pose.stride * (0.12f + 1.0f * forwardSwing)); + float knee = w * pose.stride * (0.12f + 1.0f * forwardSwing) * (1.0f - pose.air) + airKnee[s] * pose.air; + node(rig.knee[s]).rotation = rest(rig.knee[s]).rotation * rotX(knee); } // 上半身:腰の回転を打ち消して狙う向きを保つ。狙いの上下は背骨・頭・銃で分ける。走ると少し前かがみ diff --git a/games/tps/src/character.hh b/games/tps/src/character.hh index d262966..2c939b4 100644 --- a/games/tps/src/character.hh +++ b/games/tps/src/character.hh @@ -30,6 +30,8 @@ struct CharacterPose { float stride = 1.0f; // 足の振りの大きさ(走ると大きい) / leg swing size (bigger when running) float legYaw = 0.0f; // 腰から下を移動の向きへ回す(ラジアン) / turns the legs towards the movement (radians) float aimPitch = 0.0f; // 銃の上下(ラジアン、正 = 上) / the gun's pitch (radians, positive = up) + float air = 0.0f; // 0 = 地面、1 = 空中(脚を縮める、第37章) / 0 = on the ground, 1 = airborne (legs tucked, + // chapter 37) }; // ゲームの中の位置と向き → モデル行列。headingはカメラのyawと同じ決まり(0 = −Zを向く、正 = 右へ回る)で、 diff --git a/games/tps/src/character_body.cc b/games/tps/src/character_body.cc new file mode 100644 index 0000000..f886af3 --- /dev/null +++ b/games/tps/src/character_body.cc @@ -0,0 +1,108 @@ +#include "character_body.hh" + +#include +#include + +void CharacterBody::restore(const State &s) { + position = s.position; + velocity = s.velocity; + grounded = s.grounded; + hitWall = s.hitWall; + steppedUp = s.steppedUp; + contacts = s.contacts; +} + +bool CharacterBody::blockedAt(Vec3 feet, std::span solids) const { + return deepestContact({feet, radius, height}, solids).has_value(); +} + +void CharacterBody::resolve(std::span solids) { + // 一番深い接触から順に押し出す(角では2〜3枚に同時に当たる) / push out of the deepest contact first (in a corner + // it touches two or three boxes at once) + for (int iteration = 0; iteration < 4; ++iteration) { + std::optional c = deepestContact(capsule(), solids); + if (!c) break; + ++contacts; + if (stepping && c->normal.y <= groundNormalY && climb(solids[static_cast(c->index)])) continue; + position = position + (c->depth + 1e-4f) * c->normal; + bool ground = c->normal.y > groundNormalY; + if (ground) grounded = true; + else if (c->normal.y > -groundNormalY) hitWall = true; // 天井はどちらでもない / a ceiling is neither + float into = dot(velocity, c->normal); + if (into >= 0.0f) continue; // もう離れていく / already moving away + if (slide || ground) { + // 壁ずり:面に向かう成分だけを消す。残りは面に沿う速度 / wall slide: remove only the part towards the + // surface; what remains runs along it + velocity = velocity - into * c->normal; + } else { + // 比べる用:壁に当たったら水平に止まる(ゲームでは引っかかって動けなくなる) / for comparison: stop horizontally + // at a wall (in a game you get stuck on every corner) + velocity = {0.0f, std::fmin(velocity.y, 0.0f), 0.0f}; + } + } +} + +bool CharacterBody::climb(const Aabb &box) { + // 下の球が低い箱の角に当たった(箱の上面が足元からstepHeight以内で、下の球の中心より下):横に押し返す代わりに、 + // 球がその角に乗る高さまで真上に持ち上げる。近づくほど持ち上がるので、段差は小さな坂のように上れる + // The lower sphere touches the edge of a low box (its top within stepHeight of the feet and below the lower + // sphere's center): instead of pushing back sideways, lift straight up until the sphere rests on that edge. The + // closer it gets, the higher it is lifted, so a step is climbed like a small ramp + float rise = box.hi.y - position.y; + if (rise <= 0.0f || rise > stepHeight || box.hi.y > position.y + radius) return false; + Vec3 centre = position + Vec3{0.0f, radius, 0.0f}; + Vec3 q = closestPoint(box, centre); + Vec3 toEdge = {q.x - centre.x, 0.0f, q.z - centre.z}; + float flat = length(toEdge); + // 向かっている段だけ:離れていく段(下りるときの今の段)の角に乗せ直すと、体が角に引っかかって浮く + // Only a step we are moving towards: lifting the body back onto the edge of a step it is leaving (going down) + // would leave it hanging on that edge + if (flat >= radius || dot(toEdge, velocity) <= 0.0f) return false; + float lift = box.hi.y + std::sqrt(radius * radius - flat * flat) - centre.y + 1e-4f; + if (lift <= 0.0f || blockedAt(position + Vec3{0.0f, lift, 0.0f}, {&box, 1})) return false; + position.y += lift; + velocity.y = std::fmax(velocity.y, 0.0f); + grounded = steppedUp = true; + return true; +} + +void CharacterBody::advance(float dt, std::span solids) { + // 一度に半径の半分より進まない:速くても薄い箱をすり抜けない(トンネリング) / never move more than half the + // radius at once, so fast motion does not tunnel through thin boxes + float distance = length(velocity) * dt; + int pieces = std::max(1, static_cast(std::ceil(distance / (0.5f * radius)))); + float h = dt / static_cast(pieces); + for (int i = 0; i < pieces; ++i) { + position = position + h * velocity; + resolve(solids); + } +} + +void CharacterBody::move(float dt, std::span solids, bool canStep) { + bool wasGrounded = grounded; + grounded = hitWall = steppedUp = snappedDown = false; + contacts = 0; + stepping = canStep && wasGrounded; // 段差を上ってよいのは地面にいたときだけ / climb ledges only from the ground + advance(dt, solids); + + // 下りの段差に吸い付く:さっきまで地面にいて、跳んでいないなら、stepHeightまで下に地面を探す。一度に下ろすと + // 今の段の角に深くめり込み、角の斜めの法線で前へ押し出される(跳ねる、届かない)ので、5 cmずつ下ろして + // 地面に着いた所で止める + // Stick to the ground going down a step: if it was grounded a moment ago and did not jump, look for ground up to + // stepHeight below. Dropping it all at once would sink deep into the edge of the step it is leaving, and the edge's + // tilted normal would push it forward (a hop, or a miss), so lower it 5 cm at a time and stop on the first ground + if (canStep && wasGrounded && !grounded && velocity.y <= 0.0f) { + State before = save(); + const int pieces = 6; // 0.3 m / 6 = 5 cm + for (int i = 0; i < pieces && !grounded; ++i) { + position.y -= stepHeight / static_cast(pieces); + resolve(solids); + } + if (grounded) { + snappedDown = true; + velocity.y = 0.0f; + } else { + restore(before); + } + } +} diff --git a/games/tps/src/character_body.hh b/games/tps/src/character_body.hh new file mode 100644 index 0000000..2b3d715 --- /dev/null +++ b/games/tps/src/character_body.hh @@ -0,0 +1,59 @@ +// キャラクターの体(第37章):縦のカプセルを、レベルの箱にめり込まないように動かす。 +// ・速度で少しずつ進み(サブステップ)、めり込んだら一番深い接触の法線の向きに押し出す +// ・壁ずり:速度から壁に向かう成分を引く v' = v − (v·n) n (線型代数の第4章、射影) +// ・法線が上を向いた接触(n.y > 0.7)は地面:着地 +// ・段差(stepHeight以下)は上る:下の球が低い箱の角に当たったら、横ではなく真上に押し上げる +// ・地面にいたのに足元が消えたら(階段を下りる)stepHeightまで少しずつ下に吸い付ける +// A character's body (chapter 37): moves an upright capsule without letting it sink into the level's boxes. +// - advance by the velocity in small pieces (sub-steps); when it penetrates, push out along the deepest contact's +// normal +// - wall sliding: remove the part of the velocity that goes into the wall v' = v − (v·n) n (Linear Algebra +// chapter 4, projection) +// - a contact whose normal points up (n.y > 0.7) is ground: landed +// - small ledges (up to stepHeight) are climbed: when the lower sphere hits the edge of a low box, it is pushed up +// instead of sideways +// - if the ground vanishes under a grounded body (walking down stairs), it is snapped down, in small pieces, by up +// to stepHeight +#pragma once + +#include "collision3d.hh" + +#include + +class CharacterBody { +public: + Vec3 position; // 足元(カプセルの底) / the feet (the bottom of the capsule) + Vec3 velocity; // m/s。重力は呼ぶ側が足す / m/s. The caller adds gravity + float radius = 0.35f; + float height = 1.8f; + float stepHeight = 0.3f; // これ以下の段差は自動で上る / ledges up to this height are climbed automatically + float groundNormalY = 0.7f; // n.yがこれより大きい面は地面(約45°まで) / n.y above this = ground (up to ~45°) + bool slide = true; // false:壁に当たると止まる(比べるため、L) / false: stop at walls (to compare, L) + + // 最後のmoveの結果 / results of the last move + bool grounded = false; + bool hitWall = false; + bool steppedUp = false; + bool snappedDown = false; + int contacts = 0; // 押し出した回数 / how many times it was pushed out + + Capsule capsule() const { return {position, radius, height}; } + // 1ステップ動かす。canStep = 段差を上る・下りるか(空中ではfalseで良い) / one step. canStep = climb / snap + // ledges (may be false in the air) + void move(float dt, std::span solids, bool canStep = true); + // その位置に置いたらめり込むか / would the body penetrate something at this position? + bool blockedAt(Vec3 feet, std::span solids) const; + +private: + struct State { + Vec3 position, velocity; + bool grounded, hitWall, steppedUp; + int contacts; + }; + State save() const { return {position, velocity, grounded, hitWall, steppedUp, contacts}; } + void restore(const State &s); + void advance(float dt, std::span solids); // サブステップで進む / advance in sub-steps + void resolve(std::span solids); // めり込みを直す / fix penetrations + bool climb(const Aabb &box); // 段差に乗る / step onto a ledge + bool stepping = false; // このmoveで段差を上ってよいか / may climb in this move +}; diff --git a/games/tps/src/collision3d.cc b/games/tps/src/collision3d.cc index 95f9134..3982008 100644 --- a/games/tps/src/collision3d.cc +++ b/games/tps/src/collision3d.cc @@ -89,3 +89,45 @@ std::optional sphereCast(const Ray &ray, float radius, std::span sphereAabb(Vec3 centre, float radius, const Aabb &box) { + Vec3 q = closestPoint(box, centre); + Vec3 d = centre - q; + float dist2 = dot(d, d); + if (dist2 >= radius * radius) return std::nullopt; + if (dist2 > 1e-12f) { + float dist = std::sqrt(dist2); + return Contact{d / dist, radius - dist, -1}; + } + // 中心が箱の中:一番近い面から外へ / the center is inside the box: out through the nearest face + const float gaps[6] = {centre.x - box.lo.x, box.hi.x - centre.x, centre.y - box.lo.y, + box.hi.y - centre.y, centre.z - box.lo.z, box.hi.z - centre.z}; + const Vec3 normals[6] = {{-1, 0, 0}, {1, 0, 0}, {0, -1, 0}, {0, 1, 0}, {0, 0, -1}, {0, 0, 1}}; + int best = 0; + for (int i = 1; i < 6; ++i) + if (gaps[i] < gaps[best]) best = i; + return Contact{normals[best], gaps[best] + radius, -1}; +} + +std::optional capsuleAabb(const Capsule &capsule, const Aabb &box) { + float y = std::clamp(0.5f * (box.lo.y + box.hi.y), capsule.bottomY(), capsule.topY()); + return sphereAabb({capsule.base.x, y, capsule.base.z}, capsule.radius, box); +} + +std::optional deepestContact(const Capsule &capsule, std::span boxes) { + std::optional best; + Aabb reach = capsule.bounds(); + for (size_t i = 0; i < boxes.size(); ++i) { + if (!overlaps(reach, boxes[i])) continue; // 大まかな判定(ブロードフェーズ) / the coarse test (broad phase) + std::optional c = capsuleAabb(capsule, boxes[i]); + if (c && (!best || c->depth > best->depth)) { + best = c; + best->index = static_cast(i); + } + } + return best; +} diff --git a/games/tps/src/collision3d.hh b/games/tps/src/collision3d.hh index af2f463..fa7ad6b 100644 --- a/games/tps/src/collision3d.hh +++ b/games/tps/src/collision3d.hh @@ -1,6 +1,7 @@ -// 3Dの当たり判定(第36章):軸に平行な箱(AABB)と、レイ・球を飛ばすテスト。カメラが壁にめり込まないために使う -// 3D collision (chapter 36): axis-aligned boxes (AABBs) and ray / sphere casts. The camera uses them to stay out of -// the walls +// 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) #pragma once #include "engine/mathx.hh" @@ -49,3 +50,41 @@ std::optional raycast(const Ray &ray, std::span boxes, float // Casts a sphere of the given radius: a ray against the boxes grown by the radius (the real Minkowski sum has rounded // corners, so near corners this stops a little early, which is the safe side for a camera) std::optional sphereCast(const Ray &ray, float radius, std::span boxes, float maxT); + +// 箱の中で点pに一番近い点(各軸でクランプ) / the point of the box nearest to p (clamp per axis) +Vec3 closestPoint(const Aabb &box, Vec3 p); + +// めり込み:normalの向きにdepthだけ動かすと離れる(normalは箱から外向きの単位ベクトル) / a penetration: moving by depth +// along normal separates them (normal = unit vector pointing out of the box) +struct Contact { + Vec3 normal; + float depth = 0.0f; + int index = -1; +}; + +// 球と箱 / sphere against box +std::optional sphereAabb(Vec3 centre, float radius, const Aabb &box); + +// 縦に立ったカプセル(第37章のキャラクターの体):底の点base、半径radius、全体の高さheight(≥ 2·radius)。 +// 中心の線分は base + (0, radius, 0) から base + (0, height − radius, 0) まで +// An upright capsule (the characters' body, chapter 37): bottom point base, radius, total height (≥ 2·radius). Its +// core segment runs from base + (0, radius, 0) to base + (0, height − radius, 0) +struct Capsule { + Vec3 base; + float radius = 0.35f; + float height = 1.8f; + + float bottomY() const { return base.y + radius; } // 下の球の中心の高さ / height of the lower sphere's center + float topY() const { return base.y + height - radius; } // 上の球の中心の高さ / height of the upper sphere's center + Aabb bounds() const { + return {{base.x - radius, base.y, base.z - radius}, {base.x + radius, base.y + height, base.z + radius}}; + } +}; + +// カプセルと箱。線分が縦なので簡単:線分の中で箱に一番近い高さyを選べば(箱の高さの真ん中を線分の範囲に +// クランプ)、あとはその高さの球と箱の問題になる +// Capsule against box. The segment is vertical, which makes it easy: pick the height y on the segment nearest to the +// box (the box's middle height clamped to the segment), then it is a sphere at that height against the box +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); diff --git a/games/tps/src/main.cc b/games/tps/src/main.cc index 7292dc9..ec6cd55 100644 --- a/games/tps/src/main.cc +++ b/games/tps/src/main.cc @@ -1,16 +1,21 @@ -// 第36〜39章:三人称シューティング(TPS)。第36章:レベル、キャラクター、三人称カメラ -// Chapters 36-39: the third-person shooter (TPS). Chapter 36: the level, the character and the third-person camera +// 第36〜39章:三人称シューティング(TPS)。第36章:レベル、キャラクター、三人称カメラ。第37章:当たり判定、重力、 +// ジャンプ、壁ずり +// 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 // // 操作 / Controls: // WASD カメラの向きに対して移動 / move relative to the camera // マウス / mouse 見回す / look around // Shift 走る(前へ) / run (forwards) +// Space ジャンプ / jump // Q 右肩 ⇔ 左肩 / right ⇔ left shoulder -// B 当たり判定の箱 / collision boxes +// B 当たり判定の箱・カプセル・ソケット・軌跡 / collision boxes, capsule, sockets, trail // F3 時間と描いた数 / timings and draw counts // F4 視錐台カリングのオン・オフ / frustum culling on / off // C カメラだけ回す(キャラクターを前から見る) / turn only the camera (look at the character) // K カメラの当たり判定のオン・オフ / camera collision on / off +// O 上から見下ろす(デバッグ) / view from above (debugging) +// L 壁ずり ⇔ 壁で止まる(比べる) / wall sliding ⇔ stopping at walls (to compare) // P 手続き的な姿勢のオン・オフ(読み込んだままの姿勢) / procedural pose on / off (the pose as loaded) // Tab カーソルのキャプチャ / cursor capture // Esc 終了 / quit @@ -56,6 +61,7 @@ int main(int argc, char **argv) { input.bind("left", {InputBinding::key(GLFW_KEY_A), InputBinding::key(GLFW_KEY_LEFT)}); 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)}); GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); Game game{.window = window, .input = input, .loop = loop, .renderer = *renderer, .batch = *batch, .ui = *ui, diff --git a/games/tps/src/play_scene.cc b/games/tps/src/play_scene.cc index cffd807..838eb9f 100644 --- a/games/tps/src/play_scene.cc +++ b/games/tps/src/play_scene.cc @@ -18,6 +18,14 @@ 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 +constexpr float kAirControl = 2.5f; // 空中ではゆっくりしか向きを変えられない / in the air it steers only slowly +constexpr float kGravity = 20.0f; // m/s²(現実の約2倍:ゲームでは重めが気持ち良い) / m/s² (about twice the real + // value: games feel better heavier) +constexpr float kJumpSpeed = 7.0f; // m/s → 高さ1.17 m(60 Hzの固定ステップ。v²/2gなら1.23 m) / m/s → 1.17 m high + // with the 60 Hz fixed step (v²/2g would give 1.23 m) +constexpr float kCoyoteTime = 0.1f; // 足場を離れてからまだ跳べる時間 / time after leaving a ledge that still allows a jump +constexpr float kJumpBuffer = 0.1f; // 着地の少し前に押したジャンプを覚えておく時間 / a jump pressed just before + // landing is remembered this long PlayScene::PlayScene(Game &game) : g(game) {} @@ -30,7 +38,7 @@ Vec3 PlayScene::cameraPivot() const { } void PlayScene::enter() { - position = prevPosition = g.level.spawn; + body.position = position = prevPosition = g.level.spawn; heading = prevHeading = g.level.spawnYaw; camera.yaw = g.level.spawnYaw; camera.reset(cameraPivot(), g.level.solids); @@ -64,6 +72,8 @@ void PlayScene::update(float dt) { if (in.pressed(GLFW_KEY_K)) cameraCollision = !cameraCollision; if (in.pressed(GLFW_KEY_P)) posing = !posing; 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; // 1. 見回す(マウスの動きはフレームごと:最初のステップだけが使う) / 1. look around (mouse movement is per frame: // only the first step uses it) @@ -80,11 +90,48 @@ void PlayScene::update(float dt) { 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; - velocity = velocity + approach(kAcceleration, dt) * (target - velocity); - position = position + dt * velocity; // 第36章:まだ当たり判定なし / chapter 36: no collision yet + // 水平の速度だけを目標へ(上下は重力とジャンプ)。空中ではゆっくり / only the horizontal velocity approaches the + // target (vertical = gravity and jumps); slowly in the air + Vec3 &v = body.velocity; + float k = approach(body.grounded ? kAcceleration : kAirControl, dt); + v.x += k * (target.x - v.x); + v.z += k * (target.z - v.z); - // 3. キャラクターはカメラの向きを向く(肩越しの撃ち合いの決まり)。脚は移動の向きへ - // 3. the character faces where the camera looks (the over-the-shoulder shooter convention); the legs turn towards + // 3. 重力とジャンプ。コヨーテタイム(足場を離れた直後)とジャンプの先行入力(着地の直前)で、押したのに + // 跳べないことをなくす + // 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; + bool jumped = false; + if (jumpBuffer > 0.0f && coyote > 0.0f) { + v.y = kJumpSpeed; + jumpBuffer = coyote = 0.0f; + jumped = true; + ++jumps; + } + v.y -= kGravity * dt; + v.y = std::fmax(v.y, -30.0f); // 終端速度 / terminal velocity + body.move(dt, g.level.solids, !jumped); + if (body.position.y < -20.0f) { // 落ちたら出発点へ / fell out of the level: back to the start + // 補間もカメラも出発点から(下から飛んで来ない) / interpolation and camera restart there too (no swoop from below) + body.position = position = prevPosition = g.level.spawn; + v = {0.0f, 0.0f, 0.0f}; + camera.reset(cameraPivot(), g.level.solids); + prevEye = camera.eye(); + prevForward = camera.forward(); + } + position = body.position; + Vec3 velocity = body.velocity; // 実際に動いた速度(壁ずりの後) / the velocity after sliding + // 軌跡(B):0.05秒ごとに足元を覚える / the trail (B): remember the feet every 0.05 s + if (++trailTick % 3 == 0) { + trail[trailNext] = position; + trailNext = (trailNext + 1) % kTrail; + trailCount = std::min(trailCount + 1, kTrail); + } + + // 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}); @@ -109,8 +156,11 @@ void PlayScene::update(float dt) { 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; - // 4. カメラ:CameraPivotソケットを追う / 4. the camera follows the CameraPivot socket + // 5. カメラ:CameraPivotソケットを追う / 5. the camera follows the CameraPivot socket // (Kで当たり判定なしのカメラと比べられる) / (K compares with a camera that ignores the walls) camera.update(cameraPivot(), cameraCollision ? std::span(g.level.solids) : std::span(), dt); } @@ -142,7 +192,19 @@ void PlayScene::drawDebugBoxes() { s.set("uModel", translate(b.centre()) * scale(b.hi - b.lo)); g.renderer.cube.draw(); } + // プレイヤーのカプセル(伸ばした球で近似して線で) / the player's capsule (approximated by a stretched sphere, as lines) + Vec3 feet = lerp(prevPosition, position, drawAlpha); + s.set("uColor", body.grounded ? Vec3{1.5f, 1.5f, 0.2f} : Vec3{2.0f, 0.4f, 0.1f}); + s.set("uModel", translate(feet + Vec3{0.0f, 0.5f * body.height, 0.0f}) * + scale({2.0f * body.radius, body.height, 2.0f * body.radius})); + g.renderer.sphere.draw(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + // 足元の軌跡:壁ずりでは壁に沿って曲がる / the trail of the feet: with wall sliding it bends along the wall + s.set("uColor", body.slide ? Vec3{0.2f, 1.6f, 2.0f} : Vec3{2.0f, 0.3f, 0.3f}); + for (int i = 0; i < trailCount; ++i) { + s.set("uModel", translate(trail[i] + Vec3{0.0f, 0.06f, 0.0f}) * scale({0.12f, 0.12f, 0.12f})); + g.renderer.cube.draw(); + } // ソケット(空のノード)を小さな箱で、体に隠れないように深度テストなしで:CameraPivot 水色、Weapon 紫、 // 両手 黄色、Muzzle 赤 // The sockets (empty nodes) as small boxes, without the depth test so the body does not hide them: CameraPivot @@ -172,6 +234,13 @@ void PlayScene::draw(float alpha) { view.eye = lerp(prevEye, camera.eye(), alpha); view.forward = normalize(lerp(prevForward, camera.forward(), alpha)); view.fovY = camera.fovY; + if (overhead) { + // O:上から見下ろすデバッグ用のカメラ(遊ぶカメラはそのまま動き続ける) / O: a debug camera looking down from above + // (the gameplay camera keeps working underneath) + Vec3 target = lerp(prevPosition, position, alpha); + view.eye = target + Vec3{0.0f, 11.0f, 6.0f}; + view.forward = normalize(target - view.eye); + } view.aspect = static_cast(g.window.width()) / static_cast(g.window.height()); view.time = time; @@ -224,16 +293,21 @@ void PlayScene::drawUi(float /*alpha*/) { std::string lines = std::format( "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", + "camera distance {:.2f} m{}{} collision boxes {} culling {} scene fragments {:.2f} M\n" + "body: {} {}{}{} contacts {} y {:.2f} m velocity ({:.1f}, {:.1f}, {:.1f}) jumps {} wall slide {}", 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)" : "", cameraCollision ? "" : " (camera collision OFF)", g.level.solids.size(), culling ? "on" : "OFF (F4)", - static_cast(r.timings.sceneFragments) / 1e6); - batch.drawRect({0.0f, 0.0f, 1280.0f, 68.0f}, {0.0f, 0.0f, 0.0f, 0.45f}); + 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}); g.ui.draw(batch, lines, {10.0f, 6.0f}, small); } - g.ui.draw(batch, "WASD 移動 / move マウス / mouse: look Shift 走る / run Q 肩 / shoulder B 箱 / boxes F3", + g.ui.draw(batch, "WASD 移動 / move マウス / mouse: look Shift 走る / run Space 跳ぶ / jump Q 肩 / shoulder " + "B 箱 / boxes F3", {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 7c9e7d7..c140301 100644 --- a/games/tps/src/play_scene.hh +++ b/games/tps/src/play_scene.hh @@ -3,6 +3,7 @@ // follows without entering walls #pragma once +#include "character_body.hh" #include "game.hh" #include "third_person_camera.hh" @@ -28,9 +29,15 @@ private: ThirdPersonCamera camera; Vec3 prevEye, prevForward; // 前のステップのカメラ(補間用) / last step's camera (for interpolation) - // プレイヤー(第37章で当たり判定と重力が付く) / the player (chapter 37 adds collision and gravity) + // プレイヤー:体(カプセル、当たり判定、重力)と、描くための位置 / the player: the body (capsule, collision, + // gravity) and the positions drawing interpolates + CharacterBody body; Vec3 position, prevPosition; - Vec3 velocity; + float coyote = 0.0f, jumpBuffer = 0.0f; + int jumps = 0; + static constexpr int kTrail = 80; // 軌跡(B):4秒分 / the trail (B): 4 seconds + Vec3 trail[kTrail]; + int trailNext = 0, trailCount = 0, trailTick = 0; float heading = 0.0f, prevHeading = 0.0f; // カメラのyawと同じ決まり / same convention as the camera yaw CharacterPose pose; float time = 0.0f; @@ -38,6 +45,7 @@ private: // the character from the front) bool cameraCollision = true; // K:カメラの当たり判定 / camera collision bool culling = true; // F4:視錐台カリング / frustum culling + bool overhead = false; // O:上からの視点 / view from above bool posing = true; // P:手続き的な姿勢 / procedural pose float drawAlpha = 1.0f; // drawの補間の割合 / draw's interpolation factor LevelDrawStats levelStats, shadowStats; diff --git a/games/tps/src/renderer.cc b/games/tps/src/renderer.cc index 40f6244..dc2722b 100644 --- a/games/tps/src/renderer.cc +++ b/games/tps/src/renderer.cc @@ -69,6 +69,7 @@ std::unique_ptr Renderer::create(int width, int height, const RenderSe const unsigned char whitePixel[4] = {255, 255, 255, 255}; r->white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); r->cube = makeCube(); + r->sphere = makeSphere(16, 8); return r; } diff --git a/games/tps/src/renderer.hh b/games/tps/src/renderer.hh index 5adbb5e..8ffcc77 100644 --- a/games/tps/src/renderer.hh +++ b/games/tps/src/renderer.hh @@ -119,6 +119,7 @@ public: std::optional unlit; // 光らない一色(デバッグの箱) / unlit color (debug boxes) Texture2D white; Mesh cube; // 1 × 1 × 1、中心が原点 / centered unit cube + Mesh sphere; // 直径1、中心が原点 / diameter 1, centered RenderSettings settings; RenderTimings timings; // 数フレーム遅れの値 / values a few frames old