Chira Engine
A customizable MIT-licensed game engine.
CameraComponent.h
1 #pragma once
2 
3 #include <entt/entt.hpp>
4 #include <core/Assertions.h>
5 #include <math/Types.h>
6 #include <utility/Types.h>
7 #include "LayerComponents.h"
8 #include "TransformComponent.h"
9 
10 namespace chira {
11 
13  enum class ProjectionMode {
14  PERSPECTIVE,
15  ORTHOGRAPHIC,
16  };
17 
18  explicit CameraComponent(ProjectionMode mode = ProjectionMode::PERSPECTIVE, float fov_ = 70.f,
19  float nearDistance_ = 0.1f, float farDistance_ = 1024.f, float orthoSize_ = 10.f,
20  bool active_ = true)
21  : projectionMode(mode)
22  , activeLayers(0)
23  , fov(fov_)
24  , nearDistance(nearDistance_)
25  , farDistance(farDistance_)
26  , orthoSize(orthoSize_)
27  , active(active_) {
28  foreach(LAYER_COMPONENTS, [&](auto layer) {
29  this->activeLayers += decltype(layer)::index;
30  });
31  }
32 
33  [[nodiscard]] glm::mat4 getProjection(glm::vec2i size) const {
34  size.x = std::max(size.x, 1);
35  size.y = std::max(size.y, 1);
36  float aspectRatio = static_cast<float>(size.x) / static_cast<float>(size.y);
37 
38  switch (this->projectionMode) {
39  using enum ProjectionMode;
40  case PERSPECTIVE: {
41  return glm::perspective(glm::radians(this->fov), aspectRatio, this->nearDistance, this->farDistance);
42  }
43  case ORTHOGRAPHIC: {
44  float orthoRight = this->orthoSize * aspectRatio / 2;
45  float orthoLeft = -orthoRight;
46  float orthoTop = this->orthoSize / 2;
47  float orthoBottom = -orthoTop;
48  return glm::ortho(orthoLeft, orthoRight, orthoBottom, orthoTop, this->nearDistance, this->farDistance);
49  }
50  CHIRA_NO_DEFAULT;
51  }
52  }
53 
54  [[nodiscard]] glm::mat4 getView() const {
55  const glm::vec3 position = this->transform->getPosition();
56  return glm::lookAt(position, position + this->transform->getFrontVector(), this->transform->getUpVector());
57  }
58 
59  void setCurrent() {
60  this->active = true;
61  }
62 
63  void clearCurrent() {
64  this->active = false;
65  }
66 
67 public:
68  TransformComponent* transform = nullptr;
69  ProjectionMode projectionMode;
70 
71  // The combined values of every layer index
72  std::size_t activeLayers;
73 
74  float fov;
75  float nearDistance;
76  float farDistance;
77 
78  float orthoSize;
79 
80  bool active;
81 };
82 
83 } // namespace chira