38. Third-Person Shooter Part 3: Shooting and Enemies

After chapter 37 our soldier has a body: a capsule that collides with the level, slides along walls, climbs stairs and jumps.
But the arena is empty, and the rifle is only decoration.
This chapter makes it a shooter.

The player shoots with rays: one from the camera finds what the crosshair covers, and a second one from the rifle's muzzle decides what the bullet really hits.
Five enemies patrol the arena, notice you with their eyes and ears, react, shoot back, chase you and look for you when they lose you, all driven by a small state machine.
And every shot has to look and feel like one: a muzzle flash that lights up the wall next to you, a bright tracer that blooms, sparks, a red flash on the enemy you hit and a red screen edge when you get hit.

Most of the chapter is game code and geometry: the ray tests against the level, the enemies' spheres and the player's capsule, worked through with numbers, random directions in a cone, and the AI.
The new OpenGL part is small but useful: a particle renderer that draws instanced billboards without any vertex buffer, with additive blending and without depth writes.

38.1 What we're building

Here is the second hit on the guard on the platform, a few frames into the fight: the tracer from the muzzle into the guard, red sparks where the bullet hit, and the guard glowing from the hit flash:

The view over the right shoulder of the player at the start of the arena. A thin bright tracer runs from the rifle up the stairs to a red enemy soldier standing on the platform, who glows bright red; small sparks around the hit. A second enemy stands far right. The status line at the bottom reads HP 100, AMMO 22 of 24, ENEMIES 5 of 5, hits 2 of 2

The clip is the whole scripted fight, 11 seconds: the guard on the platform, then up the stairs, the guard in front of the north stairs, the one coming down the east lane, a reload, the one running round the west corner, and the last one at the north cover.
The script and the enemies' random numbers are fixed, so this exact fight replays every time (38.14):

The controls of chapters 36 and 37 stay, and four are new:

  • Left mouse button: fire (hold for automatic fire)
  • Right mouse button: aim (the camera moves closer over the shoulder, the view narrows, the spread shrinks, and you walk slower)
  • R: reload
  • F8: print the state of the game every frame to the terminal (for writing scripts)
  • B now also shows the enemies' state, their hit spheres, patrol points and line of sight

As in the previous chapters, everything happens inside games/tps/:

  • src/collision3d.hh, src/collision3d.cc: raySphere and rayCapsule join chapter 36's rayAabb
  • src/enemy.hh, src/enemy.cc (new): Enemy with its senses and its state machine
  • src/effects.hh, src/effects.cc (new): muzzle flashes, tracers and sparks
  • shaders/particle.vert, shaders/particle.frag (new): the spark billboards
  • src/angles.hh (new): angle helpers that used to be static functions in play_scene.cc
  • src/character.hh, src/character.cc: updateLocomotion, moved out of play_scene.cc so that enemies walk with the same code
  • src/level.hh, src/level.cc, assets/levels/arena.level: the enemy command and five enemies
  • assets/models/enemy.glb (new), from the same script of mine as the player (the finished files are in the chapter's ZIP and in ch38/ of the assets ZIP)
  • src/play_scene.hh, src/play_scene.cc: shooting, enemies, health, ammo, effects and the UI
  • src/game.hh, src/main.cc: the enemy model and the actions fire, aim and reload
  • CMakeLists.txt, README.md, assets/LICENSE.txt

The two new sources go into the game's 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 Five enemies in the level file

The enemies are part of the level, so they're placed in arena.level like everything else.
The new command takes a start position, a yaw in degrees (0 faces north, −Z, like spawn) and any number of patrol points:

# 敵(第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

The loader reads the four numbers and then pairs of x and z until the line ends; an odd number of values (an x without its z) or anything that isn't a number stops loading with the file name and line, like every other mistake in the file.
Patrol points get the start's height, which is what puts the third enemy's route on top of the 1.5 m platform.
An enemy without patrol points gets its own position as the only point, so it stands guard:

    } 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);

Enemy Start Facing Patrol Where
0 (−14, 0, −13) south 10 m north–south the west lane
1 (−6, 0, −14.5) east 12 m east–west the north lane
2 (0, 1.5, −3) south 6 m north–south on the platform, looking at the spawn
3 (13.5, 0, −9) south 16 m north–south the east lane
4 (−6, 0, −8.5) east 12 m east–west in front of the north stairs

The model is enemy.glb, made by the same generator script as player.glb in chapter 36: dark red armor, a red emissive visor, a crest and shoulder spikes, but the same node names.
That's the whole trick for animating them: CharacterRig::find finds the same joints, applyPose writes the same walk cycle and aim pitch, and the arms use the same two-bone IK onto the same rifle.
The walk-cycle code moved from play_scene.cc into character.cc as updateLocomotion(pose, velocity, heading, grounded, dt, walkSpeed, runSpeed), so player and enemies call one function.

There is one Model for all five enemies.
In chapter 36 we saw that a model's nodes are its pose; each character keeps its own CharacterPose and writes it into the shared model right before it's drawn.
Five enemies therefore cost five pose writes per pass and no extra GPU memory.
The same applies when we need an enemy's muzzle position to shoot: write the pose first, then ask for the socket.

38.3 Rays against the level

Everything in this chapter that "looks" uses a ray: the crosshair, the bullet, an enemy's line of sight.
A ray is a start point and a direction,

𝐩(t)=𝐨+t𝐝,t≥0,‖𝐝‖=1

the same ray as the camera rays of GLSL chapter 14 and the picking ray of Linear Algebra chapter 12.
Because 𝐝 has length 1 (Linear Algebra chapter 3), t is the distance in meters along the ray, which is what we compare to find the nearest hit.

