Caffeine

Camera 3D Implementation Plan

Historical Last updated:

For Claude: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.

Goal: Implement Camera3D with perspective projection, FPS/Orbital/Follow modes, and frustum culling integration (RF5.5, RF5.6).

Architecture: Single inline header src/caffeine/render/Camera3D.hpp following the same pattern as Camera2D.hpp — Dirty-flagged VP cache, all methods inline, .cpp file. Integrates with existing Spatial::Frustum::fromCamera() for culling and uses Mat4::perspective() / Quat::toMatrix() for matrix construction.

Tech Stack: C++20, custom math (Vec3, Quat, Mat4), ECS (Entity/World), Spatial (AABB3D/Frustum)


Task 1: Create Camera3D header#

Files:

  • Create: src/caffeine/render/Camera3D.hpp
  • Implementation — complete file content:*
cpp
#pragma once

#include "RenderTypes.hpp"
#include "../math/Vec2.hpp"
#include "../math/Vec3.hpp"
#include "../math/Mat4.hpp"
#include "../math/Quat.hpp"
#include "../math/Math.hpp"
#include "../spatial/Octree.hpp"
#include "../ecs/Entity.hpp"
#include "../ecs/World.hpp"
#include "../ecs/Components3D.hpp"
#include <cmath>

namespace Caffeine::Render {

using namespace Caffeine;

// ============================================================================
// @brief  Câmera 3D com projeção perspectiva.
//
//  Modos:
//  - FPS: mouse look, WASD movement
//  - Orbital: rotação em torno de um ponto (editor, estratégia)
//  - Follow: segue entidade com offset (terceira pessoa)
// ============================================================================
class Camera3D {
public:
    Camera3D() = default;

    // ── Matrices ──────────────────────────────────────────────────────────────

    Mat4 viewMatrix() const {
        return calculateViewMatrix();
    }

    Mat4 projectionMatrix() const {
        return calculateProjectionMatrix();
    }

    Mat4 viewProjectionMatrix() const {
        if (m_dirty) {
            m_cachedVP = calculateProjectionMatrix() * calculateViewMatrix();
            m_dirty = false;
        }
        return m_cachedVP;
    }

    // ── Frustum ──────────────────────────────────────────────────────────────

    Spatial::Frustum frustum() const {
        Vec3 fwd = forward();
        Vec3 pos = effectivePosition();
        return Spatial::Frustum::fromCamera(
            pos, pos + fwd, Vec3::up(),
            Math::degToRad(m_fovY), m_aspect, m_near, m_far
        );
    }

    // ── Space conversion ─────────────────────────────────────────────────────

    Vec3 worldToScreen(Vec3 worldPos) const {
        Mat4 vp = viewProjectionMatrix();
        Vec3 p  = vp.transformPoint(worldPos);
        // NDC → screen (Y flipped: NDC +Y = up, screen +Y = down)
        f32 sx = (p.x + 1.0f) * 0.5f * m_viewport.size.x + m_viewport.position.x;
        f32 sy = (1.0f - p.y) * 0.5f * m_viewport.size.y + m_viewport.position.y;
        f32 sz = (p.z + 1.0f) * 0.5f; // depth 0-1
        return { sx, sy, sz };
    }

    Vec3 screenToWorld(Vec2 screenPos, f32 depth = 0.5f) const {
        // Screen → NDC
        f32 ndcX = (screenPos.x - m_viewport.position.x) / m_viewport.size.x * 2.0f - 1.0f;
        f32 ndcY = 1.0f - (screenPos.y - m_viewport.position.y) / m_viewport.size.y * 2.0f;
        f32 ndcZ = depth * 2.0f - 1.0f;

        // Unproject via inverse VP
        Mat4 invVP = viewProjectionMatrix().inverted();
        return invVP.transformPoint({ ndcX, ndcY, ndcZ });
    }

    bool isVisible(const Spatial::AABB3D& bounds) const {
        return frustum().intersects(bounds);
    }

    // ── Perspective configuration ────────────────────────────────────────────

    void setFOV(f32 fovYDegrees) {
        m_fovY  = fovYDegrees;
        m_dirty = true;
    }

