38. TPS パート3:射撃と敵
第37章で、兵士には体が出来ました。
レベルとぶつかり、壁をずり、階段を上り、跳ぶカプセルです。
でも、アリーナには誰もいませんし、ライフルは飾りでしかありません。
此の章で、此れをシューティングゲームにします。
プレイヤーはレイで撃ちます。
カメラからのレイが照準の指す物を見つけ、ライフルの銃口からの2本目のレイが、弾が本当に何に当たるかを決めます。
アリーナでは5人の敵が巡回し、目と耳で気づき、反応し、撃ち返し、追いかけ、見失うと探します。
全て小さな状態機械で動きます。
そして、撃った手応えも要ります。
隣の壁を照らす銃口の光、ブルームで光る明るいトレーサー、火花、当たった敵の赤い光、撃たれた時の画面の縁の赤です。
章の殆どはゲームのコードと幾何学です。
レベル・敵の球・プレイヤーのカプセルに対するレイの判定を数字で追い、円錐の中のでたらめな向きを作り、AIを書きます。
新しいOpenGLの部分は小さいですが便利な物です。
頂点バッファを全く使わずにインスタンスのビルボードを描き、加算合成で、深度を書かないパーティクルの描画です。
38.1 此の章で作る物
台の上の見張りへの2発目です。
銃口から見張りへのトレーサー、弾が当たった所の赤い火花、そして当たって光る見張りが見えます:
動画は台本通りの戦い全部で、11秒です。
台の上の見張り、階段を上って北の階段の前の見張り、東の通路を来る敵、弾の込め直し、西の角を回って来る敵、最後に北の遮蔽物の所の敵です。
台本と敵の乱数は決まっているので、全く同じ戦いが毎回再現されます(38.14):
第36・37章の操作は其の儘で、新しいのは4つです:
- 左ボタン:撃つ(押し続けると連射)
- 右ボタン:狙う(カメラが肩に寄り、視野が狭まり、拡散が小さくなり、歩きが遅くなる)
- R:弾を込め直す
- F8:毎フレームのゲームの状態を端末に出す(台本を書く為)
- Bは敵の状態、当たり判定の球、巡回の点、視線も見せる
今までの章と同じく、全てgames/tps/の中です:
src/collision3d.hh、src/collision3d.cc:第36章のrayAabbにraySphereとrayCapsuleが加わるsrc/enemy.hh、src/enemy.cc(新規):感覚と状態機械を持つEnemysrc/effects.hh、src/effects.cc(新規):銃口の光、トレーサー、火花shaders/particle.vert、shaders/particle.frag(新規):火花のビルボードsrc/angles.hh(新規):今までplay_scene.ccのstatic関数だった角度の小道具src/character.hh、src/character.cc:updateLocomotionをplay_scene.ccから移し、敵も同じコードで歩くsrc/level.hh、src/level.cc、assets/levels/arena.level:enemyの命令と5人の敵assets/models/enemy.glb(新規):プレイヤーと同じあたしのスクリプトで作る(完成したファイルは章のZIPとアセットのZIPのch38/に入っています)src/play_scene.hh、src/play_scene.cc:射撃、敵、体力、弾、効果、UIsrc/game.hh、src/main.cc:敵のモデルと、撃つ・狙う・込め直すのアクションCMakeLists.txt、README.md、assets/LICENSE.txt
新しい2つのソースはゲームのCMakeLists.txtに入ります:
# 第36〜39章:三人称シューティング(TPS) / Chapters 36-39: the third-person shooter (TPS)
add_executable(tps
src/main.cc
src/collision3d.cc
src/character_body.cc
src/frustum.cc
src/level.cc
src/renderer.cc
src/character.cc
src/third_person_camera.cc
src/enemy.cc
src/effects.cc
src/play_scene.cc)
38.2 レベルのファイルの5人の敵
敵はレベルの一部なので、他の物と同じくarena.levelに置きます。
新しい命令は、出発点、度で表したyaw(0で北、−Zを向く。spawnと同じ)、そして好きな数の巡回の点を取ります:
# 敵(第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
読み込みは4つの数を読み、行の終わりまでxとzの組を読みます。
数が奇数(zの無いx)だったり、数でない物があったりすると、ファイルの他の間違いと同じく、ファイル名と行を出して読み込みを止めます。
巡回の点の高さは出発点と同じなので、3人目の道は1.5 mの台の上になります。
巡回の点が無い敵は自分の位置を唯一の点として持つので、其の場で見張ります:
} 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<float> 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);
| 敵 | 出発点 | 向き | 巡回 | 場所 |
|---|---|---|---|---|
| 0 | (−14, 0, −13) | 南 | 南北に10 m | 西の通路 |
| 1 | (−6, 0, −14.5) | 東 | 東西に12 m | 北の通路 |
| 2 | (0, 1.5, −3) | 南 | 南北に6 m | 台の上、出発点の方を見ている |
| 3 | (13.5, 0, −9) | 南 | 南北に16 m | 東の通路 |
| 4 | (−6, 0, −8.5) | 東 | 東西に12 m | 北の階段の前 |
モデルはenemy.glbで、第36章のplayer.glbと同じ生成スクリプトで作ります。
暗い赤の鎧、赤く光るバイザー、とさかと肩の棘を持ちますが、ノードの名前は同じです。
動かす為の仕掛けは其れだけです。
CharacterRig::findは同じ関節を見つけ、applyPoseは同じ歩きの周期と狙いの角度を書き、腕は同じライフルへ同じ2ボーンIKで伸びます。
歩きの周期のコードはplay_scene.ccからcharacter.ccへupdateLocomotion(pose, velocity, heading, grounded, dt, walkSpeed, runSpeed)として移ったので、プレイヤーも敵も1つの関数を呼びます。
5人の敵にModelは1つです。
第36章で見た様に、モデルのnodesは其の姿勢です。
キャラクターは其々自分のCharacterPoseを持ち、描く直前に共有のモデルへ書き込みます。
従って5人の敵は、1つのパスにつき5回の姿勢の書き込みだけで、GPUのメモリは増えません。
撃つ為に敵の銃口の位置が要る時も同じです。
先に姿勢を書き、其れからソケットを尋ねます。
38.3 レイとレベル
此の章で「見る」物は全てレイを使います。
照準、弾、敵の視線です。
レイは始点と向きです:
GLSLの第14章のカメラのレイや、線型代数の第12章のピッキングのレイと同じ物です。
の長さが1なので(線型代数の第3章)、はレイに沿った距離(m)で、一番近い当たりを探す時に比べるのは此の値です。
レベルの当たり判定は軸に平行な箱(AABB)の並びで、カメラと体が既に使っている85個の箱です。
第36章はカメラのスフィアキャストの為にrayAabbをスラブ法で作り、数字で確かめました(36.10)。
軸ごとに、レイは其の軸の2枚の平面の間にのある区間だけいて、箱の中にいるのは3つの区間が重なる所、一番遅い入りから一番早い出までで、なら当たりです。
此処から同じ関数が射撃の中心になり、此の章が頼るのは其の3つの性質です:
- 法線がただで分かる。 一番遅い入りの軸が当たった面で、法線は其の軸に沿ってレイに逆らう向きです。火花を壁から正しい向きに飛ばすには、此の法線が要ります。
- 箱の中から始まるレイはで当たる(法線は0)。目が壁の中にある敵が壁の向こうを見る事はありません。
maxTが探す範囲を限る。raycastは85個の箱を全部試し、其れまでの一番近い当たりを新しい限度として渡すので、もっと近い当たりの後ろの箱は捨てられます。1ステップに数本のレイなら何でもありません(38.15)。
でも、敵は箱ではありません。
38.4 レイと球
敵は1人につき4つの当たり判定の球を持ち(38.7)、レイと球は2次方程式です。
GLSLの第14章が「について方程式を解く事も出来る」と言ってから、代わりにスフィアトレーシングを選んだ、其の方程式です。
式
中心、半径の球の上の点は、中心からの距離がの点です。
レイを入れて両辺を2乗し、中心からレイの始点へのベクトルをと書きます:
内積は線型代数の第4章の物です。
なので、、とするとになり、
です。
式より図の方が分かり易いです。
はレイに沿って中心に一番近い点までの距離(のへの射影)、は(はレイと中心の一番近い距離、ピタゴラス)、平方根はレイが球を切る弦の半分です。
が負なら、レイは中心からより遠くを通ります。
外れです。
小さい方の解が入る所です。
計算の例
、、、とします:
- 、
- (もう1つの解は出る所)
当たりの点はで、其処の法線は中心からの向きです。
全ての長さを10で割ると、ゲームの中の1発になります。
10 m先の半径0.3 mの胸の球の、中心の0.18 m横を通るレイは、 mで当たります。
コード
std::optional<RayHit> 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};
}
最初の判定は、意味の分かり易い早い打ち切りです。
は始点が球の外にある事、は中心がレイの始点より後ろにある事(への射影が負)を表すので、レイは球から遠ざかり、当たりません。
を0で止めるのは、rayAabbと同じく、球の中から始まるレイの為です。
2つの判定に共通の良い習慣は、向きを正規化しておく事です。
此の式はを前提にしています。
正規化していない向きなら一般のの形が要り、はもうmではありません。
レイとカプセル
敵の弾はプレイヤーに当たらなければなりません。
プレイヤーは既にカプセルです(第37章)。
半径0.35 m、高さ1.8 mで、中心の縦の線分は足元から0.35 m〜1.45 mです。
カプセルは両端に球の付いた円柱なので、rayCapsuleは3つの当たりの一番近い物を取ります:
std::optional<RayHit> rayCapsule(const Ray &ray, const Capsule &capsule, float maxT) {
std::optional<RayHit> best;
auto keep = [&](std::optional<RayHit> 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;
}
2つの球はraySphereです。
側面は円の問題です。
縦の円柱はyを気にしないので、yを捨ててレイのxzの部分と半径の円を交差させます。
式は球と同じですが、のxzの部分は単位ベクトルではないので、一般の形が出て来ます:、です。
当たりは、其の高さが2つの球の中心の間にある時だけ数えます。
其れより上や下は端の球の担当です。
真っ直ぐ縦のレイはで、側面には触れず、球に任せます。
第37章のcapsuleAabbと同じく、カプセルが決して傾かない事が仕掛けです。
38.5 弾は何処へ飛ぶ? 2本のレイ
三人称のゲームで撃つ素直なやり方は、2つの違う意味で間違っています。
プレイヤーは画面の真ん中の照準で狙い、其処はカメラが見ている所です。
でも、カメラはキャラクターの3.6 m後ろ、0.7 m右にあり(第36章の肩のずらし)、ライフルの銃口は体の軸の8 cm右でしかありません(Weaponソケットのxは−0.08 mで、+Xはキャラクターの左)。
従って、カメラの線と銃の線は横に約0.62 m離れています:
- 銃口からカメラのレイに沿って撃つと(aの赤い点線)、どの距離でも0.62 mずれた儘です。胸の球の半径は0.3 mなので、照準の真ん中で撃つと、照準の上にいる敵に当たりません。此れが視差で、銃の照準器が銃身の上にあるのと同じ効果です。
- カメラからカメラのレイに沿って撃つと、照準が見せる物に当たりますが、弾は銃ではなく目から出ます。bでは、カメラは壁の角の向こうが見え、銃は壁の後ろです。カメラからの弾は角を通り過ぎて敵に当たり、壁の後ろにある銃で遮蔽物越しに撃てる事になります。
本物の三人称シューティングは2本のレイを使います:
- カメラから照準を通るレイが狙う点、つまり狙った物を見つける。
- 弾は銃口から其の狙う点へ飛び、レベルと敵に対して調べるのは此の弾のレイ。
開けた所なら、2本とも同じ敵に届きます(a)。
角では2本目のレイが角に当たり、敵に当たる代わりに壁に火花が見えます(b)。
撃つには遮蔽物から出なければならず、其れが遮蔽物を公平にします。
狙いのレイ
PlayScene::shoot()の前半です:
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<RayHit> h = raycast(aimRay, g.level.solids, range)) target = aimRay.origin + h->t * f;
if (std::optional<RayHit> h = hitEnemy(aimRay, length(target - aimRay.origin), index, multiplier))
target = aimRay.origin + h->t * f;
銃口は、ライフルを描くのと同じ行列(キャラクターの行列、Weaponソケット、ライフルのノード)を通した、ライフルのMuzzleソケットから求めます。
腕と背骨が何処にあるかは姿勢が決めるので、先に姿勢を当てはめます。
姿勢を、要る時に何時でも共有のモデルへ書ける値にしておいた理由が、此処にもう1つあります。
銃身の向きは武器の行列の3列目、ライフルの+Z軸です。
線型代数の第11章で、此れを向きとして読む事を学びました。
狙いのレイは目からではなく、其処からt0だけ進んだ所、肩の深さから始まります。
第36章のカメラは、目を肩から今のカメラの距離だけ後ろに置くので、t0は丁度其の距離で、狙いのレイは肩から始まります。
カメラとキャラクターの間にある物を的にしてはいけません。
すぐ後ろに立つ敵や、K(カメラの当たり判定なし)の時にカメラが入っている壁です。
カメラの当たり判定がオンなら、スフィアキャストが其の区間からレベルの箱を既に追い出しているので、レベルについては始点が効く事は殆ど無いですが、敵には効きます。
狙いのレイは先にレベル、次にレベルの当たりの距離までの敵を調べ、一番近い当たりが狙う点です。
何にも当たらなければ、狙う点は120 m先です。
弾のレイ
// 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<RayHit> blocked = raycast({pivot, (muzzle - pivot) / toMuzzle}, g.level.solids, toMuzzle);
std::optional<RayHit> wall = blocked ? std::optional<RayHit>(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<RayHit> enemyHit =
blocked ? std::nullopt : hitEnemy(bullet, wall ? wall->t : range, index, multiplier);
壁の近くで弾を正しく振る舞わせる、特別な場合が2つあります:
- 銃身が壁から突き出ている。 壁に顔を向けて立つと、銃口(背骨の0.94 m前)が壁の向こう側に出る事があります。其処から出た弾は、壁の後ろの敵に当たってしまいます。其の為、体の軸の上の
CameraPivotソケットから銃口へもう1本レイを飛ばし、箱に当たったら、弾は其の箱の其の点に当たる事にします(blocked、t = 0)。 - 狙う点が銃の後ろにある。 C(第36章のカメラだけ回す視点)では、キャラクターが反対を狙った儘、前から見る事が出来ます。すると狙う点はライフルの後ろになり、トレーサーが体を通って後ろへ飛んでしまいます。狙う点への向きが銃身から60°より離れていたら(
dot < 0.5)、代わりに銃身の向きを使います。
其の後、弾のレイを狙いのレイと同じ様に、レベル、其れから壁までの生きている敵に対して調べます。
38.6 拡散:円錐の中のでたらめな向き
狙った所に丁度当たる銃はありません。
小さなでたらめの拡散は、遠くへの射撃を不正確にし、狙う事に報い、敵にとっては一番大事な難しさのつまみになります。
軸の周りの半角の円錐の中で、でたらめな向きが欲しく、中の全ての向きが同じ確率であるべきです。
軸に沿って距離1の所に円板を置くと、其の半径はで、円錐の中の全ての向きは円板の丁度1点を通ります。
従って、円板の中のでたらめな点を選び、其処を狙えば良いです。
其の点の為に、に垂直で互いにも垂直な2つの単位ベクトルとが要ります。
線型代数の第5章の外積で作れます(ワールドの上を手がかりに使い、軸が殆ど縦ならワールドのxを使う)。
でたらめな角度と、円板の中心からのでたらめな距離で、
です。
落とし穴はです。
[0, 1)で一様なでとするのが素直な選び方ですが、間違いです:
点の半分が半分の半径の内側に落ちますが、其の内側の円の面積は4分の1しかないので、真ん中は4倍混み過ぎです。
一様にするには、の内側に落ちる確率が面積に比例し、でなければなりません。
をについて解くと、直し方が出ます:
此れで、半分の半径の内側に入るのは4分の1になります(図では600個のうち151個)。
乱数は第26章の種38のRngから取るので、毎回同じ様に散らばります:
// 円錐の中のでたらめな向き(拡散):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);
}
厳密には、平らな円板の上で一様な点は、円錐の立体角の上で完全に一様ではありませんが、数度の円錐なら差は小さ過ぎて分かりません。
プレイヤーの拡散は腰だめで1.4°、狙っている間は0.4°、動いている間(0.5 m/sより速い)は1.2°足します。
敵は2.2°に、プレイヤーの速さ1 m/sごとに0.5°を足すので、多くのシューティングと同じく、走っているプレイヤーには当たり難くなります。
15 m先で、其の円錐はどの位の大きさでしょうか?
| 誰 | 半角 | 15 m先の半径 |
|---|---|---|
| プレイヤー、狙う | 0.4° | 0.10 m |
| プレイヤー、腰だめ | 1.4° | 0.37 m |
| プレイヤー、腰だめで動く | 2.6° | 0.68 m |
| 敵、プレイヤーが止まっている | 2.2° | 0.58 m |
| 敵、プレイヤーが歩く(3.2 m/s) | 3.8° | 1.00 m |
| 敵、プレイヤーが走る(6 m/s) | 5.2° | 1.37 m |
狙えば、15 m先の弾は全て、照準の周りの0.3 mの胸の球の中に入ります。
腰だめで動きながらだと、多くが外れます。
敵に対しては、開けた所で止まっているのは危険です。
プレイヤーのカプセルの幅は0.7 mなので、走っているプレイヤーには当たるより外れる方が多いです。
38.7 当たり判定の球、ダメージ、音
敵1人に4つの球
弾を敵の三角形と調べる事も出来ますが、其の必要はありません。
敵は其々、足元に対して決まった4つの球を持ちます:
// 当たり判定の球(頭・胸・腰・脚):足元からの高さ、半径、ダメージの倍率 / 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}};
球はアニメーションに付いて行きません。
歩きの周期は脚を振り、狙いの角度は背骨を曲げますが、球は其の儘です。
四角い兵士には其れで十分で、当たりは甘く、安くなります。
5人 × 4つの球 = 1本のレイにつきraySphereを20回です。
Bのキーで球をピンクの線で描くので、或る1発が当たったか当たらなかったかの理由を一番簡単に見られます。
hitEnemyは、生きている敵の一番近い球を見つけ、どの敵か、其の球のダメージの倍率を返します:
std::optional<RayHit> PlayScene::hitEnemy(const Ray &ray, float maxT, int &index, float &multiplier) const {
std::optional<RayHit> 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<RayHit> 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<int>(i);
multiplier = h.damage;
}
}
}
return best;
}
ダメージ
1発は34点 × 球の倍率で、敵の体力は100です:
- 胸か腰:34、3発で倒れる(2発なら残り32)
- 頭:34 × 2.5 = 85、2発で倒れ、頭と胸1発ずつ(119)でも倒れる
- 脚:34 × 0.7 = 23.8、5発要る(4発なら残り4.8)
よくあるシューティングの決まりです。
上を狙う程早く倒せます。
shoot()の残りは、当たりを当てはめ、効果を出し、音を立てます:
effects.muzzleFlash(muzzle, barrel);
Vec3 end = start + range * dir;
if (enemyHit) {
end = muzzle + enemyHit->t * dir;
Enemy &e = enemies[static_cast<size_t>(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);
}
alert(38.9)は3つの事を一度にします。
ダメージを引き、0.12秒の光を始め、敵にプレイヤーの居場所を教えます。
撃たれると、後ろからでも必ず撃った者が分かります。
視野の外から当てた敵は振り向きます。
音
最後の2行は敵の耳です。
プレイヤーから18 m以内の生きている敵は全て銃声を聞き、ダメージ無しの同じalertを受けます。
距離は壁を真っ直ぐ通して測り、音は大体そう伝わります。
此れが戦いを広げます。
1人の見張りへの最初の1発が、近くの他の敵を起こします。
台本の戦いでは、フレーム136に台の上から撃った最初の1発で、同じステップに3人の敵が気づきます。
38.8 敵が気づく物
敵の振る舞いは、其の知覚の良さで決まるので、其処から始めます。
数は全てenemy.ccの最初の定数です:
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;
毎ステップの最初、状態機械が動く前に、敵は見ます:
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;
}
3つの判定を、安い物から順に行います:
- 距離。 巡回中の敵は22 mまで見えます。何かで気づいた後は32 mで、32 × 32 mのアリーナの殆どに届きます。
- 視野。 巡回中は向きの±65°以内だけです。向きと、プレイヤーへの水平の向きの内積がより大きくなければなりません(又、線型代数の第4章)。気づいた敵は何処でも見ます。
- 視線。 敵の目(足元から1.6 m)からプレイヤーの胸(プレイヤーの足元から1.3 m)へのレイを、2人の間の距離までレベルの箱と調べます。プレイヤーより近くに当たった箱があれば、見えません。弾と同じ
raycastなので、敵が見えるなら撃つ事も出来、其の逆も同じです。
判定はわざとプレイヤーと対称です。
敵から隠してくれる遮蔽物は、自分の弾も止めます。
角から覗いても、自分が見られるのは銃も出ている時だけです(38.5の2本のレイの決まり)。
lastSeenは敵が最後にプレイヤーを見た、又は聞いた所を、lostTimeは其れがどの位前かを覚えます。
状態機械はプレイヤーの本当の位置ではなく、此の2つで動きます。
其の為に、敵はプレイヤーを見失います。
見えなくなったら、プレイヤーがいた所へ行きます。
38.9 状態機械
第30章の格闘家は状態機械でしたし、第32章のCPUの相手もそうでした。
敵も6つの状態を持つ状態機械です:
enum class EnemyState { Patrol, Alert, Chase, Attack, Search, Dead };
其々の状態が、此のステップで敵がどう動くか、何時切り替えるかを決めます。
巡回と気づくです:
// 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<size_t>(nextPoint)], kPatrolSpeed, dt)) {
stop(dt);
if (stateTime > 1.0f) {
nextPoint = (nextPoint + 1) % static_cast<int>(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;
巡回は1.8 m/sで巡回の点から点へ歩き、各点で1秒待ちます。
歩いている間はstateTimeを0に戻すので、此れが待ち時間を測ります。
気づくは公平さの為に一番大事な状態です。
敵は止まり、0.55秒プレイヤーの方を向いてからでないと、他の事が出来ません。
此の反応時間がゲームを遊べる物にします。
無ければ、敵は気づいた其のステップで撃ちます(課題2で其の感じが分かります)。
反応の後、15 m以内にプレイヤーが見えれば攻撃し、そうでなければ追います。
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<int>(i);
}
}
setState(EnemyState::Patrol);
}
break;
case EnemyState::Dead: break;
}
攻撃は立ち止まり、プレイヤーを向いて撃ちます。
「向いている」は14°以内(dot > 0.97、)の事で、振り向いたばかりの敵が横へ撃つ事はありません。
撃つ間隔はRngからの0.55〜0.95秒のでたらめなので、5人が揃って撃つ事はありません。
0.6秒見えないか、17 mより遠くなると追うへ切り替えます。
15 m(攻撃を始める)と17 m(攻撃をやめる)の間の2 mはヒステリシスです。
此れが無いと、丁度15 mの敵が毎ステップ2つの状態を行ったり来たりします。
追うは3.4 m/sでlastSeenへ走ります。
巡回より速く、プレイヤーが走る速さ(6 m/s)より遅いので、振り切る事が出来ます。
其処に着くか、8秒経つと探します。
其の場で1.6 rad/sで3秒回り(4.8 rad、約275°)、其れから今いる所に一番近い巡回の点から巡回に戻ります。
倒れたは何もしません。
描く為のmatrixが体を倒します(38.12)。
外から状態機械に入る道はalertで、当たりと音で呼ばれます:
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);
}
巡回と探すだけを気づくへ切り替えます。
既に攻撃している、追っている敵は、プレイヤーの新しい位置を知るだけです。
此の様に、1つのswitchと、タイマーを0に戻す1つのsetStateで切り替えをはっきり書くと、AIをデバッグし易く保てます。
Bは全ての敵の頭の上に色の付いた立方体を描き(緑が巡回、黄が気づく又は探す、橙が追う、赤が攻撃)、F8は毎フレーム全ての敵の状態を出します(38.14)。
38.10 経路探索無しで歩く
敵は第37章のプレイヤーのCharacterBodyで歩きます。
同じカプセル、重力、壁ずり、階段上りです。
AIは水平の速度を決めるだけで、其れをするのがwalkToです:
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;
}
速度は毎秒8の割合で欲しい速度に近づき(第36章から何処でも使っている指数的な近づき方)、敵は歩く方を向きます。
壁ずりで、浅い角なら既に回り込めます。
でも、壁に真正面から歩き込むと、ずる物が残りません。
速度の壁へ向かう成分が引かれ、何も残らないからです。
追うの最初の版は、そうして北の遮蔽物に永遠に引っかかっていました。
直し方は、経路探索の代わりとして一番簡単な物です。
体が壁に当たっていて、欲しい速さの30 %未満でしか動いていなければ、敵は目標に垂直な向きへ0.7秒横に避け(追う3.4 m/sなら最大2.4 m)、其れから又真っ直ぐ試します。
避ける向きは交互なので、間違った側を選んだ敵は次に反対を試します。
雑ですが、低い遮蔽物とL字の壁2つのアリーナなら十分に働きます。
でも、此れは経路探索ではありません。
台の向こう側にいる敵は、階段を使わず、台に歩き込んで台に沿って横に避けます。
本当の解決は、レベルの中で道を探す事です。
体が立てる所のグラフ(マスの格子、又は歩ける多角形のナビゲーションメッシュ)を作り、其の上でA*を走らせます。
A*は「此処までの距離+目標までの直線距離」の順にノードを広げ、マップ全体を探さずに一番短い道を見つけます。
課題6で格子版を作ります。
エンジンはレベルの形から作ったナビゲーションメッシュを使います(38.17)。
updateの最後の部分が体を動かし、姿勢を決めます:
// 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;
狙いの角度はプレイヤーの胸への上下の角度なので、攻撃している間、敵のライフルはプレイヤーを向きます。
背骨・頭・武器に分ける狙いの角度は、プレイヤーと同じです。
38.11 敵の弾とプレイヤーの体力
PlayScene::updateでは、敵はプレイヤーの移動、カメラ、射撃の後に動きます:
// 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);
敵が教えられるのはEnemySensesだけです。
レベルの箱、プレイヤーの足元、プレイヤーが生きているかです。
updateがtrueを返したら、敵は撃ちます:
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<RayHit> wall = raycast(bullet, g.level.solids, range);
std::optional<RayHit> 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);
}
}
プレイヤーの射撃の、弾の半分です。
敵自身の姿勢からの銃口(先に共有のenemy.glbへ書く)、プレイヤーの胸への向きの周りの拡散の円錐、其れからレベルとプレイヤーのカプセルへのrayCapsuleで、近い方が勝ちます。
1発ごとに8点なので、13発で倒れます(12発なら残り4)。
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;
}
}
残りはupdateの最後の部分です:
// 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();
}
体力は毎秒12点回復しますが、最後に撃たれてから4秒後からだけです。
従って、戦いの最中ではなく、戦いを離れて回復します。
台本の戦いが終わる時の52点からなら、4秒待って、48 / 12 = 4秒で回復します。
0になるとプレイヤーは敵と同じく倒れ、3秒後に出発点から戻ります。
prevPositionとカメラも其処でリセットするので、倒れた場所から補間されたりなめらかに追ったりする事はありません。
第39章で負けの画面になります。
体どうしも離れていなければなりません。
レベルとだけぶつかる2つのカプセルは、互いを素通りします。
separateCharactersは、生きている体の全ての組を、半径の和(0.7 m)より近い時に水平に半分ずつ押し離します。
壁へ押し込んでしまったら、次のステップのmoveが直します。
38.12 当たった時の効果
1発はレイと引き算です。
其れを撃った感じにするのは、0.1秒の光です。
エンジンにはパーティクルの仕組みが無いので、全て小さなEffectsクラスの中にあります:
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}); }
どの効果も短い寿命を持ち、updateが其れを減らし、0になったらstd::erase_ifで消します。
銃口の光と其の明かり
光はunlitシェーダーで、銃身に沿って伸ばした球と小さな丸い球として描き、色は0.05秒で消えて行くHDRの(16, 9, 3.5)です。
ブルームのしきい値1.0より明るい物は全て光るので(第21章)、光らせるには明るい形だけで十分です。
本物の銃口の光は周りも照らします。
パイプラインには既に、第19章のLightsユニフォームバッファの点光源があります:
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});
}
}
生きている光は其々、第12章の近距離用の減衰のオレンジの点光源になります。
は1 mで0.29、2 mで0.10なので、床と隣の壁はちらつき、アリーナの他の所はちらつきません。
足すのは最大4つ(ブロックには8つ分の場所がある)なので、5人の敵が一度に撃っても溢れません。
addLightsはdrawでフレームのLightSetを作る時に動くので、明かりは光があるフレームにだけあります。
トレーサー
トレーサーは銃口から当たりまでの細い筋で、0.06秒描きます。
単位立方体をbeamMatrixで線に沿って伸ばした物です。
此の行列の列は、太さ(2 cm)に拡大した垂直な2つの向き、長さに拡大した線の向き、そして中点です。
プレイヤーのトレーサーは暖かい白(5, 3.6, 1.6)、敵のはもっと赤い(6, 1.4, 0.5)なので、誰が撃っているか分かります。
どちらも1よりずっと明るく、ブルームで光ります。
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();
}
}
火花:頂点バッファの無いビルボード
火花は多く、小さく、すぐ消えます。
敵に当たると赤いのが14個、壁に当たると黄色いのが10個、敵の弾1発で8個です。
CPUで、面の法線の側(スラブ法からの法線、敵に当たった時は撃った者の方へ戻る向き)のでたらめな向き、2〜6.5 m/sの速さ、0.18〜0.45秒の寿命で作り、重力で落とします:
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)});
}
}
描く所で、新しいOpenGLが出て来ます。
火花は其々、常にカメラを向く小さな四角、ビルボードです。
火花1つに要るのは位置、半分の大きさ、色だけで、32バイト、vec42つです。
角は何処にも保存する必要がありません。
頂点シェーダーがgl_VertexIDから作れます。
第17章の全画面三角形の技です。
従って、VAOには頂点ごとのバッファが全く無く、インスタンスごとの属性だけです:
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<GLsizeiptr>(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);
}
}
glVertexArrayBindingDivisor(vao, bindingindex, divisor)は第19章のインスタンシングの関数ですが、此処では唯一のバインディング0に使います。
divisorが1なので、location 4と5の属性は頂点ごとではなく、インスタンスごとに1つ進みます。
VAOの中に頂点ごとに進む物は何も無く、其れで構いません。
但し、頂点シェーダーは頂点ごとの属性を読んではいけません。
location 4と5に意味は無く、此のVAOは他に何も使いません。
頂点シェーダーです:
#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);
}
インスタンス1つにつき6頂点、三角形2つで、角はgl_VertexID(各インスタンスの中で0〜5)で引く定数の配列から取ります。
四角をカメラに向けるには、ワールド座標でのカメラの右と上の向きが要ります。
其れはビュー行列に既にあります。
左上の3 × 3はワールドからビュー空間への回転なので、其の行がワールド座標で表したカメラの軸です(線型代数の第11章)。
GLSLの行列は列が先なので、行0はuView[0][0], uView[1][0], uView[2][0]です。
角は中心+c.x · right + c.y · upに半分の大きさを掛けた物で、其処からはいつもの投影です。
フラグメントシェーダーは四角を柔らかい点にします:
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);
}
dは角の単位で表した中心からの距離の2乗なので、内接円の外のフラグメントはdiscardし、内側の明るさはです。
真ん中で1、半分の半径で0.5625、縁で0になり、縁の線は見えません。
色はHDR(赤い火花で消える前に最大6 × 1.4 = 8.4)なので、火花もブルームで光ります。
第21章から場面のFBOに描く全てのプログラムと同じく、out_brightも書き、brightPartの為にPostブロックを宣言します。
Effectsはプログラムを読み込む時に、2つのブロックをcheckUniformBlockで確かめます。
最後に、描画です:
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<GLsizeiptr>(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<GLsizei>(scratch.size()));
glDepthMask(GL_TRUE);
glDisable(GL_BLEND);
glEnable(GL_CULL_FACE);
glBindVertexArray(0);
}
3つの状態がパーティクルを簡単にします:
- 加算合成、
glBlendFunc(GL_ONE, GL_ONE):結果は元+先です(第16章)。足し算は順番を気にしないので、第16章の透明な物と違い、火花は並べ替えが要りません。光としても物理的に正しく、重なった2つの火花は1つより明るくなります。フラグメントはアルファ0を書くので、先のアルファ(後処理は1の儘である事に頼る)は変わりません。 - 深度テストはオン、深度の書き込みはオフ、
glDepthMask(GL_FALSE)(第15章):手前の壁は其の後ろの火花を隠しますが、火花が他の火花や後で描く物を隠す事はありません。深度を書くと、柔らかい点の周りの黒い角(discardするのは円の外だけ)が、後ろの火花から四角を切り抜いてしまいます。 - カリングはオフ:ビルボードの巻き順は、こちらで決められない物で決まるので、効かない様にします。
glDrawArraysInstanced(mode, first, count, instancecount)は、第19章のglDrawElementsInstancedのインデックス無し版です。
firstからcount個の頂点をinstancecount回描きます。
此処では6頂点 × 火花の数を、1回の描画呼び出しで描きます。
よくある間違いは、glDepthMask(GL_TRUE)に戻し忘れる事(すると、第15章で注意した通り、次のフレームの深度バッファのglClearが黙って何もしなくなる)と、不透明な物の前にパーティクルを描く事(すると深度テストの相手がいない)です。
インスタンスのデータは毎フレーム、一度だけ確保した1024 × 32バイト = 32 KiBのバッファへglNamedBufferSubDataで送ります。
数百の火花で1フレームに数キロバイトで、どのGPUにも何でもありません。
フレームの中の順番
効果は場面のパスで此の順に描きます:
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();
トレーサーと銃口の光は不透明で、他の物と同じく深度を書きます。
火花はスカイボックスの後です。
空は深度バッファがまだ1の所に深度テスト付きで描くので、其の前に描いた加算の火花を上書きしてしまうからです。
Bのデバッグ表示も同じ理由で空の後に移しました。
其の印(ソケットと、敵の頭の上に浮かぶ状態の立方体)は深度テスト無しで描くので深度を書かず、後ろが空だけの印は全部空に塗り潰されてしまいます。
当たりの光と倒れる動き
当たった敵は0.12秒赤く光ります。
pbr.fragは既にベースカラーにvTintを掛け、phong.vertは其れをユニフォームuTint(第19章のインスタンスごとの色、既定値1)から取ります。
従って、光にシェーダーの変更は要らず、描画の前後のユニフォームだけです:
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);
}
}
一番強い時の色は(8, 2.5, 2)で、ベースカラーは明るい赤になり、1を超えるのでブルームで光ります。
ユニフォームは変えるまでプログラムに残るので、ライフルと次の描画の前に1に戻します。
バイザーの様な発光する部分は変わりません。
「ちゃんとした」光は発光に足す物で、ゲーム専用のpbr.fragのコピーが要ります。
倒れる動きはアニメーションではなく行列です:
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);
}
0.6秒の間、smoothstepで体を足元を軸に後ろへ90°回し、背中が床に沈まない様に最後に15 cm持ち上げます。
原点以外の点の周りの回転は、平行移動と回転を正しい順に掛けた物です(線型代数の第9章)。
モデルの原点は両足の間なので、モデル空間で回せば既に足元の周りで回ります。
drawEnemiesの視錐台カリング(第36章の外接球)も同じ行列を通します。
モデル空間で足元から0.9 m上の球の中心にmを掛けるので、体が床に横たわると球も一緒に横になります。
足元から0.9 m上に固定した中心は立った儘なので、足元から約1.8 m後ろへ行った頭は半径1.3 mの球の外に出てしまい、画面の端の死体は球が視野から出た時に頭を失います。
38.13 狙う、込め直す、照準
右ボタンで狙うカメラへ混ぜて行きます:
// 右ボタンで狙う:肩に寄り、視野を狭める(なめらかに) / 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<const Aabb>(g.level.solids) : std::span<const Aabb>(), dt);
aimBlendは毎秒12の割合で0か1に近づきます。
カメラの距離は3.6 mから2.4 mへ、肩のずらしは0.7 mから0.85 mへ、縦の視野は55°から42°へ変わります。
狙っている間は65 %の速さ(3.2の代わりに2.08 m/s)で歩き、走れず、拡散は1.4°から0.4°に下がります。
三人称シューティングの昔ながらの取り引きです。
動き易さと引き換えに正確さを得ます。
撃つのと込め直すのは、タイマー幾つかです:
// 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
}
}
撃つ間隔は0.11秒ですが、ゲームは1/60秒の固定のステップで動き(第26章)、タイマーは1ステップに1回確かめます。
6ステップは0.1秒で足りないので、1発は7ステップごと、0.117秒ごとになり、毎秒約8.6発です。
24発の弾倉は、ボタンを2.8秒押し続けると空になります。
込め直しは1.6秒掛かり、弾倉が空になると自動で始まり、倒れると取り消されます。
丁度毎秒9発にしたいなら、余った時間を持ち越します(=の代わりにfireTimer += kFireInterval)。
本物のゲームの速射の武器はそうしています。
其の時は、ボタンを離している間にタイマーが0よりずっと下まで減らない様にもして下さい(fireTimer = std::fmax(fireTimer - dt, -dt))。
其うしないと、休んだ後の最初の一押しで何発も一度に出てしまいます。
照準は後処理の後にSpriteBatchで描きます。
真ん中の点と4本の線で、線の隙間は拡散と一緒に大きくなり(狙うと5 px、腰だめで14 px、動くと8 px足す)、当てた後0.15秒は当たりの印として赤くなります。
撃たれると、画面の周りの赤い枠が0.35秒で消えて行きます。
状態の行は体力、弾、残りの敵、撃った数のうち当てた数を見せます。
第39章で、此れらをちゃんとしたHUDにします。
38.14 全く同じに再現される戦い
最初の動画は、誰かが遊んだ録画ではありません。
キー、マウスボタン、マウスの位置の台本からテスト用のハーネスが作った物で、動画の40フレームの塊ごとに、全てのフレームを最初から描き直しています(第26章)。
其れが出来るのは、戦いが決定的な時だけです。
同じ入力は、最後の火花まで同じゲームにならなければなりません。
其の為の3つの事:
- ゲームのロジックは固定のステップでだけ動き、壁時計は使わない(第26章)。
- 全ての乱数はシーンの1つの
Rng rng{38}から取る。拡散、火花、敵の撃つ間隔。std::random_deviceも時刻の種も、標準ライブラリによって違うstd::uniform_real_distributionも使わない。 - 敵は毎ステップ同じ順番(レベルのファイルの順)で更新するので、
rngから同じ順番で引く。
5人の動く敵に本当に当たる台本を書くのが難しい所です。
F8が助けます。
1フレームに1行、フレームの番号、プレイヤーの位置、カメラの目・yaw・pitch、体力、弾、全ての敵の状態・位置・体力、見えている間は「sees」を出します。
戦いのフレーム24と25で、台の上の見張り(3人目の敵)が3発目で倒れる所です:
log frame 24 pos (0.00 0.00 11.50) eye (0.969 1.423 13.851) yaw -0.0500 pitch 0.0529 hp 100 ammo 22 | patrol (-14.00 0.00 -13.00) 100 | patrol (-6.00 0.00 -14.50) 100 | attack (0.00 1.50 -3.00) 32 sees | patrol (13.50 0.00 -9.00) 100 | patrol (-6.00 0.00 -8.50) 100 |
log frame 25 pos (0.00 0.00 11.50) eye (0.969 1.423 13.851) yaw -0.0500 pitch 0.0529 hp 100 ammo 21 | patrol (-14.00 0.00 -13.00) 100 | patrol (-6.00 0.00 -14.50) 100 | dead (0.00 1.50 -3.00) 0 | patrol (13.50 0.00 -9.00) 100 | patrol (-6.00 0.00 -8.50) 100 |
台本のマウスの動きは此の行から調整しました。
的へのyawとpitchを計算し、感度(1ピクセル0.0025 rad)でピクセルに直し、走らせ、ログから残りのずれを読み、直します。
カメラが回ると目が動く(肩のずらしの分だけ注視点の周りを回る)ので、最初の見積もりは必ず数度ずれ、1つの的につき2回直しました。
出来上がった台本は、30 fpsの動画のフレーム25、143、171、240、295で敵を倒し、体力52で終わり、毎回そうなります。
ログから状態の変化を読むと、AIの働きが見えます。
台の上の見張りはフレーム1で既に気づいていて(出発点の方を向いている)、反応時間の後のフレーム17で攻撃に変わり、25で倒れます。
フレーム136の台の上からの最初の1発で、3人の敵が同じステップに音を聞いて気づきます。
Bのキーは同じ情報を絵で見せます:
38.15 動かす
今まで通りビルドし、プロジェクトのルートから./build/games/tps/tpsを実行して下さい(Visual Studioではtpsのターゲットを起動。作業ディレクトリは既にルートです)。
ウィンドウをクリックしてマウスを捕まえ、右ボタンを押した儘、台の上の見張りを撃って下さい。
音で他の敵が来ます。
Bを付けると、敵が気づくにつれて状態の立方体の色が変わるのが見えます。
AIとレイは安いです。
1ステップに、85個の箱に対する5本の視線のレイと、1発ごとに数本のレイで、マイクロ秒の単位です。
ハーネスのソフトウェアレンダラー(llvmpipe、2コアのVMの上のCPUのラスタライザーで、GPUではない)では、台本の戦いで1フレーム117〜128 msでした。
其のうち場面のパスが100〜110 ms、影のパスが約5.5 ms、後処理が10〜12 msで、場面のフラグメントは104万〜110万でした。
第37章の空のアリーナと同じ範囲で、5人のキャラクター、最大4つの点光源、数百の火花は誤差に紛れます。
デスクトップのGPUなら、フレーム全体で1〜2ミリ秒です。
38.16 プラットフォームの注意
- 全て: 38.14の決定性は、1つの機械の1つのビルドでの話です。コンパイラーや標準ライブラリが違うと、
std::sinやstd::expなどが最後のビットで違う事があり、ターゲットにFMA命令がある時(又はMSVCの/fp:fastの様なオプションで)、コンパイラーがa · b + cを融合積和に変える事もあります。Linuxで調整した台本が、Windowsでは多くのフレームの後にずれて行く事があります。リプレイやロックステップの通信を持つゲームは、入力を記録して状態のチェックサムを比べるか、固定小数点の計算でシミュレーションする事で、此れを避けます。 - Windows(Visual Studio): デバッグビルドは標準のコンテナが全てのアクセスを確かめるので、リリースよりずっと遅いです。振る舞いは変わらず、フレームの時間だけです。遊ぶならRelWithDebInfoの構成を使って下さい。
- Linux、FreeBSD: 特に無し。エンジンの
Windowは、カーソルを捕まえている間、プラットフォームが対応していればGLFWの生のマウスの動き(GLFW_RAW_MOUSE_MOTION)を既にオンにするので、デスクトップのマウスの加速が狙いを曲げる事はありません。X11ではXInput2の拡張が要りますが、今のXサーバーは全て持っています。
38.17 本物のゲームはどうしているか
- 当たり判定: 物理エンジン(PhysX、Jolt、Havok、Bullet)は、場面の全ての物に対するレイキャストと形のキャストを持ち、85個の箱のループではなく、バウンディングボリューム階層で速くしています。キャラクターはスケルトンの骨ごとに1つのカプセルか箱(「ヒットボックス」)を持ち、骨と一緒に動き、ダメージは骨で決まります。此の章の決まった4つの球は、スケルトン無しの其の考えです。
- 2本のレイ: カメラから照準へのレイと銃口のレイは、肩越しのシューティングの標準の解決です。弾の道を少し曲げて、銃口から出て照準に届く様にするゲームもあれば、銃口のレイが遮られていると照準に「遮られた」印を出すゲームもあります。後者は良い追加です(課題にもなります)。
- 弾: 此の章はヒットスキャン、一瞬のレイです。遅い武器(ロケット、矢、ゲームによってはスナイパーライフル)は弾体で、毎ステップ動き、其のステップで通った線分を調べ、重力や空気抵抗も付ける事が多いです。
- パーティクル: エンジンにはGPUのパーティクルの仕組み(UnrealのNiagara、UnityのVFX Graph)があり、コンピュートシェーダーでパーティクルを作り、シミュレーションし、並べ替え、スプライトシート、軌跡、衝突も扱います。描画の芯は此の章で書いた物です。インスタンスのビルボード、加算か乗算済みアルファの合成、深度を書かない事です。
- AI: 小さな敵には今でも状態機械がよく使われます。大きなゲームはビヘイビアツリー(Unreal)、ユーティリティAI(一番点の高い行動を選ぶ)、GOAP(行動の並びを計画する、F.E.A.R.で使われた)を使います。知覚は普通、視野の円錐、音の出来事、記憶を持つ別の仕組みで、
EnemySensesとlastSeenに良く似ています。 - 移動: Recast & Detour(Unity、Unreal、Godotで何らかの形で使われる)は、レベルの三角形からナビゲーションメッシュを作り、其の上でA*で道を探し、敵どうしがぶつからない様に操舵と群衆の回避も行います。此れが横に避けるやり方の代わりになります。
- 遮蔽物: 遮蔽物の仕組みは、障害物の後ろの位置をレベルのデータに印として付け、敵に安全さとプレイヤーへの視線で点を付けさせます(課題7)。
38.18 まとめ
- 2本のレイ: 照準を通るカメラからのレイを肩の深さから始めて狙う点を見つけ、弾は
Muzzleソケットから其の点へ飛び、もう一度調べる。カメラと銃は横に0.62 m離れているので、1本では足りない。銃口からカメラのレイに沿うと外れ(視差)、カメラからだと遮蔽物越しに撃てる。注視点から銃口へのレイで壁を突き抜けた銃身を捕まえ、銃の後ろの狙う点は銃身の向きに戻す。 - レイとレベル: 第36章のスラブ法(
rayAabb、raycast)が、一番近い当たりの、一番遅い入りのスラブからの面の法線(火花の為)、箱の中から始まるレイには(壁の向こうを見ない)をくれる。 - レイと球: 、、で。外にいて遠ざかるなら早い外れ。レイとカプセル = 2つの球 + xzの円、球の中心の間なら当たり。
- 拡散: 距離1の半径の円板のでたらめな点。一様にする為に、軸の周りに外積で作った垂直な2つのベクトル。プレイヤーは1.4° / 狙うと0.4° / 動くと+1.2°、敵は2.2° + プレイヤーの速さ1 m/sごとに0.5°。
- ダメージ: 敵1人に当たり判定の球4つ(頭2.5倍、胸、腰、脚0.7倍)、1発34。胸3発か頭2発で倒れる。撃つと当たった敵が気づき、18 m以内に聞こえる。
- 敵: レベルのファイルから5人(
enemy x y z yaw patrol…)、共有のenemy.glb1つに使う前に其々の姿勢を書く、移動はプレイヤーのCharacterBody。 - 感覚: 距離(22 m、気づいた後は32 m)、視野(巡回中は±65°)、目から胸への視線のレイ。本当の位置ではなく
lastSeenとlostTime。 - 状態機械: 巡回、気づく(0.55秒の反応)、攻撃(14°以内を向き、0.55〜0.95秒ごとに撃つ)、追う(3.4 m/sで最後に見た所へ)、探す(3秒回る)、倒れた。15 mと17 mの間のヒステリシス。引っかかった敵は経路探索の代わりに0.7秒横に避ける。本当の解決は格子かナビゲーションメッシュの上のA*。
- プレイヤー: 体力100、敵の1発で8、4秒後から毎秒12の回復、3秒後に戻る。狙うと視野と拡散が狭まり、遅くなる。24発、60 Hzのステップで毎秒約8.6発、込め直し1.6秒。
- 効果: 発光する銃口の光とLightsブロックの近距離の点光源、ブルームで光るHDRのトレーサー、CPUでシミュレーションし、頂点バッファ無しのインスタンスのビルボード(角は
gl_VertexIDから、カメラの軸はビュー行列の行から)で、加算合成・深度テストあり・深度の書き込みなしで描く火花、uTintによる当たりの光。 - 決定性: 固定のステップ、種を決めた1つの
Rng、決まった更新の順。F8で毎フレームの状態をログに出し、其れで台本の戦いを調整した。フレーム25、143、171、240、295で5人全員を倒し、全く同じに再現される。
38.19 課題
- ★
kHitSpheresの倍率を頭4倍、脚0.3倍に変えて下さい。頭への1発で倒れ(34 × 4 = 136)、脚への1発は10.2点になるので、脚なら10発要るはずです。 - ★
kReactionを0にして、出発点の開けた所に立って下さい。台の上の見張りは0.55秒後ではなく最初のステップで撃ち始め、台本の戦いの始めで、前は減らなかった体力が減るはずです(台本の残りも合わなくなります)。 - ★ 敵の拡散を0.5°にして下さい(
2.2f + 0.5f * movingを0.5fに)。走っても守られなくなり、赤いトレーサーが殆ど全て自分で終わるのが見えるはずです。 - ★★ 反動を足して下さい。1発ごとにカメラのpitchを0.6°、拡散を0.3°上げ、どちらも毎秒5の割合で戻します。長い連射は的より上に上がって散らばり、2〜3発の短い連射なら15 m先の胸に収まるはずです。
- ★★ 弾痕:レベルに当たるたびに当たった点と法線を覚え(リングで最後の64個)、其処に法線に揃えた小さな暗い四角を、z-fightingを避ける
glPolygonOffset(又は法線に沿って1 mmずらす)で描いて下さい。印は壁に残り、決してちらつかないはずです。 - ★★★ 経路探索:アリーナに0.5 mのマスの格子を作り、中心が体の半径(0.35 m)だけ大きくした当たり判定の箱の中にあるマスを塞ぎ、追い始めた時に敵のマスから
lastSeenのマスまでA*を走らせ、道の角に沿って歩かせて下さい。追う敵は、台とL字の壁に沿って横に避ける代わりに回り込むはずで、Bで道を描けます。 - ★★★ 遮蔽物:攻撃中に撃たれた敵に、プレイヤーから見て向こう側が隠れている一番近い遮蔽物(プレイヤーから其の点への視線のレイが遮蔽物に当たる)を選ばせ、其処へ歩き、1〜2秒待ってから出て撃たせて下さい。連射の合間に遮蔽物の後ろに隠れる敵との戦いになるはずです。
ファイル: a/games/tps/CMakeLists.txt | b/games/tps/CMakeLists.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -8,6 +8,8 @@ add_executable(tps | |||
| 8 | src/renderer.cc | 8 | src/renderer.cc |
| 9 | src/character.cc | 9 | src/character.cc |
| 10 | src/third_person_camera.cc | 10 | src/third_person_camera.cc |
| 11 | src/enemy.cc | ||
| 12 | src/effects.cc | ||
| 11 | src/play_scene.cc) | 13 | src/play_scene.cc) |
| 12 | target_include_directories(tps PRIVATE src) | 14 | target_include_directories(tps PRIVATE src) |
| 13 | target_link_libraries(tps PRIVATE engine) | 15 | target_link_libraries(tps PRIVATE engine) |
ファイル: a/games/tps/README.md | b/games/tps/README.md
| 前 | 新 | ||
|---|---|---|---|
| @@ -7,7 +7,7 @@ | |||
| 7 | ./build/games/tps/tps games/tps/assets/levels/pieces.level # 部品を並べたレベル / every piece in a row | 7 | ./build/games/tps/tps games/tps/assets/levels/pieces.level # 部品を並べたレベル / every piece in a row |
| 8 | ``` | 8 | ``` |
| 9 | 9 | ||
| 10 | ## 操作 / Controls(第36・37章 / chapters 36-37) | 10 | ## 操作 / Controls(第36〜38章 / chapters 36-38) |
| 11 | 11 | ||
| 12 | | キー / key | | | 12 | | キー / key | | |
| 13 | |---|---| | 13 | |---|---| |
| @@ -15,14 +15,18 @@ | |||
| 15 | | マウス / mouse | 見回す / look around | | 15 | | マウス / mouse | 見回す / look around | |
| 16 | | Shift | 走る(前へ) / run (forwards) | | 16 | | Shift | 走る(前へ) / run (forwards) | |
| 17 | | Space | ジャンプ / jump | | 17 | | Space | ジャンプ / jump | |
| 18 | | 左ボタン / LMB | 撃つ(押し続けると連射) / fire (hold for automatic fire) | | ||
| 19 | | 右ボタン / RMB | 狙う(肩に寄る、拡散が小さい) / aim (closer, less spread) | | ||
| 20 | | R | 弾を込め直す / reload | | ||
| 18 | | Q | 右肩 ⇔ 左肩 / right ⇔ left shoulder | | 21 | | Q | 右肩 ⇔ 左肩 / right ⇔ left shoulder | |
| 19 | | B | 当たり判定の箱・カプセル・軌跡・ソケット / collision boxes, capsule, trail, sockets | | 22 | | B | 当たり判定の箱・カプセル・軌跡・ソケット・敵のAI / collision boxes, capsule, trail, sockets, enemy AI | |
| 20 | | O | 上から見下ろす(デバッグ) / view from above (debugging) | | 23 | | O | 上から見下ろす(デバッグ) / view from above (debugging) | |
| 21 | | L | 壁ずり ⇔ 壁で止まる / wall sliding ⇔ stopping at walls | | 24 | | L | 壁ずり ⇔ 壁で止まる / wall sliding ⇔ stopping at walls | |
| 22 | | C | カメラだけ回す(キャラクターを前から見る) / turn only the camera (look at the character) | | 25 | | C | カメラだけ回す(キャラクターを前から見る) / turn only the camera (look at the character) | |
| 23 | | K | カメラの当たり判定のオン・オフ / camera collision on / off | | 26 | | K | カメラの当たり判定のオン・オフ / camera collision on / off | |
| 24 | | P | 手続き的な姿勢のオン・オフ / procedural pose on / off | | 27 | | P | 手続き的な姿勢のオン・オフ / procedural pose on / off | |
| 25 | | F3 | 時間と描いた数 / timings and draw counts | | 28 | | F3 | 時間と描いた数 / timings and draw counts | |
| 29 | | F8 | 毎フレームの状態を標準出力へ(台本作り用) / log the state every frame to stdout (for scripting) | | ||
| 26 | | F4 | 視錐台カリングのオン・オフ / frustum culling on / off | | 30 | | F4 | 視錐台カリングのオン・オフ / frustum culling on / off | |
| 27 | | Tab | カーソルのキャプチャ / cursor capture | | 31 | | Tab | カーソルのキャプチャ / cursor capture | |
| 28 | | Esc | 終了 / quit | | 32 | | Esc | 終了 / quit | |
| @@ -36,6 +40,10 @@ src/play_scene.* 遊ぶシーン / the play scene | |||
| 36 | src/level.* レベルのファイル、インスタンシング、カリング / level file, instancing, culling | 40 | src/level.* レベルのファイル、インスタンシング、カリング / level file, instancing, culling |
| 37 | src/collision3d.* AABB、レイ、スフィアキャスト、カプセルと箱 / AABBs, rays, sphere casts, capsule vs box | 41 | src/collision3d.* AABB、レイ、スフィアキャスト、カプセルと箱 / AABBs, rays, sphere casts, capsule vs box |
| 38 | src/character_body.* 当たり判定・重力・壁ずり・段差 / collision, gravity, wall sliding, steps | 42 | src/character_body.* 当たり判定・重力・壁ずり・段差 / collision, gravity, wall sliding, steps |
| 43 | src/enemy.* 敵の状態機械のAI / the enemies' state-machine AI | ||
| 44 | src/effects.* 銃口の光・トレーサー・火花 / muzzle flash, tracers, sparks | ||
| 45 | src/angles.hh 角度の小道具 / angle helpers | ||
| 46 | shaders/particle.vert/.frag 火花のビルボード / spark billboards | ||
| 39 | src/frustum.* 視錐台の平面 / frustum planes | 47 | src/frustum.* 視錐台の平面 / frustum planes |
| 40 | src/renderer.* 影 → 場面(PBR + IBL) → 後処理 / shadows → scene (PBR + IBL) → post | 48 | src/renderer.* 影 → 場面(PBR + IBL) → 後処理 / shadows → scene (PBR + IBL) → post |
| 41 | src/character.* 関節の姿勢と腕のIK / joint poses and arm IK | 49 | src/character.* 関節の姿勢と腕のIK / joint poses and arm IK |
ファイル: a/games/tps/assets/LICENSE.txt | b/games/tps/assets/LICENSE.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -8,6 +8,7 @@ models/pillar.glb 柱と照明 / a pillar with a lamp | |||
| 8 | models/platform.glb 台(縞鋼板の上面) / a platform with a diamond-plate top | 8 | models/platform.glb 台(縞鋼板の上面) / a platform with a diamond-plate top |
| 9 | models/stairs.glb 階段 / stairs | 9 | models/stairs.glb 階段 / stairs |
| 10 | models/player.glb プレイヤー:部品の階層とソケット / the player: parts in a node hierarchy + sockets | 10 | models/player.glb プレイヤー:部品の階層とソケット / the player: parts in a node hierarchy + sockets |
| 11 | models/enemy.glb 敵(同じ骨組み) / the enemy (same skeleton) (chapter 38) | ||
| 11 | models/rifle.glb ライフル(Muzzle・Foregripソケット) / the rifle (Muzzle and Foregrip sockets) | 12 | models/rifle.glb ライフル(Muzzle・Foregripソケット) / the rifle (Muzzle and Foregrip sockets) |
| 12 | levels/arena.level レベル(手で書いたテキスト) / the level (hand-written text) | 13 | levels/arena.level レベル(手で書いたテキスト) / the level (hand-written text) |
| 13 | levels/pieces.level 部品を並べた確認用のレベル / every piece in a row, for checking (hand-written text) | 14 | levels/pieces.level 部品を並べた確認用のレベル / every piece in a row, for checking (hand-written text) |
ファイル: a/games/tps/assets/levels/arena.level | b/games/tps/assets/levels/arena.level
| 前 | 新 | ||
|---|---|---|---|
| @@ -7,6 +7,7 @@ | |||
| 7 | # row <name> x y z yaw dx dz count count pieces, (dx, dz) apart | 7 | # row <name> x y z yaw dx dz count count pieces, (dx, dz) apart |
| 8 | # grid <name> x y z yaw step nx nz nx × nz pieces, step apart | 8 | # grid <name> x y z yaw step nx nz nx × nz pieces, step apart |
| 9 | # spawn x y z yaw the player's start (yaw 0 = facing north, -Z) | 9 | # spawn x y z yaw the player's start (yaw 0 = facing north, -Z) |
| 10 | # enemy x y z yaw x1 z1 x2 z2 ... an enemy: start + patrol points (chapter 38) | ||
| 10 | 11 | ||
| 11 | model floor games/tps/assets/models/floor_tile.glb noshadow nocollide vary=0.06 | 12 | model floor games/tps/assets/models/floor_tile.glb noshadow nocollide vary=0.06 |
| 12 | model wall games/tps/assets/models/wall.glb vary=0.05 | 13 | model wall games/tps/assets/models/wall.glb vary=0.05 |
| @@ -85,3 +86,10 @@ place barrel -12.2 0 -13.6 90 | |||
| 85 | place barrel 6.9 0 0.3 0 | 86 | place barrel 6.9 0 0.3 0 |
| 86 | 87 | ||
| 87 | spawn 0 0 11.5 0 | 88 | spawn 0 0 11.5 0 |
| 89 | |||
| 90 | # 敵(第38章):enemy x y z yaw 巡回の点 x z ... / enemies (chapter 38): enemy x y z yaw patrol points x z ... | ||
| 91 | enemy -14 0 -13 180 -14 -13 -14 -3 | ||
| 92 | enemy -6 0 -14.5 90 -6 -14.5 6 -14.5 | ||
| 93 | enemy 0 1.5 -3 180 0 -3 0 3 | ||
| 94 | enemy 13.5 0 -9 180 13.5 -9 13.5 7 | ||
| 95 | enemy -6 0 -8.5 90 -6 -8.5 6 -8.5 | ||
ファイル: /dev/null | b/games/tps/assets/models/enemy.glb
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/games/tps/shaders/particle.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,37 @@ | |||
| 1 | #version 460 core | ||
| 2 | // 火花:丸く柔らかい光の点。加算合成(glBlendFunc(GL_ONE, GL_ONE))なので、描く順番は関係ない | ||
| 3 | // Sparks: soft round dots of light. Additive blending (glBlendFunc(GL_ONE, GL_ONE)), so the draw order does not matter | ||
| 4 | in vec2 vCorner; | ||
| 5 | in vec3 vColor; | ||
| 6 | |||
| 7 | layout(location = 0) out vec4 out_color; | ||
| 8 | |||
| 9 | // 後処理の設定(ユニフォームバッファ、結合点3、std140、第21章)。使う全部のシェーダーで同じ宣言(C++ではPostBlock) | ||
| 10 | // Post-processing settings (uniform buffer, binding 3, std140, chapter 21). The same declaration in every shader that | ||
| 11 | // uses it (PostBlock in C++) | ||
| 12 | layout(std140, binding = 3) uniform Post { | ||
| 13 | float uExposure; // 明るさの倍率 / brightness multiplier | ||
| 14 | float uBloomStrength; // ブルームの強さ / bloom strength | ||
| 15 | float uBloomThreshold; // これより明るい部分が光る(リニアのHDR値) / brighter than this glows (linear HDR value) | ||
| 16 | int uToneMapper; // 0 = クランプ / clamp, 1 = Reinhard, 2 = ACES | ||
| 17 | int uGammaMode; // 0 = シェーダー / shader, 1 = GL_FRAMEBUFFER_SRGB, 2 = なし / none, 3 = 二重 / double | ||
| 18 | int uPostView; // 0 = 完成 / final, 1 = ブルームなし / no bloom, 2 = 明るい部分 / bright part, 3 = ブルーム / bloom | ||
| 19 | int uPostPad0, uPostPad1; // std140の大きさを32バイトにそろえる / pads the block to 32 bytes | ||
| 20 | }; | ||
| 21 | |||
| 22 | // ブルーム用の2つ目の出力(MRT、GL_COLOR_ATTACHMENT1) / the second output for bloom (MRT, GL_COLOR_ATTACHMENT1) | ||
| 23 | layout(location = 1) out vec4 out_bright; | ||
| 24 | vec3 brightPart(vec3 c) { | ||
| 25 | float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); // 輝度 / luminance | ||
| 26 | return c * (max(l - uBloomThreshold, 0.0) / max(l, 1e-4)); | ||
| 27 | } | ||
| 28 | |||
| 29 | void main() { | ||
| 30 | float d = dot(vCorner, vCorner); | ||
| 31 | if (d > 1.0) discard; | ||
| 32 | float a = (1.0 - d) * (1.0 - d); // 真ん中ほど明るい / brighter towards the center | ||
| 33 | vec3 c = vColor * a; | ||
| 34 | // アルファ0:加算でも行き先のアルファは変わらない / alpha 0: the destination alpha stays as it is | ||
| 35 | out_color = vec4(c, 0.0); | ||
| 36 | out_bright = vec4(brightPart(c), 0.0); | ||
| 37 | } | ||
ファイル: /dev/null | b/games/tps/shaders/particle.vert
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,34 @@ | |||
| 1 | #version 460 core | ||
| 2 | // 火花(第38章):インスタンスごとに一枚の四角形をカメラに向けて描く(ビルボード)。頂点バッファはなく、 | ||
| 3 | // gl_VertexIDから角を作る(第17章の全画面三角形と同じ考え) | ||
| 4 | // Sparks (chapter 38): one camera-facing quad per instance (a billboard). There is no vertex buffer: the corners come | ||
| 5 | // from gl_VertexID (the same idea as chapter 17's fullscreen triangle) | ||
| 6 | layout(location = 4) in vec4 aParticle; // xyz = 位置 / position, w = 半分の大きさ(m) / half size (m) | ||
| 7 | layout(location = 5) in vec4 aColor; // rgb = HDRの色(消えていく分を掛け済み) / HDR color (fade applied) | ||
| 8 | |||
| 9 | // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock) | ||
| 10 | // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++) | ||
| 11 | layout(std140, binding = 0) uniform Camera { | ||
| 12 | mat4 uView; | ||
| 13 | mat4 uProj; | ||
| 14 | vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space) | ||
| 15 | float uTime; // アニメーションの時間(秒) / animation time (seconds) | ||
| 16 | }; | ||
| 17 | |||
| 18 | out vec2 vCorner; | ||
| 19 | out vec3 vColor; | ||
| 20 | |||
| 21 | const vec2 kCorners[6] = vec2[](vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), | ||
| 22 | vec2(1.0, 1.0), vec2(-1.0, 1.0), vec2(-1.0, -1.0)); | ||
| 23 | |||
| 24 | void main() { | ||
| 25 | vec2 c = kCorners[gl_VertexID]; | ||
| 26 | // ビュー行列の行0・行1 = カメラの右と上(ワールド座標) / rows 0 and 1 of the view matrix = the camera's right and | ||
| 27 | // up in world space | ||
| 28 | vec3 right = vec3(uView[0][0], uView[1][0], uView[2][0]); | ||
| 29 | vec3 up = vec3(uView[0][1], uView[1][1], uView[2][1]); | ||
| 30 | vec3 p = aParticle.xyz + (c.x * right + c.y * up) * aParticle.w; | ||
| 31 | vCorner = c; | ||
| 32 | vColor = aColor.rgb; | ||
| 33 | gl_Position = uProj * uView * vec4(p, 1.0); | ||
| 34 | } | ||
ファイル: /dev/null | b/games/tps/src/angles.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,21 @@ | |||
| 1 | // 角度と、なめらかに近づく計算(第36〜38章のあちこちで使う) / angles and smooth approach (used all over ch. 36-38) | ||
| 2 | #pragma once | ||
| 3 | |||
| 4 | #include <linalg.hh> | ||
| 5 | |||
| 6 | #include <cmath> | ||
| 7 | |||
| 8 | // 角度を −π〜π に / wraps an angle into −π..π | ||
| 9 | inline float wrapAngle(float a) { | ||
| 10 | while (a > PI) a -= 2.0f * PI; | ||
| 11 | while (a < -PI) a += 2.0f * PI; | ||
| 12 | return a; | ||
| 13 | } | ||
| 14 | // 指数的に近づく割合:毎秒rateで目標へ(ステップの長さによらない) / exponential smoothing factor: approaches the | ||
| 15 | // target at `rate` per second, independent of the step length | ||
| 16 | inline float approach(float rate, float dt) { return 1.0f - std::exp(-rate * dt); } | ||
| 17 | // 目標の角度へ短い方の向きで近づく / approaches a target angle the short way round | ||
| 18 | inline float approachAngle(float current, float target, float k) { return current + wrapAngle(target - current) * k; } | ||
| 19 | // 水平の前(カメラのyawと同じ決まり:0 = −Z) / horizontal forward (camera-yaw convention: 0 = −Z) | ||
| 20 | inline Vec3 headingForward(float heading) { return {std::sin(heading), 0.0f, -std::cos(heading)}; } | ||
| 21 | inline Vec3 headingRight(float heading) { return {std::cos(heading), 0.0f, std::sin(heading)}; } | ||
ファイル: a/games/tps/src/character.cc | b/games/tps/src/character.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,5 +1,7 @@ | |||
| 1 | #include "character.hh" | 1 | #include "character.hh" |
| 2 | 2 | ||
| 3 | #include "angles.hh" | ||
| 4 | |||
| 3 | #include <algorithm> | 5 | #include <algorithm> |
| 4 | #include <cmath> | 6 | #include <cmath> |
| 5 | #include <cstdio> | 7 | #include <cstdio> |
| @@ -30,6 +32,33 @@ std::optional<CharacterRig> CharacterRig::find(const Model &model) { | |||
| 30 | return rig; | 32 | return rig; |
| 31 | } | 33 | } |
| 32 | 34 | ||
| 35 | void updateLocomotion(CharacterPose &pose, Vec3 velocity, float heading, bool grounded, float dt, float walkSpeed, | ||
| 36 | float runSpeed) { | ||
| 37 | float speed = length(Vec3{velocity.x, 0.0f, velocity.z}); | ||
| 38 | float legTarget = 0.0f, direction = 1.0f; | ||
| 39 | if (speed > 0.2f) { | ||
| 40 | // 速度をキャラクターの座標へ:+Zが前、+Xが左(右手系で+Zを向くと+Xは左) / velocity in character space: +Z is | ||
| 41 | // forward, +X is LEFT (facing +Z in a right-handed system, +X is on the left) | ||
| 42 | float mz = dot(velocity, headingForward(heading)), mx = -dot(velocity, headingRight(heading)); | ||
| 43 | legTarget = std::atan2(mx, mz); | ||
| 44 | if (std::fabs(legTarget) > radians(100.0f)) { // 後ろ歩き:脚は前を向いたまま逆に回す / walking backwards | ||
| 45 | legTarget = wrapAngle(legTarget - PI); | ||
| 46 | direction = -1.0f; | ||
| 47 | } | ||
| 48 | legTarget = std::clamp(legTarget, radians(-70.0f), radians(70.0f)); | ||
| 49 | } | ||
| 50 | pose.legYaw = approachAngle(pose.legYaw, legTarget, approach(10.0f, dt)); | ||
| 51 | // 歩きの周期は進んだ距離に比例:足が地面を滑らない / the walk cycle advances with distance: feet do not skate | ||
| 52 | float run = std::clamp((speed - walkSpeed) / (runSpeed - walkSpeed), 0.0f, 1.0f); | ||
| 53 | float cycleLength = 1.5f + 0.9f * run; // 1周期(2歩)のm / meters per cycle (two steps) | ||
| 54 | pose.walkPhase = std::fmod(pose.walkPhase + direction * 2.0f * PI * speed * dt / cycleLength, 2.0f * PI); | ||
| 55 | pose.walkAmount = std::clamp(speed / walkSpeed, 0.0f, 1.0f); | ||
| 56 | pose.stride = 1.0f + 0.5f * run; | ||
| 57 | // 空中の姿勢へなめらかに(着地で戻る) / blend into the airborne pose (and back on landing) | ||
| 58 | pose.air += ((grounded ? 0.0f : 1.0f) - pose.air) * approach(12.0f, dt); | ||
| 59 | if (!grounded) pose.walkAmount *= 1.0f - pose.air; | ||
| 60 | } | ||
| 61 | |||
| 33 | Mat4 characterMatrix(Vec3 position, float heading) { return translate(position) * rotateY(PI - heading); } | 62 | Mat4 characterMatrix(Vec3 position, float heading) { return translate(position) * rotateY(PI - heading); } |
| 34 | 63 | ||
| 35 | // X軸周りの回転 / rotation about X | 64 | // X軸周りの回転 / rotation about X |
ファイル: a/games/tps/src/character.hh | b/games/tps/src/character.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -34,6 +34,14 @@ struct CharacterPose { | |||
| 34 | // chapter 37) | 34 | // chapter 37) |
| 35 | }; | 35 | }; |
| 36 | 36 | ||
| 37 | // 速度と向きから歩きのパラメーターを進める(プレイヤーも敵も同じ、第38章でplay_sceneから移した): | ||
| 38 | // 歩きの周期は進んだ距離に比例、脚は移動の向きへ(後ろ歩きは逆回し)、空中では脚を縮める | ||
| 39 | // Advances the walking parameters from velocity and heading (player and enemies alike; moved out of play_scene in | ||
| 40 | // chapter 38): the cycle advances with distance, the legs turn towards the movement (backwards runs the cycle in | ||
| 41 | // reverse), airborne tucks the legs | ||
| 42 | void updateLocomotion(CharacterPose &pose, Vec3 velocity, float heading, bool grounded, float dt, float walkSpeed, | ||
| 43 | float runSpeed); | ||
| 44 | |||
| 37 | // ゲームの中の位置と向き → モデル行列。headingはカメラのyawと同じ決まり(0 = −Zを向く、正 = 右へ回る)で、 | 45 | // ゲームの中の位置と向き → モデル行列。headingはカメラのyawと同じ決まり(0 = −Zを向く、正 = 右へ回る)で、 |
| 38 | // モデルの正面は+Z(第14章の決まり)なので rotateY(π − heading) | 46 | // モデルの正面は+Z(第14章の決まり)なので rotateY(π − heading) |
| 39 | // Position and heading in the game → model matrix. heading uses the camera's yaw convention (0 = facing −Z, positive | 47 | // Position and heading in the game → model matrix. heading uses the camera's yaw convention (0 = facing −Z, positive |
ファイル: a/games/tps/src/collision3d.cc | b/games/tps/src/collision3d.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -131,3 +131,43 @@ std::optional<Contact> deepestContact(const Capsule &capsule, std::span<const Aa | |||
| 131 | } | 131 | } |
| 132 | return best; | 132 | return best; |
| 133 | } | 133 | } |
| 134 | |||
| 135 | std::optional<RayHit> raySphere(const Ray &ray, Vec3 centre, float radius, float maxT) { | ||
| 136 | // |o + t·d − c|² = r² → t² + 2(m·d)t + (m·m − r²) = 0 (m = o − c、|d| = 1) / (m = o − c, |d| = 1) | ||
| 137 | Vec3 m = ray.origin - centre; | ||
| 138 | float b = dot(m, ray.direction), c = dot(m, m) - radius * radius; | ||
| 139 | if (c > 0.0f && b > 0.0f) return std::nullopt; // 外にいて遠ざかる / outside and moving away | ||
| 140 | float disc = b * b - c; | ||
| 141 | if (disc < 0.0f) return std::nullopt; // 外れ / a miss | ||
| 142 | float t = std::fmax(-b - std::sqrt(disc), 0.0f); | ||
| 143 | if (t > maxT) return std::nullopt; | ||
| 144 | Vec3 p = ray.origin + t * ray.direction; | ||
| 145 | return RayHit{t, normalize(p - centre), -1}; | ||
| 146 | } | ||
| 147 | |||
| 148 | std::optional<RayHit> rayCapsule(const Ray &ray, const Capsule &capsule, float maxT) { | ||
| 149 | std::optional<RayHit> best; | ||
| 150 | auto keep = [&](std::optional<RayHit> h) { | ||
| 151 | if (h && (!best || h->t < best->t)) best = h; | ||
| 152 | }; | ||
| 153 | float y0 = capsule.bottomY(), y1 = capsule.topY(); | ||
| 154 | keep(raySphere(ray, {capsule.base.x, y0, capsule.base.z}, capsule.radius, maxT)); | ||
| 155 | keep(raySphere(ray, {capsule.base.x, y1, capsule.base.z}, capsule.radius, maxT)); | ||
| 156 | // 側面:xzだけで円と交差させ、当たった高さが線分の範囲なら当たり / the side: intersect the circle in xz only; a hit | ||
| 157 | // counts if its height is within the segment | ||
| 158 | float ox = ray.origin.x - capsule.base.x, oz = ray.origin.z - capsule.base.z; | ||
| 159 | float dx = ray.direction.x, dz = ray.direction.z; | ||
| 160 | float a = dx * dx + dz * dz; | ||
| 161 | if (a > 1e-8f) { | ||
| 162 | float b = ox * dx + oz * dz, c = ox * ox + oz * oz - capsule.radius * capsule.radius; | ||
| 163 | float disc = b * b - a * c; | ||
| 164 | if (disc >= 0.0f) { | ||
| 165 | float t = (-b - std::sqrt(disc)) / a; | ||
| 166 | if (t >= 0.0f && t <= maxT) { | ||
| 167 | Vec3 p = ray.origin + t * ray.direction; | ||
| 168 | 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}); | ||
| 169 | } | ||
| 170 | } | ||
| 171 | } | ||
| 172 | return best; | ||
| 173 | } | ||
ファイル: a/games/tps/src/collision3d.hh | b/games/tps/src/collision3d.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,7 +1,8 @@ | |||
| 1 | // 3Dの当たり判定(第36・37章):軸に平行な箱(AABB)、レイ・球を飛ばすテスト(カメラ、第36章)、 | 1 | // 3Dの当たり判定(第36〜38章):軸に平行な箱(AABB)、レイ・球を飛ばすテスト(カメラ、第36章)、 |
| 2 | // 縦のカプセル・球と箱のめり込み(キャラクター、第37章) | 2 | // 縦のカプセル・球と箱のめり込み(キャラクター、第37章)、レイと球・カプセル(弾、第38章) |
| 3 | // 3D collision (chapters 36-37): axis-aligned boxes (AABBs), ray / sphere casts (the camera, chapter 36) and the | 3 | // 3D collision (chapters 36-38): axis-aligned boxes (AABBs), ray / sphere casts (the camera, chapter 36), the |
| 4 | // penetration of upright capsules / spheres into boxes (the characters, chapter 37) | 4 | // penetration of upright capsules / spheres into boxes (the characters, chapter 37) and rays against spheres and |
| 5 | // capsules (the bullets, chapter 38) | ||
| 5 | #pragma once | 6 | #pragma once |
| 6 | 7 | ||
| 7 | #include "engine/mathx.hh" | 8 | #include "engine/mathx.hh" |
| @@ -88,3 +89,12 @@ struct Capsule { | |||
| 88 | std::optional<Contact> capsuleAabb(const Capsule &capsule, const Aabb &box); | 89 | std::optional<Contact> capsuleAabb(const Capsule &capsule, const Aabb &box); |
| 89 | // 一番深いめり込み(なければnullopt) / the deepest penetration among the boxes (nullopt if none) | 90 | // 一番深いめり込み(なければnullopt) / the deepest penetration among the boxes (nullopt if none) |
| 90 | std::optional<Contact> deepestContact(const Capsule &capsule, std::span<const Aabb> boxes); | 91 | std::optional<Contact> deepestContact(const Capsule &capsule, std::span<const Aabb> boxes); |
| 92 | |||
| 93 | // レイと球(第38章:敵の当たり判定は頭・胸・腰・脚の球)。始点が球の中ならt = 0 | ||
| 94 | // Ray against sphere (chapter 38: an enemy's hit volumes are spheres for head, chest, hips and legs). Origin inside → | ||
| 95 | // t = 0 | ||
| 96 | std::optional<RayHit> raySphere(const Ray &ray, Vec3 centre, float radius, float maxT); | ||
| 97 | // レイと縦のカプセル(第38章:敵の弾とプレイヤー):円柱の側面(xz平面の円との交差)と上下の球 | ||
| 98 | // Ray against an upright capsule (chapter 38: enemy bullets against the player): the cylinder's side (a circle | ||
| 99 | // intersection in the xz plane) and the two end spheres | ||
| 100 | std::optional<RayHit> rayCapsule(const Ray &ray, const Capsule &capsule, float maxT); | ||
ファイル: /dev/null | b/games/tps/src/effects.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,127 @@ | |||
| 1 | #include "effects.hh" | ||
| 2 | |||
| 3 | #include "engine/uniforms.hh" | ||
| 4 | |||
| 5 | #include <algorithm> | ||
| 6 | #include <cmath> | ||
| 7 | |||
| 8 | Effects::Effects() { | ||
| 9 | shader = Shader::load("games/tps/shaders/particle.vert", "games/tps/shaders/particle.frag"); | ||
| 10 | if (shader && (!shader->checkUniformBlock("Camera", sizeof(CameraBlock)) || | ||
| 11 | !shader->checkUniformBlock("Post", sizeof(PostBlock)))) | ||
| 12 | shader.reset(); | ||
| 13 | // 頂点の属性はインスタンスごとの2つだけ(バインディング0、divisor 1)。角はシェーダーがgl_VertexIDから作る | ||
| 14 | // Only two per-instance attributes (binding 0, divisor 1). The shader makes the corners from gl_VertexID | ||
| 15 | instances = Buffer(nullptr, kMaxParticles * static_cast<GLsizeiptr>(sizeof(ParticleInstance)), GL_DYNAMIC_STORAGE_BIT); | ||
| 16 | glCreateVertexArrays(1, &vao); | ||
| 17 | glVertexArrayVertexBuffer(vao, 0, instances.id(), 0, sizeof(ParticleInstance)); | ||
| 18 | glVertexArrayBindingDivisor(vao, 0, 1); | ||
| 19 | for (GLuint location : {4u, 5u}) { | ||
| 20 | glEnableVertexArrayAttrib(vao, location); | ||
| 21 | glVertexArrayAttribFormat(vao, location, 4, GL_FLOAT, GL_FALSE, location == 4 ? 0 : sizeof(Vec4)); | ||
| 22 | glVertexArrayAttribBinding(vao, location, 0); | ||
| 23 | } | ||
| 24 | } | ||
| 25 | |||
| 26 | Effects::~Effects() { | ||
| 27 | if (vao) glDeleteVertexArrays(1, &vao); | ||
| 28 | } | ||
| 29 | |||
| 30 | void Effects::sparks(Vec3 at, Vec3 normal, Vec3 color, int count, Rng &rng) { | ||
| 31 | for (int i = 0; i < count && particles.size() < kMaxParticles; ++i) { | ||
| 32 | // 球の中の向きを一つ選び、法線の側へ折り返し、法線の向きを少し足す(面から跳ね返る) / a random direction, folded | ||
| 33 | // to the normal's side, plus a bit of the normal (bouncing off the surface) | ||
| 34 | Vec3 d = {rng.range(-1.0f, 1.0f), rng.range(-1.0f, 1.0f), rng.range(-1.0f, 1.0f)}; | ||
| 35 | if (dot(d, normal) < 0.0f) d = d - 2.0f * dot(d, normal) * normal; | ||
| 36 | d = normalize(d + 0.6f * normal); | ||
| 37 | float life = rng.range(0.18f, 0.45f); | ||
| 38 | particles.push_back({at + 0.02f * normal, rng.range(2.0f, 6.5f) * d, life, life, rng.range(0.015f, 0.035f), | ||
| 39 | color * rng.range(0.6f, 1.4f)}); | ||
| 40 | } | ||
| 41 | } | ||
| 42 | |||
| 43 | void Effects::tracer(Vec3 from, Vec3 to, Vec3 color) { streaks.push_back({from, to, 0.06f, 0.06f, color}); } | ||
| 44 | |||
| 45 | void Effects::muzzleFlash(Vec3 at, Vec3 direction) { flashes.push_back({at, direction, 0.05f}); } | ||
| 46 | |||
| 47 | void Effects::update(float dt) { | ||
| 48 | for (Particle &p : particles) { | ||
| 49 | p.velocity.y -= 9.8f * dt; // 火花も落ちる / sparks fall too | ||
| 50 | p.velocity = (1.0f - 2.0f * dt) * p.velocity; // 空気抵抗 / air drag | ||
| 51 | p.position = p.position + dt * p.velocity; | ||
| 52 | p.life -= dt; | ||
| 53 | } | ||
| 54 | std::erase_if(particles, [](const Particle &p) { return p.life <= 0.0f; }); | ||
| 55 | for (Streak &s : streaks) s.life -= dt; | ||
| 56 | std::erase_if(streaks, [](const Streak &s) { return s.life <= 0.0f; }); | ||
| 57 | for (Flash &f : flashes) f.life -= dt; | ||
| 58 | std::erase_if(flashes, [](const Flash &f) { return f.life <= 0.0f; }); | ||
| 59 | } | ||
| 60 | |||
| 61 | void Effects::addLights(LightSet &lights) const { | ||
| 62 | int n = 0; | ||
| 63 | for (const Flash &f : flashes) { | ||
| 64 | if (n++ == 4) break; | ||
| 65 | float k = f.life / 0.05f; | ||
| 66 | lights.points.push_back({.position = f.position, .color = k * Vec3{3.0f, 1.9f, 0.9f}, .attenuation = kShortRange}); | ||
| 67 | } | ||
| 68 | } | ||
| 69 | |||
| 70 | Mat4 beamMatrix(Vec3 a, Vec3 b, float thickness) { | ||
| 71 | Vec3 d = b - a; | ||
| 72 | float len = std::fmax(length(d), 1e-4f); | ||
| 73 | Vec3 z = d / len; | ||
| 74 | Vec3 x = normalize(cross(std::fabs(z.y) > 0.99f ? Vec3{1, 0, 0} : Vec3{0, 1, 0}, z)); | ||
| 75 | Vec3 y = cross(z, x); | ||
| 76 | Mat4 m; | ||
| 77 | m.c[0] = {thickness * x.x, thickness * x.y, thickness * x.z, 0.0f}; | ||
| 78 | m.c[1] = {thickness * y.x, thickness * y.y, thickness * y.z, 0.0f}; | ||
| 79 | m.c[2] = {len * z.x, len * z.y, len * z.z, 0.0f}; | ||
| 80 | Vec3 mid = 0.5f * (a + b); | ||
| 81 | m.c[3] = {mid.x, mid.y, mid.z, 1.0f}; | ||
| 82 | return m; | ||
| 83 | } | ||
| 84 | |||
| 85 | void Effects::drawStreaks(const Renderer &r) const { | ||
| 86 | if (streaks.empty() && flashes.empty()) return; | ||
| 87 | const Shader &s = *r.unlit; | ||
| 88 | s.use(); | ||
| 89 | for (const Streak &t : streaks) { | ||
| 90 | float k = t.life / t.maxLife; | ||
| 91 | s.set("uColor", k * t.color); | ||
| 92 | s.set("uModel", beamMatrix(t.from, t.to, 0.02f)); | ||
| 93 | r.cube.draw(); | ||
| 94 | } | ||
| 95 | // 銃口の光:銃の向きに伸ばした明るい球を2つ(十字に見える) / the muzzle flash: two bright spheres stretched along | ||
| 96 | // the barrel (reads as a star) | ||
| 97 | for (const Flash &f : flashes) { | ||
| 98 | float k = f.life / 0.05f; | ||
| 99 | s.set("uColor", k * Vec3{16.0f, 9.0f, 3.5f}); | ||
| 100 | s.set("uModel", beamMatrix(f.position, f.position + 0.28f * f.direction, 0.09f)); | ||
| 101 | r.sphere.draw(); | ||
| 102 | s.set("uModel", translate(f.position + 0.06f * f.direction) * scale({0.16f, 0.16f, 0.16f})); | ||
| 103 | r.sphere.draw(); | ||
| 104 | } | ||
| 105 | } | ||
| 106 | |||
| 107 | void Effects::drawParticles() { | ||
| 108 | if (particles.empty() || !shader) return; | ||
| 109 | scratch.clear(); | ||
| 110 | for (const Particle &p : particles) { | ||
| 111 | float k = p.life / p.maxLife; // 消えていく / fading out | ||
| 112 | Vec3 c = k * p.color; | ||
| 113 | 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}}); | ||
| 114 | } | ||
| 115 | instances.update(scratch.data(), static_cast<GLsizeiptr>(scratch.size() * sizeof(ParticleInstance))); | ||
| 116 | shader->use(); | ||
| 117 | glBindVertexArray(vao); | ||
| 118 | glEnable(GL_BLEND); | ||
| 119 | glBlendFunc(GL_ONE, GL_ONE); // 加算 / additive | ||
| 120 | glDepthMask(GL_FALSE); // 光は後ろの物を隠さない / light does not hide what is behind it | ||
| 121 | glDisable(GL_CULL_FACE); | ||
| 122 | glDrawArraysInstanced(GL_TRIANGLES, 0, 6, static_cast<GLsizei>(scratch.size())); | ||
| 123 | glDepthMask(GL_TRUE); | ||
| 124 | glDisable(GL_BLEND); | ||
| 125 | glEnable(GL_CULL_FACE); | ||
| 126 | glBindVertexArray(0); | ||
| 127 | } | ||
ファイル: /dev/null | b/games/tps/src/effects.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,79 @@ | |||
| 1 | // 撃ったときの見た目(第38章):銃口の光(発光する形+点光源)、弾の軌跡(トレーサー)、火花(パーティクル)。 | ||
| 2 | // エンジンにはパーティクルの仕組みがないので、ゲームの中に小さく作る(後でエンジンへ移せる) | ||
| 3 | // What a shot looks like (chapter 38): the muzzle flash (an emissive shape + a point light), the bullet's trail (a | ||
| 4 | // tracer) and sparks (particles). The engine has no particle system, so a small one lives in the game (it could move | ||
| 5 | // into the engine later) | ||
| 6 | #pragma once | ||
| 7 | |||
| 8 | #include "renderer.hh" | ||
| 9 | |||
| 10 | #include "engine/buffer.hh" | ||
| 11 | #include "engine/lights.hh" | ||
| 12 | #include "engine/rng.hh" | ||
| 13 | #include "engine/shader.hh" | ||
| 14 | |||
| 15 | #include <optional> | ||
| 16 | #include <vector> | ||
| 17 | |||
| 18 | // aからbへの細い角材(立方体を伸ばす行列):トレーサーとデバッグの線 / a thin beam from a to b (a matrix stretching the | ||
| 19 | // unit cube): tracers and debug lines | ||
| 20 | Mat4 beamMatrix(Vec3 a, Vec3 b, float thickness); | ||
| 21 | |||
| 22 | class Effects { | ||
| 23 | public: | ||
| 24 | Effects(); // GLのものを作る(コンテキストが必要) / creates the GL objects (needs the context) | ||
| 25 | ~Effects(); | ||
| 26 | Effects(const Effects &) = delete; | ||
| 27 | Effects &operator=(const Effects &) = delete; | ||
| 28 | bool ok() const { return shader.has_value(); } | ||
| 29 | |||
| 30 | // 当たった所から法線の側へ火花を飛ばす / sparks flying from a hit point, towards the normal's side | ||
| 31 | void sparks(Vec3 at, Vec3 normal, Vec3 color, int count, Rng &rng); | ||
| 32 | // 銃口から当たった所までの光の筋 / a streak of light from the muzzle to the hit | ||
| 33 | void tracer(Vec3 from, Vec3 to, Vec3 color); | ||
| 34 | // 銃口の光(形と点光源) / the muzzle flash (shape and point light) | ||
| 35 | void muzzleFlash(Vec3 at, Vec3 direction); | ||
| 36 | |||
| 37 | void update(float dt); | ||
| 38 | // 銃口の光を点光源として足す(最大4つ) / adds the muzzle flashes as point lights (4 at most) | ||
| 39 | void addLights(LightSet &lights) const; | ||
| 40 | // 不透明のパスの後:トレーサーと銃口の光(unlit、HDRの色でブルーム) / after the opaque pass: tracers and flashes | ||
| 41 | // (unlit, HDR colors → bloom) | ||
| 42 | void drawStreaks(const Renderer &r) const; | ||
| 43 | // 最後に:火花を加算合成で(深度テストあり、深度は書かない) / last: sparks with additive blending (depth test on, | ||
| 44 | // no depth writes) | ||
| 45 | void drawParticles(); | ||
| 46 | |||
| 47 | int particleCount() const { return static_cast<int>(particles.size()); } | ||
| 48 | |||
| 49 | private: | ||
| 50 | struct Particle { | ||
| 51 | Vec3 position, velocity; | ||
| 52 | float life, maxLife, size; | ||
| 53 | Vec3 color; | ||
| 54 | }; | ||
| 55 | struct Streak { | ||
| 56 | Vec3 from, to; | ||
| 57 | float life, maxLife; | ||
| 58 | Vec3 color; | ||
| 59 | }; | ||
| 60 | struct Flash { | ||
| 61 | Vec3 position, direction; | ||
| 62 | float life; | ||
| 63 | }; | ||
| 64 | // GPUへ送る一つ分(location 4 = 位置と大きさ、5 = 色) / one instance for the GPU (location 4 = position + size, | ||
| 65 | // 5 = color) | ||
| 66 | struct ParticleInstance { | ||
| 67 | Vec4 positionSize; | ||
| 68 | Vec4 color; | ||
| 69 | }; | ||
| 70 | static constexpr int kMaxParticles = 1024; | ||
| 71 | |||
| 72 | std::optional<Shader> shader; | ||
| 73 | GLuint vao = 0; | ||
| 74 | Buffer instances; | ||
| 75 | std::vector<Particle> particles; | ||
| 76 | std::vector<Streak> streaks; | ||
| 77 | std::vector<Flash> flashes; | ||
| 78 | std::vector<ParticleInstance> scratch; | ||
| 79 | }; | ||
ファイル: /dev/null | b/games/tps/src/enemy.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,222 @@ | |||
| 1 | #include "enemy.hh" | ||
| 2 | |||
| 3 | #include "angles.hh" | ||
| 4 | |||
| 5 | #include <algorithm> | ||
| 6 | #include <cmath> | ||
| 7 | |||
| 8 | constexpr float kPatrolSpeed = 1.8f; // m/s | ||
| 9 | constexpr float kChaseSpeed = 3.4f; // m/s | ||
| 10 | constexpr float kSightRange = 22.0f; // 気づく前に見える距離 / sight range before noticing anything | ||
| 11 | constexpr float kAlertRange = 32.0f; // 気づいた後(どの向きでも) / once alert (any direction) | ||
| 12 | constexpr float kViewCos = 0.42f; // 視野の半分の角度 65°のcos / cos of half the field of view (65°) | ||
| 13 | constexpr float kAttackRange = 15.0f; // これより近く、見えていれば撃つ / closer than this and visible: shoot | ||
| 14 | constexpr float kReaction = 0.55f; // 気づいてから撃ち始めるまで / from noticing to the first shot | ||
| 15 | constexpr float kGravity = 20.0f; | ||
| 16 | |||
| 17 | const char *enemyStateName(EnemyState s) { | ||
| 18 | switch (s) { | ||
| 19 | case EnemyState::Patrol: return "patrol"; | ||
| 20 | case EnemyState::Alert: return "alert"; | ||
| 21 | case EnemyState::Chase: return "chase"; | ||
| 22 | case EnemyState::Attack: return "attack"; | ||
| 23 | case EnemyState::Search: return "search"; | ||
| 24 | case EnemyState::Dead: return "dead"; | ||
| 25 | } | ||
| 26 | return "?"; | ||
| 27 | } | ||
| 28 | |||
| 29 | Enemy::Enemy(const EnemySpawn &spawn) : heading(spawn.yaw), prevHeading(spawn.yaw), patrol(spawn.patrol) { | ||
| 30 | body.position = prevPosition = lastSeen = spawn.position; | ||
| 31 | body.grounded = true; | ||
| 32 | } | ||
| 33 | |||
| 34 | void Enemy::setState(EnemyState s) { | ||
| 35 | state = s; | ||
| 36 | stateTime = 0.0f; | ||
| 37 | } | ||
| 38 | |||
| 39 | void Enemy::alert(Vec3 playerPosition, float damage) { | ||
| 40 | if (!alive()) return; | ||
| 41 | lastSeen = playerPosition; | ||
| 42 | if (damage > 0.0f) { | ||
| 43 | health -= damage; | ||
| 44 | flash = 0.12f; | ||
| 45 | if (health <= 0.0f) { | ||
| 46 | health = 0.0f; | ||
| 47 | setState(EnemyState::Dead); | ||
| 48 | body.velocity = {0.0f, 0.0f, 0.0f}; | ||
| 49 | return; | ||
| 50 | } | ||
| 51 | } | ||
| 52 | // 巡回中・探している途中なら、すぐにそちらを向く / patrolling or searching: turn that way at once | ||
| 53 | if (state == EnemyState::Patrol || state == EnemyState::Search) setState(EnemyState::Alert); | ||
| 54 | } | ||
| 55 | |||
| 56 | void Enemy::face(Vec3 target, float dt, float rate) { | ||
| 57 | Vec3 d = target - body.position; | ||
| 58 | if (d.x * d.x + d.z * d.z < 1e-4f) return; | ||
| 59 | float want = std::atan2(d.x, -d.z); // headingForward(want) = d の向き / so that headingForward(want) points along d | ||
| 60 | heading = approachAngle(heading, want, approach(rate, dt)); | ||
| 61 | } | ||
| 62 | |||
| 63 | bool Enemy::walkTo(Vec3 target, float speed, float dt) { | ||
| 64 | Vec3 d = target - body.position; | ||
| 65 | d.y = 0.0f; | ||
| 66 | float dist = length(d); | ||
| 67 | Vec3 want = dist > 0.4f ? (speed / dist) * d : Vec3{}; | ||
| 68 | // 引っかかったら(壁に当たって進めない)、少しの間だけ横へ回り込む。本物の経路探索(ナビメッシュ+A*)の代わりの | ||
| 69 | // 一番簡単なもの | ||
| 70 | // Stuck (blocked by a wall)? Side-step for a moment. The simplest stand-in for real path finding (a navigation mesh | ||
| 71 | // + A*) | ||
| 72 | float moved = length(Vec3{body.velocity.x, 0.0f, body.velocity.z}); | ||
| 73 | if (detour <= 0.0f && dist > 0.4f && body.hitWall && moved < 0.3f * speed) { | ||
| 74 | side = -side; | ||
| 75 | detourDir = side * normalize(Vec3{-d.z, 0.0f, d.x}); | ||
| 76 | detour = 0.7f; | ||
| 77 | } | ||
| 78 | if (detour > 0.0f) { | ||
| 79 | detour -= dt; | ||
| 80 | want = speed * detourDir; | ||
| 81 | } | ||
| 82 | float k = approach(8.0f, dt); | ||
| 83 | body.velocity.x += k * (want.x - body.velocity.x); | ||
| 84 | body.velocity.z += k * (want.z - body.velocity.z); | ||
| 85 | if (dist > 0.4f) face(target, dt); | ||
| 86 | return dist <= 0.5f; | ||
| 87 | } | ||
| 88 | |||
| 89 | void Enemy::stop(float dt) { | ||
| 90 | float k = approach(10.0f, dt); | ||
| 91 | body.velocity.x -= k * body.velocity.x; | ||
| 92 | body.velocity.z -= k * body.velocity.z; | ||
| 93 | } | ||
| 94 | |||
| 95 | bool Enemy::update(float dt, const EnemySenses &senses, Rng &rng, Vec3 &aim) { | ||
| 96 | prevPosition = body.position; | ||
| 97 | prevHeading = heading; | ||
| 98 | stateTime += dt; | ||
| 99 | flash = std::fmax(flash - dt, 0.0f); | ||
| 100 | fireCooldown -= dt; | ||
| 101 | if (state == EnemyState::Dead) { | ||
| 102 | deathTime += dt; | ||
| 103 | seesPlayer = false; | ||
| 104 | pose.walkAmount = 0.0f; | ||
| 105 | return false; | ||
| 106 | } | ||
| 107 | |||
| 108 | // 1. 見る:距離・視野の角度・視線(目からプレイヤーの胸へのレイがレベルの箱に当たらないか) | ||
| 109 | // 1. look: distance, field-of-view angle, line of sight (does the ray from the eyes to the player's chest hit a box?) | ||
| 110 | Vec3 eye = body.position + Vec3{0.0f, 1.6f, 0.0f}; | ||
| 111 | Vec3 chest = senses.playerPosition + Vec3{0.0f, 1.3f, 0.0f}; | ||
| 112 | Vec3 to = chest - eye; | ||
| 113 | float dist = length(to); | ||
| 114 | bool alerted = state != EnemyState::Patrol; | ||
| 115 | bool inView = senses.playerAlive && dist > 0.01f && | ||
| 116 | (alerted ? dist < kAlertRange | ||
| 117 | : dist < kSightRange && dot(headingForward(heading), normalize(Vec3{to.x, 0.0f, to.z})) > kViewCos); | ||
| 118 | seesPlayer = inView && !raycast({eye, to / dist}, senses.solids, dist).has_value(); | ||
| 119 | if (seesPlayer) { | ||
| 120 | lastSeen = senses.playerPosition; | ||
| 121 | lostTime = 0.0f; | ||
| 122 | } else { | ||
| 123 | lostTime += dt; | ||
| 124 | } | ||
| 125 | |||
| 126 | // 2. 状態機械 / 2. the state machine | ||
| 127 | bool fire = false; | ||
| 128 | switch (state) { | ||
| 129 | case EnemyState::Patrol: | ||
| 130 | if (seesPlayer) { | ||
| 131 | setState(EnemyState::Alert); | ||
| 132 | break; | ||
| 133 | } | ||
| 134 | // 巡回の点で1秒止まってから次へ / stop for a second at each patrol point, then go on | ||
| 135 | if (walkTo(patrol[static_cast<size_t>(nextPoint)], kPatrolSpeed, dt)) { | ||
| 136 | stop(dt); | ||
| 137 | if (stateTime > 1.0f) { | ||
| 138 | nextPoint = (nextPoint + 1) % static_cast<int>(patrol.size()); | ||
| 139 | stateTime = 0.0f; | ||
| 140 | } | ||
| 141 | } else { | ||
| 142 | stateTime = 0.0f; | ||
| 143 | } | ||
| 144 | break; | ||
| 145 | case EnemyState::Alert: // 気づいた:止まってそちらを向く(反応時間) / noticed: stop and turn (reaction time) | ||
| 146 | stop(dt); | ||
| 147 | face(lastSeen, dt, 8.0f); | ||
| 148 | if (stateTime > kReaction) setState(seesPlayer && dist < kAttackRange ? EnemyState::Attack : EnemyState::Chase); | ||
| 149 | break; | ||
| 150 | case EnemyState::Attack: | ||
| 151 | stop(dt); | ||
| 152 | face(lastSeen, dt, 8.0f); | ||
| 153 | if (!senses.playerAlive) { | ||
| 154 | setState(EnemyState::Search); | ||
| 155 | } else if (!seesPlayer && lostTime > 0.6f) { | ||
| 156 | setState(EnemyState::Chase); | ||
| 157 | } else if (dist > kAttackRange + 2.0f) { | ||
| 158 | setState(EnemyState::Chase); | ||
| 159 | } else if (seesPlayer && fireCooldown <= 0.0f) { | ||
| 160 | // 撃つのは正面を向いてから / fire only when facing the player | ||
| 161 | Vec3 f = headingForward(heading); | ||
| 162 | if (dot(f, normalize(Vec3{to.x, 0.0f, to.z})) > 0.97f) { | ||
| 163 | fire = true; | ||
| 164 | aim = chest; | ||
| 165 | fireCooldown = rng.range(0.55f, 0.95f); | ||
| 166 | } | ||
| 167 | } | ||
| 168 | break; | ||
| 169 | case EnemyState::Chase: | ||
| 170 | if (seesPlayer && dist < kAttackRange) { | ||
| 171 | setState(EnemyState::Attack); | ||
| 172 | break; | ||
| 173 | } | ||
| 174 | if (walkTo(lastSeen, kChaseSpeed, dt) || stateTime > 8.0f) setState(EnemyState::Search); | ||
| 175 | break; | ||
| 176 | case EnemyState::Search: // 見回して、3秒で巡回へ戻る / look around, back to patrolling after 3 s | ||
| 177 | stop(dt); | ||
| 178 | heading += 1.6f * dt; | ||
| 179 | if (seesPlayer) { | ||
| 180 | setState(EnemyState::Alert); | ||
| 181 | } else if (stateTime > 3.0f) { | ||
| 182 | // 一番近い巡回の点から / from the nearest patrol point | ||
| 183 | float best = 1e9f; | ||
| 184 | for (size_t i = 0; i < patrol.size(); ++i) { | ||
| 185 | float d = length(patrol[i] - body.position); | ||
| 186 | if (d < best) { | ||
| 187 | best = d; | ||
| 188 | nextPoint = static_cast<int>(i); | ||
| 189 | } | ||
| 190 | } | ||
| 191 | setState(EnemyState::Patrol); | ||
| 192 | } | ||
| 193 | break; | ||
| 194 | case EnemyState::Dead: break; | ||
| 195 | } | ||
| 196 | |||
| 197 | // 3. 体を動かす(プレイヤーと同じ重力・当たり判定・壁ずり・段差) / 3. move the body (the player's gravity, | ||
| 198 | // collision, wall sliding and steps) | ||
| 199 | body.velocity.y -= kGravity * dt; | ||
| 200 | body.move(dt, senses.solids); | ||
| 201 | |||
| 202 | // 4. 姿勢:歩き、狙うときは銃をプレイヤーの胸へ / 4. pose: walking, and the gun towards the player's chest when | ||
| 203 | // aiming | ||
| 204 | updateLocomotion(pose, body.velocity, heading, body.grounded, dt, kPatrolSpeed, kChaseSpeed); | ||
| 205 | float pitch = 0.0f; | ||
| 206 | if (state == EnemyState::Attack || state == EnemyState::Alert) { | ||
| 207 | Vec3 d = lastSeen + Vec3{0.0f, 1.3f, 0.0f} - eye; | ||
| 208 | pitch = std::atan2(d.y, std::sqrt(d.x * d.x + d.z * d.z)); | ||
| 209 | } | ||
| 210 | pose.aimPitch += (pitch - pose.aimPitch) * approach(8.0f, dt); | ||
| 211 | return fire; | ||
| 212 | } | ||
| 213 | |||
| 214 | Mat4 Enemy::matrix(float alpha) const { | ||
| 215 | Mat4 m = characterMatrix(lerp(prevPosition, body.position, alpha), approachAngle(prevHeading, heading, alpha)); | ||
| 216 | if (state != EnemyState::Dead) return m; | ||
| 217 | // 倒れる:足元を軸に後ろへ90°(0.6秒)、背中の厚みの分だけ持ち上げる | ||
| 218 | // Falling: 90° backwards about the feet (0.6 s), lifted by the thickness of the back | ||
| 219 | float t = std::clamp(deathTime / 0.6f, 0.0f, 1.0f); | ||
| 220 | float fall = t * t * (3.0f - 2.0f * t); | ||
| 221 | return m * translate({0.0f, 0.15f * fall, 0.0f}) * rotateX(-0.5f * PI * fall); | ||
| 222 | } | ||
ファイル: /dev/null | b/games/tps/src/enemy.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,76 @@ | |||
| 1 | // 敵(第38章):状態機械のAI。巡回 → 気づく → 追う / 撃つ → 見失ったら探す → 巡回へ戻る。撃たれると気づき、 | ||
| 2 | // 体力が0で倒れる。体はプレイヤーと同じCharacterBody、見た目は同じ骨組みのenemy.glb | ||
| 3 | // An enemy (chapter 38): a state-machine AI. Patrol → notice → chase / shoot → search when the player is lost → back to | ||
| 4 | // patrolling. Being shot alerts it; at 0 health it falls. The body is the same CharacterBody as the player's, the look | ||
| 5 | // is enemy.glb with the same skeleton | ||
| 6 | #pragma once | ||
| 7 | |||
| 8 | #include "character.hh" | ||
| 9 | #include "character_body.hh" | ||
| 10 | #include "level.hh" | ||
| 11 | |||
| 12 | #include "engine/rng.hh" | ||
| 13 | |||
| 14 | #include <span> | ||
| 15 | |||
| 16 | enum class EnemyState { Patrol, Alert, Chase, Attack, Search, Dead }; | ||
| 17 | const char *enemyStateName(EnemyState s); | ||
| 18 | |||
| 19 | // AIが世界について知ること(毎ステップ) / what the AI knows about the world (every step) | ||
| 20 | struct EnemySenses { | ||
| 21 | std::span<const Aabb> solids; | ||
| 22 | Vec3 playerPosition; // 足元 / feet | ||
| 23 | bool playerAlive = true; | ||
| 24 | }; | ||
| 25 | |||
| 26 | // 当たり判定の球(頭・胸・腰・脚):足元からの高さ、半径、ダメージの倍率 / hit spheres (head, chest, hips, legs): | ||
| 27 | // height above the feet, radius, damage multiplier | ||
| 28 | struct HitSphere { | ||
| 29 | float height, radius, damage; | ||
| 30 | }; | ||
| 31 | inline constexpr HitSphere kHitSpheres[] = {{1.62f, 0.17f, 2.5f}, {1.25f, 0.30f, 1.0f}, {0.88f, 0.25f, 1.0f}, | ||
| 32 | {0.45f, 0.24f, 0.7f}}; | ||
| 33 | |||
| 34 | class Enemy { | ||
| 35 | public: | ||
| 36 | explicit Enemy(const EnemySpawn &spawn); | ||
| 37 | |||
| 38 | // 1ステップ。撃ちたいときはtrueを返し、aimに狙う点(プレイヤーの胸)を入れる | ||
| 39 | // One step. Returns true when it wants to fire, with aim = the point it aims at (the player's chest) | ||
| 40 | bool update(float dt, const EnemySenses &senses, Rng &rng, Vec3 &aim); | ||
| 41 | // 撃たれた(damage)・銃声を聞いた(damage 0)。どちらもプレイヤーの居場所に気づく | ||
| 42 | // Shot (damage) or heard a shot (damage 0). Either way it learns where the player is | ||
| 43 | void alert(Vec3 playerPosition, float damage = 0.0f); | ||
| 44 | bool alive() const { return state != EnemyState::Dead; } | ||
| 45 | |||
| 46 | // 描くとき:補間した行列(倒れる回転込み)と姿勢 / for drawing: the interpolated matrix (including the fall) and pose | ||
| 47 | Mat4 matrix(float alpha) const; | ||
| 48 | |||
| 49 | CharacterBody body; | ||
| 50 | float heading = 0.0f, prevHeading = 0.0f; | ||
| 51 | Vec3 prevPosition; | ||
| 52 | CharacterPose pose; | ||
| 53 | EnemyState state = EnemyState::Patrol; | ||
| 54 | float health = 100.0f; | ||
| 55 | float flash = 0.0f; // 撃たれて光る残り時間 / time left of the hit flash | ||
| 56 | float stateTime = 0.0f; | ||
| 57 | Vec3 lastSeen; // 最後にプレイヤーを見た(聞いた)所 / where the player was last seen (heard) | ||
| 58 | bool seesPlayer = false; | ||
| 59 | std::vector<Vec3> patrol; | ||
| 60 | int nextPoint = 0; | ||
| 61 | |||
| 62 | private: | ||
| 63 | void setState(EnemyState s); | ||
| 64 | // 目標へ歩く(水平の速度を決める)。着いたらtrue / walks towards a target (sets the horizontal velocity); true when | ||
| 65 | // arrived | ||
| 66 | bool walkTo(Vec3 target, float speed, float dt); | ||
| 67 | void stop(float dt); | ||
| 68 | void face(Vec3 target, float dt, float rate = 6.0f); | ||
| 69 | |||
| 70 | float fireCooldown = 0.0f; | ||
| 71 | float lostTime = 0.0f; // 見失ってからの時間 / time since the player was last seen | ||
| 72 | float deathTime = 0.0f; | ||
| 73 | float detour = 0.0f; // 回り込みの残り時間 / time left of a side-step | ||
| 74 | Vec3 detourDir; | ||
| 75 | float side = 1.0f; // 回り込む向き(交互に) / which way to side-step (alternating) | ||
| 76 | }; | ||
ファイル: a/games/tps/src/game.hh | b/games/tps/src/game.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -25,6 +25,8 @@ struct Game { | |||
| 25 | Model &player; // player.glb(姿勢を書き込むので非const) / non-const: poses are written into it | 25 | Model &player; // player.glb(姿勢を書き込むので非const) / non-const: poses are written into it |
| 26 | Model &rifle; | 26 | Model &rifle; |
| 27 | const CharacterRig &playerRig; | 27 | const CharacterRig &playerRig; |
| 28 | Model &enemy; // enemy.glb:全部の敵がこれ一つを使う(第38章) / every enemy shares this one (chapter 38) | ||
| 29 | const CharacterRig &enemyRig; | ||
| 28 | Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI | 30 | Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI |
| 29 | Viewport uiViewport; | 31 | Viewport uiViewport; |
| 30 | int frame = 0; // 描いたフレームの数 / frames drawn so far | 32 | int frame = 0; // 描いたフレームの数 / frames drawn so far |
ファイル: a/games/tps/src/level.cc | b/games/tps/src/level.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -119,6 +119,21 @@ std::optional<Level> Level::load(const std::string &path) { | |||
| 119 | float yaw = 0.0f; | 119 | float yaw = 0.0f; |
| 120 | if (!(in >> level.spawn.x >> level.spawn.y >> level.spawn.z >> yaw)) return fail("spawn x y z yaw"); | 120 | if (!(in >> level.spawn.x >> level.spawn.y >> level.spawn.z >> yaw)) return fail("spawn x y z yaw"); |
| 121 | level.spawnYaw = radians(yaw); | 121 | level.spawnYaw = radians(yaw); |
| 122 | } else if (command == "enemy") { | ||
| 123 | // enemy x y z yaw x1 z1 x2 z2 ...:出発点と巡回の点(第38章) / start and patrol points (chapter 38) | ||
| 124 | EnemySpawn e; | ||
| 125 | float yaw = 0.0f; | ||
| 126 | if (!(in >> e.position.x >> e.position.y >> e.position.z >> yaw)) return fail("enemy x y z yaw [x z]..."); | ||
| 127 | e.yaw = radians(yaw); | ||
| 128 | std::vector<float> xz; | ||
| 129 | float value = 0.0f; | ||
| 130 | while (in >> value) xz.push_back(value); | ||
| 131 | // 数でない物が残っている、または数が奇数(zのないx)なら書き間違い / something that is not a number, or an odd | ||
| 132 | // count (an x without its z), is a typo | ||
| 133 | if (!in.eof() || xz.size() % 2 != 0) return fail("巡回の点は x z の組 / patrol points are x z pairs"); | ||
| 134 | for (size_t i = 0; i < xz.size(); i += 2) e.patrol.push_back({xz[i], e.position.y, xz[i + 1]}); | ||
| 135 | if (e.patrol.empty()) e.patrol.push_back(e.position); // 立って見張る / stands guard | ||
| 136 | level.enemies.push_back(e); | ||
| 122 | } else { | 137 | } else { |
| 123 | return fail("知らない命令 / unknown command"); | 138 | return fail("知らない命令 / unknown command"); |
| 124 | } | 139 | } |
| @@ -159,8 +174,8 @@ std::optional<Level> Level::load(const std::string &path) { | |||
| 159 | GL_DYNAMIC_STORAGE_BIT); | 174 | GL_DYNAMIC_STORAGE_BIT); |
| 160 | type.model->setInstanceBuffer(type.instances, sizeof(InstanceData), kInstanceLayout); | 175 | type.model->setInstanceBuffer(type.instances, sizeof(InstanceData), kInstanceLayout); |
| 161 | } | 176 | } |
| 162 | printf("%s: %zu piece types, %zu pieces, %zu collision boxes\n", path.c_str(), level.types.size(), | 177 | printf("%s: %zu piece types, %zu pieces, %zu collision boxes, %zu enemies\n", path.c_str(), level.types.size(), |
| 163 | level.pieces.size(), level.solids.size()); | 178 | level.pieces.size(), level.solids.size(), level.enemies.size()); |
| 164 | return level; | 179 | return level; |
| 165 | } | 180 | } |
| 166 | 181 | ||
ファイル: a/games/tps/src/level.hh | b/games/tps/src/level.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -41,6 +41,13 @@ struct Piece { | |||
| 41 | float sphereRadius = 0.0f; | 41 | float sphereRadius = 0.0f; |
| 42 | }; | 42 | }; |
| 43 | 43 | ||
| 44 | // 敵の出発点と巡回の道(第38章) / an enemy's start and patrol route (chapter 38) | ||
| 45 | struct EnemySpawn { | ||
| 46 | Vec3 position; | ||
| 47 | float yaw = 0.0f; // ラジアン、0 = −Zを向く / radians, 0 = facing −Z | ||
| 48 | std::vector<Vec3> patrol; // 巡回の点(高さは出発点と同じ) / patrol points (at the start's height) | ||
| 49 | }; | ||
| 50 | |||
| 44 | // 描いた数(画面の数字とNOTES用) / how much was drawn (for the overlay and the notes) | 51 | // 描いた数(画面の数字とNOTES用) / how much was drawn (for the overlay and the notes) |
| 45 | struct LevelDrawStats { | 52 | struct LevelDrawStats { |
| 46 | int visible = 0, total = 0, drawCalls = 0; | 53 | int visible = 0, total = 0, drawCalls = 0; |
| @@ -67,6 +74,7 @@ public: | |||
| 67 | std::vector<Aabb> solids; // ワールドの当たり判定の箱 / world-space collision boxes | 74 | std::vector<Aabb> solids; // ワールドの当たり判定の箱 / world-space collision boxes |
| 68 | Vec3 spawn; // プレイヤーの出発点 / the player's start | 75 | Vec3 spawn; // プレイヤーの出発点 / the player's start |
| 69 | float spawnYaw = 0.0f; // ラジアン、0 = −Zを向く / radians, 0 = facing −Z | 76 | float spawnYaw = 0.0f; // ラジアン、0 = −Zを向く / radians, 0 = facing −Z |
| 77 | std::vector<EnemySpawn> enemies; // 第38章 / chapter 38 | ||
| 70 | Aabb bounds; // 全部を囲む箱 / box around everything | 78 | Aabb bounds; // 全部を囲む箱 / box around everything |
| 71 | 79 | ||
| 72 | private: | 80 | private: |
ファイル: a/games/tps/src/main.cc | b/games/tps/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,13 +1,16 @@ | |||
| 1 | // 第36〜39章:三人称シューティング(TPS)。第36章:レベル、キャラクター、三人称カメラ。第37章:当たり判定、重力、 | 1 | // 第36〜39章:三人称シューティング(TPS)。第36章:レベル、キャラクター、三人称カメラ。第37章:当たり判定、重力、 |
| 2 | // ジャンプ、壁ずり | 2 | // ジャンプ、壁ずり。第38章:射撃、敵、体力、当たったときの効果 |
| 3 | // Chapters 36-39: the third-person shooter (TPS). Chapter 36: the level, the character and the third-person camera. | 3 | // Chapters 36-39: the third-person shooter (TPS). Chapter 36: the level, the character and the third-person camera. |
| 4 | // Chapter 37: collision, gravity, jumping, wall sliding | 4 | // Chapter 37: collision, gravity, jumping, wall sliding. Chapter 38: shooting, enemies, health, hit effects |
| 5 | // | 5 | // |
| 6 | // 操作 / Controls: | 6 | // 操作 / Controls: |
| 7 | // WASD カメラの向きに対して移動 / move relative to the camera | 7 | // WASD カメラの向きに対して移動 / move relative to the camera |
| 8 | // マウス / mouse 見回す / look around | 8 | // マウス / mouse 見回す / look around |
| 9 | // Shift 走る(前へ) / run (forwards) | 9 | // Shift 走る(前へ) / run (forwards) |
| 10 | // Space ジャンプ / jump | 10 | // Space ジャンプ / jump |
| 11 | // 左ボタン / LMB 撃つ(押し続けると連射) / fire (hold for automatic fire) | ||
| 12 | // 右ボタン / RMB 狙う(肩に寄って視野が狭まる) / aim (closer over the shoulder, narrower view) | ||
| 13 | // R 弾を込め直す / reload | ||
| 11 | // Q 右肩 ⇔ 左肩 / right ⇔ left shoulder | 14 | // Q 右肩 ⇔ 左肩 / right ⇔ left shoulder |
| 12 | // B 当たり判定の箱・カプセル・ソケット・軌跡 / collision boxes, capsule, sockets, trail | 15 | // B 当たり判定の箱・カプセル・ソケット・軌跡 / collision boxes, capsule, sockets, trail |
| 13 | // F3 時間と描いた数 / timings and draw counts | 16 | // F3 時間と描いた数 / timings and draw counts |
| @@ -15,6 +18,7 @@ | |||
| 15 | // C カメラだけ回す(キャラクターを前から見る) / turn only the camera (look at the character) | 18 | // C カメラだけ回す(キャラクターを前から見る) / turn only the camera (look at the character) |
| 16 | // K カメラの当たり判定のオン・オフ / camera collision on / off | 19 | // K カメラの当たり判定のオン・オフ / camera collision on / off |
| 17 | // O 上から見下ろす(デバッグ) / view from above (debugging) | 20 | // O 上から見下ろす(デバッグ) / view from above (debugging) |
| 21 | // F8 毎フレームの状態を標準出力へ(台本を作る用) / log the state every frame to stdout (for scripting) | ||
| 18 | // L 壁ずり ⇔ 壁で止まる(比べる) / wall sliding ⇔ stopping at walls (to compare) | 22 | // L 壁ずり ⇔ 壁で止まる(比べる) / wall sliding ⇔ stopping at walls (to compare) |
| 19 | // P 手続き的な姿勢のオン・オフ(読み込んだままの姿勢) / procedural pose on / off (the pose as loaded) | 23 | // P 手続き的な姿勢のオン・オフ(読み込んだままの姿勢) / procedural pose on / off (the pose as loaded) |
| 20 | // Tab カーソルのキャプチャ / cursor capture | 24 | // Tab カーソルのキャプチャ / cursor capture |
| @@ -43,9 +47,11 @@ int main(int argc, char **argv) { | |||
| 43 | std::optional<Level> level = Level::load(argc > 1 ? argv[1] : "games/tps/assets/levels/arena.level"); | 47 | std::optional<Level> level = Level::load(argc > 1 ? argv[1] : "games/tps/assets/levels/arena.level"); |
| 44 | std::optional<Model> player = Model::load("games/tps/assets/models/player.glb"); | 48 | std::optional<Model> player = Model::load("games/tps/assets/models/player.glb"); |
| 45 | std::optional<Model> rifle = Model::load("games/tps/assets/models/rifle.glb"); | 49 | std::optional<Model> rifle = Model::load("games/tps/assets/models/rifle.glb"); |
| 46 | if (!level || !player || !rifle) return 1; | 50 | std::optional<Model> enemy = Model::load("games/tps/assets/models/enemy.glb"); |
| 51 | if (!level || !player || !rifle || !enemy) return 1; | ||
| 47 | std::optional<CharacterRig> playerRig = CharacterRig::find(*player); | 52 | std::optional<CharacterRig> playerRig = CharacterRig::find(*player); |
| 48 | if (!playerRig) return 1; | 53 | std::optional<CharacterRig> enemyRig = CharacterRig::find(*enemy); |
| 54 | if (!playerRig || !enemyRig) return 1; | ||
| 49 | 55 | ||
| 50 | // HUDと文字(第25・26章の2Dの道具を3Dの絵の上に) / HUD and text (the chapter 25-26 2D toolkit over the 3D image) | 56 | // HUDと文字(第25・26章の2Dの道具を3Dの絵の上に) / HUD and text (the chapter 25-26 2D toolkit over the 3D image) |
| 51 | std::optional<SpriteBatch> batch = SpriteBatch::create(); | 57 | std::optional<SpriteBatch> batch = SpriteBatch::create(); |
| @@ -62,10 +68,14 @@ int main(int argc, char **argv) { | |||
| 62 | input.bind("right", {InputBinding::key(GLFW_KEY_D), InputBinding::key(GLFW_KEY_RIGHT)}); | 68 | input.bind("right", {InputBinding::key(GLFW_KEY_D), InputBinding::key(GLFW_KEY_RIGHT)}); |
| 63 | input.bind("run", {InputBinding::key(GLFW_KEY_LEFT_SHIFT)}); | 69 | input.bind("run", {InputBinding::key(GLFW_KEY_LEFT_SHIFT)}); |
| 64 | input.bind("jump", {InputBinding::key(GLFW_KEY_SPACE)}); | 70 | input.bind("jump", {InputBinding::key(GLFW_KEY_SPACE)}); |
| 71 | input.bind("fire", {InputBinding::mouse(GLFW_MOUSE_BUTTON_LEFT)}); | ||
| 72 | input.bind("aim", {InputBinding::mouse(GLFW_MOUSE_BUTTON_RIGHT)}); | ||
| 73 | input.bind("reload", {InputBinding::key(GLFW_KEY_R)}); | ||
| 65 | 74 | ||
| 66 | GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); | 75 | GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); |
| 67 | Game game{.window = window, .input = input, .loop = loop, .renderer = *renderer, .batch = *batch, .ui = *ui, | 76 | Game game{.window = window, .input = input, .loop = loop, .renderer = *renderer, .batch = *batch, .ui = *ui, |
| 68 | .level = *level, .player = *player, .rifle = *rifle, .playerRig = *playerRig, | 77 | .level = *level, .player = *player, .rifle = *rifle, .playerRig = *playerRig, |
| 78 | .enemy = *enemy, .enemyRig = *enemyRig, | ||
| 69 | .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}}; | 79 | .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}}; |
| 70 | 80 | ||
| 71 | SceneManager scenes; | 81 | SceneManager scenes; |
ファイル: a/games/tps/src/play_scene.cc | b/games/tps/src/play_scene.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,20 +1,12 @@ | |||
| 1 | #include "play_scene.hh" | 1 | #include "play_scene.hh" |
| 2 | 2 | ||
| 3 | #include "angles.hh" | ||
| 4 | |||
| 3 | #include <algorithm> | 5 | #include <algorithm> |
| 4 | #include <cmath> | 6 | #include <cmath> |
| 5 | #include <cstdio> | 7 | #include <cstdio> |
| 6 | #include <format> | 8 | #include <format> |
| 7 | 9 | ||
| 8 | // 角度を −π〜π に / wraps an angle into −π..π | ||
| 9 | static float wrapAngle(float a) { | ||
| 10 | while (a > PI) a -= 2.0f * PI; | ||
| 11 | while (a < -PI) a += 2.0f * PI; | ||
| 12 | return a; | ||
| 13 | } | ||
| 14 | // 目標の角度へ短い方の向きで近づく / approaches a target angle the short way round | ||
| 15 | static float approachAngle(float current, float target, float k) { return current + wrapAngle(target - current) * k; } | ||
| 16 | static float approach(float rate, float dt) { return 1.0f - std::exp(-rate * dt); } | ||
| 17 | |||
| 18 | constexpr float kWalkSpeed = 3.2f; // m/s | 10 | constexpr float kWalkSpeed = 3.2f; // m/s |
| 19 | constexpr float kRunSpeed = 6.0f; // m/s(Shift) | 11 | constexpr float kRunSpeed = 6.0f; // m/s(Shift) |
| 20 | constexpr float kAcceleration = 12.0f; // 速度が目標に近づく割合(毎秒) / how fast the velocity approaches its target | 12 | constexpr float kAcceleration = 12.0f; // 速度が目標に近づく割合(毎秒) / how fast the velocity approaches its target |
| @@ -27,7 +19,29 @@ constexpr float kCoyoteTime = 0.1f; // 足場を離れてからまだ跳べ | |||
| 27 | constexpr float kJumpBuffer = 0.1f; // 着地の少し前に押したジャンプを覚えておく時間 / a jump pressed just before | 19 | constexpr float kJumpBuffer = 0.1f; // 着地の少し前に押したジャンプを覚えておく時間 / a jump pressed just before |
| 28 | // landing is remembered this long | 20 | // landing is remembered this long |
| 29 | 21 | ||
| 30 | PlayScene::PlayScene(Game &game) : g(game) {} | 22 | // 武器と体力(第38章) / weapon and health (chapter 38) |
| 23 | constexpr float kFireInterval = 0.11f; // 秒:60 Hzでは7ステップごと、毎秒約8.6発 / s: every 7 steps at 60 Hz, ≈ 8.6 rounds/s | ||
| 24 | constexpr float kReloadTime = 1.6f; | ||
| 25 | constexpr float kDamage = 34.0f; // 胸に3発、頭に2発 / three to the chest, two to the head | ||
| 26 | constexpr float kEnemyDamage = 8.0f; | ||
| 27 | constexpr float kHearing = 18.0f; // 銃声が聞こえる距離 / how far a shot is heard | ||
| 28 | constexpr float kRespawnTime = 3.0f; | ||
| 29 | |||
| 30 | // 円錐の中のでたらめな向き(拡散):axisから最大angleラジアン / a random direction inside a cone (spread): at most angle | ||
| 31 | // radians from axis | ||
| 32 | static Vec3 spreadDirection(Vec3 axis, float angle, Rng &rng) { | ||
| 33 | Vec3 u = normalize(cross(std::fabs(axis.y) > 0.99f ? Vec3{1, 0, 0} : Vec3{0, 1, 0}, axis)); | ||
| 34 | Vec3 v = cross(axis, u); | ||
| 35 | float r = std::tan(angle) * std::sqrt(rng.unit()); // 円の中で一様 / uniform inside the disc | ||
| 36 | float a = 2.0f * PI * rng.unit(); | ||
| 37 | return normalize(axis + (r * std::cos(a)) * u + (r * std::sin(a)) * v); | ||
| 38 | } | ||
| 39 | |||
| 40 | static Vec3 origin(const Mat4 &m) { return {m.c[3].x, m.c[3].y, m.c[3].z}; } | ||
| 41 | |||
| 42 | PlayScene::PlayScene(Game &game) : g(game) { | ||
| 43 | for (const EnemySpawn &spawn : g.level.enemies) enemies.emplace_back(spawn); | ||
| 44 | } | ||
| 31 | 45 | ||
| 32 | Vec3 PlayScene::cameraPivot() const { | 46 | Vec3 PlayScene::cameraPivot() const { |
| 33 | // CameraPivotソケット(空のノード)のワールドの位置:モデル行列 × ノードの行列の原点 | 47 | // CameraPivotソケット(空のノード)のワールドの位置:モデル行列 × ノードの行列の原点 |
| @@ -74,6 +88,7 @@ void PlayScene::update(float dt) { | |||
| 74 | if (in.pressed(GLFW_KEY_F4)) culling = !culling; | 88 | if (in.pressed(GLFW_KEY_F4)) culling = !culling; |
| 75 | if (in.pressed(GLFW_KEY_L)) body.slide = !body.slide; | 89 | if (in.pressed(GLFW_KEY_L)) body.slide = !body.slide; |
| 76 | if (in.pressed(GLFW_KEY_O)) overhead = !overhead; | 90 | if (in.pressed(GLFW_KEY_O)) overhead = !overhead; |
| 91 | if (in.pressed(GLFW_KEY_F8)) logging = !logging; | ||
| 77 | 92 | ||
| 78 | // 1. 見回す(マウスの動きはフレームごと:最初のステップだけが使う) / 1. look around (mouse movement is per frame: | 93 | // 1. 見回す(マウスの動きはフレームごと:最初のステップだけが使う) / 1. look around (mouse movement is per frame: |
| 79 | // only the first step uses it) | 94 | // only the first step uses it) |
| @@ -84,12 +99,13 @@ void PlayScene::update(float dt) { | |||
| 84 | // 2. movement relative to the camera: the input (right, forward) times the camera's horizontal right and forward | 99 | // 2. movement relative to the camera: the input (right, forward) times the camera's horizontal right and forward |
| 85 | // vectors (not the world axes) | 100 | // vectors (not the world axes) |
| 86 | Vec2 stick = {in.axis("left", "right"), in.axis("back", "forward")}; | 101 | Vec2 stick = {in.axis("left", "right"), in.axis("back", "forward")}; |
| 87 | if (inspect) stick = {0.0f, 0.0f}; // C:キャラクターの周りを見るだけ / C: only look around the character | 102 | if (inspect || !alive) stick = {0.0f, 0.0f}; // C:周りを見るだけ / C: only look around; dead: no input |
| 88 | Vec3 wish = stick.x * camera.right() + stick.y * camera.flatForward(); | 103 | Vec3 wish = stick.x * camera.right() + stick.y * camera.flatForward(); |
| 89 | float wishLength = length(wish); | 104 | float wishLength = length(wish); |
| 90 | if (wishLength > 1.0f) wish = wish / wishLength; // 斜めでも同じ速さ / same speed diagonally | 105 | if (wishLength > 1.0f) wish = wish / wishLength; // 斜めでも同じ速さ / same speed diagonally |
| 91 | bool running = in.actionHeld("run") && stick.y > 0.0f; | 106 | bool running = in.actionHeld("run") && stick.y > 0.0f && aimBlend < 0.5f; |
| 92 | Vec3 target = (running ? kRunSpeed : kWalkSpeed) * wish; | 107 | // 狙っている間は歩くだけ / walk only while aiming |
| 108 | Vec3 target = (running ? kRunSpeed : kWalkSpeed * (1.0f - 0.35f * aimBlend)) * wish; | ||
| 93 | // 水平の速度だけを目標へ(上下は重力とジャンプ)。空中ではゆっくり / only the horizontal velocity approaches the | 109 | // 水平の速度だけを目標へ(上下は重力とジャンプ)。空中ではゆっくり / only the horizontal velocity approaches the |
| 94 | // target (vertical = gravity and jumps); slowly in the air | 110 | // target (vertical = gravity and jumps); slowly in the air |
| 95 | Vec3 &v = body.velocity; | 111 | Vec3 &v = body.velocity; |
| @@ -102,7 +118,7 @@ void PlayScene::update(float dt) { | |||
| 102 | // 3. gravity and jumping. Coyote time (just after leaving a ledge) and a jump buffer (just before landing) make sure | 118 | // 3. gravity and jumping. Coyote time (just after leaving a ledge) and a jump buffer (just before landing) make sure |
| 103 | // a press is never lost | 119 | // a press is never lost |
| 104 | coyote = body.grounded ? kCoyoteTime : coyote - dt; | 120 | coyote = body.grounded ? kCoyoteTime : coyote - dt; |
| 105 | jumpBuffer = in.actionPressed("jump") ? kJumpBuffer : jumpBuffer - dt; | 121 | jumpBuffer = in.actionPressed("jump") && alive ? kJumpBuffer : jumpBuffer - dt; |
| 106 | bool jumped = false; | 122 | bool jumped = false; |
| 107 | if (jumpBuffer > 0.0f && coyote > 0.0f) { | 123 | if (jumpBuffer > 0.0f && coyote > 0.0f) { |
| 108 | v.y = kJumpSpeed; | 124 | v.y = kJumpSpeed; |
| @@ -133,42 +149,220 @@ void PlayScene::update(float dt) { | |||
| 133 | // 4. キャラクターはカメラの向きを向く(肩越しの撃ち合いの決まり)。脚は移動の向きへ | 149 | // 4. キャラクターはカメラの向きを向く(肩越しの撃ち合いの決まり)。脚は移動の向きへ |
| 134 | // 4. the character faces where the camera looks (the over-the-shoulder shooter convention); the legs turn towards | 150 | // 4. the character faces where the camera looks (the over-the-shoulder shooter convention); the legs turn towards |
| 135 | // the movement | 151 | // the movement |
| 136 | if (!inspect) heading = approachAngle(heading, camera.yaw, approach(14.0f, dt)); | 152 | if (!inspect && alive) heading = approachAngle(heading, camera.yaw, approach(14.0f, dt)); |
| 137 | float speed = length(Vec3{velocity.x, 0.0f, velocity.z}); | 153 | updateLocomotion(pose, velocity, heading, body.grounded, dt, kWalkSpeed, kRunSpeed); |
| 138 | float legTarget = 0.0f, direction = 1.0f; | 154 | if (!inspect && alive) pose.aimPitch = camera.pitch; |
| 139 | if (speed > 0.2f) { | ||
| 140 | // 速度をキャラクターの座標へ:+Zが前、+Xが左(右手系で+Zを向くと+Xは左) / velocity in character space: +Z is | ||
| 141 | // forward, +X is LEFT (facing +Z in a right-handed system, +X is on the left) | ||
| 142 | Vec3 fwd = {std::sin(heading), 0.0f, -std::cos(heading)}, rgt = {std::cos(heading), 0.0f, std::sin(heading)}; | ||
| 143 | float mz = dot(velocity, fwd), mx = -dot(velocity, rgt); | ||
| 144 | legTarget = std::atan2(mx, mz); | ||
| 145 | if (std::fabs(legTarget) > radians(100.0f)) { // 後ろ歩き:脚は前を向いたまま逆に回す / walking backwards | ||
| 146 | legTarget = wrapAngle(legTarget - PI); | ||
| 147 | direction = -1.0f; | ||
| 148 | } | ||
| 149 | legTarget = std::clamp(legTarget, radians(-70.0f), radians(70.0f)); | ||
| 150 | } | ||
| 151 | pose.legYaw = approachAngle(pose.legYaw, legTarget, approach(10.0f, dt)); | ||
| 152 | // 歩きの周期は進んだ距離に比例:足が地面を滑らない / the walk cycle advances with distance: feet do not skate | ||
| 153 | float run = std::clamp((speed - kWalkSpeed) / (kRunSpeed - kWalkSpeed), 0.0f, 1.0f); | ||
| 154 | float cycleLength = 1.5f + 0.9f * run; // 1周期(2歩)のm / meters per cycle (two steps) | ||
| 155 | pose.walkPhase = std::fmod(pose.walkPhase + direction * 2.0f * PI * speed * dt / cycleLength, 2.0f * PI); | ||
| 156 | pose.walkAmount = std::clamp(speed / kWalkSpeed, 0.0f, 1.0f); | ||
| 157 | pose.stride = 1.0f + 0.5f * run; | ||
| 158 | if (!inspect) pose.aimPitch = camera.pitch; | ||
| 159 | // 空中の姿勢へなめらかに(着地で戻る) / blend into the airborne pose (and back on landing) | ||
| 160 | pose.air += ((body.grounded ? 0.0f : 1.0f) - pose.air) * approach(12.0f, dt); | ||
| 161 | if (!body.grounded) pose.walkAmount *= 1.0f - pose.air; | ||
| 162 | 155 | ||
| 163 | // 5. カメラ:CameraPivotソケットを追う / 5. the camera follows the CameraPivot socket | 156 | // 5. カメラ:CameraPivotソケットを追う / 5. the camera follows the CameraPivot socket |
| 164 | // (Kで当たり判定なしのカメラと比べられる) / (K compares with a camera that ignores the walls) | 157 | // (Kで当たり判定なしのカメラと比べられる) / (K compares with a camera that ignores the walls) |
| 158 | // 右ボタンで狙う:肩に寄り、視野を狭める(なめらかに) / right button aims: closer to the shoulder, narrower view | ||
| 159 | // (smoothly) | ||
| 160 | aimBlend += ((in.actionHeld("aim") && alive ? 1.0f : 0.0f) - aimBlend) * approach(12.0f, dt); | ||
| 161 | camera.distance = 3.6f - 1.2f * aimBlend; | ||
| 162 | camera.shoulderOffset = 0.7f + 0.15f * aimBlend; | ||
| 163 | camera.fovY = radians(55.0f - 13.0f * aimBlend); | ||
| 165 | camera.update(cameraPivot(), cameraCollision ? std::span<const Aabb>(g.level.solids) : std::span<const Aabb>(), dt); | 164 | camera.update(cameraPivot(), cameraCollision ? std::span<const Aabb>(g.level.solids) : std::span<const Aabb>(), dt); |
| 165 | |||
| 166 | // 6. 撃つ・込め直す(第38章) / 6. fire and reload (chapter 38) | ||
| 167 | fireTimer -= dt; | ||
| 168 | hitMarker -= dt; | ||
| 169 | if (reloadTime > 0.0f && (reloadTime -= dt) <= 0.0f) ammo = kMagazine; | ||
| 170 | if (alive && reloadTime <= 0.0f) { | ||
| 171 | if (in.actionPressed("reload") && ammo < kMagazine) reloadTime = kReloadTime; | ||
| 172 | else if (in.actionHeld("fire") && fireTimer <= 0.0f) { | ||
| 173 | if (ammo > 0) shoot(); | ||
| 174 | else reloadTime = kReloadTime; // 空なら自動で / automatically when empty | ||
| 175 | } | ||
| 176 | } | ||
| 177 | |||
| 178 | // 7. 敵(状態機械のAI)と、敵の射撃 / 7. the enemies (state-machine AI) and their shots | ||
| 179 | EnemySenses senses{g.level.solids, position, alive}; | ||
| 180 | for (Enemy &e : enemies) { | ||
| 181 | Vec3 aim; | ||
| 182 | if (e.update(dt, senses, rng, aim)) enemyFire(e, aim); | ||
| 183 | } | ||
| 184 | separateCharacters(); | ||
| 185 | effects.update(dt); | ||
| 186 | |||
| 187 | // 8. 体力:撃たれなければ4秒後から回復。倒れたら3秒後に出発点から(第39章で負けの画面になる) | ||
| 188 | // 8. health: regenerates from 4 s after the last hit. When down, back at the start after 3 s (chapter 39 turns this | ||
| 189 | // into the defeat screen) | ||
| 190 | hurt = std::fmax(hurt - dt, 0.0f); | ||
| 191 | sinceHurt += dt; | ||
| 192 | if (alive && sinceHurt > 4.0f) health = std::fmin(health + 12.0f * dt, 100.0f); | ||
| 193 | if (!alive && (deadTime += dt) > kRespawnTime) { | ||
| 194 | alive = true; | ||
| 195 | health = 100.0f; | ||
| 196 | ammo = kMagazine; | ||
| 197 | body.position = position = prevPosition = g.level.spawn; | ||
| 198 | body.velocity = {0.0f, 0.0f, 0.0f}; | ||
| 199 | camera.reset(cameraPivot(), g.level.solids); // カメラもすぐ出発点へ / the camera cuts to the spawn too | ||
| 200 | prevEye = camera.eye(); | ||
| 201 | prevForward = camera.forward(); | ||
| 202 | } | ||
| 203 | } | ||
| 204 | |||
| 205 | std::optional<RayHit> PlayScene::hitEnemy(const Ray &ray, float maxT, int &index, float &multiplier) const { | ||
| 206 | std::optional<RayHit> best; | ||
| 207 | for (size_t i = 0; i < enemies.size(); ++i) { | ||
| 208 | const Enemy &e = enemies[i]; | ||
| 209 | if (!e.alive()) continue; | ||
| 210 | for (const HitSphere &h : kHitSpheres) { | ||
| 211 | std::optional<RayHit> hit = | ||
| 212 | raySphere(ray, e.body.position + Vec3{0.0f, h.height, 0.0f}, h.radius, best ? best->t : maxT); | ||
| 213 | if (hit && (!best || hit->t < best->t)) { | ||
| 214 | best = hit; | ||
| 215 | index = static_cast<int>(i); | ||
| 216 | multiplier = h.damage; | ||
| 217 | } | ||
| 218 | } | ||
| 219 | } | ||
| 220 | return best; | ||
| 221 | } | ||
| 222 | |||
| 223 | void PlayScene::shoot() { | ||
| 224 | fireTimer = kFireInterval; | ||
| 225 | --ammo; | ||
| 226 | ++shotsFired; | ||
| 227 | // 銃口はモデルのソケット:今の姿勢を書いてから求める / the muzzle is a socket of the model: apply the current pose, | ||
| 228 | // then ask for it | ||
| 229 | applyPose(g.player, g.rifle, g.playerRig, pose); | ||
| 230 | Mat4 w = weaponMatrix(g.player, g.playerRig, characterMatrix(position, heading)); | ||
| 231 | int muzzleNode = g.rifle.findNode("Muzzle"); | ||
| 232 | Vec3 muzzle = origin(w * g.rifle.nodeTransform(muzzleNode)); | ||
| 233 | Vec3 barrel = normalize(Vec3{w.c[2].x, w.c[2].y, w.c[2].z}); | ||
| 234 | |||
| 235 | // 1. 画面の真ん中(照準)が指している所:カメラから前へのレイ。カメラと体の間の物に当たらないよう、 | ||
| 236 | // 体の深さから始める | ||
| 237 | // 1. what the screen center (the crosshair) points at: a ray forwards from the camera. It starts at the body's depth | ||
| 238 | // so that things between the camera and the character are not hit | ||
| 239 | Vec3 eye = camera.eye(), f = camera.forward(); | ||
| 240 | float t0 = std::fmax(dot(camera.shoulder() - eye, f), 0.0f); | ||
| 241 | Ray aimRay{eye + t0 * f, f}; | ||
| 242 | float range = 120.0f; | ||
| 243 | Vec3 target = aimRay.origin + range * f; | ||
| 244 | int index = -1; | ||
| 245 | float multiplier = 1.0f; | ||
| 246 | if (std::optional<RayHit> h = raycast(aimRay, g.level.solids, range)) target = aimRay.origin + h->t * f; | ||
| 247 | if (std::optional<RayHit> h = hitEnemy(aimRay, length(target - aimRay.origin), index, multiplier)) | ||
| 248 | target = aimRay.origin + h->t * f; | ||
| 249 | |||
| 250 | // 2. 弾は銃口からその点へ(拡散を足して)。銃口が壁の向こうに突き出ていたら、その壁に当たる | ||
| 251 | // 2. the bullet flies from the muzzle to that point (plus spread). If the muzzle pokes through a wall, the bullet | ||
| 252 | // hits that wall | ||
| 253 | float moving = length(Vec3{body.velocity.x, 0.0f, body.velocity.z}) > 0.5f ? 1.0f : 0.0f; | ||
| 254 | float spread = radians(1.4f - 1.0f * aimBlend + 1.2f * moving); | ||
| 255 | // 照準の点が銃の後ろ側(カメラだけ大きく回したとき)なら銃身の向きへ:弾が体を通って後ろへ飛ばない | ||
| 256 | // If the aim point is behind the gun (the camera alone was turned far), use the barrel: no bullets flying backwards | ||
| 257 | // through the body | ||
| 258 | Vec3 toTarget = normalize(target - muzzle); | ||
| 259 | Vec3 dir = spreadDirection(dot(toTarget, barrel) > 0.5f ? toTarget : barrel, spread, rng); | ||
| 260 | Ray bullet{muzzle, dir}; | ||
| 261 | Vec3 pivot = cameraPivot(); | ||
| 262 | float toMuzzle = length(muzzle - pivot); | ||
| 263 | std::optional<RayHit> blocked = raycast({pivot, (muzzle - pivot) / toMuzzle}, g.level.solids, toMuzzle); | ||
| 264 | std::optional<RayHit> wall = blocked ? std::optional<RayHit>(RayHit{0.0f, blocked->normal, blocked->index}) | ||
| 265 | : raycast(bullet, g.level.solids, range); | ||
| 266 | Vec3 start = blocked ? pivot + blocked->t * (muzzle - pivot) / toMuzzle : muzzle; | ||
| 267 | index = -1; | ||
| 268 | std::optional<RayHit> enemyHit = | ||
| 269 | blocked ? std::nullopt : hitEnemy(bullet, wall ? wall->t : range, index, multiplier); | ||
| 270 | |||
| 271 | effects.muzzleFlash(muzzle, barrel); | ||
| 272 | Vec3 end = start + range * dir; | ||
| 273 | if (enemyHit) { | ||
| 274 | end = muzzle + enemyHit->t * dir; | ||
| 275 | Enemy &e = enemies[static_cast<size_t>(index)]; | ||
| 276 | bool wasAlive = e.alive(); | ||
| 277 | e.alert(position, kDamage * multiplier); | ||
| 278 | if (wasAlive && !e.alive()) ++kills; | ||
| 279 | ++shotsHit; | ||
| 280 | hitMarker = 0.15f; | ||
| 281 | effects.sparks(end, -1.0f * dir, {6.0f, 0.9f, 0.4f}, 14, rng); // 赤い火花 / red sparks | ||
| 282 | } else if (wall) { | ||
| 283 | end = blocked ? start : muzzle + wall->t * dir; | ||
| 284 | effects.sparks(end, wall->normal, {5.0f, 3.2f, 1.2f}, 10, rng); // 黄色い火花 / yellow sparks | ||
| 285 | } | ||
| 286 | effects.tracer(muzzle, end, {5.0f, 3.6f, 1.6f}); | ||
| 287 | // 銃声:近くの敵が気づく / the noise: enemies nearby notice | ||
| 288 | for (Enemy &e : enemies) | ||
| 289 | if (length(e.body.position - position) < kHearing) e.alert(position); | ||
| 290 | } | ||
| 291 | |||
| 292 | void PlayScene::enemyFire(Enemy &e, Vec3 aim) { | ||
| 293 | applyPose(g.enemy, g.rifle, g.enemyRig, e.pose); | ||
| 294 | Mat4 w = weaponMatrix(g.enemy, g.enemyRig, e.matrix(1.0f)); | ||
| 295 | Vec3 muzzle = origin(w * g.rifle.nodeTransform(g.rifle.findNode("Muzzle"))); | ||
| 296 | // 敵の弾は外れやすく:動いているプレイヤーにはもっと / enemy shots spread more, even more against a moving player | ||
| 297 | float moving = length(Vec3{body.velocity.x, 0.0f, body.velocity.z}); | ||
| 298 | Vec3 dir = spreadDirection(normalize(aim - muzzle), radians(2.2f + 0.5f * moving), rng); | ||
| 299 | Ray bullet{muzzle, dir}; | ||
| 300 | float range = 60.0f; | ||
| 301 | std::optional<RayHit> wall = raycast(bullet, g.level.solids, range); | ||
| 302 | std::optional<RayHit> hit = alive ? rayCapsule(bullet, playerCapsule(), wall ? wall->t : range) : std::nullopt; | ||
| 303 | Vec3 end = muzzle + (hit ? hit->t : wall ? wall->t : range) * dir; | ||
| 304 | effects.muzzleFlash(muzzle, normalize(Vec3{w.c[2].x, w.c[2].y, w.c[2].z})); | ||
| 305 | effects.tracer(muzzle, end, {6.0f, 1.4f, 0.5f}); | ||
| 306 | if (hit) { | ||
| 307 | hurtPlayer(kEnemyDamage); | ||
| 308 | effects.sparks(end, -1.0f * dir, {6.0f, 0.9f, 0.4f}, 8, rng); | ||
| 309 | } else if (wall) { | ||
| 310 | effects.sparks(end, wall->normal, {5.0f, 3.2f, 1.2f}, 8, rng); | ||
| 311 | } | ||
| 312 | } | ||
| 313 | |||
| 314 | void PlayScene::hurtPlayer(float damage) { | ||
| 315 | if (!alive) return; | ||
| 316 | health -= damage; | ||
| 317 | hurt = 0.35f; | ||
| 318 | sinceHurt = 0.0f; | ||
| 319 | if (health <= 0.0f) { | ||
| 320 | health = 0.0f; | ||
| 321 | alive = false; | ||
| 322 | deadTime = 0.0f; | ||
| 323 | ++deaths; | ||
| 324 | reloadTime = 0.0f; | ||
| 325 | } | ||
| 326 | } | ||
| 327 | |||
| 328 | void PlayScene::separateCharacters() { | ||
| 329 | // 体どうしは水平に押し合う(円と円)。押した後の壁へのめり込みは次のステップのmoveが直す | ||
| 330 | // Bodies push each other apart horizontally (circle against circle); any wall penetration this causes is fixed by | ||
| 331 | // the next step's move | ||
| 332 | std::vector<CharacterBody *> bodies = {&body}; | ||
| 333 | for (Enemy &e : enemies) | ||
| 334 | if (e.alive()) bodies.push_back(&e.body); | ||
| 335 | for (size_t i = 0; i < bodies.size(); ++i) | ||
| 336 | for (size_t j = i + 1; j < bodies.size(); ++j) { | ||
| 337 | Vec3 d = bodies[j]->position - bodies[i]->position; | ||
| 338 | d.y = 0.0f; | ||
| 339 | float dist = length(d), minDist = bodies[i]->radius + bodies[j]->radius; | ||
| 340 | if (dist >= minDist || dist < 1e-5f) continue; | ||
| 341 | Vec3 push = (0.5f * (minDist - dist) / dist) * d; | ||
| 342 | bodies[i]->position = bodies[i]->position - push; | ||
| 343 | bodies[j]->position = bodies[j]->position + push; | ||
| 344 | } | ||
| 345 | position = body.position; | ||
| 346 | } | ||
| 347 | |||
| 348 | void PlayScene::logState() const { | ||
| 349 | Vec3 eye = camera.eye(); | ||
| 350 | printf("log frame %d pos (%.2f %.2f %.2f) eye (%.3f %.3f %.3f) yaw %.4f pitch %.4f hp %.0f ammo %d |", g.frame, | ||
| 351 | position.x, position.y, position.z, eye.x, eye.y, eye.z, camera.yaw, camera.pitch, health, ammo); | ||
| 352 | for (const Enemy &e : enemies) | ||
| 353 | printf(" %s (%.2f %.2f %.2f) %.0f%s |", enemyStateName(e.state), e.body.position.x, e.body.position.y, | ||
| 354 | e.body.position.z, e.health, e.seesPlayer ? " sees" : ""); | ||
| 355 | printf("\n"); | ||
| 166 | } | 356 | } |
| 167 | 357 | ||
| 168 | void PlayScene::drawCharacters(const Shader &shader, bool depthOnly, Vec3 eye) { | 358 | void PlayScene::drawCharacters(const Shader &shader, bool depthOnly, Vec3 eye) { |
| 169 | // 前のステップと今のステップの間をdrawAlphaで補間(第26章) / interpolate between the last and the current step | 359 | // 前のステップと今のステップの間をdrawAlphaで補間(第26章) / interpolate between the last and the current step |
| 170 | // with drawAlpha (chapter 26) | 360 | // with drawAlpha (chapter 26) |
| 171 | Mat4 m = characterMatrix(lerp(prevPosition, position, drawAlpha), approachAngle(prevHeading, heading, drawAlpha)); | 361 | Mat4 m = characterMatrix(lerp(prevPosition, position, drawAlpha), approachAngle(prevHeading, heading, drawAlpha)); |
| 362 | if (!alive) { // 倒れる(敵と同じ) / falling over (like the enemies) | ||
| 363 | float t = std::clamp(deadTime / 0.6f, 0.0f, 1.0f), fall = t * t * (3.0f - 2.0f * t); | ||
| 364 | m = m * translate({0.0f, 0.15f * fall, 0.0f}) * rotateX(-0.5f * PI * fall); | ||
| 365 | } | ||
| 172 | if (posing) applyPose(g.player, g.rifle, g.playerRig, pose); | 366 | if (posing) applyPose(g.player, g.rifle, g.playerRig, pose); |
| 173 | else g.player.nodes = g.playerRig.rest; // P:読み込んだままの姿勢 / P: the pose as loaded | 367 | else g.player.nodes = g.playerRig.rest; // P:読み込んだままの姿勢 / P: the pose as loaded |
| 174 | Mat4 w = weaponMatrix(g.player, g.playerRig, m); | 368 | Mat4 w = weaponMatrix(g.player, g.playerRig, m); |
| @@ -181,6 +375,34 @@ void PlayScene::drawCharacters(const Shader &shader, bool depthOnly, Vec3 eye) { | |||
| 181 | } | 375 | } |
| 182 | } | 376 | } |
| 183 | 377 | ||
| 378 | void PlayScene::drawEnemies(const Shader &shader, bool depthOnly, Vec3 eye, const Frustum *frustum) { | ||
| 379 | // 一つのenemy.glbを全員で使う:描く直前にその敵の姿勢を書く / all enemies share one enemy.glb: write each one's pose | ||
| 380 | // right before drawing it | ||
| 381 | for (const Enemy &e : enemies) { | ||
| 382 | Mat4 m = e.matrix(drawAlpha); | ||
| 383 | // カリングの球:体の真ん中(足元から0.9 m)を姿勢の行列で動かすので、倒れて横になっても体を包む | ||
| 384 | // The culling sphere: the body's middle (0.9 m above the feet) goes through the pose's matrix, so it still | ||
| 385 | // encloses the body once it lies on the ground | ||
| 386 | Vec4 middle = m * Vec4{0.0f, 0.9f, 0.0f, 1.0f}; | ||
| 387 | if (frustum && !frustum->sphereVisible({middle.x, middle.y, middle.z}, 1.3f)) continue; | ||
| 388 | applyPose(g.enemy, g.rifle, g.enemyRig, e.pose); | ||
| 389 | Mat4 w = weaponMatrix(g.enemy, g.enemyRig, m); | ||
| 390 | if (depthOnly) { | ||
| 391 | g.enemy.drawDepth(shader, m, g.renderer.white); | ||
| 392 | g.rifle.drawDepth(shader, w, g.renderer.white); | ||
| 393 | continue; | ||
| 394 | } | ||
| 395 | // 撃たれた光:pbr.fragがベースカラーに掛けるuTint(phong.vert → vTint)を一瞬明るい赤に | ||
| 396 | // The hit flash: uTint (phong.vert → vTint, which pbr.frag multiplies into the base color) becomes a bright red | ||
| 397 | // for a moment | ||
| 398 | float f = e.flash / 0.12f; | ||
| 399 | shader.set("uTint", Vec3{1.0f + 7.0f * f, 1.0f + 1.5f * f, 1.0f + 1.0f * f}); | ||
| 400 | g.enemy.draw(shader, m, g.renderer.white, ModelPass::Opaque, eye, Shading::Pbr); | ||
| 401 | shader.set("uTint", Vec3{1.0f, 1.0f, 1.0f}); | ||
| 402 | g.rifle.draw(shader, w, g.renderer.white, ModelPass::Opaque, eye, Shading::Pbr); | ||
| 403 | } | ||
| 404 | } | ||
| 405 | |||
| 184 | void PlayScene::drawDebugBoxes() { | 406 | void PlayScene::drawDebugBoxes() { |
| 185 | // 当たり判定の箱を線で(unlit、HDRの色) / the collision boxes as lines (unlit, HDR color) | 407 | // 当たり判定の箱を線で(unlit、HDRの色) / the collision boxes as lines (unlit, HDR color) |
| 186 | const Shader &s = *g.renderer.unlit; | 408 | const Shader &s = *g.renderer.unlit; |
| @@ -223,6 +445,38 @@ void PlayScene::drawDebugBoxes() { | |||
| 223 | marker(m * g.player.nodeTransform(rig.hand[1]), {2.0f, 2.0f, 0.0f}); | 445 | marker(m * g.player.nodeTransform(rig.hand[1]), {2.0f, 2.0f, 0.0f}); |
| 224 | int muzzle = g.rifle.findNode("Muzzle"); | 446 | int muzzle = g.rifle.findNode("Muzzle"); |
| 225 | if (muzzle >= 0) marker(weaponMatrix(g.player, rig, m) * g.rifle.nodeTransform(muzzle), {3.0f, 0.1f, 0.1f}); | 447 | if (muzzle >= 0) marker(weaponMatrix(g.player, rig, m) * g.rifle.nodeTransform(muzzle), {3.0f, 0.1f, 0.1f}); |
| 448 | // 敵のAI:頭の上に状態の色(緑 巡回、黄 気づいた・探す、橙 追う、赤 撃つ)、巡回の点、見えているときは視線 | ||
| 449 | // The enemy AI: a state color above the head (green patrol, yellow alert / search, orange chase, red attack), | ||
| 450 | // the patrol points, and the line of sight while it sees the player | ||
| 451 | for (const Enemy &e : enemies) { | ||
| 452 | if (!e.alive()) continue; | ||
| 453 | Vec3 p = lerp(e.prevPosition, e.body.position, drawAlpha); | ||
| 454 | Vec3 c = e.state == EnemyState::Patrol ? Vec3{0.2f, 2.0f, 0.3f} | ||
| 455 | : e.state == EnemyState::Chase ? Vec3{3.0f, 0.25f, 0.02f} | ||
| 456 | : e.state == EnemyState::Attack ? Vec3{3.0f, 0.1f, 0.1f} | ||
| 457 | : Vec3{2.5f, 2.2f, 0.2f}; | ||
| 458 | s.set("uColor", c); | ||
| 459 | s.set("uModel", translate(p + Vec3{0.0f, 2.2f, 0.0f}) * scale({0.2f, 0.2f, 0.2f})); | ||
| 460 | g.renderer.cube.draw(); | ||
| 461 | // 当たり判定の球(ray–球):頭・胸・腰・脚 / the hit spheres (ray–sphere): head, chest, hips, legs | ||
| 462 | glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); | ||
| 463 | s.set("uColor", Vec3{2.0f, 0.5f, 1.6f}); | ||
| 464 | for (const HitSphere &h : kHitSpheres) { | ||
| 465 | 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})); | ||
| 466 | g.renderer.sphere.draw(); | ||
| 467 | } | ||
| 468 | glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); | ||
| 469 | s.set("uColor", Vec3{0.2f, 1.0f, 0.3f}); | ||
| 470 | for (Vec3 q : e.patrol) { | ||
| 471 | s.set("uModel", translate(q + Vec3{0.0f, 0.1f, 0.0f}) * scale({0.25f, 0.2f, 0.25f})); | ||
| 472 | g.renderer.cube.draw(); | ||
| 473 | } | ||
| 474 | if (e.seesPlayer) { | ||
| 475 | s.set("uColor", Vec3{3.0f, 0.3f, 0.2f}); | ||
| 476 | s.set("uModel", beamMatrix(p + Vec3{0.0f, 1.6f, 0.0f}, feet + Vec3{0.0f, 1.3f, 0.0f}, 0.03f)); | ||
| 477 | g.renderer.cube.draw(); | ||
| 478 | } | ||
| 479 | } | ||
| 226 | glEnable(GL_DEPTH_TEST); | 480 | glEnable(GL_DEPTH_TEST); |
| 227 | glEnable(GL_CULL_FACE); | 481 | glEnable(GL_CULL_FACE); |
| 228 | } | 482 | } |
| @@ -249,7 +503,9 @@ void PlayScene::draw(float alpha) { | |||
| 249 | LightSet lights; | 503 | LightSet lights; |
| 250 | lights.ambient = {0.20f, 0.24f, 0.33f}; | 504 | lights.ambient = {0.20f, 0.24f, 0.33f}; |
| 251 | lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {2.6f, 2.45f, 2.2f}}; | 505 | lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {2.6f, 2.45f, 2.2f}}; |
| 506 | effects.addLights(lights); // 銃口の光が周りを照らす / muzzle flashes light their surroundings | ||
| 252 | r.beginFrame(view, lights); | 507 | r.beginFrame(view, lights); |
| 508 | if (logging) logState(); | ||
| 253 | 509 | ||
| 254 | // カメラが体の中に入ったら(壁際で寄せられて)自分を描かない:頭や胴の内側が映る。肩へずらしているので、 | 510 | // カメラが体の中に入ったら(壁際で寄せられて)自分を描かない:頭や胴の内側が映る。肩へずらしているので、 |
| 255 | // 距離が短いだけでは入らない:体の軸からの水平距離で決める | 511 | // 距離が短いだけでは入らない:体の軸からの水平距離で決める |
| @@ -264,6 +520,7 @@ void PlayScene::draw(float alpha) { | |||
| 264 | if (r.beginShadows()) { | 520 | if (r.beginShadows()) { |
| 265 | shadowStats = g.level.drawShadows(*r.shadow, r.white, r.lightFrustum()); | 521 | shadowStats = g.level.drawShadows(*r.shadow, r.white, r.lightFrustum()); |
| 266 | drawCharacters(*r.shadow, true, view.eye); | 522 | drawCharacters(*r.shadow, true, view.eye); |
| 523 | drawEnemies(*r.shadow, true, view.eye, &r.lightFrustum()); | ||
| 267 | r.endShadows(); | 524 | r.endShadows(); |
| 268 | } | 525 | } |
| 269 | // 2. 場面 / 2. the scene | 526 | // 2. 場面 / 2. the scene |
| @@ -271,14 +528,20 @@ void PlayScene::draw(float alpha) { | |||
| 271 | // 手前の物から:キャラクター → レベル(床は最後) / nearest first: the character → the level (floor last) | 528 | // 手前の物から:キャラクター → レベル(床は最後) / nearest first: the character → the level (floor last) |
| 272 | r.pbr->use(); | 529 | r.pbr->use(); |
| 273 | if (drawPlayer) drawCharacters(*r.pbr, false, view.eye); | 530 | if (drawPlayer) drawCharacters(*r.pbr, false, view.eye); |
| 531 | drawEnemies(*r.pbr, false, view.eye, &r.viewFrustum()); | ||
| 274 | r.pbrInstanced->use(); | 532 | r.pbrInstanced->use(); |
| 275 | // F4:カリングなし(全部の部品をインスタンスのバッファへ)と比べる。平面(0, 0, 0, 1)なら全部が内側 | 533 | // F4:カリングなし(全部の部品をインスタンスのバッファへ)と比べる。平面(0, 0, 0, 1)なら全部が内側 |
| 276 | // F4: compare with no culling (every piece goes into the instance buffers). Planes (0, 0, 0, 1) keep everything in | 534 | // F4: compare with no culling (every piece goes into the instance buffers). Planes (0, 0, 0, 1) keep everything in |
| 277 | Frustum everything; | 535 | Frustum everything; |
| 278 | for (Vec4 &plane : everything.planes) plane = {0.0f, 0.0f, 0.0f, 1.0f}; | 536 | for (Vec4 &plane : everything.planes) plane = {0.0f, 0.0f, 0.0f, 1.0f}; |
| 279 | levelStats = g.level.draw(*r.pbrInstanced, r.white, culling ? r.viewFrustum() : everything); | 537 | levelStats = g.level.draw(*r.pbrInstanced, r.white, culling ? r.viewFrustum() : everything); |
| 280 | if (g.showBoxes) drawDebugBoxes(); | 538 | effects.drawStreaks(r); // トレーサーと銃口の光(HDRで明るい → ブルーム) / tracers and flashes (bright HDR → bloom) |
| 281 | r.drawSky(); | 539 | r.drawSky(); |
| 540 | // デバッグ表示は空の後:深度テストなしで描く印(頭の上の状態の立方体など)を空が上書きしない様に | ||
| 541 | // The debug view after the sky, so the sky does not paint over the markers drawn without the depth test (such as | ||
| 542 | // the state cubes above the heads) | ||
| 543 | if (g.showBoxes) drawDebugBoxes(); | ||
| 544 | effects.drawParticles(); // 火花:空の後、加算で / sparks: after the sky, additive | ||
| 282 | r.endScene(); | 545 | r.endScene(); |
| 283 | // 3. 後処理 → 画面 / 3. post-processing → the screen | 546 | // 3. 後処理 → 画面 / 3. post-processing → the screen |
| 284 | r.present(g.window.width(), g.window.height()); | 547 | r.present(g.window.width(), g.window.height()); |
| @@ -294,7 +557,8 @@ void PlayScene::drawUi(float /*alpha*/) { | |||
| 294 | "CPU frame {:.1f} ms (wall clock) llvmpipe raster: shadow {:.1f} ms, scene {:.1f} ms, post {:.1f} ms\n" | 557 | "CPU frame {:.1f} ms (wall clock) llvmpipe raster: shadow {:.1f} ms, scene {:.1f} ms, post {:.1f} ms\n" |
| 295 | "level pieces drawn {}/{} ({} draw calls) shadow casters {} ({} draw calls) shadow texel {:.1f} mm\n" | 558 | "level pieces drawn {}/{} ({} draw calls) shadow casters {} ({} draw calls) shadow texel {:.1f} mm\n" |
| 296 | "camera distance {:.2f} m{}{} collision boxes {} culling {} scene fragments {:.2f} M\n" | 559 | "camera distance {:.2f} m{}{} collision boxes {} culling {} scene fragments {:.2f} M\n" |
| 297 | "body: {} {}{}{} contacts {} y {:.2f} m velocity ({:.1f}, {:.1f}, {:.1f}) jumps {} wall slide {}", | 560 | "body: {} {}{}{} contacts {} y {:.2f} m velocity ({:.1f}, {:.1f}, {:.1f}) jumps {} wall slide {}\n" |
| 561 | "particles {} kills {} deaths {}", | ||
| 298 | g.frameMs, r.timings.shadowMs, r.timings.sceneMs, r.timings.postMs, levelStats.visible, levelStats.total, | 562 | g.frameMs, r.timings.shadowMs, r.timings.sceneMs, r.timings.postMs, levelStats.visible, levelStats.total, |
| 299 | levelStats.drawCalls, shadowStats.visible, shadowStats.drawCalls, r.shadowTexelMm(), | 563 | levelStats.drawCalls, shadowStats.visible, shadowStats.drawCalls, r.shadowTexelMm(), |
| 300 | camera.currentDistance(), camera.blocked() ? " (pulled in by a wall)" : "", | 564 | camera.currentDistance(), camera.blocked() ? " (pulled in by a wall)" : "", |
| @@ -302,12 +566,46 @@ void PlayScene::drawUi(float /*alpha*/) { | |||
| 302 | static_cast<double>(r.timings.sceneFragments) / 1e6, body.grounded ? "grounded" : "airborne", | 566 | static_cast<double>(r.timings.sceneFragments) / 1e6, body.grounded ? "grounded" : "airborne", |
| 303 | body.hitWall ? "wall " : "", body.steppedUp ? "stepped-up " : "", body.snappedDown ? "snapped-down " : "", | 567 | body.hitWall ? "wall " : "", body.steppedUp ? "stepped-up " : "", body.snappedDown ? "snapped-down " : "", |
| 304 | body.contacts, body.position.y, body.velocity.x, body.velocity.y, body.velocity.z, jumps, | 568 | body.contacts, body.position.y, body.velocity.x, body.velocity.y, body.velocity.z, jumps, |
| 305 | body.slide ? "on" : "OFF (L)"); | 569 | body.slide ? "on" : "OFF (L)", effects.particleCount(), kills, deaths); |
| 306 | batch.drawRect({0.0f, 0.0f, 1280.0f, 88.0f}, {0.0f, 0.0f, 0.0f, 0.45f}); | 570 | batch.drawRect({0.0f, 0.0f, 1280.0f, 108.0f}, {0.0f, 0.0f, 0.0f, 0.45f}); |
| 307 | g.ui.draw(batch, lines, {10.0f, 6.0f}, small); | 571 | g.ui.draw(batch, lines, {10.0f, 6.0f}, small); |
| 308 | } | 572 | } |
| 309 | g.ui.draw(batch, "WASD 移動 / move マウス / mouse: look Shift 走る / run Space 跳ぶ / jump Q 肩 / shoulder " | 573 | // 照準(第38章の簡単なもの。第39章でHUDになる):真ん中の点と4本の線。拡散が大きいほど開く。当てると赤く |
| 310 | "B 箱 / boxes F3", | 574 | // The crosshair (chapter 38's simple one; chapter 39 makes it a HUD): a center dot and four lines that open with the |
| 575 | // spread; red on a hit | ||
| 576 | if (alive) { | ||
| 577 | float moving = length(Vec3{body.velocity.x, 0.0f, body.velocity.z}) > 0.5f ? 1.0f : 0.0f; | ||
| 578 | float gap = 5.0f + 9.0f * (1.0f - aimBlend) + 8.0f * moving; | ||
| 579 | Vec4 c = hitMarker > 0.0f ? Vec4{1.0f, 0.25f, 0.2f, 1.0f} : Vec4{1.0f, 1.0f, 1.0f, 0.9f}; | ||
| 580 | batch.drawRect({639.0f, 359.0f, 2.0f, 2.0f}, c); | ||
| 581 | batch.drawRect({639.0f, 360.0f - gap - 8.0f, 2.0f, 8.0f}, c); | ||
| 582 | batch.drawRect({639.0f, 360.0f + gap, 2.0f, 8.0f}, c); | ||
| 583 | batch.drawRect({640.0f - gap - 8.0f, 359.0f, 8.0f, 2.0f}, c); | ||
| 584 | batch.drawRect({640.0f + gap, 359.0f, 8.0f, 2.0f}, c); | ||
| 585 | } | ||
| 586 | // 撃たれたら画面の縁を赤く / a red screen edge when hit | ||
| 587 | if (hurt > 0.0f) { | ||
| 588 | Vec4 red = {0.8f, 0.0f, 0.0f, 0.5f * hurt / 0.35f}; | ||
| 589 | batch.drawRect({0.0f, 0.0f, 1280.0f, 40.0f}, red); | ||
| 590 | batch.drawRect({0.0f, 680.0f, 1280.0f, 40.0f}, red); | ||
| 591 | batch.drawRect({0.0f, 40.0f, 40.0f, 640.0f}, red); | ||
| 592 | batch.drawRect({1240.0f, 40.0f, 40.0f, 640.0f}, red); | ||
| 593 | } | ||
| 594 | int left = 0; | ||
| 595 | for (const Enemy &e : enemies) left += e.alive() ? 1 : 0; | ||
| 596 | std::string status = std::format("体力 / HP {:3.0f} 弾 / AMMO {:2d}/{}{} 敵 / ENEMIES {}/{} hits {}/{}", health, | ||
| 597 | ammo, kMagazine, reloadTime > 0.0f ? " (装填 / reloading)" : "", left, | ||
| 598 | enemies.size(), shotsHit, shotsFired); | ||
| 599 | g.ui.draw(batch, status, {20.0f, 660.0f}, {.color = {1.0f, 1.0f, 1.0f, 0.95f}, .scale = 1.0f, | ||
| 600 | .shadow = {0.0f, 0.0f, 0.0f, 0.9f}}); | ||
| 601 | if (!alive) | ||
| 602 | g.ui.draw(batch, "倒れた / DOWN", {640.0f, 300.0f}, {.color = {1.0f, 0.3f, 0.25f, 1.0f}, .scale = 3.0f, | ||
| 603 | .align = TextAlign::Centre, .shadow = {0, 0, 0, 0.9f}}); | ||
| 604 | else if (left == 0) | ||
| 605 | g.ui.draw(batch, "敵を全部倒した / ALL ENEMIES DOWN", {640.0f, 300.0f}, | ||
| 606 | {.color = {1.0f, 0.85f, 0.3f, 1.0f}, .scale = 2.0f, .align = TextAlign::Centre, .shadow = {0, 0, 0, 0.9f}}); | ||
| 607 | g.ui.draw(batch, "LMB 撃つ / fire RMB 狙う / aim R 装填 / reload Space 跳ぶ / jump Shift 走る / run " | ||
| 608 | "Q 肩 / shoulder", | ||
| 311 | {640.0f, 694.0f}, {.color = {1.0f, 1.0f, 1.0f, 0.7f}, .align = TextAlign::Centre, | 609 | {640.0f, 694.0f}, {.color = {1.0f, 1.0f, 1.0f, 0.7f}, .align = TextAlign::Centre, |
| 312 | .shadow = {0.0f, 0.0f, 0.0f, 0.8f}}); | 610 | .shadow = {0.0f, 0.0f, 0.0f, 0.8f}}); |
| 313 | batch.end(); | 611 | batch.end(); |
ファイル: a/games/tps/src/play_scene.hh | b/games/tps/src/play_scene.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,14 +1,20 @@ | |||
| 1 | // 遊ぶシーン(第36章):レベルの中をキャラクターで歩き回る。カメラの向きに対して動き、カメラは壁を避けて付いてくる | 1 | // 遊ぶシーン(第36〜38章):レベルの中をキャラクターで歩き回り(カメラに対する移動、壁を避けるカメラ、第36章)、 |
| 2 | // The play scene (chapter 36): walk a character around the level. It moves relative to the camera, and the camera | 2 | // 跳び、壁をずり(第37章)、撃ち合う(第38章) |
| 3 | // follows without entering walls | 3 | // The play scene (chapters 36-38): walk a character around the level (camera-relative movement, a camera that avoids |
| 4 | // walls, chapter 36), jump and slide along walls (chapter 37), and fight (chapter 38) | ||
| 4 | #pragma once | 5 | #pragma once |
| 5 | 6 | ||
| 6 | #include "character_body.hh" | 7 | #include "character_body.hh" |
| 8 | #include "effects.hh" | ||
| 9 | #include "enemy.hh" | ||
| 7 | #include "game.hh" | 10 | #include "game.hh" |
| 8 | #include "third_person_camera.hh" | 11 | #include "third_person_camera.hh" |
| 9 | 12 | ||
| 13 | #include "engine/rng.hh" | ||
| 10 | #include "engine/scene.hh" | 14 | #include "engine/scene.hh" |
| 11 | 15 | ||
| 16 | #include <vector> | ||
| 17 | |||
| 12 | class PlayScene : public Scene { | 18 | class PlayScene : public Scene { |
| 13 | public: | 19 | public: |
| 14 | explicit PlayScene(Game &game); | 20 | explicit PlayScene(Game &game); |
| @@ -22,8 +28,19 @@ private: | |||
| 22 | // 見えるもの全部(影のパスと場面のパスで同じ物を描く) / everything visible (the shadow and the scene pass draw | 28 | // 見えるもの全部(影のパスと場面のパスで同じ物を描く) / everything visible (the shadow and the scene pass draw |
| 23 | // the same things) | 29 | // the same things) |
| 24 | void drawCharacters(const Shader &shader, bool depthOnly, Vec3 eye); | 30 | void drawCharacters(const Shader &shader, bool depthOnly, Vec3 eye); |
| 31 | void drawEnemies(const Shader &shader, bool depthOnly, Vec3 eye, const Frustum *frustum); | ||
| 25 | void drawDebugBoxes(); | 32 | void drawDebugBoxes(); |
| 26 | Vec3 cameraPivot() const; | 33 | Vec3 cameraPivot() const; |
| 34 | // 射撃(第38章) / shooting (chapter 38) | ||
| 35 | void shoot(); | ||
| 36 | void enemyFire(Enemy &enemy, Vec3 aim); | ||
| 37 | // 一番近い敵の当たり(ray–球):敵の番号と、当たった球のダメージの倍率 / the nearest enemy hit (ray–sphere): the | ||
| 38 | // enemy's index and the hit sphere's damage multiplier | ||
| 39 | std::optional<RayHit> hitEnemy(const Ray &ray, float maxT, int &index, float &multiplier) const; | ||
| 40 | Capsule playerCapsule() const { return body.capsule(); } | ||
| 41 | void hurtPlayer(float damage); | ||
| 42 | void separateCharacters(); | ||
| 43 | void logState() const; | ||
| 27 | 44 | ||
| 28 | Game &g; | 45 | Game &g; |
| 29 | ThirdPersonCamera camera; | 46 | ThirdPersonCamera camera; |
| @@ -48,5 +65,22 @@ private: | |||
| 48 | bool overhead = false; // O:上からの視点 / view from above | 65 | bool overhead = false; // O:上からの視点 / view from above |
| 49 | bool posing = true; // P:手続き的な姿勢 / procedural pose | 66 | bool posing = true; // P:手続き的な姿勢 / procedural pose |
| 50 | float drawAlpha = 1.0f; // drawの補間の割合 / draw's interpolation factor | 67 | float drawAlpha = 1.0f; // drawの補間の割合 / draw's interpolation factor |
| 68 | bool logging = false; // F8 | ||
| 69 | |||
| 70 | // 戦い(第38章) / combat (chapter 38) | ||
| 71 | std::vector<Enemy> enemies; | ||
| 72 | Effects effects; | ||
| 73 | Rng rng{38}; // 決まった種:同じ入力なら毎回同じ戦い / fixed seed: the same input gives the same fight | ||
| 74 | float health = 100.0f; | ||
| 75 | float hurt = 0.0f; // 撃たれた赤い光の残り / remaining red hurt flash | ||
| 76 | float sinceHurt = 10.0f; // 最後に撃たれてから(回復用) / time since the last hit (for regeneration) | ||
| 77 | bool alive = true; | ||
| 78 | float deadTime = 0.0f; | ||
| 79 | static constexpr int kMagazine = 24; | ||
| 80 | int ammo = kMagazine; | ||
| 81 | float fireTimer = 0.0f, reloadTime = 0.0f; | ||
| 82 | float aimBlend = 0.0f; // 0 = 腰だめ、1 = 狙う(右ボタン) / 0 = hip fire, 1 = aiming (right button) | ||
| 83 | float hitMarker = 0.0f; // 当てたときの印の残り / remaining hit-marker time | ||
| 84 | int shotsFired = 0, shotsHit = 0, kills = 0, deaths = 0; | ||
| 51 | LevelDrawStats levelStats, shadowStats; | 85 | LevelDrawStats levelStats, shadowStats; |
| 52 | }; | 86 | }; |
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。