The level's collision is a list of axis-aligned boxes (AABBs), the 85 boxes that the camera and the body already use.
Chapter 36 built rayAabb for the camera's sphere cast with the slab method and worked through it with numbers (36.10): per axis, the ray is between that axis's two planes for an interval of t; it's inside the box where the three intervals overlap, from the latest entry to the earliest exit, and it hits if tenter≤texit.
Now the same function becomes the heart of shooting, and three of its properties are what this chapter relies on:

  • The normal comes for free. The axis of the latest entry is the face that was hit, and the normal points against the ray along that axis. The sparks need it to fly off the wall the right way.
  • A ray that starts inside a box hits it at t=0, with a zero normal. An enemy whose eyes are inside a wall never sees through it.
  • maxT limits the search. raycast tries all 85 boxes and passes the best hit so far as the new limit, so boxes behind a closer hit are rejected; with a few rays per step that costs nothing (38.15).

The enemies, though, aren't boxes.

38.4 Ray against sphere

Each enemy gets four hit spheres (38.7), and a ray against a sphere is a quadratic equation, the "solve an equation for t" that GLSL chapter 14 mentioned before it chose sphere tracing instead.

The formula

A point is on the sphere with center 𝐜 and radius r when its distance to the center is r.
Put the ray in and square both sides, writing 𝐦=𝐨−𝐜 for the vector from the center to the ray's start:

‖𝐦+t𝐝‖2=r2⇒t2(𝐝⋅𝐝)+2t(𝐦⋅𝐝)+𝐦⋅𝐦−r2=0

The dot products are those of Linear Algebra chapter 4, and since 𝐝⋅𝐝=1, with b=𝐦⋅𝐝 and c=𝐦⋅𝐦−r2 this is t2+2bt+c=0, so

t=−b±b2−c

The geometry is easier to see than the algebra: −b is the distance along the ray to the point closest to the center (the projection of 𝐜−𝐨 onto 𝐝), b2−c is r2−h2 where h is the ray's closest distance to the center (Pythagoras), and the square root is half the chord the ray cuts through the sphere.
A negative b2−c means the ray passes farther than r from the center: a miss.
The smaller root is where it enters.

A worked example

A circle with center c = 5, 1.8 and radius 3, a ray from o = 0, 0 along d = 1, 0. A green dashed line drops from c to the ray at t = 5, length h = 1.8; the radius r = 3 goes from c to the hit point p at t = 2.6; the half chord is 2.4. The normal n points down-left from p. The second root t = 7.4 is where the ray leaves

Take 𝐨=(0,0), 𝐝=(1,0), 𝐜=(5,1.8) and r=3:

  • 𝐦=𝐨−𝐜=(−5,−1.8)
  • b=𝐦⋅𝐝=−5
  • c=𝐦⋅𝐦−r2=25+3.24−9=19.24
  • b2−c=25−19.24=5.76, and 5.76=2.4
  • t=−b−2.4=5−2.4=2.6 (the other root, 5+2.4=7.4, is the exit)

The hit point is 𝐩=(2.6,0), and the normal there is the direction from the center, (𝐩−𝐜)/r=(−2.4,−1.8)/3=(−0.8,−0.6).
Divide every length by 10 and you have a shot in the game: a chest sphere of radius 0.3 m, 10 m away, and a ray passing 0.18 m beside its center hits at t=10−0.09−0.0324=10−0.24=9.76 m.

The code

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};
}

The first test is an early out with a nice meaning: c>0 says the origin is outside the sphere, and b>0 says the center is behind the ray's start (the projection onto 𝐝 is negative), so the ray moves away from the sphere and can't hit it.
Clamping t at 0 handles a ray that starts inside a sphere, as rayAabb does.
A useful habit with both tests: keep the direction normalized.
Our formula assumes 𝐝⋅𝐝=1; with an unnormalized direction you'd need the general at2+2bt+c form, and t would no longer be in meters.

Ray against capsule

Enemy bullets have to hit the player, and the player is already a capsule (chapter 37): radius 0.35 m, 1.8 m tall, with a vertical core segment from 0.35 m to 1.45 m above the feet.
A capsule is a cylinder with a sphere on each end, so rayCapsule takes the nearest of three hits:

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;
}

The two spheres are raySphere.
The side is a circle problem: an upright cylinder doesn't care about y, so we drop y and intersect the ray's xz part with a circle of radius r.
The algebra is the same as for the sphere, but the xz part of 𝐝 isn't a unit vector, so the general form appears: a=dx2+dz2 and t=(−b−b2−ac)/a.
The hit counts only if its height lies between the two sphere centers; above or below, the end spheres take over.
A vertical ray has a=0, never touches the side, and is left to the spheres.
Like chapter 37's capsuleAabb, the trick is that the capsule never tilts.

38.5 Where does the bullet go? Two rays

The obvious way to shoot in a third-person game is wrong, in two different ways.