    void setAspect(f32 aspect) {
        m_aspect = aspect;
        m_dirty  = true;
    }

    void setNearFar(f32 nearPlane, f32 farPlane) {
        m_near  = nearPlane;
        m_far   = farPlane;
        m_dirty = true;
    }

    void setViewport(Rect2D viewport) {
        m_viewport = viewport;
        m_dirty    = true;
    }

    // ── Transform ────────────────────────────────────────────────────────────

    void setPosition(Vec3 pos) {
        m_position = pos;
        syncRotationToAngles();
        m_dirty = true;
    }

    void setRotation(Quat rot) {
        m_rotation = rot;
        syncAnglesToRotation();
        m_dirty = true;
    }

    void lookAt(Vec3 eye, Vec3 target, Vec3 up = {0, 1, 0}) {
        m_position = eye;
        Vec3 fwd = (target - eye).normalized();
        if (fwd.lengthSquared() < 1e-8f) fwd = {0, 0, 1};
        m_rotation = Quat::lookAt(fwd, up);
        syncAnglesToRotation();
        m_dirty = true;
    }

    // ── FPS mode ─────────────────────────────────────────────────────────────

    void rotateFPS(f32 deltaPitch, f32 deltaYaw) {
        m_pitch += deltaPitch;
        m_yaw   += deltaYaw;
        m_pitch  = Math::clamp(m_pitch, -89.0f, 89.0f);
        syncRotationToAngles();
        m_dirty = true;
    }

    void moveFPS(Vec3 localDelta) {
        m_position = m_position + right() * localDelta.x
                                 + Vec3::up() * localDelta.y
                                 + forward() * localDelta.z;
        m_dirty = true;
    }

    // ── Orbital mode ─────────────────────────────────────────────────────────

    void orbit(f32 deltaAzimuth, f32 deltaElevation) {
        m_azimuth   += deltaAzimuth;
        m_elevation += deltaElevation;
        m_elevation  = Math::clamp(m_elevation, -89.0f, 89.0f);
        updateOrbitalPosition();
        m_dirty = true;
    }

    void setOrbitTarget(Vec3 target) {
        m_orbitTarget = target;
        updateOrbitalPosition();
        m_dirty = true;
    }

    void setOrbitDistance(f32 distance) {
        m_orbitDistance = distance > 0.0f ? distance : 0.001f;
        updateOrbitalPosition();
        m_dirty = true;
    }

    void zoom(f32 delta) {
        setOrbitDistance(m_orbitDistance + delta);
    }

    // ── Follow mode ──────────────────────────────────────────────────────────

    void follow(ECS::Entity target, Vec3 offset = {0, 2, -5}, f32 smoothing = 0.05f) {
        m_followTarget    = target;
        m_followOffset    = offset;
        m_followSmoothing = smoothing;
    }

    void stopFollowing() {
        m_followTarget = ECS::Entity::INVALID;
    }

    void update(f64 dt, const ECS::World& world) {
        if (m_followTarget.isValid()) {
            const auto* pos = world.get<ECS::Position3D>(m_followTarget);
            if (pos) {
                Vec3 target = pos->position + m_followOffset;
                m_position = Vec3(
                    Math::lerp(m_position.x, target.x, m_followSmoothing),
                    Math::lerp(m_position.y, target.y, m_followSmoothing),
                    Math::lerp(m_position.z, target.z, m_followSmoothing)
                );
                syncRotationToAngles();
                m_dirty = true;
            }
        }
    }

    // ── Getters ──────────────────────────────────────────────────────────────

    Vec3 position() const { return m_position; }
    Quat rotation() const { return m_rotation; }

    Vec3 forward() const {
        return m_rotation.rotate({0, 0, 1});
    }

    Vec3 right() const {
        return m_rotation.rotate({1, 0, 0});
    }

    Vec3 up() const {
        return m_rotation.rotate({0, 1, 0});
    }

    f32  fov()       const { return m_fovY; }
    f32  aspect()    const { return m_aspect; }
    f32  nearPlane() const { return m_near; }
    f32  farPlane()  const { return m_far; }
    Rect2D viewport() const { return m_viewport; }

private:
    // ── Matrix construction ───────────────────────────────────────────────────

