Minor - ECS use in other method pt.1 - V12.2.0

This commit is contained in:
CatChow0 2025-06-24 16:13:56 +02:00
parent 3adfddf44f
commit bf1b5d78e5
2 changed files with 225 additions and 190 deletions

View File

@ -7,7 +7,6 @@
/////////////////////// ///////////////////////
#include "d_3d_class.h" #include "d_3d_class.h"
#include "camera_class.h" #include "camera_class.h"
#include "object.h"
#include "light_class.h" #include "light_class.h"
#include "bitmap_class.h" #include "bitmap_class.h"
@ -106,13 +105,8 @@ public:
void set_speed(const float speed) { this->speed_ = speed; }; void set_speed(const float speed) { this->speed_ = speed; };
void add_cube(); void add_cube();
void delete_entity_by_id(int entity_id);
void delete_kobject(int index); void delete_kobject(int index);
size_t get_cube_count() const { return cubes_.size(); };
size_t get_terrain_cube_count() const { return terrain_chunk_.size(); };
std::vector<object*> get_cubes() const { return cubes_; };
std::vector<object*> get_terrain_cubes() const { return terrain_chunk_; };
std::vector<object*> get_kobjects() const { return object_; };
void set_kobjects(std::vector<object*> kobjects) { object_ = kobjects; };
void add_kobject(std::wstring& filepath); void add_kobject(std::wstring& filepath);
void set_path(WCHAR* path) { path_ = path; }; void set_path(WCHAR* path) { path_ = path; };
void set_w_folder(const std::filesystem::path& w_folder) { w_folder_ = w_folder; }; void set_w_folder(const std::filesystem::path& w_folder) { w_folder_ = w_folder; };
@ -188,7 +182,7 @@ private:
bool render_scene_to_texture(float); bool render_scene_to_texture(float);
bool render_refraction_to_texture(); bool render_refraction_to_texture();
bool render_reflection_to_texture(); bool render_reflection_to_texture();
bool render_pass(const std::vector<std::reference_wrapper<std::vector<object*>>>& RenderQueues, XMFLOAT4* diffuse, XMFLOAT4* position, XMFLOAT4* ambient, XMMATRIX view, XMMATRIX projection); bool render_pass(XMFLOAT4* diffuse, XMFLOAT4* position, XMFLOAT4* ambient, XMMATRIX view, XMMATRIX projection);
void update_skybox_position(); void update_skybox_position();
void culling_thread_function(); void culling_thread_function();
@ -246,14 +240,10 @@ private :
std::unique_ptr<ecs::EntityManager> entity_manager_; std::unique_ptr<ecs::EntityManager> entity_manager_;
object* selected_object_; object* selected_object_;
std::vector<object*> cubes_;
std::vector<object*> terrain_chunk_;
std::vector<object*> object_;
float speed_ = 0.1f; // speed for the demo spinning object float speed_ = 0.1f; // speed for the demo spinning object
std::vector<object*> imported_object_; std::vector<object*> imported_object_;
int object_id_ = 0; int object_id_ = 0;
std::vector<std::reference_wrapper<std::vector<object*>>> render_queues_;
std::vector<object*> skybox_; std::vector<object*> skybox_;
// ----------------------------------- // // ----------------------------------- //

View File