The player aims with the crosshair in the middle of the screen, which is where the camera looks.
But the camera is 3.6 m behind the character and 0.7 m to the right of it (chapter 36's shoulder offset), and the rifle's muzzle is only 8 cm to the right of the body's axis (the Weapon socket's x of −0.08 m, and +X is the character's left).
So the camera's line and the gun's line are about 0.62 m apart sideways:

Two top views to scale. In a, the camera ray runs from the camera through the shoulder to an enemy 5 m ahead; the yellow bullet goes from the muzzle to the aim point on the enemy; a red dashed line parallel to the camera ray from the muzzle passes 0.62 m beside the enemy&

  • Shooting along the camera ray from the muzzle (the red dashed line in a) keeps the 0.62 m offset at every distance. A chest sphere has a radius of 0.3 m, so a shot at the crosshair's center misses the enemy the crosshair is on. This is parallax, the same effect that makes a gun sight sit above the barrel.
  • Shooting along the camera ray from the camera hits what the crosshair shows, but the bullet starts at your eyes, not at your gun. In b, the camera sees past the corner of the wall and the gun is behind the wall: a bullet from the camera would fly past the corner and hit the enemy, and you'd be shooting through cover with a gun that is behind it.

Real third-person shooters use two rays:

  1. A ray from the camera through the crosshair finds the aim point: what you aimed at.
  2. The bullet flies from the muzzle to the aim point, and it is the bullet's ray that is tested against the level and the enemies.

On open ground, both reach the same enemy (a).
At a corner, the second ray hits the corner, and you see sparks on the wall instead of hitting the enemy (b): you must step out of cover to shoot, which is what makes cover fair.

The aim ray

Here is the first half of 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;

The muzzle comes from the rifle's Muzzle socket, through the same matrices that draw the rifle: character matrix, Weapon socket, rifle node.
The pose decides where the arms and the spine are, so it is applied first; this is one more reason the pose is a value we can write into the shared model whenever we need it.
The barrel direction is the weapon matrix's third column, the rifle's +Z axis, which Linear Algebra chapter 11 taught us to read as a direction.

The aim ray doesn't start at the eye but at t0 along it, the depth of the shoulder.
Since chapter 36's camera puts the eye at the shoulder moved back by the current camera distance, t0 is exactly that distance, and the aim ray starts at the shoulder.
Anything between the camera and the character must not become the target: an enemy standing right behind you, or, with K (camera collision off), the wall the camera is in.
With camera collision on, the sphere cast already keeps level boxes out of that stretch, so for the level the start rarely matters; for enemies it does.

The aim ray tests the level first, then the enemies up to the level's distance, and the nearest hit is the aim point.
If nothing is hit, the aim point is 120 m away.

The bullet ray

  // 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);

Two special cases make the bullet behave near walls:

  • The barrel pokes through a wall. Standing with your face to a wall, the muzzle (0.94 m in front of the spine) can be on the other side of it. A bullet starting there would hit an enemy behind the wall. So we cast one more ray, from the CameraPivot socket on the body's axis to the muzzle; if it hits a box, the bullet hits that box at that point (blocked), with t = 0.
  • The aim point is behind the gun. With C (the camera-only orbit of chapter 36) you can look at the character from the front while it keeps aiming the other way; the aim point is then behind the rifle, and the tracer would fly backwards through the body. When the direction to the aim point is more than 60° from the barrel (dot < 0.5), the barrel direction is used instead.

Then the bullet ray is tested like the aim ray: against the level, then against the living enemies up to the wall.

38.6 Spread: a random direction in a cone

No gun hits exactly where it points.
A small random spread makes long-range fire less precise, rewards aiming, and, for the enemies, is the main difficulty knob.
We want a random direction inside a cone of half angle θ around the axis 𝐚, and every direction inside should be equally likely.

Put a disc at distance 1 along the axis: its radius is tanθ, and every direction in the cone passes through exactly one point of the disc.
So we choose a random point in the disc and aim at it.
For that point we need two unit vectors perpendicular to 𝐚 and to each other, 𝐮 and 𝐯; the cross product of Linear Algebra chapter 5 gives them (with world up as a helper, or world x when the axis is nearly vertical).
With a random angle φ and a random distance ρ from the disc's center,

𝐝𝐢𝐫=normalize(𝐚+ρ(cosφ𝐮+sinφ𝐯))

The catch is ρ.
Taking ρ=tanθ⋅u with u uniform in [0, 1) is the obvious choice, and it's wrong:

Left, the side view of a cone of half angle theta around the axis a with a disc of radius tan theta at distance 1. Middle, 600 points with r = tan theta times u: crowded in the center, 300 of 600 inside half the radius. Right, 600 points with r = tan theta times the square root of u: spread evenly, 151 of 600 inside half the radius

Half of the points land within half the radius, but that inner circle has only a quarter of the area, so the center is four times too crowded.
For a uniform distribution, the chance to land within ρ must be proportional to the area, P=(ρ/R)2.
Solving u=(ρ/R)2 for ρ gives the fix:

ρ=Ru,R=tanθ

Now a quarter of the samples falls inside half the radius, as it should (151 of 600 in the picture).
The random numbers come from chapter 26's Rng, seeded with 38, so every run spreads the same way:

// 円錐の中のでたらめな向き(拡散):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);
}

Strictly speaking, points uniform on a flat disc aren't quite uniform over the cone's solid angle, but for cones of a few degrees the difference is far too small to notice.

The player's spread is 1.4° from the hip, 0.4° while aiming, and 1.2° more while moving (faster than 0.5 m/s).
Enemies get 2.2° plus 0.5° for every m/s the player moves, so a running player is much harder to hit, as in most shooters.
How big are those cones at 15 m?

Who Half angle Radius at 15 m
player, aiming 0.4° 0.10 m
player, from the hip 1.4° 0.37 m
player, from the hip and moving 2.6° 0.68 m
enemy, player standing still 2.2° 0.58 m
enemy, player walking (3.2 m/s) 3.8° 1.00 m
enemy, player running (6 m/s) 5.2° 1.37 m

Aimed, every shot at 15 m lands inside a 0.3 m chest sphere around the crosshair; from the hip while moving, many won't.
Against an enemy, standing still in the open is dangerous; the player's capsule is 0.7 m wide, so a running player is missed more often than hit.

38.7 Hit spheres, damage and noise

Four spheres per enemy

We could test the bullet against the enemy's triangles, but there is no need.
Each enemy has four spheres, fixed relative to its feet:

// 当たり判定の球(頭・胸・腰・脚):足元からの高さ、半径、ダメージの倍率 / 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}};

Side view to scale of the enemy model in its rest pose with four pink circles: head at 1.62 m with radius 0.17 and damage times 2.5, 85 points; chest at 1.25 m, radius 0.30, times 1, 34; hips at 0.88 m, radius 0.25, times 1, 34; legs at 0.45 m, radius 0.24, times 0.7, 23.8. To the right, the player&