    Mat4 calculateViewMatrix() const {
        // View = rotation⁻¹ * translation⁻¹
        // Since Quat is unit, inverse = conjugate
        Mat4 rot   = m_rotation.conjugate().toMatrix();
        Vec3 ep    = effectivePosition();
        Mat4 trans = Mat4::translation(-ep.x, -ep.y, -ep.z);
        return rot * trans;
    }

    Mat4 calculateProjectionMatrix() const {
        return Mat4::perspective(Math::degToRad(m_fovY), m_aspect, m_near, m_far);
    }

    Vec3 effectivePosition() const {
        return m_position;
    }

    // ── Rotation ↔ Euler sync ────────────────────────────────────────────────

    void syncRotationToAngles() {
        Vec3 euler = m_rotation.toEuler();
        m_pitch = Math::radToDeg(euler.x);
        m_yaw   = Math::radToDeg(euler.y);
    }

    void syncAnglesToRotation() {
        m_rotation = Quat::fromEuler(
            Math::degToRad(m_pitch),
            Math::degToRad(m_yaw),
            0.0f // roll always 0 for FPS/orbital
        );
    }

    // ── Orbital helper ───────────────────────────────────────────────────────

    void updateOrbitalPosition() {
        f32 azRad   = Math::degToRad(m_azimuth);
        f32 elRad   = Math::degToRad(m_elevation);
        Vec3 offset = {
            cosf(elRad) * sinf(azRad) * m_orbitDistance,
            sinf(elRad) * m_orbitDistance,
            cosf(elRad) * cosf(azRad) * m_orbitDistance
        };
        m_position = m_orbitTarget + offset;
        // Look at target
        Vec3 fwd = (m_orbitTarget - m_position).normalized();
        if (fwd.lengthSquared() > 1e-8f) {
            m_rotation = Quat::lookAt(fwd, Vec3::up());
        }
        syncRotationToAngles();
    }

    // ── State ────────────────────────────────────────────────────────────────

    Vec3   m_position { 0.0f, 0.0f, -5.0f };
    Quat   m_rotation { Quat::identity() };
    f32    m_fovY     { 60.0f };
    f32    m_aspect   { 16.0f / 9.0f };
    f32    m_near     { 0.1f };
    f32    m_far      { 1000.0f };
    Rect2D m_viewport {};

    // FPS
    f32 m_pitch { 0.0f };
    f32 m_yaw   { 0.0f };

    // Follow
    ECS::Entity m_followTarget    { ECS::Entity::INVALID };
    Vec3         m_followOffset    { 0.0f, 2.0f, -5.0f };
    f32          m_followSmoothing { 0.05f };

    // Orbital
    Vec3 m_orbitTarget   { 0.0f, 0.0f, 0.0f };
    f32  m_orbitDistance { 5.0f };
    f32  m_azimuth       { 0.0f };
    f32  m_elevation     { 30.0f };

    mutable Mat4 m_cachedVP;
    mutable bool m_dirty { true };
};

} // namespace Caffeine::Render

Step 1: Write the header file

bash
cat > src/render/Camera3D.hpp << 'CAMERA3D_EOF'
... (content above) ...
CAMERA3D_EOF

Step 2: Verify it compiles

Run: cmake --build build Expected: Compilation succeeds


Task 2: Add Mat4::inverted() helper#

Files:

  • Modify: src/caffeine/math/Mat4.hpp

Context: screenToWorld needs inverse VP matrix. Mat4 currently has transposed() but no inverted() . Need to add one using cofactor expansion.

Step 1: Add inverted() method to Mat4

Add after transposed() (around line 86):

