9. The Camera
In chapter 8 the camera was one fixed line of code: lookAt({0, 1.5, 6}, {0, 0, -2}, up).
A 3D program you can't walk around in isn't much fun, so in this chapter we build a proper camera.
We'll write a first-person fly camera that you steer with WASD and the mouse, add zooming with the scroll wheel, and then an orbit camera that circles around a point, the kind you know from model viewers and third-person games.
The math is the yaw/pitch camera from section 11.7 of the Linear Algebra series, so this chapter is mostly about turning input into numbers: capturing the mouse, measuring how far it moved, and making movement independent of the frame rate.
There is no new OpenGL in this chapter at all, only GLFW input functions and C++.
9.1 What we're building
A floor of stone tiles with twelve crates of different sizes standing on it, some stacked.
You start at eye height and can fly around freely:
The controls:
- W, A, S, D: move forward, left, back, right
- Space and Left Ctrl: move up and down
- Left Shift: move three times faster
- Mouse: look around
- Scroll wheel: zoom (in the FPS camera it changes the field of view, in the orbit camera the distance)
- C: switch between the FPS camera and the orbit camera (orbit: drag with the left mouse button)
- Tab: release or capture the mouse cursor
- R: reload the shaders, Esc: quit
Starting from chapter 8, the changes are:
src/window.hhandsrc/window.cc: mouse movement, scroll amount and cursor capturesrc/camera.hhandsrc/camera.cc(new):CameraandOrbitCamerasrc/shapes.hhandsrc/shapes.cc:makePlane()for the floorassets/textures/floor.png(new): the stone floor texture, generated like the crate (the finished files are in the chapter's ZIP and inch09/of the assets ZIP)src/main.cc: the new scene and the input handlingCMakeLists.txt: the new source file
9.2 Mouse input for cameras
Positions are not enough
Since chapter 2 our Window has known where the cursor is (mouseX(), mouseY()).
For a camera that's the wrong information.
We don't care where the mouse is; we care how far it moved since the last frame, because that's how much the view should turn.
And it must keep working when the cursor would hit the edge of the screen: in a first-person game you can turn around ten times in a row.
So Window gets two new values per frame: the mouse movement and the scroll amount.
In window.hh, next to the polling helpers:
// 前のpollEvents()から今回までのマウスの移動量とホイールの回転量 / mouse movement and scroll since the last pollEvents()
Vec2 mouseDelta() const { return frameMouseDelta; }
float scrollDelta() const { return frameScroll; }
// カーソルを隠して固定する(FPSカメラ用)。移動量は無制限に取れる。
// Hides and locks the cursor (for FPS cameras). Movement is then unlimited.
void setCursorCaptured(bool captured);
bool cursorCaptured() const { return captured; }
and four new members in the private part:
double cursorX = 0.0, cursorY = 0.0;
Vec2 frameMouseDelta;
float frameScroll = 0.0f;
bool captured = false;
bool skipNextDelta = true; // 最初とキャプチャ切り替え直後の飛びを無視 / ignore the jump at start and after (un)capturing
bool vsyncOn = true;
window.hh now includes <linalg.hh> for Vec2.
Adding up movement in the callbacks
GLFW can call the cursor callback several times during one glfwPollEvents() (a fast mouse produces many events per frame).
So the callbacks add to the per-frame totals, and pollEvents() resets them to zero before asking GLFW for new events:
void Window::pollEvents() {
// 今回のフレームの分を数え直す(コールバックで足していく) / start counting this frame (the callbacks add to these)
frameMouseDelta = {0.0f, 0.0f};
frameScroll = 0.0f;
glfwPollEvents();
}
The cursor callback computes the movement from the previous position it remembered, and the scroll callback adds the vertical scroll offset:
void Window::cursorPosCallback(GLFWwindow *w, double x, double y) {
Window *win = self(w);
if (!win->skipNextDelta) {
win->frameMouseDelta.x += static_cast<float>(x - win->cursorX);
win->frameMouseDelta.y += static_cast<float>(y - win->cursorY);
}
win->skipNextDelta = false;
win->cursorX = x;
win->cursorY = y;
if (win->onCursorPos) win->onCursorPos(x, y);
}
void Window::scrollCallback(GLFWwindow *w, double dx, double dy) {
Window *win = self(w);
win->frameScroll += static_cast<float>(dy);
if (win->onScroll) win->onScroll(dx, dy);
}
After pollEvents() returns, mouseDelta() holds the total movement of this frame in pixels (x to the right, y downwards, because window coordinates start at the top-left), and scrollDelta() the number of wheel "notches" (positive when scrolling up, away from you).
The existing onCursorPos and onScroll callbacks from chapter 2 still work; we just record a little more.
Capturing the cursor
To get unlimited movement, the cursor has to be hidden and locked to the window.
GLFW does that with one call:
void Window::setCursorCaptured(bool on) {
captured = on;
glfwSetInputMode(glfwWindow, GLFW_CURSOR, on ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL);
// OSのマウス加速なしの生の動き(使えれば) / raw motion without OS mouse acceleration (if available)
if (glfwRawMouseMotionSupported()) glfwSetInputMode(glfwWindow, GLFW_RAW_MOUSE_MOTION, on ? GLFW_TRUE : GLFW_FALSE);
skipNextDelta = true;
}
glfwSetInputMode(window, mode, value) changes an input setting of one window.
With mode = GLFW_CURSOR the value is one of:
GLFW_CURSOR_NORMAL: the normal, visible cursor.GLFW_CURSOR_HIDDEN: invisible while over the window, but it can still leave it.GLFW_CURSOR_DISABLED: invisible and locked. GLFW keeps the real cursor in the window and reports a virtual position that can grow without limit, which is exactly what a camera needs.GLFW_CURSOR_CAPTURED(GLFW 3.4 only): visible, but it can't leave the window. Useful for strategy games that scroll at the screen edge.
GLFW_RAW_MOUSE_MOTION asks for the mouse's raw movement, without the operating system's pointer acceleration.
With acceleration, a fast flick turns the camera further than a slow movement of the same distance, which feels wrong for aiming.
Raw motion only applies while the cursor is disabled, and not every platform has it, so we ask glfwRawMouseMotionSupported() first; without it, we simply get the normal (accelerated) movement.
The skipNextDelta flag solves a small but very visible problem.
Right after the mode changes (and for the very first event after startup), the reported position can jump: GLFW moves the hidden cursor to the window center, or the remembered cursorX is from before the cursor was disabled.
Treating that jump as movement would whip the camera around by hundreds of pixels' worth.
So the first cursor event after a change only updates the remembered position.
Platform notes
- Windows: cursor capture and raw input work out of the box. When the window loses focus (Alt+Tab, or hitting a breakpoint in Visual Studio), GLFW releases the cursor, and it captures it again when the window gets focus back. If the debugger stops while you're looking around, that's why your cursor is suddenly free.
- Linux with X11, and FreeBSD: works the same; raw motion depends on the X server supporting the XInput2 extension, which is why we check first.
- Linux with Wayland:
GLFW_CURSOR_DISABLEDuses the compositor's pointer-lock protocols, which GNOME, KDE and the wlroots compositors support. One difference: Wayland doesn't let applications move the cursor, soglfwSetCursorPosdoes nothing there. We never call it, so our camera works on both. - Virtual machines and remote desktops often only send absolute cursor positions. If the camera turns only until the invisible cursor hits the edge, turn off the VM's mouse integration.
The Tab key releases the cursor (setCursorCaptured(!window.cursorCaptured())), which is handy when you need it for something else.
9.3 Yaw and pitch
Two angles for a direction
A first-person camera doesn't store a target point.
It stores two angles:
- yaw: turning left and right, around the world's up axis Y
- pitch: looking up and down
(Aircraft have a third angle, roll, tilting the head sideways. First-person cameras don't use it.)
From the two angles we compute the front vector, the direction the camera looks.
Pitch first: a direction lifted by the angle above the horizontal has height and horizontal length .
Then yaw turns that horizontal part away from −Z towards +X by the angle .
Together:
With both angles 0 the camera looks down −Z, exactly like the default view space.
With it looks down +X, to the right.
And it's always unit length: .
A note on the sign of yaw
If you've read the Linear Algebra chapter, you'll notice that its formula is , with a minus sign in x.
Both are right; they just measure yaw in opposite directions.
The math chapter follows the right-hand rule, where a positive rotation around +Y is counter-clockwise seen from above, so positive yaw turns left and "mouse right" has to decrease the angle.
Our Camera class uses the convention most games use instead: positive yaw turns right, so moving the mouse to the right simply adds to yaw.
It's the same formula with .
Pick one convention per project and write it next to the variable, as camera.hh does.
Worked example
The camera in our scene starts with yaw 0 and pitch −8° (looking slightly down).
Suppose you move the mouse 200 pixels to the right.
With the sensitivity of 0.0025 radians per pixel, yaw becomes radians, about 28.6°.
Let's use round numbers, yaw and pitch :
Check the length: .
The camera looks mostly into the scene (−Z), somewhat to the right (+X) and a little down (−Y), as expected.
The right vector
For strafing (A and D) we also need the camera's right direction.
It's perpendicular to both the front and the world's up, which is what the cross product gives (Linear Algebra chapter 5):
For yaw 0 and pitch 0: , to the right.
The cross product's length is , not 1, when the camera looks up or down, which is why we normalize.
It also shows why the pitch must never reach ±90°: then is parallel to up, the cross product is the zero vector, and normalize can't make a direction out of it.
lookAt uses the same cross product internally (section 11.6, "When lookAt breaks"), so the whole view would collapse.
We clamp the pitch to ±89°.
9.4 The Camera class
Here is the new header, src/camera.hh, starting with the FPS camera:
// 一人称(FPS)の飛べるカメラ。向きはヨー(左右)とピッチ(上下)で表す。
// A first-person (FPS) fly camera. Its direction is yaw (left/right) and pitch (up/down).
class Camera {
public:
Vec3 position = {0.0f, 0.0f, 3.0f};
float yaw = 0.0f; // ラジアン。0で-Zを向き、正で右へ回る / radians. 0 looks down -Z, positive turns right
float pitch = 0.0f; // ラジアン。正で上を向く / radians. positive looks up
float fov = radians(45.0f); // 縦の視野角 / vertical field of view
float nearPlane = 0.1f, farPlane = 100.0f;
float speed = 3.0f; // 単位毎秒 / units per second
float sensitivity = 0.0025f; // ラジアン毎ピクセル / radians per pixel of mouse movement
Vec3 front() const; // 見ている方向(単位ベクトル) / the viewing direction (unit vector)
Vec3 right() const; // 右(水平) / right (horizontal)
// マウスの移動量(ピクセル)で向きを変える。真上・真下は向けない。
// Turns by a mouse movement in pixels. Cannot look straight up or down.
void turn(float dxPixels, float dyPixels);
// ローカルな方向(x = 右、y = 上、z = 前)に dt 秒だけ動く / moves for dt seconds in a local direction (x right, y up, z forward)
void move(Vec3 direction, float dt);
// ホイールで視野角を変える(ズーム) / changes the field of view with the scroll wheel (zoom)
void zoom(float scrollSteps);
Mat4 view() const;
Mat4 projection(float aspect) const;
};
A few design decisions:
- Public fields, no getters. A camera is a bag of numbers that the game sets and reads all the time (place it at a spawn point, read its position for lighting in chapter 10). Getters and setters would add nothing.
- No GL and no GLFW. The camera doesn't know about windows, keys or shaders. It receives numbers (pixels, seconds, a direction) and returns matrices.
mainreads the input and passes it in. That keeps the class easy to test and to reuse; chapter 26 adds a pressed/held/released input layer without touching it. nearPlaneandfarPlane, notnearandfar: those two are macros on Windows (chapter 8).
camera.cc
The implementation starts with two constants:
// ピッチの限界:±89度(真上を向くとlookAtのcross(前, 上)が0になる)
// pitch limit: ±89° (looking straight up makes lookAt's cross(forward, up) zero)
constexpr float kMaxPitch = radians(89.0f);
constexpr Vec3 kWorldUp = {0.0f, 1.0f, 0.0f};
radians from linalg.hh is constexpr, so kMaxPitch is computed at compile time.
front() and right() are the two formulas from section 9.3:
Vec3 Camera::front() const {
// 球面座標:yawで水平に回し、pitchで持ち上げる / spherical coordinates: yaw turns horizontally, pitch lifts
return {std::cos(pitch) * std::sin(yaw), std::sin(pitch), -std::cos(pitch) * std::cos(yaw)};
}
Vec3 Camera::right() const { return normalize(cross(front(), kWorldUp)); }
Turning
void Camera::turn(float dxPixels, float dyPixels) {
yaw += dxPixels * sensitivity;
pitch -= dyPixels * sensitivity; // マウスのyは下向きが正 / mouse y grows downwards
pitch = std::clamp(pitch, -kMaxPitch, kMaxPitch);
}
Mouse x to the right turns right (positive yaw).
Mouse y grows downwards in window coordinates, so moving the mouse up gives a negative dy, and we subtract it to look up.
Getting this sign wrong gives you an "inverted" camera (some players like that; challenge 1 makes it an option).
The sensitivity of 0.0025 radians per pixel means 1000 pixels of mouse movement turn the camera by 2.5 radians, about 143°.
Yaw is not clamped; it can grow forever, and sin/cos don't mind.
Notice that there is no dt here.
The mouse delta is already "how far the mouse moved this frame".
At 60 frames per second you get small deltas 60 times, at 240 frames per second smaller deltas 240 times, and the total per second is the same.
Multiplying by dt would make the camera turn slower at higher frame rates, a real bug that shipped in more than one game.
Moving
void Camera::move(Vec3 direction, float dt) {
if (length(direction) == 0.0f) return;
direction = normalize(direction); // 斜めでも速さは同じ / same speed diagonally
Vec3 velocity = direction.x * right() + direction.y * kWorldUp + direction.z * front();
position = position + (speed * dt) * velocity;
}
direction is a local direction built from the keys: x = right, y = up, z = forward.
Pressing W and D together gives , which has length ; without the normalize, diagonal movement would be 41% faster, the classic bug from Linear Algebra chapter 3.
The local direction is then turned into a world direction as a linear combination of the camera's axes: so much of right(), so much of world up, so much of front().
Finally the position moves by speed × time × direction.
This is where dt must be used.
Keys are held over many frames, and each frame moves the camera by speed * dt: at 60 FPS that's units per frame, at 144 FPS about 0.021, and in both cases 3 units per second.
Without dt, a faster computer would move faster.
Because front() includes the pitch, this is a fly camera: look up and press W, and you rise.
That's what a level editor or a debug camera wants.
A walking player should move along the horizontal front instead (challenge 2), and the third-person game in part 6 does exactly that.
One more small quirk: world up is not perpendicular to a pitched front vector, so holding W and Space while looking up moves you a bit faster than the speed (up to times at 89°); the walking version doesn't have this problem.
Zooming
void Camera::zoom(float scrollSteps) {
fov = std::clamp(fov - radians(2.0f) * scrollSteps, radians(15.0f), radians(75.0f));
}
"Zoom" in a first-person camera means changing the field of view, like a telephoto lens: a smaller angle shows less of the scene, so what's left fills the screen.
Each notch of the wheel changes the FOV by 2°, between 15° and 75°; from the default 45°, 15 notches take you to either limit.
The position doesn't change at all, which is why zooming in with a narrow FOV also flattens the depth (things look stacked):
The matrices
Mat4 Camera::view() const { return lookAt(position, position + front(), kWorldUp); }
Mat4 Camera::projection(float aspect) const { return perspectiveGl(fov, aspect, nearPlane, farPlane); }
lookAt wants a target point, and position + front() is a point one unit in front of the eye.
Any point along that line would give the same matrix.
The projection is chapter 8's perspectiveGl, now with the camera's own FOV and planes.
The aspect ratio is a parameter because it belongs to the window, not to the camera.
9.5 Using the camera in main
Setup
After loading the textures (now with a third one for the floor), main creates both cameras:
std::optional<Shader> shader = Shader::load("shaders/textured.vert", "shaders/textured.frag");
std::optional<Texture2D> crate = Texture2D::load("assets/textures/crate.png");
std::optional<Texture2D> emblem = Texture2D::load("assets/textures/emblem.png");
std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png");
if (!shader || !crate || !emblem || !floorTexture) return 1;
glEnable(GL_DEPTH_TEST);
Camera fps;
fps.position = {0.0f, 1.6f, 7.0f}; // 目の高さ / eye height
fps.pitch = radians(-8.0f);
OrbitCamera orbit;
orbit.target = {0.0f, 0.8f, 0.0f};
orbit.distance = 9.0f;
orbit.yaw = radians(30.0f);
bool useOrbit = false;
window.setCursorCaptured(true); // FPSはカーソルを隠して固定 / FPS: hide and lock the cursor
One unit is one meter in this scene (a crate is 1 m), so 1.6 is roughly the eye height of a person.
The depth test from chapter 8 stays on all the time; the Z toggle and the pause key are gone.
We name the texture floorTexture, not floor, so it can't be confused with the floor function from <cmath> (and doesn't trigger shadowing warnings).
Keys that happen once
One-shot actions stay in the key callback, as in chapter 2:
window.onKey = [&](int key, int action, int /*mods*/) {
if (action != GLFW_PRESS) return;
if (key == GLFW_KEY_ESCAPE) window.close();
if (key == GLFW_KEY_R && shader->reload()) printf("シェーダーを読み直した / shaders reloaded\n");
if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured());
if (key == GLFW_KEY_C) {
useOrbit = !useOrbit;
// オービットはマウスでドラッグするのでカーソルを見せる / orbit is dragged with the mouse, so show the cursor
window.setCursorCaptured(!useOrbit);
printf("camera: %s\n", useOrbit ? "orbit" : "fps");
}
};
Input every frame
Held keys and mouse movement are read every frame, right after pollEvents():
Vec2 mouse = window.mouseDelta();
if (useOrbit) {
if (window.mouseButtonDown(GLFW_MOUSE_BUTTON_LEFT)) orbit.turn(mouse.x, mouse.y);
orbit.zoom(window.scrollDelta());
} else {
if (window.cursorCaptured()) fps.turn(mouse.x, mouse.y);
fps.zoom(window.scrollDelta());
// キーからローカルな移動方向を作る(x = 右、y = 上、z = 前) / build a local direction from the keys
Vec3 dir;
if (window.keyDown(GLFW_KEY_W)) dir.z += 1.0f;
if (window.keyDown(GLFW_KEY_S)) dir.z -= 1.0f;
if (window.keyDown(GLFW_KEY_D)) dir.x += 1.0f;
if (window.keyDown(GLFW_KEY_A)) dir.x -= 1.0f;
if (window.keyDown(GLFW_KEY_SPACE)) dir.y += 1.0f;
if (window.keyDown(GLFW_KEY_LEFT_CONTROL)) dir.y -= 1.0f;
fps.speed = window.keyDown(GLFW_KEY_LEFT_SHIFT) ? 9.0f : 3.0f;
// dtを掛けるのでフレームレートに関係なく同じ速さ / multiplied by dt: the same speed at any frame rate
fps.move(dir, dt);
}
Mat4 view = useOrbit ? orbit.view() : fps.view();
Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect());
The keys build the local direction by adding and subtracting: W and S together cancel out to 0, which is what players expect.
Vec3 dir; starts at because linalg.hh's vectors have default member initializers.
The FPS camera only turns while the cursor is captured, so after pressing Tab you can move the visible cursor without the view spinning.
The GLFW_KEY_… constants are layout-independent "positions" on a US keyboard: on a French AZERTY keyboard, GLFW_KEY_W is the key labelled Z, which is usually what you want for WASD.
view and proj come from whichever camera is active.
Since both classes have view() and projection(aspect), the rest of the frame doesn't care which one it is.
9.6 A floor to stand on
Flying around in empty space makes it hard to feel movement, so the scene gets a floor.
shapes.hh gets a second function:
// XZ平面上のsize×sizeの床(y = 0、法線は+Y)。UVはuvRepeat回繰り返す(GL_REPEATが必要)。
// A size × size floor on the XZ plane (y = 0, normal +Y). UVs repeat uvRepeat times (needs GL_REPEAT).
Mesh makePlane(float size, float uvRepeat);
and shapes.cc builds it from four Vertex3D:
Mesh makePlane(float size, float uvRepeat) {
float h = 0.5f * size;
Vec3 n = {0.0f, 1.0f, 0.0f};
// 上から見て反時計回り / counter-clockwise seen from above
std::vector<Vertex3D> vertices = {
{{-h, 0.0f, h}, n, {0.0f, 0.0f}},
{{h, 0.0f, h}, n, {uvRepeat, 0.0f}},
{{h, 0.0f, -h}, n, {uvRepeat, uvRepeat}},
{{-h, 0.0f, -h}, n, {0.0f, uvRepeat}},
};
return Mesh(vertices, {0, 1, 2, 2, 3, 0}, kVertex3DLayout);
}
The UVs go from 0 to uvRepeat instead of 0 to 1.
With the GL_REPEAT wrap mode (the default of our Texture2D, chapter 6), the texture then tiles uvRepeat times in each direction.
The order of the corners is counter-clockwise when you look down from above (+Y), so the top side is the front side, like the cube faces in chapter 8.
In main, the floor is 40×40 units with the texture repeated 10 times:
Mesh cube = makeCube();
// 40×40の床。テクスチャにタイル4枚なので10回繰り返すと1タイル = 1単位
// A 40 × 40 floor. The texture holds 4 tiles, so repeating it 10 times makes one tile = one unit
Mesh floorMesh = makePlane(40.0f, 10.0f);
floor.png is a 512×512 seamless texture with 4×4 stone tiles, generated by a Python script like the crate (see assets/LICENSE.txt).
Ten repeats over 40 units means one repeat every 4 units, and with 4 tiles per repeat, one tile per unit: exactly the size of a 1×1×1 crate.
A floor with a known scale makes the size of everything else readable.
The floor is also a good test for the mipmaps from chapter 6.
Far away, each pixel covers many texels, and without mipmaps the tiles would shimmer in a moiré pattern as you move.
With mipmaps they turn smoothly blurry instead; anisotropic filtering (challenge 6) makes them sharp again.
Drawing the scene
glClearColor(0.10f, 0.15f, 0.25f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shader->use();
shader->set("uView", view);
shader->set("uProj", proj);
shader->set("uEmblemScale", 1.0f);
// 床:二枚目のテクスチャは混ぜない / the floor: no second texture
floorTexture->bind(0);
emblem->bind(1);
shader->set("uMix", 0.0f);
shader->set("uModel", Mat4::identity());
floorMesh.draw();
// 箱:立方体は原点が中心なので半分持ち上げて床に置く / crates: the cube is centred, so lift it by half its size
crate->bind(0);
shader->set("uMix", 0.8f);
for (const CrateInfo &c : kCrates) {
Vec3 centre = c.position + Vec3{0.0f, 0.5f * c.size, 0.0f};
shader->set("uModel", translate(centre) * rotateY(c.angle) * scale({c.size, c.size, c.size}));
cube.draw();
}
The floor's vertices are already in world space, so its model matrix is the identity.
It uses the same shader as the crates, with uMix = 0 so that no sakura emblem appears on the stones.
The emblem stays bound to unit 1 anyway: the shader samples uTexture1 whether or not the result is used, and it's good practice to never leave a sampler pointing at nothing.
The crates are a table of bottom-center positions, sizes and yaw angles:
// 床に置いた箱:位置(底の中心)、大きさ、Y軸周りの回転 / crates on the floor: position (bottom centre), size, yaw
struct CrateInfo {
Vec3 position;
float size;
float angle;
};
static const CrateInfo kCrates[] = {
{{0.0f, 0.0f, 0.0f}, 1.0f, 0.0f}, {{1.1f, 0.0f, 0.2f}, 1.0f, 0.3f},
{{0.5f, 1.0f, 0.1f}, 1.0f, -0.2f}, {{-3.0f, 0.0f, -2.0f}, 2.0f, 0.6f},
{{-3.0f, 2.0f, -2.0f}, 1.0f, 0.1f}, {{4.0f, 0.0f, -4.0f}, 1.5f, -0.5f},
{{-6.0f, 0.0f, 3.0f}, 1.0f, 0.9f}, {{6.5f, 0.0f, 2.5f}, 1.0f, 0.2f},
{{2.0f, 0.0f, -9.0f}, 3.0f, 0.4f}, {{-8.0f, 0.0f, -8.0f}, 2.0f, -0.3f},
{{9.0f, 0.0f, -12.0f}, 2.5f, 0.7f}, {{-2.5f, 0.0f, 5.5f}, 0.6f, 0.5f},
};
Storing the bottom center is more natural for things that stand on a floor: a crate at height 0 is on the floor, and the crate at stands on top of the two 1-unit crates below it.
Our cube is centered on its origin, though, so the drawing code lifts it by half its size before applying chapter 7's : scale to the crate's size, turn it around Y, move it to its place.
Finally, CMakeLists.txt gets src/camera.cc:
add_executable(game
src/main.cc
src/window.cc
src/gl_debug.cc
src/buffer.cc
src/mesh.cc
src/file_util.cc
src/shader.cc
src/texture.cc
src/shapes.cc
src/camera.cc)
9.7 The orbit camera
Press C and the camera changes character: the cursor appears, and dragging with the left mouse button swings the view around the crates in the middle.
The scroll wheel now moves the camera closer or farther.
The second class in camera.hh:
// 注視点の周りを回るカメラ(モデルビューアーやTPS向け)。
// A camera that orbits a target point (for model viewers and third-person games).
class OrbitCamera {
public:
Vec3 target = {0.0f, 0.0f, 0.0f};
float distance = 8.0f;
float yaw = 0.0f; // 0で+Z側から見る / 0 looks from the +Z side
float pitch = radians(20.0f); // 正で上から見る / positive looks from above
float fov = radians(45.0f);
float nearPlane = 0.1f, farPlane = 100.0f;
float sensitivity = 0.005f;
Vec3 position() const;
void turn(float dxPixels, float dyPixels);
void zoom(float scrollSteps); // 距離を変える / changes the distance
Mat4 view() const;
Mat4 projection(float aspect) const;
};
Here the angles describe where the eye sits on a sphere around the target, not where it looks.
The eye is distance away from the target in the direction given by yaw and pitch:
Vec3 OrbitCamera::position() const {
Vec3 offset = {std::cos(pitch) * std::sin(yaw), std::sin(pitch), std::cos(pitch) * std::cos(yaw)};
return target + distance * offset;
}
It's the same spherical-coordinates idea as front(), except that yaw 0 puts the eye on the +Z side of the target (looking towards −Z, like the FPS camera's default) and a positive pitch puts it above.
In the Linear Algebra chapter the same thing is written as : the eye is behind the target, against the viewing direction.
With the values from main (target , distance 9, yaw 30°, pitch 20°):
So the default orbit view looks from the front right, about 3.9 m up, which is the screenshot above.
Turning and zooming:
void OrbitCamera::turn(float dxPixels, float dyPixels) {
yaw -= dxPixels * sensitivity; // 右へドラッグすると物が右へ回る / drag right and the object turns right
pitch = std::clamp(pitch + dyPixels * sensitivity, -kMaxPitch, kMaxPitch);
}
void OrbitCamera::zoom(float scrollSteps) {
// 一段ごとに10%近づく(掛け算なので遠くでも近くでも同じ感覚) / 10% closer per step (multiplicative: feels the same near and far)
distance = std::clamp(distance * std::pow(0.9f, scrollSteps), 1.5f, 50.0f);
}
The signs are chosen so that dragging feels like grabbing the scene: drag right and the eye moves left around the target, so the objects turn to the right; drag down and the eye rises, so you look more from above.
The pitch is clamped to ±89° for the same lookAt reason as before.
The zoom is multiplicative: each notch multiplies the distance by 0.9.
From 9 units, one notch gives 8.1, five notches 5.31 and ten notches 3.14.
Adding a fixed amount instead (say 0.5 per notch) would feel too slow when far away and much too fast up close; multiplying makes each notch feel the same.
The distance stays between 1.5 and 50.
The view matrix is simply lookAt from the eye to the target, and the projection is the same as the FPS camera's:
Mat4 OrbitCamera::view() const { return lookAt(position(), target, kWorldUp); }
Mat4 OrbitCamera::projection(float aspect) const { return perspectiveGl(fov, aspect, nearPlane, farPlane); }
In orbit mode the cursor is visible (C calls setCursorCaptured(!useOrbit)), because you need to see where you click.
mouseDelta() still works with a visible cursor; we just use it only while the left button is down.
This class is the base of the third-person camera in chapter 36, where the target is the player and the camera additionally has to avoid walls.
9.8 How real engines do it
- Smoothing. Games rarely apply the mouse directly to the view for everything. Aiming stays direct (players hate input lag), but cinematic or third-person cameras ease towards their target position and rotation every frame. Challenge 4 does this for the FOV.
- Quaternions for free cameras. Yaw and pitch are perfect for people walking on a floor. A spaceship or a flight simulator also needs roll, and three angles in a row run into gimbal lock; those cameras store their orientation as a quaternion (Linear Algebra chapter 13).
- Horizontal FOV. We fix the vertical FOV, so a wider window shows more to the sides ("Hor+"). That's what most modern games do. Some older games fixed the horizontal FOV instead, which cut off the top and bottom on wide screens.
- Camera collision. An orbit camera behind a player would go through walls. Third-person games cast a ray (or a sphere) from the target to the desired eye position and move the camera closer when something is in the way, the "spring arm" in Unreal Engine. We'll build a simple one in chapter 36.
- Input mapping. Engines don't hard-code
GLFW_KEY_W; they map physical keys, mouse buttons and gamepad sticks to actions like "move forward" that players can rebind. Chapter 26 builds a small input layer for the games.
9.9 Summary
- A camera needs mouse movement, not positions.
Window::mouseDelta()adds up the cursor events of one frame;scrollDelta()does the same for the wheel. glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED)hides and locks the cursor for unlimited movement;GLFW_RAW_MOUSE_MOTIONturns off pointer acceleration where supported. Skip the first event after changing the mode.- The FPS camera stores yaw and pitch. Front = with positive yaw turning right; right = normalize(front × up). Clamp the pitch to ±89° or
lookAtbreaks. - Movement is speed ×
dt× a normalized local direction mapped onto the camera's axes. Mouse turning is not multiplied bydt. - FPS zoom changes the field of view; orbit zoom multiplies the distance.
- The orbit camera places the eye on a sphere around a target and calls
lookAt(eye, target, up). - The camera classes are pure math with public fields;
mainreads the input and passes numbers in.
9.10 Challenges
- ★ Add an "invert mouse Y" option on the I key (a
boolinmainthat flips the sign ofmouse.ybeforefps.turn). With it on, moving the mouse up should look down. Also try a few values ofsensitivityandspeedto find what feels right to you. - ★ Turn the fly camera into a walking camera: in
move, use the horizontal front instead offront(), ignoredirection.y, and keepposition.yat 1.6. Looking up and pressing W should no longer lift you off the floor, and walking speed should be the same whatever the pitch. - ★ Print the camera position and yaw/pitch in degrees in the window title every half second (with
window.setTitleanddegrees()fromlinalg.hh). The numbers should change live as you move; check that the start position reads with pitch −8. - ★★ Smooth zoom: keep a
targetFovthat the wheel changes, and every frame move the real FOV towards it withfov += (targetFov - fov) * (1 - std::exp(-10 * dt)). Zooming should ease in and out instead of stepping, at the same speed at any frame rate. - ★★ Let the orbit camera follow a moving crate: move one crate in a circle (
x = 3 cos t,z = 3 sin t) and setorbit.targetto its center every frame. The crate should stay in the middle of the screen while the floor moves underneath, a preview of the third-person camera. - ★★ Anisotropic filtering for the floor: after loading it, call
glTextureParameterf(floorTexture->id(), GL_TEXTURE_MAX_ANISOTROPY, 16.0f)(core in OpenGL 4.6; older drivers have it asGL_TEXTURE_MAX_ANISOTROPY_EXT). Look at the floor at a flat angle: the far tiles should become sharp instead of blurry. Query the maximum withglGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY, &value)first. - ★★★ Build the FPS view matrix without
lookAt:rotateX(-fps.pitch) * rotateY(fps.yaw) * translate(-fps.position). Explain why the rotations are in this order with these signs (the view matrix is the inverse of the camera's own placement, Linear Algebra chapter 10), then print the largest difference between its 16 elements and those offps.view(). You should get the same picture and a difference around .
ファイル: a/CMakeLists.txt | b/CMakeLists.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -34,7 +34,8 @@ add_executable(game | |||
| 34 | src/file_util.cc | 34 | src/file_util.cc |
| 35 | src/shader.cc | 35 | src/shader.cc |
| 36 | src/texture.cc | 36 | src/texture.cc |
| 37 | src/shapes.cc) | 37 | src/shapes.cc |
| 38 | src/camera.cc) | ||
| 38 | target_include_directories(game PRIVATE src external/stb external/linalg) | 39 | target_include_directories(game PRIVATE src external/stb external/linalg) |
| 39 | target_link_libraries(game PRIVATE glad stb_image glfw) | 40 | target_link_libraries(game PRIVATE glad stb_image glfw) |
| 40 | 41 | ||
ファイル: a/assets/LICENSE.txt | b/assets/LICENSE.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -5,3 +5,4 @@ which are not part of this project). Free to use for any purpose. | |||
| 5 | 5 | ||
| 6 | textures/crate.png 木箱 / wooden crate | 6 | textures/crate.png 木箱 / wooden crate |
| 7 | textures/emblem.png 桜の紋章 / sakura emblem | 7 | textures/emblem.png 桜の紋章 / sakura emblem |
| 8 | textures/floor.png 石の床 / stone floor tiles | ||
ファイル: /dev/null | b/assets/textures/floor.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/src/camera.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,64 @@ | |||
| 1 | #include "camera.hh" | ||
| 2 | |||
| 3 | #include <algorithm> | ||
| 4 | #include <cmath> | ||
| 5 | |||
| 6 | // ピッチの限界:±89度(真上を向くとlookAtのcross(前, 上)が0になる) | ||
| 7 | // pitch limit: ±89° (looking straight up makes lookAt's cross(forward, up) zero) | ||
| 8 | constexpr float kMaxPitch = radians(89.0f); | ||
| 9 | constexpr Vec3 kWorldUp = {0.0f, 1.0f, 0.0f}; | ||
| 10 | |||
| 11 | //------------------------------------------ | ||
| 12 | // Camera(FPS) | ||
| 13 | //------------------------------------------ | ||
| 14 | |||
| 15 | Vec3 Camera::front() const { | ||
| 16 | // 球面座標:yawで水平に回し、pitchで持ち上げる / spherical coordinates: yaw turns horizontally, pitch lifts | ||
| 17 | return {std::cos(pitch) * std::sin(yaw), std::sin(pitch), -std::cos(pitch) * std::cos(yaw)}; | ||
| 18 | } | ||
| 19 | |||
| 20 | Vec3 Camera::right() const { return normalize(cross(front(), kWorldUp)); } | ||
| 21 | |||
| 22 | void Camera::turn(float dxPixels, float dyPixels) { | ||
| 23 | yaw += dxPixels * sensitivity; | ||
| 24 | pitch -= dyPixels * sensitivity; // マウスのyは下向きが正 / mouse y grows downwards | ||
| 25 | pitch = std::clamp(pitch, -kMaxPitch, kMaxPitch); | ||
| 26 | } | ||
| 27 | |||
| 28 | void Camera::move(Vec3 direction, float dt) { | ||
| 29 | if (length(direction) == 0.0f) return; | ||
| 30 | direction = normalize(direction); // 斜めでも速さは同じ / same speed diagonally | ||
| 31 | Vec3 velocity = direction.x * right() + direction.y * kWorldUp + direction.z * front(); | ||
| 32 | position = position + (speed * dt) * velocity; | ||
| 33 | } | ||
| 34 | |||
| 35 | void Camera::zoom(float scrollSteps) { | ||
| 36 | fov = std::clamp(fov - radians(2.0f) * scrollSteps, radians(15.0f), radians(75.0f)); | ||
| 37 | } | ||
| 38 | |||
| 39 | Mat4 Camera::view() const { return lookAt(position, position + front(), kWorldUp); } | ||
| 40 | |||
| 41 | Mat4 Camera::projection(float aspect) const { return perspectiveGl(fov, aspect, nearPlane, farPlane); } | ||
| 42 | |||
| 43 | //------------------------------------------ | ||
| 44 | // OrbitCamera | ||
| 45 | //------------------------------------------ | ||
| 46 | |||
| 47 | Vec3 OrbitCamera::position() const { | ||
| 48 | Vec3 offset = {std::cos(pitch) * std::sin(yaw), std::sin(pitch), std::cos(pitch) * std::cos(yaw)}; | ||
| 49 | return target + distance * offset; | ||
| 50 | } | ||
| 51 | |||
| 52 | void OrbitCamera::turn(float dxPixels, float dyPixels) { | ||
| 53 | yaw -= dxPixels * sensitivity; // 右へドラッグすると物が右へ回る / drag right and the object turns right | ||
| 54 | pitch = std::clamp(pitch + dyPixels * sensitivity, -kMaxPitch, kMaxPitch); | ||
| 55 | } | ||
| 56 | |||
| 57 | void OrbitCamera::zoom(float scrollSteps) { | ||
| 58 | // 一段ごとに10%近づく(掛け算なので遠くでも近くでも同じ感覚) / 10% closer per step (multiplicative: feels the same near and far) | ||
| 59 | distance = std::clamp(distance * std::pow(0.9f, scrollSteps), 1.5f, 50.0f); | ||
| 60 | } | ||
| 61 | |||
| 62 | Mat4 OrbitCamera::view() const { return lookAt(position(), target, kWorldUp); } | ||
| 63 | |||
| 64 | Mat4 OrbitCamera::projection(float aspect) const { return perspectiveGl(fov, aspect, nearPlane, farPlane); } | ||
ファイル: /dev/null | b/src/camera.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,51 @@ | |||
| 1 | // カメラ / cameras | ||
| 2 | #pragma once | ||
| 3 | |||
| 4 | #include <linalg.hh> | ||
| 5 | |||
| 6 | // 一人称(FPS)の飛べるカメラ。向きはヨー(左右)とピッチ(上下)で表す。 | ||
| 7 | // A first-person (FPS) fly camera. Its direction is yaw (left/right) and pitch (up/down). | ||
| 8 | class Camera { | ||
| 9 | public: | ||
| 10 | Vec3 position = {0.0f, 0.0f, 3.0f}; | ||
| 11 | float yaw = 0.0f; // ラジアン。0で-Zを向き、正で右へ回る / radians. 0 looks down -Z, positive turns right | ||
| 12 | float pitch = 0.0f; // ラジアン。正で上を向く / radians. positive looks up | ||
| 13 | float fov = radians(45.0f); // 縦の視野角 / vertical field of view | ||
| 14 | float nearPlane = 0.1f, farPlane = 100.0f; | ||
| 15 | float speed = 3.0f; // 単位毎秒 / units per second | ||
| 16 | float sensitivity = 0.0025f; // ラジアン毎ピクセル / radians per pixel of mouse movement | ||
| 17 | |||
| 18 | Vec3 front() const; // 見ている方向(単位ベクトル) / the viewing direction (unit vector) | ||
| 19 | Vec3 right() const; // 右(水平) / right (horizontal) | ||
| 20 | |||
| 21 | // マウスの移動量(ピクセル)で向きを変える。真上・真下は向けない。 | ||
| 22 | // Turns by a mouse movement in pixels. Cannot look straight up or down. | ||
| 23 | void turn(float dxPixels, float dyPixels); | ||
| 24 | // ローカルな方向(x = 右、y = 上、z = 前)に dt 秒だけ動く / moves for dt seconds in a local direction (x right, y up, z forward) | ||
| 25 | void move(Vec3 direction, float dt); | ||
| 26 | // ホイールで視野角を変える(ズーム) / changes the field of view with the scroll wheel (zoom) | ||
| 27 | void zoom(float scrollSteps); | ||
| 28 | |||
| 29 | Mat4 view() const; | ||
| 30 | Mat4 projection(float aspect) const; | ||
| 31 | }; | ||
| 32 | |||
| 33 | // 注視点の周りを回るカメラ(モデルビューアーやTPS向け)。 | ||
| 34 | // A camera that orbits a target point (for model viewers and third-person games). | ||
| 35 | class OrbitCamera { | ||
| 36 | public: | ||
| 37 | Vec3 target = {0.0f, 0.0f, 0.0f}; | ||
| 38 | float distance = 8.0f; | ||
| 39 | float yaw = 0.0f; // 0で+Z側から見る / 0 looks from the +Z side | ||
| 40 | float pitch = radians(20.0f); // 正で上から見る / positive looks from above | ||
| 41 | float fov = radians(45.0f); | ||
| 42 | float nearPlane = 0.1f, farPlane = 100.0f; | ||
| 43 | float sensitivity = 0.005f; | ||
| 44 | |||
| 45 | Vec3 position() const; | ||
| 46 | void turn(float dxPixels, float dyPixels); | ||
| 47 | void zoom(float scrollSteps); // 距離を変える / changes the distance | ||
| 48 | |||
| 49 | Mat4 view() const; | ||
| 50 | Mat4 projection(float aspect) const; | ||
| 51 | }; | ||
ファイル: a/src/main.cc | b/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,11 +1,17 @@ | |||
| 1 | // 第8章:3Dへ:座標系と深度 | 1 | // 第9章:カメラ |
| 2 | // Chapter 8: going 3D: coordinate systems and depth | 2 | // Chapter 9: the camera |
| 3 | // | 3 | // |
| 4 | // 操作 / Controls: | 4 | // 操作 / Controls: |
| 5 | // Z 深度テストの切り替え / toggle the depth test | 5 | // WASD 前後左右に移動 / move forward, back, left, right |
| 6 | // スペース 一時停止 / pause | 6 | // Space / Ctrl 上昇・下降 / move up / down |
| 7 | // R シェーダーを読み直す / reload the shaders | 7 | // Shift 速く動く / move faster |
| 8 | // Esc 終了 / quit | 8 | // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit |
| 9 | // ホイール / wheel ズーム(FPSは視野角、オービットは距離) / zoom (FPS: field of view, orbit: distance) | ||
| 10 | // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera | ||
| 11 | // Tab カーソルのキャプチャ切り替え / toggle cursor capture | ||
| 12 | // R シェーダーを読み直す / reload the shaders | ||
| 13 | // Esc 終了 / quit | ||
| 14 | #include "camera.hh" | ||
| 9 | #include "mesh.hh" | 15 | #include "mesh.hh" |
| 10 | #include "shader.hh" | 16 | #include "shader.hh" |
| 11 | #include "shapes.hh" | 17 | #include "shapes.hh" |
| @@ -17,86 +23,115 @@ | |||
| 17 | #include <cstdio> | 23 | #include <cstdio> |
| 18 | #include <optional> | 24 | #include <optional> |
| 19 | 25 | ||
| 20 | // 立方体の位置と回転軸 / where each cube is and the axis it spins around | 26 | // 床に置いた箱:位置(底の中心)、大きさ、Y軸周りの回転 / crates on the floor: position (bottom centre), size, yaw |
| 21 | struct CubeInfo { | 27 | struct CrateInfo { |
| 22 | Vec3 position; | 28 | Vec3 position; |
| 23 | Vec3 axis; | 29 | float size; |
| 24 | float speed; // ラジアン毎秒 / radians per second | 30 | float angle; |
| 25 | }; | 31 | }; |
| 26 | 32 | ||
| 27 | static const CubeInfo kCubes[] = { | 33 | static const CrateInfo kCrates[] = { |
| 28 | {{0.0f, 0.0f, 0.0f}, {0.3f, 1.0f, 0.2f}, 0.6f}, | 34 | {{0.0f, 0.0f, 0.0f}, 1.0f, 0.0f}, {{1.1f, 0.0f, 0.2f}, 1.0f, 0.3f}, |
| 29 | {{2.4f, 1.2f, -3.5f}, {1.0f, 0.3f, 0.0f}, 0.9f}, | 35 | {{0.5f, 1.0f, 0.1f}, 1.0f, -0.2f}, {{-3.0f, 0.0f, -2.0f}, 2.0f, 0.6f}, |
| 30 | {{-2.2f, -1.0f, -2.5f}, {0.0f, 1.0f, 0.6f}, -0.7f}, | 36 | {{-3.0f, 2.0f, -2.0f}, 1.0f, 0.1f}, {{4.0f, 0.0f, -4.0f}, 1.5f, -0.5f}, |
| 31 | {{-3.8f, 1.6f, -7.0f}, {0.5f, 0.5f, 0.1f}, 0.5f}, | 37 | {{-6.0f, 0.0f, 3.0f}, 1.0f, 0.9f}, {{6.5f, 0.0f, 2.5f}, 1.0f, 0.2f}, |
| 32 | {{2.6f, -1.3f, -1.2f}, {0.2f, 0.4f, 1.0f}, -1.1f}, | 38 | {{2.0f, 0.0f, -9.0f}, 3.0f, 0.4f}, {{-8.0f, 0.0f, -8.0f}, 2.0f, -0.3f}, |
| 33 | {{-1.3f, 2.0f, -4.0f}, {1.0f, 0.0f, 0.4f}, 0.8f}, | 39 | {{9.0f, 0.0f, -12.0f}, 2.5f, 0.7f}, {{-2.5f, 0.0f, 5.5f}, 0.6f, 0.5f}, |
| 34 | {{1.0f, -0.6f, -6.5f}, {0.7f, 1.0f, 0.3f}, -0.5f}, | ||
| 35 | {{4.8f, 0.4f, -8.5f}, {0.1f, 1.0f, 0.9f}, 1.2f}, | ||
| 36 | {{-4.4f, -1.5f, -5.5f}, {0.9f, 0.2f, 0.6f}, -0.9f}, | ||
| 37 | {{0.4f, 2.6f, -9.5f}, {0.4f, 0.8f, 1.0f}, 0.7f}, | ||
| 38 | }; | 40 | }; |
| 39 | 41 | ||
| 40 | int main() { | 42 | int main() { |
| 41 | Window window; | 43 | Window window; |
| 42 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 8")) return 1; | 44 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 9")) return 1; |
| 43 | 45 | ||
| 44 | std::optional<Shader> shader = Shader::load("shaders/textured.vert", "shaders/textured.frag"); | 46 | std::optional<Shader> shader = Shader::load("shaders/textured.vert", "shaders/textured.frag"); |
| 45 | std::optional<Texture2D> crate = Texture2D::load("assets/textures/crate.png"); | 47 | std::optional<Texture2D> crate = Texture2D::load("assets/textures/crate.png"); |
| 46 | std::optional<Texture2D> emblem = Texture2D::load("assets/textures/emblem.png"); | 48 | std::optional<Texture2D> emblem = Texture2D::load("assets/textures/emblem.png"); |
| 47 | if (!shader || !crate || !emblem) return 1; | 49 | std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png"); |
| 48 | 50 | if (!shader || !crate || !emblem || !floorTexture) return 1; | |
| 49 | // 近いものが遠いものを隠すようにする / make near things hide far things | ||
| 50 | bool depthTest = true; | ||
| 51 | glEnable(GL_DEPTH_TEST); | 51 | glEnable(GL_DEPTH_TEST); |
| 52 | 52 | ||
| 53 | bool paused = false; | 53 | Camera fps; |
| 54 | fps.position = {0.0f, 1.6f, 7.0f}; // 目の高さ / eye height | ||
| 55 | fps.pitch = radians(-8.0f); | ||
| 56 | |||
| 57 | OrbitCamera orbit; | ||
| 58 | orbit.target = {0.0f, 0.8f, 0.0f}; | ||
| 59 | orbit.distance = 9.0f; | ||
| 60 | orbit.yaw = radians(30.0f); | ||
| 61 | |||
| 62 | bool useOrbit = false; | ||
| 63 | window.setCursorCaptured(true); // FPSはカーソルを隠して固定 / FPS: hide and lock the cursor | ||
| 64 | |||
| 54 | window.onKey = [&](int key, int action, int /*mods*/) { | 65 | window.onKey = [&](int key, int action, int /*mods*/) { |
| 55 | if (action != GLFW_PRESS) return; | 66 | if (action != GLFW_PRESS) return; |
| 56 | if (key == GLFW_KEY_ESCAPE) window.close(); | 67 | if (key == GLFW_KEY_ESCAPE) window.close(); |
| 57 | if (key == GLFW_KEY_SPACE) paused = !paused; | ||
| 58 | if (key == GLFW_KEY_R && shader->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); | 68 | if (key == GLFW_KEY_R && shader->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); |
| 59 | if (key == GLFW_KEY_Z) { | 69 | if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); |
| 60 | depthTest = !depthTest; | 70 | if (key == GLFW_KEY_C) { |
| 61 | if (depthTest) | 71 | useOrbit = !useOrbit; |
| 62 | glEnable(GL_DEPTH_TEST); | 72 | // オービットはマウスでドラッグするのでカーソルを見せる / orbit is dragged with the mouse, so show the cursor |
| 63 | else | 73 | window.setCursorCaptured(!useOrbit); |
| 64 | glDisable(GL_DEPTH_TEST); | 74 | printf("camera: %s\n", useOrbit ? "orbit" : "fps"); |
| 65 | printf("depth test %s\n", depthTest ? "on" : "off"); | ||
| 66 | } | 75 | } |
| 67 | }; | 76 | }; |
| 68 | 77 | ||
| 69 | Mesh cube = makeCube(); | 78 | Mesh cube = makeCube(); |
| 79 | // 40×40の床。テクスチャにタイル4枚なので10回繰り返すと1タイル = 1単位 | ||
| 80 | // A 40 × 40 floor. The texture holds 4 tiles, so repeating it 10 times makes one tile = one unit | ||
| 81 | Mesh floorMesh = makePlane(40.0f, 10.0f); | ||
| 70 | 82 | ||
| 71 | float t = 0.0f; | ||
| 72 | double lastTime = window.time(); | 83 | double lastTime = window.time(); |
| 73 | while (!window.shouldClose()) { | 84 | while (!window.shouldClose()) { |
| 74 | double now = window.time(); | 85 | double now = window.time(); |
| 75 | float dt = static_cast<float>(now - lastTime); | 86 | float dt = static_cast<float>(now - lastTime); |
| 76 | lastTime = now; | 87 | lastTime = now; |
| 77 | window.pollEvents(); | 88 | window.pollEvents(); |
| 78 | if (!paused) t += dt; | 89 | |
| 90 | Vec2 mouse = window.mouseDelta(); | ||
| 91 | if (useOrbit) { | ||
| 92 | if (window.mouseButtonDown(GLFW_MOUSE_BUTTON_LEFT)) orbit.turn(mouse.x, mouse.y); | ||
| 93 | orbit.zoom(window.scrollDelta()); | ||
| 94 | } else { | ||
| 95 | if (window.cursorCaptured()) fps.turn(mouse.x, mouse.y); | ||
| 96 | fps.zoom(window.scrollDelta()); | ||
| 97 | |||
| 98 | // キーからローカルな移動方向を作る(x = 右、y = 上、z = 前) / build a local direction from the keys | ||
| 99 | Vec3 dir; | ||
| 100 | if (window.keyDown(GLFW_KEY_W)) dir.z += 1.0f; | ||
| 101 | if (window.keyDown(GLFW_KEY_S)) dir.z -= 1.0f; | ||
| 102 | if (window.keyDown(GLFW_KEY_D)) dir.x += 1.0f; | ||
| 103 | if (window.keyDown(GLFW_KEY_A)) dir.x -= 1.0f; | ||
| 104 | if (window.keyDown(GLFW_KEY_SPACE)) dir.y += 1.0f; | ||
| 105 | if (window.keyDown(GLFW_KEY_LEFT_CONTROL)) dir.y -= 1.0f; | ||
| 106 | fps.speed = window.keyDown(GLFW_KEY_LEFT_SHIFT) ? 9.0f : 3.0f; | ||
| 107 | // dtを掛けるのでフレームレートに関係なく同じ速さ / multiplied by dt: the same speed at any frame rate | ||
| 108 | fps.move(dir, dt); | ||
| 109 | } | ||
| 110 | |||
| 111 | Mat4 view = useOrbit ? orbit.view() : fps.view(); | ||
| 112 | Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect()); | ||
| 79 | 113 | ||
| 80 | glClearColor(0.10f, 0.15f, 0.25f, 1.0f); | 114 | glClearColor(0.10f, 0.15f, 0.25f, 1.0f); |
| 81 | // 色と深度の両方を毎フレーム消す / clear both colour and depth every frame | ||
| 82 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); | 115 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); |
| 83 | 116 | ||
| 84 | // ビュー:カメラは(0, 1.5, 6)から少し奥を見る / view: the camera at (0, 1.5, 6) looks a little into the scene | ||
| 85 | Mat4 view = lookAt({0.0f, 1.5f, 6.0f}, {0.0f, 0.0f, -2.0f}, {0.0f, 1.0f, 0.0f}); | ||
| 86 | // 投影:縦の視野角45度。アスペクト比は毎フレーム読むので、ウィンドウを変えても歪まない。 | ||
| 87 | // projection: 45° vertical field of view. The aspect ratio is read every frame, so resizing does not distort. | ||
| 88 | Mat4 proj = perspectiveGl(radians(45.0f), window.aspect(), 0.1f, 100.0f); | ||
| 89 | |||
| 90 | crate->bind(0); | ||
| 91 | emblem->bind(1); | ||
| 92 | shader->use(); | 117 | shader->use(); |
| 93 | shader->set("uMix", 0.8f); | ||
| 94 | shader->set("uEmblemScale", 1.0f); | ||
| 95 | shader->set("uView", view); | 118 | shader->set("uView", view); |
| 96 | shader->set("uProj", proj); | 119 | shader->set("uProj", proj); |
| 120 | shader->set("uEmblemScale", 1.0f); | ||
| 97 | 121 | ||
| 98 | for (const CubeInfo &c : kCubes) { | 122 | // 床:二枚目のテクスチャは混ぜない / the floor: no second texture |
| 99 | shader->set("uModel", translate(c.position) * rotate(c.axis, t * c.speed + c.position.x)); | 123 | floorTexture->bind(0); |
| 124 | emblem->bind(1); | ||
| 125 | shader->set("uMix", 0.0f); | ||
| 126 | shader->set("uModel", Mat4::identity()); | ||
| 127 | floorMesh.draw(); | ||
| 128 | |||
| 129 | // 箱:立方体は原点が中心なので半分持ち上げて床に置く / crates: the cube is centred, so lift it by half its size | ||
| 130 | crate->bind(0); | ||
| 131 | shader->set("uMix", 0.8f); | ||
| 132 | for (const CrateInfo &c : kCrates) { | ||
| 133 | Vec3 centre = c.position + Vec3{0.0f, 0.5f * c.size, 0.0f}; | ||
| 134 | shader->set("uModel", translate(centre) * rotateY(c.angle) * scale({c.size, c.size, c.size})); | ||
| 100 | cube.draw(); | 135 | cube.draw(); |
| 101 | } | 136 | } |
| 102 | 137 | ||
ファイル: a/src/shapes.cc | b/src/shapes.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -28,3 +28,16 @@ Mesh makeCube() { | |||
| 28 | addFace(vertices, indices, {0, -1, 0}, {1, 0, 0}, {0, 0, 1}); // 下 -Y / bottom | 28 | addFace(vertices, indices, {0, -1, 0}, {1, 0, 0}, {0, 0, 1}); // 下 -Y / bottom |
| 29 | return Mesh(vertices, indices, kVertex3DLayout); | 29 | return Mesh(vertices, indices, kVertex3DLayout); |
| 30 | } | 30 | } |
| 31 | |||
| 32 | Mesh makePlane(float size, float uvRepeat) { | ||
| 33 | float h = 0.5f * size; | ||
| 34 | Vec3 n = {0.0f, 1.0f, 0.0f}; | ||
| 35 | // 上から見て反時計回り / counter-clockwise seen from above | ||
| 36 | std::vector<Vertex3D> vertices = { | ||
| 37 | {{-h, 0.0f, h}, n, {0.0f, 0.0f}}, | ||
| 38 | {{h, 0.0f, h}, n, {uvRepeat, 0.0f}}, | ||
| 39 | {{h, 0.0f, -h}, n, {uvRepeat, uvRepeat}}, | ||
| 40 | {{-h, 0.0f, -h}, n, {0.0f, uvRepeat}}, | ||
| 41 | }; | ||
| 42 | return Mesh(vertices, {0, 1, 2, 2, 3, 0}, kVertex3DLayout); | ||
| 43 | } | ||
ファイル: a/src/shapes.hh | b/src/shapes.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -8,3 +8,7 @@ | |||
| 8 | // A 1×1×1 cube centred on the origin. 4 vertices per face (UVs and normals differ per face, so corners | 8 | // A 1×1×1 cube centred on the origin. 4 vertices per face (UVs and normals differ per face, so corners |
| 9 | // cannot be shared) = 24 vertices, 36 indices. Counter-clockwise seen from outside (for culling in chapter 16). | 9 | // cannot be shared) = 24 vertices, 36 indices. Counter-clockwise seen from outside (for culling in chapter 16). |
| 10 | Mesh makeCube(); | 10 | Mesh makeCube(); |
| 11 | |||
| 12 | // XZ平面上のsize×sizeの床(y = 0、法線は+Y)。UVはuvRepeat回繰り返す(GL_REPEATが必要)。 | ||
| 13 | // A size × size floor on the XZ plane (y = 0, normal +Y). UVs repeat uvRepeat times (needs GL_REPEAT). | ||
| 14 | Mesh makePlane(float size, float uvRepeat); | ||
ファイル: a/src/window.cc | b/src/window.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -67,7 +67,20 @@ bool Window::create(int width, int height, const char *title) { | |||
| 67 | 67 | ||
| 68 | bool Window::shouldClose() const { return glfwWindowShouldClose(glfwWindow); } | 68 | bool Window::shouldClose() const { return glfwWindowShouldClose(glfwWindow); } |
| 69 | void Window::close() { glfwSetWindowShouldClose(glfwWindow, GLFW_TRUE); } | 69 | void Window::close() { glfwSetWindowShouldClose(glfwWindow, GLFW_TRUE); } |
| 70 | void Window::pollEvents() { glfwPollEvents(); } | 70 | void Window::pollEvents() { |
| 71 | // 今回のフレームの分を数え直す(コールバックで足していく) / start counting this frame (the callbacks add to these) | ||
| 72 | frameMouseDelta = {0.0f, 0.0f}; | ||
| 73 | frameScroll = 0.0f; | ||
| 74 | glfwPollEvents(); | ||
| 75 | } | ||
| 76 | |||
| 77 | void Window::setCursorCaptured(bool on) { | ||
| 78 | captured = on; | ||
| 79 | glfwSetInputMode(glfwWindow, GLFW_CURSOR, on ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL); | ||
| 80 | // OSのマウス加速なしの生の動き(使えれば) / raw motion without OS mouse acceleration (if available) | ||
| 81 | if (glfwRawMouseMotionSupported()) glfwSetInputMode(glfwWindow, GLFW_RAW_MOUSE_MOTION, on ? GLFW_TRUE : GLFW_FALSE); | ||
| 82 | skipNextDelta = true; | ||
| 83 | } | ||
| 71 | void Window::swapBuffers() { glfwSwapBuffers(glfwWindow); } | 84 | void Window::swapBuffers() { glfwSwapBuffers(glfwWindow); } |
| 72 | void Window::setTitle(const char *title) { glfwSetWindowTitle(glfwWindow, title); } | 85 | void Window::setTitle(const char *title) { glfwSetWindowTitle(glfwWindow, title); } |
| 73 | 86 | ||
| @@ -112,6 +125,11 @@ void Window::mouseButtonCallback(GLFWwindow *w, int button, int action, int mods | |||
| 112 | 125 | ||
| 113 | void Window::cursorPosCallback(GLFWwindow *w, double x, double y) { | 126 | void Window::cursorPosCallback(GLFWwindow *w, double x, double y) { |
| 114 | Window *win = self(w); | 127 | Window *win = self(w); |
| 128 | if (!win->skipNextDelta) { | ||
| 129 | win->frameMouseDelta.x += static_cast<float>(x - win->cursorX); | ||
| 130 | win->frameMouseDelta.y += static_cast<float>(y - win->cursorY); | ||
| 131 | } | ||
| 132 | win->skipNextDelta = false; | ||
| 115 | win->cursorX = x; | 133 | win->cursorX = x; |
| 116 | win->cursorY = y; | 134 | win->cursorY = y; |
| 117 | if (win->onCursorPos) win->onCursorPos(x, y); | 135 | if (win->onCursorPos) win->onCursorPos(x, y); |
| @@ -119,5 +137,6 @@ void Window::cursorPosCallback(GLFWwindow *w, double x, double y) { | |||
| 119 | 137 | ||
| 120 | void Window::scrollCallback(GLFWwindow *w, double dx, double dy) { | 138 | void Window::scrollCallback(GLFWwindow *w, double dx, double dy) { |
| 121 | Window *win = self(w); | 139 | Window *win = self(w); |
| 140 | win->frameScroll += static_cast<float>(dy); | ||
| 122 | if (win->onScroll) win->onScroll(dx, dy); | 141 | if (win->onScroll) win->onScroll(dx, dy); |
| 123 | } | 142 | } |
ファイル: a/src/window.hh | b/src/window.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -4,6 +4,7 @@ | |||
| 4 | // GLADはGLFWより先にインクルードする / include GLAD before GLFW | 4 | // GLADはGLFWより先にインクルードする / include GLAD before GLFW |
| 5 | #include <glad/glad.h> | 5 | #include <glad/glad.h> |
| 6 | #include <GLFW/glfw3.h> | 6 | #include <GLFW/glfw3.h> |
| 7 | #include <linalg.hh> | ||
| 7 | 8 | ||
| 8 | #include <functional> | 9 | #include <functional> |
| 9 | 10 | ||
| @@ -48,6 +49,15 @@ public: | |||
| 48 | double mouseX() const { return cursorX; } // ウィンドウ座標、左上が原点 / window coords, origin top-left | 49 | double mouseX() const { return cursorX; } // ウィンドウ座標、左上が原点 / window coords, origin top-left |
| 49 | double mouseY() const { return cursorY; } | 50 | double mouseY() const { return cursorY; } |
| 50 | 51 | ||
| 52 | // 前のpollEvents()から今回までのマウスの移動量とホイールの回転量 / mouse movement and scroll since the last pollEvents() | ||
| 53 | Vec2 mouseDelta() const { return frameMouseDelta; } | ||
| 54 | float scrollDelta() const { return frameScroll; } | ||
| 55 | |||
| 56 | // カーソルを隠して固定する(FPSカメラ用)。移動量は無制限に取れる。 | ||
| 57 | // Hides and locks the cursor (for FPS cameras). Movement is then unlimited. | ||
| 58 | void setCursorCaptured(bool captured); | ||
| 59 | bool cursorCaptured() const { return captured; } | ||
| 60 | |||
| 51 | // コールバック(設定は任意) / callbacks (all optional) | 61 | // コールバック(設定は任意) / callbacks (all optional) |
| 52 | std::function<void(int key, int action, int mods)> onKey; | 62 | std::function<void(int key, int action, int mods)> onKey; |
| 53 | std::function<void(int button, int action, int mods)> onMouseButton; | 63 | std::function<void(int button, int action, int mods)> onMouseButton; |
| @@ -68,5 +78,9 @@ private: | |||
| 68 | bool glfwStarted = false; | 78 | bool glfwStarted = false; |
| 69 | int fbWidth = 0, fbHeight = 0; | 79 | int fbWidth = 0, fbHeight = 0; |
| 70 | double cursorX = 0.0, cursorY = 0.0; | 80 | double cursorX = 0.0, cursorY = 0.0; |
| 81 | Vec2 frameMouseDelta; | ||
| 82 | float frameScroll = 0.0f; | ||
| 83 | bool captured = false; | ||
| 84 | bool skipNextDelta = true; // 最初とキャプチャ切り替え直後の飛びを無視 / ignore the jump at start and after (un)capturing | ||
| 71 | bool vsyncOn = true; | 85 | bool vsyncOn = true; |
| 72 | }; | 86 | }; |
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。