The spheres don't follow the animation: the walk cycle swings the legs and the aim pitch bends the spine, but the spheres stay put.
For blocky soldiers that's fine, and it makes hits forgiving and cheap: 5 enemies × 4 spheres = 20 raySphere calls per ray.
The B key draws them as pink wireframes, which is the easiest way to see why a shot did or didn't count.

hitEnemy finds the nearest sphere of any living enemy and reports which enemy it was and the sphere's damage multiplier:

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;
}

Damage

A hit does 34 points × the sphere's multiplier, and an enemy has 100:

  • chest or hips: 34, so three hits kill (two leave 32)
  • head: 34 × 2.5 = 85, so two hits kill, and a head plus a chest hit (119) as well
  • legs: 34 × 0.7 = 23.8, so it takes five (four leave 4.8)

That's the usual shooter scheme: aim higher to kill faster.
The rest of shoot() applies the hit, spawns the effects and makes noise:

  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) does three things at once: subtract the damage, start the 0.12 s hit flash, and tell the enemy where you are.
Being shot always reveals the shooter, even from behind: an enemy you hit from outside its view turns around.

Noise

The last two lines are the enemies' ears: every living enemy within 18 m of the player hears the shot and gets the same alert, with no damage.
The distance is measured straight through walls, which is what sound roughly does, and it's what makes a fight escalate: your first shot at one guard wakes up the others nearby.
In the scripted fight, the first shot from the platform at frame 136 alerts three enemies in the same step.

38.8 What an enemy notices

An enemy's behavior is only as good as its perception, so let's start there.
All the numbers are constants at the top of 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;

At the start of every step, before the state machine runs, the enemy looks:

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;
  }

A top view to scale. An enemy at the center faces up. A green fan of plus minus 65 degrees and 22 m is what it sees while patrolling; a player inside the fan is seen; another inside the fan, behind a cover box, is not, the red line of sight ends at the box. A third player behind the enemy is outside the view. A yellow dashed circle of 32 m is the range once the enemy is alert, in any direction; an orange dotted circle of 18 m around the third player shows how far a shot is heard

Three tests, cheapest first:

  • Distance. A patrolling enemy sees 22 m. Once something has alerted it, it sees 32 m, which covers most of the 32 × 32 m arena.
  • Field of view. While patrolling, only within ±65° of its heading: the dot product of the heading and the horizontal direction to the player must be above cos65°≈0.42 (Linear Algebra chapter 4 again). An alerted enemy looks everywhere.
  • Line of sight. A ray from the enemy's eyes (1.6 m above its feet) to the player's chest (1.3 m above the player's feet) against the level boxes, limited to the distance between them. Any box hit closer than the player blocks the view. This is the same raycast as the bullet, so if an enemy can see you, it can also shoot you, and the other way round.

The test is symmetric to the player's on purpose: a cover that hides you from an enemy also stops your bullets, and a corner you peek around exposes you only when your gun is out too (the two-ray rule of 38.5).
lastSeen remembers where you were the last time the enemy saw or heard you, and lostTime how long ago that was; the state machine works with these two, not with your actual position.
That's what makes enemies lose you: once you're out of sight, they go to where you were.

38.9 The state machine

The fighter in chapter 30 was a state machine, and so was the CPU opponent of chapter 32.
An enemy is one too, with six states:

enum class EnemyState { Patrol, Alert, Chase, Attack, Search, Dead };

The enemy state machine. Patrol goes to Alert when it sees you, is shot or hears a shot within 18 m. After 0.55 s Alert goes to Attack if it sees you closer than 15 m, otherwise to Chase. Attack goes to Chase when it has lost you for 0.6 s or you are farther than 17 m; Chase goes to Attack when it sees you closer than 15 m. Chase goes to Search when it has reached the last seen position or after 8 s. Search goes back to Alert when it sees you, is shot or hears a shot, and to Patrol after 3 s, from the nearest waypoint. Dead is reached from any state at health 0. Attack goes to Search when you are down

Each state decides how the enemy moves this step and when to switch.
Here are Patrol and Alert:

  // 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;

Patrol walks from waypoint to waypoint at 1.8 m/s and waits a second at each one; stateTime is reset while walking, so it measures the wait.
Alert is the most important state for fairness: the enemy stops and turns towards you for 0.55 s before it may do anything else.
That reaction time is what makes the game playable: without it, an enemy would shoot in the same step it notices you (challenge 2 shows how that feels).
After the reaction, the enemy attacks if it sees you within 15 m and chases you otherwise.

  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;
  }

Attack stands still, faces you and fires.
"Facing" means within 14° (dot > 0.97, and arccos0.97≈14°), so an enemy that has just turned doesn't fire sideways.
Between shots it waits a random 0.55 to 0.95 s from the Rng, so five enemies never fire in lockstep.
It switches to Chase when it hasn't seen you for 0.6 s, or when you are more than 17 m away; the 2 m between 15 m (start attacking) and 17 m (stop attacking) is hysteresis: without it, an enemy at exactly 15 m would flip between the two states every step.
Chase runs at 3.4 m/s to lastSeen, faster than the patrol but slower than you run (6 m/s), so you can break contact.
When it arrives there, or after 8 s, it searches: it turns on the spot at 1.6 rad/s for 3 s (4.8 rad, about 275°), then goes back to patrolling from the waypoint nearest to where it is.
Dead does nothing; the matrix used for drawing makes the body fall (38.12).

The way into the machine from outside is alert, called for hits and for noise:

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);
}

It only switches Patrol and Search to Alert; an enemy that is already attacking or chasing just learns your new position.
Making the transitions explicit like this, with one switch and one setState that resets the timer, keeps the AI debuggable: B draws a colored cube above every enemy (green patrol, yellow alert or search, orange chase, red attack), and F8 prints every enemy's state in every frame (38.14).