cpp
/// 4×4 matrix inverse using cofactor expansion (Cramér's rule).
/// Returns identity if the matrix is singular (det = 0).
Mat4 inverted() const {
    f32 a[4][4];
    for (u32 col = 0; col < 4; ++col)
        for (u32 row = 0; row < 4; ++row)
            a[row][col] = (*this)(row, col);

    f32 inv[4][4];

    inv[0][0] = a[1][1] * (a[2][2] * a[3][3] - a[2][3] * a[3][2])
              - a[1][2] * (a[2][1] * a[3][3] - a[2][3] * a[3][1])
              + a[1][3] * (a[2][1] * a[3][2] - a[2][2] * a[3][1]);
    inv[0][1] = -a[0][1] * (a[2][2] * a[3][3] - a[2][3] * a[3][2])
               + a[0][2] * (a[2][1] * a[3][3] - a[2][3] * a[3][1])
               - a[0][3] * (a[2][1] * a[3][2] - a[2][2] * a[3][1]);
    inv[0][2] = a[0][1] * (a[1][2] * a[3][3] - a[1][3] * a[3][2])
              - a[0][2] * (a[1][1] * a[3][3] - a[1][3] * a[3][1])
              + a[0][3] * (a[1][1] * a[3][2] - a[1][2] * a[3][1]);
    inv[0][3] = -a[0][1] * (a[1][2] * a[2][3] - a[1][3] * a[2][2])
               + a[0][2] * (a[1][1] * a[2][3] - a[1][3] * a[2][1])
               - a[0][3] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]);

    inv[1][0] = -a[1][0] * (a[2][2] * a[3][3] - a[2][3] * a[3][2])
               + a[1][2] * (a[2][0] * a[3][3] - a[2][3] * a[3][0])
               - a[1][3] * (a[2][0] * a[3][2] - a[2][2] * a[3][0]);
    inv[1][1] = a[0][0] * (a[2][2] * a[3][3] - a[2][3] * a[3][2])
              - a[0][2] * (a[2][0] * a[3][3] - a[2][3] * a[3][0])
              + a[0][3] * (a[2][0] * a[3][2] - a[2][2] * a[3][0]);
    inv[1][2] = -a[0][0] * (a[1][2] * a[3][3] - a[1][3] * a[3][2])
               + a[0][2] * (a[1][0] * a[3][3] - a[1][3] * a[3][0])
               - a[0][3] * (a[1][0] * a[3][2] - a[1][2] * a[3][0]);
    inv[1][3] = a[0][0] * (a[1][2] * a[2][3] - a[1][3] * a[2][2])
              - a[0][2] * (a[1][0] * a[2][3] - a[1][3] * a[2][0])
              + a[0][3] * (a[1][0] * a[2][2] - a[1][2] * a[2][0]);

    inv[2][0] = a[1][0] * (a[2][1] * a[3][3] - a[2][3] * a[3][1])
              - a[1][1] * (a[2][0] * a[3][3] - a[2][3] * a[3][0])
              + a[1][3] * (a[2][0] * a[3][1] - a[2][1] * a[3][0]);
    inv[2][1] = -a[0][0] * (a[2][1] * a[3][3] - a[2][3] * a[3][1])
               + a[0][1] * (a[2][0] * a[3][3] - a[2][3] * a[3][0])
               - a[0][3] * (a[2][0] * a[3][1] - a[2][1] * a[3][0]);
    inv[2][2] = a[0][0] * (a[1][1] * a[3][3] - a[1][3] * a[3][1])
              - a[0][1] * (a[1][0] * a[3][3] - a[1][3] * a[3][0])
              + a[0][3] * (a[1][0] * a[3][1] - a[1][1] * a[3][0]);
    inv[2][3] = -a[0][0] * (a[1][1] * a[2][3] - a[1][3] * a[2][1])
               + a[0][1] * (a[1][0] * a[2][3] - a[1][3] * a[2][0])
               - a[0][3] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]);

    inv[3][0] = -a[1][0] * (a[2][1] * a[3][2] - a[2][2] * a[3][1])
               + a[1][1] * (a[2][0] * a[3][2] - a[2][2] * a[3][0])
               - a[1][2] * (a[2][0] * a[3][1] - a[2][1] * a[3][0]);
    inv[3][1] = a[0][0] * (a[2][1] * a[3][2] - a[2][2] * a[3][1])
              - a[0][1] * (a[2][0] * a[3][2] - a[2][2] * a[3][0])
              + a[0][2] * (a[2][0] * a[3][1] - a[2][1] * a[3][0]);
    inv[3][2] = -a[0][0] * (a[1][1] * a[3][2] - a[1][2] * a[3][1])
               + a[0][1] * (a[1][0] * a[3][2] - a[1][2] * a[3][0])
               - a[0][2] * (a[1][0] * a[3][1] - a[1][1] * a[3][0]);
    inv[3][3] = a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
              - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
              + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]);

    f32 det = a[0][0] * inv[0][0] + a[0][1] * inv[1][0] + a[0][2] * inv[2][0] + a[0][3] * inv[3][0];

    if (Math::absf(det) < 1e-8f) {
        Mat4 id;
        return id; // singular → return identity
    }

    f32 invDet = 1.0f / det;
    Mat4 result;
    for (u32 col = 0; col < 4; ++col)
        for (u32 row = 0; row < 4; ++row)
            result(row, col) = inv[col][row] * invDet;
    return result;
}

