procedural-3d-engine/base/camera.hpp

323 lines
7.9 KiB
C++
Raw Normal View History

/*
2024-11-23 15:37:57 +01:00
* Basic camera class providing a look-at and first-person camera
*
2024-11-23 15:37:57 +01:00
* Copyright (C) 2016-2024 by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
2017-02-11 09:44:46 +01:00
#include <glm/gtc/matrix_transform.hpp>
class Camera
{
private:
float fov;
float znear, zfar;
void updateViewMatrix()
{
glm::mat4 currentMatrix = matrices.view;
if (useOrbitMode && type == CameraType::lookat) {
// Orbit mode: position camera relative to orbit center using spherical coordinates
updateOrbitPosition();
// Use lookAt matrix for orbit mode
matrices.view = glm::lookAt(position, orbitCenter, glm::vec3(0.0f, 1.0f, 0.0f));
viewPos = glm::vec4(position, 0.0f) * glm::vec4(-1.0f, 1.0f, -1.0f, 1.0f);
} else {
// Standard Sascha camera behavior
glm::mat4 rotM = glm::mat4(1.0f);
glm::mat4 transM;
rotM = glm::rotate(rotM, glm::radians(rotation.x * (flipY ? -1.0f : 1.0f)), glm::vec3(1.0f, 0.0f, 0.0f));
rotM = glm::rotate(rotM, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
rotM = glm::rotate(rotM, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f));
glm::vec3 translation = position;
if (flipY) {
translation.y *= -1.0f;
}
transM = glm::translate(glm::mat4(1.0f), translation);
if (type == CameraType::firstperson)
{
matrices.view = rotM * transM;
}
else
{
matrices.view = transM * rotM;
}
viewPos = glm::vec4(position, 0.0f) * glm::vec4(-1.0f, 1.0f, -1.0f, 1.0f);
}
if (matrices.view != currentMatrix) {
updated = true;
}
};
public:
2016-06-20 20:17:46 +02:00
enum CameraType { lookat, firstperson };
CameraType type = CameraType::lookat;
glm::vec3 rotation = glm::vec3();
glm::vec3 position = glm::vec3();
glm::vec4 viewPos = glm::vec4();
// Orbit camera support
glm::vec3 orbitCenter = glm::vec3(0.0f);
float orbitDistance = 8.0f;
bool useOrbitMode = false;
float rotationSpeed = 1.0f;
float movementSpeed = 1.0f;
bool updated = true;
bool flipY = false;
struct
{
glm::mat4 perspective;
glm::mat4 view;
} matrices;
struct
{
bool left = false;
bool right = false;
bool up = false;
bool down = false;
} keys;
2024-11-23 15:37:57 +01:00
bool moving() const
{
return keys.left || keys.right || keys.up || keys.down;
}
2024-11-23 15:37:57 +01:00
float getNearClip() const {
2017-12-09 21:12:16 +01:00
return znear;
}
2024-11-23 15:37:57 +01:00
float getFarClip() const {
2017-12-09 21:12:16 +01:00
return zfar;
}
void setPerspective(float fov, float aspect, float znear, float zfar)
{
glm::mat4 currentMatrix = matrices.perspective;
this->fov = fov;
this->znear = znear;
this->zfar = zfar;
matrices.perspective = glm::perspective(glm::radians(fov), aspect, znear, zfar);
if (flipY) {
Merge glTF branch (#747) * Added helper function for easy pipeline vertex input state create info structure setup from glTF model vertex class * Split glTF loader into header and implementation * Updated sample to use glTF * Removed collada files Replaced assets are now part of the asset pack * Return value for glTF model vertex input state create info helper * Removed unused assets * Use glTF assets * Added default material for glTF node's without materials * Use glTF assets * Apply pre-transforms to normals * Use glTF assets * Use glTF assets * Use vertex input state from glTF model class * Scene setup * Use glTF assets * Use glTF assets * Display error message and exit if glTF file could not be loaded * Use glTF assets * Use glTF assets * Use glTF assets * Remove unused buffer binds * Use glTF assets * Remove no longer used model files * Remove no longer used model files * Added support for rendering glTF models with images * glTF model normal pre-transform ignores translation * Use glTF assets * Use glTF assets * Use glTF assets * Use glTF assets * Use glTF assets * Only add combined image samplers to pool if actually used in the scene * Use global descriptor set layouts * Use global descriptor set layouts * Use glTF assets * Use glTF assets * Use glTF assets Code cleanup Updated GLSL and HLSL shaders * Use glTF assets Code cleanup * Use glTF assets Code cleanup Updated GLSL and HLSL shaders * Remove no-longer used model * Use glTF assets Code cleanup Updated GLSL and HLSL shaders * Use glTF assets Code cleanup Updated GLSL and HLSL shaders Removed no-longer used model * Use glTF assets Code cleanup Use RGBA texture instead of different compressed formats Removed no-longer used assets * Adnrdoid build file * Use glTF assets Code cleanup and refactoring Updated GLSL and HLSL shaders * Added vertex count and way of passing additional memory property type flags to glTF loader * Use glTF assets Updated GLSL and HLSL shaders Removed no-longer used assets * Use glTF assets Updated GLSL and HLSL shaders * Remove unfinished sample * Completely reworked push constants sample Use glTF assets Updated GLSL and HLSL shaders Removed no-longer used assets * Android CMake build files * Removed un-used asset * Explicit buffer binding function * Use glTF assets Code cleanup Updated GLSL and HLSL shaders * Use glTF assets Code cleanup * Use glTF assets Code cleanup Removed no-longer used assets * Use glTF assets Code cleanup Updated GLSL and HLSL shaders Removed no-longer used assets * Remove no-longer used asset * Use glTF assets Code cleanup and refactoring Performance optimizations Updated GLSL and HLSL shaders Removed no-longer used assets * Use glTF assets Code cleanup and refactoring Updated GLSL and HLSL shaders Removed no-longer used assets * Use glTF assets Code cleanup and refactoring Updated GLSL and HLSL shaders Removed no-longer used assets * Use glTF assets Code cleanup and refactoring Removed no-longer used assets * Use glTF assets Code cleanup and refactoring Removed no-longer used assets * Use glTF assets Code cleanup and refactoring * Use glTF assets Code cleanup and refactoring * Use glTF assets Code cleanup and refactoring Removed no-longer used assets * Pass vertex size and calculate multiplier in shaders instead of hard-coding With this, changes to the glTF vertex structure won't break the ray tracing samples * Load tangents (if present) * Use glTF assets Code cleanup and heavy refactoring Reworked debug display code * Android build * Normal mapping fixes Udpated HLSL shaders * Use glTF assets Code cleanup and heavy refactoring Reworked debug display code Updated GLSL and HLSL shaders * Code cleanup, comments * Use glTF assets Code cleanup and heavy refactoring Reworked debug display code Updated GLSL and HLSL shaders * Added sample count to framebuffer create info * Removed no-longer used assets * Android build Removed no-longer used assets * Code cleanup and heavy refactoring Updated GLSL and HLSL shaders Use tangents stored in GLSL instead of calculating them in the fragment shader * Renamed textured PBR sample main cpp file * Use glTF assets Code cleanup and refactoring Updated GLSL and HLSL shaders Removed no-longer used assets * Use glTF assets Removed no-longer used assets * Android build files * Android build files * Use glTF assets Removed no-longer used assets * Fixed HLSL shaders * Android build files * Use glTF assets Updated GLSL and HLSL shaders Removed no-longer used assets * Use glTF assets Updated GLSL and HLSL shaders Removed no-longer used assets * Added flag to disable glTF image loading Useful for samples that use their own textures or don't use textures at all to speed up loading * Use glTF assets Code cleanup Use Sponza scene instead of Sibenik to better highlight the effect Updated GLSL and HLSL shaders * Updated Android build files * Removed left-over comment * Use Sponza scene for the SSAO sample * Removed unused code * Removed ASSIMP No longer required as all samples now use the glTF file format * Added missing vertex shader stage * Removed old ASSIMP-based model loader * Added support for loading external glTF images from ktx Android fixes for loading external buffer files * Scene setup * Added missing shader stages * Removed ASSIMP from build files * Fixed compiler warning * Removed ASSIMP from readmes * Android build files cleanup * Replaced ktx submodule with only the files required for this repo The ktx submodule was a tad too big and contained lots of files not required for this repo * Moved ktx build files into base project * Use glTF assets * Use glTF assets * Removed license files, will be moved to asset pack * Use RGBA textures * Use RGBA cubemp texture with face assignment based on original images Refs #679 * Android build files * Removed textures All textures will be moved to the asset pack * Ignore asset folders * Removed font Fonts will be moved to the asset pack * Link to gltf asset pack * Updated gitignore * Android build file
2020-07-28 20:20:38 +02:00
matrices.perspective[1][1] *= -1.0f;
}
if (matrices.view != currentMatrix) {
updated = true;
}
};
void updateAspectRatio(float aspect)
{
glm::mat4 currentMatrix = matrices.perspective;
matrices.perspective = glm::perspective(glm::radians(fov), aspect, znear, zfar);
if (flipY) {
Merge glTF branch (#747) * Added helper function for easy pipeline vertex input state create info structure setup from glTF model vertex class * Split glTF loader into header and implementation * Updated sample to use glTF * Removed collada files Replaced assets are now part of the asset pack * Return value for glTF model vertex input state create info helper * Removed unused assets * Use glTF assets * Added default material for glTF node's without materials * Use glTF assets * Apply pre-transforms to normals * Use glTF assets * Use glTF assets * Use vertex input state from glTF model class * Scene setup * Use glTF assets * Use glTF assets * Display error message and exit if glTF file could not be loaded * Use glTF assets * Use glTF assets * Use glTF assets * Remove unused buffer binds * Use glTF assets * Remove no longer used model files * Remove no longer used model files * Added support for rendering glTF models with images * glTF model normal pre-transform ignores translation * Use glTF assets * Use glTF assets * Use glTF assets * Use glTF assets * Use glTF assets * Only add combined image samplers to pool if actually used in the scene * Use global descriptor set layouts * Use global descriptor set layouts * Use glTF assets * Use glTF assets * Use glTF assets Code cleanup Updated GLSL and HLSL shaders * Use glTF assets Code cleanup * Use glTF assets Code cleanup Updated GLSL and HLSL shaders * Remove no-longer used model * Use glTF assets Code cleanup Updated GLSL and HLSL shaders * Use glTF assets Code cleanup Updated GLSL and HLSL shaders Removed no-longer used model * Use glTF assets Code cleanup Use RGBA texture instead of different compressed formats Removed no-longer used assets * Adnrdoid build file * Use glTF assets Code cleanup and refactoring Updated GLSL and HLSL shaders * Added vertex count and way of passing additional memory property type flags to glTF loader * Use glTF assets Updated GLSL and HLSL shaders Removed no-longer used assets * Use glTF assets Updated GLSL and HLSL shaders * Remove unfinished sample * Completely reworked push constants sample Use glTF assets Updated GLSL and HLSL shaders Removed no-longer used assets * Android CMake build files * Removed un-used asset * Explicit buffer binding function * Use glTF assets Code cleanup Updated GLSL and HLSL shaders * Use glTF assets Code cleanup * Use glTF assets Code cleanup Removed no-longer used assets * Use glTF assets Code cleanup Updated GLSL and HLSL shaders Removed no-longer used assets * Remove no-longer used asset * Use glTF assets Code cleanup and refactoring Performance optimizations Updated GLSL and HLSL shaders Removed no-longer used assets * Use glTF assets Code cleanup and refactoring Updated GLSL and HLSL shaders Removed no-longer used assets * Use glTF assets Code cleanup and refactoring Updated GLSL and HLSL shaders Removed no-longer used assets * Use glTF assets Code cleanup and refactoring Removed no-longer used assets * Use glTF assets Code cleanup and refactoring Removed no-longer used assets * Use glTF assets Code cleanup and refactoring * Use glTF assets Code cleanup and refactoring * Use glTF assets Code cleanup and refactoring Removed no-longer used assets * Pass vertex size and calculate multiplier in shaders instead of hard-coding With this, changes to the glTF vertex structure won't break the ray tracing samples * Load tangents (if present) * Use glTF assets Code cleanup and heavy refactoring Reworked debug display code * Android build * Normal mapping fixes Udpated HLSL shaders * Use glTF assets Code cleanup and heavy refactoring Reworked debug display code Updated GLSL and HLSL shaders * Code cleanup, comments * Use glTF assets Code cleanup and heavy refactoring Reworked debug display code Updated GLSL and HLSL shaders * Added sample count to framebuffer create info * Removed no-longer used assets * Android build Removed no-longer used assets * Code cleanup and heavy refactoring Updated GLSL and HLSL shaders Use tangents stored in GLSL instead of calculating them in the fragment shader * Renamed textured PBR sample main cpp file * Use glTF assets Code cleanup and refactoring Updated GLSL and HLSL shaders Removed no-longer used assets * Use glTF assets Removed no-longer used assets * Android build files * Android build files * Use glTF assets Removed no-longer used assets * Fixed HLSL shaders * Android build files * Use glTF assets Updated GLSL and HLSL shaders Removed no-longer used assets * Use glTF assets Updated GLSL and HLSL shaders Removed no-longer used assets * Added flag to disable glTF image loading Useful for samples that use their own textures or don't use textures at all to speed up loading * Use glTF assets Code cleanup Use Sponza scene instead of Sibenik to better highlight the effect Updated GLSL and HLSL shaders * Updated Android build files * Removed left-over comment * Use Sponza scene for the SSAO sample * Removed unused code * Removed ASSIMP No longer required as all samples now use the glTF file format * Added missing vertex shader stage * Removed old ASSIMP-based model loader * Added support for loading external glTF images from ktx Android fixes for loading external buffer files * Scene setup * Added missing shader stages * Removed ASSIMP from build files * Fixed compiler warning * Removed ASSIMP from readmes * Android build files cleanup * Replaced ktx submodule with only the files required for this repo The ktx submodule was a tad too big and contained lots of files not required for this repo * Moved ktx build files into base project * Use glTF assets * Use glTF assets * Removed license files, will be moved to asset pack * Use RGBA textures * Use RGBA cubemp texture with face assignment based on original images Refs #679 * Android build files * Removed textures All textures will be moved to the asset pack * Ignore asset folders * Removed font Fonts will be moved to the asset pack * Link to gltf asset pack * Updated gitignore * Android build file
2020-07-28 20:20:38 +02:00
matrices.perspective[1][1] *= -1.0f;
}
if (matrices.view != currentMatrix) {
updated = true;
}
}
2016-12-20 22:25:17 +01:00
void setPosition(glm::vec3 position)
{
this->position = position;
updateViewMatrix();
}
void setRotation(glm::vec3 rotation)
{
this->rotation = rotation;
updateViewMatrix();
}
void rotate(glm::vec3 delta)
{
this->rotation += delta;
updateViewMatrix();
}
void setTranslation(glm::vec3 translation)
{
this->position = translation;
updateViewMatrix();
};
void translate(glm::vec3 delta)
{
this->position += delta;
updateViewMatrix();
}
void setRotationSpeed(float rotationSpeed)
{
this->rotationSpeed = rotationSpeed;
}
void setMovementSpeed(float movementSpeed)
{
this->movementSpeed = movementSpeed;
}
// Update camera position based on orbit center and current rotation
void updateOrbitPosition()
{
if (!useOrbitMode) return;
// Convert Euler angles to spherical coordinates around orbit center
float pitch = glm::radians(rotation.x);
float yaw = glm::radians(rotation.y);
// Calculate position relative to orbit center using spherical coordinates
float x = orbitDistance * cos(pitch) * cos(yaw);
float y = orbitDistance * sin(pitch);
float z = orbitDistance * cos(pitch) * sin(yaw);
position = orbitCenter + glm::vec3(x, y, z);
}
// Enable orbit mode and set orbit center
void setOrbitMode(glm::vec3 center, float distance)
{
orbitCenter = center;
orbitDistance = distance;
useOrbitMode = true;
updateViewMatrix();
}
// Disable orbit mode and return to standard camera
void disableOrbitMode()
{
useOrbitMode = false;
updateViewMatrix();
}
// Focus camera on an object using orbit mode
void focusOnObject(glm::vec3 objectCenter, float objectRadius)
{
// Calculate optimal viewing distance based on object radius and FOV
float halfFovRadians = glm::radians(fov * 0.5f);
float distance = objectRadius / glm::tan(halfFovRadians) * 2.5f;
distance = glm::max(distance, objectRadius * 3.0f);
// Set orbit center to the object center
orbitCenter = objectCenter;
orbitDistance = distance;
useOrbitMode = true;
// Set camera to a good viewing angle (slightly elevated and angled)
rotation.x = 15.0f; // Slight elevation
rotation.y = 30.0f; // Angled view
rotation.z = 0.0f;
// Update position and view matrix
updateViewMatrix();
}
void update(float deltaTime)
{
updated = false;
2016-06-20 20:17:46 +02:00
if (type == CameraType::firstperson)
{
if (moving())
{
glm::vec3 camFront;
camFront.x = -cos(glm::radians(rotation.x)) * sin(glm::radians(rotation.y));
camFront.y = sin(glm::radians(rotation.x));
camFront.z = cos(glm::radians(rotation.x)) * cos(glm::radians(rotation.y));
camFront = glm::normalize(camFront);
float moveSpeed = deltaTime * movementSpeed;
if (keys.up)
position += camFront * moveSpeed;
if (keys.down)
position -= camFront * moveSpeed;
if (keys.left)
position -= glm::normalize(glm::cross(camFront, glm::vec3(0.0f, 1.0f, 0.0f))) * moveSpeed;
if (keys.right)
position += glm::normalize(glm::cross(camFront, glm::vec3(0.0f, 1.0f, 0.0f))) * moveSpeed;
}
}
updateViewMatrix();
};
// Update camera passing separate axis data (gamepad)
// Returns true if view or position has been changed
bool updatePad(glm::vec2 axisLeft, glm::vec2 axisRight, float deltaTime)
{
bool retVal = false;
if (type == CameraType::firstperson)
{
// Use the common console thumbstick layout
// Left = view, right = move
const float deadZone = 0.0015f;
const float range = 1.0f - deadZone;
glm::vec3 camFront;
camFront.x = -cos(glm::radians(rotation.x)) * sin(glm::radians(rotation.y));
camFront.y = sin(glm::radians(rotation.x));
camFront.z = cos(glm::radians(rotation.x)) * cos(glm::radians(rotation.y));
camFront = glm::normalize(camFront);
float moveSpeed = deltaTime * movementSpeed * 2.0f;
2016-07-03 21:06:17 +02:00
float rotSpeed = deltaTime * rotationSpeed * 50.0f;
// Move
if (fabsf(axisLeft.y) > deadZone)
{
float pos = (fabsf(axisLeft.y) - deadZone) / range;
position -= camFront * pos * ((axisLeft.y < 0.0f) ? -1.0f : 1.0f) * moveSpeed;
retVal = true;
}
if (fabsf(axisLeft.x) > deadZone)
{
float pos = (fabsf(axisLeft.x) - deadZone) / range;
position += glm::normalize(glm::cross(camFront, glm::vec3(0.0f, 1.0f, 0.0f))) * pos * ((axisLeft.x < 0.0f) ? -1.0f : 1.0f) * moveSpeed;
retVal = true;
}
// Rotate
if (fabsf(axisRight.x) > deadZone)
{
float pos = (fabsf(axisRight.x) - deadZone) / range;
rotation.y += pos * ((axisRight.x < 0.0f) ? -1.0f : 1.0f) * rotSpeed;
retVal = true;
}
if (fabsf(axisRight.y) > deadZone)
{
float pos = (fabsf(axisRight.y) - deadZone) / range;
rotation.x -= pos * ((axisRight.y < 0.0f) ? -1.0f : 1.0f) * rotSpeed;
retVal = true;
}
}
else
{
// todo: move code from example base class for look-at
}
if (retVal)
{
updateViewMatrix();
}
return retVal;
}
};