38.10 Walking without path finding

The enemies walk with the player's CharacterBody from chapter 37: the same capsule, gravity, wall sliding and stair climbing.
The AI only sets the horizontal velocity, and walkTo does that:

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;
}

The velocity approaches the wanted one at 8/s, the same exponential smoothing as everywhere since chapter 36, and the enemy turns towards where it walks.
Wall sliding already gets an enemy around shallow corners.
But walking straight into a wall head-on leaves nothing to slide along: the velocity's component into the wall is removed and nothing is left.
The first version of the chase got stuck on the north cover like that, forever.

The fix is the simplest possible stand-in for path finding: when the body hit a wall and moves at less than 30 % of the wanted speed, the enemy side-steps perpendicular to its goal for 0.7 s (up to 2.4 m while chasing at 3.4 m/s), then tries the straight line again.
The side alternates, so an enemy that picked the wrong side tries the other one next time.
It's crude, and it works well enough in an arena of low covers and two L-shaped walls.

It isn't path finding, though.
An enemy on the far side of the platform still walks into it and side-steps along it instead of taking the stairs.
The real solution is to search the level for a route: build a graph of where a body can stand (a grid of cells or a navigation mesh of walkable polygons) and run A* on it, which expands the nodes in order of "distance so far plus straight-line distance to the goal" and finds the shortest route without searching the whole map.
Challenge 6 builds the grid version; engines use navigation meshes generated from the level geometry (38.17).

The last part of update moves the body and sets the pose:

  // 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;

The aim pitch is the angle up or down to your chest, so the enemy's rifle points at you while it attacks: the same aim-pitch split over spine, head and weapon as the player's.

38.11 Enemy shots and the player's health

In PlayScene::update, the enemies run after the player's movement, camera and shot:

  // 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 is all an enemy is told: the level boxes, the player's feet and whether the player is alive.
When update returns true, the enemy fires:

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);
  }
}

It's the bullet half of the player's shot: the muzzle from the enemy's own pose (written into the shared enemy.glb first), a spread cone around the direction to your chest, then the level and rayCapsule against your capsule, nearest wins.
Each hit costs 8 points, so 13 hits kill you (12 leave 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;
  }
}

The rest is in the last section of 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();
  }

Health regenerates at 12 points per second, but only 4 s after the last hit, so you recover by leaving the fight, not during it: from the 52 points the scripted fight ends with, it takes 4 s of waiting plus 48 / 12 = 4 s of healing.
At 0 the player falls like an enemy and comes back at the spawn after 3 s, with prevPosition and the camera reset there too, so nothing is interpolated or smoothed from the place where you fell; chapter 39 replaces this with a defeat screen.

Bodies also have to stay apart: two capsules that only collide with the level walk straight through each other.
separateCharacters pushes every pair of living bodies apart horizontally, half each, when they are closer than the sum of their radii (0.7 m).
A push into a wall is fixed by the next step's move.

38.12 Hit effects

A shot is a ray and a subtraction; what makes it feel like a shot is a tenth of a second of light.
All of it lives in a small Effects class, because the engine has no particle system:

Six crops from the fight. Muzzle flash: a bright star at the rifle&

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}); }

Every effect has a short life that update counts down, and everything is removed with std::erase_if when its life reaches 0.

The muzzle flash and its light

The flash is drawn with the unlit shader as a sphere stretched along the barrel plus a small round one, in an HDR color of (16, 9, 3.5) that fades out within 0.05 s.
Anything above the bloom threshold of 1.0 glows (chapter 21), so a bright shape is all it takes to get a glow.
A real muzzle flash also lights its surroundings, and our pipeline already has point lights in the Lights uniform buffer of chapter 19:

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});
  }
}

Each living flash becomes an orange point light with the short-range attenuation of chapter 12: 1/(1+0.7d+1.8d2) is 0.29 at 1 m and 0.10 at 2 m, so the floor and a wall next to you flicker and the rest of the arena doesn't.
At most four are added (the block has room for eight), so even five enemies firing at once can't overflow it.
addLights runs in draw when the frame's LightSet is built, so the light exists only for the frames the flash does.

Tracers

A tracer is a thin streak from the muzzle to the hit, drawn for 0.06 s: a unit cube stretched along the line by beamMatrix, a matrix whose columns are two perpendicular directions scaled to the thickness (2 cm), the line's direction scaled to its length, and the midpoint.
The player's tracers are a warm white (5, 3.6, 1.6), the enemies' redder (6, 1.4, 0.5), so you can tell who is shooting; both are far above 1 and bloom.

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();
  }
}

Sparks: billboards without a vertex buffer

Sparks are many, tiny and short-lived: 14 red ones per enemy hit, 10 yellow ones per wall hit, 8 per enemy bullet.
They're spawned on the CPU with a random direction on the side of the surface normal (from the slab test, or back towards the shooter for an enemy hit), a speed of 2 to 6.5 m/s and a life of 0.18 to 0.45 s, and they fall with gravity:

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)});
  }
}

Drawing them is where the new OpenGL comes in.
Each spark is a small square that always faces the camera, a billboard.
All we need per spark is a position, a half size and a color: 32 bytes, two vec4s.
The corners don't need to be stored anywhere; the vertex shader can make them from gl_VertexID, the trick of chapter 17's fullscreen triangle (chapter 17).
So the VAO has no per-vertex buffer at all, only per-instance attributes:

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) is the call from chapter 19's instancing, but here it's on binding 0, the only binding: with a divisor of 1 the attributes at locations 4 and 5 advance once per instance, not per vertex.
Nothing in the VAO advances per vertex, and that's allowed; the vertex shader just must not read a per-vertex attribute.
Locations 4 and 5 are arbitrary; nothing else uses this VAO.