Step 2: Build and test

Run: cmake --build build && ./build/tests/CaffeineTest Expected: All existing tests pass

Step 3: Commit

bash
git add src/math/Mat4.hpp
git commit -m "feat(math): add Mat4::inverted() using cofactor expansion"

Task 3: Create Camera3D tests#

Files:

  • Create: tests/test_camera3d.cpp
  • Modify: tests/CMakeLists.txt

Test content — 20+ test cases:

cpp
#include <catch2/catch_test_macros.hpp>
#include <catch2/catch_approx.hpp>
#include "Caffeine.hpp"

using namespace Caffeine::Render;
using namespace Caffeine::Spatial;
using namespace Caffeine;

TEST_CASE("Camera3D default state", "[camera3d]") {
    Camera3D cam;
    REQUIRE(cam.position().x == Catch::Approx(0.0f));
    REQUIRE(cam.position().y == Catch::Approx(0.0f));
    REQUIRE(cam.position().z == Catch::Approx(-5.0f));
    REQUIRE(cam.fov() == Catch::Approx(60.0f));
    REQUIRE(cam.aspect() == Catch::Approx(16.0f/9.0f));
}

TEST_CASE("Camera3D view matrix matches lookAt", "[camera3d]") {
    Camera3D cam;
    cam.lookAt({0, 0, -5}, {0, 0, 0});
    Mat4 view = cam.viewMatrix();
    Mat4 expected = Mat4::lookAt({0, 0, -5}, {0, 0, 0}, {0, 1, 0});
    for (u32 i = 0; i < 16; ++i) {
        REQUIRE(view.data()[i] == Catch::Approx(expected.data()[i]));
    }
}

TEST_CASE("Camera3D lookAt from different angle", "[camera3d]") {
    Camera3D cam;
    cam.lookAt({10, 5, 10}, {0, 0, 0});
    Mat4 view = cam.viewMatrix();
    Mat4 expected = Mat4::lookAt({10, 5, 10}, {0, 0, 0}, {0, 1, 0});
    for (u32 i = 0; i < 16; ++i) {
        REQUIRE(view.data()[i] == Catch::Approx(expected.data()[i]));
    }
}

TEST_CASE("Camera3D projection matrix matches Mat4::perspective", "[camera3d]") {
    Camera3D cam;
    cam.setFOV(60.0f);
    cam.setAspect(16.0f/9.0f);
    cam.setNearFar(0.1f, 1000.0f);
    Mat4 proj = cam.projectionMatrix();
    Mat4 expected = Mat4::perspective(Math::degToRad(60.0f), 16.0f/9.0f, 0.1f, 1000.0f);
    for (u32 i = 0; i < 16; ++i) {
        REQUIRE(proj.data()[i] == Catch::Approx(expected.data()[i]));
    }
}

TEST_CASE("Camera3D VP matrix is cached", "[camera3d]") {
    Camera3D cam;
    Mat4 vp1 = cam.viewProjectionMatrix();
    Mat4 vp2 = cam.viewProjectionMatrix();
    // Same pointer content check (cached, not recomputed)
    for (u32 i = 0; i < 16; ++i) {
        REQUIRE(vp1.data()[i] == vp2.data()[i]);
    }
}