@ -28,10 +28,6 @@ application_class::application_class() : should_quit_(false)
reflection_texture_ = nullptr; reflection_texture_ = nullptr;
scene_texture_ = nullptr; scene_texture_ = nullptr;
physics_ = nullptr; physics_ = nullptr;
cubes_.clear();
terrain_chunk_.clear();
object_.clear();
render_queues_.clear();
skybox_.clear(); skybox_.clear();
lights_.clear(); lights_.clear();
sun_light_ = nullptr; sun_light_ = nullptr;
@ -86,11 +82,6 @@ bool application_class::initialize(int screenWidth, int screenHeight, HWND hwnd,
bool result; bool result;
HRESULT Hresult; HRESULT Hresult;
render_queues_.push_back(std::ref(skybox_)); // Skybox doit être rendu en premier pour être derrière touts les autres objets
render_queues_.push_back(std::ref(object_));
render_queues_.push_back(std::ref(cubes_));
render_queues_.push_back(std::ref(terrain_chunk_));
// create entity manager // create entity manager
entity_manager_ = std::make_unique<ecs::EntityManager>(); entity_manager_ = std::make_unique<ecs::EntityManager>();
@ -1138,7 +1129,7 @@ bool application_class::render(float rotation, float x, float y, float z, float
// active_camera_->render(); // active_camera_->render();
// // Render the objects in the render queues. with depth only pass. // // Render the objects in the render queues. with depth only pass.
// active_camera_->get_view_matrix(viewMatrix); // active_camera_->get_view_matrix(viewMatrix);
result = render_pass(render_queues_, diffuseColor, lightPosition, ambientColor, viewMatrix, projectionMatrix); result = render_pass(diffuseColor, lightPosition, ambientColor, viewMatrix, projectionMatrix);
if (!result) if (!result)
{ {
Logger::Get().Log("Could not render the model using any shader", __FILE__, __LINE__, Logger::LogLevel::Error); Logger::Get().Log("Could not render the model using any shader", __FILE__, __LINE__, Logger::LogLevel::Error);
@ -1301,9 +1292,10 @@ int application_class::get_screen_height() const
void application_class::generate_terrain() void application_class::generate_terrain()
{ {
Logger::Get().Log("Génération du terrain avec instanciation", __FILE__, __LINE__, Logger::LogLevel::Info); Logger::Get().Log("Génération du terrain avec ECS", __FILE__, __LINE__, Logger::LogLevel::Info);
terrain_chunk_.clear(); // delete previous terrain if it exists
delete_terrain();
// Dimensions du terrain // Dimensions du terrain
float scaleX = 10.0f; float scaleX = 10.0f;
@ -1312,56 +1304,75 @@ void application_class::generate_terrain()
int gridSizeX = 20; int gridSizeX = 20;
int gridSizeZ = 20; int gridSizeZ = 20;
// Créer un conteneur de textures_ partagé // Vérifier si le modèle existe déjà dans le cache
std::string modelName = "assets/Model/OBJ/plane.obj";
std::shared_ptr<model_class> sharedModel;
auto it = g_model_cache.find(modelName);
if (it != g_model_cache.end()) {
// Utiliser le modèle existant du cache
Logger::Get().Log("Using cached model for terrain: " + modelName, __FILE__, __LINE__);
sharedModel = it->second;
}
else {
// Créer un conteneur de textures partagé
TextureContainer textureContainer; TextureContainer textureContainer;
textureContainer.diffusePaths.push_back(L"assets/Texture/Bricks2K.png"); textureContainer.diffusePaths.push_back(L"assets/Texture/Bricks2K.png");
textureContainer.normalPaths.push_back(L"assets/Texture/BricksNRM2K.png"); textureContainer.normalPaths.push_back(L"assets/Texture/BricksNRM2K.png");
textureContainer.specularPaths.push_back(L"assets/Texture/BricksGLOSS2K.png"); textureContainer.specularPaths.push_back(L"assets/Texture/BricksGLOSS2K.png");
// Précharger les textures_ une seule fois // Créer et initialiser le modèle si non trouvé
model_class* sharedModel = new model_class();
sharedModel->PreloadTextures(direct_3d_->get_device(), direct_3d_->get_device_context(), textureContainer);
char modelFilename[128]; char modelFilename[128];
strcpy_s(modelFilename, "assets/Model/OBJ/plane.obj"); strcpy_s(modelFilename, modelName.c_str());
// Générer les tuiles de terrain auto newModel = std::make_shared<model_class>();
for (int i = 0; i < gridSizeX; i++) newModel->PreloadTextures(direct_3d_->get_device(), direct_3d_->get_device_context(), textureContainer);
{
for (int j = 0; j < gridSizeZ; j++)
{
// Créer un nouvel objet de terrain
object* terrain = new object(*this);
// Initialiser avec le modèle et les textures_ préchargées if (!newModel->Initialize(direct_3d_->get_device(), direct_3d_->get_device_context(), modelFilename, textureContainer)) {
if (!terrain->Initialize(direct_3d_->get_device(), direct_3d_->get_device_context(), modelFilename, textureContainer)) Logger::Get().Log("Impossible d'initialiser le modèle du terrain", __FILE__, __LINE__, Logger::LogLevel::Error);
{ return;
Logger::Get().Log("Échec de l'initialisation d'une tuile de terrain", __FILE__, __LINE__, Logger::LogLevel::Error);
delete terrain;
continue;
} }
// Définir la position dans la grille // Ajouter le modèle au cache
XMFLOAT3 position(i * scaleX, -12.0f, j * scaleZ); g_model_cache[modelName] = newModel;
XMFLOAT3 scale(scaleX, scaleY, scaleZ); sharedModel = newModel;
Logger::Get().Log("Added terrain model to cache: " + modelName, __FILE__, __LINE__);
}
terrain->SetPosition(XMLoadFloat3(&position)); // Vérifier si l'entity manager est disponible
terrain->SetScale(XMLoadFloat3(&scale)); if (entity_manager_) {
// Générer les tuiles de terrain avec le système ECS
for (int i = 0; i < gridSizeX; i++) {
for (int j = 0; j < gridSizeZ; j++) {
// Créer une entité
auto entity = entity_manager_->CreateEntity();
// Configurer les propriétés // Ajouter un composant d'identité
terrain->SetName("TerrainTile_" + std::to_string(i) + "_" + std::to_string(j)); auto identity = entity->AddComponent<ecs::IdentityComponent>(object_id_++);
terrain->SetType(ObjectType::Cube); identity->SetName("TerrainTile_" + std::to_string(i) + "_" + std::to_string(j));
terrain->SetActiveShader(ShaderType::SUNLIGHT); identity->SetType(ecs::ObjectType::Terrain);
terrain->SetId(object_id_++);
// Ajouter à la liste des chunks de terrain // Ajouter un composant de transformation
terrain_chunk_.push_back(terrain); auto transform = entity->AddComponent<ecs::TransformComponent>();
transform->SetPosition(XMVectorSet(i * scaleX, -12.0f, j * scaleZ, 0.0f));
transform->SetScale(XMVectorSet(scaleX, scaleY, scaleZ, 0.0f));
transform->UpdateWorldMatrix();
// Ajouter un composant de rendu
auto render = entity->AddComponent<ecs::RenderComponent>();
render->InitializeWithModel(sharedModel);
// Ajouter un composant de shader
auto shader = entity->AddComponent<ecs::ShaderComponent>();
shader->SetActiveShader(ecs::ShaderType::SUNLIGHT);
}
}
}
update_stats_after_modification(); update_stats_after_modification();
}
}
Logger::Get().Log("Terrain généré avec " + std::to_string(terrain_chunk_.size()) + " tuiles", __FILE__, __LINE__, Logger::LogLevel::Info); int totalTiles = gridSizeX * gridSizeZ;
Logger::Get().Log("Terrain généré avec " + std::to_string(totalTiles) + " tuiles", __FILE__, __LINE__, Logger::LogLevel::Info);
} }
void application_class::add_kobject(std::wstring& filepath) void application_class::add_kobject(std::wstring& filepath)
@ -1455,37 +1466,80 @@ void application_class::add_cube()
std::lock_guard<std::mutex> lock(objects_mutex_); std::lock_guard<std::mutex> lock(objects_mutex_);
Logger::Get().Log("Adding cube", __FILE__, __LINE__); Logger::Get().Log("Adding cube", __FILE__, __LINE__);
char modelFilename[128]; std::string model_name = "assets/Model/TXT/cube.txt";
TextureContainer CubeTexture; std::shared_ptr<model_class> sharedModel;
// Set the file name of the model.
strcpy_s(modelFilename, "assets/Model/TXT/cube.txt");
// Liste des fichiers de texture auto it = g_model_cache.find(model_name);
std::vector<std::wstring> cubeTexture = { if (it != g_model_cache.end())
L"assets/Texture/Bricks2K.png" {
}; Logger::Get().Log("Using cached model: " + model_name, __FILE__, __LINE__);
sharedModel = it->second;
}
else
{
TextureContainer cube_textures;
cube_textures.diffusePaths.push_back(L"assets/Texture/Bricks2K.png");
cube_textures.normalPaths.push_back(L"assets/Texture/BricksNRM2K.png");
cube_textures.specularPaths.push_back(L"assets/Texture/BricksGLOSS2K.png");
static int cubeCount = 0; char model_filename[128];
float position = cubeCount * 2.0f; strcpy_s(model_filename, model_name.c_str());
object* newCube = new object(*this);
newCube->LoadTexturesFromPath(cubeTexture, CubeTexture, direct_3d_); // Load textures_ from the path
newCube->Initialize(direct_3d_->get_device(), direct_3d_->get_device_context(), modelFilename, CubeTexture);
newCube->SetTranslateMatrix(XMMatrixTranslation(position, 0.0f, 0.0f));
cubes_.push_back(newCube); auto newModel = std::make_shared<model_class>();
newModel->PreloadTextures(direct_3d_->get_device(), direct_3d_->get_device_context(), cube_textures);
if (!newModel->Initialize(direct_3d_->get_device(), direct_3d_->get_device_context(), model_filename, cube_textures)) {
Logger::Get().Log("Failed to initialize cube model", __FILE__, __LINE__, Logger::LogLevel::Error);
return;
}
g_model_cache[model_name] = newModel;
sharedModel = newModel;
Logger::Get().Log("Added cube model to cache: " + model_name, __FILE__, __LINE__);
if (entity_manager_)
{
auto entity = entity_manager_->CreateEntity();
auto identity = entity->AddComponent<ecs::IdentityComponent>(object_id_++);
identity->SetName("Cube");
identity->SetType(ecs::ObjectType::Cube);
auto transform = entity->AddComponent<ecs::TransformComponent>();
transform->SetPosition(XMVectorSet(0.0f, 10.0f, 0.0f, 0.0f));
transform->SetScale(XMVectorSet(1.0f, 1.0f, 1.0f, 0.0f));
transform->UpdateWorldMatrix();
auto render = entity->AddComponent<ecs::RenderComponent>();
render->InitializeWithModel(sharedModel);
auto shader = entity->AddComponent<ecs::ShaderComponent>();
shader->SetActiveShader(ecs::ShaderType::TEXTURE);
}
}
update_stats_after_modification(); update_stats_after_modification();
Logger::Get().Log("Cube added successfully", __FILE__, __LINE__, Logger::LogLevel::Info);
} }
void application_class::delete_kobject(int index) void application_class::delete_entity_by_id(int entity_id)
{ {
std::lock_guard<std::mutex> lock(objects_mutex_); std::lock_guard<std::mutex> lock(objects_mutex_);
Logger::Get().Log("Deleting object", __FILE__, __LINE__); Logger::Get().Log("Deleting entity with ID: " + std::to_string(entity_id), __FILE__, __LINE__, Logger::LogLevel::Info);
if (index < object_.size()) if (entity_manager_) {
{ // Rechercher l'entité avec l'ID spécifié via le composant IdentityComponent
object_.erase(object_.begin() + index); auto entities_with_identity = entity_manager_->GetEntitiesWithComponent<ecs::IdentityComponent>();
for (auto& entity : entities_with_identity) {
auto identity = entity->GetComponent<ecs::IdentityComponent>();
if (identity && identity->GetId() == entity_id) {
// Supprimer l'entité
entity_manager_->DestroyEntity(entity->GetID());
Logger::Get().Log("Entity with ID " + std::to_string(entity_id) + " successfully deleted", __FILE__, __LINE__, Logger::LogLevel::Info);
break;
}
}
} }
update_stats_after_modification(); update_stats_after_modification();
@ -1494,8 +1548,19 @@ void application_class::delete_kobject(int index)
void application_class::delete_terrain() void application_class::delete_terrain()
{ {
std::lock_guard<std::mutex> lock(objects_mutex_); std::lock_guard<std::mutex> lock(objects_mutex_);
Logger::Get().Log("Deleting terrain", __FILE__, __LINE__); Logger::Get().Log("Deleting terrain", __FILE__, __LINE__, Logger::LogLevel::Info);
terrain_chunk_.clear();
// Get all entities with the Terrain type
auto entities_with_terrain = entity_manager_->GetEntitiesWithComponent<ecs::IdentityComponent>();
for (auto& entity : entities_with_terrain) {
auto identity = entity->GetComponent<ecs::IdentityComponent>();
if (identity && identity->GetType() == ecs::ObjectType::Terrain) {
// Destroy the entity
entity_manager_->DestroyEntity(entity->GetID());
Logger::Get().Log("Terrain entity with ID " + std::to_string(identity->GetId()) + " successfully deleted", __FILE__, __LINE__, Logger::LogLevel::Info);
}
}
update_stats_after_modification(); update_stats_after_modification();
} }
@ -1766,7 +1831,7 @@ void application_class::culling_thread_function()
bool application_class::render_pass(const std::vector<std::reference_wrapper<std::vector<object*>>>& RenderQueues, XMFLOAT4* diffuse, XMFLOAT4* position, XMFLOAT4* ambient, XMMATRIX view, XMMATRIX projection) bool application_class::render_pass(XMFLOAT4* diffuse, XMFLOAT4* position, XMFLOAT4* ambient, XMMATRIX view, XMMATRIX projection)
{ {
std::lock_guard<std::mutex> lock(objects_mutex_); std::lock_guard<std::mutex> lock(objects_mutex_);
XMMATRIX scaleMatrix, rotateMatrix, translateMatrix; XMMATRIX scaleMatrix, rotateMatrix, translateMatrix;
@ -2034,8 +2099,6 @@ bool application_class::create_big_cube(int side_count)
sharedModel = newModel; sharedModel = newModel;
} }
// Version ECS - Créer les entités pour le cube
if (entity_manager_) {
for (int x = 0; x < side_count; x++) { for (int x = 0; x < side_count; x++) {
for (int y = 0; y < side_count; y++) { for (int y = 0; y < side_count; y++) {
for (int z = 0; z < side_count; z++) { for (int z = 0; z < side_count; z++) {
@ -2045,7 +2108,7 @@ bool application_class::create_big_cube(int side_count)
// Ajouter un composant d'identité // Ajouter un composant d'identité
auto identity = entity->AddComponent<ecs::IdentityComponent>(object_id_++); auto identity = entity->AddComponent<ecs::IdentityComponent>(object_id_++);
identity->SetName("CubePart_" + std::to_string(x) + "_" + std::to_string(y) + "_" + std::to_string(z)); identity->SetName("CubePart_" + std::to_string(x) + "_" + std::to_string(y) + "_" + std::to_string(z));
identity->SetType(ecs::ObjectType::Cube); identity->SetType(ecs::ObjectType::Terrain);
// Ajouter un composant de transformation // Ajouter un composant de transformation
auto transform = entity->AddComponent<ecs::TransformComponent>(); auto transform = entity->AddComponent<ecs::TransformComponent>();
@ -2063,25 +2126,6 @@ bool application_class::create_big_cube(int side_count)
} }
} }
} }
} else {
// Ancien système - Créer temporairement les cubes dans un vecteur local
std::vector<object*> tempCubes;
tempCubes.reserve(side_count * side_count * side_count);
// Générer side_count³ cubes
for (int x = 0; x < side_count; x++) {
for (int y = 0; y < side_count; y++) {
for (int z = 0; z < side_count; z++) {
object* cubePart = new object(*this);
cubePart->SetModel(sharedModel);
cubePart->SetTranslateMatrix(XMMatrixTranslation(static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)));
tempCubes.push_back(cubePart);
}
}
}
// Transférer les cubes du vecteur temporaire au vecteur membre
cubes_ = std::move(tempCubes);
}
update_stats_after_modification(); update_stats_after_modification();
@ -2095,3 +2139,4 @@ void application_class::update_stats_after_modification()
stats_ -> update_geometric_stats(); stats_ -> update_geometric_stats();
} }
} }