Initial commit - Migration from cmake to gradle
This commit is contained in:
commit
279f292225
217 files changed
+14945
No files matched your search
@@ -0,0 +1,32 @@
|
||||
plugins {
|
||||
id 'cpp-library'
|
||||
id 'cpp-unit-test'
|
||||
}
|
||||
apply from: rootProject.file('gradle/common.gradle')
|
||||
|
||||
library {
|
||||
baseName = 'CosmicEngine'
|
||||
linkage = [Linkage.SHARED]
|
||||
targetMachines.add(machines.windows.x86_64)
|
||||
targetMachines.add(machines.linux.x86_64)
|
||||
source.from('src/main')
|
||||
publicHeaders.from('src/main') // visibles par App et Scripts
|
||||
}
|
||||
|
||||
// Seul le moteur lie les libs vcpkg (SDL, Jolt, assimp...).
|
||||
tasks.withType(AbstractLinkTask).configureEach {
|
||||
dependsOn ':vcpkg'
|
||||
linkerArgs.addAll("-L${rootProject.ext.vcpkgLibDir}", "@${rootProject.ext.vcpkgRsp}")
|
||||
if (!org.gradle.internal.os.OperatingSystem.current().isWindows()) {
|
||||
linkerArgs.add('-lopenal')
|
||||
}
|
||||
}
|
||||
|
||||
// Pour les tests
|
||||
tasks.withType(RunTestExecutable).configureEach {
|
||||
args("--gtest_color=yes")
|
||||
args("--gtest_output=xml:report.xml")
|
||||
// Les DLL/SO vcpkg doivent être trouvables à l'exécution des tests.
|
||||
def pathVar = org.gradle.internal.os.OperatingSystem.current().isWindows() ? 'PATH' : 'LD_LIBRARY_PATH'
|
||||
environment pathVar, rootProject.ext.runtimeDir.absolutePath + File.pathSeparator + (System.getenv(pathVar) ?: '')
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#include "CAbstractComponent.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
constexpr std::string typeToString(EComponentType type)
|
||||
{
|
||||
switch (type) {
|
||||
case EComponentType::COMPONENT_SCRIPT:
|
||||
return "Script";
|
||||
case EComponentType::COMPONENT_CAMERA:
|
||||
return "Camera";
|
||||
case EComponentType::COMPONENT_LIGHT:
|
||||
return "Light";
|
||||
case EComponentType::COMPONENT_RIGIDBODY:
|
||||
return "Rigidbody";
|
||||
case EComponentType::COMPONENT_COLLIDER:
|
||||
return "Collider";
|
||||
case EComponentType::COMPONENT_CUSTOM:
|
||||
return "Custom";
|
||||
case EComponentType::COMPONENT_META:
|
||||
return "Meta";
|
||||
default:
|
||||
return "UNKNOWN_COMPONENT";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
#ifndef CABSTRACT_COMPONENT_HPP
|
||||
#define CABSTRACT_COMPONENT_HPP
|
||||
|
||||
#include "../../Utils/JsonParser/CSerializable.hpp"
|
||||
#include "../Entity/CEntity.hpp"
|
||||
namespace CosmicCore {
|
||||
|
||||
/**
|
||||
* @brief Enum representing every type of component that can be created.
|
||||
*/
|
||||
enum class EComponentType : unsigned char {
|
||||
COMPONENT_SCRIPT,
|
||||
COMPONENT_CAMERA,
|
||||
COMPONENT_LIGHT,
|
||||
COMPONENT_RIGIDBODY,
|
||||
COMPONENT_COLLIDER,
|
||||
COMPONENT_CUSTOM,
|
||||
COMPONENT_RENDERER,
|
||||
COMPONENT_META,
|
||||
COMPONENT_COUNT
|
||||
};
|
||||
|
||||
constexpr std::string typeToString(EComponentType type);
|
||||
|
||||
class CAbstractComponent : public CSerializable{
|
||||
public:
|
||||
CAbstractComponent(CEntity& entity): m_owningEntity(entity){};
|
||||
CAbstractComponent(CAbstractComponent&& other) = default;
|
||||
CAbstractComponent& operator=(CAbstractComponent&&) = default;
|
||||
|
||||
virtual ~CAbstractComponent() = default;
|
||||
|
||||
CEntity& getEntity() {
|
||||
return m_owningEntity;
|
||||
}
|
||||
|
||||
const CEntity& getEntity() const {
|
||||
return m_owningEntity;
|
||||
}
|
||||
|
||||
virtual nlohmann::json to_json() = 0;
|
||||
private:
|
||||
/**
|
||||
* @brief The entity to which the component is linked.
|
||||
*/
|
||||
CEntity m_owningEntity;
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,158 @@
|
||||
#ifndef CCAMERA_HPP
|
||||
#define CCAMERA_HPP
|
||||
|
||||
#include "../CAbstractComponent.hpp"
|
||||
//pour vulkan depth 0-1 (opengl [-1,1])
|
||||
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
|
||||
#include <glm/glm.hpp>
|
||||
#include <glm/gtc/matrix_transform.hpp>
|
||||
#include "../../Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp"
|
||||
#include "../Geometry/CTransform.hpp"
|
||||
namespace CosmicCore {
|
||||
|
||||
class CCamera : public CAbstractComponent {
|
||||
private:
|
||||
// paramètres de la caméra
|
||||
float m_fov = 45.0f;
|
||||
float m_near = 0.1f;
|
||||
float m_far = 1000.0f;
|
||||
float m_aspect = 16.0f / 9.0f;
|
||||
|
||||
// matrices calculées
|
||||
glm::mat4 m_view = glm::mat4(1.0f);
|
||||
glm::mat4 m_projection = glm::mat4(1.0f);
|
||||
|
||||
// GPU
|
||||
struct CameraUBOData {
|
||||
glm::mat4 view;
|
||||
glm::mat4 projection;
|
||||
glm::vec4 position;
|
||||
};
|
||||
|
||||
std::array<VMABuffer, MAX_FRAMES_IN_FLIGHT> m_uniformBuffers;
|
||||
std::array<void*, MAX_FRAMES_IN_FLIGHT> m_mappedData{};
|
||||
std::array<ManagedDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_descriptorSets;
|
||||
|
||||
void recalcProjection() {
|
||||
m_projection = glm::perspective(glm::radians(m_fov), m_aspect, m_near, m_far);
|
||||
// Vulkan a l'axe Y inversé par rapport à OpenGL
|
||||
m_projection[1][1] *= -1;
|
||||
}
|
||||
|
||||
public:
|
||||
CCamera(CEntity& entity) : CAbstractComponent(entity) {
|
||||
recalcProjection();
|
||||
}
|
||||
|
||||
~CCamera(){
|
||||
destroy();
|
||||
}
|
||||
|
||||
void setFov(float fov) {
|
||||
m_fov = fov;
|
||||
recalcProjection();
|
||||
}
|
||||
|
||||
void setAspect(float aspect) {
|
||||
m_aspect = aspect;
|
||||
recalcProjection();
|
||||
}
|
||||
|
||||
void setNearFar(float near, float far) {
|
||||
m_near = near;
|
||||
m_far = far;
|
||||
recalcProjection();
|
||||
}
|
||||
|
||||
// getters
|
||||
glm::mat4 getView(const CTransform& transform) const {
|
||||
/*glm::quat q = transform.getOrientation();
|
||||
glm::vec3 position = transform.getCenter();
|
||||
|
||||
// rotation inverse (conjugué du quaternion) + translation inverse
|
||||
glm::mat4 rotInverse = glm::toMat4(glm::conjugate(q));
|
||||
glm::mat4 transInverse = glm::translate(glm::mat4(1.0f), -position);*/
|
||||
|
||||
//return rotInverse * transInverse;
|
||||
return glm::inverse(transform.getInheritedTransformation());
|
||||
}
|
||||
glm::mat4 getProjection() const { return m_projection; }
|
||||
|
||||
// GPU
|
||||
void initUniformBuffer(VmaAllocator allocator) {
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
|
||||
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
||||
VkBufferCreateInfo bufferInfo{};
|
||||
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
bufferInfo.size = sizeof(CameraUBOData);
|
||||
bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
|
||||
|
||||
VmaAllocationCreateInfo allocInfo{};
|
||||
allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
|
||||
allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
|
||||
|
||||
VmaAllocationInfo info{};
|
||||
vmaCreateBuffer(allocator, &bufferInfo, &allocInfo,
|
||||
&m_uniformBuffers[i].buffer,
|
||||
&m_uniformBuffers[i].allocation,
|
||||
&info);
|
||||
m_mappedData[i] = info.pMappedData;
|
||||
|
||||
m_descriptorSets[i] = api->getDescriptorPoolManager().allocate(
|
||||
*api->getCameraLayout()
|
||||
);
|
||||
|
||||
vk::DescriptorBufferInfo descriptorBufferInfo{
|
||||
vk::Buffer(m_uniformBuffers[i].buffer),
|
||||
0,
|
||||
sizeof(CameraUBOData)
|
||||
};
|
||||
vk::WriteDescriptorSet descriptorWrite{
|
||||
*m_descriptorSets[i].set,
|
||||
0, 0, 1,
|
||||
vk::DescriptorType::eUniformBuffer,
|
||||
{}, &descriptorBufferInfo
|
||||
};
|
||||
static_cast<vk::raii::Device*>(api->getDevice())->updateDescriptorSets(descriptorWrite, {});
|
||||
}
|
||||
}
|
||||
|
||||
void destroyUniformBuffer(VmaAllocator allocator) {
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
||||
api->getDescriptorPoolManager().free(m_descriptorSets[i]);
|
||||
vmaDestroyBuffer(allocator, m_uniformBuffers[i].buffer,
|
||||
m_uniformBuffers[i].allocation);
|
||||
}
|
||||
}
|
||||
|
||||
void updateUniformBuffer(uint32_t frameIndex, const CTransform& transform) {
|
||||
glm::mat4 worldTransform = transform.getInheritedTransformation();
|
||||
glm::vec3 worldPosition = glm::vec3(worldTransform[3]);
|
||||
CameraUBOData data{ getView(transform), m_projection, glm::vec4(worldPosition, 1.0f)};
|
||||
memcpy(m_mappedData[frameIndex], &data, sizeof(data));
|
||||
}
|
||||
|
||||
vk::raii::DescriptorSet& getDescriptorSet(uint32_t frameIndex) {
|
||||
return m_descriptorSets[frameIndex].set;
|
||||
}
|
||||
|
||||
void destroy()
|
||||
{
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
|
||||
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
||||
|
||||
api->destroyBuffer(m_uniformBuffers[i], api->getCurrentFrameIndex());
|
||||
api->destroyDescriptorSet(m_descriptorSets[i], api->getCurrentFrameIndex());
|
||||
}
|
||||
}
|
||||
|
||||
nlohmann::json to_json(){
|
||||
return nlohmann::json();
|
||||
};
|
||||
};
|
||||
|
||||
} // namespace CosmicCore
|
||||
#endif
|
||||
@@ -0,0 +1,15 @@
|
||||
#include "CCamera2D.hpp"
|
||||
#include "Engine/Core/Kernel/CKernel.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
void CCamera2D::recalcProjection() {
|
||||
//todo
|
||||
float width = CKernelBase::instance()->getWindowWidth();
|
||||
float height = CKernelBase::instance()->getWindowHeight();
|
||||
//m_projection = glm::ortho(0.0f, width, 0.0f, height, -1.0f, 1.0f);
|
||||
//m_projection //= glm::perspective(glm::radians(m_fov), m_aspect, m_near, m_far);
|
||||
m_projection = glm::ortho(0.0f, width, 0.0f, height, -1.0f, 1.0f);
|
||||
|
||||
//m_projection[1][1] *= -1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
#ifndef CCAMERA2D_HPP
|
||||
#define CCAMERA2D_HPP
|
||||
|
||||
#include "../CAbstractComponent.hpp"
|
||||
//pour vulkan depth 0-1 (opengl [-1,1])
|
||||
#include <glm/glm.hpp>
|
||||
#include <glm/gtc/matrix_transform.hpp>
|
||||
#include "../../Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp"
|
||||
#include "../Geometry/CTransform2D.hpp"
|
||||
namespace CosmicCore {
|
||||
|
||||
//TODO LES MAJ REELLES DUN MOUVEMENT TRANSFORM
|
||||
//AJOUT DONC DE LA VUE ET AUTRE PARAM
|
||||
//Pour le moment ne gère qu'une caméra fixe (UI)
|
||||
class CCamera2D : public CAbstractComponent {
|
||||
private:
|
||||
glm::mat4 m_projection = glm::mat4(1.0f);
|
||||
|
||||
// GPU
|
||||
struct Camera2DUBOData {
|
||||
glm::mat4 projection;
|
||||
};
|
||||
|
||||
std::array<VMABuffer, MAX_FRAMES_IN_FLIGHT> m_uniformBuffers;
|
||||
std::array<void*, MAX_FRAMES_IN_FLIGHT> m_mappedData{};
|
||||
std::array<ManagedDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_descriptorSets;
|
||||
|
||||
void recalcProjection();
|
||||
|
||||
public:
|
||||
CCamera2D(CEntity& entity) : CAbstractComponent(entity) {
|
||||
recalcProjection();
|
||||
}
|
||||
|
||||
~CCamera2D(){
|
||||
destroy();
|
||||
}
|
||||
|
||||
glm::mat4 getProjection() const { return m_projection; }
|
||||
|
||||
// GPU
|
||||
void initUniformBuffer(VmaAllocator allocator) {
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
|
||||
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
||||
VkBufferCreateInfo bufferInfo{};
|
||||
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
bufferInfo.size = sizeof(Camera2DUBOData);
|
||||
bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
|
||||
|
||||
VmaAllocationCreateInfo allocInfo{};
|
||||
allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
|
||||
allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
|
||||
|
||||
VmaAllocationInfo info{};
|
||||
vmaCreateBuffer(allocator, &bufferInfo, &allocInfo,
|
||||
&m_uniformBuffers[i].buffer,
|
||||
&m_uniformBuffers[i].allocation,
|
||||
&info);
|
||||
m_mappedData[i] = info.pMappedData;
|
||||
|
||||
m_descriptorSets[i] = api->getDescriptorPoolManager().allocate(
|
||||
*api->getProjection2DLayout()
|
||||
);
|
||||
|
||||
vk::DescriptorBufferInfo descriptorBufferInfo{
|
||||
vk::Buffer(m_uniformBuffers[i].buffer),
|
||||
0,
|
||||
sizeof(Camera2DUBOData)
|
||||
};
|
||||
vk::WriteDescriptorSet descriptorWrite{
|
||||
*m_descriptorSets[i].set,
|
||||
0, 0, 1,
|
||||
vk::DescriptorType::eUniformBuffer,
|
||||
{}, &descriptorBufferInfo
|
||||
};
|
||||
static_cast<vk::raii::Device*>(api->getDevice())->updateDescriptorSets(descriptorWrite, {});
|
||||
}
|
||||
}
|
||||
|
||||
void destroyUniformBuffer(VmaAllocator allocator) {
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
||||
api->getDescriptorPoolManager().free(m_descriptorSets[i]);
|
||||
vmaDestroyBuffer(allocator, m_uniformBuffers[i].buffer,
|
||||
m_uniformBuffers[i].allocation);
|
||||
}
|
||||
}
|
||||
|
||||
void updateUniformBuffer(uint32_t frameIndex, const CTransform2D& transform) {
|
||||
|
||||
Camera2DUBOData data{ m_projection};
|
||||
memcpy(m_mappedData[frameIndex], &data, sizeof(data));
|
||||
}
|
||||
|
||||
vk::raii::DescriptorSet& getDescriptorSet(uint32_t frameIndex) {
|
||||
return m_descriptorSets[frameIndex].set;
|
||||
}
|
||||
|
||||
void destroy()
|
||||
{
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
|
||||
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
||||
|
||||
api->destroyBuffer(m_uniformBuffers[i], api->getCurrentFrameIndex());
|
||||
api->destroyDescriptorSet(m_descriptorSets[i], api->getCurrentFrameIndex());
|
||||
}
|
||||
}
|
||||
|
||||
nlohmann::json to_json(){
|
||||
return nlohmann::json();
|
||||
};
|
||||
};
|
||||
|
||||
} // namespace CosmicCore
|
||||
#endif
|
||||
Whitespace-only changes.
@@ -0,0 +1,11 @@
|
||||
#ifndef CABSTRACTCOLLIDER_HPP
|
||||
#define CABSTRACTCOLLIDER_HPP
|
||||
#include "../CAbstractComponent.hpp"
|
||||
namespace CosmicCore {
|
||||
class CAbstractCollider: public CAbstractComponent
|
||||
{
|
||||
public:
|
||||
CAbstractCollider(CEntity& entity): CAbstractComponent(entity){};
|
||||
};
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,78 @@
|
||||
#include "CCollider.hpp"
|
||||
#include "CAbstractCollider.hpp"
|
||||
#include <Jolt/Physics/Collision/Shape/BoxShape.h>
|
||||
#include <Jolt/Physics/Collision/Shape/SphereShape.h>
|
||||
#include <Jolt/Physics/Collision/Shape/MeshShape.h>
|
||||
#include <Jolt/Physics/Collision/Shape/ConvexHullShape.h>
|
||||
#include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
|
||||
namespace CosmicCore {
|
||||
CCollider::CCollider(CEntity& e, EColliderType type): CAbstractCollider(e), m_type(type)
|
||||
{
|
||||
buildDefaultShape();
|
||||
}
|
||||
|
||||
void CCollider::buildFromMesh(CMesh* mesh) {
|
||||
if (m_type == EColliderType::ConvexHull) {
|
||||
JPH::ConvexHullShapeSettings settings;
|
||||
for (auto& v : mesh->getVertices())
|
||||
settings.mPoints.push_back({v.m_position.x,
|
||||
v.m_position.y,
|
||||
v.m_position.z});
|
||||
m_shape = settings.Create().Get();
|
||||
}
|
||||
/*else if (m_type == EColliderType::Mesh) {
|
||||
// pour les statiques
|
||||
JPH::MeshShapeSettings settings;
|
||||
// remplir triangles depuis vertices + indices
|
||||
m_shape = settings.Create().Get();
|
||||
}*/
|
||||
}
|
||||
|
||||
void CCollider::buildDefaultShape()
|
||||
{
|
||||
switch (m_type) {
|
||||
case CosmicCore::EColliderType::Box:
|
||||
setBoxSize({1.0f,1.0f,1.0f});
|
||||
break;
|
||||
case EColliderType::Sphere:
|
||||
setSphereRadius(1.0f);
|
||||
break;
|
||||
case EColliderType::Capsule:
|
||||
setCapsule(2.0f, 1.0f);
|
||||
break;
|
||||
case EColliderType::ConvexHull:
|
||||
break;
|
||||
case EColliderType::Mesh:
|
||||
break;
|
||||
case EColliderType::Compound:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// override manuel de la taille
|
||||
void CCollider::setBoxSize(glm::vec3 size) {
|
||||
m_type = EColliderType::Box;
|
||||
m_shape = new JPH::BoxShape(JPH::Vec3(size.x, size.y, size.z));
|
||||
}
|
||||
|
||||
void CCollider::setSphereRadius(float radius) {
|
||||
m_type = EColliderType::Sphere;
|
||||
m_shape = new JPH::SphereShape(radius);
|
||||
}
|
||||
|
||||
void CCollider::setCapsule(float halfHeight, float radius) {
|
||||
m_type = EColliderType::Capsule;
|
||||
m_shape = new JPH::CapsuleShape(halfHeight, radius);
|
||||
}
|
||||
|
||||
// build depuis le mesh du renderer si présent
|
||||
void CCollider::buildFromRenderer() {
|
||||
/*auto& registry = getEntity().getRegistry();
|
||||
if (!registry.all_of<CRenderer>(getEntity().getHandle())) return;
|
||||
|
||||
auto* model = registry.get<CRenderer>(getEntity().getHandle()).getModel();
|
||||
if (model->getMeshes().empty()) return;
|
||||
|
||||
buildFromMesh(model->getMeshes()[0]);*/
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
#ifndef CCOLLIDER_HPP
|
||||
#define CCOLLIDER_HPP
|
||||
#include "CAbstractCollider.hpp"
|
||||
#include <Jolt/Jolt.h>
|
||||
#include <Jolt/Physics/Collision/Shape/Shape.h>
|
||||
#include "../../Systems/Graphics/Data/Mesh/CMesh.hpp"
|
||||
#include "nlohmann/json_fwd.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
enum class EColliderType {
|
||||
Box,
|
||||
Sphere,
|
||||
Capsule,
|
||||
ConvexHull,
|
||||
Mesh,
|
||||
Compound
|
||||
};
|
||||
|
||||
class CCollider : public CAbstractCollider{
|
||||
private:
|
||||
EColliderType m_type;
|
||||
JPH::ShapeRefC m_shape = nullptr;
|
||||
public:
|
||||
CCollider(CEntity& e, EColliderType type);
|
||||
|
||||
void buildFromMesh(CMesh* mesh);
|
||||
void buildDefaultShape();
|
||||
|
||||
JPH::ShapeRefC getShape() const { return m_shape; }
|
||||
EColliderType getType() const { return m_type; }
|
||||
|
||||
void setCapsule(float halfHeight, float radius);
|
||||
void setSphereRadius(float radius);
|
||||
void setBoxSize(glm::vec3 size);
|
||||
void buildFromRenderer();
|
||||
|
||||
nlohmann::json to_json(){return nlohmann::json();};
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,29 @@
|
||||
#include "CCollider2D.hpp"
|
||||
#include "Engine/Core/Component/Geometry/CTransform2D.hpp"
|
||||
#include "Engine/Core/Kernel/CKernel.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
bool CCollider2D::shapeContains(glm::vec2 point) const {
|
||||
auto& registry = getEntity().getRegistry();
|
||||
|
||||
// récupère le transform
|
||||
auto& transform = registry.registry.get<CTransform2D>(*getEntity());
|
||||
|
||||
glm::vec2 abs = transform.getAbsolutePosition();
|
||||
float y = CKernelBase::instance()->getWindowHeight();
|
||||
|
||||
switch (m_shape) {
|
||||
|
||||
case E2DShape::RECTANGLE: {
|
||||
bool isX = point.x >= abs.x - transform.getSize().x*transform.getScale().x * 0.5f && point.x <= abs.x + transform.getSize().x*transform.getScale().x * 0.5f;
|
||||
bool isY = point.y >= abs.y - transform.getSize().y*transform.getScale().y * 0.5f && point.y <= abs.y + transform.getSize().y*transform.getScale().y * 0.5f;
|
||||
return isX && isY;
|
||||
}
|
||||
case E2DShape::CIRCLE: break;//TODO
|
||||
case E2DShape::TEXT: break;
|
||||
case E2DShape::POLYGON: break;
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#ifndef CCOLLIDER2D_HPP
|
||||
#define CCOLLIDER2D_HPP
|
||||
|
||||
#include "Engine/Core/Component/CAbstractComponent.hpp"
|
||||
#include "Engine/Core/Entity/CEntity.hpp"
|
||||
#include "glm/ext/vector_float2.hpp"
|
||||
namespace CosmicCore {
|
||||
|
||||
enum class E2DShape
|
||||
{
|
||||
RECTANGLE,
|
||||
CIRCLE,
|
||||
TEXT,
|
||||
POLYGON
|
||||
};
|
||||
|
||||
class CCollider2D: public CAbstractComponent
|
||||
{
|
||||
private:
|
||||
E2DShape m_shape = E2DShape::RECTANGLE;
|
||||
public:
|
||||
CCollider2D(CEntity& entity, E2DShape shape): CAbstractComponent(entity), m_shape(shape){};
|
||||
|
||||
bool shapeContains(glm::vec2 point) const;
|
||||
nlohmann::json to_json(){return nlohmann::json();};
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,34 @@
|
||||
#include "CAbstractCustomComponent.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
CAbstractCustomComponent::CAbstractCustomComponent(CEntity& entity): CAbstractComponent(entity)
|
||||
{
|
||||
}
|
||||
|
||||
void CAbstractCustomComponent::addProperty(std::string name, float value)
|
||||
{
|
||||
m_properties[name] = value;
|
||||
}
|
||||
|
||||
float CAbstractCustomComponent::getProperty(std::string name)
|
||||
{
|
||||
return m_properties[name];
|
||||
}
|
||||
|
||||
void CAbstractCustomComponent::setProperty(std::string name, float value)
|
||||
{
|
||||
if (m_properties.count(name) != 0)
|
||||
{
|
||||
m_properties[name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
nlohmann::json CAbstractCustomComponent::to_json()
|
||||
{
|
||||
nlohmann::json j;
|
||||
j["ComponentType"] = EComponentType::COMPONENT_CUSTOM;
|
||||
return j;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
#ifndef CABSTRACTCUSTOMCOMPONENT_HPP
|
||||
#define CABSTRACTCUSTOMCOMPONENT_HPP
|
||||
|
||||
#include "../CAbstractComponent.hpp"
|
||||
#include <unordered_map>
|
||||
|
||||
namespace CosmicCore {
|
||||
/**
|
||||
* @brief Class representing a Data Dictonnary. Is a component.
|
||||
*/
|
||||
class CAbstractCustomComponent : public CAbstractComponent{
|
||||
private:
|
||||
std::unordered_map<std::string, float> m_properties;
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief CData's default constructor, disabled.
|
||||
*/
|
||||
CAbstractCustomComponent() = delete;
|
||||
virtual ~CAbstractCustomComponent() = default;
|
||||
|
||||
/**
|
||||
* @brief CData's constructor.
|
||||
* @param[in, out] entity The entity to which we want to attach specific informations.
|
||||
*/
|
||||
CAbstractCustomComponent(CEntity& entity);
|
||||
|
||||
|
||||
void addProperty(std::string name, float value);
|
||||
|
||||
float getProperty(std::string name);
|
||||
|
||||
void setProperty(std::string name, float value);
|
||||
|
||||
nlohmann::json to_json();
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,231 @@
|
||||
#include "CTransform.hpp"
|
||||
#include "../../Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp"
|
||||
#include "../Relationships/CRelationship.hpp"
|
||||
namespace CosmicCore
|
||||
{
|
||||
|
||||
void CTransform::calcTranslation(void) {
|
||||
m_translation = glm::translate(glm::mat4(1.0f), m_center);
|
||||
}
|
||||
|
||||
void CTransform::calcRotation(void) {
|
||||
m_rotation = glm::toMat4(m_orientation);
|
||||
}
|
||||
|
||||
void CTransform::calcHomothety(void) {
|
||||
m_homothety = glm::scale(glm::mat4(1.0f), m_scale);
|
||||
}
|
||||
|
||||
void CTransform::calcTranformation(void) {
|
||||
m_transformation = m_translation * m_rotation * m_homothety;
|
||||
}
|
||||
|
||||
CTransform::CTransform(CEntity& entity) : CAbstractComponent(entity),
|
||||
m_center(0.0f, 0.0f, 0.0f),
|
||||
m_scale(1.0f, 1.0f, 1.0f),
|
||||
m_orientation(glm::identity<glm::quat>()),
|
||||
m_observers() {
|
||||
calcTranslation();
|
||||
calcRotation();
|
||||
calcHomothety();
|
||||
calcTranformation();
|
||||
}
|
||||
|
||||
CTransform::CTransform(CEntity& entity, glm::vec3 center, glm::vec3 scale, glm::vec3 eulerAngle) : CAbstractComponent(entity),
|
||||
m_center(center),
|
||||
m_scale(scale),
|
||||
m_orientation(eulerAngle),
|
||||
m_observers() {
|
||||
calcTranslation();
|
||||
calcRotation();
|
||||
calcHomothety();
|
||||
calcTranformation();
|
||||
}
|
||||
|
||||
CTransform::~CTransform()
|
||||
{
|
||||
destroyUniformBuffer();
|
||||
}
|
||||
|
||||
glm::mat4 CTransform::getTranslation(void) const {
|
||||
return m_translation;
|
||||
}
|
||||
|
||||
glm::mat4 CTransform::getRotation(void) const {
|
||||
return m_rotation;
|
||||
}
|
||||
|
||||
glm::mat4 CTransform::getHomothety(void) const {
|
||||
return m_homothety;
|
||||
}
|
||||
|
||||
glm::mat4 CTransform::getTransormation(void) const {
|
||||
return m_transformation;
|
||||
}
|
||||
|
||||
glm::mat4 CTransform::getInheritedTransformation(void) const {
|
||||
auto& registry = getEntity().getRegistry();
|
||||
|
||||
if (!registry().all_of<CRelationship>(*getEntity()))
|
||||
return m_transformation;
|
||||
|
||||
auto& rel = registry().get<CRelationship>(*getEntity());
|
||||
|
||||
if (!rel.getParent().has_value())
|
||||
return m_transformation;
|
||||
|
||||
auto& parentTransform = registry().get<CTransform>(rel.getParent().value());
|
||||
return parentTransform.getInheritedTransformation() * m_transformation;
|
||||
}
|
||||
|
||||
|
||||
glm::vec3 CTransform::getCenter(void) const {
|
||||
return m_center;
|
||||
}
|
||||
|
||||
glm::vec3* CTransform::getCenterReference(void)
|
||||
{
|
||||
return &m_center;
|
||||
}
|
||||
|
||||
glm::vec3 CTransform::getScale(void) const {
|
||||
return m_scale;
|
||||
}
|
||||
|
||||
glm::vec3& CTransform::getScalePtr(void)
|
||||
{
|
||||
return m_scale;
|
||||
}
|
||||
|
||||
glm::vec3 CTransform::getEulerAngle(void) const {
|
||||
return glm::eulerAngles(m_orientation);
|
||||
}
|
||||
|
||||
glm::quat CTransform::getOrientation(void) const
|
||||
{
|
||||
return m_orientation;
|
||||
}
|
||||
|
||||
void CTransform::setCenter(glm::vec3 newCenter) {
|
||||
m_center = newCenter;
|
||||
calcTranslation();
|
||||
calcTranformation();
|
||||
for (auto const& obs : m_observers) {
|
||||
if(auto ptrObs = obs.lock())
|
||||
ptrObs->onCenterChange();
|
||||
}
|
||||
}
|
||||
|
||||
void CTransform::setUniformScale(float newScale) {
|
||||
m_scale = glm::vec3(newScale, newScale, newScale);
|
||||
calcHomothety();
|
||||
calcTranformation();
|
||||
for (auto const& obs : m_observers) {
|
||||
if(auto ptrObs = obs.lock())
|
||||
ptrObs->onScaleChange();
|
||||
}
|
||||
}
|
||||
|
||||
void CTransform::setScale(glm::vec3 newScale) {
|
||||
m_scale = newScale;
|
||||
calcHomothety();
|
||||
calcTranformation();
|
||||
for (auto const& obs : m_observers) {
|
||||
if(auto ptrObs = obs.lock())
|
||||
ptrObs->onScaleChange();
|
||||
}
|
||||
}
|
||||
|
||||
void CTransform::rotate(glm::vec3 axis, float angle) {
|
||||
m_orientation = glm::rotate(m_orientation, angle, axis);
|
||||
calcRotation();
|
||||
calcTranformation();
|
||||
for (auto const& obs : m_observers) {
|
||||
if(auto ptrObs = obs.lock())
|
||||
ptrObs->onRotationChange();
|
||||
}
|
||||
}
|
||||
|
||||
void CTransform::setEulerAngle(glm::vec3 newEulerAngle) {
|
||||
m_orientation = glm::quat(newEulerAngle);
|
||||
calcRotation();
|
||||
calcTranformation();
|
||||
for (auto const& obs : m_observers) {
|
||||
if(auto ptrObs = obs.lock())
|
||||
ptrObs->onRotationChange();
|
||||
}
|
||||
}
|
||||
|
||||
void CTransform::setQuaternion(glm::quat newQuaternion) {
|
||||
m_orientation = newQuaternion;
|
||||
calcRotation();
|
||||
calcTranformation();
|
||||
for (auto const& obs : m_observers) {
|
||||
if(auto ptrObs = obs.lock())
|
||||
ptrObs->onRotationChange();
|
||||
}
|
||||
}
|
||||
|
||||
void CTransform::forward(glm::vec3 value) {
|
||||
glm::vec3 relValue = m_orientation * value;
|
||||
m_center += relValue;
|
||||
calcTranslation();
|
||||
calcTranformation();
|
||||
for (auto const& obs : m_observers) {
|
||||
if(auto ptrObs = obs.lock())
|
||||
ptrObs->onCenterChange();
|
||||
}
|
||||
}
|
||||
|
||||
void CTransform::addObserver(std::weak_ptr<CTransformObserver> newObserver) {
|
||||
m_observers.emplace_back(newObserver);
|
||||
}
|
||||
|
||||
void CTransform::removeObserver(std::weak_ptr<CTransformObserver> obs)
|
||||
{
|
||||
//TODO
|
||||
}
|
||||
|
||||
void CTransform::updateUniformBuffer(uint32_t frameIndex) {
|
||||
auto data{ getInheritedTransformation() }; // utilise la transformation héritée
|
||||
memcpy(m_mappedData[frameIndex], &data, sizeof(data));
|
||||
}
|
||||
|
||||
void CTransform::initUniformBuffer(VmaAllocator allocator) {
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
|
||||
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
||||
VkBufferCreateInfo bufferInfo{};
|
||||
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
bufferInfo.size = sizeof(glm::mat4);
|
||||
bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
|
||||
|
||||
VmaAllocationCreateInfo allocInfo{};
|
||||
allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
|
||||
allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
|
||||
|
||||
VmaAllocationInfo info{};
|
||||
vmaCreateBuffer(allocator, &bufferInfo, &allocInfo,
|
||||
&m_uniformBuffers[i].buffer,
|
||||
&m_uniformBuffers[i].allocation,
|
||||
&info);
|
||||
m_mappedData[i] = info.pMappedData;
|
||||
|
||||
m_descriptorSets[i] = api->getDescriptorPoolManager().allocate(api->getTransformLayout());
|
||||
|
||||
vk::DescriptorBufferInfo descriptorBufferInfo{vk::Buffer(m_uniformBuffers[i].buffer), 0, sizeof(glm::mat4)};
|
||||
vk::WriteDescriptorSet descriptorWrite{m_descriptorSets[i].set, 0, 0,1, vk::DescriptorType::eUniformBuffer, {}, &descriptorBufferInfo};
|
||||
static_cast<vk::raii::Device*>(api->getDevice())->updateDescriptorSets(descriptorWrite, {});
|
||||
}
|
||||
}
|
||||
|
||||
void CTransform::destroyUniformBuffer() {
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
|
||||
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
||||
|
||||
api->destroyBuffer(m_uniformBuffers[i], api->getCurrentFrameIndex());
|
||||
api->destroyDescriptorSet(m_descriptorSets[i], api->getCurrentFrameIndex());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
#ifndef CTRANSFORM_HPP
|
||||
#define CTRANSFORM_HPP
|
||||
|
||||
#include "../../Observer/CTransformObserver.hpp"
|
||||
#include "../CAbstractComponent.hpp"
|
||||
#include <memory>
|
||||
|
||||
#include <glm/glm.hpp>
|
||||
#include <glm/gtc/quaternion.hpp>
|
||||
#include <glm/gtx/quaternion.hpp>
|
||||
#include "../../Systems/Graphics/API/VulkanImplementation/VMABuffer.hpp"
|
||||
#include "../../Systems/Graphics/API/VulkanImplementation/ManagedDescriptorSet.hpp"
|
||||
|
||||
namespace CosmicCore
|
||||
{
|
||||
/**
|
||||
* @brief Class representing the transformations of the object in the space.
|
||||
*/
|
||||
class CTransform : public CAbstractComponent {
|
||||
private:
|
||||
|
||||
/**
|
||||
* @brief A 3D vector representing the position of the entity .
|
||||
*/
|
||||
glm::vec3 m_center;
|
||||
|
||||
/**
|
||||
* @brief A 3D vector representing the scale of the entity on each axis.
|
||||
*/
|
||||
glm::vec3 m_scale;
|
||||
|
||||
/**
|
||||
* @brief A quaternion which represent the rotation.
|
||||
*/
|
||||
glm::quat m_orientation;
|
||||
|
||||
/**
|
||||
* @brief A mat4 matrix representing the translation transformation.
|
||||
*/
|
||||
glm::mat4 m_translation;
|
||||
|
||||
/**
|
||||
* @brief A mat4 matrix representing the rotation transformation.
|
||||
*/
|
||||
glm::mat4 m_rotation;
|
||||
|
||||
/**
|
||||
* @brief A mat4 representing the scale of the object on each axis.
|
||||
*/
|
||||
glm::mat4 m_homothety;
|
||||
|
||||
/**
|
||||
* @brief Full transformation of the object.
|
||||
* result of m_translation * m_rotation * m_homothety.
|
||||
*/
|
||||
glm::mat4 m_transformation;
|
||||
|
||||
/**
|
||||
* @brief a list of observer.
|
||||
*/
|
||||
std::vector<std::weak_ptr<CTransformObserver>> m_observers;
|
||||
|
||||
/**
|
||||
* @brief Compute the translation matrix.
|
||||
*/
|
||||
void calcTranslation(void);
|
||||
|
||||
/**
|
||||
* @brief Compute the rotation matrix.
|
||||
*/
|
||||
void calcRotation(void);
|
||||
|
||||
/**
|
||||
* @brief Compute the homothety matrix.
|
||||
*/
|
||||
void calcHomothety(void);
|
||||
|
||||
/**
|
||||
* @brief Compute the full transformation of the object.
|
||||
*/
|
||||
void calcTranformation(void);
|
||||
|
||||
std::array<VMABuffer, MAX_FRAMES_IN_FLIGHT> m_uniformBuffers;
|
||||
std::array<void*, MAX_FRAMES_IN_FLIGHT> m_mappedData{};
|
||||
std::array<ManagedDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_descriptorSets;
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief CTransform's constructor. Assign the center to (0,0,0) and the scale to (1,1,1).
|
||||
* @param[in, out] m_entity The entity to which the transform belongs.
|
||||
*/
|
||||
CTransform(CEntity& m_entity);
|
||||
|
||||
~CTransform();
|
||||
|
||||
CTransform(CTransform&&) = default;
|
||||
CTransform& operator=(CTransform&&) = default;
|
||||
|
||||
CTransform(const CTransform&) = delete;
|
||||
CTransform& operator=(const CTransform&) = delete;
|
||||
/**
|
||||
* @brief CTransform's constructor.
|
||||
* @param[in, out] m_entity The entity to which the transform belongs.
|
||||
* @param[in] center A 3D vector which represent the initial position of the entity.
|
||||
* @param[in] scale A 3D vector which represent the scale of the entity on each axis.
|
||||
* @param[in] eulerAngle A 3D vector wich represent the initial rotation of the entity.
|
||||
*/
|
||||
CTransform(CEntity& m_entity, glm::vec3 center, glm::vec3 scale, glm::vec3 eulerAngle);
|
||||
|
||||
/**
|
||||
* @brief Getter to the translation matrix.
|
||||
* @return A mat4 equal to m_translation.
|
||||
*/
|
||||
glm::mat4 getTranslation(void) const;
|
||||
|
||||
/**
|
||||
* @brief Getter to the rotation matrix.
|
||||
* @return A mat4 equal to m_rotation.
|
||||
*/
|
||||
glm::mat4 getRotation(void) const;
|
||||
|
||||
/**
|
||||
* @brief Getter to the homothety.
|
||||
* @return A mat4 equal to m_homothety .
|
||||
*/
|
||||
glm::mat4 getHomothety(void) const;
|
||||
|
||||
/**
|
||||
* @brief Getter to the full transformation.
|
||||
* @return A mat4 equal to m_transformation.
|
||||
*/
|
||||
glm::mat4 getTransormation(void) const;
|
||||
|
||||
/**
|
||||
* @brief Getter to the full inherited transformation.
|
||||
* Return the current entity's transformation if there is no parent or the transformation of each parent recursively times the current transformation.
|
||||
* @return A mat4 representing the actual transformation of the entity (in the global scale).
|
||||
*/
|
||||
glm::mat4 getInheritedTransformation(void) const;
|
||||
|
||||
/**
|
||||
* @brief Getter to the entity's center.
|
||||
* @return The 3D vector of the position.
|
||||
*/
|
||||
glm::vec3 getCenter(void) const;
|
||||
|
||||
/**
|
||||
* @brief Getter to the entity's center by its pointer.
|
||||
* @return The 3D vector of the position.
|
||||
*/
|
||||
glm::vec3* getCenterReference(void);
|
||||
|
||||
|
||||
/**
|
||||
* @brief Getter to the scale.
|
||||
* @return The 3D vector of the scale.
|
||||
*/
|
||||
glm::vec3 getScale(void) const;
|
||||
|
||||
glm::vec3& getScalePtr(void);
|
||||
|
||||
/**
|
||||
* @brief Getter to the angles of the rotation on each axis.
|
||||
* @return The 3D vector of the rotation angles, determining the orientation of the object.
|
||||
*/
|
||||
glm::vec3 getEulerAngle(void) const;
|
||||
|
||||
|
||||
/**
|
||||
* @brief Getter to the quaternion.
|
||||
* @return A quaternion representing the orientation of the object.
|
||||
*/
|
||||
glm::quat getOrientation(void) const;
|
||||
|
||||
/**
|
||||
* @brief Setter of the position.
|
||||
* @param[in] newCenter The new position of the object.
|
||||
*/
|
||||
void setCenter(glm::vec3 newCenter);
|
||||
|
||||
/**
|
||||
* @brief Setter of the uniform scale (same scale on the 3-axis).
|
||||
* @param[in] newScale The new uniform scale.
|
||||
*/
|
||||
void setUniformScale(float newScale);
|
||||
|
||||
/**
|
||||
* @brief Setter of the scale.
|
||||
* @param[in] newScale The new scale on each axis (3D vector).
|
||||
*/
|
||||
void setScale(glm::vec3 newScale);
|
||||
|
||||
/**
|
||||
* @brief Rotate the object on a given axis with the given angle.
|
||||
* @param[in] axis The axis on which the rotation will occur.
|
||||
* @param[in] angle The angle the rotation must reach.
|
||||
*/
|
||||
void rotate(glm::vec3 axis, float angle);
|
||||
|
||||
/**
|
||||
* @brief Translate the object on the given axis with the given value on each axis.
|
||||
* @param[in] value The 3D vector of the translation.
|
||||
*/
|
||||
void forward(glm::vec3 value);
|
||||
|
||||
/**
|
||||
* @brief Setter of the Angles.
|
||||
* @param[in] newEulerAngle The new orientation of the object.
|
||||
*/
|
||||
void setEulerAngle(glm::vec3 newEulerAngle);
|
||||
|
||||
/**
|
||||
* @brief Setter of the orientation quaternion.
|
||||
* @param[in] newQuaternion The new orientation of the object.
|
||||
*/
|
||||
void setQuaternion(glm::quat newQuaternion);
|
||||
|
||||
/**
|
||||
* @brief Add an observer on the transform. Can be from any class if the said class is child class of CTransformObserver.
|
||||
* @param[in, out] newObserver The observer to add.
|
||||
*/
|
||||
void addObserver(std::weak_ptr<CTransformObserver> newObserver);
|
||||
|
||||
/**
|
||||
* @brief Remove an observer of the transform. Does nothing if the observer doesn't exist.
|
||||
* @param[in, out] obs The observer to remove.
|
||||
*/
|
||||
void removeObserver(std::weak_ptr<CTransformObserver> obs);
|
||||
|
||||
nlohmann::json to_json() {
|
||||
nlohmann::json j;
|
||||
j["Position"]["x"] = m_center.x;
|
||||
j["Position"]["y"] = m_center.y;
|
||||
j["Position"]["z"] = m_center.z;
|
||||
|
||||
j["Rotation"]["x"] = getEulerAngle().x;
|
||||
j["Rotation"]["y"] = getEulerAngle().y;
|
||||
j["Rotation"]["z"] = getEulerAngle().z;
|
||||
|
||||
j["Scale"]["x"] = getScale().x;
|
||||
j["Scale"]["y"] = getScale().y;
|
||||
j["Scale"]["z"] = getScale().z;
|
||||
return j;
|
||||
};
|
||||
|
||||
static CTransform from_json(CEntity entity,nlohmann::json& j)
|
||||
{
|
||||
CTransform t(entity);
|
||||
t.setCenter(glm::vec3(j["Position"]["x"], j["Position"]["y"], j["Position"]["z"]));
|
||||
t.setEulerAngle(glm::vec3(j["Rotation"]["x"], j["Rotation"]["y"], j["Rotation"]["z"]));
|
||||
t.setScale(glm::vec3(j["Scale"]["x"], j["Scale"]["y"], j["Scale"]["z"]));
|
||||
return t;
|
||||
};
|
||||
|
||||
void initUniformBuffer(VmaAllocator allocator);
|
||||
void destroyUniformBuffer();
|
||||
void updateUniformBuffer(uint32_t frameIndex);
|
||||
|
||||
VMABuffer& getUniformBuffer(uint32_t frameIndex) {
|
||||
return m_uniformBuffers[frameIndex];
|
||||
};
|
||||
vk::raii::DescriptorSet& getDescriptorSet(uint32_t frameIndex) {
|
||||
return m_descriptorSets[frameIndex].set;
|
||||
};
|
||||
};
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,64 @@
|
||||
#include "CTransform2D.hpp"
|
||||
#include "Engine/Core/Kernel/CKernel.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp"
|
||||
#include <iostream>
|
||||
|
||||
namespace CosmicCore {
|
||||
void CTransform2D::initUniformBuffer(VmaAllocator allocator)
|
||||
{
|
||||
if(m_gpuInitialized) return;
|
||||
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
|
||||
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
||||
VkBufferCreateInfo bufferInfo{};
|
||||
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
bufferInfo.size = sizeof(Transform2DUBO);
|
||||
bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
|
||||
|
||||
VmaAllocationCreateInfo allocInfo{};
|
||||
allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
|
||||
allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
|
||||
|
||||
VmaAllocationInfo info{};
|
||||
vmaCreateBuffer(allocator, &bufferInfo, &allocInfo,
|
||||
&m_uniformBuffers[i].buffer,
|
||||
&m_uniformBuffers[i].allocation,
|
||||
&info);
|
||||
m_mappedData[i] = info.pMappedData;
|
||||
|
||||
m_descriptorSets[i] = api->getDescriptorPoolManager().allocate(api->getTransform2DLayout());
|
||||
|
||||
vk::DescriptorBufferInfo descriptorBufferInfo{vk::Buffer(m_uniformBuffers[i].buffer), 0, sizeof(Transform2DUBO)};
|
||||
vk::WriteDescriptorSet descriptorWrite{m_descriptorSets[i].set, 0, 0,1, vk::DescriptorType::eUniformBuffer, {}, &descriptorBufferInfo};
|
||||
static_cast<vk::raii::Device*>(api->getDevice())->updateDescriptorSets(descriptorWrite, {});
|
||||
}
|
||||
m_gpuInitialized = true;
|
||||
}
|
||||
|
||||
void CTransform2D::destroyUniformBuffer()
|
||||
{
|
||||
if(!m_gpuInitialized) return;
|
||||
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
|
||||
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
||||
|
||||
api->destroyBuffer(m_uniformBuffers[i], api->getCurrentFrameIndex());
|
||||
api->destroyDescriptorSet(m_descriptorSets[i], api->getCurrentFrameIndex());
|
||||
}
|
||||
}
|
||||
|
||||
void CTransform2D::updateUniformBuffer(uint32_t frameIndex)
|
||||
{
|
||||
if (!m_gpuInitialized) return;
|
||||
Transform2DUBO data{
|
||||
getMatrix(),
|
||||
m_size,
|
||||
m_zOrder,
|
||||
0.0f
|
||||
};
|
||||
memcpy(m_mappedData[frameIndex], &data, sizeof(data));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
#ifndef CTRANSFORM2D_HPP
|
||||
#define CTRANSFORM2D_HPP
|
||||
|
||||
#include "Engine/Core/Component/CAbstractComponent.hpp"
|
||||
#include "Engine/Core/Component/Relationships/CRelationship.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/ManagedDescriptorSet.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/VMABuffer.hpp"
|
||||
#include "glm/ext/matrix_float4x4.hpp"
|
||||
#include "glm/ext/vector_float2.hpp"
|
||||
#include "glm/gtx/transform.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
struct Transform2DUBO {
|
||||
glm::mat4 transform; // matrice 2D
|
||||
glm::vec2 size; // taille pour le shader SDF
|
||||
float zOrder; // = 0 => pas utilse géré dans l'ordre de render de scene
|
||||
float padding; // = 0 => pas utilse (pour l'instant ?)
|
||||
};
|
||||
|
||||
class CTransform2D : public CAbstractComponent {
|
||||
glm::vec2 m_position = {0, 0};
|
||||
glm::vec2 m_size = {100, 100};
|
||||
glm::vec2 m_scale = {1, 1}; // scale indépendant de la taille
|
||||
glm::vec2 m_anchor = {0, 0}; // 0=topleft, 0.5=center, 1=bottomright
|
||||
glm::vec2 m_pivot = {0, 0};
|
||||
float m_rotation = 0.0f;
|
||||
float m_zOrder = 0.0f; // ordre de rendu UI
|
||||
bool m_visible = true;
|
||||
|
||||
std::array<VMABuffer, MAX_FRAMES_IN_FLIGHT> m_uniformBuffers;
|
||||
std::array<void*, MAX_FRAMES_IN_FLIGHT> m_mappedData{};
|
||||
std::array<ManagedDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_descriptorSets;
|
||||
bool m_gpuInitialized = false;
|
||||
|
||||
public:
|
||||
explicit CTransform2D(CEntity& entity) : CAbstractComponent(entity) {}
|
||||
|
||||
~CTransform2D() {
|
||||
if (m_gpuInitialized) destroyUniformBuffer();
|
||||
}
|
||||
|
||||
CTransform2D(CTransform2D&&) = default;
|
||||
CTransform2D& operator=(CTransform2D&&) = default;
|
||||
CTransform2D(const CTransform2D&) = delete;
|
||||
CTransform2D& operator=(const CTransform2D&) = delete;
|
||||
|
||||
CTransform2D& setPosition(glm::vec2 pos) { m_position = pos; return *this; }
|
||||
CTransform2D& setSize(glm::vec2 size) { m_size = size; return *this; }
|
||||
CTransform2D& setScale(glm::vec2 scale) { m_scale = scale;return *this; }
|
||||
CTransform2D& setRotation(float rot) { m_rotation = rot; return *this; }
|
||||
CTransform2D& setZOrder(float z) { m_zOrder = z; return *this; }
|
||||
CTransform2D& setVisible(bool v) { m_visible = v; return *this; }
|
||||
CTransform2D& setAnchor(glm::vec2 anchor) { m_anchor = anchor; return *this; }
|
||||
CTransform2D& setPivot(glm::vec2 pivot) { m_pivot = pivot; return *this; }
|
||||
|
||||
glm::vec2 getPosition() const { return m_position; }
|
||||
glm::vec2 getSize() const { return m_size; }
|
||||
glm::vec2 getScale() const { return m_scale; }
|
||||
float getRotation() const { return m_rotation; }
|
||||
float getZOrder() const { return m_zOrder; }
|
||||
bool isVisible() const { return m_visible; }
|
||||
|
||||
glm::vec2 getAbsolutePosition() const {
|
||||
|
||||
auto& registry = getEntity().getRegistry();
|
||||
|
||||
if (!registry().all_of<CRelationship>(*getEntity()))
|
||||
return m_position;
|
||||
|
||||
auto& rel = registry().get<CRelationship>(*getEntity());
|
||||
|
||||
if (!rel.getParent().has_value())
|
||||
return m_position;
|
||||
|
||||
auto& parentTransform = registry().get<CTransform2D>(rel.getParent().value());
|
||||
return parentTransform.getAbsolutePosition() + m_anchor * parentTransform.getSize() + m_position;
|
||||
}
|
||||
|
||||
glm::mat4 getMatrix() const {
|
||||
glm::vec2 absPos = getAbsolutePosition();
|
||||
glm::vec2 pivotPx = m_pivot * m_size;
|
||||
|
||||
glm::mat4 mat = glm::mat4(1.0f);
|
||||
mat = glm::translate(mat, glm::vec3(absPos + pivotPx, 0));
|
||||
mat = glm::rotate(mat, glm::radians(m_rotation), {0, 0, 1});
|
||||
mat = glm::scale(mat, glm::vec3(m_size * m_scale, 1));
|
||||
mat = glm::translate(mat, glm::vec3(-m_pivot, 0));
|
||||
return mat;
|
||||
}
|
||||
|
||||
// ── GPU ───────────────────────────────────────────────────────────
|
||||
void initUniformBuffer(VmaAllocator allocator);
|
||||
void destroyUniformBuffer();
|
||||
void updateUniformBuffer(uint32_t frameIndex);
|
||||
|
||||
vk::raii::DescriptorSet& getDescriptorSet(uint32_t frameIndex) {
|
||||
return m_descriptorSets[frameIndex].set;
|
||||
}
|
||||
|
||||
nlohmann::json to_json() {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
Whitespace-only changes.
@@ -0,0 +1,11 @@
|
||||
#ifndef CABSTRACTRENDERER_HPP
|
||||
#define CABSTRACTRENDERER_HPP
|
||||
#include "../CAbstractComponent.hpp"
|
||||
namespace CosmicCore {
|
||||
class CAbstractRenderer : public CAbstractComponent
|
||||
{
|
||||
public:
|
||||
CAbstractRenderer(CEntity& e): CAbstractComponent(e){};
|
||||
};
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,3 @@
|
||||
#include "CRenderer.hpp"
|
||||
namespace CosmicCore {
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#ifndef CTESTRENDERER_HPP
|
||||
#define CTESTRENDERER_HPP
|
||||
#include "CAbstractRenderer.hpp"
|
||||
#include "../../Systems/Graphics/Data/Model/CModel.hpp"
|
||||
namespace CosmicCore {
|
||||
class CRenderer: public CAbstractRenderer
|
||||
{
|
||||
CModel* m_model = nullptr;
|
||||
public:
|
||||
CRenderer() = delete;
|
||||
CRenderer(CEntity& e): CAbstractRenderer(e){};
|
||||
CRenderer(CEntity& e, CModel* mod): CAbstractRenderer(e), m_model(mod){};
|
||||
nlohmann::json to_json() override{return nlohmann::json();};
|
||||
CModel* getModel(){return m_model;};
|
||||
};
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
#include "CRenderer2D.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
} // namespace CosmicCore
|
||||
@@ -0,0 +1,21 @@
|
||||
#ifndef CUIRENDERER_HPP
|
||||
#define CUIRENDERER_HPP
|
||||
|
||||
#include "Engine/Core/Component/Graphics/CAbstractRenderer.hpp"
|
||||
#include "Engine/Core/Entity/CEntity.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/Data/Model/CModel2D.hpp"
|
||||
namespace CosmicCore {
|
||||
class CRenderer2D : public CAbstractRenderer{
|
||||
|
||||
CModel2D* m_model;
|
||||
|
||||
public:
|
||||
CRenderer2D() = delete;
|
||||
CRenderer2D(CEntity& e): CAbstractRenderer(e){};
|
||||
CRenderer2D(CEntity& e, CModel2D* mod): CAbstractRenderer(e), m_model(mod){};
|
||||
nlohmann::json to_json() override{return nlohmann::json();};
|
||||
CModel2D* getModel(){return m_model;};
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,85 @@
|
||||
#include "CInputManager.hpp"
|
||||
#include "Engine/Core/Systems/Input/API/CInputAPI.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
void CInputManager::onPressed(const std::string& actionName, std::function<void(CEntity&)> cb)
|
||||
{
|
||||
m_onPressed.push_back({actionName, cb, 0, false});
|
||||
}
|
||||
|
||||
void CInputManager::onHeld(const std::string& actionName, std::function<void(CEntity&)> cb)
|
||||
{
|
||||
m_onHeld.push_back({actionName, cb, 0, false});
|
||||
}
|
||||
|
||||
void CInputManager::onReleased(const std::string& actionName, std::function<void(CEntity&)> cb)
|
||||
{
|
||||
m_onReleased.push_back({actionName, cb, 0, false});
|
||||
}
|
||||
|
||||
void CInputManager::addOnMouseMove(std::function<void(CEntity&, glm::vec2)> cb)
|
||||
{
|
||||
m_onMouseMove.emplace_back(cb);
|
||||
}
|
||||
|
||||
void CInputManager::addOnGenericMouseLeftClick(std::function<void(CEntity&)> cb)
|
||||
{
|
||||
m_onMouseLeftClickReleased.emplace_back(GenericMouseClickAction(cb));
|
||||
}
|
||||
|
||||
// appelé par CInputWorld::updateWorld()
|
||||
void CInputManager::dispatch(const CInputDispatcher& inputWorld) {
|
||||
if (!m_enabled) return;
|
||||
auto& entity = getEntity();
|
||||
|
||||
// résolution lazy — une seule fois par action
|
||||
for (auto& bound : m_onHeld) {
|
||||
if (!bound.resolved) {
|
||||
auto action = CInputAPI::getAction(bound.name);
|
||||
if (action) {
|
||||
bound.resolvedId = *action;
|
||||
bound.resolved = true;
|
||||
}
|
||||
// si pas encore enregistrée → retry au prochain frame
|
||||
}
|
||||
if (bound.resolved && inputWorld.isActive(bound.resolvedId))
|
||||
bound.cb(entity);
|
||||
}
|
||||
|
||||
for (auto& bound : m_onPressed) {
|
||||
if (!bound.resolved) {
|
||||
auto action = CInputAPI::getAction(bound.name);
|
||||
if (action) { bound.resolvedId = *action; bound.resolved = true; }
|
||||
}
|
||||
if (bound.resolved && inputWorld.isJustPressed(bound.resolvedId))
|
||||
bound.cb(entity);
|
||||
}
|
||||
|
||||
for (auto& bound : m_onReleased) {
|
||||
if (!bound.resolved) {
|
||||
auto action = CInputAPI::getAction(bound.name);
|
||||
if (action) { bound.resolvedId = *action; bound.resolved = true; }
|
||||
}
|
||||
if (bound.resolved && inputWorld.isJustReleased(bound.resolvedId))
|
||||
bound.cb(entity);
|
||||
}
|
||||
|
||||
glm::vec2 mouseRel = inputWorld.getMouseRelative();
|
||||
if (!m_onMouseMove.empty() && (mouseRel.x != 0 || mouseRel.y != 0))
|
||||
{
|
||||
for(auto& cbH : m_onMouseMove)
|
||||
{
|
||||
cbH.cb(entity, mouseRel);
|
||||
}
|
||||
}
|
||||
//todo other click (onClick and right click)
|
||||
if(!m_onMouseLeftClickReleased.empty() && inputWorld.isLeftMouseButtonJustReleased())
|
||||
{
|
||||
for(auto& clickCB : m_onMouseLeftClickReleased)
|
||||
{
|
||||
clickCB.cb(entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
#ifndef CINPUTMANAGER_HPP
|
||||
#define CINPUTMANAGER_HPP
|
||||
|
||||
#include "Engine/Core/Component/CAbstractComponent.hpp"
|
||||
#include "Engine/Core/Systems/Input/API/CInputAPI.hpp"
|
||||
#include "Engine/Core/Systems/Input/CInputDispatcher.hpp"
|
||||
#include "glm/fwd.hpp"
|
||||
#include "nlohmann/json_fwd.hpp"
|
||||
#include <vector>
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
class CInputManager : public CAbstractComponent
|
||||
{
|
||||
private:
|
||||
|
||||
struct BoundAction {
|
||||
std::string name;
|
||||
std::function<void(CEntity&)> cb;
|
||||
InputAction resolvedId = 0;
|
||||
bool resolved = false;
|
||||
};
|
||||
|
||||
struct GenericMouseClickAction{
|
||||
std::function<void(CEntity&)> cb;
|
||||
};
|
||||
|
||||
struct MouseMovementAction{
|
||||
std::function<void(CEntity&, glm::vec2)> cb;
|
||||
};
|
||||
|
||||
std::vector<BoundAction> m_onHeld;
|
||||
std::vector<BoundAction> m_onPressed;
|
||||
std::vector<BoundAction> m_onReleased;
|
||||
|
||||
std::vector<MouseMovementAction> m_onMouseMove;
|
||||
std::vector<GenericMouseClickAction> m_onMouseLeftClickPressed;
|
||||
std::vector<GenericMouseClickAction> m_onMouseLeftClickReleased;
|
||||
std::vector<GenericMouseClickAction> m_onMouseRightClickPressed;
|
||||
std::vector<GenericMouseClickAction> m_onMouseRightClickReleased;
|
||||
bool m_enabled = true;
|
||||
|
||||
public:
|
||||
CInputManager(CEntity& entity) : CAbstractComponent(entity) {}
|
||||
|
||||
|
||||
void onPressed(const std::string& actionName, std::function<void(CEntity&)> cb);
|
||||
void onHeld(const std::string& actionName, std::function<void(CEntity&)> cb);
|
||||
void onReleased(const std::string& actionName, std::function<void(CEntity&)> cb);
|
||||
void addOnMouseMove(std::function<void(CEntity&, glm::vec2)> cb);
|
||||
void addOnGenericMouseLeftClick(std::function<void(CEntity&)> cb);
|
||||
|
||||
void setEnabled(bool enabled) { m_enabled = enabled; }
|
||||
|
||||
void dispatch(const CInputDispatcher& inputWorld);
|
||||
|
||||
nlohmann::json to_json(){return nlohmann::json();}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,5 @@
|
||||
#include "CLight.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
#ifndef CLIGHT_HPP
|
||||
#define CLIGHT_HPP
|
||||
#include "../CAbstractComponent.hpp"
|
||||
#include "glm/ext/vector_float3.hpp"
|
||||
namespace CosmicCore {
|
||||
|
||||
enum class ELightType {
|
||||
Directional, // soleil
|
||||
Point, // ampoule
|
||||
Spot // lampe torche
|
||||
};
|
||||
|
||||
class CLight: public CAbstractComponent
|
||||
{
|
||||
// données communes
|
||||
glm::vec3 color = {1.0f, 1.0f, 1.0f};
|
||||
float intensity = 1.0f;
|
||||
bool castShadow = false;
|
||||
|
||||
// Point + Spot
|
||||
float range = 10.0f;
|
||||
float attenuation = 1.0f; // falloff
|
||||
|
||||
// Spot uniquement
|
||||
float innerAngle = 15.0f; // degrés
|
||||
float outerAngle = 30.0f; // degrés
|
||||
|
||||
ELightType type = ELightType::Directional;
|
||||
|
||||
public:
|
||||
|
||||
CLight(CEntity& entity, ELightType type = ELightType::Directional)
|
||||
: CAbstractComponent(entity), type(type) {}
|
||||
|
||||
CLight(CLight&&) = default;
|
||||
CLight& operator=(CLight&&) = default;
|
||||
CLight(const CLight&) = delete;
|
||||
CLight& operator=(const CLight&) = delete;
|
||||
|
||||
|
||||
const glm::vec3& getColor() const {return color;};
|
||||
float getRange(){return range;};
|
||||
float getIntensity(){return intensity;};
|
||||
float getInnerAngle(){return innerAngle;};
|
||||
float getOuterAngle(){return outerAngle;};
|
||||
float getAttenuation(){return attenuation;}
|
||||
ELightType getType(){return type;}
|
||||
|
||||
void setColor(const glm::vec3& c) { color = c; }
|
||||
void setRange(float r) { range = r; }
|
||||
void setIntensity(float i) { intensity = i; }
|
||||
void setInnerAngle(float angle) { innerAngle = angle; }
|
||||
void setOuterAngle(float angle) { outerAngle = angle; }
|
||||
void setAttenuation(float a) { attenuation = a; }
|
||||
void setType(ELightType t) { type = t; }
|
||||
void setCastShadow(bool shadow) { castShadow = shadow; }
|
||||
|
||||
nlohmann::json to_json() {
|
||||
nlohmann::json j;
|
||||
j["type"] = (int)type;
|
||||
j["color"] = {color.r, color.g, color.b};
|
||||
j["intensity"] = intensity;
|
||||
j["range"] = range;
|
||||
j["innerAngle"] = innerAngle;
|
||||
j["outerAngle"] = outerAngle;
|
||||
j["castShadow"] = castShadow;
|
||||
return j;
|
||||
}
|
||||
};
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,23 @@
|
||||
#ifndef CMETADATA_HPP
|
||||
#define CMETADATA_HPP
|
||||
|
||||
#include "../CAbstractComponent.hpp"
|
||||
#include "nlohmann/json_fwd.hpp"
|
||||
#include <string>
|
||||
|
||||
namespace CosmicCore {
|
||||
class CMetaData : public CAbstractComponent{
|
||||
private:
|
||||
std::string m_name;
|
||||
std::string m_description;
|
||||
public:
|
||||
CMetaData(CEntity& entity): CAbstractComponent(entity){}
|
||||
CMetaData(CEntity& entity, std::string na, std::string desc): CAbstractComponent(entity), m_name(std::move(na)), m_description(std::move(desc)){}
|
||||
nlohmann::json to_json(){return nlohmann::json();}
|
||||
void setName(std::string name){m_name = std::move(name);}
|
||||
void setDescription(std::string desc){m_description = std::move(desc);}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,31 @@
|
||||
#ifndef CRELATIONSHIP_HPP
|
||||
#define CRELATIONSHIP_HPP
|
||||
|
||||
#include "../CAbstractComponent.hpp"
|
||||
#include "nlohmann/json_fwd.hpp"
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
namespace CosmicCore {
|
||||
class CRelationship : public CAbstractComponent{
|
||||
private:
|
||||
std::optional<EntityId> parent;
|
||||
std::vector<EntityId> children;
|
||||
public:
|
||||
CRelationship(CEntity& entity): CAbstractComponent(entity){}
|
||||
CRelationship(CEntity& entity, std::optional<EntityId> p): CAbstractComponent(entity), parent(p){}
|
||||
CRelationship(CEntity& entity, std::vector<EntityId> childs): CAbstractComponent(entity), children(childs){}
|
||||
CRelationship(CEntity& entity, std::optional<EntityId> p, std::vector<EntityId> childs): CAbstractComponent(entity), parent(p), children(childs){}
|
||||
|
||||
nlohmann::json to_json(){return nlohmann::json();}
|
||||
void setParent(EntityId par){parent = par;}
|
||||
void addChild(EntityId child){children.emplace_back(child);}
|
||||
std::optional<EntityId> getParent(){return parent;}
|
||||
const std::optional<EntityId> getParent() const {return parent;}
|
||||
|
||||
std::vector<EntityId>& getChildren(){return children;}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,6 @@
|
||||
#include "CAbstractRigidbody.hpp"
|
||||
namespace CosmicCore {
|
||||
CAbstractRigidBody::CAbstractRigidBody(CEntity& entity): CAbstractComponent(entity)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#ifndef CABSTRACTRIGIDBODY_HPP
|
||||
#define CABSTRACTRIGIDBODY_HPP
|
||||
#include "../CAbstractComponent.hpp"
|
||||
#include "nlohmann/json_fwd.hpp"
|
||||
namespace CosmicCore {
|
||||
class CAbstractRigidBody: public CAbstractComponent
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief CData's constructor.
|
||||
* @param[in, out] entity The entity to which we want to attach specific informations.
|
||||
*/
|
||||
CAbstractRigidBody(CEntity& entity);
|
||||
nlohmann::json to_json(){return nlohmann::json();};
|
||||
};
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,121 @@
|
||||
#include "CRigidBody.hpp"
|
||||
#include "../../Systems/Physics/PhysicsLayers.hpp"
|
||||
#include "../../Scene/CScene.hpp"
|
||||
#include "../Geometry/CTransform.hpp"
|
||||
#include "../Collider/CCollider.hpp"
|
||||
#include "Jolt/Physics/EActivation.h"
|
||||
|
||||
namespace CosmicCore {
|
||||
CRigidBody::CRigidBody(CEntity& entity, EBodyType type): CAbstractRigidBody(entity), m_bodyType(type)
|
||||
{
|
||||
}
|
||||
|
||||
// initialise le body dans le monde physique
|
||||
// doit être appelé après CCollider et CTransform
|
||||
void CRigidBody::init() {
|
||||
|
||||
|
||||
auto& registry = getEntity().getRegistry();
|
||||
|
||||
// récupère le transform
|
||||
auto& transform = registry.registry.get<CTransform>(*getEntity());
|
||||
auto& collider = registry.registry.get<CCollider>(*getEntity());
|
||||
glm::vec3 pos = transform.getCenter();
|
||||
glm::quat ori = transform.getOrientation();
|
||||
|
||||
// motion type
|
||||
JPH::EMotionType motionType;
|
||||
JPH::ObjectLayer layer;
|
||||
switch (m_bodyType) {
|
||||
case EBodyType::Static:
|
||||
motionType = JPH::EMotionType::Static;
|
||||
layer = Layers::NON_MOVING;
|
||||
break;
|
||||
case EBodyType::Kinematic:
|
||||
motionType = JPH::EMotionType::Kinematic;
|
||||
layer = Layers::MOVING;
|
||||
break;
|
||||
case EBodyType::Dynamic:
|
||||
default:
|
||||
motionType = JPH::EMotionType::Dynamic;
|
||||
layer = Layers::MOVING;
|
||||
break;
|
||||
}
|
||||
|
||||
// création du body
|
||||
JPH::BodyCreationSettings settings(
|
||||
collider.getShape(),
|
||||
JPH::RVec3(pos.x, pos.y, pos.z),
|
||||
JPH::Quat(ori.x, ori.y, ori.z, ori.w),
|
||||
motionType,
|
||||
layer
|
||||
);
|
||||
settings.mFriction = m_friction;
|
||||
settings.mRestitution = m_restitution;
|
||||
if (m_bodyType == EBodyType::Static)
|
||||
{
|
||||
settings.mMotionType = JPH::EMotionType::Static;
|
||||
}
|
||||
else
|
||||
{
|
||||
settings.mOverrideMassProperties = JPH::EOverrideMassProperties::CalculateInertia;
|
||||
settings.mMassPropertiesOverride.mMass = m_mass;
|
||||
}
|
||||
|
||||
auto& bodyInterface = getEntity().getScene()->getTangibleWorld().getBodyInterface();
|
||||
m_bodyID = bodyInterface.CreateAndAddBody(
|
||||
settings,
|
||||
m_bodyType != EBodyType::Static ? JPH::EActivation::Activate : JPH::EActivation::DontActivate
|
||||
);
|
||||
m_initialized = true;
|
||||
}
|
||||
|
||||
void CRigidBody::destroy() {
|
||||
if (!m_initialized) return;
|
||||
// récupère le world via le kernel
|
||||
auto* scene = getEntity().getScene();
|
||||
if (!scene) return;
|
||||
auto& bodyInterface = scene->getTangibleWorld()
|
||||
.getPhysicsSystem()
|
||||
.GetBodyInterface();
|
||||
if (bodyInterface.IsAdded(m_bodyID))
|
||||
bodyInterface.RemoveBody(m_bodyID);
|
||||
bodyInterface.DestroyBody(m_bodyID);
|
||||
m_initialized = false;
|
||||
}
|
||||
|
||||
// sync CTransform depuis la physique
|
||||
void CRigidBody::syncTransform() {
|
||||
if (!m_initialized) return;
|
||||
auto& registry = getEntity().getRegistry();
|
||||
auto& transform = registry.registry.get<CTransform>(*getEntity());
|
||||
auto& bodyInterface = getEntity().getScene()
|
||||
->getTangibleWorld()
|
||||
.getBodyInterface();
|
||||
|
||||
JPH::RVec3 pos = bodyInterface.GetCenterOfMassPosition(m_bodyID);
|
||||
JPH::Quat ori = bodyInterface.GetRotation(m_bodyID);
|
||||
|
||||
transform.setCenter({pos.GetX(), pos.GetY(), pos.GetZ()});
|
||||
transform.setQuaternion({ori.GetW(), ori.GetX(), ori.GetY(), ori.GetZ()});
|
||||
}
|
||||
|
||||
// forces
|
||||
void CRigidBody::addForce(glm::vec3 force) {
|
||||
if (!m_initialized) return;
|
||||
auto& bi = getEntity().getScene()->getTangibleWorld().getBodyInterface();
|
||||
bi.AddForce(m_bodyID, JPH::Vec3(force.x, force.y, force.z));
|
||||
}
|
||||
|
||||
void CRigidBody::addImpulse(glm::vec3 impulse) {
|
||||
if (!m_initialized) return;
|
||||
auto& bi = getEntity().getScene()->getTangibleWorld().getBodyInterface();
|
||||
bi.AddImpulse(m_bodyID, JPH::Vec3(impulse.x, impulse.y, impulse.z));
|
||||
}
|
||||
|
||||
void CRigidBody::setLinearVelocity(glm::vec3 velocity) {
|
||||
if (!m_initialized) return;
|
||||
auto& bi = getEntity().getScene()->getTangibleWorld().getBodyInterface();
|
||||
bi.SetLinearVelocity(m_bodyID, JPH::Vec3(velocity.x, velocity.y, velocity.z));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
#ifndef CRIGIDBODY_HPP
|
||||
#define CRIGIDBODY_HPP
|
||||
|
||||
#include "CAbstractRigidbody.hpp"
|
||||
#include "glm/fwd.hpp"
|
||||
#include <Jolt/Jolt.h>
|
||||
#include <Jolt/Physics/Body/Body.h>
|
||||
#include <Jolt/Physics/Body/BodyCreationSettings.h>
|
||||
#include <Jolt/Physics/Body/MotionType.h>
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
enum class EBodyType {
|
||||
Static, // ne bouge pas (décors, terrain)
|
||||
Kinematic, // bouge mais pas affecté par la physique (plateformes)
|
||||
Dynamic // affecté par la physique (objets normaux)
|
||||
};
|
||||
|
||||
class CRigidBody : public CAbstractRigidBody {
|
||||
private:
|
||||
JPH::BodyID m_bodyID;
|
||||
EBodyType m_bodyType = EBodyType::Dynamic;
|
||||
float m_mass = 1.0f;
|
||||
float m_friction = 0.5f;
|
||||
float m_restitution = 0.0f; // rebond
|
||||
bool m_initialized = false;
|
||||
|
||||
public:
|
||||
CRigidBody(CEntity& entity, EBodyType type = EBodyType::Dynamic);
|
||||
|
||||
~CRigidBody() {
|
||||
destroy();
|
||||
}
|
||||
|
||||
CRigidBody(const CRigidBody&) = delete;
|
||||
CRigidBody& operator=(const CRigidBody&) = delete;
|
||||
|
||||
void setLinearVelocity(glm::vec3 velocity);
|
||||
void addImpulse(glm::vec3 impulse);
|
||||
void addForce(glm::vec3 force);
|
||||
void syncTransform();
|
||||
void destroy();
|
||||
void init();
|
||||
|
||||
|
||||
// setters
|
||||
void setMass(float mass) { m_mass = mass; }
|
||||
void setFriction(float friction) { m_friction = friction; }
|
||||
void setRestitution(float restitution){ m_restitution = restitution; }
|
||||
void setBodyType(EBodyType type) { m_bodyType = type; }
|
||||
|
||||
// getters
|
||||
JPH::BodyID getBodyID() const { return m_bodyID; }
|
||||
EBodyType getBodyType() const { return m_bodyType; }
|
||||
float getMass() const { return m_mass; }
|
||||
bool isInitialized() const { return m_initialized; }
|
||||
|
||||
nlohmann::json to_json() { return {}; }
|
||||
};
|
||||
|
||||
} // namespace CosmicCore
|
||||
#endif
|
||||
@@ -0,0 +1,10 @@
|
||||
#include "CAbstractScript.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
CAbstractScript::CAbstractScript(CEntity& entity, const std::string& name) : CAbstractComponent(entity), m_scriptName(name)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
#ifndef CABSTRACTSCRIPT_HPP
|
||||
#define CABSTRACTSCRIPT_HPP
|
||||
|
||||
#include "../CAbstractComponent.hpp"
|
||||
#include "../../Entity/CEntity.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
class CAbstractScript : public CAbstractComponent
|
||||
{
|
||||
private:
|
||||
std::string m_scriptName;
|
||||
public:
|
||||
CAbstractScript(CEntity& entity, const std::string& name);
|
||||
CAbstractScript(CAbstractScript&& other) = default;
|
||||
CAbstractScript& operator=(CAbstractScript&&) = default;
|
||||
virtual void onCreate() = 0;
|
||||
virtual void start() = 0;
|
||||
virtual void update() = 0;
|
||||
virtual void destroy() = 0;
|
||||
virtual nlohmann::json to_json() = 0;
|
||||
virtual ~CAbstractScript() = default;
|
||||
std::string getName() { return m_scriptName; };
|
||||
void setName(const std::string& name) { m_scriptName = name; };
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,44 @@
|
||||
#include "CScript.hpp"
|
||||
#include "Engine/Core/Component/Script/CAbstractScript.hpp"
|
||||
#include "Engine/Core/Systems/Scripts/API/CScriptAPI.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
CScript::CScript(CEntity& entity, const std::string& name, std::unique_ptr<CAbstractScript>&& innerScript) : CAbstractScript(entity, name), m_innerScript(std::move(innerScript))
|
||||
{
|
||||
onCreate();
|
||||
}
|
||||
|
||||
CScript::CScript(CEntity& entity, const std::string& name) : CAbstractScript(entity, name)
|
||||
{
|
||||
m_innerScript = CScriptAPI::scripts().create(name, entity, name);
|
||||
onCreate();
|
||||
}
|
||||
|
||||
void CScript::start()
|
||||
{
|
||||
m_innerScript->start();
|
||||
}
|
||||
|
||||
void CScript::update()
|
||||
{
|
||||
m_innerScript->update();
|
||||
}
|
||||
|
||||
void CScript::destroy()
|
||||
{
|
||||
m_innerScript->destroy();
|
||||
}
|
||||
|
||||
void CScript::onCreate()
|
||||
{
|
||||
m_innerScript->onCreate();
|
||||
}
|
||||
|
||||
nlohmann::json CScript::to_json()
|
||||
{
|
||||
return m_innerScript->to_json();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
#ifndef CSCRIPT_HPP
|
||||
#define CSCRIPT_HPP
|
||||
|
||||
#include "Engine//Core/Component/Script/CAbstractScript.hpp"
|
||||
#include "Engine/Core/Entity/CEntity.hpp"
|
||||
#include <memory>
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
class CScript : public CAbstractScript
|
||||
{
|
||||
private:
|
||||
std::unique_ptr<CAbstractScript> m_innerScript;
|
||||
|
||||
public:
|
||||
CScript(CEntity& entity, const std::string& name, std::unique_ptr<CAbstractScript>&& innerScript);
|
||||
CScript(CEntity& entity, const std::string& name);
|
||||
CScript(CScript&& mov) = default;
|
||||
CScript& operator=(CScript&&) = default;
|
||||
void onCreate() override;
|
||||
void start() override;
|
||||
void update() override;
|
||||
void destroy() override;
|
||||
nlohmann::json to_json() override;
|
||||
virtual ~CScript() = default;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,23 @@
|
||||
#include "CScriptManager.hpp"
|
||||
#include "Engine/Core/Component/Script/CScript.hpp"
|
||||
#include "nlohmann/json_fwd.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
void CScriptManager::emplace(const std::string& name)
|
||||
{
|
||||
m_scripts.emplace_back(getEntity(), name);
|
||||
}
|
||||
|
||||
nlohmann::json CScriptManager::to_json(){
|
||||
return nlohmann::json();
|
||||
}
|
||||
void CScriptManager::updateAll()
|
||||
{
|
||||
for(auto& sc : m_scripts)
|
||||
{
|
||||
sc.update();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#ifndef CSCRIPTMANAGER_HPP
|
||||
#define CSCRIPTMANAGER_HPP
|
||||
|
||||
#include "Engine/Core/Component/CAbstractComponent.hpp"
|
||||
#include "Engine/Core/Component/Script/CScript.hpp"
|
||||
#include "Engine/Core/Entity/CEntity.hpp"
|
||||
#include <vector>
|
||||
namespace CosmicCore {
|
||||
|
||||
class CScriptManager: public CAbstractComponent
|
||||
{
|
||||
private:
|
||||
std::vector<CScript> m_scripts;
|
||||
public:
|
||||
CScriptManager(CEntity& entity) : CAbstractComponent(entity) {};
|
||||
CScriptManager(CScriptManager&& mov) = default;
|
||||
~CScriptManager() = default;
|
||||
CScriptManager& operator=(CScriptManager&&) = default;
|
||||
|
||||
void emplace(const std::string& name);
|
||||
void updateAll();
|
||||
nlohmann::json to_json();
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,121 @@
|
||||
#include "CSpeaker.hpp"
|
||||
#include "../../Systems/Resources/API/CResourceAPI.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
CSpeaker::CSpeaker(CEntity& entity): CAbstractComponent(entity)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
void CSpeaker::addClip(const std::string& name, const std::string& path, float gain, float pitch, bool loop, bool spatial) {
|
||||
auto* clip = CResourceAPI::resources().sounds().loadClip(path);
|
||||
|
||||
SoundInstance instance;
|
||||
instance.clip = clip;
|
||||
instance.gain = gain;
|
||||
instance.pitch = pitch;
|
||||
instance.spatial = spatial;
|
||||
instance.loop = loop;
|
||||
alGenSources(1, &instance.source);
|
||||
|
||||
alSourcei(instance.source, AL_SOURCE_RELATIVE, AL_FALSE);
|
||||
//TODO
|
||||
// à passer dans la config
|
||||
alSourcef(instance.source, AL_ROLLOFF_FACTOR, 1.3f);
|
||||
alSourcef(instance.source, AL_REFERENCE_DISTANCE, 0.2f); // distance à partir de laquelle le son diminue
|
||||
alSourcef(instance.source, AL_MAX_DISTANCE, 100.0f); // distance max
|
||||
|
||||
alSourcei(instance.source, AL_BUFFER, clip->buffer);
|
||||
alSourcef(instance.source, AL_GAIN, m_masterGain*instance.gain);
|
||||
alSourcei(instance.source, AL_LOOPING, instance.loop);
|
||||
alSource3f(instance.source, AL_POSITION, 0, 0, 0);
|
||||
m_clips[name] = instance;
|
||||
}
|
||||
|
||||
void CSpeaker::addClip(const std::string& name, CAudioClip* clip, float gain, float pitch, bool loop, bool spatial) {
|
||||
SoundInstance instance;
|
||||
instance.clip = clip;
|
||||
instance.gain = gain;
|
||||
instance.pitch = pitch;
|
||||
instance.spatial = spatial;
|
||||
instance.loop = loop;
|
||||
alGenSources(1, &instance.source);
|
||||
|
||||
alSourcei(instance.source, AL_SOURCE_RELATIVE, AL_FALSE);
|
||||
//TODO
|
||||
// à passer dans la config
|
||||
alSourcef(instance.source, AL_ROLLOFF_FACTOR, 1.3f);
|
||||
alSourcef(instance.source, AL_REFERENCE_DISTANCE, 0.2f); // distance à partir de laquelle le son diminue
|
||||
alSourcef(instance.source, AL_MAX_DISTANCE, 100.0f); // distance max
|
||||
|
||||
alSourcei(instance.source, AL_BUFFER, clip->buffer);
|
||||
alSourcef(instance.source, AL_GAIN, m_masterGain*instance.gain);
|
||||
alSourcei(instance.source, AL_LOOPING, instance.loop);
|
||||
alSource3f(instance.source, AL_POSITION, 0, 0, 0);
|
||||
m_clips[name] = instance;
|
||||
}
|
||||
|
||||
void CSpeaker::play(const std::string& name) {
|
||||
auto it = m_clips.find(name);
|
||||
if (it == m_clips.end()) return;
|
||||
alSourcePlay(it->second.source);
|
||||
}
|
||||
|
||||
void CSpeaker::stop(const std::string& name) {
|
||||
auto it = m_clips.find(name);
|
||||
if (it == m_clips.end()) return;
|
||||
alSourceStop(it->second.source);
|
||||
}
|
||||
|
||||
void CSpeaker::pause(const std::string& name) {
|
||||
auto it = m_clips.find(name);
|
||||
if (it == m_clips.end()) return;
|
||||
alSourcePause(it->second.source);
|
||||
}
|
||||
|
||||
void CSpeaker::stopAll() {
|
||||
for (auto& [name, instance] : m_clips)
|
||||
alSourceStop(instance.source);
|
||||
}
|
||||
|
||||
void CSpeaker::setLoop(const std::string& name, bool loop) {
|
||||
auto it = m_clips.find(name);
|
||||
if (it == m_clips.end()) return;
|
||||
it->second.loop = loop;
|
||||
alSourcei(it->second.source, AL_LOOPING, loop ? AL_TRUE : AL_FALSE);
|
||||
}
|
||||
|
||||
void CSpeaker::setGain(const std::string& name, float gain) {
|
||||
auto it = m_clips.find(name);
|
||||
if (it == m_clips.end()) return;
|
||||
it->second.gain = gain;
|
||||
alSourcef(it->second.source, AL_GAIN, gain * m_masterGain);
|
||||
}
|
||||
|
||||
void CSpeaker::updatePosition(const CTransform& transform, glm::vec3 velocity) {
|
||||
for (auto& [name, instance] : m_clips) {
|
||||
auto center = transform.getCenter();
|
||||
if (!instance.spatial) continue;
|
||||
alSource3f(instance.source, AL_POSITION,
|
||||
center.x, center.y, center.z);
|
||||
alSource3f(instance.source, AL_VELOCITY,
|
||||
velocity.x, velocity.y, velocity.z);
|
||||
}
|
||||
}
|
||||
|
||||
bool CSpeaker::isPlaying(const std::string& name) const {
|
||||
auto it = m_clips.find(name);
|
||||
if (it == m_clips.end()) return false;
|
||||
ALint state;
|
||||
alGetSourcei(it->second.source, AL_SOURCE_STATE, &state);
|
||||
return state == AL_PLAYING;
|
||||
}
|
||||
|
||||
CSpeaker::~CSpeaker() {
|
||||
for (auto& [name, instance] : m_clips)
|
||||
alDeleteSources(1, &instance.source);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
#ifndef CSPEAKER_HPP
|
||||
#define CSPEAKER_HPP
|
||||
#include <AL/al.h>
|
||||
#include <string>
|
||||
#include "../CAbstractComponent.hpp"
|
||||
#include "../Geometry/CTransform.hpp"
|
||||
#include "../../Systems/Audio/Sound/CAudioClip.hpp"
|
||||
#include "nlohmann/json_fwd.hpp"
|
||||
namespace CosmicCore {
|
||||
|
||||
struct SoundInstance {
|
||||
CAudioClip* clip = nullptr;
|
||||
ALuint source = 0;
|
||||
float gain = 1.0f;
|
||||
float pitch = 1.0f;
|
||||
bool loop = false;
|
||||
bool spatial = true;
|
||||
};
|
||||
|
||||
class CSpeaker : public CAbstractComponent {
|
||||
std::unordered_map<std::string, SoundInstance> m_clips;
|
||||
bool m_muted = false;
|
||||
float m_masterGain = 1.0f;
|
||||
|
||||
public:
|
||||
CSpeaker(CEntity& entity);
|
||||
// charge et enregistre un son
|
||||
void addClip(const std::string& name, const std::string& path, float gain = 1.0f, float pitch = 1.0f, bool loop = false, bool spatial = true);
|
||||
void addClip(const std::string& name, CAudioClip* clip, float gain = 1.0f, float pitch = 1.0f, bool loop = false, bool spatial = true);
|
||||
|
||||
void play(const std::string& name);
|
||||
|
||||
void stop(const std::string& name);
|
||||
|
||||
void pause(const std::string& name);
|
||||
|
||||
void stopAll();
|
||||
|
||||
void setLoop(const std::string& name, bool loop);
|
||||
|
||||
void setGain(const std::string& name, float gain);
|
||||
|
||||
bool isPlaying(const std::string& name) const;
|
||||
|
||||
~CSpeaker();
|
||||
|
||||
// paramètres globaux du speaker
|
||||
void setMuted(bool muted);
|
||||
void setMasterGain(float gain);
|
||||
|
||||
void updatePosition(const CTransform& transform, glm::vec3 velocity = {0,0,0});
|
||||
|
||||
nlohmann::json to_json(){return nlohmann::json();};
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,40 @@
|
||||
#include "CEntity.hpp"
|
||||
#include "nlohmann/json_fwd.hpp"
|
||||
|
||||
#include <functional>
|
||||
|
||||
namespace CosmicCore
|
||||
{
|
||||
|
||||
CEntity::CEntity(std::reference_wrapper<EntityComponentManager> registry, EntityId handle, CScene* scene) : CSerializable(), m_scene(scene), m_registryReference(registry), m_handle(handle)
|
||||
{
|
||||
}
|
||||
|
||||
CEntity::CEntity(const CEntity& cop): m_scene(cop.m_scene), m_registryReference(cop.m_registryReference), m_handle(cop.m_handle){
|
||||
|
||||
}
|
||||
|
||||
CEntity& CEntity::operator=(const CEntity& ent)
|
||||
{
|
||||
m_handle = ent.m_handle;
|
||||
m_registryReference = ent.m_registryReference;
|
||||
m_scene = ent.m_scene;
|
||||
return *this;
|
||||
}
|
||||
|
||||
CScene* CEntity::getScene()
|
||||
{
|
||||
return m_scene;
|
||||
}
|
||||
|
||||
void CEntity::setScene(CScene* s)
|
||||
{
|
||||
m_scene = s;
|
||||
}
|
||||
|
||||
/*CEntity CEntity::getParent() {
|
||||
//to implement
|
||||
}*/
|
||||
|
||||
nlohmann::json CEntity::to_json(){return nlohmann::json();};
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
#ifndef CENTITY_HPP
|
||||
#define CENTITY_HPP
|
||||
|
||||
#include <forward_list>
|
||||
#include <functional>
|
||||
#include "../../Utils/JsonParser/CSerializable.hpp"
|
||||
#include "EntityComponentManager.hpp"
|
||||
|
||||
namespace CosmicCore
|
||||
{
|
||||
class CScene;
|
||||
|
||||
class CEntity : public CSerializable {
|
||||
|
||||
private:
|
||||
|
||||
/**
|
||||
* @brief A pointer to the scene containing the entity.
|
||||
*/
|
||||
CScene* m_scene;
|
||||
|
||||
std::reference_wrapper<EntityComponentManager> m_registryReference;
|
||||
|
||||
EntityId m_handle;
|
||||
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief CEntity's default constructor, disabled.
|
||||
*/
|
||||
CEntity() = delete;
|
||||
|
||||
CEntity(std::reference_wrapper<EntityComponentManager> registry, EntityId handle, CScene* scene);
|
||||
|
||||
CEntity(const CEntity& cop);
|
||||
|
||||
CEntity& operator=(const CEntity& ent);
|
||||
/**
|
||||
* @brief CEntity's destructor.
|
||||
*/
|
||||
~CEntity(void) = default;
|
||||
|
||||
/**
|
||||
* @brief Getter to the parent entity.
|
||||
* @return a pointer to the parent entity m_parent. nullptr if there is not.
|
||||
*/
|
||||
//CEntity getParent();
|
||||
|
||||
template<typename compType, typename... Args>
|
||||
void addComponent(Args&&... args)
|
||||
{
|
||||
m_registryReference().emplace<compType>(m_handle, *this, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template<typename compType>
|
||||
void addComponent()
|
||||
{
|
||||
m_registryReference().emplace<compType>(m_handle, *this);
|
||||
}
|
||||
|
||||
EntityComponentManager& getRegistry(){return m_registryReference;};
|
||||
const EntityComponentManager& getRegistry() const {return m_registryReference;};
|
||||
|
||||
EntityId getHandle(){return m_handle;};
|
||||
|
||||
/**
|
||||
* @brief Getter to the entity's scene.
|
||||
* @return The pointer m_scene.
|
||||
*/
|
||||
CScene* getScene();
|
||||
|
||||
/**
|
||||
* @brief Setter of the scene.
|
||||
* @param[in, out] e The scene in which the entity will be set.
|
||||
*/
|
||||
void setScene(CScene* s);
|
||||
|
||||
EntityId operator*(){
|
||||
return m_handle;
|
||||
}
|
||||
|
||||
const EntityId operator*() const {
|
||||
return m_handle;
|
||||
}
|
||||
//TODO GET COMPONENT VECTOR OF SPECIFIC TYPE ? si utile
|
||||
|
||||
nlohmann::json to_json();
|
||||
};
|
||||
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,26 @@
|
||||
#ifndef ENTITYCOMPONENTMANAGER_HPP
|
||||
#define ENTITYCOMPONENTMANAGER_HPP
|
||||
|
||||
#include <entt/entt.hpp>
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
using ECManager = entt::registry;
|
||||
using EntityId = entt::entity;
|
||||
|
||||
class EntityComponentManager{
|
||||
public:
|
||||
ECManager registry;
|
||||
ECManager& operator()(){
|
||||
return registry;
|
||||
}
|
||||
|
||||
const ECManager& operator()() const {
|
||||
return registry;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,56 @@
|
||||
#include "CException.hpp"
|
||||
|
||||
void CException::makeFullMessage(void) {
|
||||
/*std::stringstream sstring;
|
||||
sstring << "Error : " << m_code << std::endl << m_message << std::endl;
|
||||
boost::stacktrace::stacktrace stacktrace = boost::stacktrace::stacktrace();
|
||||
std::size_t frames = stacktrace.size();
|
||||
|
||||
for (size_t i = 4; i < frames; i++) {
|
||||
sstring << " #" << i - 4 << " : " << stacktrace[i].name() << " : ";
|
||||
if (stacktrace[i].source_file().empty()) {
|
||||
sstring << "no source";
|
||||
}
|
||||
else {
|
||||
sstring << stacktrace[i].source_file() << " at line : " << stacktrace[i].source_line();
|
||||
}
|
||||
sstring << " (" << stacktrace[i].address() << ')' << std::endl;
|
||||
}
|
||||
|
||||
m_fullMessage = sstring.str();*/
|
||||
}
|
||||
|
||||
CException::CException(void) noexcept :
|
||||
std::exception(),
|
||||
m_message("A error occurred"),
|
||||
m_code(0),
|
||||
m_fullMessage() {
|
||||
makeFullMessage();
|
||||
}
|
||||
|
||||
CException::CException(std::string message, unsigned int code) noexcept :
|
||||
std::exception(),
|
||||
m_message(message),
|
||||
m_code(code),
|
||||
m_fullMessage() {
|
||||
makeFullMessage();
|
||||
}
|
||||
|
||||
CException::~CException(void) noexcept {
|
||||
}
|
||||
|
||||
const char* CException::what() const noexcept {
|
||||
return m_fullMessage.c_str();
|
||||
}
|
||||
|
||||
unsigned int CException::getCode() const noexcept {
|
||||
return m_code;
|
||||
}
|
||||
|
||||
std::string CException::getMessage() const noexcept {
|
||||
return m_message;
|
||||
}
|
||||
|
||||
void CException::setMessage(std::string newMessage) noexcept {
|
||||
m_message = newMessage;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
#ifndef CEXCEPTION_HPP
|
||||
#define CEXCEPTION_HPP
|
||||
|
||||
#include <exception>
|
||||
#include <string>
|
||||
|
||||
/**
|
||||
* @file CException.hpp
|
||||
* @brief File of CException, a class to handle program exception.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief Class to handle program exception.
|
||||
*/
|
||||
class CException : public std::exception {
|
||||
|
||||
private:
|
||||
// The message of the exception.
|
||||
std::string m_message;
|
||||
|
||||
// The code of the exception.
|
||||
unsigned int m_code;
|
||||
|
||||
// The full message of the exception.
|
||||
std::string m_fullMessage;
|
||||
|
||||
/**
|
||||
* @brief Create the full message.
|
||||
*/
|
||||
void makeFullMessage(void);
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief The default constructor, build a exception with default message : "An error occurred" and the code 0.
|
||||
*/
|
||||
CException(void) noexcept;
|
||||
|
||||
/**
|
||||
* @brief The usage constructor, build a exception with a given message and the given code.
|
||||
* @param[in] message The wanted message.
|
||||
* @param[in] code The wanted code.
|
||||
*/
|
||||
CException(const std::string message, const unsigned int code) noexcept;
|
||||
|
||||
/**
|
||||
* @brief The destructor.
|
||||
*/
|
||||
~CException(void) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Give some point about the current exception.
|
||||
* @return char*, Ready to print string, error description.
|
||||
*/
|
||||
virtual const char* what(void) const noexcept;
|
||||
|
||||
/**
|
||||
* @brief The error code getter.
|
||||
* @return unsigned int, The code of the error.
|
||||
*/
|
||||
unsigned int getCode(void) const noexcept;
|
||||
|
||||
/**
|
||||
* @brief The error message getter.
|
||||
* @return std::string, The message of the error.
|
||||
*/
|
||||
std::string getMessage(void) const noexcept;
|
||||
|
||||
/**
|
||||
* @brief The error message setter.
|
||||
* @param[in] newMessage The new error message.
|
||||
*/
|
||||
void setMessage(const std::string newMessage) noexcept;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,34 @@
|
||||
#include "CExceptionManager.hpp"
|
||||
|
||||
/*void HandleException(const CException& e, bool fatal) {
|
||||
|
||||
std::string windowMessage(e.getMessage());
|
||||
windowMessage += "\nException reported in \"";
|
||||
windowMessage += DEFAULT_REPORT_PATH;
|
||||
windowMessage += "\".";
|
||||
|
||||
CFileManager fm(DEFAULT_REPORT_PATH);
|
||||
|
||||
try {
|
||||
fm.write(e.what());
|
||||
}
|
||||
catch (const std::exception& nothandled) {
|
||||
(void)nothandled;
|
||||
}
|
||||
|
||||
if (!fatal) {
|
||||
// Just warning.
|
||||
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING,
|
||||
"Error !",
|
||||
windowMessage.c_str(),
|
||||
NULL);
|
||||
} else {
|
||||
// Fatal error.
|
||||
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
|
||||
"Fatal error !",
|
||||
windowMessage.c_str(),
|
||||
NULL);
|
||||
// It's fatal, so we quit.
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}*/
|
||||
@@ -0,0 +1,23 @@
|
||||
#ifndef CEXCEPTIONMANAGER_HPP
|
||||
#define CEXCEPTIONMANAGER_HPP
|
||||
|
||||
#include "CException.hpp"
|
||||
|
||||
/**
|
||||
* @file CExceptionManager.hpp
|
||||
* @brief File contain some function to handle program exception.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @def DEFAULT_PATH default path for crash-report file.
|
||||
*/
|
||||
#define DEFAULT_REPORT_PATH "../exception-report.txt"
|
||||
|
||||
/**
|
||||
* @brief Simple function to handle program exception
|
||||
* @param[in] e The Exception instance to hanlde.
|
||||
* @param[in] fatal A flag to make this Exception as fatal, so the program will quit.
|
||||
*/
|
||||
void HandleException(const CException& e, bool fatal);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,9 @@
|
||||
#include "CFileException.hpp"
|
||||
|
||||
CFileException::CFileException(void) noexcept :
|
||||
CException("A file error occurred", FILE_EXC_CODE) {
|
||||
}
|
||||
|
||||
CFileException::CFileException(std::string message) noexcept :
|
||||
CException(message, FILE_EXC_CODE){
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
#ifndef CFILEEXCEPTION_HPP
|
||||
#define CFILEEXCEPTION_HPP
|
||||
|
||||
#include "CException.hpp"
|
||||
|
||||
#include <exception>
|
||||
#include <string>
|
||||
|
||||
/**
|
||||
* @file CFileException.hpp
|
||||
* @brief File of CFileException, a class to handle program file exception.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @def FILE_EXC_CODE default code for this kind of Exception.
|
||||
*/
|
||||
#define FILE_EXC_CODE 4
|
||||
|
||||
/**
|
||||
* @brief Class to handle program file exception.
|
||||
*/
|
||||
class CFileException : public CException {
|
||||
|
||||
private:
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief The default constructor, build a exception with default message : "A file error occurred" and the code FILE_EXC_CODE.
|
||||
*/
|
||||
CFileException(void) noexcept;
|
||||
|
||||
/**
|
||||
* @brief The usage constructor, build a exception with a given message and the code FILE_EXC_CODE.
|
||||
* @param[in] message The wanted message.
|
||||
*/
|
||||
CFileException(const std::string message) noexcept;
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,9 @@
|
||||
#include "CJsonException.hpp"
|
||||
|
||||
CJsonException::CJsonException(void) noexcept :
|
||||
CException("A json error occurred", JSON_EXC_CODE) {
|
||||
}
|
||||
|
||||
CJsonException::CJsonException(std::string message) noexcept :
|
||||
CException(message, JSON_EXC_CODE){
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
#ifndef CJSONEXCEPTION_HPP
|
||||
#define CJSONEXCEPTION_HPP
|
||||
|
||||
#include "CException.hpp"
|
||||
|
||||
#include <exception>
|
||||
#include <string>
|
||||
|
||||
/**
|
||||
* @file CJsonException.hpp
|
||||
* @brief File of CJsonException, a class to handle program json parse/handle exception.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @def JSON_EXC_CODE default code for this kind of Exception.
|
||||
*/
|
||||
#define JSON_EXC_CODE 5
|
||||
|
||||
/**
|
||||
* @brief Class to handle program file exception.
|
||||
*/
|
||||
class CJsonException : public CException {
|
||||
|
||||
private:
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief The default constructor, build a exception with default message : "A json error occurred" and the code JSON_EXC_CODE.
|
||||
*/
|
||||
CJsonException(void) noexcept;
|
||||
|
||||
/**
|
||||
* @brief The usage constructor, build a exception with a given message and the code JSON_EXC_CODE.
|
||||
* @param[in] message The wanted message.
|
||||
*/
|
||||
CJsonException(const std::string message) noexcept;
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,9 @@
|
||||
#include "CLibException.hpp"
|
||||
|
||||
CLibException::CLibException(void) noexcept :
|
||||
CException("A lib error occurred", LIB_EXC_CODE) {
|
||||
}
|
||||
|
||||
CLibException::CLibException(std::string message) noexcept :
|
||||
CException(message, LIB_EXC_CODE){
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
#ifndef CLIBEXCEPTION_HPP
|
||||
#define CLIBEXCEPTION_HPP
|
||||
|
||||
#include "CException.hpp"
|
||||
|
||||
#include <exception>
|
||||
#include <string>
|
||||
|
||||
/**
|
||||
* @file CLibException.hpp
|
||||
* @brief File of CLibException, a class to handle program library runtine exception.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @def LIB_EXC_CODE default code for this kind of Exception.
|
||||
*/
|
||||
#define LIB_EXC_CODE 3
|
||||
|
||||
/**
|
||||
* @brief Class to handle program file exception.
|
||||
*/
|
||||
class CLibException : public CException {
|
||||
|
||||
private:
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief The default constructor, build a exception with default message : "A library error occurred" and the code LIB_EXC_CODE.
|
||||
*/
|
||||
CLibException(void) noexcept;
|
||||
|
||||
/**
|
||||
* @brief The usage constructor, build a exception with a given message and the code LIB_EXC_CODE.
|
||||
* @param[in] message The wanted message.
|
||||
*/
|
||||
CLibException(const std::string message) noexcept;
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,9 @@
|
||||
#include "CLogicException.hpp"
|
||||
|
||||
CLogicException::CLogicException(void) noexcept :
|
||||
CException("A logic error occurred", LOGIC_EXC_CODE) {
|
||||
}
|
||||
|
||||
CLogicException::CLogicException(std::string message) noexcept :
|
||||
CException(message, LOGIC_EXC_CODE){
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
#ifndef CLOGICEXCEPTION_HPP
|
||||
#define CLOGICEXCEPTION_HPP
|
||||
|
||||
#include "CException.hpp"
|
||||
|
||||
#include <exception>
|
||||
#include <string>
|
||||
|
||||
/**
|
||||
* @file CLogicException.hpp
|
||||
* @brief File of CLogicException, a class to handle program logic exception, it's mean error caused by bad use of function/class by user.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @def LOGIC_EXC_CODE default code for this kind of Exception.
|
||||
*/
|
||||
#define LOGIC_EXC_CODE 1
|
||||
|
||||
/**
|
||||
* @brief Class to handle program file exception.
|
||||
*/
|
||||
class CLogicException : public CException {
|
||||
|
||||
private:
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief The default constructor, build a exception with default message : "A logic error occurred" and the code LOGIC_EXC_CODE.
|
||||
*/
|
||||
CLogicException(void) noexcept;
|
||||
|
||||
/**
|
||||
* @brief The usage constructor, build a exception with a given message and the code LOGIC_EXC_CODE.
|
||||
* @param[in] message The wanted message.
|
||||
*/
|
||||
CLogicException(const std::string message) noexcept;
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,9 @@
|
||||
#include "CRuntimeException.hpp"
|
||||
|
||||
CRuntimeException::CRuntimeException(void) noexcept :
|
||||
CException("A runtime error occurred", RUNTIME_EXC_CODE) {
|
||||
}
|
||||
|
||||
CRuntimeException::CRuntimeException(std::string message) noexcept :
|
||||
CException(message, RUNTIME_EXC_CODE){
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
#ifndef CRUNTIMEEXCEPTION_HPP
|
||||
#define CRUNTIMEEXCEPTION_HPP
|
||||
|
||||
#include "CException.hpp"
|
||||
|
||||
#include <exception>
|
||||
#include <string>
|
||||
|
||||
/**
|
||||
* @file CRuntimeException.hpp
|
||||
* @brief File of CRuntimeException, a class to handle program runtime exception.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @def LOGIC_EXC_CODE default code for this kind of Exception.
|
||||
*/
|
||||
#define RUNTIME_EXC_CODE 2
|
||||
|
||||
/**
|
||||
* @brief Class to handle program file exception.
|
||||
*/
|
||||
class CRuntimeException : public CException {
|
||||
|
||||
private:
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief The default constructor, build a exception with default message : "A runtime error occurred" and the code RUNTIME_EXC_CODE.
|
||||
*/
|
||||
CRuntimeException(void) noexcept;
|
||||
|
||||
/**
|
||||
* @brief The usage constructor, build a exception with a given message and the code RUNTIME_EXC_CODE.
|
||||
* @param[in] message The wanted message.
|
||||
*/
|
||||
CRuntimeException(const std::string message) noexcept;
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,165 @@
|
||||
#include "CInput.hpp"
|
||||
/*
|
||||
#include "../CKernel.hpp"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
CInput::CInput(CKernel* kernel) :
|
||||
m_kernel(kernel),
|
||||
m_event(),
|
||||
m_mouse(),
|
||||
m_keyboard(),
|
||||
m_controllers(){
|
||||
m_keyboard.addObserver(this);
|
||||
}
|
||||
|
||||
CInput::~CInput(void) {
|
||||
for (std::map<unsigned int, CController*>::iterator it = m_controllers.begin(); it != m_controllers.end(); ++it) {
|
||||
delete it->second;
|
||||
}
|
||||
}
|
||||
|
||||
void CInput::updateEvent(void) {
|
||||
// Reset the mouse relative pos.
|
||||
m_mouse.reset();
|
||||
|
||||
// For each event in the SDL event queue.
|
||||
while(SDL_PollEvent(&m_event) == 1) {
|
||||
|
||||
// Switch on the event type.
|
||||
switch(m_event.type) {
|
||||
unsigned int id;
|
||||
CController* controller;
|
||||
|
||||
// On key button pressed.
|
||||
case SDL_KEYDOWN:
|
||||
m_keyboard.onKeyDown(m_event.key.keysym.scancode);
|
||||
break;
|
||||
|
||||
// On key button released.
|
||||
case SDL_KEYUP:
|
||||
m_keyboard.onKeyUp(m_event.key.keysym.scancode);
|
||||
break;
|
||||
|
||||
// On mouse button pressed.
|
||||
case SDL_MOUSEBUTTONDOWN:
|
||||
m_mouse.onButtonDown(m_event.button.button);
|
||||
break;
|
||||
|
||||
// On mouse button released.
|
||||
case SDL_MOUSEBUTTONUP:
|
||||
m_mouse.onButtonUp(m_event.button.button);
|
||||
break;
|
||||
|
||||
// On mouse cursor moved.
|
||||
case SDL_MOUSEMOTION:
|
||||
m_mouse.onMove(m_event.motion.x, m_event.motion.y, m_event.motion.xrel, m_event.motion.yrel);
|
||||
break;
|
||||
|
||||
// On mouse wheel moved.
|
||||
case SDL_MOUSEWHEEL:
|
||||
m_mouse.onWheel(m_event.wheel.x, m_event.wheel.y);
|
||||
break;
|
||||
|
||||
// On joystick unplugged.
|
||||
case SDL_JOYDEVICEREMOVED:
|
||||
id = m_event.jdevice.which;
|
||||
controller = m_controllers[id];
|
||||
delete controller;
|
||||
m_controllers.erase(id);
|
||||
break;
|
||||
|
||||
// On joystick plugged.
|
||||
case SDL_JOYDEVICEADDED:
|
||||
try {
|
||||
// Give a test id for opening.
|
||||
id = m_event.jdevice.which;
|
||||
CController* controller = new CController(id);
|
||||
// Get the final id.
|
||||
id = controller->getId();
|
||||
// Push the controller in the list.
|
||||
m_controllers.insert(std::pair<unsigned int, CController*>(id, controller));
|
||||
}
|
||||
catch (const CException& e) {
|
||||
HandleException(e, false);
|
||||
}
|
||||
break;
|
||||
|
||||
// On joystick axis moved.
|
||||
case SDL_JOYAXISMOTION:
|
||||
controller = m_controllers[m_event.jaxis.which];
|
||||
controller->onAxis(m_event.jaxis.axis, m_event.jaxis.value);
|
||||
break;
|
||||
|
||||
// On joystick hat moved.
|
||||
case SDL_JOYHATMOTION:
|
||||
controller = m_controllers[m_event.jhat.which];
|
||||
controller->onHat(m_event.jhat.hat, m_event.jhat.value);
|
||||
break;
|
||||
|
||||
// On joystick button pressed.
|
||||
case SDL_JOYBUTTONDOWN:
|
||||
controller = m_controllers[m_event.jaxis.which];
|
||||
controller->onButtonDown(m_event.jbutton.button);
|
||||
break;
|
||||
|
||||
// On joystick button released.
|
||||
case SDL_JOYBUTTONUP:
|
||||
controller = m_controllers[m_event.jaxis.which];
|
||||
controller->onButtonUp(m_event.jbutton.button);
|
||||
break;
|
||||
|
||||
// Case of window event.
|
||||
case SDL_WINDOWEVENT:
|
||||
|
||||
// If the window is closed.
|
||||
if (m_event.window.event == SDL_WINDOWEVENT_CLOSE) {
|
||||
m_kernel->quit();
|
||||
}
|
||||
|
||||
// If the window is focused.
|
||||
if (m_event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED) {
|
||||
m_kernel->focus();
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CKeyboard* CInput::getKeyboard(void) {
|
||||
return &m_keyboard;
|
||||
}
|
||||
|
||||
CMouse* CInput::getMouse(void) {
|
||||
return &m_mouse;
|
||||
}
|
||||
|
||||
CController* CInput::getController(unsigned int id) {
|
||||
return m_controllers[id];
|
||||
}
|
||||
|
||||
std::map<unsigned int, CController*> CInput::getControllers(void) {
|
||||
return m_controllers;
|
||||
}
|
||||
|
||||
void CInput::onKKeyDown(unsigned int which) {
|
||||
// 40 is enter.
|
||||
if (which == 40) {
|
||||
// If 226 is pressed.
|
||||
if (m_keyboard.getKey(226)) {
|
||||
m_kernel->fullscreen();
|
||||
}
|
||||
}
|
||||
|
||||
// 227 is command/windows/meta.
|
||||
if (which == 227) {
|
||||
m_kernel->desktop();
|
||||
}
|
||||
}
|
||||
|
||||
void CInput::onKKeyUp(unsigned int which) {
|
||||
(void)which;
|
||||
}*/
|
||||
@@ -0,0 +1,100 @@
|
||||
#ifndef CINPUT_HPP
|
||||
#define CINPUT_HPP
|
||||
|
||||
/*#include "../../Model/Input/CMouse.hpp"
|
||||
#include "../../Model/Input/CKeyboard.hpp"
|
||||
#include "../../Model/Input/CController.hpp"
|
||||
#include "../Exception/CException.hpp"
|
||||
#include "../../Model/Observer/CKeyObserver.hpp"
|
||||
#include "../Exception/CExceptionManager.hpp"
|
||||
#include "../CKernel.fwd.hpp"*/
|
||||
|
||||
/*#include <SDL.h>
|
||||
#include <utility>
|
||||
#include <map>*/
|
||||
|
||||
/**
|
||||
* @file CInput.hpp
|
||||
* @brief file of the CInput class, class to handle all input event.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief Class to handle all input event.
|
||||
*/
|
||||
/*class CInput : public CKeyObserver {
|
||||
private:*/
|
||||
// A pointer to the game.
|
||||
//CKernel* m_kernel;
|
||||
|
||||
// The event handler.
|
||||
//SDL_Event m_event;
|
||||
|
||||
// The mouse model.
|
||||
//CMouse m_mouse;
|
||||
|
||||
// The keyboard model.
|
||||
//CKeyboard m_keyboard;
|
||||
|
||||
// The controllers model, sorted by id.
|
||||
//std::map<unsigned int, CController*> m_controllers;
|
||||
|
||||
/*public:
|
||||
CInput(void) = delete;
|
||||
CInput(const CInput& param) = delete;
|
||||
CInput& operator=(const CInput& param) = delete;*/
|
||||
|
||||
/**
|
||||
* @brief The usage constructor.
|
||||
* @param[in] game A pointer to the game object, to handle specific event, like quit.
|
||||
*/
|
||||
//CInput(CKernel* game);
|
||||
|
||||
/**
|
||||
* @brief The destructor.
|
||||
*/
|
||||
//~CInput(void);
|
||||
|
||||
/**
|
||||
* @brief Function to handle all event of the game, SDL and CGame must be initialized. This function is call once per game frame.
|
||||
*/
|
||||
void updateEvent(void);
|
||||
|
||||
/**
|
||||
* @brief The keyboard getter.
|
||||
* @return CKeyboard*, The keyboard.
|
||||
*/
|
||||
//CKeyboard* getKeyboard(void);
|
||||
|
||||
/**
|
||||
* @brief The mouse getter.
|
||||
* @return CMouse*, The mouse.
|
||||
*/
|
||||
//CMouse* getMouse(void);
|
||||
|
||||
/**
|
||||
* @brief The controller getter.
|
||||
* @param[in] id The id of the wanted controller.
|
||||
* @return CController*, The controller.
|
||||
*/
|
||||
//CController* getController(unsigned int id);
|
||||
|
||||
/**
|
||||
* @brief The controllers getter.
|
||||
* @return std::map<unsigned int, CController*>, All the controllers, ordered by id.
|
||||
*/
|
||||
//std::map<unsigned int, CController*> getControllers(void);
|
||||
|
||||
/**
|
||||
* @brief Handle key down event.
|
||||
* @param[in] which The code of the key.
|
||||
*/
|
||||
/*virtual void onKKeyDown(unsigned int which);*/
|
||||
|
||||
/**
|
||||
* @brief Handle key down event.
|
||||
* @param[in] which The code of the key.
|
||||
*/
|
||||
//virtual void onKKeyUp(unsigned int which);
|
||||
//};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,6 @@
|
||||
|
||||
#include "CKernel.hpp"
|
||||
namespace CosmicCore {
|
||||
CKernelBase* CKernelBase::m_kernelBase = nullptr;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
#ifndef CKERNEL_HPP
|
||||
#define CKERNEL_HPP
|
||||
|
||||
#include "Engine/Core/Systems/Input/CInputDispatcher.hpp"
|
||||
#include "../../Utils/Configurations/CBasicConfiguration.hpp"
|
||||
#include <memory>
|
||||
#include <glm/glm.hpp>
|
||||
#include <glm/gtx/transform.hpp>
|
||||
#include <glm/gtc/type_ptr.hpp>
|
||||
|
||||
#include "../Systems/Graphics/Window/CGameWindow.hpp"
|
||||
|
||||
#include "../Scene/CScene.hpp"
|
||||
#include "../../Utils/Configurations/CEngineConfiguration.hpp"
|
||||
|
||||
#include <SDL3/SDL_events.h>
|
||||
#include <SDL3/SDL_init.h>
|
||||
#include <SDL3/SDL_keycode.h>
|
||||
#include <SDL3/SDL_render.h>
|
||||
#include <SDL3/SDL_timer.h>
|
||||
#include <SDL3/SDL_video.h>
|
||||
#include <dlfcn.h>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "Engine/Core/Systems/Graphics/CContext.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/API/GraphicsAPI.hpp"
|
||||
#include "Engine/Core/Systems/Physics/API/CPhysicsAPI.hpp"
|
||||
#include "Engine/Core/Scene/CScene.hpp"
|
||||
#include "Engine/Core/Entity/CEntity.hpp"
|
||||
#include "Engine/Utils/Factory/CEntityFactory.hpp"
|
||||
#include "Engine/Utils/JsonParser/Identifier.hpp"
|
||||
|
||||
#include "Engine/Core/Systems/Scripts/API/CScriptAPI.hpp"
|
||||
//CShader* CKernel::m_mainShader;
|
||||
|
||||
// #define NAME "Cosmic Engine"
|
||||
#define LOGO "assets/spaceEngineIcon.png"
|
||||
// #define SPLASH "../assets/shrekt.png"
|
||||
// #define SPLASH_HEIGHT 512
|
||||
// #define SPLASH_WIDTH 512
|
||||
// #define GAME_HEIGHT 360
|
||||
// #define GAME_WIDTH 640
|
||||
|
||||
|
||||
namespace CosmicCore {
|
||||
using namespace CosmicUtils;
|
||||
|
||||
class CKernelBase {
|
||||
private:
|
||||
static CKernelBase* m_kernelBase;
|
||||
|
||||
public:
|
||||
static CKernelBase* instance() { return m_kernelBase; }
|
||||
static void setKernelInstance(CKernelBase* ins){m_kernelBase = ins;}
|
||||
// Méthodes virtuelles que tous les kernels doivent avoir
|
||||
virtual std::string getName() = 0;
|
||||
virtual unsigned int getDeltatime() = 0;
|
||||
virtual void setDeltatime(unsigned int delta) = 0;
|
||||
virtual CScene* getActiveScene() = 0;
|
||||
virtual void quit() = 0;
|
||||
virtual void cleanup() = 0;
|
||||
virtual unsigned int getWindowHeight() = 0;
|
||||
virtual unsigned int getWindowWidth() = 0;
|
||||
|
||||
virtual ~CKernelBase() = default;
|
||||
virtual void loadScene(std::string name) = 0;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @file CKernel.hpp
|
||||
* @brief Central class of the game, handle window and I/O.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief Central class of the game, handle window and I/O.
|
||||
*/
|
||||
template<typename TGameConfig = CBasicConfiguration>
|
||||
class CKernel : public CKernelBase{
|
||||
private:
|
||||
std::string m_configPath;
|
||||
std::string m_gameName;
|
||||
// The config.
|
||||
CEngineConfiguration m_engineConfig;
|
||||
TGameConfig m_gameConfig;
|
||||
|
||||
// The windows.
|
||||
//CLoadingWindow m_loadingWindow;
|
||||
CGameWindow m_window;
|
||||
CInputDispatcher m_inputWorld;
|
||||
|
||||
// Global game var.
|
||||
bool m_finished;
|
||||
unsigned int m_deltaTime;
|
||||
|
||||
// The Scenes.
|
||||
CScene* m_activeScene;
|
||||
std::map<std::string, std::unique_ptr<CScene>> m_sceneMap;
|
||||
|
||||
public:
|
||||
|
||||
CKernel() = delete;
|
||||
|
||||
std::string getName() override { return m_gameName; };
|
||||
unsigned int getWindowHeight() override {return m_window.getHeight();};
|
||||
unsigned int getWindowWidth() override {return m_window.getWidth();};
|
||||
|
||||
void cleanup() override {m_sceneMap.clear();};
|
||||
|
||||
unsigned int getDeltatime(void) override {
|
||||
return m_deltaTime;
|
||||
}
|
||||
|
||||
void setDeltatime(unsigned int delta) override{
|
||||
m_deltaTime = delta;
|
||||
}
|
||||
|
||||
CKernel(std::string name, std::string gameName) :
|
||||
m_gameName(gameName), m_window(gameName, LOGO, 1270, 720, true, false)
|
||||
{
|
||||
setKernelInstance(this);
|
||||
}
|
||||
|
||||
~CKernel()
|
||||
{
|
||||
}
|
||||
|
||||
CScene* getActiveScene() override
|
||||
{
|
||||
return m_activeScene;
|
||||
}
|
||||
|
||||
void loadScene(std::string name)
|
||||
{
|
||||
const char* pathBaseExe = SDL_GetBasePath();
|
||||
std::filesystem::path pathToScene = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / name;
|
||||
|
||||
if(!m_sceneMap.contains(name))
|
||||
{
|
||||
m_sceneMap[name] = CScene::load(pathToScene.string());
|
||||
}
|
||||
|
||||
m_activeScene = m_sceneMap[name].get();
|
||||
}
|
||||
|
||||
void start(bool isPreview = false) {
|
||||
loadConfigurations();
|
||||
CContext::init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC);
|
||||
CScriptAPI::init();
|
||||
//CScriptRegister::registerAllScripts();
|
||||
CPhysicsAPI::init();
|
||||
const char* pathBaseExe = SDL_GetBasePath();
|
||||
std::filesystem::path pathToSchema = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / "schema_json.json";
|
||||
CosmicUtils::JsonValidator::init(pathToSchema);
|
||||
if(!isPreview)
|
||||
{
|
||||
m_window.initialization();
|
||||
std::filesystem::path pathToScene = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / "assets/scenes/scene_menu.json";
|
||||
auto scene = CScene::load(pathToScene.string());
|
||||
m_activeScene = scene.get();
|
||||
m_sceneMap[scene->getName()] = std::move(scene);
|
||||
}
|
||||
}
|
||||
|
||||
void loadConfigurations()
|
||||
{
|
||||
const char* pathBaseExe = SDL_GetBasePath();
|
||||
std::filesystem::path pathToEngineConf = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / "assets/configs/engine/engine.json";
|
||||
std::filesystem::path pathToGameConf = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / "assets/configs/game/game.json";
|
||||
|
||||
if(m_engineConfig.load(pathToEngineConf.string()))
|
||||
{
|
||||
// Configuration fenêtre
|
||||
// TODO: appliquer les settings de fenêtre via CGameWindow ou GraphicsAPI
|
||||
m_window.setSize(m_engineConfig.window.width, m_engineConfig.window.height);
|
||||
m_window.setTitle(m_engineConfig.window.title);
|
||||
if(m_engineConfig.window.fullscreen) m_window.setFullscreen(true);
|
||||
|
||||
// Configuration input
|
||||
std::filesystem::path pathToActions = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / m_engineConfig.input.actionsPath;
|
||||
std::filesystem::path pathToBindings = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / m_engineConfig.input.bindingsPath;
|
||||
|
||||
m_inputWorld.loadActions(pathToActions.string());
|
||||
m_inputWorld.loadBindings(pathToBindings.string());
|
||||
|
||||
m_inputWorld.getMapping().setMouseSensitivity(m_engineConfig.input.mouseSensitivity);
|
||||
}
|
||||
if(m_gameConfig.load(pathToGameConf.string()))
|
||||
{
|
||||
m_window.setSize(m_gameConfig.window.width, m_gameConfig.window.height);
|
||||
m_window.setTitle(m_gameConfig.window.title);
|
||||
if(m_gameConfig.window.fullscreen) m_window.setFullscreen(true);
|
||||
|
||||
std::filesystem::path pathToActions = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / m_engineConfig.input.actionsPath;
|
||||
std::filesystem::path pathToBindings = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / m_engineConfig.input.bindingsPath;
|
||||
|
||||
|
||||
m_inputWorld.loadActions(pathToActions.string());
|
||||
m_inputWorld.loadBindings(pathToBindings.string());
|
||||
m_inputWorld.getMapping().setMouseSensitivity(m_gameConfig.input.mouseSensitivity);
|
||||
}
|
||||
// Configuration graphique
|
||||
// TODO: GraphicsAPI::getAPI()->setValidationLayers(m_gameConfig.graphics.validationLayers);
|
||||
// TODO: GraphicsAPI::getAPI()->setMaxFramesInFlight(m_gameConfig.graphics.maxFramesInFlight);
|
||||
|
||||
// Configuration audio
|
||||
// TODO: C AudioAPI::setMasterGain(m_gameConfig.audio.masterGain);
|
||||
// TODO: C AudioAPI::setMusicGain(m_gameConfig.audio.musicGain);
|
||||
|
||||
}
|
||||
|
||||
void loop() {
|
||||
|
||||
unsigned int frameRate(1000 / 144);
|
||||
unsigned int beginIterationTime(0);
|
||||
unsigned int endIterationTime(0);
|
||||
unsigned int spendedIterationTime(0);
|
||||
unsigned int lastFrame = 0;
|
||||
m_window.setVisible(true);
|
||||
m_window.setResizable(true);
|
||||
while (!m_finished) {
|
||||
// Define the starting time.
|
||||
beginIterationTime = SDL_GetTicks();
|
||||
|
||||
// Compute the delta time.
|
||||
unsigned int currentFrame = beginIterationTime;
|
||||
m_deltaTime = currentFrame - lastFrame;
|
||||
lastFrame = currentFrame;
|
||||
|
||||
// Update event system.
|
||||
//m_inputHandler.updateEvent();
|
||||
// ####### start render #######
|
||||
|
||||
SDL_Event event;
|
||||
while (SDL_PollEvent(&event))
|
||||
{
|
||||
if (event.type == SDL_EVENT_QUIT)
|
||||
m_finished = true;
|
||||
if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(m_window.getWindow()))
|
||||
m_finished = true;
|
||||
|
||||
m_inputWorld.processEvent(event);
|
||||
}
|
||||
|
||||
if(m_activeScene)
|
||||
{
|
||||
m_inputWorld.dispatch(m_activeScene);
|
||||
m_activeScene->getScriptWorld().updateWorld(1.0f/60.0f);
|
||||
m_activeScene->getTangibleWorld().updateWorld(1.0f/60.0f);
|
||||
m_activeScene->getAudioWorld().updateWorld(1.0f/60.0f);
|
||||
|
||||
//TODO scne update -> physics + audio + scripts ?
|
||||
GraphicsAPI::getAPI()->drawFrame();
|
||||
}
|
||||
|
||||
// ####### end render #######
|
||||
|
||||
// Compute the end and spended time .
|
||||
endIterationTime = SDL_GetTicks();
|
||||
|
||||
spendedIterationTime = endIterationTime - beginIterationTime;
|
||||
// If need, we pause the programm to have the right fps amount.
|
||||
if (spendedIterationTime < frameRate) {
|
||||
SDL_Delay(frameRate - spendedIterationTime);
|
||||
}
|
||||
}
|
||||
GraphicsAPI::getAPI()->cleanup();
|
||||
CPhysicsAPI::cleanup();
|
||||
CContext::quit();
|
||||
}
|
||||
|
||||
void quit() override {
|
||||
m_finished = true;
|
||||
}
|
||||
|
||||
|
||||
void fullscreen() {
|
||||
}
|
||||
|
||||
void desktop() {
|
||||
}
|
||||
|
||||
void focus() {
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
//template<typename TGameConfig> CKernel<TGameConfig>* CKernel<TGameConfig>::m_kernel;
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,39 @@
|
||||
#ifndef CCONTROLLEROBSERVER_HPP
|
||||
#define CCONTROLLEROBSERVER_HPP
|
||||
|
||||
/**
|
||||
* @file CControllerObserver.hpp
|
||||
* @brief file of the CControllerObserver class, abstract class to extend, alloy the daugther class to handle controller event.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief Abstract class to extend, alloy the daugther class to handle controller event.
|
||||
*/
|
||||
class CControllerObserver {
|
||||
private:
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief Handle button down event.
|
||||
* @param[in] controllerId The controller id.
|
||||
* @param[in] which The code of the button.
|
||||
*/
|
||||
virtual void onCButtonDown(unsigned int controllerId, unsigned int which) = 0;
|
||||
|
||||
/**
|
||||
* @brief Handle button up event.
|
||||
* @param[in] controllerId The controller id.
|
||||
* @param[in] which The code of the button.
|
||||
*/
|
||||
virtual void onCButtonUp(unsigned int controllerId, unsigned int which) = 0;
|
||||
|
||||
/**
|
||||
* @brief Handle axis event.
|
||||
* @param[in] controllerId The controller id.
|
||||
* @param[in] which The id of the axis.
|
||||
* @param[in] value the new Value of the axis.
|
||||
*/
|
||||
virtual void onCAxis(unsigned int controllerId, unsigned int which, int value) = 0;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,29 @@
|
||||
#ifndef CKEYOBSERVER_HPP
|
||||
#define CKEYOBSERVER_HPP
|
||||
|
||||
/**
|
||||
* @file CKeyObserver.hpp
|
||||
* @brief file of the CKeyObserver class, abstract class to extend, alloy the daugther class to handle key event.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief Abstract class to extend, alloy the daugther class to handle key event.
|
||||
*/
|
||||
class CKeyObserver {
|
||||
private:
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief Handle key down event.
|
||||
* @param[in] which The code of the key.
|
||||
*/
|
||||
virtual void onKKeyDown(unsigned int which) = 0;
|
||||
|
||||
/**
|
||||
* @brief Handle key down event.
|
||||
* @param[in] which The code of the key.
|
||||
*/
|
||||
virtual void onKKeyUp(unsigned int which) = 0;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,45 @@
|
||||
#ifndef CMOUSEOBSERVER_HPP
|
||||
#define CMOUSEOBSERVER_HPP
|
||||
|
||||
/**
|
||||
* @file CMouseObserver.hpp
|
||||
* @brief file of the CMouseObserver class, abstract class to extend, alloy the daugther class to handle mouse event.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief Abstract class to extend, alloy the daugther class to handle mouse event.
|
||||
*/
|
||||
class CMouseObserver {
|
||||
private:
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief Handle key down event.
|
||||
* @param[in] which The code of the button.
|
||||
*/
|
||||
virtual void onMButtonDown(unsigned int which) = 0;
|
||||
|
||||
/**
|
||||
* @brief Handle key up event.
|
||||
* @param[in] which The code of the button.
|
||||
*/
|
||||
virtual void onMButtonUp(unsigned int which) = 0;
|
||||
|
||||
/**
|
||||
* @brief Handle wheel event.
|
||||
* @param[in] x The relative x value.
|
||||
* @param[in] y The relative y value.
|
||||
*/
|
||||
virtual void onMWheel(int x, int y) = 0;
|
||||
|
||||
/**
|
||||
* @brief Handle move event.
|
||||
* @param[in] x The new x value.
|
||||
* @param[in] y The new y value.
|
||||
* @param[in] xRel The relative x value.
|
||||
* @param[in] yRel The relative y value.
|
||||
*/
|
||||
virtual void onMMove(int x, int y, int xRel, int yRel) = 0;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,30 @@
|
||||
#ifndef CTRANSFORMOBSERVER_HPP
|
||||
#define CTRANSFORMOBSERVER_HPP
|
||||
|
||||
/**
|
||||
* @file CTransformObserver.hpp
|
||||
* @brief file of the CTransformObserver class, abstract class to extend, alloy the daugther class to handle transform change event.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief Abstract class to extend, alloy the daugther class to handle transform change event.
|
||||
*/
|
||||
class CTransformObserver {
|
||||
public:
|
||||
/**
|
||||
* @brief Handle center change event.
|
||||
*/
|
||||
virtual void onCenterChange(void) = 0;
|
||||
|
||||
/**
|
||||
* @brief Handle scale change event.
|
||||
*/
|
||||
virtual void onScaleChange(void) = 0;
|
||||
|
||||
/**
|
||||
* @brief Handle rotation change event.
|
||||
*/
|
||||
virtual void onRotationChange(void) = 0;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,488 @@
|
||||
#include "CScene.hpp"
|
||||
#include "Engine/Core/Entity/CEntity.hpp"
|
||||
#include "Engine/Core/Component/Graphics/CRenderer.hpp"
|
||||
#include "Engine/Core/Component/Meta/CMetaData.hpp"
|
||||
#include "Engine/Core/Component/Geometry/CTransform.hpp"
|
||||
#include "Engine/Core/Component/Camera/CCamera.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/API/GraphicsAPI.hpp"
|
||||
#include "Engine/Utils/JsonParser/Identifier.hpp"
|
||||
#include "Engine/Utils/Factory/CEntityFactory.hpp"
|
||||
#include "Engine/Utils/Factory/ComponentFactory.hpp"
|
||||
|
||||
#include "Engine/Core/Component/Camera/CCamera2D.hpp"
|
||||
#include "Engine/Core/Component/Geometry/CTransform2D.hpp"
|
||||
#include "Engine/Core/Component/Graphics/CRenderer2D.hpp"
|
||||
#include "Engine/Core/Component/Light/CLight.hpp"
|
||||
#include "Engine/Core/Entity/EntityComponentManager.hpp"
|
||||
#include "glm/ext/vector_float3.hpp"
|
||||
#include "glm/gtc/type_ptr.hpp"
|
||||
#include "nlohmann/json_fwd.hpp"
|
||||
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
#include "../Systems/Graphics/Data/Light/CLightsBuffer.hpp"
|
||||
namespace CosmicCore {
|
||||
|
||||
CScene::CScene(std::string name) : CSerializable(),
|
||||
m_name(std::move(name)),
|
||||
m_tangibleWorld(this),
|
||||
m_audioWorld(this),
|
||||
m_scriptWorld(this)
|
||||
{
|
||||
m_tangibleWorld.initWorld();
|
||||
m_audioWorld.initWorld();
|
||||
m_scriptWorld.initWorld();
|
||||
m_lightsBuffer.init();
|
||||
//m_uiWorld.init();
|
||||
|
||||
m_ecManager.registry.sort<CTransform2D>([](const CTransform2D& lhs, const CTransform2D& rhs) {
|
||||
return lhs.getZOrder() > rhs.getZOrder();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
std::string CScene::getName(void) const {
|
||||
return m_name;
|
||||
}
|
||||
|
||||
CScene::~CScene()
|
||||
{
|
||||
m_tangibleWorld.destroy();
|
||||
m_audioWorld.destroy();
|
||||
m_scriptWorld.destroy();
|
||||
m_lightsBuffer.destroy();
|
||||
//m_uiWorld.destroy();
|
||||
}
|
||||
|
||||
CEntity CScene::createEntity(){
|
||||
auto handle = m_ecManager.registry.create();
|
||||
CEntity handler(m_ecManager, handle, this);
|
||||
return handler;
|
||||
}
|
||||
|
||||
unsigned int CScene::getNumEntity(void) const {
|
||||
return m_ecManager().view<CMetaData>()->size();
|
||||
}
|
||||
|
||||
void CScene::removeEntity(unsigned int index, bool destroy)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void CScene::collectLights(vk::raii::CommandBuffer& cmd, uint32_t frameIndex) {
|
||||
auto& registry = m_ecManager.registry;
|
||||
auto view = registry.view<CLight, CTransform>();
|
||||
|
||||
SLightsUBOData lightsData{};
|
||||
|
||||
for (auto entity : view) {
|
||||
if (lightsData.lightCount >= MAX_LIGHTS) break;
|
||||
|
||||
auto& light = registry.get<CLight>(entity);
|
||||
auto& transform = registry.get<CTransform>(entity);
|
||||
|
||||
SLightData data{};
|
||||
glm::vec3 pos = transform.getCenter();
|
||||
glm::vec3 dir = transform.getOrientation() * glm::vec3(0, -1, 0);
|
||||
|
||||
data.position = {pos.x, pos.y, pos.z, (float)light.getType()};
|
||||
data.direction = {dir.x, dir.y, dir.z, light.getRange()};
|
||||
data.color = {light.getColor().x, light.getColor().y,
|
||||
light.getColor().z, light.getIntensity()};
|
||||
data.innerCosAngle = glm::cos(glm::radians(light.getInnerAngle()));
|
||||
data.outerCosAngle = glm::cos(glm::radians(light.getOuterAngle()));
|
||||
data.attenuation = light.getAttenuation();
|
||||
|
||||
lightsData.lights[lightsData.lightCount++] = data;
|
||||
}
|
||||
|
||||
// upload dans le SSBO
|
||||
m_lightsBuffer.update(frameIndex, lightsData);
|
||||
}
|
||||
|
||||
void CScene::render3D(vk::raii::CommandBuffer& cmd, uint32_t frameIndex){
|
||||
auto entities = m_ecManager.registry.view<CRenderer, CTransform>();
|
||||
|
||||
if(entities.begin() != entities.end())
|
||||
{
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
auto cam = m_ecManager.registry.view<CCamera, CTransform>();
|
||||
auto& camera = m_ecManager.registry.get<CCamera>(cam.front());
|
||||
auto& transform = m_ecManager.registry.get<CTransform>(cam.front());
|
||||
|
||||
collectLights(cmd, frameIndex);
|
||||
|
||||
camera.updateUniformBuffer(frameIndex, transform);
|
||||
|
||||
cmd.bindDescriptorSets(
|
||||
vk::PipelineBindPoint::eGraphics,
|
||||
api->getDefaultPipelineLayout(), // layout du pipeline
|
||||
0,
|
||||
*camera.getDescriptorSet(frameIndex),
|
||||
{}
|
||||
);
|
||||
|
||||
//bind lumières (set 3)
|
||||
cmd.bindDescriptorSets(vk::PipelineBindPoint::eGraphics,
|
||||
api->getDefaultPipelineLayout(), 3,
|
||||
*m_lightsBuffer.getDescriptorSet(frameIndex), {});
|
||||
|
||||
|
||||
for (auto& entity : entities) {
|
||||
auto model = m_ecManager.registry.get<CRenderer>(entity).getModel();
|
||||
auto& transform = m_ecManager.registry.get<CTransform>(entity);
|
||||
|
||||
transform.updateUniformBuffer(frameIndex);
|
||||
//trier meshes par matérial ?
|
||||
|
||||
// bind transform UBO (set = 1)
|
||||
cmd.bindDescriptorSets(
|
||||
vk::PipelineBindPoint::eGraphics,
|
||||
api->getDefaultPipelineLayout(), // layout du pipeline
|
||||
1, // set = 1
|
||||
*transform.getDescriptorSet(frameIndex),
|
||||
{}
|
||||
);
|
||||
|
||||
for (auto& mm : model->getMeshMaterials()) {
|
||||
// ne rebind le pipeline que si le material change
|
||||
//if (mesh.getMaterial() != boundMaterial) {
|
||||
//boundMaterial = mesh.getMaterial();
|
||||
cmd.bindPipeline(vk::PipelineBindPoint::eGraphics,
|
||||
*mm.material->getPipeline());
|
||||
cmd.bindDescriptorSets(vk::PipelineBindPoint::eGraphics,
|
||||
*mm.material->getPipelineLayout(),
|
||||
2,
|
||||
*mm.material->getDescriptorSet(frameIndex),
|
||||
{});
|
||||
//}
|
||||
|
||||
cmd.bindVertexBuffers(0, vk::Buffer(mm.mesh->getVertexIndexBuffer().buffer), mm.mesh->getVertexOffset());
|
||||
cmd.bindIndexBuffer(vk::Buffer(mm.mesh->getVertexIndexBuffer().buffer), mm.mesh->getIndexOffset(), vk::IndexType::eUint32);
|
||||
cmd.drawIndexed(mm.mesh->getIndexCount(), 1, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CScene::render2D(vk::raii::CommandBuffer& cmd, uint32_t frameIndex){
|
||||
|
||||
auto entities = m_ecManager.registry.view<CTransform2D, CRenderer2D>();
|
||||
|
||||
if(entities.begin() != entities.end())
|
||||
{
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
auto cam = m_ecManager.registry.view<CCamera2D>();
|
||||
auto& camera = m_ecManager.registry.get<CCamera2D>(cam.front());
|
||||
auto& trCam = m_ecManager.registry.get<CTransform2D>(cam.front());
|
||||
camera.updateUniformBuffer(frameIndex, trCam);
|
||||
//
|
||||
cmd.bindDescriptorSets(
|
||||
vk::PipelineBindPoint::eGraphics,
|
||||
api->getDefault2DPipelineLayout(), // layout du pipeline
|
||||
2,
|
||||
*camera.getDescriptorSet(frameIndex),
|
||||
{}
|
||||
);
|
||||
|
||||
struct ENT_DRAW { entt::entity e; float z; };
|
||||
std::vector<ENT_DRAW> entitiesSortedToDraw;
|
||||
entitiesSortedToDraw.reserve(entities.size_hint());
|
||||
|
||||
for (auto e : entities)
|
||||
entitiesSortedToDraw.push_back({ e, m_ecManager.registry.get<CTransform2D>(e).getZOrder() });
|
||||
|
||||
std::ranges::sort(entitiesSortedToDraw, [](const ENT_DRAW& a, const ENT_DRAW& b) { return a.z < b.z; });
|
||||
|
||||
for (auto& entity : entitiesSortedToDraw) {
|
||||
auto model = m_ecManager.registry.get<CRenderer2D>(entity.e).getModel();
|
||||
auto& transform = m_ecManager.registry.get<CTransform2D>(entity.e);
|
||||
|
||||
transform.updateUniformBuffer(frameIndex);
|
||||
|
||||
// bind transform UBO (set = 1)
|
||||
cmd.bindDescriptorSets(
|
||||
vk::PipelineBindPoint::eGraphics,
|
||||
api->getDefault2DPipelineLayout(), // layout du pipeline
|
||||
0, // set = 1
|
||||
*transform.getDescriptorSet(frameIndex),
|
||||
{}
|
||||
);
|
||||
|
||||
for (auto& mm : model->getMeshMaterials()) {
|
||||
// ne rebind le pipeline que si le material change
|
||||
//if (mesh.getMaterial() != boundMaterial) {
|
||||
//boundMaterial = mesh.getMaterial();
|
||||
cmd.bindPipeline(vk::PipelineBindPoint::eGraphics,
|
||||
*mm.material->getPipeline());
|
||||
cmd.bindDescriptorSets(vk::PipelineBindPoint::eGraphics,
|
||||
*mm.material->getPipelineLayout(),
|
||||
1,
|
||||
*mm.material->getDescriptorSet(frameIndex),
|
||||
{});
|
||||
//}
|
||||
|
||||
cmd.bindVertexBuffers(0, vk::Buffer(mm.mesh->getVertexIndexBuffer().buffer), mm.mesh->getVertexOffset());
|
||||
cmd.bindIndexBuffer(vk::Buffer(mm.mesh->getVertexIndexBuffer().buffer), mm.mesh->getIndexOffset(), vk::IndexType::eUint32);
|
||||
cmd.drawIndexed(mm.mesh->getIndexCount(), 1, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CScene::render(vk::raii::CommandBuffer& cmd, uint32_t frameIndex){
|
||||
render3D(cmd, frameIndex);
|
||||
render2D(cmd, frameIndex);
|
||||
}
|
||||
|
||||
nlohmann::json CScene::to_json()
|
||||
{
|
||||
return nlohmann::json();
|
||||
}
|
||||
|
||||
std::unique_ptr<CScene> CScene::load(const std::string &path)
|
||||
{
|
||||
const char* pathBaseExe = SDL_GetBasePath();
|
||||
std::string prefix = (pathBaseExe ? std::string(pathBaseExe) : ".") + '/';
|
||||
|
||||
|
||||
|
||||
std::ifstream file(path);
|
||||
nlohmann::json sceneJson = nlohmann::json::parse(file);
|
||||
if(CosmicUtils::JsonValidator::validate(sceneJson))
|
||||
{
|
||||
std::string sceneName = sceneJson[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Scene_Name)];
|
||||
|
||||
std::unordered_map<unsigned int, CEntity> idToHandle;
|
||||
std::unordered_map<unsigned int, unsigned int> idToParent;
|
||||
std::unordered_map<unsigned int, std::vector<unsigned int>> idToChildren;
|
||||
|
||||
//TODO add descritpion to members
|
||||
std::string sceneDescription = sceneJson[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Scene_Description)];
|
||||
auto scene = std::make_unique<CScene>(sceneName);
|
||||
nlohmann::json& entities = sceneJson[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Scene_Entities)];
|
||||
for(auto& entity : entities.items())
|
||||
{
|
||||
nlohmann::json& entityObj = entity.value();
|
||||
auto ref = entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Ref)].get<unsigned int>();
|
||||
std::optional<unsigned int> parent = !entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Parent)].is_null() ? std::optional<unsigned int>(entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Parent)].get<unsigned int>()) : std::nullopt;
|
||||
auto children = entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Children)].get<std::vector<unsigned int>>();
|
||||
|
||||
nlohmann::json& components = entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Components)];
|
||||
nlohmann::json& transform = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Transform)];
|
||||
nlohmann::json& camera = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Camera)];
|
||||
nlohmann::json& collider = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Collider)];
|
||||
nlohmann::json& rigidbody = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Rigidbody)];
|
||||
nlohmann::json& renderer = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Renderer)];
|
||||
nlohmann::json& speaker = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Speaker)];
|
||||
nlohmann::json& script = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Script)];
|
||||
nlohmann::json& light = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Light)];
|
||||
|
||||
auto trConfig(!transform.is_null() ? std::optional<CosmicUtils::ComponentFactory::TransformConfig>({
|
||||
glm::make_vec3(transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Position)].get<std::vector<float>>().data()),
|
||||
glm::make_vec3(transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Rotation)].get<std::vector<float>>().data()),
|
||||
glm::make_vec3(transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Scale)].get<std::vector<float>>().data())
|
||||
}) : std::nullopt);
|
||||
|
||||
auto camConfig(!camera.is_null() ? std::optional<CosmicUtils::ComponentFactory::CameraConfig>({
|
||||
camera[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Camera_Fov)].get<float>(),
|
||||
camera[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Camera_Near)].get<float>(),
|
||||
camera[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Camera_Far)].get<float>()
|
||||
}) : std::nullopt);
|
||||
|
||||
auto colliderConfig(!collider.is_null() ? std::optional<CosmicUtils::ComponentFactory::ColliderConfig>({
|
||||
static_cast<EColliderType>(collider[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Collider_Type)].get<int>()),
|
||||
glm::vec3(),
|
||||
0,
|
||||
0,
|
||||
}) : std::nullopt);
|
||||
|
||||
auto rigidbodyConfig(!rigidbody.is_null() ? std::optional<CosmicUtils::ComponentFactory::RigidBodyConfig>({
|
||||
static_cast<EBodyType>(rigidbody[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::RigidBody_Type)].get<int>()),
|
||||
rigidbody[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::RigidBody_Mass)].get<float>(),
|
||||
rigidbody[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::RigidBody_Friction)].get<float>(),
|
||||
rigidbody[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::RigidBody_Restitution)].get<float>()
|
||||
}) : std::nullopt);
|
||||
|
||||
auto rendererConfig(!renderer.is_null() ? std::optional<CosmicUtils::ComponentFactory::RendererConfig>({
|
||||
prefix + renderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Renderer_Model)].get<std::string>(),
|
||||
renderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Renderer_Shader)].get<std::string>(),
|
||||
!renderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Renderer_Albedo)].is_null() ? std::optional<std::string>(prefix + renderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Renderer_Albedo)].get<std::string>()) : std::nullopt,
|
||||
}) : std::nullopt);
|
||||
|
||||
auto scriptConfig(!script.is_null() ? std::optional<CosmicUtils::ComponentFactory::ScriptConfig>({
|
||||
script.get<std::vector<std::string>>()
|
||||
}): std::nullopt);
|
||||
|
||||
std::optional<CosmicUtils::ComponentFactory::SpeakerConfig> speakerConfig = std::nullopt;
|
||||
if(!speaker.is_null())
|
||||
{
|
||||
if(!speaker[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Speaker_Clips)].empty())
|
||||
{
|
||||
speakerConfig = std::optional<CosmicUtils::ComponentFactory::SpeakerConfig>(CosmicUtils::ComponentFactory::SpeakerConfig());
|
||||
for(auto clipConf : speaker[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Speaker_Clips)])
|
||||
{
|
||||
CosmicUtils::ComponentFactory::SpeakerConfig::SoundClipConfig conf
|
||||
{
|
||||
prefix + clipConf[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Speaker_Path)].get<std::string>(),
|
||||
clipConf[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Speaker_Gain)].get<float>(),
|
||||
clipConf[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Speaker_Pitch)].get<float>(),
|
||||
clipConf[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Speaker_Loop)].get<bool>(),
|
||||
clipConf[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Speaker_Spatial)].get<bool>()
|
||||
};
|
||||
speakerConfig->clips.push_back(conf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto lightConfig(!light.is_null() ? std::optional<CosmicUtils::ComponentFactory::LightConfig>(
|
||||
{
|
||||
static_cast<ELightType>(light[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Light_Type)].get<unsigned int>()),
|
||||
glm::make_vec3(light[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Light_Color)].get<std::vector<float>>().data()),
|
||||
light[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Light_Intensity)].get<float>(),
|
||||
light[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Light_Range)].get<float>(),
|
||||
light[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Light_Attenuation)].get<float>(),
|
||||
light[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Light_InnerAngle)].get<float>(),
|
||||
light[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Light_OuterAngle)].get<float>(),
|
||||
light[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Light_CastShadow)].get<bool>()
|
||||
}) : std::nullopt);
|
||||
|
||||
CosmicUtils::CEntityFactory::EntityConfig config = {
|
||||
entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Name)],
|
||||
entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Description)],
|
||||
trConfig,
|
||||
camConfig,
|
||||
rendererConfig,
|
||||
colliderConfig,
|
||||
rigidbodyConfig,
|
||||
speakerConfig,
|
||||
scriptConfig,
|
||||
lightConfig
|
||||
};
|
||||
|
||||
auto entityHandle = CosmicUtils::CEntityFactory::create(scene.get(), config);
|
||||
idToHandle.emplace(std::make_pair(ref, entityHandle));
|
||||
if(parent.has_value())
|
||||
idToParent[ref] = parent.value();
|
||||
|
||||
for(auto i : children)
|
||||
{
|
||||
idToChildren[ref].push_back(i);
|
||||
}
|
||||
}
|
||||
|
||||
nlohmann::json& entities2D = sceneJson[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Scene_Entities2D)];
|
||||
for(auto& entity : entities2D.items())
|
||||
{
|
||||
nlohmann::json& entityObj = entity.value();
|
||||
auto ref = entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity2D_Ref)].get<unsigned int>();
|
||||
|
||||
std::optional<unsigned int> parent = !entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Parent)].is_null() ? std::optional<unsigned int>(entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Parent)].get<unsigned int>()) : std::nullopt;
|
||||
auto children = entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Children)].get<std::vector<unsigned int>>();
|
||||
|
||||
nlohmann::json& components = entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity2D_Components)];
|
||||
nlohmann::json& transform = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Transform2D)];
|
||||
nlohmann::json& camera = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Camera2D)];
|
||||
nlohmann::json& collider = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Collider2D)];
|
||||
nlohmann::json& renderer = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Renderer2D)];
|
||||
nlohmann::json& script = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Script)];
|
||||
nlohmann::json& textRenderer = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_TextRenderer2D)];
|
||||
|
||||
auto trConfig(!transform.is_null() ? std::optional<CosmicUtils::ComponentFactory::Transform2DConfig>({
|
||||
glm::make_vec2(transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Position2D)].get<std::vector<float>>().data()),
|
||||
glm::make_vec2(transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Size2D)].get<std::vector<float>>().data()),
|
||||
glm::make_vec2(transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Scale2D)].get<std::vector<float>>().data()),
|
||||
glm::make_vec2(transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Pivot2D)].get<std::vector<float>>().data()),
|
||||
glm::make_vec2(transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Anchor2D)].get<std::vector<float>>().data()),
|
||||
transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Rotation2D)].get<float>(),
|
||||
transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_zOrder2D)].get<float>(),
|
||||
transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Visible2D)].get<bool>()
|
||||
}) : std::nullopt);
|
||||
|
||||
auto camConfig(!camera.is_null() ? std::optional<CosmicUtils::ComponentFactory::Camera2DConfig>({
|
||||
camera[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Camera_Zoom2D)].get<float>()
|
||||
}) : std::nullopt);
|
||||
|
||||
auto colliderConfig(!collider.is_null() ? std::optional<CosmicUtils::ComponentFactory::Collider2DConfig>({
|
||||
static_cast<E2DShape>(collider[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Collider_Shape2D)].get<int>())
|
||||
}) : std::nullopt);
|
||||
|
||||
auto rendererConfig(!renderer.is_null() ? std::optional<CosmicUtils::ComponentFactory::Renderer2DConfig>({
|
||||
prefix + renderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Renderer_Model2D)].get<std::string>(),
|
||||
renderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Renderer_Shader2D)].get<std::string>(),
|
||||
}) : std::nullopt);
|
||||
|
||||
auto scriptConfig(!script.is_null() ? std::optional<CosmicUtils::ComponentFactory::ScriptConfig>({
|
||||
script.get<std::vector<std::string>>()
|
||||
}): std::nullopt);
|
||||
|
||||
auto textRenderer2DConfig(!textRenderer.is_null() ? std::optional<CosmicUtils::ComponentFactory::TextRenderer2DConfig>({
|
||||
textRenderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::TextRenderer_Text2D)].get<std::string>(),
|
||||
textRenderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::TextRenderer_Shader2D)].get<std::string>(),
|
||||
glm::make_vec4(textRenderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::TextRenderer_Color2D)].get<std::vector<float>>().data()),
|
||||
prefix + textRenderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::TextRenderer_Font2D)].get<std::string>()
|
||||
}) : std::nullopt);
|
||||
|
||||
|
||||
CosmicUtils::CEntityFactory::Entity2DConfig config = {
|
||||
entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity2D_Name)],
|
||||
entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity2D_Description)],
|
||||
trConfig,
|
||||
camConfig,
|
||||
rendererConfig,
|
||||
colliderConfig,
|
||||
scriptConfig,
|
||||
textRenderer2DConfig
|
||||
};
|
||||
|
||||
auto entityHandle = CosmicUtils::CEntityFactory::create(scene.get(), config);
|
||||
|
||||
idToHandle.emplace(std::make_pair(ref, entityHandle));
|
||||
if(parent.has_value())
|
||||
idToParent[ref] = parent.value();
|
||||
|
||||
for(auto i : children)
|
||||
{
|
||||
idToChildren[ref].push_back(i);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//Connect entities to relationships
|
||||
for(auto& [entityNb, handle]: idToHandle)
|
||||
{
|
||||
CosmicUtils::ComponentFactory::RelationshipConfig cnf;
|
||||
if(idToParent.find(entityNb) != idToParent.end())
|
||||
{
|
||||
cnf.parent = std::optional<EntityId>(idToHandle.at(idToParent.at(entityNb)).getHandle());
|
||||
}
|
||||
else
|
||||
{
|
||||
cnf.parent = std::nullopt;
|
||||
}
|
||||
|
||||
for(auto& child : idToChildren[entityNb])
|
||||
{
|
||||
cnf.children.push_back(idToHandle.at(child).getHandle());
|
||||
}
|
||||
CosmicUtils::ComponentFactory::addRelationship(handle, cnf);
|
||||
}
|
||||
|
||||
return scene;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void CScene::save(CScene *scene, const std::string &path)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void CScene::save(const std::string& path)
|
||||
{
|
||||
save(this, path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
#ifndef CSCENE_HPP
|
||||
#define CSCENE_HPP
|
||||
|
||||
#include "Engine/Core/Entity/EntityComponentManager.hpp"
|
||||
#include "Engine/Utils/JsonParser/CSerializable.hpp"
|
||||
#include <string>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
#include "Engine/Core/Systems/Physics/CTangibleWorld.hpp"
|
||||
#include "Engine/Core/Systems/Audio/CAudioWorld.hpp"
|
||||
#include "Engine/Core/Systems/Scripts/CScriptWorld.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/Data/Light/CLightsBuffer.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/UserInterface/CUIWorld.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
class CEntity;
|
||||
class CScene : public CSerializable {
|
||||
private:
|
||||
// The name of the scene.
|
||||
std::string m_name;
|
||||
EntityComponentManager m_ecManager;
|
||||
CTangibleWorld m_tangibleWorld;
|
||||
CAudioWorld m_audioWorld;
|
||||
CScriptWorld m_scriptWorld;
|
||||
CLightsBuffer m_lightsBuffer;
|
||||
//CUIWorld m_uiWorld;
|
||||
|
||||
void render3D(vk::raii::CommandBuffer& cmd, uint32_t frameIndex);
|
||||
void render2D(vk::raii::CommandBuffer& cmd, uint32_t frameIndex);
|
||||
|
||||
public:
|
||||
CScene() = delete;
|
||||
CScene(std::string name);
|
||||
CScene(CScene&&) = delete;
|
||||
CScene& operator=(CScene&&) = delete;
|
||||
CScene(const CScene&) = delete;
|
||||
CScene& operator=(const CScene&) = delete;
|
||||
|
||||
virtual ~CScene();
|
||||
|
||||
unsigned int getNumEntity() const;
|
||||
|
||||
CEntity createEntity();
|
||||
|
||||
std::string getName() const;
|
||||
|
||||
EntityComponentManager& getECManager(){return m_ecManager;};
|
||||
|
||||
void removeEntity(unsigned int index, bool destroy = true);
|
||||
|
||||
CTangibleWorld& getTangibleWorld() {return m_tangibleWorld;};
|
||||
|
||||
CAudioWorld& getAudioWorld() {return m_audioWorld;};
|
||||
|
||||
CScriptWorld& getScriptWorld() {return m_scriptWorld;};
|
||||
|
||||
//CUIWorld& getUIWorld() {return m_uiWorld;};
|
||||
//CEntity* getActiveCamera();
|
||||
//void setActiveCamera(CEntity* newCamera);
|
||||
|
||||
/**
|
||||
* @brief Getter to the light.
|
||||
* @return The pointer m_mainLight.
|
||||
*/
|
||||
//CEntity* getMainLight();
|
||||
|
||||
/**
|
||||
* @brief Setter of the light.
|
||||
* @param light : The light to set as main light.
|
||||
*/
|
||||
//void setMainLight(CEntity* light);
|
||||
|
||||
/**
|
||||
* @brief Setter of the ODE world handling class.
|
||||
* @param[in, out] world The pointer to the physical world.
|
||||
*/
|
||||
//void setTangibleWorld(CTangibleWorld* world);
|
||||
|
||||
/**
|
||||
* @brief Getter to the physical world of the environment.
|
||||
* @return The pointer m_tangibleWorld.
|
||||
*/
|
||||
//std::weak_ptr<CAbstractTangibleWorld> getTangibleWorld();
|
||||
|
||||
/**
|
||||
* @brief Setter of the layer mask.
|
||||
* @param[in] mask The new mask value.
|
||||
*/
|
||||
void setMask(unsigned int mask);
|
||||
|
||||
/**
|
||||
* @brief Getter to the layer mask.
|
||||
* @return The value of m_maskLayer.
|
||||
*/
|
||||
//unsigned int getMask();
|
||||
|
||||
void render(vk::raii::CommandBuffer& cmd, uint32_t frameIndex);
|
||||
|
||||
void collectLights(vk::raii::CommandBuffer& cmd, uint32_t frameIndex);
|
||||
//void updateScript();
|
||||
|
||||
nlohmann::json to_json();
|
||||
|
||||
/*static CScene* from_json(nlohmann::json& j)
|
||||
{
|
||||
CScene* s = new CScene(j["Name"]);
|
||||
for (nlohmann::json& entity : j["Entities"])
|
||||
{
|
||||
CEntity* e = CEntity::from_json(s, entity);
|
||||
s->addEntity(e);
|
||||
}
|
||||
return s;
|
||||
};*/
|
||||
|
||||
static std::unique_ptr<CScene> load(const std::string& path);
|
||||
static void save(CScene* scene, const std::string& path);
|
||||
|
||||
void save(const std::string& path);
|
||||
|
||||
};
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,8 @@
|
||||
#include "CAudioAPI.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
CAudioAPI::~CAudioAPI()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#ifndef CAUDIOAPI_HPP
|
||||
#define CAUDIOAPI_HPP
|
||||
namespace CosmicCore {
|
||||
|
||||
class CScene;
|
||||
/**
|
||||
* @brief Class representing any audio world - abstract.
|
||||
*/
|
||||
class CAudioAPI {
|
||||
|
||||
private:
|
||||
CScene* m_scene;
|
||||
public:
|
||||
CAudioAPI(CScene* scene): m_scene(scene){};
|
||||
virtual ~CAudioAPI();
|
||||
|
||||
virtual void updateWorld(float delta) = 0;
|
||||
|
||||
virtual void initWorld() = 0;
|
||||
virtual void destroy() = 0;
|
||||
|
||||
CScene* getScene(){return m_scene;};
|
||||
};
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,61 @@
|
||||
#include "CAudioWorld.hpp"
|
||||
#include "Engine/Core/Scene/CScene.hpp"
|
||||
#include "Engine/Core/Component/Camera/CCamera.hpp"
|
||||
#include "Engine/Core/Component/Speaker/CSpeaker.hpp"
|
||||
|
||||
#include <AL/al.h>
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
CAudioWorld::~CAudioWorld()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void CAudioWorld::initWorld() {
|
||||
m_device = alcOpenDevice(nullptr);
|
||||
m_context = alcCreateContext(m_device, nullptr);
|
||||
alcMakeContextCurrent(m_context);
|
||||
|
||||
// active le distance model
|
||||
alDistanceModel(AL_LINEAR_DISTANCE_CLAMPED);
|
||||
alListenerf(AL_GAIN, 1.0f);
|
||||
}
|
||||
|
||||
void CAudioWorld::updateWorld(float delta) {
|
||||
auto& registry = getScene()->getECManager().registry;
|
||||
|
||||
// met à jour la position de l'écouteur depuis la caméra
|
||||
auto camView = registry.view<CCamera, CTransform>();
|
||||
if (camView.begin() != camView.end()) {
|
||||
auto& camTransform = registry.get<CTransform>(camView.front());
|
||||
glm::vec3 pos = camTransform.getCenter();
|
||||
glm::vec3 forward = camTransform.getOrientation() * glm::vec3(0,0,-1);
|
||||
glm::vec3 up = camTransform.getOrientation() * glm::vec3(0,1,0);
|
||||
|
||||
alListener3f(AL_POSITION, pos.x, pos.y, pos.z);
|
||||
float orientation[6] = {
|
||||
forward.x, forward.y, forward.z,
|
||||
up.x, up.y, up.z
|
||||
};
|
||||
alListenerfv(AL_ORIENTATION, orientation);
|
||||
}
|
||||
|
||||
// met à jour la position de chaque speaker
|
||||
auto view = registry.view<CSpeaker, CTransform>();
|
||||
for (auto entity : view) {
|
||||
auto& speaker = registry.get<CSpeaker>(entity);
|
||||
auto& transform = registry.get<CTransform>(entity);
|
||||
speaker.updatePosition(
|
||||
transform,
|
||||
{0.0f,0.0f,0.0f} // si tu as une vélocité dans CTransform
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void CAudioWorld::destroy() {
|
||||
alcMakeContextCurrent(nullptr);
|
||||
alcDestroyContext(m_context);
|
||||
alcCloseDevice(m_device);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#ifndef CAUDIOWORLD_HPP
|
||||
#define CAUDIOWORLD_HPP
|
||||
|
||||
#include <AL/alc.h>
|
||||
|
||||
#include "API/CAudioAPI.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
class CAudioWorld : public CAudioAPI{
|
||||
ALCdevice* m_device = nullptr;
|
||||
ALCcontext* m_context = nullptr;
|
||||
|
||||
public:
|
||||
CAudioWorld(CScene* scene) : CAudioAPI(scene) {}
|
||||
~CAudioWorld();
|
||||
void initWorld();
|
||||
|
||||
void updateWorld(float delta);
|
||||
|
||||
void destroy();
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,20 @@
|
||||
#ifndef CAUDIOCLIP_HPP
|
||||
#define CAUDIOCLIP_HPP
|
||||
#include <AL/al.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
class CAudioClip {
|
||||
private:
|
||||
public:
|
||||
ALuint buffer = 0;
|
||||
std::string path;
|
||||
float duration = 0.0f;
|
||||
|
||||
|
||||
~CAudioClip() {
|
||||
if (buffer) alDeleteBuffers(1, &buffer);
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,10 @@
|
||||
#include "GraphicsAPI.hpp"
|
||||
#include "VulkanImplementation/VulkanImpl.hpp"
|
||||
#include <memory>
|
||||
|
||||
std::unique_ptr<GraphicsAPI> GraphicsAPI::impl = nullptr;
|
||||
|
||||
void GraphicsAPI::initAPI(){
|
||||
//todo check config for chosen api
|
||||
impl = std::make_unique<VulkanImpl>();
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#ifndef GRAPHICAPI_HPP
|
||||
#define GRAPHICAPI_HPP
|
||||
|
||||
#include <SDL3/SDL_video.h>
|
||||
#include <memory>
|
||||
|
||||
enum class GraphicsBackend{
|
||||
Vulkan,
|
||||
OpenGL,
|
||||
Metal
|
||||
};
|
||||
|
||||
class GraphicsAPI{
|
||||
static std::unique_ptr<GraphicsAPI> impl;
|
||||
public:
|
||||
static void initAPI();
|
||||
static std::unique_ptr<GraphicsAPI>& getAPI(){return impl;};
|
||||
virtual void init(SDL_Window* window) = 0;
|
||||
virtual void cleanup() = 0;
|
||||
virtual ~GraphicsAPI(){};
|
||||
virtual void* getDevice() = 0;
|
||||
virtual void drawFrame() = 0;
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
+1
@@ -0,0 +1 @@
|
||||
#define MAX_FRAMES_IN_FLIGHT 2
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#ifndef DELETIONQUEUE_HPP
|
||||
#define DELETIONQUEUE_HPP
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <deque>
|
||||
#include <array>
|
||||
#include "Constants.hpp"
|
||||
|
||||
class DeletionQueue {
|
||||
private:
|
||||
// une queue par frame + une queue immédiate
|
||||
std::array<std::deque<std::function<void()>>, MAX_FRAMES_IN_FLIGHT> m_frameQueues;
|
||||
std::deque<std::function<void()>> m_immediateQueue;
|
||||
|
||||
public:
|
||||
// destruction différée - attendre MAX_FRAMES_IN_FLIGHT frames
|
||||
void push(uint32_t currentFrame, std::function<void()>&& func) {
|
||||
// on enfile dans la frame "opposée" pour attendre un cycle complet
|
||||
uint32_t targetFrame = (currentFrame + MAX_FRAMES_IN_FLIGHT - 1) % MAX_FRAMES_IN_FLIGHT;
|
||||
m_frameQueues[targetFrame].push_back(std::move(func));
|
||||
}
|
||||
|
||||
// destruction immédiate - device.waitIdle() doit avoir été appelé avant
|
||||
void pushImmediate(std::function<void()>&& func) {
|
||||
m_immediateQueue.push_back(std::move(func));
|
||||
}
|
||||
|
||||
// appelé au début de chaque frame - détruit les ressources de cette frame
|
||||
void flush(uint32_t frameIndex) {
|
||||
auto& queue = m_frameQueues[frameIndex];
|
||||
while (!queue.empty()) {
|
||||
queue.front()();
|
||||
queue.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
// appelé à la fermeture - détruit tout
|
||||
void flushAll() {
|
||||
// vider toutes les frame queues
|
||||
for (auto& queue : m_frameQueues) {
|
||||
while (!queue.empty()) {
|
||||
queue.front()();
|
||||
queue.pop_front();
|
||||
}
|
||||
}
|
||||
// vider la queue immédiate
|
||||
while (!m_immediateQueue.empty()) {
|
||||
m_immediateQueue.front()();
|
||||
m_immediateQueue.pop_front();
|
||||
}
|
||||
}
|
||||
};
|
||||
#endif
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
#ifndef MANAGEDDESCRIPTORSET_HPP
|
||||
#define MANAGEDDESCRIPTORSET_HPP
|
||||
|
||||
#include <vulkan/vulkan_core.h>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
#define MAX_FRAMES_IN_FLIGHT 2
|
||||
|
||||
struct ManagedDescriptorSet {
|
||||
vk::raii::DescriptorSet set = nullptr;
|
||||
VkDescriptorPool ownerPool = VK_NULL_HANDLE;
|
||||
|
||||
ManagedDescriptorSet() = default;
|
||||
ManagedDescriptorSet(ManagedDescriptorSet&&) = default;
|
||||
ManagedDescriptorSet& operator=(ManagedDescriptorSet&&) = default;
|
||||
|
||||
ManagedDescriptorSet(const ManagedDescriptorSet&) = delete;
|
||||
ManagedDescriptorSet& operator=(const ManagedDescriptorSet&) = delete;
|
||||
};
|
||||
|
||||
#endif
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
#ifndef VMABUFFER_HPP
|
||||
#define VMABUFFER_HPP
|
||||
|
||||
#include "vk_mem_alloc.h"
|
||||
|
||||
typedef struct vmaBufferStruct {
|
||||
VkBuffer buffer = VK_NULL_HANDLE;
|
||||
VmaAllocation allocation = VK_NULL_HANDLE;
|
||||
|
||||
void destroy(VmaAllocator allocator) {
|
||||
vmaDestroyBuffer(allocator, buffer, allocation);
|
||||
}
|
||||
}VMABuffer;
|
||||
|
||||
#endif
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
#define VMA_IMPLEMENTATION
|
||||
#include "vk_mem_alloc.h"
|
||||
+862
@@ -0,0 +1,862 @@
|
||||
#include "VulkanImpl.hpp"
|
||||
#include <SDL3/SDL_events.h>
|
||||
#include <SDL3/SDL_video.h>
|
||||
#include <SDL3/SDL_vulkan.h>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan.hpp>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
#include "../../../../Kernel/CKernel.hpp"
|
||||
#include "DeletionQueue.hpp"
|
||||
#include "vulkan/vulkan.hpp"
|
||||
#include "../../../Resources/API/CResourceAPI.hpp"
|
||||
|
||||
static uint32_t chooseSwapMinImageCount(vk::SurfaceCapabilitiesKHR const &surfaceCapabilities)
|
||||
{
|
||||
auto minImageCount = std::max(3u, surfaceCapabilities.minImageCount);
|
||||
if ((0 < surfaceCapabilities.maxImageCount) && (surfaceCapabilities.maxImageCount < minImageCount))
|
||||
{
|
||||
minImageCount = surfaceCapabilities.maxImageCount;
|
||||
}
|
||||
return minImageCount;
|
||||
}
|
||||
|
||||
static vk::SurfaceFormatKHR chooseSwapSurfaceFormat(std::vector<vk::SurfaceFormatKHR> const &availableFormats)
|
||||
{
|
||||
assert(!availableFormats.empty());
|
||||
const auto formatIt = std::ranges::find_if(
|
||||
availableFormats,
|
||||
[](const auto &format) { return format.format == vk::Format::eB8G8R8A8Srgb && format.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear; });
|
||||
return formatIt != availableFormats.end() ? *formatIt : availableFormats[0];
|
||||
}
|
||||
|
||||
static vk::PresentModeKHR chooseSwapPresentMode(const std::vector<vk::PresentModeKHR> &availablePresentModes)
|
||||
{
|
||||
assert(std::ranges::any_of(availablePresentModes, [](auto presentMode) { return presentMode == vk::PresentModeKHR::eFifo; }));
|
||||
return std::ranges::any_of(availablePresentModes,
|
||||
[](const vk::PresentModeKHR value) { return vk::PresentModeKHR::eMailbox == value; }) ?
|
||||
vk::PresentModeKHR::eMailbox :
|
||||
vk::PresentModeKHR::eFifo;
|
||||
}
|
||||
|
||||
vk::Extent2D chooseSwapExtent(const vk::SurfaceCapabilitiesKHR &capabilities, SDL_Window* window)
|
||||
{
|
||||
if (capabilities.currentExtent.width != 0xFFFFFFFF)
|
||||
{
|
||||
return capabilities.currentExtent;
|
||||
}
|
||||
int width, height;
|
||||
SDL_GetWindowSizeInPixels(window, &width, &height);
|
||||
|
||||
return {
|
||||
std::clamp<uint32_t>(width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width),
|
||||
std::clamp<uint32_t>(height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height)};
|
||||
}
|
||||
|
||||
void VulkanImpl::init(SDL_Window* window){
|
||||
m_window = window;
|
||||
createInstance();
|
||||
createSurface();
|
||||
pickPhysicalDevice();
|
||||
createLogicalDevice();
|
||||
|
||||
//getShaders after creating device
|
||||
CResourceAPI::resources().shaders().create();
|
||||
CResourceAPI::resources().shaders().compile();
|
||||
|
||||
createSwapChain();
|
||||
createImageViews();
|
||||
createDescriptorSetLayouts();
|
||||
//createGraphicsPipeline();
|
||||
createDepthResources();
|
||||
createCommandPool();
|
||||
createDescriptorPool();
|
||||
createDefaultTexture();
|
||||
createCommandBuffer();
|
||||
createSyncObjects();
|
||||
}
|
||||
|
||||
void VulkanImpl::cleanup(){
|
||||
device.waitIdle();
|
||||
// détruire les ressources dans le ResourceManager
|
||||
// (buffers, pipelines, descriptor sets...)
|
||||
m_deletionQueue.flushAll();
|
||||
|
||||
CosmicCore::CKernelBase::instance()->cleanup();
|
||||
CResourceAPI::resources().cleanup();
|
||||
|
||||
m_deletionQueue.flushAll();
|
||||
|
||||
// 2. sync objects
|
||||
inFlightFences.clear();
|
||||
renderFinishedSemaphores.clear();
|
||||
presentCompleteSemaphores.clear();
|
||||
|
||||
// 3. command buffers puis command pool
|
||||
commandBuffers.clear();
|
||||
commandPool = nullptr;
|
||||
|
||||
// 4. swapchain
|
||||
cleanupSwapChain();
|
||||
|
||||
// descriptor set layouts + pipeline layout avant le device
|
||||
defaultPipelineLayoutInfo = nullptr;
|
||||
default2DPipelineLayoutInfo = nullptr;
|
||||
cameraLayout = nullptr;
|
||||
transformLayout = nullptr;
|
||||
materialLayout = nullptr;
|
||||
lightLayout = nullptr;
|
||||
|
||||
projection2DLayout = nullptr;
|
||||
transform2DLayout = nullptr;
|
||||
material2DLayout = nullptr;
|
||||
VmaTotalStatistics stats;
|
||||
vmaCalculateStatistics(allocator, &stats);
|
||||
if (stats.total.statistics.allocationCount > 0) {
|
||||
std::cout << "VMA: " << stats.total.statistics.allocationCount
|
||||
<< " allocations non libérées !" << std::endl;
|
||||
std::cout << "VMA: " << stats.total.statistics.allocationBytes
|
||||
<< " bytes non libérés" << std::endl;
|
||||
}
|
||||
|
||||
//Vulkan memory allocator
|
||||
vmaDestroyAllocator(allocator);
|
||||
|
||||
// surface
|
||||
surface = nullptr;
|
||||
|
||||
// device en avant-dernier
|
||||
device = nullptr;
|
||||
|
||||
// instance en dernier
|
||||
instance = nullptr;
|
||||
}
|
||||
|
||||
void VulkanImpl::createInstance(){
|
||||
|
||||
constexpr vk::ApplicationInfo appInfo{ "CosmicEngine",
|
||||
VK_MAKE_VERSION( 1, 0, 0 ),
|
||||
"No Engine",
|
||||
VK_MAKE_VERSION( 1, 0, 0 ),
|
||||
vk::ApiVersion13};
|
||||
|
||||
uint32_t sdl_extensions_count = 0;
|
||||
|
||||
const char* const* sdl_extensions = SDL_Vulkan_GetInstanceExtensions(&sdl_extensions_count);
|
||||
auto extensionProp = context.enumerateInstanceExtensionProperties();
|
||||
for (uint32_t i = 0; i < sdl_extensions_count; ++i)
|
||||
{
|
||||
if (std::ranges::none_of(extensionProp,
|
||||
[sdlExtension = sdl_extensions[i]](auto const& extensionProperty)
|
||||
{ return strcmp(extensionProperty.extensionName, sdlExtension) == 0; }))
|
||||
{
|
||||
throw std::runtime_error("Required SDL extension not supported: " + std::string(sdl_extensions[i]));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Get the required layers
|
||||
std::vector<char const*> requiredLayers;
|
||||
if (enableValidationLayers)
|
||||
{
|
||||
requiredLayers.assign(validationLayers.begin(), validationLayers.end());
|
||||
}
|
||||
|
||||
// Check if the required layers are supported by the Vulkan implementation.
|
||||
auto layerProperties = context.enumerateInstanceLayerProperties();
|
||||
auto unsupportedLayerIt = std::ranges::find_if(requiredLayers,
|
||||
[&layerProperties](auto const &requiredLayer) {
|
||||
return std::ranges::none_of(layerProperties,
|
||||
[requiredLayer](auto const &layerProperty) { return strcmp(layerProperty.layerName, requiredLayer) == 0; });
|
||||
});
|
||||
if (unsupportedLayerIt != requiredLayers.end())
|
||||
{
|
||||
throw std::runtime_error("Required layer not supported: " + std::string(*unsupportedLayerIt));
|
||||
}
|
||||
|
||||
vk::InstanceCreateInfo createInfo{{},&appInfo, static_cast<uint32_t>(requiredLayers.size()), requiredLayers.data(), sdl_extensions_count, sdl_extensions};
|
||||
|
||||
|
||||
instance = vk::raii::Instance(context, createInfo);
|
||||
}
|
||||
|
||||
void VulkanImpl::pickPhysicalDevice()
|
||||
{
|
||||
std::vector<vk::raii::PhysicalDevice> devices = instance.enumeratePhysicalDevices();
|
||||
const auto devIter = std::ranges::find_if(
|
||||
devices,
|
||||
[&](auto const &device) {
|
||||
// Check if the device supports the Vulkan 1.3 API version
|
||||
bool supportsVulkan1_3 = device.getProperties().apiVersion >= VK_API_VERSION_1_3;
|
||||
|
||||
// Check if any of the queue families support graphics operations
|
||||
auto queueFamilies = device.getQueueFamilyProperties();
|
||||
bool supportsGraphics =
|
||||
std::ranges::any_of(queueFamilies, [](auto const &qfp) { return !!(qfp.queueFlags & vk::QueueFlagBits::eGraphics); });
|
||||
|
||||
// Check if all required device extensions are available
|
||||
auto availableDeviceExtensions = device.enumerateDeviceExtensionProperties();
|
||||
bool supportsAllRequiredExtensions =
|
||||
std::ranges::all_of(requiredDeviceExtension,
|
||||
[&availableDeviceExtensions](auto const &requiredDeviceExtension) {
|
||||
return std::ranges::any_of(availableDeviceExtensions,
|
||||
[requiredDeviceExtension](auto const &availableDeviceExtension) { return strcmp(availableDeviceExtension.extensionName, requiredDeviceExtension) == 0; });
|
||||
});
|
||||
|
||||
auto features = device.template getFeatures2<vk::PhysicalDeviceFeatures2, vk::PhysicalDeviceVulkan13Features, vk::PhysicalDeviceExtendedDynamicStateFeaturesEXT>();
|
||||
bool supportsRequiredFeatures = features.template get<vk::PhysicalDeviceVulkan13Features>().dynamicRendering &&
|
||||
features.template get<vk::PhysicalDeviceExtendedDynamicStateFeaturesEXT>().extendedDynamicState;
|
||||
|
||||
return supportsVulkan1_3 && supportsGraphics && supportsAllRequiredExtensions && supportsRequiredFeatures;
|
||||
});
|
||||
if (devIter != devices.end())
|
||||
{
|
||||
physicalDevice = *devIter;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw std::runtime_error("failed to find a suitable GPU!");
|
||||
}
|
||||
}
|
||||
|
||||
void VulkanImpl::createLogicalDevice()
|
||||
{
|
||||
// find the index of the first queue family that supports graphics
|
||||
std::vector<vk::QueueFamilyProperties> queueFamilyProperties = physicalDevice.getQueueFamilyProperties();
|
||||
|
||||
// get the first index into queueFamilyProperties which supports graphics
|
||||
auto graphicsQueueFamilyProperty = std::ranges::find_if(queueFamilyProperties, [](auto const &qfp) { return (qfp.queueFlags & vk::QueueFlagBits::eGraphics) != static_cast<vk::QueueFlags>(0); });
|
||||
assert(graphicsQueueFamilyProperty != queueFamilyProperties.end() && "No graphics queue family found!");
|
||||
|
||||
auto graphicsIndex = static_cast<uint32_t>(std::distance(queueFamilyProperties.begin(), graphicsQueueFamilyProperty));
|
||||
|
||||
// determine a queueFamilyIndex that supports present
|
||||
// first check if the graphicsIndex is good enough
|
||||
auto presentIndex = physicalDevice.getSurfaceSupportKHR( graphicsIndex, *surface )
|
||||
? graphicsIndex
|
||||
: static_cast<uint32_t>( queueFamilyProperties.size() );
|
||||
if ( presentIndex == queueFamilyProperties.size() )
|
||||
{
|
||||
// the graphicsIndex doesn't support present -> look for another family index that supports both
|
||||
// graphics and present
|
||||
for ( size_t i = 0; i < queueFamilyProperties.size(); i++ )
|
||||
{
|
||||
if ( ( queueFamilyProperties[i].queueFlags & vk::QueueFlagBits::eGraphics ) &&
|
||||
physicalDevice.getSurfaceSupportKHR( static_cast<uint32_t>( i ), *surface ) )
|
||||
{
|
||||
graphicsIndex = static_cast<uint32_t>( i );
|
||||
presentIndex = graphicsIndex;
|
||||
queueIndex = graphicsIndex;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ( presentIndex == queueFamilyProperties.size() )
|
||||
{
|
||||
// there's nothing like a single family index that supports both graphics and present -> look for another
|
||||
// family index that supports present
|
||||
for ( size_t i = 0; i < queueFamilyProperties.size(); i++ )
|
||||
{
|
||||
if ( physicalDevice.getSurfaceSupportKHR( static_cast<uint32_t>( i ), *surface ) )
|
||||
{
|
||||
presentIndex = static_cast<uint32_t>( i );
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ( ( graphicsIndex == queueFamilyProperties.size() ) || ( presentIndex == queueFamilyProperties.size() ) )
|
||||
{
|
||||
throw std::runtime_error( "Could not find a queue for graphics or present -> terminating" );
|
||||
}
|
||||
|
||||
queueIndex = graphicsIndex;
|
||||
|
||||
// query for Vulkan 1.3 features
|
||||
|
||||
auto features = physicalDevice.getFeatures2();
|
||||
vk::PhysicalDeviceVulkan11Features vulkan11Features;
|
||||
vulkan11Features.shaderDrawParameters = vk::True;
|
||||
|
||||
vk::PhysicalDeviceVulkan13Features vulkan13Features;
|
||||
vk::PhysicalDeviceExtendedDynamicStateFeaturesEXT extendedDynamicStateFeatures;
|
||||
vulkan13Features.dynamicRendering = vk::True;
|
||||
vulkan13Features.synchronization2 = vk::True;
|
||||
extendedDynamicStateFeatures.extendedDynamicState = vk::True;
|
||||
vulkan11Features.pNext = &vulkan13Features;
|
||||
vulkan13Features.pNext = &extendedDynamicStateFeatures;
|
||||
features.pNext = &vulkan11Features;
|
||||
|
||||
// create a Device
|
||||
float queuePriority = 0.5f;
|
||||
vk::DeviceQueueCreateInfo deviceQueueCreateInfo{{},
|
||||
graphicsIndex,
|
||||
1,
|
||||
&queuePriority};
|
||||
|
||||
vk::DeviceCreateInfo deviceCreateInfo{{},
|
||||
1,
|
||||
&deviceQueueCreateInfo,
|
||||
{},
|
||||
{},
|
||||
static_cast<uint32_t>(requiredDeviceExtension.size()),
|
||||
requiredDeviceExtension.data(),
|
||||
{},
|
||||
&features
|
||||
};
|
||||
|
||||
|
||||
device = vk::raii::Device(physicalDevice, deviceCreateInfo);
|
||||
graphicsQueue = vk::raii::Queue(device, graphicsIndex, 0);
|
||||
presentQueue = vk::raii::Queue( device, presentIndex, 0 );
|
||||
|
||||
VmaAllocatorCreateInfo allocatorInfo{};
|
||||
allocatorInfo.physicalDevice = *physicalDevice;
|
||||
allocatorInfo.device = *device;
|
||||
allocatorInfo.instance = *instance;
|
||||
allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_3;
|
||||
vmaCreateAllocator(&allocatorInfo, &allocator);
|
||||
}
|
||||
|
||||
void VulkanImpl::createSurface()
|
||||
{
|
||||
VkSurfaceKHR _surface;
|
||||
if (!SDL_Vulkan_CreateSurface(m_window, *instance, nullptr, &_surface)) {
|
||||
throw std::runtime_error("failed to create window surface!");
|
||||
}
|
||||
surface = vk::raii::SurfaceKHR(instance, _surface);
|
||||
}
|
||||
|
||||
void VulkanImpl::createSwapChain()
|
||||
{
|
||||
auto surfaceCapabilities = physicalDevice.getSurfaceCapabilitiesKHR(*surface);
|
||||
swapChainExtent = chooseSwapExtent(surfaceCapabilities, m_window);
|
||||
swapChainSurfaceFormat = chooseSwapSurfaceFormat(physicalDevice.getSurfaceFormatsKHR(*surface));
|
||||
vk::SwapchainCreateInfoKHR swapChainCreateInfo{ {},
|
||||
*surface,
|
||||
chooseSwapMinImageCount(surfaceCapabilities),
|
||||
swapChainSurfaceFormat.format,
|
||||
swapChainSurfaceFormat.colorSpace,
|
||||
swapChainExtent,
|
||||
1,
|
||||
vk::ImageUsageFlagBits::eColorAttachment,
|
||||
vk::SharingMode::eExclusive,
|
||||
{},
|
||||
surfaceCapabilities.currentTransform,
|
||||
vk::CompositeAlphaFlagBitsKHR::eOpaque,
|
||||
chooseSwapPresentMode(physicalDevice.getSurfacePresentModesKHR(*surface)),
|
||||
true};
|
||||
|
||||
swapChain = vk::raii::SwapchainKHR(device, swapChainCreateInfo);
|
||||
|
||||
swapChainImages = swapChain.getImages();
|
||||
}
|
||||
|
||||
void VulkanImpl::createImageViews()
|
||||
{
|
||||
vk::ImageViewCreateInfo imageViewCreateInfo{
|
||||
{},
|
||||
{},
|
||||
vk::ImageViewType::e2D,
|
||||
swapChainSurfaceFormat.format,
|
||||
{},
|
||||
{vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}
|
||||
};
|
||||
for (auto& image : swapChainImages)
|
||||
{
|
||||
imageViewCreateInfo.image = image;
|
||||
swapChainImageViews.emplace_back(device, imageViewCreateInfo);
|
||||
}
|
||||
}
|
||||
|
||||
vk::raii::ImageView VulkanImpl::createImageView(vk::raii::Image& image, vk::Format format, vk::ImageAspectFlags aspectFlags)
|
||||
{
|
||||
vk::ImageViewCreateInfo imageViewCreateInfo{
|
||||
{},
|
||||
image,
|
||||
vk::ImageViewType::e2D,
|
||||
format,
|
||||
{},
|
||||
{aspectFlags, 0, 1, 0, 1}
|
||||
};
|
||||
return vk::raii::ImageView(device, imageViewCreateInfo);
|
||||
}
|
||||
|
||||
void VulkanImpl::createCommandPool()
|
||||
{
|
||||
vk::CommandPoolCreateInfo poolInfo{vk::CommandPoolCreateFlagBits::eResetCommandBuffer, queueIndex};
|
||||
commandPool = vk::raii::CommandPool(device, poolInfo);
|
||||
}
|
||||
|
||||
void VulkanImpl::createCommandBuffer()
|
||||
{
|
||||
vk::CommandBufferAllocateInfo allocInfo{commandPool, vk::CommandBufferLevel::ePrimary, MAX_FRAMES_IN_FLIGHT};
|
||||
commandBuffers = vk::raii::CommandBuffers(device, allocInfo);
|
||||
}
|
||||
|
||||
|
||||
void VulkanImpl::recordCommandBuffer(uint32_t imageIndex)
|
||||
{
|
||||
auto &commandBuffer = commandBuffers[frameIndex];
|
||||
commandBuffer.begin({});
|
||||
// Before starting rendering, transition the swapchain image to COLOR_ATTACHMENT_OPTIMAL
|
||||
transitionImageLayout(
|
||||
swapChainImages[imageIndex],
|
||||
vk::ImageLayout::eUndefined,
|
||||
vk::ImageLayout::eColorAttachmentOptimal,
|
||||
{}, // srcAccessMask (no need to wait for previous operations)
|
||||
vk::AccessFlagBits2::eColorAttachmentWrite, // dstAccessMask
|
||||
vk::PipelineStageFlagBits2::eColorAttachmentOutput, // srcStage
|
||||
vk::PipelineStageFlagBits2::eColorAttachmentOutput, // dstStage
|
||||
vk::ImageAspectFlagBits::eColor
|
||||
);
|
||||
|
||||
// Transition depth image to depth attachment optimal layout
|
||||
transitionImageLayout(
|
||||
depthImage,
|
||||
vk::ImageLayout::eUndefined,
|
||||
vk::ImageLayout::eDepthAttachmentOptimal,
|
||||
vk::AccessFlagBits2::eDepthStencilAttachmentWrite,
|
||||
vk::AccessFlagBits2::eDepthStencilAttachmentWrite,
|
||||
vk::PipelineStageFlagBits2::eEarlyFragmentTests | vk::PipelineStageFlagBits2::eLateFragmentTests,
|
||||
vk::PipelineStageFlagBits2::eEarlyFragmentTests | vk::PipelineStageFlagBits2::eLateFragmentTests,
|
||||
vk::ImageAspectFlagBits::eDepth);
|
||||
|
||||
vk::ClearValue clearColor = vk::ClearColorValue(0.0f, 0.0f, 0.0f, 1.0f);
|
||||
vk::ClearValue clearDepth = vk::ClearDepthStencilValue(1.0f, 0);
|
||||
//color
|
||||
vk::RenderingAttachmentInfo attachmentInfo = {
|
||||
swapChainImageViews[imageIndex],
|
||||
vk::ImageLayout::eColorAttachmentOptimal,
|
||||
{},
|
||||
{},
|
||||
{},
|
||||
vk::AttachmentLoadOp::eClear,
|
||||
vk::AttachmentStoreOp::eStore,
|
||||
clearColor
|
||||
};
|
||||
//depth
|
||||
vk::RenderingAttachmentInfo depthAttachmentInfo = {
|
||||
depthImageView,
|
||||
vk::ImageLayout::eDepthAttachmentOptimal,
|
||||
{},
|
||||
{},
|
||||
{},
|
||||
vk::AttachmentLoadOp::eClear,
|
||||
vk::AttachmentStoreOp::eDontCare,
|
||||
clearDepth};
|
||||
|
||||
vk::RenderingInfo renderingInfo = {{},{{0, 0}, swapChainExtent},
|
||||
1,
|
||||
{},
|
||||
1,
|
||||
&attachmentInfo,
|
||||
&depthAttachmentInfo};
|
||||
|
||||
commandBuffer.beginRendering(renderingInfo);
|
||||
|
||||
commandBuffer.setViewport(0, vk::Viewport(0.0f, 0.0f, static_cast<float>(swapChainExtent.width), static_cast<float>(swapChainExtent.height), 0.0f, 1.0f));
|
||||
commandBuffer.setScissor(0, vk::Rect2D(vk::Offset2D(0, 0), swapChainExtent));
|
||||
|
||||
CosmicCore::CKernelBase::instance()->getActiveScene()->render(commandBuffer, frameIndex);
|
||||
|
||||
commandBuffer.endRendering();
|
||||
// After rendering, transition the swapchain image to PRESENT_SRC
|
||||
transitionImageLayout(
|
||||
swapChainImages[imageIndex],
|
||||
vk::ImageLayout::eColorAttachmentOptimal,
|
||||
vk::ImageLayout::ePresentSrcKHR,
|
||||
vk::AccessFlagBits2::eColorAttachmentWrite, // srcAccessMask
|
||||
{}, // dstAccessMask
|
||||
vk::PipelineStageFlagBits2::eColorAttachmentOutput, // srcStage
|
||||
vk::PipelineStageFlagBits2::eBottomOfPipe, // dstStage
|
||||
vk::ImageAspectFlagBits::eColor
|
||||
);
|
||||
commandBuffer.end();
|
||||
}
|
||||
|
||||
void VulkanImpl::transitionImageLayout(
|
||||
vk::Image image,
|
||||
vk::ImageLayout old_layout,
|
||||
vk::ImageLayout new_layout,
|
||||
vk::AccessFlags2 src_access_mask,
|
||||
vk::AccessFlags2 dst_access_mask,
|
||||
vk::PipelineStageFlags2 src_stage_mask,
|
||||
vk::PipelineStageFlags2 dst_stage_mask, vk::ImageAspectFlags image_aspect_flags)
|
||||
{
|
||||
|
||||
vk::ImageMemoryBarrier2 barrier = {src_stage_mask, src_access_mask, dst_stage_mask, dst_access_mask, old_layout, new_layout, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, image, {image_aspect_flags,0,1,0,1}};
|
||||
vk::DependencyInfo dependency_info = {{},{},{},{}, {}, 1,&barrier};
|
||||
commandBuffers[frameIndex].pipelineBarrier2(dependency_info);
|
||||
}
|
||||
|
||||
void VulkanImpl::createSyncObjects()
|
||||
{
|
||||
for (size_t i = 0; i < swapChainImages.size(); i++)
|
||||
{
|
||||
renderFinishedSemaphores.emplace_back(device, vk::SemaphoreCreateInfo());
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
|
||||
{
|
||||
presentCompleteSemaphores.emplace_back(device, vk::SemaphoreCreateInfo());
|
||||
inFlightFences.emplace_back(device, vk::FenceCreateInfo{vk::FenceCreateFlagBits::eSignaled});
|
||||
}
|
||||
}
|
||||
|
||||
void VulkanImpl::drawFrame()
|
||||
{
|
||||
auto fenceResult = device.waitForFences(*inFlightFences[frameIndex], vk::True, UINT64_MAX);
|
||||
m_deletionQueue.flush(frameIndex); // détruit les ressources de cette frame
|
||||
if (fenceResult != vk::Result::eSuccess)
|
||||
{
|
||||
throw std::runtime_error("failed to wait for fence!");
|
||||
}
|
||||
device.resetFences(*inFlightFences[frameIndex]);
|
||||
|
||||
auto [result, imageIndex] = swapChain.acquireNextImage(UINT64_MAX, *presentCompleteSemaphores[frameIndex], nullptr);
|
||||
commandBuffers[frameIndex].reset();
|
||||
recordCommandBuffer(imageIndex);
|
||||
|
||||
vk::PipelineStageFlags waitDestinationStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput);
|
||||
const vk::SubmitInfo submitInfo{1, &*presentCompleteSemaphores[frameIndex], &waitDestinationStageMask, 1, &*commandBuffers[frameIndex], 1, &*renderFinishedSemaphores[imageIndex]};
|
||||
presentQueue.submit(submitInfo, *inFlightFences[frameIndex]);
|
||||
|
||||
const vk::PresentInfoKHR presentInfoKHR{1, &*renderFinishedSemaphores[imageIndex], 1, &*swapChain, &imageIndex};
|
||||
result = presentQueue.presentKHR(presentInfoKHR);
|
||||
// Due to VULKAN_HPP_HANDLE_ERROR_OUT_OF_DATE_AS_SUCCESS being defined, eErrorOutOfDateKHR can be checked as a result
|
||||
// here and does not need to be caught by an exception.
|
||||
if ((result == vk::Result::eSuboptimalKHR) || (result == vk::Result::eErrorOutOfDateKHR) || framebufferResized)
|
||||
{
|
||||
framebufferResized = false;
|
||||
recreateSwapChain();
|
||||
}
|
||||
else
|
||||
{
|
||||
// There are no other success codes than eSuccess; on any error code, presentKHR already threw an exception.
|
||||
assert(result == vk::Result::eSuccess);
|
||||
}
|
||||
frameIndex = (frameIndex + 1) % MAX_FRAMES_IN_FLIGHT;
|
||||
}
|
||||
|
||||
void VulkanImpl::cleanupSwapChain()
|
||||
{
|
||||
depthImageView = nullptr;
|
||||
depthImage = nullptr;
|
||||
depthImageMemory = nullptr;
|
||||
|
||||
swapChainImageViews.clear();
|
||||
swapChain = nullptr;
|
||||
swapChainImages.clear();
|
||||
}
|
||||
|
||||
void VulkanImpl::recreateSwapChain()
|
||||
{
|
||||
int width = 0, height = 0;
|
||||
SDL_GetWindowSizeInPixels(m_window, &width, &height);
|
||||
while (width == 0 || height == 0) {
|
||||
SDL_GetWindowSizeInPixels(m_window, &width, &height);
|
||||
SDL_WaitEvent(nullptr);
|
||||
}
|
||||
|
||||
device.waitIdle();
|
||||
|
||||
cleanupSwapChain();
|
||||
createSwapChain();
|
||||
createImageViews();
|
||||
createDepthResources();
|
||||
}
|
||||
|
||||
uint32_t VulkanImpl::findMemoryType(uint32_t typeFilter, vk::MemoryPropertyFlags properties)
|
||||
{
|
||||
vk::PhysicalDeviceMemoryProperties memProperties = physicalDevice.getMemoryProperties();
|
||||
|
||||
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++)
|
||||
{
|
||||
if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
throw std::runtime_error("failed to find suitable memory type!");
|
||||
}
|
||||
|
||||
void VulkanImpl::copyBuffer(VkBuffer src, VkBuffer dst, VkDeviceSize size) {
|
||||
vk::raii::CommandBuffer commandCopyBuffer = beginSingleTimeCommands();
|
||||
commandCopyBuffer.copyBuffer(vk::Buffer(src), vk::Buffer(dst), vk::BufferCopy(0, 0, size));
|
||||
endSingleTimeCommands(commandCopyBuffer);
|
||||
}
|
||||
|
||||
void VulkanImpl::createDescriptorSetLayouts()
|
||||
{
|
||||
// set 0 - Camera : un UBO en vertex shader
|
||||
vk::DescriptorSetLayoutBinding cameraBinding{
|
||||
0, // binding
|
||||
vk::DescriptorType::eUniformBuffer, // type
|
||||
1, // count
|
||||
vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, // stage
|
||||
nullptr
|
||||
};
|
||||
cameraLayout = vk::raii::DescriptorSetLayout(
|
||||
device,
|
||||
vk::DescriptorSetLayoutCreateInfo{{}, 1, &cameraBinding}
|
||||
);
|
||||
|
||||
// set 1 - Transform : un UBO en vertex shader
|
||||
vk::DescriptorSetLayoutBinding transformBinding{
|
||||
0,
|
||||
vk::DescriptorType::eUniformBuffer,
|
||||
1,
|
||||
vk::ShaderStageFlagBits::eVertex,
|
||||
nullptr
|
||||
};
|
||||
transformLayout = vk::raii::DescriptorSetLayout(
|
||||
device,
|
||||
vk::DescriptorSetLayoutCreateInfo{{}, 1, &transformBinding}
|
||||
);
|
||||
|
||||
// set 2 - Material : un UBO + deux samplers en fragment shader
|
||||
std::array<vk::DescriptorSetLayoutBinding, 3> materialBindings{{
|
||||
{0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eFragment, nullptr},
|
||||
{1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment, nullptr},
|
||||
{2, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment, nullptr},
|
||||
}};
|
||||
materialLayout = vk::raii::DescriptorSetLayout(
|
||||
device,
|
||||
vk::DescriptorSetLayoutCreateInfo{{},
|
||||
static_cast<uint32_t>(materialBindings.size()),
|
||||
materialBindings.data()}
|
||||
);
|
||||
|
||||
//set 3 - Light : un storage buffer en fragmentshader
|
||||
vk::DescriptorSetLayoutBinding lightBinding{
|
||||
0,
|
||||
vk::DescriptorType::eStorageBuffer,
|
||||
1,
|
||||
vk::ShaderStageFlagBits::eFragment,
|
||||
nullptr
|
||||
};
|
||||
lightLayout = vk::raii::DescriptorSetLayout(
|
||||
device,
|
||||
vk::DescriptorSetLayoutCreateInfo{{}, 1, &lightBinding}
|
||||
);
|
||||
|
||||
std::array<vk::DescriptorSetLayout, 4> layouts{
|
||||
*cameraLayout,
|
||||
*transformLayout,
|
||||
*materialLayout,
|
||||
*lightLayout
|
||||
};
|
||||
vk::PipelineLayoutCreateInfo layoutInfo{{},
|
||||
static_cast<uint32_t>(layouts.size()),
|
||||
layouts.data()
|
||||
};
|
||||
defaultPipelineLayoutInfo = vk::raii::PipelineLayout(device, layoutInfo);
|
||||
|
||||
//Create 2D dfault pipeline
|
||||
|
||||
// set 0 - Transform : un UBO en vertex shader
|
||||
vk::DescriptorSetLayoutBinding transform2DBinding{
|
||||
0,
|
||||
vk::DescriptorType::eUniformBuffer,
|
||||
1,
|
||||
vk::ShaderStageFlagBits::eVertex,
|
||||
nullptr
|
||||
};
|
||||
transform2DLayout = vk::raii::DescriptorSetLayout(
|
||||
device,
|
||||
vk::DescriptorSetLayoutCreateInfo{{}, 1, &transform2DBinding}
|
||||
);
|
||||
|
||||
// set 2 - Material : un UBO + deux samplers en fragment shader
|
||||
std::array<vk::DescriptorSetLayoutBinding, 2> material2DBindings{{
|
||||
{0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eFragment, nullptr},
|
||||
{1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment, nullptr}
|
||||
}};
|
||||
material2DLayout = vk::raii::DescriptorSetLayout(
|
||||
device,
|
||||
vk::DescriptorSetLayoutCreateInfo{{},
|
||||
static_cast<uint32_t>(material2DBindings.size()),
|
||||
material2DBindings.data()}
|
||||
);
|
||||
|
||||
// set 2 - Projection : un UBO en vertex shader
|
||||
vk::DescriptorSetLayoutBinding projBinding{
|
||||
0, // binding
|
||||
vk::DescriptorType::eUniformBuffer, // type
|
||||
1, // count
|
||||
vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, // stage
|
||||
nullptr
|
||||
};
|
||||
projection2DLayout = vk::raii::DescriptorSetLayout(
|
||||
device,
|
||||
vk::DescriptorSetLayoutCreateInfo{{}, 1, &projBinding}
|
||||
);
|
||||
|
||||
std::array<vk::DescriptorSetLayout, 3> layouts2D{
|
||||
*transform2DLayout,
|
||||
*material2DLayout,
|
||||
*projection2DLayout
|
||||
};
|
||||
vk::PipelineLayoutCreateInfo layout2DInfo{{},
|
||||
static_cast<uint32_t>(layouts2D.size()),
|
||||
layouts2D.data()
|
||||
};
|
||||
default2DPipelineLayoutInfo = vk::raii::PipelineLayout(device, layout2DInfo);
|
||||
}
|
||||
|
||||
//Fonction d'ajout de descriptor set qui regarde la taille de la pool, si la pool est dépassée, on ajoute une pool 2x plus grande
|
||||
void VulkanImpl::createDescriptorPool()
|
||||
{
|
||||
descriptorPoolManager.init(device);
|
||||
}
|
||||
|
||||
void VulkanImpl::createDepthResources()
|
||||
{
|
||||
vk::Format depthFormat = findDepthFormat();
|
||||
createImage(swapChainExtent.width, swapChainExtent.height, depthFormat, vk::ImageTiling::eOptimal, vk::ImageUsageFlagBits::eDepthStencilAttachment, vk::MemoryPropertyFlagBits::eDeviceLocal, depthImage, depthImageMemory);
|
||||
depthImageView = createImageView(depthImage, depthFormat, vk::ImageAspectFlagBits::eDepth);
|
||||
}
|
||||
|
||||
vk::Format VulkanImpl::findSupportedFormat(const std::vector<vk::Format>& candidates, vk::ImageTiling tiling, vk::FormatFeatureFlags features)
|
||||
{
|
||||
for (const auto format : candidates) {
|
||||
vk::FormatProperties props = physicalDevice.getFormatProperties(format);
|
||||
|
||||
if (tiling == vk::ImageTiling::eLinear && (props.linearTilingFeatures & features) == features) {
|
||||
return format;
|
||||
}
|
||||
if (tiling == vk::ImageTiling::eOptimal && (props.optimalTilingFeatures & features) == features) {
|
||||
return format;
|
||||
}
|
||||
}
|
||||
|
||||
throw std::runtime_error("failed to find supported format!");
|
||||
}
|
||||
|
||||
vk::Format VulkanImpl::findDepthFormat() {
|
||||
return findSupportedFormat(
|
||||
{vk::Format::eD32Sfloat, vk::Format::eD32SfloatS8Uint, vk::Format::eD24UnormS8Uint},
|
||||
vk::ImageTiling::eOptimal,
|
||||
vk::FormatFeatureFlagBits::eDepthStencilAttachment
|
||||
);
|
||||
}
|
||||
|
||||
bool VulkanImpl::hasStencilComponent(vk::Format format) {
|
||||
return format == vk::Format::eD32SfloatS8Uint || format == vk::Format::eD24UnormS8Uint;
|
||||
}
|
||||
|
||||
void VulkanImpl::createImage(uint32_t width, uint32_t height, vk::Format format, vk::ImageTiling tiling, vk::ImageUsageFlags usage, vk::MemoryPropertyFlags properties, vk::raii::Image &image, vk::raii::DeviceMemory &imageMemory)
|
||||
{
|
||||
vk::ImageCreateInfo imageInfo{{},vk::ImageType::e2D, format, {width, height, 1}, 1, 1, vk::SampleCountFlagBits::e1, tiling, usage, vk::SharingMode::eExclusive};
|
||||
|
||||
image = vk::raii::Image(device, imageInfo);
|
||||
|
||||
vk::MemoryRequirements memRequirements = image.getMemoryRequirements();
|
||||
vk::MemoryAllocateInfo allocInfo{memRequirements.size,
|
||||
findMemoryType(memRequirements.memoryTypeBits, properties)};
|
||||
imageMemory = vk::raii::DeviceMemory(device, allocInfo);
|
||||
image.bindMemory(imageMemory, 0);
|
||||
}
|
||||
|
||||
vk::raii::CommandBuffer VulkanImpl::beginSingleTimeCommands() {
|
||||
vk::CommandBufferAllocateInfo allocInfo{ commandPool, vk::CommandBufferLevel::ePrimary, 1 };
|
||||
vk::raii::CommandBuffer commandBuffer = std::move(device.allocateCommandBuffers(allocInfo).front());
|
||||
|
||||
vk::CommandBufferBeginInfo beginInfo{ vk::CommandBufferUsageFlagBits::eOneTimeSubmit };
|
||||
commandBuffer.begin(beginInfo);
|
||||
|
||||
return commandBuffer;
|
||||
}
|
||||
|
||||
void VulkanImpl::endSingleTimeCommands(vk::raii::CommandBuffer& commandBuffer) {
|
||||
commandBuffer.end();
|
||||
|
||||
vk::SubmitInfo submitInfo{{},{},{},1, &*commandBuffer };
|
||||
graphicsQueue.submit(submitInfo, nullptr);
|
||||
graphicsQueue.waitIdle();
|
||||
}
|
||||
|
||||
|
||||
void VulkanImpl::transitionImageLayout(vk::Image image, vk::ImageLayout oldLayout, vk::ImageLayout newLayout)
|
||||
{
|
||||
auto commandBuffer = beginSingleTimeCommands();
|
||||
|
||||
vk::ImageMemoryBarrier barrier{{},{},oldLayout, newLayout,{}, {}, image, {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}};
|
||||
|
||||
vk::PipelineStageFlags sourceStage;
|
||||
vk::PipelineStageFlags destinationStage;
|
||||
|
||||
if (oldLayout == vk::ImageLayout::eUndefined && newLayout == vk::ImageLayout::eTransferDstOptimal)
|
||||
{
|
||||
barrier.srcAccessMask = {};
|
||||
barrier.dstAccessMask = vk::AccessFlagBits::eTransferWrite;
|
||||
|
||||
sourceStage = vk::PipelineStageFlagBits::eTopOfPipe;
|
||||
destinationStage = vk::PipelineStageFlagBits::eTransfer;
|
||||
}
|
||||
else if (oldLayout == vk::ImageLayout::eTransferDstOptimal && newLayout == vk::ImageLayout::eShaderReadOnlyOptimal)
|
||||
{
|
||||
barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
|
||||
barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
|
||||
|
||||
sourceStage = vk::PipelineStageFlagBits::eTransfer;
|
||||
destinationStage = vk::PipelineStageFlagBits::eFragmentShader;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw std::invalid_argument("unsupported layout transition!");
|
||||
}
|
||||
commandBuffer.pipelineBarrier(sourceStage, destinationStage, {}, {}, nullptr, barrier);
|
||||
endSingleTimeCommands(commandBuffer);
|
||||
}
|
||||
|
||||
void VulkanImpl::copyBufferToImage(const vk::raii::Buffer &buffer, vk::raii::Image &image, uint32_t width, uint32_t height)
|
||||
{
|
||||
auto commandBuffer = beginSingleTimeCommands();
|
||||
vk::BufferImageCopy region{0, 0, 0, {vk::ImageAspectFlagBits::eColor, 0, 0, 1}, {0, 0, 0}, {width, height, 1}};
|
||||
commandBuffer.copyBufferToImage(buffer, image, vk::ImageLayout::eTransferDstOptimal, {region});
|
||||
endSingleTimeCommands(commandBuffer);
|
||||
}
|
||||
|
||||
void VulkanImpl::destroyBuffer(VMABuffer& buffer, uint32_t frame) {
|
||||
VmaAllocator& alloc = allocator;
|
||||
VkBuffer& buf = buffer.buffer;
|
||||
VmaAllocation& mem = buffer.allocation;
|
||||
|
||||
m_deletionQueue.push(frame, [alloc, buf, mem]() {
|
||||
vmaDestroyBuffer(alloc, buf, mem);
|
||||
});
|
||||
|
||||
buffer.buffer = VK_NULL_HANDLE;
|
||||
buffer.allocation = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
// destruction d'un descriptor set
|
||||
void VulkanImpl::destroyDescriptorSet(ManagedDescriptorSet& set, uint32_t frame) {
|
||||
auto s = std::make_shared<ManagedDescriptorSet>(std::move(set));
|
||||
m_deletionQueue.push(frame, [&dpm = descriptorPoolManager, s]() mutable {
|
||||
dpm.free(*s);
|
||||
});
|
||||
}
|
||||
|
||||
void VulkanImpl::destroyPipeline(vk::raii::Pipeline& pipeline, vk::raii::PipelineLayout& layout)
|
||||
{
|
||||
auto p = std::make_shared<vk::raii::Pipeline>(std::move(pipeline));
|
||||
auto pl = std::make_shared<vk::raii::PipelineLayout>(std::move(layout));
|
||||
|
||||
m_deletionQueue.push(frameIndex, [p, pl]() mutable {
|
||||
p = nullptr;
|
||||
pl = nullptr;
|
||||
});
|
||||
}
|
||||
|
||||
void VulkanImpl::createDefaultTexture()
|
||||
{
|
||||
auto def = std::make_unique<CTexture>("");
|
||||
def.get()->initDefaultTexture();
|
||||
m_defaultTexture = def.get();
|
||||
CResourceAPI::resources().textures().add("default", std::move(def));
|
||||
}
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
#ifndef VULKANIMPL_HPP
|
||||
#define VULKANIMPL_HPP
|
||||
|
||||
#include "../GraphicsAPI.hpp"
|
||||
#include "DeletionQueue.hpp"
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
#include "VMABuffer.hpp"
|
||||
#include "vk_mem_alloc.h"
|
||||
#include "vulkan/vulkan.hpp"
|
||||
#include "ManagedDescriptorSet.hpp"
|
||||
|
||||
#include "../../Data/Texture/CTexture.hpp"
|
||||
|
||||
const std::vector<char const*> validationLayers = {
|
||||
"VK_LAYER_KHRONOS_validation"
|
||||
};
|
||||
|
||||
#ifdef NDEBUG
|
||||
constexpr bool enableValidationLayers = false;
|
||||
#else
|
||||
constexpr bool enableValidationLayers = true;
|
||||
#endif
|
||||
class DescriptorAllocator {
|
||||
struct Pool {
|
||||
vk::raii::DescriptorPool pool = nullptr;
|
||||
uint32_t capacity = 0;
|
||||
uint32_t allocated = 0;
|
||||
|
||||
bool isFull() const { return allocated >= capacity; }
|
||||
bool isEmpty() const { return allocated == 0; }
|
||||
};
|
||||
|
||||
vk::raii::Device* m_device = nullptr;
|
||||
uint32_t m_baseSize = 64;
|
||||
std::vector<Pool> m_pools;
|
||||
|
||||
Pool createPool(uint32_t size) {
|
||||
std::vector<vk::DescriptorPoolSize> sizes = {
|
||||
{vk::DescriptorType::eUniformBuffer, size * 2},
|
||||
{vk::DescriptorType::eCombinedImageSampler, size * 2},
|
||||
{vk::DescriptorType::eStorageBuffer, size * 2},
|
||||
};
|
||||
Pool p;
|
||||
p.capacity = size;
|
||||
p.pool = vk::raii::DescriptorPool(*m_device,
|
||||
vk::DescriptorPoolCreateInfo{
|
||||
vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet,
|
||||
size,
|
||||
static_cast<uint32_t>(sizes.size()),
|
||||
sizes.data()
|
||||
}
|
||||
);
|
||||
return p;
|
||||
}
|
||||
|
||||
Pool& getAvailablePool() {
|
||||
// cherche une pool non pleine
|
||||
for (auto& p : m_pools)
|
||||
if (!p.isFull()) return p;
|
||||
|
||||
//nouvelle pool x2
|
||||
uint32_t newSize = m_pools.empty()
|
||||
? m_baseSize
|
||||
: m_pools.back().capacity * 2;
|
||||
|
||||
return m_pools.emplace_back(createPool(newSize));
|
||||
}
|
||||
|
||||
public:
|
||||
void init(vk::raii::Device& device) { m_device = &device; }
|
||||
|
||||
ManagedDescriptorSet allocate(vk::DescriptorSetLayout layout) {
|
||||
auto& p = getAvailablePool();
|
||||
|
||||
vk::DescriptorSetAllocateInfo allocInfo{*p.pool, 1, &layout};
|
||||
auto sets = m_device->allocateDescriptorSets(allocInfo);
|
||||
p.allocated++;
|
||||
ManagedDescriptorSet mds;
|
||||
mds.set = std::move(sets[0]);
|
||||
mds.ownerPool = *p.pool;
|
||||
return mds;
|
||||
}
|
||||
|
||||
void free(ManagedDescriptorSet& man) {
|
||||
// retrouve la pool du set pour décrémenter
|
||||
VkDescriptorPool rawPool = man.ownerPool; // handle de la pool parente
|
||||
man.set = nullptr; // libère vk::raii free
|
||||
|
||||
for (auto it = m_pools.begin(); it != m_pools.end(); ++it) {
|
||||
if (*it->pool == rawPool) {
|
||||
it->allocated--;
|
||||
if (it->isEmpty())
|
||||
m_pools.erase(it);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
class VulkanImpl: public GraphicsAPI{
|
||||
private:
|
||||
vk::raii::Context context;
|
||||
vk::raii::Instance instance = nullptr;
|
||||
vk::raii::PhysicalDevice physicalDevice = nullptr;
|
||||
std::vector<const char *> requiredDeviceExtension = {
|
||||
vk::KHRSwapchainExtensionName};
|
||||
|
||||
vk::raii::Device device = nullptr;
|
||||
vk::raii::Queue graphicsQueue = nullptr;
|
||||
vk::raii::Queue presentQueue = nullptr;
|
||||
uint32_t queueIndex = ~0;
|
||||
vk::raii::SurfaceKHR surface = nullptr;
|
||||
|
||||
vk::raii::SwapchainKHR swapChain = nullptr;
|
||||
std::vector<vk::Image> swapChainImages;
|
||||
vk::SurfaceFormatKHR swapChainSurfaceFormat;
|
||||
vk::Extent2D swapChainExtent;
|
||||
std::vector<vk::raii::ImageView> swapChainImageViews;
|
||||
|
||||
vk::raii::CommandPool commandPool = nullptr;
|
||||
std::vector<vk::raii::CommandBuffer> commandBuffers;
|
||||
|
||||
std::vector<vk::raii::Semaphore> presentCompleteSemaphores;
|
||||
std::vector<vk::raii::Semaphore> renderFinishedSemaphores;
|
||||
std::vector<vk::raii::Fence> inFlightFences;
|
||||
uint32_t frameIndex = 0;
|
||||
SDL_Window* m_window;
|
||||
|
||||
bool framebufferResized = false;
|
||||
|
||||
VmaAllocator allocator = nullptr;
|
||||
|
||||
vk::raii::DescriptorSetLayout cameraLayout = nullptr; // set 0
|
||||
vk::raii::DescriptorSetLayout transformLayout = nullptr; // set 1
|
||||
vk::raii::DescriptorSetLayout materialLayout = nullptr; // set 2
|
||||
vk::raii::DescriptorSetLayout lightLayout = nullptr; // set 3
|
||||
|
||||
vk::raii::DescriptorSetLayout transform2DLayout = nullptr; // set 0
|
||||
vk::raii::DescriptorSetLayout material2DLayout = nullptr; // set 1
|
||||
vk::raii::DescriptorSetLayout projection2DLayout = nullptr; // set 2
|
||||
|
||||
|
||||
DescriptorAllocator descriptorPoolManager;
|
||||
vk::raii::PipelineLayout defaultPipelineLayoutInfo = nullptr;
|
||||
vk::raii::PipelineLayout default2DPipelineLayoutInfo = nullptr;
|
||||
|
||||
vk::raii::Image depthImage = nullptr;
|
||||
vk::raii::DeviceMemory depthImageMemory = nullptr;
|
||||
vk::raii::ImageView depthImageView = nullptr;
|
||||
|
||||
DeletionQueue m_deletionQueue;
|
||||
|
||||
CTexture* m_defaultTexture = nullptr;
|
||||
public:
|
||||
virtual ~VulkanImpl(){};
|
||||
void init(SDL_Window* window) override;
|
||||
void cleanup()override;
|
||||
void createInstance();
|
||||
void pickPhysicalDevice();
|
||||
void createLogicalDevice();
|
||||
void createSurface();
|
||||
void createSwapChain();
|
||||
void createImageViews();
|
||||
//void createGraphicsPipeline();
|
||||
void createCommandPool();
|
||||
void createCommandBuffer();
|
||||
void createSyncObjects();
|
||||
void drawFrame() override;
|
||||
void recreateSwapChain();
|
||||
void createDescriptorSetLayouts();
|
||||
void cleanupSwapChain();
|
||||
void createDepthResources();
|
||||
void createDescriptorPool();
|
||||
|
||||
void transitionImageLayout(vk::Image image, vk::ImageLayout old_layout, vk::ImageLayout new_layout, vk::AccessFlags2 src_access_mask, vk::AccessFlags2 dst_access_mask, vk::PipelineStageFlags2 src_stage_mask, vk::PipelineStageFlags2 dst_stage_mask, vk::ImageAspectFlags image_aspect_flags);
|
||||
void transitionImageLayout(vk::Image image, vk::ImageLayout oldLayout, vk::ImageLayout newLayout);
|
||||
void recordCommandBuffer(uint32_t imageIndex);
|
||||
void* getDevice()override {return &device;};
|
||||
uint32_t findMemoryType(uint32_t typeFilter, vk::MemoryPropertyFlags properties);
|
||||
vk::SurfaceFormatKHR& getSwapChainFormat(){return swapChainSurfaceFormat;};
|
||||
uint32_t getGraphicsQueueIndex() const { return queueIndex; }
|
||||
vk::Extent2D getSwapChainExtent() const { return swapChainExtent; }
|
||||
|
||||
vk::raii::CommandBuffer beginSingleTimeCommands();
|
||||
void endSingleTimeCommands(vk::raii::CommandBuffer& commandBuffer);
|
||||
|
||||
// accès au command buffer courant pour que le Renderer puisse enregistrer
|
||||
vk::raii::CommandBuffer& getCurrentCommandBuffer();
|
||||
|
||||
// accès à l'image view courante pour le color attachment
|
||||
vk::raii::ImageView& getCurrentSwapChainImageView();
|
||||
|
||||
// pour que le Renderer sache quelle frame est en cours
|
||||
uint32_t getCurrentFrameIndex() const { return frameIndex; }
|
||||
|
||||
VmaAllocator getAllocator() { return allocator; }
|
||||
vk::raii::PhysicalDevice& getPhysicalDevice() { return physicalDevice; }
|
||||
vk::raii::DescriptorSetLayout& getCameraLayout() { return cameraLayout; }
|
||||
vk::raii::DescriptorSetLayout& getTransformLayout() { return transformLayout; }
|
||||
vk::raii::DescriptorSetLayout& getMaterialLayout() { return materialLayout; }
|
||||
vk::raii::DescriptorSetLayout& getLightLayout() { return lightLayout; }
|
||||
|
||||
vk::raii::DescriptorSetLayout& getTransform2DLayout() { return transform2DLayout; }
|
||||
vk::raii::DescriptorSetLayout& getMaterial2DLayout() { return material2DLayout; }
|
||||
vk::raii::DescriptorSetLayout& getProjection2DLayout() { return projection2DLayout; }
|
||||
|
||||
vk::raii::ImageView createImageView(vk::raii::Image& image, vk::Format format, vk::ImageAspectFlags aspectFlags);
|
||||
|
||||
void copyBuffer(VkBuffer src, VkBuffer dst, VkDeviceSize size);
|
||||
|
||||
vk::Format findSupportedFormat(const std::vector<vk::Format>& candidates, vk::ImageTiling tiling, vk::FormatFeatureFlags features);
|
||||
vk::Format findDepthFormat();
|
||||
|
||||
bool hasStencilComponent(vk::Format format);
|
||||
void createImage(uint32_t width, uint32_t height, vk::Format format, vk::ImageTiling tiling, vk::ImageUsageFlags usage, vk::MemoryPropertyFlags properties, vk::raii::Image &image, vk::raii::DeviceMemory &imageMemory);
|
||||
|
||||
DescriptorAllocator& getDescriptorPoolManager(){return descriptorPoolManager;};
|
||||
|
||||
vk::raii::PipelineLayout& getDefaultPipelineLayout(){return defaultPipelineLayoutInfo;};
|
||||
vk::raii::PipelineLayout& getDefault2DPipelineLayout(){return default2DPipelineLayoutInfo;};
|
||||
|
||||
void copyBufferToImage(const vk::raii::Buffer &buffer, vk::raii::Image &image, uint32_t width, uint32_t height);
|
||||
|
||||
void destroyBuffer(VMABuffer& buffer, uint32_t frame);
|
||||
|
||||
// destruction d'un descriptor set
|
||||
void destroyDescriptorSet(ManagedDescriptorSet& set, uint32_t frame);
|
||||
|
||||
void destroyPipeline(vk::raii::Pipeline& pipeline, vk::raii::PipelineLayout& layout);
|
||||
|
||||
DeletionQueue& getDeletionQueue(){return m_deletionQueue;};
|
||||
|
||||
CTexture* getDefaultTexture() { return m_defaultTexture; }
|
||||
|
||||
void createDefaultTexture();
|
||||
};
|
||||
#endif
|
||||
@@ -0,0 +1,42 @@
|
||||
#include "CContext.hpp"
|
||||
#include "API/GraphicsAPI.hpp"
|
||||
#include <SDL3/SDL_init.h>
|
||||
#include <SDL3_image/SDL_image.h>
|
||||
|
||||
bool CContext::m_screenSaver = false;
|
||||
|
||||
void CContext::init(SDL_InitFlags sdlFlags) {
|
||||
// Log initialisation.
|
||||
initLog();
|
||||
|
||||
|
||||
// SDL Initialization.
|
||||
if (SDL_Init(sdlFlags)) {
|
||||
SDL_Quit();
|
||||
//HandleException(CLibException(std::string("Unable to initialize SDL: ") + SDL_GetError()), true);
|
||||
}
|
||||
|
||||
GraphicsAPI::initAPI();
|
||||
}
|
||||
|
||||
bool CContext::isScreenSaverEnable(void) {
|
||||
return m_screenSaver;
|
||||
}
|
||||
|
||||
void CContext::setScreenSaverEnable(bool newScreenSaver) {
|
||||
m_screenSaver = newScreenSaver;
|
||||
if (m_screenSaver) {
|
||||
SDL_EnableScreenSaver();
|
||||
}
|
||||
else {
|
||||
SDL_DisableScreenSaver();
|
||||
}
|
||||
}
|
||||
|
||||
void CContext::quit(void) {
|
||||
SDL_Quit();
|
||||
}
|
||||
|
||||
void CContext::initLog(void) {
|
||||
//todo
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#ifndef CCONTEXT_HPP
|
||||
#define CCONTEXT_HPP
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
#include <SDL3/SDL_init.h>
|
||||
#include <SDL3_image/SDL_image.h>
|
||||
|
||||
#define LOG_FILE "CosmicEngine_%3N.log"
|
||||
#define LOG_ROTATION_SIZE 1 * 1024 * 1024
|
||||
#define LOG_MAX_SIZE 50 * 1024 * 1024
|
||||
|
||||
class CContext {
|
||||
private:
|
||||
// Say if the screenSaver is enabled.
|
||||
static bool m_screenSaver;
|
||||
|
||||
public:
|
||||
CContext(void) = delete;
|
||||
|
||||
static void init(SDL_InitFlags sdlFlags);
|
||||
|
||||
static void quit(void);
|
||||
|
||||
static bool isScreenSaverEnable(void);
|
||||
|
||||
|
||||
static void setScreenSaverEnable(bool newScreenSaver);
|
||||
|
||||
private:
|
||||
|
||||
static void initLog(void);
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,337 @@
|
||||
#include "CModelLoader.hpp"
|
||||
#include <fstream>
|
||||
#include "Engine/Core/Systems/Graphics/API/GraphicsAPI.hpp"
|
||||
#include "Engine/Core/Systems/Resources/API/CResourceAPI.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/Data/Material/CMaterial2D.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/Data/Model/CModel2D.hpp"
|
||||
#include "nlohmann/json_fwd.hpp"
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
CModel* CModelLoader::loadModel(std::string fileName, const ModelLoadConfig& config)
|
||||
{
|
||||
auto& rm = CResourceAPI::resources();
|
||||
auto cached = rm.models().get(fileName);
|
||||
if (cached && !config.forceReload) {
|
||||
if (config.materialOverrides.empty())
|
||||
return cached.value();
|
||||
return cloneWithOverrides(cached.value(), fileName, config);
|
||||
}
|
||||
|
||||
Assimp::Importer importer;
|
||||
|
||||
const aiScene* scene = importer.ReadFile(fileName.c_str(),
|
||||
aiProcess_Triangulate |
|
||||
aiProcess_FlipUVs |
|
||||
aiProcess_CalcTangentSpace |
|
||||
aiProcess_GenNormals
|
||||
);
|
||||
|
||||
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
|
||||
throw std::runtime_error("Assimp: " + std::string(importer.GetErrorString()));
|
||||
|
||||
// dossier de base pour les textures relatives
|
||||
std::vector<MeshMaterial> meshMaterials;
|
||||
processNode(scene->mRootNode, scene, fileName, meshMaterials, config);
|
||||
|
||||
for (auto& [index, mat] : config.materialOverrides)
|
||||
{
|
||||
if (index < meshMaterials.size())
|
||||
meshMaterials[index].material = mat;
|
||||
}
|
||||
|
||||
// crée et enregistre le model
|
||||
auto model = std::make_unique<CModel>(meshMaterials);
|
||||
return rm.models().add(fileName, std::move(model));;
|
||||
}
|
||||
|
||||
CModel* CModelLoader::cloneWithOverrides(CModel* original,
|
||||
const std::string& originalKey,
|
||||
const ModelLoadConfig& config)
|
||||
{
|
||||
auto& rm = CResourceAPI::resources();
|
||||
|
||||
// clé unique pour ce clone
|
||||
std::string cloneKey = originalKey;
|
||||
for (auto& [index, mat] : config.materialOverrides)
|
||||
cloneKey += "_" + std::to_string(index) + "_" + std::to_string((size_t)mat);
|
||||
|
||||
auto cached = rm.models().get(cloneKey);
|
||||
if (cached) return cached.value();
|
||||
|
||||
// clone avec overrides
|
||||
auto meshMaterials = original->getMeshMaterials();
|
||||
for (auto& [index, mat] : config.materialOverrides)
|
||||
{
|
||||
if (index < meshMaterials.size())
|
||||
meshMaterials[index].material = mat;
|
||||
}
|
||||
|
||||
auto cloned = std::make_unique<CModel>(meshMaterials);
|
||||
return rm.models().add(cloneKey, std::move(cloned));
|
||||
}
|
||||
|
||||
|
||||
void CModelLoader::processNode(aiNode* node, const aiScene* scene, const std::string& directory, std::vector<MeshMaterial>& meshes, const ModelLoadConfig& config)
|
||||
{
|
||||
// process all the node's meshes (if any)
|
||||
for (uint32_t i = 0; i < node->mNumMeshes; i++) {
|
||||
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
|
||||
meshes.push_back(processMesh(mesh, scene, directory, config));
|
||||
}
|
||||
// then do the same for each of its children
|
||||
for (uint32_t i = 0; i < node->mNumChildren; i++) {
|
||||
processNode(node->mChildren[i], scene, directory, meshes, config);
|
||||
}
|
||||
}
|
||||
|
||||
MeshMaterial CModelLoader::processMesh(aiMesh* mesh, const aiScene* scene, const std::string& directory, const ModelLoadConfig& config)
|
||||
{
|
||||
auto& rm = CResourceAPI::resources();
|
||||
std::vector<SVertex> vertices;
|
||||
std::vector<uint32_t> indices;
|
||||
|
||||
// vertices
|
||||
for (uint32_t i = 0; i < mesh->mNumVertices; i++) {
|
||||
SVertex vertex{};
|
||||
vertex.m_position = {
|
||||
mesh->mVertices[i].x,
|
||||
mesh->mVertices[i].y,
|
||||
mesh->mVertices[i].z
|
||||
};
|
||||
vertex.m_normal = mesh->HasNormals() ?
|
||||
glm::vec3(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z) :
|
||||
glm::vec3(0.0f);
|
||||
|
||||
vertex.m_texCoords = mesh->mTextureCoords[0] ?
|
||||
glm::vec2(mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y) :
|
||||
glm::vec2(0.0f);
|
||||
|
||||
vertex.m_tangent = mesh->HasTangentsAndBitangents() ?
|
||||
glm::vec3(mesh->mTangents[i].x, mesh->mTangents[i].y, mesh->mTangents[i].z) :
|
||||
glm::vec3(0.0f);
|
||||
|
||||
vertex.m_bitangent = mesh->HasTangentsAndBitangents() ?
|
||||
glm::vec3(mesh->mBitangents[i].x, mesh->mBitangents[i].y, mesh->mBitangents[i].z) :
|
||||
glm::vec3(0.0f);
|
||||
|
||||
vertices.push_back(vertex);
|
||||
}
|
||||
|
||||
// indices
|
||||
for (uint32_t i = 0; i < mesh->mNumFaces; i++) {
|
||||
aiFace face = mesh->mFaces[i];
|
||||
for (uint32_t j = 0; j < face.mNumIndices; j++)
|
||||
indices.push_back(face.mIndices[j]);
|
||||
}
|
||||
|
||||
// crée et enregistre le mesh
|
||||
std::string meshKey = directory + "_mesh_" + std::to_string(rm.meshes().size());
|
||||
auto newMesh = std::make_unique<CMesh>();
|
||||
newMesh->setVertices(vertices);
|
||||
newMesh->setIndexes(indices);
|
||||
newMesh->load();
|
||||
CMesh* meshPtr = rm.meshes().add(meshKey, std::move(newMesh));
|
||||
|
||||
// material
|
||||
CMaterial* material = nullptr;
|
||||
if (mesh->mMaterialIndex >= 0) {
|
||||
material = processMaterial(
|
||||
scene->mMaterials[mesh->mMaterialIndex],
|
||||
directory,
|
||||
config
|
||||
);
|
||||
}
|
||||
return MeshMaterial{meshPtr, material};
|
||||
}
|
||||
|
||||
CMaterial* CModelLoader::processMaterial(aiMaterial* mat, const std::string& directory, const ModelLoadConfig& config)
|
||||
{
|
||||
auto& rm = CResourceAPI::resources();
|
||||
aiString aiName;
|
||||
mat->Get(AI_MATKEY_NAME, aiName);
|
||||
std::string matKey = directory + "_" + aiName.C_Str() + "_" + config.shaderName;
|
||||
|
||||
auto cached = rm.materials().get(matKey);
|
||||
if (cached) return cached.value();
|
||||
|
||||
// textures
|
||||
CTexture* albedo = nullptr;
|
||||
CTexture* normal = nullptr;
|
||||
|
||||
// albedo
|
||||
if (mat->GetTextureCount(aiTextureType_DIFFUSE) > 0) {
|
||||
aiString path;
|
||||
mat->GetTexture(aiTextureType_DIFFUSE, 0, &path);
|
||||
albedo = rm.textures().loadTexture(directory + "/" + path.C_Str());
|
||||
}
|
||||
|
||||
// normal
|
||||
if (mat->GetTextureCount(aiTextureType_NORMALS) > 0) {
|
||||
aiString path;
|
||||
mat->GetTexture(aiTextureType_NORMALS, 0, &path);
|
||||
normal = rm.textures().loadTexture(directory + "/" + path.C_Str());
|
||||
}
|
||||
|
||||
auto shader = CResourceAPI::resources().shaders().get(config.shaderName);
|
||||
|
||||
return rm.materials().createMaterial(matKey, static_cast<CShaderImplVulkan*>(shader), albedo, normal);
|
||||
}
|
||||
|
||||
|
||||
/*CTexture* CModelLoader::loadTexture(const std::string& directory, CResourceManager& rm)
|
||||
{
|
||||
auto text = rm.getTextureManager().get(directory);
|
||||
if(rm.getTextureManager().get(directory))
|
||||
{
|
||||
return text.value();
|
||||
}
|
||||
else {
|
||||
auto tex = std::make_unique<CTexture>(directory);
|
||||
tex->init();
|
||||
|
||||
auto* ptr = tex.get();
|
||||
rm.getTextureManager().addTexture(directory, std::move(tex));
|
||||
return ptr;
|
||||
}
|
||||
}*/
|
||||
|
||||
CosmicCore::CModel2D* CModelLoader::loadModel2D(std::string filename, const Model2DLoadConfig& config)
|
||||
{
|
||||
auto& rm = CResourceAPI::resources();
|
||||
|
||||
// Check cache first
|
||||
auto cached = rm.models2D().get(filename);
|
||||
if (cached) {
|
||||
return cached.value();
|
||||
}
|
||||
|
||||
// Load and parse JSON file
|
||||
std::ifstream file(filename);
|
||||
if (!file.is_open()) {
|
||||
throw std::runtime_error("Failed to open 2D model file: " + filename);
|
||||
}
|
||||
nlohmann::json jsonData = nlohmann::json::parse(file);
|
||||
|
||||
std::vector<MeshMaterial2D> meshMaterials;
|
||||
for(auto& mesh : jsonData["meshes"])
|
||||
{
|
||||
loadMesh2D(mesh, filename, meshMaterials, config);
|
||||
}
|
||||
|
||||
|
||||
// Create and register model2D
|
||||
auto model2D = std::make_unique<CModel2D>(meshMaterials);
|
||||
return rm.models2D().add(filename, std::move(model2D));
|
||||
}
|
||||
|
||||
void CModelLoader::loadMesh2D(nlohmann::json& mesh, std::string filename, std::vector<CosmicCore::MeshMaterial2D>& meshes, const Model2DLoadConfig& config)
|
||||
{
|
||||
auto& rm = CResourceAPI::resources();
|
||||
|
||||
// Parse vertices
|
||||
std::vector<Vertex2D> vertices;
|
||||
if (mesh.contains("vertices") && mesh["vertices"].is_array()) {
|
||||
for (const auto& v : mesh["vertices"]) {
|
||||
Vertex2D vertex;
|
||||
|
||||
// Position (required: x, y)
|
||||
vertex.m_position = glm::vec2(v["x"], v["y"]);
|
||||
|
||||
// TexCoords (optional, defaults to 0,0)
|
||||
if (v.contains("u") && v.contains("v")) {
|
||||
vertex.m_uv = glm::vec2(v["u"], v["v"]);
|
||||
} else {
|
||||
vertex.m_uv = glm::vec2(0.0f);
|
||||
}
|
||||
|
||||
// Color (optional, defaults to white)
|
||||
if (v.contains("r") && v.contains("g") && v.contains("b") && v.contains("a")) {
|
||||
vertex.m_color = glm::vec4(v["r"], v["g"], v["b"], v["a"]);
|
||||
} else {
|
||||
vertex.m_color = glm::vec4(1.0f);
|
||||
}
|
||||
|
||||
vertices.push_back(vertex);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse indices
|
||||
std::vector<uint32_t> indices;
|
||||
if (mesh.contains("indices") && mesh["indices"].is_array()) {
|
||||
for (const auto& i : mesh["indices"]) {
|
||||
indices.push_back(i.get<uint32_t>());
|
||||
}
|
||||
}
|
||||
|
||||
if (vertices.empty() || indices.empty()) {
|
||||
throw std::runtime_error("Invalid 2D model file: missing vertices or indices in " + filename);
|
||||
}
|
||||
|
||||
|
||||
// Create mesh key
|
||||
std::string meshKey = filename + "_" + std::to_string(meshes.size()) + "_mesh2d";
|
||||
|
||||
// Create and setup CMesh2D
|
||||
auto mesh2D = std::make_unique<CMesh2D>();
|
||||
mesh2D->setVertices(vertices);
|
||||
mesh2D->setIndexes(indices);
|
||||
mesh2D->load();
|
||||
|
||||
CMesh2D* meshPtr = rm.meshes2D().add(meshKey, std::move(mesh2D));
|
||||
CMaterial2D* matPtr = loadMaterial2D(mesh["material"], filename, config);
|
||||
meshes.push_back({meshPtr, matPtr});
|
||||
}
|
||||
|
||||
CosmicCore::CMaterial2D* CModelLoader::loadMaterial2D(nlohmann::json& material, std::string filename, const Model2DLoadConfig& config)
|
||||
{
|
||||
auto& rm = CResourceAPI::resources();
|
||||
|
||||
// Create material2D
|
||||
CMaterial2D* material2D = nullptr;
|
||||
|
||||
|
||||
std::string matKey = filename + "_mat2d";
|
||||
auto cachedMat = rm.materials2D().get(matKey);
|
||||
|
||||
if (!cachedMat) {
|
||||
auto mat = std::make_unique<CMaterial2D>();
|
||||
|
||||
// Parse material from JSON
|
||||
if (material.contains("material")) {
|
||||
auto& matJson = material["material"];
|
||||
|
||||
if (matJson.contains("color")) {
|
||||
auto& color = matJson["color"];
|
||||
mat->m_color = glm::vec4(
|
||||
color.value("r", 1.0f),
|
||||
color.value("g", 1.0f),
|
||||
color.value("b", 1.0f),
|
||||
color.value("a", 1.0f)
|
||||
);
|
||||
}
|
||||
|
||||
if (matJson.contains("alpha_blend")) {
|
||||
mat->m_alphaBlend = matJson["alpha_blend"].get<bool>();
|
||||
}
|
||||
|
||||
if (matJson.contains("texture")) {
|
||||
std::string texPath = matJson["texture"];
|
||||
mat->m_texture = rm.textures().loadTexture(texPath);
|
||||
}
|
||||
}
|
||||
|
||||
// Get shader from config
|
||||
auto shader = rm.shaders().get(config.shaderName);
|
||||
if (!shader) {
|
||||
throw std::runtime_error("Shader not found: " + config.shaderName);
|
||||
}
|
||||
mat->shader = static_cast<CShaderImplVulkan*>(shader);
|
||||
mat->build();
|
||||
|
||||
material2D = rm.materials2D().add(matKey, std::move(mat));
|
||||
} else {
|
||||
material2D = cachedMat.value();
|
||||
}
|
||||
return material2D;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
#ifndef CMODELLOADER_HPP
|
||||
#define CMODELLOADER_HPP
|
||||
|
||||
|
||||
#include <assimp/Importer.hpp>
|
||||
#include <assimp/scene.h>
|
||||
#include <assimp/postprocess.h>
|
||||
|
||||
#include "Engine/Core/Systems/Graphics/Data/Material/CMaterial2D.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/Data/Model/CModel2D.hpp"
|
||||
#include "Model/CModel.hpp"
|
||||
#include "Texture/CTexture.hpp"
|
||||
#include "nlohmann/json_fwd.hpp"
|
||||
|
||||
struct ModelLoadConfig {
|
||||
std::string shaderName = "triangle";
|
||||
// override des materials par index de mesh
|
||||
std::unordered_map<uint32_t, CMaterial*> materialOverrides;
|
||||
// si true, recharge même si déjà en cache
|
||||
bool forceReload = false;
|
||||
};
|
||||
|
||||
struct Model2DLoadConfig {
|
||||
std::string shaderName = "ui";
|
||||
// override des materials par index de mesh
|
||||
//std::unordered_map<uint32_t, CosmicCore::CMaterial2D*> materialOverrides;
|
||||
// si true, recharge même si déjà en cache
|
||||
//bool forceReload = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Class allowing to load models from obj files.
|
||||
*/
|
||||
class CModelLoader {
|
||||
private:
|
||||
/**
|
||||
* @brief Compute every node in the loaded meshes.
|
||||
* @param[in] node The assimp created node.
|
||||
* @param[in] scene The assimp created scene.
|
||||
* @param[in] meshes The mesh list.
|
||||
* @param[in] material A pointer to a material. It's optionnal and override the obj's material.
|
||||
*/
|
||||
static void processNode(aiNode* node, const aiScene* scene, const std::string& directory, std::vector<MeshMaterial>& meshes, const ModelLoadConfig& config);
|
||||
|
||||
/**
|
||||
* @brief Compute every meshes.
|
||||
* @param[in] mesh The assimp created mesh.
|
||||
* @param[in] scene The assimp created scene.
|
||||
* @param[in] meshes The list of meshes.
|
||||
* @param[in] material A pointer to a material. It's optionnal and override the obj's material.
|
||||
*/
|
||||
static MeshMaterial processMesh(aiMesh* mesh, const aiScene* scene, const std::string& directory, const ModelLoadConfig& config);
|
||||
|
||||
/**
|
||||
* @brief Load Textures from the obj file.
|
||||
* @param[in] mat The assimp created material.
|
||||
* @param[in] type The assimp's texture type.
|
||||
* @param[in] typeName The texture's type.
|
||||
*/
|
||||
static CTexture* loadTexture(const std::string& directory);
|
||||
|
||||
static CMaterial* processMaterial(aiMaterial* mat, const std::string& directory, const ModelLoadConfig& config);
|
||||
|
||||
static CModel* cloneWithOverrides(CModel* original, const std::string& originalKey, const ModelLoadConfig& config);
|
||||
|
||||
static void loadMesh2D(nlohmann::json& mesh, std::string filename, std::vector<CosmicCore::MeshMaterial2D>& meshes, const Model2DLoadConfig& config = {});
|
||||
static CosmicCore::CMaterial2D* loadMaterial2D(nlohmann::json& material, std::string filename, const Model2DLoadConfig& config = {});
|
||||
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief main function of the class, starts loading the obj file.
|
||||
* @param[in] fileName Path to the OBJ file.
|
||||
* @param[in] material Pointer to a material. It's optionnal and override the obj's material.
|
||||
* @return A dynamically allocated CModel.
|
||||
*/
|
||||
static CModel* loadModel(std::string filename, const ModelLoadConfig& config = {});
|
||||
static CosmicCore::CModel2D* loadModel2D(std::string filename, const Model2DLoadConfig& config = {});
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,77 @@
|
||||
// CFont.cpp
|
||||
#include "CFont.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/Data/Texture/CTexture.hpp"
|
||||
#include "Engine/Core/Systems/Resources/API/CResourceAPI.hpp"
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
void CFont::init(const std::string& jsonPath, const std::string& atlasPath) {
|
||||
// charge l'atlas comme texture
|
||||
auto& rm = CResourceAPI::resources().textures();
|
||||
m_atlas = rm.loadTexture(atlasPath, TextureType::MSDFFont);
|
||||
|
||||
// parse le JSON
|
||||
std::ifstream file(jsonPath);
|
||||
if (!file.good())
|
||||
throw std::runtime_error("Font JSON not found: " + jsonPath);
|
||||
|
||||
nlohmann::json j = nlohmann::json::parse(file);
|
||||
|
||||
// métriques globales
|
||||
if (j.contains("metrics")) {
|
||||
auto& m = j["metrics"];
|
||||
m_metrics.emSize = m.value("emSize", 1.0f);
|
||||
m_metrics.lineHeight = m.value("lineHeight", 1.0f);
|
||||
m_metrics.ascender = m.value("ascender", 1.0f);
|
||||
m_metrics.descender = m.value("descender", 0.0f);
|
||||
}
|
||||
|
||||
// dimensions de l'atlas
|
||||
if (j.contains("atlas")) {
|
||||
m_atlasWidth = j["atlas"].value("width", 512u);
|
||||
m_atlasHeight = j["atlas"].value("height", 512u);
|
||||
}
|
||||
|
||||
// glyphes
|
||||
if (!j.contains("glyphs")) return;
|
||||
|
||||
for (auto& g : j["glyphs"]) {
|
||||
SGlyph glyph{};
|
||||
glyph.unicode = g.value("unicode", 0u);
|
||||
glyph.advance = g.value("advance", 0.0f);
|
||||
|
||||
if (g.contains("atlasBounds")) {
|
||||
auto& ab = g["atlasBounds"];
|
||||
float atlasW = (float)m_atlasWidth;
|
||||
float atlasH = (float)m_atlasHeight;
|
||||
glyph.atlasMin = {ab["left"].get<float>() / atlasW,
|
||||
ab["bottom"].get<float>() / atlasH};
|
||||
glyph.atlasMax = {ab["right"].get<float>() / atlasW,
|
||||
ab["top"].get<float>() / atlasH};
|
||||
}
|
||||
|
||||
if (g.contains("planeBounds")) {
|
||||
auto& pb = g["planeBounds"];
|
||||
glyph.planeMin = {pb["left"].get<float>(),
|
||||
pb["bottom"].get<float>()};
|
||||
glyph.planeMax = {pb["right"].get<float>(),
|
||||
pb["top"].get<float>()};
|
||||
}
|
||||
|
||||
m_glyphs[glyph.unicode] = glyph;
|
||||
}
|
||||
}
|
||||
|
||||
const SGlyph* CFont::getGlyph(uint32_t unicode) const {
|
||||
auto it = m_glyphs.find(unicode);
|
||||
if (it != m_glyphs.end()) return &it->second;
|
||||
// fallback sur '?' si le glyphe n'existe pas
|
||||
auto fallback = m_glyphs.find('?');
|
||||
if (fallback != m_glyphs.end()) return &fallback->second;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
} // namespace CosmicCore
|
||||
@@ -0,0 +1,57 @@
|
||||
#ifndef CFONT_HPP
|
||||
#define CFONT_HPP
|
||||
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <glm/glm.hpp>
|
||||
#include "../Texture/CTexture.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
struct SGlyph {
|
||||
uint32_t unicode;
|
||||
float advance; // largeur pour avancer le curseur
|
||||
|
||||
// position dans l'atlas (UV)
|
||||
glm::vec2 atlasMin; // UV coin bas-gauche
|
||||
glm::vec2 atlasMax; // UV coin haut-droit
|
||||
|
||||
// position relative au curseur (plane bounds)
|
||||
glm::vec2 planeMin; // offset bas-gauche
|
||||
glm::vec2 planeMax; // offset haut-droit
|
||||
};
|
||||
|
||||
struct SFontMetrics {
|
||||
float emSize = 1.0f;
|
||||
float lineHeight = 1.0f;
|
||||
float ascender = 1.0f;
|
||||
float descender = 0.0f;
|
||||
};
|
||||
|
||||
class CFont {
|
||||
std::unordered_map<uint32_t, SGlyph> m_glyphs;
|
||||
CTexture* m_atlas;
|
||||
SFontMetrics m_metrics;
|
||||
uint32_t m_atlasWidth = 0;
|
||||
uint32_t m_atlasHeight = 0;
|
||||
|
||||
public:
|
||||
CFont() = default;
|
||||
~CFont() = default;
|
||||
|
||||
CFont(const CFont&) = delete;
|
||||
CFont& operator=(const CFont&) = delete;
|
||||
CFont(CFont&&) = default;
|
||||
CFont& operator=(CFont&&) = default;
|
||||
|
||||
void init(const std::string& jsonPath, const std::string& atlasPath);
|
||||
|
||||
const SGlyph* getGlyph(uint32_t unicode) const;
|
||||
CTexture* getAtlas() const { return m_atlas; }
|
||||
SFontMetrics getMetrics() const { return m_metrics; }
|
||||
uint32_t getAtlasWidth() const { return m_atlasWidth; }
|
||||
uint32_t getAtlasHeight() const { return m_atlasHeight; }
|
||||
};
|
||||
|
||||
} // namespace CosmicCore
|
||||
#endif
|
||||
@@ -0,0 +1,73 @@
|
||||
#include "CLightsBuffer.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp"
|
||||
|
||||
namespace CosmicCore {
|
||||
void CLightsBuffer::init() {
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
auto* device = static_cast<vk::raii::Device*>(api->getDevice());
|
||||
|
||||
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
||||
// SSBO
|
||||
VkBufferCreateInfo bufferInfo{};
|
||||
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
bufferInfo.size = sizeof(SLightsUBOData);
|
||||
bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
|
||||
|
||||
VmaAllocationCreateInfo allocInfo{};
|
||||
allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
|
||||
allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
|
||||
|
||||
VmaAllocationInfo info{};
|
||||
vmaCreateBuffer(api->getAllocator(), &bufferInfo, &allocInfo,
|
||||
&m_buffers[i].buffer,
|
||||
&m_buffers[i].allocation,
|
||||
&info);
|
||||
m_mappedData[i] = info.pMappedData;
|
||||
|
||||
// descriptor set (set 3)
|
||||
m_descriptorSets[i] = api->getDescriptorPoolManager().allocate(
|
||||
*api->getLightLayout()
|
||||
);
|
||||
|
||||
vk::DescriptorBufferInfo descriptorBufferInfo{
|
||||
vk::Buffer(m_buffers[i].buffer),
|
||||
0,
|
||||
sizeof(SLightsUBOData)
|
||||
};
|
||||
vk::WriteDescriptorSet descriptorWrite{
|
||||
*m_descriptorSets[i].set,
|
||||
0, 0, 1,
|
||||
vk::DescriptorType::eStorageBuffer,
|
||||
{}, &descriptorBufferInfo
|
||||
};
|
||||
device->updateDescriptorSets(descriptorWrite, {});
|
||||
}
|
||||
m_initialized = true;
|
||||
}
|
||||
|
||||
void CLightsBuffer::update(uint32_t frameIndex, const SLightsUBOData& data) {
|
||||
if (!m_initialized) return;
|
||||
memcpy(m_mappedData[frameIndex], &data, sizeof(SLightsUBOData));
|
||||
}
|
||||
|
||||
void CLightsBuffer::destroy() {
|
||||
if (!m_initialized) return;
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
|
||||
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
||||
api->getDeletionQueue().push(api->getCurrentFrameIndex(),
|
||||
[alloc = api->getAllocator(),
|
||||
buf = m_buffers[i].buffer,
|
||||
mem = m_buffers[i].allocation]() {
|
||||
vmaDestroyBuffer(alloc, buf, mem);
|
||||
});
|
||||
api->destroyDescriptorSet(m_descriptorSets[i],
|
||||
api->getCurrentFrameIndex());
|
||||
}
|
||||
m_initialized = false;
|
||||
}
|
||||
|
||||
vk::raii::DescriptorSet& CLightsBuffer::getDescriptorSet(uint32_t frameIndex) {
|
||||
return m_descriptorSets[frameIndex].set;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// CLightsBuffer.hpp
|
||||
#ifndef CLIGHTSBUFFER_HPP
|
||||
#define CLIGHTSBUFFER_HPP
|
||||
|
||||
#include <array>
|
||||
#include <glm/glm.hpp>
|
||||
#include "../../API/VulkanImplementation/VMABuffer.hpp"
|
||||
#include "../../API/VulkanImplementation/ManagedDescriptorSet.hpp"
|
||||
|
||||
constexpr uint32_t MAX_LIGHTS = 32;
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
struct SLightData {
|
||||
glm::vec4 position; // xyz = pos, w = type (0=dir, 1=point, 2=spot)
|
||||
glm::vec4 direction; // xyz = dir, w = range
|
||||
glm::vec4 color; // xyz = color, w = intensity
|
||||
float innerCosAngle;
|
||||
float outerCosAngle;
|
||||
float attenuation;
|
||||
float padding; // alignement 16 bytes
|
||||
};
|
||||
|
||||
struct SLightsUBOData {
|
||||
SLightData lights[MAX_LIGHTS];
|
||||
int lightCount = 0;
|
||||
//glm::vec3 padding;
|
||||
};
|
||||
|
||||
class CLightsBuffer {
|
||||
std::array<VMABuffer, MAX_FRAMES_IN_FLIGHT> m_buffers;
|
||||
std::array<void*, MAX_FRAMES_IN_FLIGHT> m_mappedData{};
|
||||
std::array<ManagedDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_descriptorSets;
|
||||
bool m_initialized = false;
|
||||
|
||||
public:
|
||||
CLightsBuffer() = default;
|
||||
~CLightsBuffer() { }//destroy(); }
|
||||
|
||||
CLightsBuffer(const CLightsBuffer&) = delete;
|
||||
CLightsBuffer& operator=(const CLightsBuffer&) = delete;
|
||||
CLightsBuffer(CLightsBuffer&&) = default;
|
||||
CLightsBuffer& operator=(CLightsBuffer&&) = default;
|
||||
|
||||
void init();
|
||||
|
||||
void update(uint32_t frameIndex, const SLightsUBOData& data);
|
||||
|
||||
void destroy();
|
||||
|
||||
vk::raii::DescriptorSet& getDescriptorSet(uint32_t frameIndex);
|
||||
};
|
||||
|
||||
} // namespace CosmicCore
|
||||
#endif
|
||||
@@ -0,0 +1,137 @@
|
||||
#include "CMaterial.hpp"
|
||||
#include "../Mesh/SVertex.hpp"
|
||||
#include "../../API/VulkanImplementation/VulkanImpl.hpp"
|
||||
#include <vulkan/vulkan_core.h>
|
||||
|
||||
void CMaterial::build()
|
||||
{
|
||||
if(isInit)
|
||||
{
|
||||
destroy();
|
||||
}
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
auto* device= static_cast<vk::raii::Device*>(api->getDevice());
|
||||
auto shaderStages = shader->getShaderStages(0, vk::ShaderStageFlagBits::eVertex, vk::ShaderStageFlagBits::eFragment);
|
||||
|
||||
auto bindingDescription = Vertex::getBindingDescription();
|
||||
auto attributeDescriptions = Vertex::getAttributeDescriptions();
|
||||
vk::PipelineVertexInputStateCreateInfo vertexInputInfo{{}, 1, &bindingDescription, static_cast<uint32_t>(attributeDescriptions.size()), attributeDescriptions.data()};
|
||||
|
||||
vk::PipelineInputAssemblyStateCreateInfo inputAssembly{{},vk::PrimitiveTopology::eTriangleList};
|
||||
vk::PipelineViewportStateCreateInfo viewportState{{},1, {},1};
|
||||
|
||||
vk::PipelineRasterizationStateCreateInfo rasterizer{{},vk::False, vk::False, vk::PolygonMode::eFill,vk::CullModeFlagBits::eBack, vk::FrontFace::eCounterClockwise, vk::False, {}, {}, 1.0f, 1.0f};
|
||||
|
||||
vk::PipelineMultisampleStateCreateInfo multisampling{{}, vk::SampleCountFlagBits::e1, vk::False};
|
||||
|
||||
vk::PipelineColorBlendAttachmentState colorBlendAttachment{vk::False, {}, {}, {}, {}, {}, {}, vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA};
|
||||
|
||||
vk::PipelineColorBlendStateCreateInfo colorBlending{{},vk::False, vk::LogicOp::eCopy, 1, &colorBlendAttachment};
|
||||
|
||||
vk::PipelineDepthStencilStateCreateInfo depthStencil{{},
|
||||
vk::True,
|
||||
vk::True,
|
||||
vk::CompareOp::eLess,
|
||||
vk::False,
|
||||
vk::False};
|
||||
|
||||
std::vector dynamicStates = {
|
||||
vk::DynamicState::eViewport,
|
||||
vk::DynamicState::eScissor};
|
||||
vk::PipelineDynamicStateCreateInfo dynamicState{{}, static_cast<uint32_t>(dynamicStates.size()), dynamicStates.data()};
|
||||
|
||||
std::array<vk::DescriptorSetLayout, 4> layouts{
|
||||
*api->getCameraLayout(), // set 0
|
||||
*api->getTransformLayout(), // set 1
|
||||
*api->getMaterialLayout(), // set 2
|
||||
*api->getLightLayout() //set 3
|
||||
};
|
||||
|
||||
vk::PipelineLayoutCreateInfo pipelineLayoutInfo{{},4,layouts.data(), 0};
|
||||
|
||||
pipelineLayout = vk::raii::PipelineLayout(*static_cast<vk::raii::Device*>(api->getDevice()), pipelineLayoutInfo);
|
||||
|
||||
vk::StructureChain<vk::GraphicsPipelineCreateInfo, vk::PipelineRenderingCreateInfo> pipelineCreateInfoChain = {
|
||||
{{},
|
||||
2,
|
||||
shaderStages.data(),
|
||||
&vertexInputInfo,
|
||||
&inputAssembly,
|
||||
{},
|
||||
&viewportState,
|
||||
&rasterizer,
|
||||
&multisampling,
|
||||
&depthStencil,
|
||||
&colorBlending,
|
||||
&dynamicState,
|
||||
pipelineLayout,
|
||||
nullptr
|
||||
},
|
||||
{{},
|
||||
1,
|
||||
&api->getSwapChainFormat().format,
|
||||
api->findDepthFormat()
|
||||
}
|
||||
};
|
||||
|
||||
pipeline = vk::raii::Pipeline(*static_cast<vk::raii::Device*>(api->getDevice()), nullptr, pipelineCreateInfoChain.get<vk::GraphicsPipelineCreateInfo>());
|
||||
|
||||
// descriptor sets du material (set 2)
|
||||
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
||||
m_descriptorSets[i] = api->getDescriptorPoolManager().allocate(
|
||||
*api->getMaterialLayout()
|
||||
);
|
||||
|
||||
std::vector<vk::WriteDescriptorSet> writes;
|
||||
|
||||
// binding 1 : albedo (si présent)
|
||||
vk::DescriptorImageInfo albedoInfo;
|
||||
if (textureAlbedo) {
|
||||
albedoInfo = {
|
||||
*textureAlbedo->getSampler(),
|
||||
*textureAlbedo->getImageView(),
|
||||
vk::ImageLayout::eShaderReadOnlyOptimal
|
||||
};
|
||||
writes.push_back({
|
||||
*m_descriptorSets[i].set,
|
||||
1, 0, 1,
|
||||
vk::DescriptorType::eCombinedImageSampler,
|
||||
&albedoInfo
|
||||
});
|
||||
}
|
||||
else {
|
||||
albedoInfo = {
|
||||
api->getDefaultTexture()->getSampler(),
|
||||
api->getDefaultTexture()->getImageView(),
|
||||
vk::ImageLayout::eShaderReadOnlyOptimal
|
||||
};
|
||||
writes.push_back({
|
||||
*m_descriptorSets[i].set,
|
||||
1, 0, 1,
|
||||
vk::DescriptorType::eCombinedImageSampler,
|
||||
&albedoInfo
|
||||
});
|
||||
}
|
||||
|
||||
if (!writes.empty())
|
||||
device->updateDescriptorSets(writes, {});
|
||||
}
|
||||
isInit = true;
|
||||
}
|
||||
|
||||
CMaterial::~CMaterial()
|
||||
{
|
||||
destroy();
|
||||
}
|
||||
|
||||
void CMaterial::destroy()
|
||||
{
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
|
||||
api->destroyPipeline(pipeline, pipelineLayout);
|
||||
|
||||
// descriptor sets
|
||||
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
||||
api->destroyDescriptorSet(m_descriptorSets[i], i);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#ifndef SMATERIAL_HPP
|
||||
#define SMATERIAL_HPP
|
||||
|
||||
#include "../../Shader/Implementations/CShaderImplVulkan.hpp"
|
||||
#include "../../API/VulkanImplementation/ManagedDescriptorSet.hpp"
|
||||
#include "../Texture/CTexture.hpp"
|
||||
|
||||
class CMaterial {
|
||||
public:
|
||||
|
||||
~CMaterial();
|
||||
void destroy();
|
||||
bool isInit = false;
|
||||
CTexture* textureAlbedo = nullptr;
|
||||
CTexture* textureNormal = nullptr;
|
||||
CShaderImplVulkan* shader;
|
||||
vk::raii::PipelineLayout pipelineLayout = nullptr;
|
||||
vk::raii::Pipeline pipeline = nullptr;
|
||||
std::array<ManagedDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_descriptorSets;
|
||||
void build();
|
||||
vk::raii::Pipeline& getPipeline(){return pipeline;};
|
||||
vk::raii::PipelineLayout& getPipelineLayout(){return pipelineLayout;};
|
||||
vk::raii::DescriptorSet& getDescriptorSet(uint32_t frameIndex) {
|
||||
return m_descriptorSets[frameIndex].set;
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,157 @@
|
||||
#include "CMaterial2D.hpp"
|
||||
#include "Engine/Core/Systems/Resources/API/CResourceAPI.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/Shader/Implementations/CShaderImplVulkan.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp"
|
||||
#include <glm/gtc/matrix_transform.hpp>
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
void CMaterial2D::build() {
|
||||
|
||||
if(isInit)
|
||||
{
|
||||
destroy();
|
||||
}
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
auto* device= static_cast<vk::raii::Device*>(api->getDevice());
|
||||
auto shaderStages = shader->getShaderStages(0, vk::ShaderStageFlagBits::eVertex, vk::ShaderStageFlagBits::eFragment);
|
||||
|
||||
auto bindingDescription = Vertex2D::getBindingDescription();
|
||||
auto attributeDescriptions = Vertex2D::getAttributeDescriptions();
|
||||
vk::PipelineVertexInputStateCreateInfo vertexInputInfo{{}, 1, &bindingDescription, static_cast<uint32_t>(attributeDescriptions.size()), attributeDescriptions.data()};
|
||||
|
||||
vk::PipelineInputAssemblyStateCreateInfo inputAssembly{{},vk::PrimitiveTopology::eTriangleList};
|
||||
vk::PipelineViewportStateCreateInfo viewportState{{},1, {},1};
|
||||
|
||||
vk::PipelineRasterizationStateCreateInfo rasterizer{{},vk::False, vk::False, vk::PolygonMode::eFill,vk::CullModeFlagBits::eNone, vk::FrontFace::eCounterClockwise, vk::False, {}, {}, 1.0f, 1.0f};
|
||||
|
||||
vk::PipelineMultisampleStateCreateInfo multisampling{{}, vk::SampleCountFlagBits::e1, vk::False};
|
||||
|
||||
vk::PipelineColorBlendAttachmentState colorBlendAttachment{
|
||||
vk::True,
|
||||
vk::BlendFactor::eSrcAlpha,
|
||||
vk::BlendFactor::eOneMinusSrcAlpha,
|
||||
vk::BlendOp::eAdd,
|
||||
vk::BlendFactor::eOne,
|
||||
vk::BlendFactor::eZero,
|
||||
vk::BlendOp::eAdd,
|
||||
vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA};
|
||||
|
||||
vk::PipelineColorBlendStateCreateInfo colorBlending{{},vk::False, vk::LogicOp::eCopy, 1, &colorBlendAttachment};
|
||||
|
||||
vk::PipelineDepthStencilStateCreateInfo depthStencil{{},
|
||||
vk::False,
|
||||
vk::False,
|
||||
vk::CompareOp::eAlways,
|
||||
vk::False,
|
||||
vk::False};
|
||||
|
||||
std::vector dynamicStates = {
|
||||
vk::DynamicState::eViewport,
|
||||
vk::DynamicState::eScissor};
|
||||
vk::PipelineDynamicStateCreateInfo dynamicState{{}, static_cast<uint32_t>(dynamicStates.size()), dynamicStates.data()};
|
||||
|
||||
std::array<vk::DescriptorSetLayout, 3> layouts{
|
||||
*api->getTransform2DLayout(), // set 0
|
||||
*api->getMaterial2DLayout(), // set 1
|
||||
*api->getProjection2DLayout(), // set 2
|
||||
|
||||
};
|
||||
|
||||
vk::PipelineLayoutCreateInfo pipelineLayoutInfo{{},3,layouts.data(), 0};
|
||||
|
||||
pipelineLayout = vk::raii::PipelineLayout(*static_cast<vk::raii::Device*>(api->getDevice()), pipelineLayoutInfo);
|
||||
|
||||
vk::StructureChain<vk::GraphicsPipelineCreateInfo, vk::PipelineRenderingCreateInfo> pipelineCreateInfoChain = {
|
||||
{{},
|
||||
2,
|
||||
shaderStages.data(),
|
||||
&vertexInputInfo,
|
||||
&inputAssembly,
|
||||
{},
|
||||
&viewportState,
|
||||
&rasterizer,
|
||||
&multisampling,
|
||||
&depthStencil,
|
||||
&colorBlending,
|
||||
&dynamicState,
|
||||
pipelineLayout,
|
||||
nullptr
|
||||
},
|
||||
{{},
|
||||
1,
|
||||
&api->getSwapChainFormat().format,
|
||||
api->findDepthFormat()
|
||||
}
|
||||
};
|
||||
|
||||
pipeline = vk::raii::Pipeline(*static_cast<vk::raii::Device*>(api->getDevice()), nullptr, pipelineCreateInfoChain.get<vk::GraphicsPipelineCreateInfo>());
|
||||
|
||||
// descriptor sets du material (set 2)
|
||||
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
||||
m_descriptorSets[i] = api->getDescriptorPoolManager().allocate(
|
||||
*api->getMaterial2DLayout()
|
||||
);
|
||||
|
||||
std::vector<vk::WriteDescriptorSet> writes;
|
||||
|
||||
// binding 1 : albedo (si présent)
|
||||
vk::DescriptorImageInfo albedoInfo;
|
||||
if (m_texture) {
|
||||
albedoInfo = {
|
||||
*m_texture->getSampler(),
|
||||
*m_texture->getImageView(),
|
||||
vk::ImageLayout::eShaderReadOnlyOptimal
|
||||
};
|
||||
writes.push_back({
|
||||
*m_descriptorSets[i].set,
|
||||
1, 0, 1,
|
||||
vk::DescriptorType::eCombinedImageSampler,
|
||||
&albedoInfo
|
||||
});
|
||||
}
|
||||
else if (m_font) {
|
||||
albedoInfo = {
|
||||
*m_font->getAtlas()->getSampler(),
|
||||
*m_font->getAtlas()->getImageView(),
|
||||
vk::ImageLayout::eShaderReadOnlyOptimal
|
||||
};
|
||||
writes.push_back({
|
||||
*m_descriptorSets[i].set,
|
||||
1, 0, 1,
|
||||
vk::DescriptorType::eCombinedImageSampler,
|
||||
&albedoInfo
|
||||
});
|
||||
}
|
||||
else {
|
||||
albedoInfo = {
|
||||
api->getDefaultTexture()->getSampler(),
|
||||
api->getDefaultTexture()->getImageView(),
|
||||
vk::ImageLayout::eShaderReadOnlyOptimal
|
||||
};
|
||||
writes.push_back({
|
||||
*m_descriptorSets[i].set,
|
||||
1, 0, 1,
|
||||
vk::DescriptorType::eCombinedImageSampler,
|
||||
&albedoInfo
|
||||
});
|
||||
}
|
||||
|
||||
if (!writes.empty())
|
||||
device->updateDescriptorSets(writes, {});
|
||||
}
|
||||
isInit = true;
|
||||
}
|
||||
|
||||
void CMaterial2D::destroy() {
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
|
||||
api->destroyPipeline(pipeline, pipelineLayout);
|
||||
|
||||
// descriptor sets
|
||||
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
||||
api->destroyDescriptorSet(m_descriptorSets[i], i);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace CosmicCore
|
||||
@@ -0,0 +1,48 @@
|
||||
#ifndef CUIPIPELINE_HPP
|
||||
#define CUIPIPELINE_HPP
|
||||
|
||||
#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/Constants.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/ManagedDescriptorSet.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/Data/Font/CFont.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/Data/Texture/CTexture.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/Shader/Implementations/CShaderImplVulkan.hpp"
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
namespace CosmicCore {
|
||||
|
||||
class CMaterial2D {
|
||||
private:
|
||||
|
||||
|
||||
public:
|
||||
glm::vec4 m_color = {1, 1, 1, 1};
|
||||
CTexture* m_texture = nullptr;
|
||||
CFont* m_font = nullptr;
|
||||
bool m_alphaBlend = true;
|
||||
|
||||
bool isInit = false;
|
||||
CTexture* texture = nullptr;
|
||||
CShaderImplVulkan* shader;
|
||||
vk::raii::PipelineLayout pipelineLayout = nullptr;
|
||||
vk::raii::Pipeline pipeline = nullptr;
|
||||
std::array<ManagedDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_descriptorSets;
|
||||
void build();
|
||||
void destroy();
|
||||
|
||||
vk::raii::Pipeline& getPipeline() { return pipeline; }
|
||||
vk::raii::PipelineLayout& getPipelineLayout() { return pipelineLayout; }
|
||||
vk::raii::DescriptorSet& getDescriptorSet(uint32_t frameIndex) {
|
||||
return m_descriptorSets[frameIndex].set;
|
||||
}
|
||||
|
||||
CMaterial2D() = default;
|
||||
~CMaterial2D() { destroy(); }
|
||||
|
||||
CMaterial2D(CMaterial2D&&) = default;
|
||||
CMaterial2D& operator=(CMaterial2D&&) = default;
|
||||
CMaterial2D(const CMaterial2D&) = delete;
|
||||
CMaterial2D& operator=(const CMaterial2D&) = delete;
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,39 @@
|
||||
#ifndef SCOLOR_HPP
|
||||
#define SCOLOR_HPP
|
||||
|
||||
#include <glm/glm.hpp>
|
||||
|
||||
/**
|
||||
* @file SColor.hpp
|
||||
* @brief File for the color struct of a material.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief the number of type in the enum EColorType.
|
||||
*/
|
||||
#define COLOR_TYPE_NUMBER 2
|
||||
|
||||
/**
|
||||
* @brief The enum for color type in the material.
|
||||
*/
|
||||
enum EColorType {
|
||||
COLOR_DIFFUSE,
|
||||
COLOR_SPECULAR,
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief The struct color of the material.
|
||||
*/
|
||||
typedef struct {
|
||||
/**
|
||||
* @brief 4D Vector representing the RGBA color.
|
||||
*/
|
||||
glm::vec4 m_vector;
|
||||
|
||||
/**
|
||||
* @brief The color's type.
|
||||
*/
|
||||
EColorType m_type;
|
||||
} SColor;
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,85 @@
|
||||
#include "CMesh.hpp"
|
||||
#include "../../API/VulkanImplementation/VulkanImpl.hpp"
|
||||
#include <vulkan/vulkan_core.h>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
CMesh::CMesh(void) :
|
||||
m_vertexes() {
|
||||
}
|
||||
|
||||
CMesh::~CMesh(void) {
|
||||
destroy();
|
||||
}
|
||||
|
||||
void CMesh::destroy()
|
||||
{
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
api->destroyBuffer(vertexIndexBuffer, api->getCurrentFrameIndex());
|
||||
}
|
||||
std::vector<SVertex>& CMesh::getVertices(void) {
|
||||
return m_vertexes;
|
||||
}
|
||||
|
||||
|
||||
void CMesh::setVertices(std::vector<SVertex> vertices)
|
||||
{
|
||||
m_vertexes = vertices;
|
||||
}
|
||||
void CMesh::setIndexes(std::vector<uint32_t> indexes){
|
||||
m_indexes = indexes;
|
||||
}
|
||||
|
||||
std::vector<uint32_t>& CMesh::getIndexes(void){
|
||||
return m_indexes;
|
||||
}
|
||||
|
||||
void CMesh::load(void) {
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
VmaAllocator allocator = api->getAllocator();
|
||||
|
||||
VkDeviceSize vertexSize = sizeof(m_vertexes[0]) * m_vertexes.size();
|
||||
VkDeviceSize indexSize = sizeof(m_indexes[0]) * m_indexes.size();
|
||||
VkDeviceSize totalSize = vertexSize + indexSize;
|
||||
|
||||
// 1. staging buffer - CPU visible, temporaire
|
||||
VkBufferCreateInfo stagingBufferInfo{};
|
||||
stagingBufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
stagingBufferInfo.size = totalSize;
|
||||
stagingBufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
|
||||
|
||||
VmaAllocationCreateInfo stagingAllocInfo{};
|
||||
stagingAllocInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY;
|
||||
stagingAllocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
|
||||
|
||||
VMABuffer stagingBuffer;
|
||||
VmaAllocationInfo stagingInfo{};
|
||||
vmaCreateBuffer(allocator, &stagingBufferInfo, &stagingAllocInfo,
|
||||
&stagingBuffer.buffer, &stagingBuffer.allocation, &stagingInfo);
|
||||
|
||||
// 2. copie des données CPU → staging
|
||||
memcpy(stagingInfo.pMappedData, m_vertexes.data(), vertexSize);
|
||||
memcpy((char*)stagingInfo.pMappedData + vertexSize, m_indexes.data(), indexSize);
|
||||
vmaFlushAllocation(allocator, stagingBuffer.allocation, 0, VK_WHOLE_SIZE);
|
||||
|
||||
// 3. vertex buffer final - DEVICE_LOCAL, rapide
|
||||
VkBufferCreateInfo vertexBufferInfo{};
|
||||
vertexBufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
vertexBufferInfo.size = totalSize;
|
||||
vertexBufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT
|
||||
| VK_BUFFER_USAGE_INDEX_BUFFER_BIT
|
||||
| VK_BUFFER_USAGE_TRANSFER_DST_BIT;
|
||||
|
||||
VmaAllocationCreateInfo vertexAllocInfo{};
|
||||
vertexAllocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
|
||||
|
||||
vmaCreateBuffer(allocator, &vertexBufferInfo, &vertexAllocInfo,
|
||||
&vertexIndexBuffer.buffer, &vertexIndexBuffer.allocation, nullptr);
|
||||
|
||||
// 4. copie GPU staging → vertex buffer via command buffer
|
||||
api->copyBuffer(stagingBuffer.buffer, vertexIndexBuffer.buffer, totalSize);
|
||||
|
||||
m_vertexOffset = 0;
|
||||
m_indexOffset = vertexSize;
|
||||
m_indexCount = m_indexes.size();
|
||||
// 5. détruire le staging buffer
|
||||
vmaDestroyBuffer(allocator, stagingBuffer.buffer, stagingBuffer.allocation);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
#ifndef CMESH_HPP
|
||||
#define CMESH_HPP
|
||||
|
||||
#include "SVertex.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
#include <glm/glm.hpp>
|
||||
#include "../../API/VulkanImplementation/VMABuffer.hpp"
|
||||
|
||||
class CMesh {
|
||||
private:
|
||||
|
||||
std::vector<Vertex> m_vertexes;
|
||||
std::vector<uint32_t> m_indexes;
|
||||
|
||||
VMABuffer vertexIndexBuffer;
|
||||
VkDeviceSize m_vertexOffset = 0;
|
||||
VkDeviceSize m_indexOffset = 0;
|
||||
uint32_t m_indexCount = 0;
|
||||
|
||||
public:
|
||||
|
||||
CMesh(void);
|
||||
|
||||
~CMesh(void);
|
||||
|
||||
std::vector<SVertex>& getVertices(void);
|
||||
std::vector<uint32_t>& getIndexes(void);
|
||||
|
||||
void setVertices(std::vector<SVertex> vertices);
|
||||
void setIndexes(std::vector<uint32_t> indexes);
|
||||
|
||||
void load(void);
|
||||
|
||||
VMABuffer& getVertexIndexBuffer(){return vertexIndexBuffer;};
|
||||
VkDeviceSize getVertexOffset(){return m_vertexOffset;}
|
||||
VkDeviceSize getIndexOffset(){return m_indexOffset;};
|
||||
uint32_t getIndexCount(){return m_indexCount;};
|
||||
void destroy();
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,186 @@
|
||||
#include "CMesh2D.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/Data/Mesh/SVertex.hpp"
|
||||
#include "glm/ext/vector_float2.hpp"
|
||||
#include <vulkan/vulkan_core.h>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
namespace CosmicCore {
|
||||
|
||||
CMesh2D::CMesh2D(void) :
|
||||
m_vertexes() {
|
||||
}
|
||||
|
||||
CMesh2D::~CMesh2D(void) {
|
||||
destroy();
|
||||
}
|
||||
|
||||
void CMesh2D::destroy()
|
||||
{
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
api->destroyBuffer(vertexIndexBuffer, api->getCurrentFrameIndex());
|
||||
}
|
||||
std::vector<Vertex2D>& CMesh2D::getVertices(void) {
|
||||
return m_vertexes;
|
||||
}
|
||||
|
||||
|
||||
void CMesh2D::setVertices(std::vector<Vertex2D> vertices)
|
||||
{
|
||||
m_vertexes = vertices;
|
||||
computeCenter();
|
||||
}
|
||||
void CMesh2D::setIndexes(std::vector<uint32_t> indexes){
|
||||
m_indexes = indexes;
|
||||
}
|
||||
|
||||
std::vector<uint32_t>& CMesh2D::getIndexes(void){
|
||||
return m_indexes;
|
||||
}
|
||||
|
||||
void CMesh2D::computeCenter()
|
||||
{
|
||||
if (m_vertexes.empty())
|
||||
m_center = glm::vec2(0.0f, 0.0f);
|
||||
|
||||
glm::vec2 mn{ m_vertexes[0].m_position.x, m_vertexes[0].m_position.y };
|
||||
glm::vec2 mx = mn;
|
||||
|
||||
for (const auto& v : m_vertexes) {
|
||||
mn.x = std::min(mn.x, v.m_position.x);
|
||||
mn.y = std::min(mn.y, v.m_position.y);
|
||||
mx.x = std::max(mx.x, v.m_position.x);
|
||||
mx.y = std::max(mx.y, v.m_position.y);
|
||||
}
|
||||
m_center = (mn + mx) * 0.5f;
|
||||
}
|
||||
|
||||
|
||||
void CMesh2D::load(void) {
|
||||
VulkanImpl* api = dynamic_cast<VulkanImpl*>(GraphicsAPI::getAPI().get());
|
||||
VmaAllocator allocator = api->getAllocator();
|
||||
|
||||
VkDeviceSize vertexSize = sizeof(m_vertexes[0]) * m_vertexes.size();
|
||||
VkDeviceSize indexSize = sizeof(m_indexes[0]) * m_indexes.size();
|
||||
VkDeviceSize totalSize = vertexSize + indexSize;
|
||||
|
||||
//staging buffer CPU visible, temporaire
|
||||
VkBufferCreateInfo stagingBufferInfo{};
|
||||
stagingBufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
stagingBufferInfo.size = totalSize;
|
||||
stagingBufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
|
||||
|
||||
VmaAllocationCreateInfo stagingAllocInfo{};
|
||||
stagingAllocInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY;
|
||||
stagingAllocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
|
||||
|
||||
VMABuffer stagingBuffer;
|
||||
VmaAllocationInfo stagingInfo{};
|
||||
vmaCreateBuffer(allocator, &stagingBufferInfo, &stagingAllocInfo,
|
||||
&stagingBuffer.buffer, &stagingBuffer.allocation, &stagingInfo);
|
||||
|
||||
// copie des données CPU → staging
|
||||
memcpy(stagingInfo.pMappedData, m_vertexes.data(), vertexSize);
|
||||
memcpy((char*)stagingInfo.pMappedData + vertexSize, m_indexes.data(), indexSize);
|
||||
vmaFlushAllocation(allocator, stagingBuffer.allocation, 0, VK_WHOLE_SIZE);
|
||||
|
||||
//vertex buffer final - DEVICE_LOCAL
|
||||
VkBufferCreateInfo vertexBufferInfo{};
|
||||
vertexBufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
vertexBufferInfo.size = totalSize;
|
||||
vertexBufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT
|
||||
| VK_BUFFER_USAGE_INDEX_BUFFER_BIT
|
||||
| VK_BUFFER_USAGE_TRANSFER_DST_BIT;
|
||||
|
||||
VmaAllocationCreateInfo vertexAllocInfo{};
|
||||
vertexAllocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
|
||||
|
||||
vmaCreateBuffer(allocator, &vertexBufferInfo, &vertexAllocInfo,
|
||||
&vertexIndexBuffer.buffer, &vertexIndexBuffer.allocation, nullptr);
|
||||
|
||||
// copie GPU staging vertex buffer via command buffer
|
||||
api->copyBuffer(stagingBuffer.buffer, vertexIndexBuffer.buffer, totalSize);
|
||||
|
||||
m_vertexOffset = 0;
|
||||
m_indexOffset = vertexSize;
|
||||
m_indexCount = m_indexes.size();
|
||||
//détruire le staging buffer
|
||||
vmaDestroyBuffer(allocator, stagingBuffer.buffer, stagingBuffer.allocation);
|
||||
}
|
||||
|
||||
glm::vec2 CMesh2D::buildFromText(CFont* font, const std::string& text)
|
||||
{
|
||||
//destroy check before load if text is edited ?
|
||||
if (!font || text.empty()) {
|
||||
setVertices({});
|
||||
setIndexes({});
|
||||
return {0.0f, 0.0f};
|
||||
}
|
||||
|
||||
std::vector<Vertex2D> vertices;
|
||||
std::vector<uint32_t> indices;
|
||||
|
||||
float scale = font->getMetrics().emSize;
|
||||
float cursorX = 0.0f;
|
||||
float cursorY = 0.0f;
|
||||
float maxWidth = 0.0f;
|
||||
float maxHeight = 0.0f;
|
||||
int lineCount = 1;
|
||||
|
||||
for (char c : text) {
|
||||
if (c == '\n') {
|
||||
maxWidth = std::max(maxWidth, cursorX);
|
||||
cursorX = 0.0f;
|
||||
cursorY += font->getMetrics().lineHeight * scale;
|
||||
lineCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const SGlyph* glyph = font->getGlyph((uint32_t)c);
|
||||
if (!glyph) continue;
|
||||
|
||||
// positions des coins du quad (espace local au mesh)
|
||||
glm::vec2 p0 = {
|
||||
cursorX + glyph->planeMin.x * scale,
|
||||
cursorY - glyph->planeMin.y * scale
|
||||
};
|
||||
glm::vec2 p1 = {
|
||||
cursorX + glyph->planeMax.x * scale,
|
||||
cursorY - glyph->planeMax.y * scale
|
||||
};
|
||||
maxHeight = std::max(maxHeight, glyph->planeMax.y);
|
||||
// UVs dans l'atlas — flip V pour Vulkan
|
||||
glm::vec2 uv0 = {glyph->atlasMin.x, 1.0f - glyph->atlasMax.y};
|
||||
glm::vec2 uv1 = {glyph->atlasMax.x, 1.0f - glyph->atlasMin.y};
|
||||
|
||||
uint32_t base = (uint32_t)vertices.size();
|
||||
|
||||
vertices.push_back({{p0.x, p1.y}, {uv0.x, uv0.y}, {1, 1, 1, 1}});
|
||||
vertices.push_back({{p0.x, p0.y}, {uv0.x, uv1.y}, {1, 1, 1, 1}});
|
||||
vertices.push_back({{p1.x, p0.y}, {uv1.x, uv1.y}, {1, 1, 1, 1}});
|
||||
vertices.push_back({{p1.x, p1.y}, {uv1.x, uv0.y}, {1, 1, 1, 1}});
|
||||
|
||||
|
||||
indices.insert(indices.end(),
|
||||
{base, base+1, base+2, base+2, base+3, base});
|
||||
|
||||
cursorX += glyph->advance * scale;
|
||||
}
|
||||
|
||||
maxWidth = std::max(maxWidth, cursorX);
|
||||
float totalHeight = lineCount * font->getMetrics().lineHeight * scale;
|
||||
|
||||
setVertices(vertices);
|
||||
setIndexes(indices);
|
||||
|
||||
//recentrer le mesh sur le centre du texte
|
||||
for (auto& v : m_vertexes) {
|
||||
v.m_position.x -= m_center.x;
|
||||
v.m_position.y -= m_center.y;
|
||||
}
|
||||
|
||||
load(); // upload GPU
|
||||
|
||||
return {maxWidth, totalHeight};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
#ifndef CMESH2D_HPP
|
||||
#define CMESH2D_HPP
|
||||
|
||||
#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/VMABuffer.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/Data/Font/CFont.hpp"
|
||||
#include "Engine/Core/Systems/Graphics/Data/Mesh/SVertex.hpp"
|
||||
#include "glm/ext/vector_float2.hpp"
|
||||
namespace CosmicCore {
|
||||
class CMesh2D
|
||||
{
|
||||
private:
|
||||
std::vector<Vertex2D> m_vertexes;
|
||||
std::vector<uint32_t> m_indexes;
|
||||
|
||||
VMABuffer vertexIndexBuffer;
|
||||
VkDeviceSize m_vertexOffset = 0;
|
||||
VkDeviceSize m_indexOffset = 0;
|
||||
uint32_t m_indexCount = 0;
|
||||
|
||||
glm::vec2 m_center;
|
||||
void computeCenter();
|
||||
public:
|
||||
|
||||
CMesh2D(void);
|
||||
|
||||
~CMesh2D(void);
|
||||
|
||||
std::vector<Vertex2D>& getVertices(void);
|
||||
std::vector<uint32_t>& getIndexes(void);
|
||||
|
||||
void setVertices(std::vector<Vertex2D> vertices);
|
||||
void setIndexes(std::vector<uint32_t> indexes);
|
||||
|
||||
void load(void);
|
||||
|
||||
VMABuffer& getVertexIndexBuffer(){return vertexIndexBuffer;};
|
||||
VkDeviceSize getVertexOffset(){return m_vertexOffset;}
|
||||
VkDeviceSize getIndexOffset(){return m_indexOffset;};
|
||||
uint32_t getIndexCount(){return m_indexCount;};
|
||||
void destroy();
|
||||
glm::vec2 buildFromText(CFont* font, const std::string& text);
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
Loaded 100 of 217 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user