TEST_CASE("Camera3D VP matrix recomputes when dirty", "[camera3d]") {
    Camera3D cam;
    Mat4 vp1 = cam.viewProjectionMatrix();
    cam.setPosition({10, 0, 0});
    Mat4 vp2 = cam.viewProjectionMatrix();
    bool same = true;
    for (u32 i = 0; i < 16; ++i) {
        if (vp1.data()[i] != vp2.data()[i]) { same = false; break; }
    }
    REQUIRE(!same);
}

TEST_CASE("Camera3D forward default", "[camera3d]") {
    Camera3D cam;
    Vec3 fwd = cam.forward();
    REQUIRE(fwd.x == Catch::Approx(0.0f));
    REQUIRE(fwd.y == Catch::Approx(0.0f));
    REQUIRE(fwd.z == Catch::Approx(1.0f));
}

TEST_CASE("Camera3D forward after lookAt", "[camera3d]") {
    Camera3D cam;
    cam.lookAt({0, 0, -5}, {0, 0, 0});
    Vec3 fwd = cam.forward();
    REQUIRE(fwd.x == Catch::Approx(0.0f));
    REQUIRE(fwd.y == Catch::Approx(0.0f));
    REQUIRE(fwd.z == Catch::Approx(1.0f));
}

TEST_CASE("Camera3D Frustum extraction", "[camera3d]") {
    Camera3D cam;
    cam.lookAt({0, 5, -10}, {0, 0, 0});
    Frustum f = cam.frustum();
    // Origin should be inside frustum (it's looking at origin)
    REQUIRE(f.contains({0, 0, 0}));
    // A point behind the camera should be outside
    REQUIRE(!f.contains({0, 0, -20}));
}

TEST_CASE("Camera3D isVisible", "[camera3d]") {
    Camera3D cam;
    cam.lookAt({0, 0, -10}, {0, 0, 0});
    AABB3D visibleBox = {{-1, -1, -1}, {1, 1, 1}};
    REQUIRE(cam.isVisible(visibleBox));
    // Far away box behind camera
    AABB3D hiddenBox = {{-1, -1, -30}, {1, 1, -28}};
    REQUIRE(!cam.isVisible(hiddenBox));
}

TEST_CASE("Camera3D worldToScreen basic", "[camera3d]") {
    Camera3D cam;
    cam.lookAt({0, 0, -5}, {0, 0, 0});
    cam.setViewport({{0, 0}, {1280, 720}});
    // Origin should project to center of screen
    Vec3 screen = cam.worldToScreen({0, 0, 0});
    REQUIRE(screen.x == Catch::Approx(640.0f).margin(1.0f));
    REQUIRE(screen.y == Catch::Approx(360.0f).margin(1.0f));
}

TEST_CASE("Camera3D screenToWorld roundtrip", "[camera3d]") {
    Camera3D cam;
    cam.lookAt({0, 0, -5}, {0, 0, 0});
    cam.setViewport({{0, 0}, {1280, 720}});
    Vec3 world = {1.0f, 2.0f, -3.0f};
    Vec3 screen = cam.worldToScreen(world);
    Vec3 roundtrip = cam.screenToWorld({screen.x, screen.y}, screen.z);
    REQUIRE(roundtrip.x == Catch::Approx(world.x).margin(0.01f));
    REQUIRE(roundtrip.y == Catch::Approx(world.y).margin(0.01f));
    REQUIRE(roundtrip.z == Catch::Approx(world.z).margin(0.01f));
}

TEST_CASE("Camera3D FPS rotation pitch clamping", "[camera3d]") {
    Camera3D cam;
    cam.rotateFPS(200.0f, 0.0f);
    // Pitch should be clamped to [-89, 89]
    Vec3 fwd = cam.forward();
    // After 200 degrees up, looking almost straight down
    REQUIRE(fwd.y < 0.0f); // looking somewhat downward
    // Pitch angle should be clamped (not beyond 89)
    cam.rotateFPS(-200.0f, 0.0f); // try to go past -89
    cam.rotateFPS(-200.0f, 0.0f);
    // should still be clamped
    // forward should have a reasonable y
    REQUIRE(fabs(cam.forward().y) < 1.0f); // not NaN or crazy
}