On the left, a quad with corners minus 1, minus 1 to plus 1, plus 1 split into two triangles, the corners labeled with the gl_VertexID values 0 and 5, 1, 2 and 3, and 4; camera right is row 0 of uView, camera up is row 1; the corners are scaled by aParticle.w around aParticle.xyz; a dashed circle shows where fragments are discarded. On the right, the brightness 1 minus rho squared, squared, against the distance rho from the center: 1 at the center, 0.5625 at half the radius, 0 at the edge

Here is the vertex shader:

#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);
}

Six vertices per instance, two triangles, corners from a constant array indexed by gl_VertexID (0 to 5 within each instance).
To make the square face the camera, we need the camera's right and up directions in world space.
They are already in the view matrix: its upper 3 × 3 part is a rotation from world to view space, so its rows are the camera's axes expressed in world coordinates (Linear Algebra chapter 11).
GLSL indexes matrices column first, so row 0 is uView[0][0], uView[1][0], uView[2][0].
The corner is the center plus c.x · right + c.y · up times the half size, and from there it's the usual projection.

The fragment shader turns the square into a soft dot:

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 is the squared distance from the center in corner units, so outside the inscribed circle the fragment is discarded and inside the brightness is (1−ρ2)2: 1 in the middle, 0.5625 at half the radius, and 0 at the edge, without a visible rim.
The colors are HDR (up to 6 × 1.4 = 8.4 for red sparks, before the fade), so sparks bloom too.
Like every program that draws into the scene FBO since chapter 21, it writes out_bright as well, and it declares the Post block for brightPart; Effects checks both blocks with checkUniformBlock when it loads the program.

Finally, the draw:

void Effects::drawParticles() {
  if (particles.empty() || !shader) return;
  scratch.clear();
  for (const Particle &p : particles) {
    float k = p.life / p.maxLife; // 消えていく / fading out
    Vec3 c = k * p.color;
    scratch.push_back({{p.position.x, p.position.y, p.position.z, p.size * (0.5f + 0.5f * k)}, {c.x, c.y, c.z, 1.0f}});
  }
  instances.update(scratch.data(), static_cast<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);
}

Three pieces of state make particles easy:

  • Additive blending, glBlendFunc(GL_ONE, GL_ONE): the result is source + destination (chapter 16). Addition doesn't care about order, so the sparks need no sorting, unlike chapter 16's transparent objects. It is also physically right for light: two sparks in front of each other are brighter than one. The fragment writes an alpha of 0, so the destination alpha (which the post pass relies on staying 1) doesn't change.
  • Depth test on, depth writes off, glDepthMask(GL_FALSE) (chapter 15): a wall in front still hides the sparks behind it, but a spark never hides another spark or anything drawn after it. With depth writes on, the black corners around the soft dot (discarded only outside the circle) would cut squares out of the sparks behind.
  • Culling off: a billboard's winding depends on nothing we control, so we don't let it matter.

glDrawArraysInstanced(mode, first, count, instancecount) is the non-indexed sibling of chapter 19's glDrawElementsInstanced: count vertices starting at first, instancecount times.
Here it's 6 vertices × the number of sparks, all in one draw call.
The common mistakes are forgetting to restore glDepthMask(GL_TRUE) (the next frame's glClear of the depth buffer then silently does nothing, as chapter 15 warned) and drawing particles before opaque objects (then the depth test has nothing to test against).

The instance data is uploaded every frame with glNamedBufferSubData into a buffer of 1024 × 32 bytes = 32 KiB, allocated once.
A few hundred sparks are a few kilobytes per frame, nothing for any GPU.

Order in the frame

The effects are drawn in this order in the scene pass:

  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();

Tracers and flashes are opaque and write depth like any object.
The sparks come after the sky box, because the sky is drawn with the depth test where the depth buffer is still at 1, and it would overwrite additive sparks drawn before it.
The debug view of B moved behind the sky for the same reason: its markers (the sockets, and now the enemies' state cubes floating above their heads) are drawn without the depth test and so don't write depth, and the sky would paint over every one of them that has only sky behind it.

The hit flash and the fall

An enemy that is hit flashes red for 0.12 s.
pbr.frag already multiplies the base color by vTint, which phong.vert takes from the uniform uTint (chapter 19's per-instance color, defaulting to 1).
So the flash needs no shader change, only a uniform around the draw:

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);
  }
}

At full strength the tint is (8, 2.5, 2): the base color becomes bright red and, being above 1, blooms.
It's reset to 1 before the rifle and the next draw, because a uniform stays set on the program until it's changed.
Emissive parts like the visor aren't affected; a "proper" flash would add to the emission, which needs a game-local copy of pbr.frag.

The death fall is a matrix, not an animation:

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);
}

For 0.6 s the body rotates 90° backwards about its feet with a smoothstep, lifted by 15 cm at the end so the back doesn't sink into the floor.
Rotations about a point other than the origin are a translation and a rotation multiplied in the right order (Linear Algebra chapter 9); because the model's origin is between the feet, rotating in model space already turns it about the feet.
The frustum culling in drawEnemies (chapter 36's bounding spheres) goes through the same matrix: the sphere's center, 0.9 m above the feet in model space, is multiplied by m, so when the body lies on the ground the sphere lies with it.
A center fixed 0.9 m above the feet would stay upright while the head ends up about 1.8 m behind the feet, outside the 1.3 m sphere, and a corpse at the edge of the screen would lose its head when the sphere left the view.

38.13 Aiming, reloading and the crosshair

The right mouse button blends into an aiming camera:

  // 右ボタンで狙う:肩に寄り、視野を狭める(なめらかに) / 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 approaches 0 or 1 at 12/s; the camera distance goes from 3.6 m to 2.4 m, the shoulder offset from 0.7 m to 0.85 m and the vertical field of view from 55° to 42°.
While aiming you walk at 65 % speed (2.08 m/s instead of 3.2) and can't run, and the spread drops from 1.4° to 0.4°.
That's the classic trade of third-person shooters: precision for mobility.

Firing and reloading are a few timers:

  // 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
    }
  }