TEST_CASE("Camera3D FPS move", "[camera3d]") {
    Camera3D cam;
    Vec3 before = cam.position();
    cam.moveFPS({0, 0, 1}); // move forward
    Vec3 after = cam.position();
    // Should have moved along forward direction
    REQUIRE(after.z > before.z); // forward is +Z
}

TEST_CASE("Camera3D setPosition getPosition", "[camera3d]") {
    Camera3D cam;
    cam.setPosition({10, 20, 30});
    Vec3 pos = cam.position();
    REQUIRE(pos.x == Catch::Approx(10.0f));
    REQUIRE(pos.y == Catch::Approx(20.0f));
    REQUIRE(pos.z == Catch::Approx(30.0f));
}

TEST_CASE("Camera3D setFOV", "[camera3d]") {
    Camera3D cam;
    cam.setFOV(90.0f);
    REQUIRE(cam.fov() == Catch::Approx(90.0f));
}

TEST_CASE("Camera3D setAspect", "[camera3d]") {
    Camera3D cam;
    cam.setAspect(4.0f/3.0f);
    REQUIRE(cam.aspect() == Catch::Approx(4.0f/3.0f));
}

TEST_CASE("Camera3D setNearFar", "[camera3d]") {
    Camera3D cam;
    cam.setNearFar(0.5f, 500.0f);
    REQUIRE(cam.nearPlane() == Catch::Approx(0.5f));
    REQUIRE(cam.farPlane() == Catch::Approx(500.0f));
}

TEST_CASE("Camera3D setRotation", "[camera3d]") {
    Camera3D cam;
    Quat rot = Quat::fromAxisAngle({0, 1, 0}, Math::degToRad(90.0f));
    cam.setRotation(rot);
    Vec3 fwd = cam.forward();
    REQUIRE(fwd.x == Catch::Approx(1.0f).margin(0.01f));
    REQUIRE(fwd.z == Catch::Approx(0.0f).margin(0.01f));
}

Step 1: Write the test file

bash
cat > tests/test_camera3d.cpp << 'TEST_EOF'
...
TEST_EOF

Step 2: Register test in CMakeLists.txt

Add to tests/CMakeLists.txt :

cmake
add_executable(CaffeineTest
    ...
    test_camera3d.cpp
    ...
)

Step 3: Build and run tests

Run: cmake --build build && ./build/tests/CaffeineTest Expected: All tests pass (including pre-existing)

Step 4: Commit

bash
git add tests/test_camera3d.cpp tests/CMakeLists.txt
git commit -m "test(camera3d): add 20+ test cases for Camera3D"

Task 4: Integrate Camera3D into engine header#

Files:

  • Modify: src/caffeine/Caffeine.hpp

Step 1: Add include

After #include "render/Camera2D.hpp" (around line 53), add:

cpp
#include "render/Camera3D.hpp"

Step 2: Build and verify

Run: cmake --build build && ./build/tests/CaffeineTest Expected: All tests pass

Step 3: Commit

bash
git add src/Caffeine.hpp
git commit -m "feat(camera3d): integrate Camera3D into main engine header"

Task 5: Update documentation#

Files:

  • Modify: docs/fase5/camera3d.md

Step 1: Update status and acceptance criteria

  • Change Status: 📅 Planejado → Status: ✅ Implementado
  • Mark acceptance criteria checkboxes:
md
 - [x] `lookAt` produz view matrix correta (comparado com glm::lookAt)
 - [x] `perspective` produz projection correta (comparado com glm::perspective)
 - [x] Frustum cooking: objects outside the frustum do not render
 - [x] Follow suave sem jitter (igual ao Camera2D)
 - [x] FPS mode: pitch clamped at [-89°, +89°] (no flip)
  • Update the "API Planejada" section title to "API"
  • Update the projection math section to reference Mat4::perspective() with the actual engine layout
  • Add viewport member to the private state listing

Step 2: Commit

bash
git add docs/fase5/camera3d.md
git commit -m "docs(camera3d): update documentation for Camera3D implementation"