The fire interval is 0.11 s, but the game runs in fixed 1/60 s steps (chapter 26), and the timer is checked once per step: 6 steps are 0.1 s, not enough, so a shot is fired every 7 steps, 0.117 s, about 8.6 shots per second.
A magazine of 24 lasts 2.8 s of holding the button.
Reloading takes 1.6 s, starts automatically when the magazine is empty, and is canceled if you go down.
If you want exactly 9 shots per second, carry the leftover time over (fireTimer += kFireInterval instead of =), which is what weapons with high fire rates in real games do; then also stop the timer from running far below zero while the button is up (fireTimer = std::fmax(fireTimer - dt, -dt)), or the first press after a pause fires several rounds in one burst.

The crosshair is drawn with the SpriteBatch after the post pass: a center dot and four lines whose gap grows with the spread (5 px aiming, 14 px from the hip, 8 px more while moving), red for 0.15 s after a hit as a hit marker.
A red frame around the screen fades out for 0.35 s after you are hit.
The status line shows health, ammo, the remaining enemies and your hits out of your shots.
Chapter 39 turns all of this into a proper HUD.

38.14 A fight that replays exactly

The clip at the top is not a recording of someone playing.
It's produced by the harness from a script of keys, mouse buttons and mouse positions, and every frame is rendered again from the start for each 40-frame piece of the video (chapter 26).
That only works if the fight is deterministic: the same input must give the same game, down to the last spark.

Three things make it so:

  • Game logic only runs in fixed steps, never with the wall clock (chapter 26).
  • Every random number comes from the one Rng rng{38} of the scene: spread, sparks, enemy fire cooldowns. No std::random_device, no time seed, no std::uniform_real_distribution (which differs between standard libraries).
  • The enemies are updated in the same order every step (their order in the level file), and so they draw from rng in the same order.

Writing a script that actually hits five moving enemies is the hard part.
F8 helps: it prints one line per frame with the frame number, the player's position, the camera's eye, yaw and pitch, health, ammo and every enemy's state, position and health, plus "sees" while it sees you.
Here are frames 24 and 25 of the fight, the platform guard (the third enemy) dying from the third hit:

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 |

The mouse moves of the script were tuned from these lines: compute the yaw and pitch towards the target, convert to pixels with the sensitivity (0.0025 rad per pixel), run, read the residual from the log, correct.
It took two corrections per target, because the eye moves as the camera turns (it orbits the pivot with the shoulder offset), so the first estimate is always a few degrees off.
The final script kills the enemies at frames 25, 143, 171, 240 and 295 of the 30 fps clip and ends with 52 health, and it does so on every run.
Reading the state changes out of the log shows the AI at work: the platform guard is already alert at frame 1 (it faces the spawn), turns to attack at frame 17 after its reaction time, and dies at 25; the first shot from the platform at frame 136 makes three enemies hear it and become alert in the same step.

The B key shows the same information in the picture:

Two views with B. Left: the player at the spawn in front of the stairs, a red line of sight from the enemy on the platform, its red state cube (attack) over its head and the pink wireframes of its hit spheres; the other enemies&

38.15 Running it

Build as before and run ./build/games/tps/tps from the project root (in Visual Studio, start the tps target; the working directory is already the root).
Click into the window to capture the mouse, hold the right button, and shoot the guard on the platform; the noise brings the others.
With B on you can watch each enemy's state cube change color as it notices you.

The AI and the rays are cheap: per step, five line-of-sight rays against 85 boxes, plus a few rays per shot; that is microseconds.
On the harness's software renderer (llvmpipe, a CPU rasterizer on a 2-core VM, not a GPU), the scripted fight measured 117 to 128 ms per frame, of which the scene pass took 100 to 110 ms, the shadow pass about 5.5 ms and the post pass 10 to 12 ms, with 1.04 to 1.10 million scene fragments.
That is the same range as the empty arena of chapter 37: five more characters, up to four extra point lights and a few hundred sparks are lost in the noise.
On a desktop GPU the whole frame is a millisecond or two.

38.16 Platform notes

  • All: the determinism of 38.14 holds for one build on one machine. Across compilers and standard libraries, std::sin, std::exp and friends may differ in the last bit, and a compiler may turn a · b + c into a fused multiply-add when the target has FMA instructions (or with options such as MSVC's /fp:fast); a script tuned on Linux can then drift on Windows after many frames. Games with replays or lockstep networking avoid this by recording inputs and comparing state checksums, or by simulating in fixed-point math.
  • Windows (Visual Studio): the debug build is much slower than release because the standard containers check every access; that doesn't change behavior, only frame time. Use the RelWithDebInfo configuration for playing.
  • Linux, FreeBSD: nothing special. The engine's Window already turns on GLFW's raw mouse motion (GLFW_RAW_MOUSE_MOTION) while the cursor is captured, if the platform supports it, so the desktop's mouse acceleration doesn't bend your aim; on X11 that needs the XInput2 extension, which every current X server has.

38.17 How real games do it

  • Hit detection: physics engines (PhysX, Jolt, Havok, Bullet) provide ray casts and shape casts against everything in the scene, accelerated by a bounding volume hierarchy instead of our loop over 85 boxes. Characters get one capsule or box per bone of the skeleton ("hitboxes"), animated with it, and the damage depends on the bone. Our four fixed spheres are that idea without a skeleton.
  • Two rays: the camera-to-crosshair ray plus a muzzle ray is the standard solution in over-the-shoulder shooters; some games bend the bullet path slightly so it starts at the muzzle and ends on the crosshair, others show a "blocked" marker on the crosshair when the muzzle ray is obstructed, which is a nice addition (and a good challenge).
  • Bullets: we use hitscan, an instant ray. Slow weapons (rockets, arrows, sniper rifles in some games) are projectiles that move every step and test the segment they covered, often with gravity and drag.
  • Particles: engines have GPU particle systems (Unreal's Niagara, Unity's VFX Graph) that spawn, simulate and sort particles in compute shaders, with sprite sheets, trails and collisions. The rendering core is what we wrote: instanced billboards, additive or premultiplied blending, no depth writes.
  • AI: state machines are still common for small enemies; larger games use behavior trees (Unreal), utility AI (choose the action with the best score) or GOAP (plan a sequence of actions, used in F.E.A.R.). Perception is usually a separate system with sight cones, hearing events and memory, very much like EnemySenses plus lastSeen.
  • Navigation: Recast & Detour (used by Unity, Unreal and Godot in some form) builds a navigation mesh from the level's triangles and finds paths on it with A*, plus steering and crowd avoidance so enemies don't bump into each other. That's what replaces our side-step.
  • Cover: cover systems mark positions behind obstacles in the level data and let enemies score them by safety and line of sight to the player (challenge 7).

38.18 Summary

  • Two rays: a ray from the camera through the crosshair, started at the shoulder's depth, finds the aim point; the bullet flies from the Muzzle socket to that point and is tested again. The camera and the gun are 0.62 m apart sideways, so one ray isn't enough: from the muzzle along the camera ray misses (parallax), from the camera shoots through cover. A pivot-to-muzzle ray catches a barrel through a wall; an aim point behind the gun falls back to the barrel direction.
  • Rays against the level: chapter 36's slab test (rayAabb, raycast) gives the nearest hit's t, the face normal from the slab of the latest entry (for the sparks), and t=0 for a ray that starts inside a box (no seeing through walls).
  • Ray–sphere: with 𝐦=𝐨−𝐜, b=𝐦⋅𝐝, c=𝐦⋅𝐦−r2: t=−b−b2−c; outside and moving away is an early miss. Ray–capsule = two spheres + a circle in xz, accepted between the sphere centers.
  • Spread: a random point in the disc of radius tanθ at distance 1, with ρ=Ru for uniform density, around the axis with two perpendicular vectors from cross products. Player 1.4° / 0.4° aimed / +1.2° moving; enemies 2.2° + 0.5° per m/s of the player's speed.
  • Damage: four hit spheres per enemy (head ×2.5, chest, hips, legs ×0.7), 34 per hit: three chest hits or two head hits kill. Shots alert the hit enemy and are heard within 18 m.
  • Enemies: five from the level file (enemy x y z yaw patrol…), one shared enemy.glb with each enemy's pose written before use, the player's CharacterBody for movement.
  • Senses: distance (22 m, 32 m once alert), field of view (±65°, while patrolling) and a line-of-sight ray from the eyes to the chest; lastSeen and lostTime instead of the true position.
  • State machine: Patrol, Alert (0.55 s reaction), Attack (face within 14°, fire every 0.55–0.95 s), Chase (3.4 m/s to the last seen position), Search (turn for 3 s), Dead; hysteresis between 15 and 17 m. Stuck enemies side-step for 0.7 s instead of path finding; A* on a grid or a navigation mesh is the real solution.
  • Player: 100 health, 8 per enemy hit, regeneration of 12/s after 4 s, respawn after 3 s; aiming narrows the view and the spread and slows you down; 24 rounds, about 8.6 shots per second at the 60 Hz step, 1.6 s reload.
  • Effects: an emissive muzzle flash plus a short-range point light in the Lights block, HDR tracers that bloom, CPU-simulated sparks drawn as instanced billboards with no vertex buffer (corners from gl_VertexID, camera axes from the view matrix's rows) with additive blending, the depth test on and depth writes off, and a hit flash through uTint.
  • Determinism: fixed steps, one seeded Rng, a fixed update order; F8 logs the state every frame, which is how the scripted fight was tuned. It kills all five enemies at frames 25, 143, 171, 240 and 295 and replays exactly.

38.19 Challenges

  1. ★ Change the multipliers in kHitSpheres to ×4 for the head and ×0.3 for the legs. One head hit should now kill (34 × 4 = 136), and a leg hit should do 10.2 points, so it takes 10 leg hits.
  2. ★ Set kReaction to 0 and stand in the open at the spawn. The platform guard should start firing in the first steps instead of after 0.55 s, and the start of the scripted fight should cost you health it didn't cost before (and the rest of the script will no longer match).
  3. ★ Make the enemies' spread 0.5° (replace 2.2f + 0.5f * moving with 0.5f). Running should no longer protect you, and you should see nearly every red tracer end on you.
  4. ★★ Add recoil: every shot raises the camera pitch by 0.6° and the spread by 0.3°, both decaying back at 5/s. Long bursts should climb above the target and spread out, while short bursts of two or three shots stay on a chest at 15 m.
  5. ★★ Bullet holes: at every level hit, store the hit point and normal (keep the last 64 in a ring) and draw a small dark square there, aligned with the normal, using glPolygonOffset (or a 1 mm offset along the normal) against z-fighting. The marks should stay on the walls and never flicker.
  6. ★★★ Path finding: build a grid of 0.5 m cells over the arena, block every cell whose center lies inside a collision box grown by the body radius (0.35 m), run A* from the enemy's cell to lastSeen's cell when it starts chasing, and walk along the path's corners. A chasing enemy should walk around the platform and the L-shaped walls instead of side-stepping along them, and B can draw the path.
  7. ★★★ Cover: when an enemy is hit while attacking, let it pick the nearest cover piece whose far side is hidden from the player (a line-of-sight ray from the player to that point hits the cover), walk there, wait 1–2 s and step out to fire again. Fights should now have enemies ducking behind the covers between bursts.

Download the diff

Download the project (ZIP)

ファイル: 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)

まだコメントはありません。