Compare commits

..

No commits in common. "main" and "V11.4.0" have entirely different histories.

24 changed files with 1095 additions and 2111 deletions

View File

@ -7,9 +7,14 @@
<list default="true" id="e81d6e08-efc7-40a0-909d-ec4943d948e9" name="Changes" comment=""> <list default="true" id="e81d6e08-efc7-40a0-909d-ec4943d948e9" name="Changes" comment="">
<change beforePath="$PROJECT_DIR$/.idea/.idea.KhaoticEngineReborn/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/.idea.KhaoticEngineReborn/.idea/workspace.xml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.idea/.idea.KhaoticEngineReborn/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/.idea.KhaoticEngineReborn/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/enginecustom/imgui.ini" beforeDir="false" afterPath="$PROJECT_DIR$/enginecustom/imgui.ini" afterDir="false" /> <change beforePath="$PROJECT_DIR$/enginecustom/imgui.ini" beforeDir="false" afterPath="$PROJECT_DIR$/enginecustom/imgui.ini" afterDir="false" />
<change beforePath="$PROJECT_DIR$/enginecustom/src/inc/system/ecs/component.h" beforeDir="false" afterPath="$PROJECT_DIR$/enginecustom/src/inc/system/ecs/component.h" afterDir="false" /> <change beforePath="$PROJECT_DIR$/enginecustom/src/inc/system/Skybox.h" beforeDir="false" afterPath="$PROJECT_DIR$/enginecustom/src/inc/system/Skybox.h" afterDir="false" />
<change beforePath="$PROJECT_DIR$/enginecustom/src/inc/system/ecs/components/identity_component.h" beforeDir="false" afterPath="$PROJECT_DIR$/enginecustom/src/inc/system/ecs/components/identity_component.h" afterDir="false" /> <change beforePath="$PROJECT_DIR$/enginecustom/src/inc/system/application_class.h" beforeDir="false" afterPath="$PROJECT_DIR$/enginecustom/src/inc/system/application_class.h" afterDir="false" />
<change beforePath="$PROJECT_DIR$/enginecustom/src/src/system/scene_manager.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/enginecustom/src/src/system/scene_manager.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/enginecustom/src/inc/system/object.h" beforeDir="false" afterPath="$PROJECT_DIR$/enginecustom/src/inc/system/object.h" afterDir="false" />
<change beforePath="$PROJECT_DIR$/enginecustom/src/inc/system/stats.h" beforeDir="false" afterPath="$PROJECT_DIR$/enginecustom/src/inc/system/stats.h" afterDir="false" />
<change beforePath="$PROJECT_DIR$/enginecustom/src/src/system/Skybox.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/enginecustom/src/src/system/Skybox.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/enginecustom/src/src/system/application_class.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/enginecustom/src/src/system/application_class.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/enginecustom/src/src/system/object.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/enginecustom/src/src/system/object.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/enginecustom/src/src/system/stats.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/enginecustom/src/src/system/stats.cpp" afterDir="false" />
</list> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -23,21 +28,91 @@
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" /> <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component> </component>
<component name="HighlightingSettingsPerFile"> <component name="HighlightingSettingsPerFile">
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="mock:///dummy.cpp" root0="SKIP_HIGHLIGHTING" />
<setting file="file://C:/Program Files (x86)/Windows Kits/10/Include/10.0.26100.0/um/d3d11.h" root0="SKIP_HIGHLIGHTING" /> <setting file="file://C:/Program Files (x86)/Windows Kits/10/Include/10.0.26100.0/um/d3d11.h" root0="SKIP_HIGHLIGHTING" />
<setting file="file://C:/Program Files (x86)/Windows Kits/10/Include/10.0.26100.0/um/dinput.h" root0="SKIP_HIGHLIGHTING" /> <setting file="file://C:/Program Files (x86)/Windows Kits/10/Include/10.0.26100.0/um/dinput.h" root0="SKIP_HIGHLIGHTING" />
<setting file="file://C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.44.35207/include/memory" root0="SKIP_HIGHLIGHTING" /> <setting file="file://C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.44.35207/include/memory" root0="SKIP_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/enginecustom/include/Inc/VertexTypes.h" root0="SKIP_HIGHLIGHTING" /> <setting file="file://$PROJECT_DIR$/enginecustom/include/Inc/VertexTypes.h" root0="SKIP_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/enginecustom/include/Vulkan/Include/vulkan/vulkan_core.h" root0="SKIP_HIGHLIGHTING" /> <setting file="file://$PROJECT_DIR$/enginecustom/include/Vulkan/Include/vulkan/vulkan_core.h" root0="SKIP_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/enginecustom/src/inc/system/ecs/component.h" root0="FORCE_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/enginecustom/src/inc/system/ecs/components/identity_component.h" root0="FORCE_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/enginecustom/src/inc/system/ecs/components/model_path_component.h" root0="FORCE_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/enginecustom/src/inc/system/ecs/components/physics_component.h" root0="FORCE_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/enginecustom/src/inc/system/ecs/components/render_component.h" root0="FORCE_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/enginecustom/src/inc/system/ecs/components/shader_component.h" root0="FORCE_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/enginecustom/src/inc/system/ecs/components/transform_component.h" root0="FORCE_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/enginecustom/src/inc/system/ecs/entity.h" root0="FORCE_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/enginecustom/src/inc/system/ecs/entity_manager.h" root0="FORCE_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/enginecustom/src/inc/system/ecs/systems/render_system.h" root0="FORCE_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/../../IDE_VS/VC/Tools/MSVC/14.38.33130/include/type_traits" root0="SKIP_HIGHLIGHTING" /> <setting file="file://$PROJECT_DIR$/../../IDE_VS/VC/Tools/MSVC/14.38.33130/include/type_traits" root0="SKIP_HIGHLIGHTING" />
</component> </component>
<component name="KubernetesApiPersistence">{}</component> <component name="KubernetesApiPersistence">{}</component>
@ -59,26 +134,26 @@
<option name="hideEmptyMiddlePackages" value="true" /> <option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" /> <option name="showLibraryContents" value="true" />
</component> </component>
<component name="PropertiesComponent">{ <component name="PropertiesComponent"><![CDATA[{
&quot;keyToString&quot;: { "keyToString": {
&quot;ASKED_SHARE_PROJECT_CONFIGURATION_FILES&quot;: &quot;true&quot;, "ASKED_SHARE_PROJECT_CONFIGURATION_FILES": "true",
&quot;C++ Project.enginecustom.executor&quot;: &quot;Run&quot;, "C++ Project.enginecustom.executor": "Run",
&quot;C/C++ Project.KhaoticDemo.executor&quot;: &quot;Run&quot;, "C/C++ Project.KhaoticDemo.executor": "Run",
&quot;C/C++ Project.enginecustom.executor&quot;: &quot;Run&quot;, "C/C++ Project.enginecustom.executor": "Debug",
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;, "RunOnceActivity.ShowReadmeOnStart": "true",
&quot;RunOnceActivity.git.unshallow&quot;: &quot;true&quot;, "RunOnceActivity.git.unshallow": "true",
&quot;SHARE_PROJECT_CONFIGURATION_FILES&quot;: &quot;true&quot;, "SHARE_PROJECT_CONFIGURATION_FILES": "true",
&quot;git-widget-placeholder&quot;: &quot;main&quot;, "git-widget-placeholder": "main",
&quot;ignore.virus.scanning.warn.message&quot;: &quot;true&quot;, "ignore.virus.scanning.warn.message": "true",
&quot;node.js.detected.package.eslint&quot;: &quot;true&quot;, "node.js.detected.package.eslint": "true",
&quot;node.js.detected.package.tslint&quot;: &quot;true&quot;, "node.js.detected.package.tslint": "true",
&quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;, "node.js.selected.package.eslint": "(autodetect)",
&quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;, "node.js.selected.package.tslint": "(autodetect)",
&quot;nodejs_package_manager_path&quot;: &quot;npm&quot;, "nodejs_package_manager_path": "npm",
&quot;settings.editor.selected.configurable&quot;: &quot;preferences.environmentSetup&quot;, "settings.editor.selected.configurable": "preferences.pluginManager",
&quot;vue.rearranger.settings.migration&quot;: &quot;true&quot; "vue.rearranger.settings.migration": "true"
} }
}</component> }]]></component>
<component name="RunManager" selected="C/C++ Project.enginecustom"> <component name="RunManager" selected="C/C++ Project.enginecustom">
<configuration name="KhaoticDemo" type="CppProject" factoryName="C++ Project"> <configuration name="KhaoticDemo" type="CppProject" factoryName="C++ Project">
<configuration_1 setup="1"> <configuration_1 setup="1">
@ -225,14 +300,6 @@
<workItem from="1750335650897" duration="2051000" /> <workItem from="1750335650897" duration="2051000" />
<workItem from="1750344288223" duration="1751000" /> <workItem from="1750344288223" duration="1751000" />
<workItem from="1750351735497" duration="9648000" /> <workItem from="1750351735497" duration="9648000" />
<workItem from="1750417484899" duration="2384000" />
<workItem from="1750420267631" duration="148000" />
<workItem from="1750592598277" duration="332000" />
<workItem from="1750699146323" duration="10385000" />
<workItem from="1750763086646" duration="4874000" />
<workItem from="1750770680795" duration="13425000" />
<workItem from="1750964683511" duration="27000" />
<workItem from="1750964770914" duration="2126000" />
</task> </task>
<task id="LOCAL-00001" summary="Minor update - viewport window tweak"> <task id="LOCAL-00001" summary="Minor update - viewport window tweak">
<option name="closed" value="true" /> <option name="closed" value="true" />

View File

@ -0,0 +1 @@
1 isosphere 0 10 0 0 -0 0 1 1 1 Content/Assets/Kobject/isosphere.obj ALPHA_MAPPING 1 Unknown 1 0 2 assets/Texture/Bricks2K.png F:\Github_Repo\khaotic-engine-Reborn\enginecustom\assets\Texture\moss01.png 1 assets/Texture/BricksNRM2K.png 1 assets/Texture/BricksGLOSS2K.png 1 F:\Github_Repo\khaotic-engine-Reborn\enginecustom\assets\Texture\alpha01.png

View File

@ -0,0 +1 @@
0 vaisseautri 0 50 0 0 -0 0 1 1 1 Content/Assets/Kobject/vaisseautri.obj CEL_SHADING 1 Unknown 1 0 1 F:\Github_Repo\khaotic-engine-Reborn\enginecustom\assets\Texture\marble01.png 1 assets/Texture/BricksNRM2K.png 1 assets/Texture/BricksGLOSS2K.png 0

View File

@ -1 +0,0 @@
1 CubePart_0_0_0 0 0 0 0 -0 0 1 1 1 LIGHTING 0 Terrain 0 0 1 assets/Texture/Bricks2K.png 1 assets/Texture/BricksNRM2K.png 1 assets/Texture/BricksGLOSS2K.png 0

View File

@ -119,16 +119,6 @@
<ClInclude Include="src\inc\system\camera_class.h" /> <ClInclude Include="src\inc\system\camera_class.h" />
<ClInclude Include="src\inc\system\d_3d_class.h" /> <ClInclude Include="src\inc\system\d_3d_class.h" />
<ClInclude Include="src\inc\system\display_plane_class.h" /> <ClInclude Include="src\inc\system\display_plane_class.h" />
<ClInclude Include="src\inc\system\ecs\component.h" />
<ClInclude Include="src\inc\system\ecs\components\identity_component.h" />
<ClInclude Include="src\inc\system\ecs\components\model_path_component.h" />
<ClInclude Include="src\inc\system\ecs\components\physics_component.h" />
<ClInclude Include="src\inc\system\ecs\components\render_component.h" />
<ClInclude Include="src\inc\system\ecs\components\shader_component.h" />
<ClInclude Include="src\inc\system\ecs\components\transform_component.h" />
<ClInclude Include="src\inc\system\ecs\entity.h" />
<ClInclude Include="src\inc\system\ecs\entity_manager.h" />
<ClInclude Include="src\inc\system\ecs\systems\render_system.h" />
<ClInclude Include="src\inc\system\font_class.h" /> <ClInclude Include="src\inc\system\font_class.h" />
<ClInclude Include="src\inc\system\fps_class.h" /> <ClInclude Include="src\inc\system\fps_class.h" />
<ClInclude Include="src\inc\system\fps_limiter.h" /> <ClInclude Include="src\inc\system\fps_limiter.h" />
@ -144,6 +134,7 @@
<ClInclude Include="src\inc\system\physics.h" /> <ClInclude Include="src\inc\system\physics.h" />
<ClInclude Include="src\inc\system\position_class.h" /> <ClInclude Include="src\inc\system\position_class.h" />
<ClInclude Include="src\inc\system\render_texture_class.h" /> <ClInclude Include="src\inc\system\render_texture_class.h" />
<ClInclude Include="src\inc\system\sceneManager.h" />
<ClInclude Include="src\inc\system\scene_manager.h" /> <ClInclude Include="src\inc\system\scene_manager.h" />
<ClInclude Include="src\inc\system\shadow_map.h" /> <ClInclude Include="src\inc\system\shadow_map.h" />
<ClInclude Include="src\inc\system\Skybox.h" /> <ClInclude Include="src\inc\system\Skybox.h" />

View File

@ -10,24 +10,24 @@ Collapsed=0
[Window][Khaotic Engine] [Window][Khaotic Engine]
Pos=1267,19 Pos=1267,19
Size=317,842 Size=317,609
Collapsed=0 Collapsed=0
DockId=0x00000005,0 DockId=0x00000002,0
[Window][render Stats] [Window][render Stats]
Pos=0,630 Pos=0,630
Size=792,231 Size=1584,231
Collapsed=0 Collapsed=0
DockId=0x00000009,0 DockId=0x00000009,0
[Window][Objects] [Window][Objects]
Pos=0,19 Pos=0,19
Size=234,609 Size=238,609
Collapsed=0 Collapsed=0
DockId=0x0000000B,0 DockId=0x0000000B,0
[Window][Terrain] [Window][Terrain]
Pos=236,19 Pos=0,19
Size=266,609 Size=266,609
Collapsed=0 Collapsed=0
DockId=0x00000007,0 DockId=0x00000007,0
@ -40,27 +40,19 @@ DockId=0x0000000A,0
[Window][Light] [Window][Light]
Pos=0,19 Pos=0,19
Size=234,609 Size=238,609
Collapsed=0 Collapsed=0
DockId=0x0000000B,1 DockId=0x0000000B,1
[Window][Engine Settings]
Pos=1267,462
Size=317,166
Collapsed=0
DockId=0x00000006,0
[Docking][Data] [Docking][Data]
DockSpace ID=0xCCBD8CF7 Window=0x3DA2F1DE Pos=0,19 Size=1584,842 Split=Y DockSpace ID=0xCCBD8CF7 Window=0x3DA2F1DE Pos=0,19 Size=1584,842 Split=Y
DockNode ID=0x00000003 Parent=0xCCBD8CF7 SizeRef=1584,609 Split=X DockNode ID=0x00000003 Parent=0xCCBD8CF7 SizeRef=1584,609 Split=X
DockNode ID=0x0000000B Parent=0x00000003 SizeRef=234,842 Selected=0x321620B2 DockNode ID=0x0000000B Parent=0x00000003 SizeRef=238,842 Selected=0x031DC75C
DockNode ID=0x0000000C Parent=0x00000003 SizeRef=1348,842 Split=X DockNode ID=0x0000000C Parent=0x00000003 SizeRef=1344,842 Split=X
DockNode ID=0x00000007 Parent=0x0000000C SizeRef=266,842 Selected=0x393905AB DockNode ID=0x00000007 Parent=0x0000000C SizeRef=266,842 Selected=0x393905AB
DockNode ID=0x00000008 Parent=0x0000000C SizeRef=1316,842 Split=X DockNode ID=0x00000008 Parent=0x0000000C SizeRef=1316,842 Split=X
DockNode ID=0x00000001 Parent=0x00000008 SizeRef=1265,842 CentralNode=1 DockNode ID=0x00000001 Parent=0x00000008 SizeRef=1025,842 CentralNode=1
DockNode ID=0x00000002 Parent=0x00000008 SizeRef=317,842 Split=Y Selected=0x9F035453 DockNode ID=0x00000002 Parent=0x00000008 SizeRef=317,842 Selected=0x9F035453
DockNode ID=0x00000005 Parent=0x00000002 SizeRef=317,441 Selected=0x9F035453
DockNode ID=0x00000006 Parent=0x00000002 SizeRef=317,166 Selected=0x0B098C4B
DockNode ID=0x00000004 Parent=0xCCBD8CF7 SizeRef=1584,231 Split=X Selected=0xF5D1BB37 DockNode ID=0x00000004 Parent=0xCCBD8CF7 SizeRef=1584,231 Split=X Selected=0xF5D1BB37
DockNode ID=0x00000009 Parent=0x00000004 SizeRef=792,231 Selected=0xF5D1BB37 DockNode ID=0x00000009 Parent=0x00000004 SizeRef=792,231 Selected=0xF5D1BB37
DockNode ID=0x0000000A Parent=0x00000004 SizeRef=790,231 Selected=0xAB74BEE9 DockNode ID=0x0000000A Parent=0x00000004 SizeRef=790,231 Selected=0xAB74BEE9

View File

@ -7,7 +7,10 @@
/////////////////////// ///////////////////////
#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 <vector>
#include <filesystem>
#include "bitmap_class.h" #include "bitmap_class.h"
#include "sprite_class.h" #include "sprite_class.h"
@ -28,16 +31,7 @@
#include "physics.h" #include "physics.h"
#include "frustum.h" #include "frustum.h"
#include "skybox.h" #include "skybox.h"
#include "shadow_map.h"
#include "stats.h"
#include "ecs/components/identity_component.h"
#include "ecs/components/render_component.h"
#include "ecs/components/transform_component.h"
#include "ecs/components/physics_component.h"
#include "ecs/components/shader_component.h"
#include "ecs/systems/render_system.h"
#include "ecs/components/model_path_component.h"
#include <fstream> #include <fstream>
#include <WICTextureLoader.h> #include <WICTextureLoader.h>
@ -49,10 +43,9 @@
#include <DirectXMath.h> #include <DirectXMath.h>
#include <mutex> #include <mutex>
#include <memory> #include <memory>
#include <vector>
#include <filesystem>
#include "ecs/entity_manager.h" #include "shadow_map.h"
#include "stats.h"
///////////// /////////////
@ -105,12 +98,17 @@ 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);
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; };
std::filesystem::path get_w_folder() const { return w_folder_; }; std::filesystem::path get_w_folder() const { return w_folder_; };
int get_terrain_entity_count();
int get_object_id() const { return object_id_; }; int get_object_id() const { return object_id_; };
void set_object_id(int object_id) { object_id_ = object_id; }; void set_object_id(int object_id) { object_id_ = object_id; };
@ -130,20 +128,14 @@ public:
void set_cel_shading(const bool enable) { enable_cel_shading_ = enable; }; void set_cel_shading(const bool enable) { enable_cel_shading_ = enable; };
void set_vsync(bool vsync) { void set_vsync(bool vsync);
vsync_enabled_ = vsync;
if (direct_3d_) {
direct_3d_->set_vsync(vsync);
Logger::Get().Log("Setting Vsync to " + std::to_string(vsync), __FILE__, __LINE__);
}
};
bool get_vsync() const { return vsync_enabled_; }; bool get_vsync() const { return vsync_enabled_; };
HWND get_hwnd() const { return hwnd_; }; HWND get_hwnd() const;
void set_hwnd(HWND hwnd) { hwnd_ = hwnd; }; void set_hwnd(HWND hwnd);
bool is_windowed() const { return windowed_; }; bool is_windowed() const;
void set_windowed(bool windowed) { windowed_ = windowed; }; void set_windowed(bool windowed);
void set_window_size(const ImVec2 size) { window_size_ = size; }; void set_window_size(const ImVec2 size) { window_size_ = size; };
ImVec2 get_window_size() const { return window_size_; }; ImVec2 get_window_size() const { return window_size_; };
@ -159,7 +151,6 @@ public:
void set_frustum(const frustum& frustum) { frustum_culling_ = frustum; }; void set_frustum(const frustum& frustum) { frustum_culling_ = frustum; };
void construct_frustum(); void construct_frustum();
int get_render_count() const { return render_count_; }; int get_render_count() const { return render_count_; };
void set_render_count(const int render_count) { render_count_ = render_count; }; void set_render_count(const int render_count) { render_count_ = render_count; };
float get_frustum_tolerance() const { return frustum_culling_tolerance_; }; float get_frustum_tolerance() const { return frustum_culling_tolerance_; };
@ -173,23 +164,18 @@ public:
stats* get_stats() const { return stats_; }; stats* get_stats() const { return stats_; };
fps_class* get_fps() const { return fps_; }; fps_class* get_fps() const { return fps_; };
ecs::EntityManager* get_entity_manager() const { return entity_manager_.get(); };
void update_stats_after_modification();
std::map<std::string, std::shared_ptr<model_class>>& get_model_cache() { return g_model_cache; }
private: private:
bool render(float, float, float, float, float); bool render(float, float, float, float, float);
bool render_physics(float delta_time); bool render_physics(bool key_left, bool key_right, bool key_up, bool key_down, float delta_time);
bool update_mouse_strings(int, int, bool); bool update_mouse_strings(int, int, bool);
bool update_fps(); bool update_fps();
bool update_render_count_string(int); bool update_render_count_string(int);
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(XMFLOAT4* diffuse, XMFLOAT4* position, XMFLOAT4* ambient, XMMATRIX view, XMMATRIX projection); bool render_pass(const std::vector<std::reference_wrapper<std::vector<object*>>>& RenderQueues, XMFLOAT4* diffuse, XMFLOAT4* position, XMFLOAT4* ambient, XMMATRIX view, XMMATRIX projection);
void update_skybox_position(); void update_skybox_position();
void culling_thread_function();
public : public :
std::vector<ID3D11ShaderResourceView*> textures; std::vector<ID3D11ShaderResourceView*> textures;
@ -200,6 +186,8 @@ private :
std::thread culling_thread_; std::thread culling_thread_;
std::atomic<bool> culling_active_; std::atomic<bool> culling_active_;
std::mutex objects_mutex_; std::mutex objects_mutex_;
void culling_thread_function();
std::mutex terrain_mutex_; std::mutex terrain_mutex_;
std::vector<std::tuple<float, float, float, std::string, int>> terrain_generation_data_; std::vector<std::tuple<float, float, float, std::string, int>> terrain_generation_data_;
@ -240,13 +228,14 @@ private :
// ------------- OBJECTS -------------- // // ------------- OBJECTS -------------- //
// ------------------------------------ // // ------------------------------------ //
std::unique_ptr<ecs::EntityManager> entity_manager_;
object* selected_object_; object* selected_object_;
std::vector<object*> cubes_;
std::vector<object*> terrain_chunk_;
float speed_ = 0.1f; // speed for the demo spinning object float speed_ = 0.1f; // speed for the demo spinning object
std::vector<object*> 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

@ -1,43 +0,0 @@
#pragma once
#include <memory>
#include <typeindex>
#include <typeinfo>
namespace ecs {
// Classe de base pour tous les composants
class Component {
public:
Component() = default;
virtual ~Component() = default;
// Empêcher la copie
Component(const Component&) = delete;
Component& operator=(const Component&) = delete;
// Permettre le déplacement
Component(Component&&) = default;
Component& operator=(Component&&) = default;
// Fonction virtuelle pour initialiser le composant
virtual void Initialize() {}
// Fonction virtuelle pour la mise à jour du composant
virtual void Update(float deltaTime) {}
// virtual std::string Serialize() {}
// virtual void Deserialize(const std::string& data) {}
};
// Alias utiles
using ComponentPtr = std::shared_ptr<Component>;
using ComponentTypeID = std::type_index;
// Fonction pour obtenir l'ID de type d'un composant
template<typename T>
ComponentTypeID GetComponentTypeID() {
static_assert(std::is_base_of<Component, T>::value, "T must derive from Component");
return std::type_index(typeid(T));
}
} // namespace ecs

View File

@ -1,58 +0,0 @@
#pragma once
#include "../component.h"
#include <string>
namespace ecs {
enum class ObjectType
{
Sphere,
Cube,
Terrain,
Unknown
};
class IdentityComponent : public Component {
public:
IdentityComponent() : m_id(0), m_type(ObjectType::Unknown) {}
explicit IdentityComponent(int id) : m_id(id), m_type(ObjectType::Unknown) {}
IdentityComponent(int id, const std::string& name) : m_id(id), m_name(name), m_type(ObjectType::Unknown) {}
~IdentityComponent() = default;
void Initialize() override {}
//void Update(float deltaTime) override {}
// Getters et setters
int GetId() const { return m_id; }
void SetId(int id) { m_id = id; }
const std::string& GetName() const { return m_name; }
void SetName(const std::string& name) { m_name = name; }
ObjectType GetType() const { return m_type; }
void SetType(ObjectType type) { m_type = type; }
// Conversions utiles
static std::string ObjectTypeToString(ObjectType type) {
switch (type) {
case ObjectType::Cube: return "Cube";
case ObjectType::Sphere: return "Sphere";
case ObjectType::Terrain: return "Terrain";
default: return "Unknown";
}
}
static ObjectType StringToObjectType(const std::string& str) {
if (str == "Cube") return ObjectType::Cube;
if (str == "Sphere") return ObjectType::Sphere;
if (str == "Terrain") return ObjectType::Terrain;
return ObjectType::Unknown;
}
private:
int m_id;
std::string m_name;
ObjectType m_type;
};
} // namespace ecs

View File

@ -1,24 +0,0 @@
#pragma once
#include "../component.h"
#include <string>
namespace ecs {
class ModelPathComponent : public Component {
public:
ModelPathComponent() = default;
explicit ModelPathComponent(const std::wstring& path) : m_path(path) {}
~ModelPathComponent() = default;
void Initialize() override {}
void Update(float deltaTime) override {}
// Getters et setters
const std::wstring& GetPath() const { return m_path; }
void SetPath(const std::wstring& path) { m_path = path; }
private:
std::wstring m_path;
};
} // namespace ecs

View File

@ -1,110 +0,0 @@
#pragma once
#include "../component.h"
#include <DirectXMath.h>
using namespace DirectX;
namespace ecs {
class PhysicsComponent : public Component {
public:
PhysicsComponent() {
m_Velocity = XMVectorZero();
m_Acceleration = XMVectorZero();
m_PreviousPosition = XMVectorZero();
m_Mass = 1.0f;
m_BoundingRadius = 1.0f;
m_IsGrounded = false;
m_IsPhysicsEnabled = false;
m_GravityEnabled = true;
}
~PhysicsComponent() = default;
void Initialize() override {
// Initialisation du composant physique
}
void Update(float deltaTime) override {
if (!m_IsPhysicsEnabled) return;
// Mise à jour de la vélocité basée sur l'accélération
m_Velocity = m_Velocity + m_Acceleration * deltaTime;
// Si la physique est activée et qu'une fonction de mise à jour de position est définie
if (m_UpdatePositionCallback) {
m_UpdatePositionCallback(m_Velocity * deltaTime);
}
}
// Lancement d'un objet
void LaunchObject(float alpha, float initialStretch, float springConstant) {
// Constants
const float gravity = -9.81f;
// Convert alpha from degrees to radians if needed
float alphaRadians = alpha * (XM_PI / 180.0f);
// Scale factors to make the physics simulation more visible
float scaleFactor = 200.0f; // Adjust this based on your world scale
// Calculate initial velocity magnitude
float velocityMagnitude = initialStretch * sqrtf(springConstant / m_Mass) *
sqrtf(1.0f - powf((m_Mass * gravity * sinf(alphaRadians) /
(springConstant * initialStretch)), 2.0f));
// Apply scale factor
velocityMagnitude *= scaleFactor;
// Calculate velocity components
XMVECTOR velocity = XMVectorSet(
velocityMagnitude * cosf(alphaRadians), // vx = v0 * cos(alpha)
velocityMagnitude * sinf(alphaRadians), // vy = v0 * sin(alpha)
0.0f, // z-component (0 for 2D trajectory)
0.0f
);
// Apply velocity
SetVelocity(velocity);
// Enable physics and reset grounded state
SetPhysicsEnabled(true);
SetGrounded(false);
}
// Setters
void SetVelocity(XMVECTOR velocity) { m_Velocity = velocity; }
void SetAcceleration(XMVECTOR acceleration) { m_Acceleration = acceleration; }
void SetMass(float mass) { m_Mass = mass; }
void SetGrounded(bool isGrounded) { m_IsGrounded = isGrounded; }
void SetPhysicsEnabled(bool enabled) { m_IsPhysicsEnabled = enabled; }
void SetBoundingRadius(float radius) { m_BoundingRadius = radius; }
void SetPreviousPosition(XMVECTOR position) { m_PreviousPosition = position; }
void SetGravityEnabled(bool enabled) { m_GravityEnabled = enabled; }
void SetUpdatePositionCallback(std::function<void(XMVECTOR)> callback) { m_UpdatePositionCallback = callback; }
// Getters
XMVECTOR GetVelocity() const { return m_Velocity; }
XMVECTOR GetAcceleration() const { return m_Acceleration; }
float GetMass() const { return m_Mass; }
bool IsGrounded() const { return m_IsGrounded; }
bool IsPhysicsEnabled() const { return m_IsPhysicsEnabled; }
float GetBoundingRadius() const { return m_BoundingRadius; }
XMVECTOR GetPreviousPosition() const { return m_PreviousPosition; }
bool IsGravityEnabled() const { return m_GravityEnabled; }
private:
XMVECTOR m_Velocity;
XMVECTOR m_Acceleration;
XMVECTOR m_PreviousPosition;
float m_Mass;
float m_BoundingRadius;
bool m_IsGrounded;
bool m_IsPhysicsEnabled;
bool m_GravityEnabled;
// Callback pour mettre à jour la position (sera connecté au TransformComponent)
std::function<void(XMVECTOR)> m_UpdatePositionCallback;
};
} // namespace ecs

View File

@ -1,124 +0,0 @@
#pragma once
#include "../component.h"
#include "model_class.h"
#include <memory>
#include <string>
#include <map>
#include <WICTextureLoader.h>
// Déclaration externe de la variable globale définie dans application_class.h
extern std::map<std::string, std::shared_ptr<model_class>> g_model_cache;
namespace ecs {
enum class TextureType
{
Diffuse,
Normal,
Specular,
Alpha,
Reflection
};
class RenderComponent : public Component {
public:
RenderComponent() : m_model(nullptr), m_isVisible(true) {}
~RenderComponent() = default;
void Initialize() override {}
void Update(float deltaTime) override {}
// Initialisation avec un modèle existant
bool InitializeWithModel(std::shared_ptr<model_class> model) {
if (!model) return false;
m_model = model;
return true;
}
// Initialisation avec un chemin de fichier
bool InitializeFromFile(ID3D11Device* device, ID3D11DeviceContext* deviceContext,
const char* modelFilename, TextureContainer& textureContainer) {
// Vérifier si le modèle existe déjà dans le cache
std::string filename(modelFilename);
auto it = g_model_cache.find(filename);
if (it != g_model_cache.end()) {
m_model = it->second;
} else {
// Créer un nouveau modèle
auto new_model = std::make_shared<model_class>();
if (!new_model->Initialize(device, deviceContext, const_cast<char*>(modelFilename), textureContainer)) {
return false;
}
g_model_cache[filename] = new_model;
m_model = new_model;
}
m_modelFilePath = modelFilename;
return true;
}
// Charger des textures depuis un chemin
bool LoadTexturesFromPath(std::vector<std::wstring>& texturePaths, TextureContainer& texturesContainer,
ID3D11Device* device, ID3D11DeviceContext* deviceContext) {
HRESULT result;
int i = 0;
for (const auto& texturePath : texturePaths) {
ID3D11ShaderResourceView* texture = nullptr;
result = DirectX::CreateWICTextureFromFile(device, deviceContext, texturePath.c_str(), nullptr, &texture);
if (FAILED(result)) {
return false;
}
texturesContainer.AssignTexture(texturesContainer, texture, texturePath, i);
i++;
}
return true;
}
// Getters et setters
std::shared_ptr<model_class> GetModel() const { return m_model; }
void SetModel(std::shared_ptr<model_class> model) { m_model = model; }
const std::string& GetModelFilePath() const { return m_modelFilePath; }
void SetModelFilePath(const std::string& path) { m_modelFilePath = path; }
bool IsVisible() const { return m_isVisible; }
void SetVisible(bool visible) { m_isVisible = visible; }
// Accès aux textures
ID3D11ShaderResourceView* GetTexture(TextureType type, int index = 0) {
if (!m_model) return nullptr;
switch (type) {
case TextureType::Diffuse:
return m_model->GetTexture(::TextureType::Diffuse, index);
case TextureType::Normal:
return m_model->GetTexture(::TextureType::Normal, index);
case TextureType::Specular:
return m_model->GetTexture(::TextureType::Specular, index);
case TextureType::Alpha:
return m_model->GetTexture(::TextureType::Alpha, index);
default:
return nullptr;
}
}
// Pour le rendu
int GetIndexCount() const {
return m_model ? m_model->GetIndexCount() : 0;
}
void Render(ID3D11DeviceContext* deviceContext) {
if (m_model && m_isVisible) {
m_model->Render(deviceContext);
}
}
private:
std::shared_ptr<model_class> m_model;
std::string m_modelFilePath;
bool m_isVisible;
};
} // namespace ecs

View File

@ -1,67 +0,0 @@
#pragma once
#include "../component.h"
namespace ecs {
enum class ShaderType
{
CEL_SHADING,
LIGHTING,
NORMAL_MAPPING,
SPECULAR_MAPPING,
REFLECTION,
REFRACTION,
TEXTURE,
SKYBOX,
SUNLIGHT,
ALPHA_MAPPING
};
class ShaderComponent : public Component {
public:
ShaderComponent() : m_activeShader(ShaderType::LIGHTING) {}
~ShaderComponent() = default;
void Initialize() override {}
void Update(float deltaTime) override {}
// Getters et setters
ShaderType GetActiveShader() const { return m_activeShader; }
void SetActiveShader(ShaderType shader) { m_activeShader = shader; }
// Conversions utiles
static ShaderType StringToShaderType(const std::string& str) {
if (str == "ALPHA_MAPPING") return ShaderType::ALPHA_MAPPING;
if (str == "CEL_SHADING") return ShaderType::CEL_SHADING;
if (str == "NORMAL_MAPPING") return ShaderType::NORMAL_MAPPING;
if (str == "SPECULAR_MAPPING") return ShaderType::SPECULAR_MAPPING;
if (str == "TEXTURE") return ShaderType::TEXTURE;
if (str == "LIGHTING") return ShaderType::LIGHTING;
if (str == "SUNLIGHT") return ShaderType::SUNLIGHT;
if (str == "SKYBOX") return ShaderType::SKYBOX;
if (str == "REFLECTION") return ShaderType::REFLECTION;
if (str == "REFRACTION") return ShaderType::REFRACTION;
return ShaderType::TEXTURE;
}
static std::string ShaderTypeToString(ShaderType type) {
switch (type) {
case ShaderType::ALPHA_MAPPING: return "ALPHA_MAPPING";
case ShaderType::CEL_SHADING: return "CEL_SHADING";
case ShaderType::NORMAL_MAPPING: return "NORMAL_MAPPING";
case ShaderType::SPECULAR_MAPPING: return "SPECULAR_MAPPING";
case ShaderType::TEXTURE: return "TEXTURE";
case ShaderType::LIGHTING: return "LIGHTING";
case ShaderType::SUNLIGHT: return "SUNLIGHT";
case ShaderType::SKYBOX: return "SKYBOX";
case ShaderType::REFLECTION: return "REFLECTION";
case ShaderType::REFRACTION: return "REFRACTION";
default: return "TEXTURE";
}
}
private:
ShaderType m_activeShader;
};
} // namespace ecs

View File

@ -1,101 +0,0 @@
#pragma once
#include "../component.h"
#include <DirectXMath.h>
using namespace DirectX;
namespace ecs {
class TransformComponent : public Component {
public:
TransformComponent() {
m_ScaleMatrix = XMMatrixIdentity();
m_RotateMatrix = XMMatrixIdentity();
m_TranslateMatrix = XMMatrixIdentity();
m_WorldMatrix = XMMatrixIdentity();
}
~TransformComponent() = default;
// Méthodes pour les matrices
void SetPosition(XMVECTOR position) {
XMFLOAT4X4 matrix;
XMStoreFloat4x4(&matrix, m_TranslateMatrix);
matrix._41 = XMVectorGetX(position);
matrix._42 = XMVectorGetY(position);
matrix._43 = XMVectorGetZ(position);
m_TranslateMatrix = XMLoadFloat4x4(&matrix);
UpdateWorldMatrix();
}
void SetRotation(XMVECTOR rotation) {
m_RotateMatrix = XMMatrixRotationRollPitchYawFromVector(rotation);
UpdateWorldMatrix();
}
void SetScale(XMVECTOR scale) {
XMFLOAT4X4 matrix;
XMStoreFloat4x4(&matrix, m_ScaleMatrix);
matrix._11 = XMVectorGetX(scale);
matrix._22 = XMVectorGetY(scale);
matrix._33 = XMVectorGetZ(scale);
m_ScaleMatrix = XMLoadFloat4x4(&matrix);
UpdateWorldMatrix();
}
XMVECTOR GetPosition() const {
XMFLOAT4X4 matrix;
XMStoreFloat4x4(&matrix, m_TranslateMatrix);
return XMVectorSet(matrix._41, matrix._42, matrix._43, 0.0f);
}
XMVECTOR GetRotation() const {
XMFLOAT4X4 matrix;
XMStoreFloat4x4(&matrix, m_RotateMatrix);
float rotationX = atan2f(matrix._32, matrix._33);
float rotationY = atan2f(-matrix._31, sqrtf(matrix._32 * matrix._32 + matrix._33 * matrix._33));
float rotationZ = atan2f(matrix._21, matrix._11);
return XMVectorSet(rotationX, rotationY, rotationZ, 0.0f);
}
XMVECTOR GetScale() const {
XMFLOAT4X4 matrix;
XMStoreFloat4x4(&matrix, m_ScaleMatrix);
XMVECTOR row1 = XMLoadFloat3(reinterpret_cast<XMFLOAT3*>(&matrix._11));
XMVECTOR row2 = XMLoadFloat3(reinterpret_cast<XMFLOAT3*>(&matrix._21));
XMVECTOR row3 = XMLoadFloat3(reinterpret_cast<XMFLOAT3*>(&matrix._31));
XMVECTOR scale = XMVectorSet(
XMVectorGetX(XMVector3Length(row1)),
XMVectorGetX(XMVector3Length(row2)),
XMVectorGetX(XMVector3Length(row3)),
0.0f
);
return scale;
}
void UpdateWorldMatrix() {
m_WorldMatrix = m_ScaleMatrix * m_RotateMatrix * m_TranslateMatrix;
}
// Getters pour les matrices
XMMATRIX GetScaleMatrix() const { return m_ScaleMatrix; }
XMMATRIX GetRotateMatrix() const { return m_RotateMatrix; }
XMMATRIX GetTranslateMatrix() const { return m_TranslateMatrix; }
XMMATRIX GetWorldMatrix() const { return m_WorldMatrix; }
// Setters pour les matrices
void SetScaleMatrix(XMMATRIX matrix) { m_ScaleMatrix = matrix; UpdateWorldMatrix(); }
void SetRotateMatrix(XMMATRIX matrix) { m_RotateMatrix = matrix; UpdateWorldMatrix(); }
void SetTranslateMatrix(XMMATRIX matrix) { m_TranslateMatrix = matrix; UpdateWorldMatrix(); }
private:
XMMATRIX m_ScaleMatrix;
XMMATRIX m_RotateMatrix;
XMMATRIX m_TranslateMatrix;
XMMATRIX m_WorldMatrix;
};
} // namespace ecs

View File

@ -1,101 +0,0 @@
#pragma once
#include "component.h"
#include <unordered_map>
#include <vector>
#include <memory>
#include <algorithm>
#include <cassert>
namespace ecs {
// Identifiant unique pour les entités
using EntityID = uint32_t;
class Entity {
public:
explicit Entity(EntityID id) : m_ID(id) {}
~Entity() = default;
// Empêcher la copie
Entity(const Entity&) = delete;
Entity& operator=(const Entity&) = delete;
// Permettre le déplacement
Entity(Entity&&) = default;
Entity& operator=(Entity&&) = default;
// Getter pour l'ID
EntityID GetID() const { return m_ID; }
// Ajouter un composant
template<typename T, typename... Args>
std::shared_ptr<T> AddComponent(Args&&... args) {
static_assert(std::is_base_of<Component, T>::value, "T must derive from Component");
ComponentTypeID typeID = GetComponentTypeID<T>();
// Vérifier si le composant existe déjà
if (m_Components.find(typeID) != m_Components.end()) {
return std::static_pointer_cast<T>(m_Components[typeID]);
}
// Créer et ajouter le composant
auto component = std::make_shared<T>(std::forward<Args>(args)...);
m_Components[typeID] = component;
// Initialiser le composant
component->Initialize();
return component;
}
// Récupérer un composant
template<typename T>
std::shared_ptr<T> GetComponent() {
static_assert(std::is_base_of<Component, T>::value, "T must derive from Component");
ComponentTypeID typeID = GetComponentTypeID<T>();
auto it = m_Components.find(typeID);
if (it != m_Components.end()) {
return std::static_pointer_cast<T>(it->second);
}
return nullptr;
}
// Vérifier si l'entité possède un composant
template<typename T>
bool HasComponent() const {
static_assert(std::is_base_of<Component, T>::value, "T must derive from Component");
ComponentTypeID typeID = GetComponentTypeID<T>();
return m_Components.find(typeID) != m_Components.end();
}
// Supprimer un composant
template<typename T>
void RemoveComponent() {
static_assert(std::is_base_of<Component, T>::value, "T must derive from Component");
ComponentTypeID typeID = GetComponentTypeID<T>();
auto it = m_Components.find(typeID);
if (it != m_Components.end()) {
m_Components.erase(it);
}
}
// Mettre à jour tous les composants
void UpdateComponents(float deltaTime) {
for (auto& [typeID, component] : m_Components) {
component->Update(deltaTime);
}
}
private:
EntityID m_ID;
std::unordered_map<ComponentTypeID, ComponentPtr> m_Components;
};
} // namespace ecs

View File

@ -1,107 +0,0 @@
#pragma once
#include "entity.h"
#include <vector>
#include <unordered_map>
#include <queue>
namespace ecs {
class EntityManager {
public:
EntityManager() : m_NextEntityID(0) {}
~EntityManager() = default;
// Créer une nouvelle entité
std::shared_ptr<Entity> CreateEntity() {
EntityID id;
// Réutiliser les IDs des entités supprimées si possible
if (!m_FreeIDs.empty()) {
id = m_FreeIDs.front();
m_FreeIDs.pop();
} else {
id = m_NextEntityID++;
}
auto entity = std::make_shared<Entity>(id);
m_Entities[id] = entity;
return entity;
}
// Supprimer une entité
void DestroyEntity(EntityID id) {
auto it = m_Entities.find(id);
if (it != m_Entities.end()) {
m_Entities.erase(it);
m_FreeIDs.push(id); // Recycler l'ID
}
}
// Obtenir une entité par son ID
std::shared_ptr<Entity> GetEntity(EntityID id) {
auto it = m_Entities.find(id);
if (it != m_Entities.end()) {
return it->second;
}
return nullptr;
}
// Mettre à jour toutes les entités
void UpdateEntities(float deltaTime) {
for (auto& [id, entity] : m_Entities) {
entity->UpdateComponents(deltaTime);
}
}
// Obtenir toutes les entités
std::vector<std::shared_ptr<Entity>> GetAllEntities() {
std::vector<std::shared_ptr<Entity>> result;
result.reserve(m_Entities.size());
for (const auto& [id, entity] : m_Entities) {
result.push_back(entity);
}
return result;
}
// Obtenir toutes les entités qui ont un composant spécifique
template<typename T>
std::vector<std::shared_ptr<Entity>> GetEntitiesWithComponent() {
static_assert(std::is_base_of<Component, T>::value, "T must derive from Component");
std::vector<std::shared_ptr<Entity>> result;
for (auto& [id, entity] : m_Entities) {
if (entity->HasComponent<T>()) {
result.push_back(entity);
}
}
return result;
}
// Obtenir le nombre d'entités
size_t GetEntityCount() const {
return m_Entities.size();
}
// Vider toutes les entités
void Clear() {
m_Entities.clear();
// Vider la file des IDs libres
std::queue<EntityID> empty;
std::swap(m_FreeIDs, empty);
m_NextEntityID = 0;
}
private:
EntityID m_NextEntityID;
std::unordered_map<EntityID, std::shared_ptr<Entity>> m_Entities;
std::queue<EntityID> m_FreeIDs; // IDs à réutiliser
};
} // namespace ecs

View File

@ -1,222 +0,0 @@
#pragma once
#include "../entity_manager.h"
#include "../components/render_component.h"
#include "../components/transform_component.h"
#include "../components/shader_component.h"
#include "shader_manager_class.h"
#include <DirectXMath.h>
namespace ecs {
class RenderSystem {
public:
RenderSystem(ID3D11DeviceContext* deviceContext, shader_manager_class* shaderManager)
: m_deviceContext(deviceContext), m_shaderManager(shaderManager) {}
// Rendu d'une entité spécifique
bool RenderEntity(std::shared_ptr<Entity> entity,
const DirectX::XMMATRIX& viewMatrix,
const DirectX::XMMATRIX& projectionMatrix,
const DirectX::XMFLOAT4* diffuseColors,
const DirectX::XMFLOAT4* lightPositions,
const DirectX::XMFLOAT4* ambientColors,
const DirectX::XMFLOAT3& cameraPosition,
const DirectX::XMFLOAT4& sunlightDiffuse,
const DirectX::XMFLOAT4& sunlightAmbient,
const DirectX::XMFLOAT3& sunlightDirection,
float sunlightIntensity) {
// Vérifier si l'entité a tous les composants nécessaires
auto transform = entity->GetComponent<TransformComponent>();
auto render = entity->GetComponent<RenderComponent>();
auto shader = entity->GetComponent<ShaderComponent>();
if (!transform || !render || !shader || !render->GetModel())
return false;
// Calculer la matrice monde
XMMATRIX scaleMatrix = transform->GetScaleMatrix();
XMMATRIX rotateMatrix = transform->GetRotateMatrix();
XMMATRIX translateMatrix = transform->GetTranslateMatrix();
XMMATRIX worldMatrix = XMMatrixMultiply(
XMMatrixMultiply(scaleMatrix, rotateMatrix),
translateMatrix
);
// Rendre le modèle
render->Render(m_deviceContext);
// Sélectionner le shader approprié
switch (shader->GetActiveShader()) {
case ShaderType::ALPHA_MAPPING:
return m_shaderManager->render_alpha_map_shader(
m_deviceContext,
render->GetIndexCount(),
worldMatrix,
viewMatrix,
projectionMatrix,
render->GetTexture(TextureType::Diffuse, 0),
render->GetTexture(TextureType::Diffuse, 1),
render->GetTexture(TextureType::Alpha, 0)
);
case ShaderType::CEL_SHADING:
return m_shaderManager->render_cel_shading_shader(
m_deviceContext,
render->GetIndexCount(),
worldMatrix,
viewMatrix,
projectionMatrix,
render->GetTexture(TextureType::Diffuse, 0),
sunlightDiffuse,
sunlightAmbient,
sunlightDirection,
sunlightIntensity
);
case ShaderType::NORMAL_MAPPING:
return m_shaderManager->render_normal_map_shader(
m_deviceContext,
render->GetIndexCount(),
worldMatrix,
viewMatrix,
projectionMatrix,
render->GetTexture(TextureType::Diffuse, 0),
render->GetTexture(TextureType::Normal, 0),
sunlightDirection,
sunlightDiffuse
);
case ShaderType::SPECULAR_MAPPING:
return m_shaderManager->render_spec_map_shader(
m_deviceContext,
render->GetIndexCount(),
worldMatrix,
viewMatrix,
projectionMatrix,
render->GetTexture(TextureType::Diffuse, 0),
render->GetTexture(TextureType::Normal, 0),
render->GetTexture(TextureType::Specular, 0),
sunlightDirection,
sunlightDiffuse,
cameraPosition,
sunlightDiffuse, // Couleur speculaire (à ajuster)
16.0f // Puissance speculaire (à ajuster)
);
case ShaderType::LIGHTING:
{
// Créer des copies locales non constantes des tableaux
DirectX::XMFLOAT4 localDiffuseColors[4];
DirectX::XMFLOAT4 localLightPositions[4];
DirectX::XMFLOAT4 localAmbientColors[4];
// Copier les données
for (int i = 0; i < 4; i++) {
localDiffuseColors[i] = diffuseColors[i];
localLightPositions[i] = lightPositions[i];
localAmbientColors[i] = ambientColors[i];
}
return m_shaderManager->renderlight_shader(
m_deviceContext,
render->GetIndexCount(),
worldMatrix,
viewMatrix,
projectionMatrix,
render->GetTexture(TextureType::Diffuse, 0),
localDiffuseColors,
localLightPositions,
localAmbientColors
);
}
case ShaderType::SUNLIGHT:
return m_shaderManager->render_sunlight_shader(
m_deviceContext,
render->GetIndexCount(),
worldMatrix,
viewMatrix,
projectionMatrix,
render->GetTexture(TextureType::Diffuse, 0),
sunlightDiffuse,
sunlightAmbient,
sunlightDirection,
sunlightIntensity
);
case ShaderType::SKYBOX:
return m_shaderManager->render_skybox_shader(
m_deviceContext,
render->GetIndexCount(),
worldMatrix,
viewMatrix,
projectionMatrix,
render->GetTexture(TextureType::Diffuse, 0),
sunlightDiffuse,
sunlightAmbient,
sunlightDirection,
sunlightIntensity
);
case ShaderType::TEXTURE:
default:
return m_shaderManager->render_texture_shader(
m_deviceContext,
render->GetIndexCount(),
worldMatrix,
viewMatrix,
projectionMatrix,
render->GetTexture(TextureType::Diffuse, 0)
);
}
}
// Rendu de toutes les entités avec les composants nécessaires
int RenderAllEntities(EntityManager* entityManager,
const DirectX::XMMATRIX& viewMatrix,
const DirectX::XMMATRIX& projectionMatrix,
const DirectX::XMFLOAT4* diffuseColors,
const DirectX::XMFLOAT4* lightPositions,
const DirectX::XMFLOAT4* ambientColors,
const DirectX::XMFLOAT3& cameraPos,
const DirectX::XMFLOAT4& sunlightDiffuse,
const DirectX::XMFLOAT4& sunlightAmbient,
const DirectX::XMFLOAT3& sunlightDirection,
float sunlightIntensity) {
int renderCount = 0;
// Récupérer toutes les entités qui ont les composants RenderComponent et TransformComponent
auto entities = entityManager->GetEntitiesWithComponent<RenderComponent>();
for (auto& entity : entities) {
auto render = entity->GetComponent<RenderComponent>();
// Vérifier si l'entité a un TransformComponent
auto transform = entity->GetComponent<TransformComponent>();
if (!transform) continue;
// Vérifier si le modèle est visible
if (!render->IsVisible()) continue;
// Effectuer le rendu
if (RenderEntity(entity, viewMatrix, projectionMatrix,
diffuseColors, lightPositions, ambientColors,cameraPos,
sunlightDiffuse, sunlightAmbient, sunlightDirection,
sunlightIntensity)) {
renderCount++;
}
}
return renderCount;
}
private:
ID3D11DeviceContext* m_deviceContext;
shader_manager_class* m_shaderManager;
};
} // namespace ecs

View File

@ -106,12 +106,9 @@ private:
const std::deque<Logger::LogEntry>& logBuffer = Logger::Get().GetLogBuffer(); const std::deque<Logger::LogEntry>& logBuffer = Logger::Get().GetLogBuffer();
int current_fps_, min_fps_, max_fps_, draw_calls_, visible_triangle_count_; int current_fps_, min_fps_, max_fps_, draw_calls_, total_vertex_count_, total_triangle_count_, visible_triangle_count_;
float current_frame_time_, min_frame_time_, max_frame_time_ ; float current_frame_time_, min_frame_time_, max_frame_time_ ;
std::shared_ptr<int> total_vertex_count_;
std::shared_ptr<int> total_triangle_count_;
// gpu information // gpu information
char card_name_[128]; char card_name_[128];
int video_memory_ = 0; int video_memory_ = 0;

View File

@ -3,8 +3,6 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include "ecs/entity.h"
class d_3d_class; class d_3d_class;
class object; class object;
class application_class; class application_class;
@ -28,8 +26,6 @@ public:
private: private:
std::vector<std::shared_ptr<ecs::Entity>> entity_;
application_class* app_; application_class* app_;
std::string scene_path_; std::string scene_path_;
std::vector<object*> object_vec_; std::vector<object*> object_vec_;

View File

@ -18,7 +18,6 @@ public:
bool initialize(application_class* app); bool initialize(application_class* app);
void update_geometric_stats(); void update_geometric_stats();
void update_visible_count();
void update_display_stats(); void update_display_stats();
int get_total_vertex_count() const; int get_total_vertex_count() const;
@ -37,10 +36,6 @@ public:
std::string get_cpu_name(); std::string get_cpu_name();
std::string get_gpu_driver_version(ID3D11Device* device); std::string get_gpu_driver_version(ID3D11Device* device);
std::shared_ptr<int>& get_vertex_count_ptr() { return total_vertex_count_; }
std::shared_ptr<int>& get_triangle_count_ptr() { return total_triangle_count_; }
private: private:
std::thread update_display_thread_; std::thread update_display_thread_;
@ -52,9 +47,8 @@ private:
std::vector<object*> cubes_vec_; std::vector<object*> cubes_vec_;
std::vector<object*> terrain_chunk_vec_; std::vector<object*> terrain_chunk_vec_;
std::shared_ptr<int> total_vertex_count_; int total_vertex_count_;
std::shared_ptr<int> total_triangle_count_; int total_triangle_count_;
int visible_triangle_count_ = 0; int visible_triangle_count_ = 0;
int current_fps_ = 0; int current_fps_ = 0;
int min_fps_ = 0; int min_fps_ = 0;

View File

@ -28,6 +28,10 @@ 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;
@ -82,8 +86,10 @@ bool application_class::initialize(int screenWidth, int screenHeight, HWND hwnd,
bool result; bool result;
HRESULT Hresult; HRESULT Hresult;
// create entity manager render_queues_.push_back(std::ref(skybox_)); // Skybox doit être rendu en premier pour être derrière touts les autres objets
entity_manager_ = std::make_unique<ecs::EntityManager>(); render_queues_.push_back(std::ref(object_));
render_queues_.push_back(std::ref(cubes_));
render_queues_.push_back(std::ref(terrain_chunk_));
screen_width_ = screenWidth; screen_width_ = screenWidth;
screen_height_ = screenHeight; screen_height_ = screenHeight;
@ -1129,7 +1135,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(diffuseColor, lightPosition, ambientColor, viewMatrix, projectionMatrix); result = render_pass(render_queues_, 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);
@ -1149,7 +1155,7 @@ bool application_class::render(float rotation, float x, float y, float z, float
// return false; // return false;
// } // }
// stats_->update_geometric_stats(); stats_->update_geometric_stats();
// Update the render count text. // Update the render count text.
result = update_render_count_string(get_render_count()); result = update_render_count_string(get_render_count());
@ -1292,10 +1298,9 @@ 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 ECS", __FILE__, __LINE__, Logger::LogLevel::Info); Logger::Get().Log("Génération du terrain avec instanciation", __FILE__, __LINE__, Logger::LogLevel::Info);
// delete previous terrain if it exists terrain_chunk_.clear();
delete_terrain();
// Dimensions du terrain // Dimensions du terrain
float scaleX = 10.0f; float scaleX = 10.0f;
@ -1304,75 +1309,54 @@ void application_class::generate_terrain()
int gridSizeX = 20; int gridSizeX = 20;
int gridSizeZ = 20; int gridSizeZ = 20;
// Vérifier si le modèle existe déjà dans le cache // Créer un conteneur de textures_ partagé
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");
// Créer et initialiser le modèle si non trouvé // Précharger les textures_ une seule fois
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, modelName.c_str()); strcpy_s(modelFilename, "assets/Model/OBJ/plane.obj");
auto newModel = std::make_shared<model_class>(); // Générer les tuiles de terrain
newModel->PreloadTextures(direct_3d_->get_device(), direct_3d_->get_device_context(), textureContainer); for (int i = 0; i < gridSizeX; i++)
{
for (int j = 0; j < gridSizeZ; j++)
{
// Créer un nouvel objet de terrain
object* terrain = new object(*this);
if (!newModel->Initialize(direct_3d_->get_device(), direct_3d_->get_device_context(), modelFilename, textureContainer)) { // Initialiser avec le modèle et les textures_ préchargées
Logger::Get().Log("Impossible d'initialiser le modèle du terrain", __FILE__, __LINE__, Logger::LogLevel::Error); if (!terrain->Initialize(direct_3d_->get_device(), direct_3d_->get_device_context(), modelFilename, textureContainer))
return; {
Logger::Get().Log("Échec de l'initialisation d'une tuile de terrain", __FILE__, __LINE__, Logger::LogLevel::Error);
delete terrain;
continue;
} }
// Ajouter le modèle au cache // Définir la position dans la grille
g_model_cache[modelName] = newModel; XMFLOAT3 position(i * scaleX, -12.0f, j * scaleZ);
sharedModel = newModel; XMFLOAT3 scale(scaleX, scaleY, scaleZ);
Logger::Get().Log("Added terrain model to cache: " + modelName, __FILE__, __LINE__);
}
// Vérifier si l'entity manager est disponible terrain->SetPosition(XMLoadFloat3(&position));
if (entity_manager_) { terrain->SetScale(XMLoadFloat3(&scale));
// 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();
// Ajouter un composant d'identité // Configurer les propriétés
auto identity = entity->AddComponent<ecs::IdentityComponent>(object_id_++); terrain->SetName("TerrainTile_" + std::to_string(i) + "_" + std::to_string(j));
identity->SetName("TerrainTile_" + std::to_string(i) + "_" + std::to_string(j)); terrain->SetType(ObjectType::Cube);
identity->SetType(ecs::ObjectType::Terrain); terrain->SetActiveShader(ShaderType::SUNLIGHT);
terrain->SetId(object_id_++);
// Ajouter un composant de transformation // Ajouter à la liste des chunks de terrain
auto transform = entity->AddComponent<ecs::TransformComponent>(); terrain_chunk_.push_back(terrain);
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(); 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)
@ -1381,6 +1365,7 @@ void application_class::add_kobject(std::wstring& filepath)
Logger::Get().Log("Adding object", __FILE__, __LINE__); Logger::Get().Log("Adding object", __FILE__, __LINE__);
char modelFilename[128]; char modelFilename[128];
vector<string> Filename;
TextureContainer KobjectsTextures; TextureContainer KobjectsTextures;
filesystem::path p(filepath); filesystem::path p(filepath);
string filename = p.stem().string(); string filename = p.stem().string();
@ -1397,68 +1382,24 @@ void application_class::add_kobject(std::wstring& filepath)
L"assets/Texture/BricksGLOSS2K.png" L"assets/Texture/BricksGLOSS2K.png"
}; };
// Configurer les chemins des textures dans le conteneur object* newObject = new object(*this);
KobjectsTextures.diffusePaths.push_back(kobjTexture[0]); newObject->LoadTexturesFromPath(kobjTexture,KobjectsTextures, direct_3d_); // Load textures_ from the path
if (kobjTexture.size() > 1) KobjectsTextures.normalPaths.push_back(kobjTexture[1]); newObject->Initialize(direct_3d_->get_device(), direct_3d_->get_device_context(), modelFilename, KobjectsTextures);
if (kobjTexture.size() > 2) KobjectsTextures.specularPaths.push_back(kobjTexture[2]); newObject->SetMass(1.0f);
newObject->SetTranslateMatrix(XMMatrixTranslation(0.0f, 50.0f, 0.0f));
newObject->SetName(filename);
newObject->SetId(object_id_);
newObject->SetModelPath(filepath); // Store the path as std::wstring
// Vérifier si le modèle existe déjà dans le cache object_id_++;
std::string modelKey = std::string(modelFilename);
std::shared_ptr<model_class> sharedModel;
auto it = g_model_cache.find(modelKey); object_.push_back(newObject);
if (it != g_model_cache.end()) {
// Utiliser le modèle existant du cache // Vérifiez que l'objet a bien reçu les textures_
Logger::Get().Log("Using cached model for " + modelKey, __FILE__, __LINE__); if (newObject->get_model()->GetTexture(TextureType::Diffuse,0) == nullptr)
sharedModel = it->second; {
Logger::Get().Log("object texture is null after initialization", __FILE__, __LINE__, Logger::LogLevel::Error);
} }
else {
// Créer un nouveau modèle
sharedModel = std::make_shared<model_class>();
// Précharger les textures
sharedModel->PreloadTextures(direct_3d_->get_device(), direct_3d_->get_device_context(), KobjectsTextures);
// Initialiser le modèle
if (!sharedModel->Initialize(direct_3d_->get_device(), direct_3d_->get_device_context(), modelFilename, KobjectsTextures)) {
Logger::Get().Log("Failed to initialize model for object: " + modelKey, __FILE__, __LINE__, Logger::LogLevel::Error);
return;
}
// Ajouter le modèle au cache
g_model_cache[modelKey] = sharedModel;
Logger::Get().Log("Added model to cache: " + modelKey, __FILE__, __LINE__);
}
// Créer une nouvelle entité
auto entity = entity_manager_->CreateEntity();
// Ajouter un composant d'identité
auto identity = entity->AddComponent<ecs::IdentityComponent>(object_id_++);
identity->SetName(filename);
identity->SetType(ecs::ObjectType::Unknown);
// Ajouter un composant de transformation
auto transform = entity->AddComponent<ecs::TransformComponent>();
transform->SetPosition(XMVectorSet(0.0f, 50.0f, 0.0f, 0.0f));
transform->SetScale(XMVectorSet(1.0f, 1.0f, 1.0f, 0.0f));
transform->UpdateWorldMatrix();
// Ajouter un composant de rendu avec le modèle partagé
auto render = entity->AddComponent<ecs::RenderComponent>();
render->InitializeWithModel(sharedModel);
// Ajouter un composant de shader
auto shader = entity->AddComponent<ecs::ShaderComponent>();
shader->SetActiveShader(ecs::ShaderType::LIGHTING);
// Stocker le chemin du modèle
auto modelPath = entity->AddComponent<ecs::ModelPathComponent>();
modelPath->SetPath(filepath);
Logger::Get().Log("ECS entity created with ID: " + std::to_string(identity->GetId()), __FILE__, __LINE__);
update_stats_after_modification();
} }
void application_class::add_cube() void application_class::add_cube()
@ -1466,102 +1407,43 @@ 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__);
std::string model_name = "assets/Model/TXT/cube.txt"; char modelFilename[128];
std::shared_ptr<model_class> sharedModel; TextureContainer CubeTexture;
// Set the file name of the model.
strcpy_s(modelFilename, "assets/Model/TXT/cube.txt");
auto it = g_model_cache.find(model_name); // Liste des fichiers de texture
if (it != g_model_cache.end()) std::vector<std::wstring> cubeTexture = {
{ 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");
char model_filename[128]; static int cubeCount = 0;
strcpy_s(model_filename, model_name.c_str()); float position = cubeCount * 2.0f;
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));
auto newModel = std::make_shared<model_class>(); cubes_.push_back(newCube);
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();
Logger::Get().Log("Cube added successfully", __FILE__, __LINE__, Logger::LogLevel::Info);
} }
void application_class::delete_entity_by_id(int entity_id) void application_class::delete_kobject(int index)
{ {
std::lock_guard<std::mutex> lock(objects_mutex_); std::lock_guard<std::mutex> lock(objects_mutex_);
Logger::Get().Log("Deleting entity with ID: " + std::to_string(entity_id), __FILE__, __LINE__, Logger::LogLevel::Info); Logger::Get().Log("Deleting object", __FILE__, __LINE__);
if (entity_manager_) { if (index < object_.size())
// Rechercher l'entité avec l'ID spécifié via le composant IdentityComponent {
auto entities_with_identity = entity_manager_->GetEntitiesWithComponent<ecs::IdentityComponent>(); object_.erase(object_.begin() + index);
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();
} }
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::LogLevel::Info); Logger::Get().Log("Deleting terrain", __FILE__, __LINE__);
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();
} }
bool application_class::update_mouse_strings(int mouseX, int mouseY, bool mouseDown) bool application_class::update_mouse_strings(int mouseX, int mouseY, bool mouseDown)
@ -1755,6 +1637,39 @@ void application_class::set_light_position(int index, XMVECTOR position)
lights_[index]->SetPosition(lightPosition.x, lightPosition.y, lightPosition.z); lights_[index]->SetPosition(lightPosition.x, lightPosition.y, lightPosition.z);
} }
void application_class::set_vsync(bool vsync)
{
vsync_enabled_ = vsync;
if (direct_3d_)
{
Logger::Get().Log("Setting Vsync to " + std::to_string(vsync) + " with a screen width : " + std::to_string(get_screen_width()) + "and a screen height : " + std::to_string(get_screen_height()), __FILE__, __LINE__);
direct_3d_->set_vsync(vsync);
}
}
HWND application_class::get_hwnd() const
{
return hwnd_;
}
void application_class::set_hwnd(HWND hwnd)
{
hwnd_ = hwnd;
}
bool application_class::is_windowed() const
{
return windowed_;
}
void application_class::set_windowed(bool windowed)
{
// log the new windowed mode
Logger::Get().Log("Setting windowed mode to " + std::to_string(windowed), __FILE__, __LINE__);
windowed_ = windowed;
}
void application_class::set_screen_height(int height) void application_class::set_screen_height(int height)
{ {
// log the new screen height // log the new screen height
@ -1791,31 +1706,33 @@ void application_class::culling_thread_function()
} }
// Traitement des files d'objets normaux (sans la skybox) // Traitement des files d'objets normaux (sans la skybox)
auto all_entity = entity_manager_->GetAllEntities(); std::vector<std::reference_wrapper<std::vector<object*>>> queues = {
std::ref(object_), std::ref(cubes_), std::ref(terrain_chunk_)
};
for (auto& entity : all_entity) for (auto& queueRef : queues)
{ {
std::vector<object*>& queue = queueRef.get();
std::lock_guard<std::mutex> lock(objects_mutex_); std::lock_guard<std::mutex> lock(objects_mutex_);
auto renderComponent = entity->GetComponent<ecs::RenderComponent>();
if (renderComponent && renderComponent->GetModel()) for (auto* object : queue)
{ {
// Extraction des données de position via le composant TransformComponent if (!object) continue;
auto transformComponent = entity->GetComponent<ecs::TransformComponent>();
if (transformComponent) // Extraction des données de position
{ XMVECTOR position = object->GetPosition();
XMVECTOR transformPosition = transformComponent->GetPosition(); float x = XMVectorGetX(position);
float x = XMVectorGetX(transformPosition); float y = XMVectorGetY(position);
float y = XMVectorGetY(transformPosition); float z = XMVectorGetZ(position);
float z = XMVectorGetZ(transformPosition);
// Calcul du rayon approximatif // Calcul du rayon approximatif
XMVECTOR scale = transformComponent->GetScale(); XMVECTOR scale = object->GetScale();
float radius = max(max(XMVectorGetX(scale), XMVectorGetY(scale)), XMVectorGetZ(scale)); float radius = max(max(XMVectorGetX(scale), XMVectorGetY(scale)), XMVectorGetZ(scale));
// verification du frustum // Vérification du frustum
bool visible = frustum_culling_.CheckCube(x, y, z, radius, get_frustum_tolerance()); bool visible = frustum_culling_.CheckCube(x, y, z, radius, get_frustum_tolerance());
renderComponent->SetVisible(visible); object->SetVisible(visible);
}
} }
} }
@ -1829,51 +1746,212 @@ void application_class::culling_thread_function()
bool application_class::render_pass(XMFLOAT4* diffuse, XMFLOAT4* position, XMFLOAT4* ambient, XMMATRIX view, XMMATRIX projection) 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)
{ {
std::lock_guard<std::mutex> lock(objects_mutex_); std::lock_guard<std::mutex> lock(objects_mutex_);
XMMATRIX scaleMatrix, rotateMatrix, translateMatrix; XMMATRIX scaleMatrix, rotateMatrix, translateMatrix ;
bool result; bool result;
int renderCount = 0; int renderCount = 0;
int i;
// render skybox if (RenderQueues.empty())
for (auto& skyboxObject : skybox_)
{ {
if (skyboxObject == nullptr) Logger::Get().Log("RenderQueues is empty", __FILE__, __LINE__, Logger::LogLevel::Error);
{
Logger::Get().Log("skyboxObject is null", __FILE__, __LINE__, Logger::LogLevel::Error);
return false; return false;
} }
if (!skyboxObject->IsVisible()) // if (active_camera_ == sun_camera_)
// {
// shadow_map_->set_render_target(direct_3d_->get_device_context());
// shadow_map_->clear_render_target(direct_3d_->get_device_context());
// }
for (const auto& RenderQueue : RenderQueues)
{
// Désactiver le Z-buffer si la RenderQueue est skybox_
bool isSkybox = (&RenderQueue.get() == &skybox_);
if (isSkybox)
{
direct_3d_->turn_z_buffer_off();
}
for (auto& object : RenderQueue.get())
{
if (object == nullptr)
{
Logger::Get().Log("object is null", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
// Check if the object has physics enabled
if (object->IsPhysicsEnabled())
{
object->UpdatePosition(timer_->GetTime());
}
if (!object->IsVisible())
{ {
continue; continue;
} }
direct_3d_->turn_z_buffer_off(); renderCount++;
scaleMatrix = skyboxObject->GetScaleMatrix(); scaleMatrix = object->GetScaleMatrix();
rotateMatrix = skyboxObject->GetRotateMatrix(); rotateMatrix = object->GetRotateMatrix();
translateMatrix = skyboxObject->GetTranslateMatrix(); translateMatrix = object->GetTranslateMatrix();
XMMATRIX worldMatrix = XMMatrixMultiply( XMMATRIX worldMatrix = XMMatrixMultiply(
XMMatrixMultiply(scaleMatrix, rotateMatrix), XMMatrixMultiply(scaleMatrix, rotateMatrix),
translateMatrix translateMatrix
); );
renderCount++; object->get_model()->Render(direct_3d_->get_device_context());
skyboxObject->get_model()->Render(direct_3d_->get_device_context()); if (active_camera_ == sun_camera_)
{
result = shader_manager_->render_skybox_shader( result = shader_manager_->render_depth_shader(
direct_3d_->get_device_context(), direct_3d_->get_device_context(),
skyboxObject->get_model()->GetIndexCount(), object->get_model()->GetIndexCount(),
worldMatrix, worldMatrix,
view, view,
projection, projection,
skyboxObject->get_model()->GetTexture(TextureType::Diffuse,0), object->get_model()->GetTexture(TextureType::Diffuse,0)
);
}
// Utiliser l'enum ShaderType pour déterminer quel shader utiliser
switch (object->GetActiveShader())
{
case ShaderType::ALPHA_MAPPING:
// Enable alpha blending for transparency.
direct_3d_->enable_alpha_blending();
result = shader_manager_->render_alpha_map_shader(
direct_3d_->get_device_context(),
object->get_model()->GetIndexCount(),
worldMatrix,
view,
projection,
object->get_model()->GetTexture(TextureType::Diffuse,0),
object->get_model()->GetTexture(TextureType::Diffuse,1),
object->get_model()->GetTexture(TextureType::Alpha,0)
);
if (!result)
{
Logger::Get().Log("Could not render the model using the alpha map shader", __FILE__, __LINE__, Logger::LogLevel::Error);
direct_3d_->disable_alpha_blending();
return false;
}
direct_3d_->disable_alpha_blending();
break;
case ShaderType::CEL_SHADING:
result = shader_manager_->render_cel_shading_shader(
direct_3d_->get_device_context(),
object->get_model()->GetIndexCount(),
worldMatrix,
view,
projection,
object->get_model()->GetTexture(TextureType::Diffuse,0),
sun_light_->GetDiffuseColor(),
sun_light_->GetAmbientColor(),
sun_light_->GetDirection(),
sun_light_->GetIntensity()
);
if (!result)
{
Logger::Get().Log("Could not render the model using the cel shader", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
break;
case ShaderType::NORMAL_MAPPING:
result = shader_manager_->render_normal_map_shader(
direct_3d_->get_device_context(),
object->get_model()->GetIndexCount(),
worldMatrix,
view,
projection,
object->get_model()->GetTexture(TextureType::Diffuse,0),
object->get_model()->GetTexture(TextureType::Normal,0),
lights_[0]->GetDirection(),
lights_[0]->GetDiffuseColor()
);
if (!result)
{
Logger::Get().Log("Could not render the model using the normal map shader", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
break;
case ShaderType::SPECULAR_MAPPING:
result = shader_manager_->render_spec_map_shader(
direct_3d_->get_device_context(),
object->get_model()->GetIndexCount(),
worldMatrix,
view,
projection,
object->get_model()->GetTexture(TextureType::Diffuse,0),
object->get_model()->GetTexture(TextureType::Normal,0),
object->get_model()->GetTexture(TextureType::Specular,0),
lights_[0]->GetDirection(),
lights_[0]->GetDiffuseColor(),
camera_->get_position(),
lights_[0]->GetSpecularColor(),
lights_[0]->GetSpecularPower()
);
if (!result)
{
Logger::Get().Log("Could not render the model using the specular map shader", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
break;
case ShaderType::TEXTURE:
result = shader_manager_->render_texture_shader(
direct_3d_->get_device_context(),
object->get_model()->GetIndexCount(),
worldMatrix,
view,
projection,
object->get_model()->GetTexture(TextureType::Diffuse,0)
);
if (!result)
{
Logger::Get().Log("Could not render the model using the texture shader", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
break;
case ShaderType::LIGHTING:
result = shader_manager_->renderlight_shader(
direct_3d_->get_device_context(),
object->get_model()->GetIndexCount(),
worldMatrix,
view,
projection,
object->get_model()->GetTexture(TextureType::Diffuse,0),
diffuse,
position,
ambient
);
if (!result)
{
Logger::Get().Log("Could not render the object model using the light shader", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
break;
case ShaderType::SKYBOX:
result = shader_manager_->render_skybox_shader(
direct_3d_->get_device_context(),
object->get_model()->GetIndexCount(),
worldMatrix,
view,
projection,
object->get_model()->GetTexture(TextureType::Diffuse,0),
sun_light_->GetDiffuseColor(), sun_light_->GetDiffuseColor(),
sun_light_->GetAmbientColor(), sun_light_->GetAmbientColor(),
sun_light_->GetDirection(), sun_light_->GetDirection(),
@ -1884,47 +1962,56 @@ bool application_class::render_pass(XMFLOAT4* diffuse, XMFLOAT4* position, XMFLO
Logger::Get().Log("Could not render the object model using the skybox shader", __FILE__, __LINE__, Logger::LogLevel::Error); Logger::Get().Log("Could not render the object model using the skybox shader", __FILE__, __LINE__, Logger::LogLevel::Error);
return false; return false;
} }
direct_3d_->turn_z_buffer_on(); // Réactiver le Z-buffer après le rendu de la skybox
break; break;
} case ShaderType::SUNLIGHT:
result = shader_manager_->render_sunlight_shader(
// Rendu des entités du système ECS s'il est disponible direct_3d_->get_device_context(),
if (entity_manager_) { object->get_model()->GetIndexCount(),
// Créer le système de rendu pour les entités worldMatrix,
ecs::RenderSystem renderSystem(direct_3d_->get_device_context(), shader_manager_);
// Données pour le système de rendu
XMFLOAT4 sunlightDiffuse = sun_light_->GetDiffuseColor();
XMFLOAT4 sunlightAmbient = sun_light_->GetAmbientColor();
XMFLOAT3 sunlightDirection = sun_light_->GetDirection();
float sunlightIntensity = sun_light_->GetIntensity();
// Effectuer le rendu de toutes les entités
int entitiesRendered = renderSystem.RenderAllEntities(
entity_manager_.get(),
view, view,
projection, projection,
object->get_model()->GetTexture(TextureType::Diffuse,0),
sun_light_->GetDiffuseColor(),
sun_light_->GetAmbientColor(),
sun_light_->GetDirection(),
sun_light_->GetIntensity()
//shadow_map_srv_
);
if (!result)
{
Logger::Get().Log("Could not render the object model using the sunlight shader", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
break;
default:
result = shader_manager_->renderlight_shader(
direct_3d_->get_device_context(),
object->get_model()->GetIndexCount(),
worldMatrix,
view,
projection,
object->get_model()->GetTexture(TextureType::Diffuse,0),
diffuse, diffuse,
position, position,
ambient, ambient
camera_->get_position(),
sunlightDiffuse,
sunlightAmbient,
sunlightDirection,
sunlightIntensity
); );
if (!result)
renderCount += entitiesRendered; {
Logger::Get().Log("Could not render the object model using the light shader", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
break;
} }
// Rendu des objets traditionnels comme avant stats_->increment_draw_call_count();
// if (active_camera_ == sun_camera_) }
// {
// shadow_map_->set_render_target(direct_3d_->get_device_context()); if (isSkybox)
// shadow_map_->clear_render_target(direct_3d_->get_device_context()); {
// } direct_3d_->turn_z_buffer_on();
}
}
// if (active_camera_ == sun_camera_) // if (active_camera_ == sun_camera_)
// { // {
@ -1960,16 +2047,83 @@ void application_class::update_skybox_position()
} }
bool application_class::render_physics(float delta_time) { bool application_class::render_physics(bool key_left, bool key_right, bool key_up, bool key_down, float delta_time) {
const float maxSpeed = 50.0f; // Limite de vitesse maximale
// update the physical entity if they have the physics component for (auto& object : object_) {
auto entities_with_physics = entity_manager_->GetEntitiesWithComponent<ecs::PhysicsComponent>(); if (object == nullptr) {
for (auto& entity : entities_with_physics) { Logger::Get().Log("object is null", __FILE__, __LINE__, Logger::LogLevel::Error);
auto physicsComponent = entity->GetComponent<ecs::PhysicsComponent>(); return false;
if (physicsComponent) {
// Update the physics component with the input keys and delta time
physicsComponent->Update(delta_time);
} }
if (!object->IsPhysicsEnabled()) {
continue;
}
// Reset acceleration for the new frame
object->SetAcceleration(XMVectorZero());
object->SetGrounded(false);
for (auto& chunk : terrain_chunk_) {
if (!physics_->IsColliding(object, chunk)) {
continue;
}
object->SetVelocity(XMVectorSetY(object->GetVelocity(), 0.0f));
object->SetAcceleration(XMVectorSetY(object->GetAcceleration(), 0.0f));
object->SetGrounded(true);
}
for (auto& object2 : object_) {
if (object->GetId() == object2->GetId()) {
continue;
}
if (!physics_->IsColliding(object, object2)) {
continue;
}
object->SetVelocity(XMVectorZero());
object->SetAcceleration(XMVectorZero());
}
float forceX = 0, forceY = 0, forceZ = 0, forceW = 0;
if (key_left) {
forceX = -40.0f;
}
if (key_right) {
forceX = 40.0f;
}
if (key_up) {
forceY = 40.0f;
}
if (key_down && !object->IsGrounded()) {
forceY = -40.0f;
}
XMVECTOR force = XMVectorSet(forceX, forceY, forceZ, forceW);
physics_->AddForce(object, force);
object->AddVelocity(delta_time);
XMVECTOR velocity = object->GetVelocity();
float speed = XMVectorGetX(XMVector3Length(velocity));
if (speed > maxSpeed) {
velocity = XMVectorScale(velocity, maxSpeed / speed);
object->SetVelocity(velocity);
}
if (object->m_gravityEnabled) {
physics_->ApplyGravity(object, delta_time);
}
if (XMVectorGetY(object->GetPosition()) < -30.0f) {
XMVECTOR currentPosition = object->GetPosition();
object->SetPosition(XMVectorSetY(currentPosition, 50.0f));
}
object->m_previousPosition = object->GetPosition();
} }
return true; return true;
@ -1988,7 +2142,7 @@ void application_class::physics_thread_function()
lastTime = now; lastTime = now;
float deltaTime = 1.0f / static_cast<float>(physics_tick_rate_); float deltaTime = 1.0f / static_cast<float>(physics_tick_rate_);
bool result = render_physics(deltaTime); bool result = render_physics(inputs_.key_left, inputs_.key_right, inputs_.key_up, inputs_.key_down, deltaTime);
if (!result) if (!result)
{ {
Logger::Get().Log("Could not render the physics scene", __FILE__, __LINE__, Logger::LogLevel::Error); Logger::Get().Log("Could not render the physics scene", __FILE__, __LINE__, Logger::LogLevel::Error);
@ -2030,60 +2184,26 @@ bool application_class::create_big_cube(int side_count)
sharedModel = newModel; sharedModel = newModel;
} }
for (int x = 0; x < side_count; x++) { // Créer temporairement les cubes dans un vecteur local
for (int y = 0; y < side_count; y++) { std::vector<object*> tempCubes;
for (int z = 0; z < side_count; z++) { tempCubes.reserve(side_count * side_count * side_count);
// Créer une entité
auto entity = entity_manager_->CreateEntity();
// Ajouter un composant d'identité // Générer side_count³ cubes
auto identity = entity->AddComponent<ecs::IdentityComponent>(object_id_++); for (int x = 0; x < side_count; x++)
identity->SetName("CubePart_" + std::to_string(x) + "_" + std::to_string(y) + "_" + std::to_string(z)); {
identity->SetType(ecs::ObjectType::Terrain); for (int y = 0; y < side_count; y++)
{
// Ajouter un composant de transformation for (int z = 0; z < side_count; z++)
auto transform = entity->AddComponent<ecs::TransformComponent>(); {
transform->SetPosition(XMVectorSet(static_cast<float>(x), static_cast<float>(y), static_cast<float>(z), 0.0f)); object* cubePart = new object(*this);
transform->SetScale(XMVectorSet(1.0f, 1.0f, 1.0f, 0.0f)); cubePart->SetModel(sharedModel);
transform->UpdateWorldMatrix(); cubePart->SetTranslateMatrix(XMMatrixTranslation(static_cast<float>(x),static_cast<float>(y),static_cast<float>(z)));
tempCubes.push_back(cubePart);
// 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::LIGHTING);
} }
} }
} }
// Transférer les cubes du vecteur temporaire au vecteur membre
update_stats_after_modification(); cubes_ = std::move(tempCubes);
return true; return true;
} }
void application_class::update_stats_after_modification()
{
if (stats_)
{
stats_ -> update_geometric_stats();
}
}
int application_class::get_terrain_entity_count()
{
std::lock_guard<std::mutex> lock(objects_mutex_);
int terrainCount = 0;
// 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) {
terrainCount++;
}
}
return terrainCount;
}

View File

@ -18,14 +18,6 @@ imguiManager::imguiManager()
visible_triangle_count_ = 0; visible_triangle_count_ = 0;
current_frame_time_ = 0; current_frame_time_ = 0;
showObjectWindow = false;
showTerrainWindow = false;
showLightWindow = false;
showOldSceneWindow = false;
showEngineSettingsWindow = false;
showLogWindow = false;
showStatsWindow = false;
// Initialiser l'historique des frametimes à zéro // Initialiser l'historique des frametimes à zéro
for (int i = 0; i < FRAME_HISTORY_COUNT; i++) for (int i = 0; i < FRAME_HISTORY_COUNT; i++)
{ {
@ -180,9 +172,6 @@ bool imguiManager::Initialize(HWND hwnd, ID3D11Device* device, ID3D11DeviceConte
stats_ = app_->get_stats(); stats_ = app_->get_stats();
total_triangle_count_ = stats_->get_triangle_count_ptr();
total_vertex_count_ = stats_->get_vertex_count_ptr();
Logger::Get().Log("imgui initialized", __FILE__, __LINE__, Logger::LogLevel::Initialize); Logger::Get().Log("imgui initialized", __FILE__, __LINE__, Logger::LogLevel::Initialize);
return true; return true;
@ -386,65 +375,47 @@ void imguiManager::WidgetAddObject()
} }
ImGui::SameLine(); ImGui::SameLine();
ImGui::Text("Number of cubes: %d", app_->get_entity_manager()->GetEntityCount()); ImGui::Text("Number of cubes: %d", app_->get_cube_count());
} }
} }
void imguiManager::WidgetObjectWindow() void imguiManager::WidgetObjectWindow()
{ {
ImGui::Begin("Objects", &showObjectWindow); ImGui::Begin("Objects", &showObjectWindow);
// Obtenir toutes les entités avec un composant d'identité et de transformation
auto entities = app_->get_entity_manager()->GetEntitiesWithComponent<ecs::IdentityComponent>();
int index = 0; int index = 0;
for (auto& entity : entities) for (auto& object : app_->get_kobjects())
{ {
auto identity = entity->GetComponent<ecs::IdentityComponent>(); std::string headerName = object->GetName() + " " + std::to_string(index);
auto transform = entity->GetComponent<ecs::TransformComponent>();
auto render = entity->GetComponent<ecs::RenderComponent>();
auto shader = entity->GetComponent<ecs::ShaderComponent>();
auto physics = entity->GetComponent<ecs::PhysicsComponent>();
if (identity && transform)
{
std::string headerName = identity->GetName() + " " + std::to_string(identity->GetId());
if (ImGui::CollapsingHeader(headerName.c_str())) if (ImGui::CollapsingHeader(headerName.c_str()))
{ {
// Position, Rotation, Scale
XMVECTOR position = transform->GetPosition(); XMVECTOR position = object->GetPosition();
XMVECTOR rotation = transform->GetRotation(); XMVECTOR rotation = object->GetRotation();
XMVECTOR scale = transform->GetScale(); XMVECTOR scale = object->GetScale();
float pos[3] = { XMVectorGetX(position), XMVectorGetY(position), XMVectorGetZ(position) }; float pos[3] = { XMVectorGetX(position), XMVectorGetY(position), XMVectorGetZ(position) };
std::string posLabel = "Position##" + std::to_string(identity->GetId()); std::string posLabel = "Position##" + std::to_string(index);
if (ImGui::DragFloat3(posLabel.c_str(), pos)) if (ImGui::DragFloat3(posLabel.c_str(), pos))
{ {
transform->SetPosition(XMVectorSet(pos[0], pos[1], pos[2], 0.0f)); object->SetPosition(XMVectorSet(pos[0], pos[1], pos[2], 0.0f));
transform->UpdateWorldMatrix();
} }
float rot[3] = { XMVectorGetX(rotation), XMVectorGetY(rotation), XMVectorGetZ(rotation) }; float rot[3] = { XMVectorGetX(rotation), XMVectorGetY(rotation), XMVectorGetZ(rotation) };
std::string rotLabel = "Rotation##" + std::to_string(identity->GetId()); std::string rotLabel = "Rotation##" + std::to_string(index);
if (ImGui::DragFloat3(rotLabel.c_str(), rot)) if (ImGui::DragFloat3(rotLabel.c_str(), rot))
{ {
transform->SetRotation(XMVectorSet(rot[0], rot[1], rot[2], 0.0f)); object->SetRotation(XMVectorSet(rot[0], rot[1], rot[2], 0.0f));
transform->UpdateWorldMatrix();
} }
float scl[3] = { XMVectorGetX(scale), XMVectorGetY(scale), XMVectorGetZ(scale) }; float scl[3] = { XMVectorGetX(scale), XMVectorGetY(scale), XMVectorGetZ(scale) };
std::string sclLabel = "Scale##" + std::to_string(identity->GetId()); std::string sclLabel = "Scale##" + std::to_string(index);
if (ImGui::DragFloat3(sclLabel.c_str(), scl)) if (ImGui::DragFloat3(sclLabel.c_str(), scl))
{ {
transform->SetScale(XMVectorSet(scl[0], scl[1], scl[2], 0.0f)); object->SetScale(XMVectorSet(scl[0], scl[1], scl[2], 0.0f));
transform->UpdateWorldMatrix();
} }
ImGui::Separator(); ImGui::Separator();
// Textures - Seulement si le composant de rendu existe
if (render && render->GetModel())
{
// Définir les types de textures_ // Définir les types de textures_
std::vector<std::string> textureCategories = { std::vector<std::string> textureCategories = {
"Diffuse", "Normal", "Specular", "Alpha" "Diffuse", "Normal", "Specular", "Alpha"
@ -456,8 +427,7 @@ void imguiManager::WidgetObjectWindow()
}; };
// Créer un espace pour afficher les textures_ avec défilement // Créer un espace pour afficher les textures_ avec défilement
std::string textureChildId = "TextureChild##" + std::to_string(identity->GetId()); ImGui::BeginChild("TextureChild", ImVec2(0, 200), true, ImGuiWindowFlags_HorizontalScrollbar);
ImGui::BeginChild(textureChildId.c_str(), ImVec2(0, 200), true, ImGuiWindowFlags_HorizontalScrollbar);
// Pour chaque type de texture // Pour chaque type de texture
for (int typeIndex = 0; typeIndex < textureCategories.size(); typeIndex++) for (int typeIndex = 0; typeIndex < textureCategories.size(); typeIndex++)
@ -466,27 +436,25 @@ void imguiManager::WidgetObjectWindow()
std::string typeName = textureCategories[typeIndex]; std::string typeName = textureCategories[typeIndex];
// Afficher le titre de la catégorie // Afficher le titre de la catégorie
std::string categoryLabel = typeName + "##" + std::to_string(identity->GetId());
ImGui::Text("%s:", typeName.c_str()); ImGui::Text("%s:", typeName.c_str());
ImGui::SameLine(); ImGui::SameLine();
// Compter combien de textures_ de ce type existent // Compter combien de textures_ de ce type existent
int textureCount = 0; int textureCount = 0;
while (render->GetModel()->GetTexture(type, textureCount) != nullptr) while (object->get_model()->GetTexture(type, textureCount) != nullptr)
{ {
textureCount++; textureCount++;
} }
// Afficher toutes les textures_ existantes // Afficher toutes les textures_ existantes
std::string groupId = "TextureGroup_" + std::to_string(identity->GetId()) + "_" + std::to_string(typeIndex);
ImGui::BeginGroup(); ImGui::BeginGroup();
for (int texIndex = 0; texIndex < textureCount; texIndex++) for (int texIndex = 0; texIndex < textureCount; texIndex++)
{ {
ID3D11ShaderResourceView* texture = render->GetModel()->GetTexture(type, texIndex); ID3D11ShaderResourceView* texture = object->get_model()->GetTexture(type, texIndex);
if (texture) if (texture)
{ {
// ID unique pour chaque bouton de texture // ID unique pour chaque bouton de texture
std::string buttonId = "tex##" + std::to_string(identity->GetId()) + "_" + std::string buttonId = "tex##" + std::to_string(index) + "_" +
std::to_string(typeIndex) + "_" + std::to_string(typeIndex) + "_" +
std::to_string(texIndex); std::to_string(texIndex);
@ -494,11 +462,12 @@ void imguiManager::WidgetObjectWindow()
{ {
// Ouvrir une boîte de dialogue pour changer la texture // Ouvrir une boîte de dialogue pour changer la texture
OPENFILENAME ofn; OPENFILENAME ofn;
WCHAR szFile[260] = {0}; WCHAR szFile[260];
ZeroMemory(&ofn, sizeof(ofn)); ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn); ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL; ofn.hwndOwner = NULL;
ofn.lpstrFile = szFile; ofn.lpstrFile = szFile;
szFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile); ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = L"Texture\0*.png;*.jpg;*.dds\0"; ofn.lpstrFilter = L"Texture\0*.png;*.jpg;*.dds\0";
ofn.nFilterIndex = 1; ofn.nFilterIndex = 1;
@ -508,7 +477,7 @@ void imguiManager::WidgetObjectWindow()
if (GetOpenFileName(&ofn)) if (GetOpenFileName(&ofn))
{ {
// Changer la texture existante // Changer la texture existante
render->GetModel()->ChangeTexture(m_device, m_deviceContext, ofn.lpstrFile, type, texIndex); object->get_model()->ChangeTexture(m_device, m_deviceContext, ofn.lpstrFile, type, texIndex);
} }
} }
@ -526,16 +495,17 @@ void imguiManager::WidgetObjectWindow()
} }
// Bouton pour ajouter une nouvelle texture // Bouton pour ajouter une nouvelle texture
std::string addButtonLabel = "+##" + std::to_string(identity->GetId()) + "_" + std::to_string(typeIndex); std::string addButtonLabel = "+##" + std::to_string(index) + "_" + std::to_string(typeIndex);
if (ImGui::Button(addButtonLabel.c_str(), ImVec2(48, 48))) if (ImGui::Button(addButtonLabel.c_str(), ImVec2(48, 48)))
{ {
// Ouvrir une boîte de dialogue pour ajouter une texture // Ouvrir une boîte de dialogue pour ajouter une texture
OPENFILENAME ofn; OPENFILENAME ofn;
WCHAR szFile[260] = {0}; WCHAR szFile[260];
ZeroMemory(&ofn, sizeof(ofn)); ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn); ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL; ofn.hwndOwner = NULL;
ofn.lpstrFile = szFile; ofn.lpstrFile = szFile;
szFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile); ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = L"Texture\0*.png;*.jpg;*.dds\0"; ofn.lpstrFilter = L"Texture\0*.png;*.jpg;*.dds\0";
ofn.nFilterIndex = 1; ofn.nFilterIndex = 1;
@ -545,7 +515,7 @@ void imguiManager::WidgetObjectWindow()
if (GetOpenFileName(&ofn)) if (GetOpenFileName(&ofn))
{ {
// Ajouter une nouvelle texture // Ajouter une nouvelle texture
render->GetModel()->AddTexture(m_device, m_deviceContext, ofn.lpstrFile, type); object->get_model()->AddTexture(m_device, m_deviceContext, ofn.lpstrFile, type);
} }
} }
@ -554,25 +524,19 @@ void imguiManager::WidgetObjectWindow()
} }
ImGui::EndChild(); ImGui::EndChild();
}
ImGui::Separator(); ImGui::Separator();
// Delete button // Delete button
std::string deleteLabel = "Delete##" + std::to_string(identity->GetId()); std::string deleteLabel = "Delete##" + std::to_string(index);
if (ImGui::Button(deleteLabel.c_str())) if (ImGui::Button(deleteLabel.c_str()))
{ {
app_->delete_entity_by_id(identity->GetId()); app_->delete_kobject(index);
// Sortir du boucle après suppression pour éviter des accès invalides
break;
} }
ImGui::Separator(); ImGui::Separator();
// Shader options // Liste des options
if (shader)
{
// Liste des options de shader
const char* shaderOptions[] = { const char* shaderOptions[] = {
"Enable Global Lighting", "Enable Global Lighting",
"Enable Lighting", "Enable Lighting",
@ -582,41 +546,30 @@ void imguiManager::WidgetObjectWindow()
"Enable Alpha Mapping" "Enable Alpha Mapping"
}; };
std::vector<ecs::ShaderType> shaderTypes = { ShaderType shaderTypes[] = {
ecs::ShaderType::SUNLIGHT, ShaderType::SUNLIGHT,
ecs::ShaderType::LIGHTING, ShaderType::LIGHTING,
ecs::ShaderType::CEL_SHADING, ShaderType::CEL_SHADING,
ecs::ShaderType::NORMAL_MAPPING, ShaderType::NORMAL_MAPPING,
ecs::ShaderType::SPECULAR_MAPPING, ShaderType::SPECULAR_MAPPING,
ecs::ShaderType::ALPHA_MAPPING ShaderType::ALPHA_MAPPING
}; };
// Trouver l'index actuel du shader pour cette entité spécifique // Variable pour stocker l'option sélectionnée
int currentShader = 0; static int currentShader = 0; // Index de l'option actuellement sélectionnée
ecs::ShaderType activeShader = shader->GetActiveShader();
for (size_t i = 0; i < shaderTypes.size(); i++)
{
if (shaderTypes[i] == activeShader)
{
currentShader = static_cast<int>(i);
break;
}
}
// Création du menu déroulant avec un ID unique pour chaque entité // Création du menu déroulant
std::string shaderComboId = "Shader Options##" + std::to_string(identity->GetId()); if (ImGui::BeginCombo("Shader Options", shaderOptions[currentShader]))
if (ImGui::BeginCombo(shaderComboId.c_str(), shaderOptions[currentShader]))
{ {
for (int i = 0; i < IM_ARRAYSIZE(shaderOptions); i++) for (int i = 0; i < IM_ARRAYSIZE(shaderOptions); i++)
{ {
// Crée une option sélectionnable pour chaque shader avec ID unique // Crée une option sélectionnable pour chaque shader
std::string shaderSelectableId = std::to_string(i) + "##shader_" + std::to_string(identity->GetId());
bool isSelected = (currentShader == i); bool isSelected = (currentShader == i);
if (ImGui::Selectable(shaderOptions[i], isSelected)) if (ImGui::Selectable(shaderOptions[i], isSelected))
{ {
// Met à jour l'option sélectionnée uniquement pour cette entité // Met à jour l'option sélectionnée
currentShader = i; currentShader = i;
shader->SetActiveShader(shaderTypes[i]); object->SetActiveShader(shaderTypes[i]);
} }
// Si l'option sélectionnée est active, nous mettons en surbrillance // Si l'option sélectionnée est active, nous mettons en surbrillance
@ -625,75 +578,88 @@ void imguiManager::WidgetObjectWindow()
} }
ImGui::EndCombo(); ImGui::EndCombo();
} }
}
ImGui::Separator(); ImGui::Separator();
// Physics // physics
bool isPhysicsEnabled = (physics != nullptr); std::string physicsLabel = "physics##" + std::to_string(index);
std::string physicsLabel = "Physics##" + std::to_string(identity->GetId());
if (ImGui::Checkbox(physicsLabel.c_str(), &isPhysicsEnabled)) if (ImGui::Checkbox(physicsLabel.c_str(), &m_isPhyiscsEnabled))
{ {
if (isPhysicsEnabled && !physics) object->SetPhysicsEnabled(m_isPhyiscsEnabled);
{
// Ajouter un composant de physique
physics = entity->AddComponent<ecs::PhysicsComponent>();
physics->Initialize();
}
else if (!isPhysicsEnabled && physics)
{
// Retirer le composant de physique
entity->RemoveComponent<ecs::PhysicsComponent>();
physics = nullptr;
}
} }
if (physics)
{
// Gravity Enabled checkbox // Gravity Enabled checkbox
bool gravityEnabled = physics->IsGravityEnabled(); std::string gravityLabel = "Gravity##" + std::to_string(index);
std::string gravityLabel = "Gravity##" + std::to_string(identity->GetId()); if (ImGui::Checkbox(gravityLabel.c_str(), &object->m_gravityEnabled))
if (ImGui::Checkbox(gravityLabel.c_str(), &gravityEnabled))
{ {
physics->SetGravityEnabled(gravityEnabled); object->SetGravityEnabled(object->m_gravityEnabled);
} }
// 3 radio buttons pour le type d'objet physique avec IDs uniques
std::string typeLabel = "Type##" + std::to_string(identity->GetId());
ecs::ObjectType type = identity->GetType();
if (ImGui::RadioButton(("None##" + std::to_string(identity->GetId())).c_str(), // 3 radio button on the same line to set the ObjectType
type == ecs::ObjectType::Unknown)) std::string typeLabel = "Type##" + std::to_string(index);
ObjectType type = object->GetType();
if (ImGui::RadioButton("None", type == ObjectType::Unknown))
{ {
identity->SetType(ecs::ObjectType::Unknown); object->SetType(ObjectType::Unknown);
} }
ImGui::SameLine(); ImGui::SameLine();
if (ImGui::RadioButton(("Cube##" + std::to_string(identity->GetId())).c_str(), if (ImGui::RadioButton("Cube", type == ObjectType::Cube))
type == ecs::ObjectType::Cube))
{ {
identity->SetType(ecs::ObjectType::Cube); object->SetType(ObjectType::Cube);
} }
ImGui::SameLine(); ImGui::SameLine();
if (ImGui::RadioButton(("Sphere##" + std::to_string(identity->GetId())).c_str(), if (ImGui::RadioButton("Sphere", type == ObjectType::Sphere))
type == ecs::ObjectType::Sphere))
{ {
identity->SetType(ecs::ObjectType::Sphere); object->SetType(ObjectType::Sphere);
}
ImGui::SameLine();
if (ImGui::RadioButton(("Terrain##" + std::to_string(identity->GetId())).c_str(),
type == ecs::ObjectType::Terrain))
{
identity->SetType(ecs::ObjectType::Terrain);
} }
// button to launch the object
std::string launchLabel = "Launch##" + std::to_string(index);
// paraeter to set the alpha, initial stretch and spring constant
float alpha = object->GetAlpha();
float initialStretch = object->GetInitialStretch();
float springConstant = object->GetSpringConstant();
if (ImGui::DragFloat("Alpha##" , &alpha, 0.01f, 0.0f, 1.0f))
{
object->SetAlpha(alpha);
} }
if (ImGui::DragFloat("Initial Stretch##", &initialStretch, 0.01f, 0.0f, 1.0f))
{
object->SetInitialStretch(initialStretch);
}
if (ImGui::DragFloat("Spring Constant##", &springConstant, 0.01f, 0.0f, 100.0f))
{
object->SetSpringConstant(springConstant);
}
if (ImGui::Button(launchLabel.c_str()))
{
object->LaunchObject();
}
ImGui::SameLine();
// button to stop the object
std::string stopLabel = "Stop##" + std::to_string(index);
if (ImGui::Button(stopLabel.c_str()))
{
object->SetVelocity(XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f));
object->SetPosition(XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f));
}
ImGui::Separator(); ImGui::Separator();
// Demo spinning
std::string demoLabel = "Demo spinning##" + std::to_string(index);
ImGui::Checkbox(demoLabel.c_str(), &object->m_demoSpinning);
} }
index++; index++;
} }
}
ImGui::End(); ImGui::End();
} }
@ -702,7 +668,7 @@ void imguiManager::WidgetTerrainWindow()
{ {
ImGui::Begin("Terrain", &showTerrainWindow); ImGui::Begin("Terrain", &showTerrainWindow);
ImGui::Text("Number of terrain cubes: %d", app_->get_terrain_entity_count()); ImGui::Text("Number of terrain cubes: %d", app_->get_terrain_cube_count());
ImGui::Separator(); ImGui::Separator();
@ -1023,11 +989,8 @@ void imguiManager::WidgetRenderStats()
min_fps_ = stats_->get_min_fps(); min_fps_ = stats_->get_min_fps();
max_fps_ = stats_->get_max_fps(); max_fps_ = stats_->get_max_fps();
draw_calls_ = stats_->get_draw_calls(); draw_calls_ = stats_->get_draw_calls();
total_vertex_count_ = stats_->get_total_vertex_count();
total_triangle_count_ = stats_->get_total_triangle_count();
// total_vertex_count_ = stats_->get_total_vertex_count();
// total_triangle_count_ = stats_->get_total_triangle_count();
visible_triangle_count_ = stats_->get_visible_triangle_count(); visible_triangle_count_ = stats_->get_visible_triangle_count();
current_frame_time_ = stats_->get_frame_time(); current_frame_time_ = stats_->get_frame_time();
@ -1076,9 +1039,9 @@ void imguiManager::WidgetRenderStats()
ImGui::Separator(); ImGui::Separator();
ImGui::Text("Statistiques de rendu:"); ImGui::Text("Statistiques de rendu:");
ImGui::Text("Vertices total: %d", *total_vertex_count_); ImGui::Text("Vertices total: %d", total_vertex_count_);
ImGui::Text("Triangles total: %d", *total_triangle_count_); ImGui::Text("Triangles total: %d", total_triangle_count_);
ImGui::SameLine(); ImGui::SameLine();
ImGui::Text("Triangles visibles: %d", visible_triangle_count_); ImGui::Text("Triangles visibles: %d", visible_triangle_count_);
@ -1130,4 +1093,3 @@ void imguiManager::WidgetRenderStats()
ImGui::End(); ImGui::End();
} }

View File

@ -52,7 +52,7 @@ bool scene_manager::save_scene_as() {
// Mettre à jour le chemin de scène // Mettre à jour le chemin de scène
scene_path_ = convert_w_string_to_string(filepath.wstring()); scene_path_ = convert_w_string_to_string(filepath.wstring());
//object_vec_ = app_->get_kobjects(); // TODO object_vec_ = app_->get_kobjects();
// Sauvegarder la scène avec le nouveau chemin // Sauvegarder la scène avec le nouveau chemin
save_scene(); save_scene();
@ -67,30 +67,27 @@ bool scene_manager::save_scene_as() {
bool scene_manager::load_scene() { bool scene_manager::load_scene() {
Logger::Get().Log("Loading scene from " , __FILE__, __LINE__, Logger::LogLevel::Info); Logger::Get().Log("Loading scene from " , __FILE__, __LINE__, Logger::LogLevel::Info);
object_vec_ = app_->get_kobjects();
object_id_ = app_->get_object_id(); object_id_ = app_->get_object_id();
w_folder_ = app_->get_w_folder(); w_folder_ = app_->get_w_folder();
direct_3d_ = app_->get_direct_3d(); direct_3d_ = app_->get_direct_3d();
std::wstring scenePath = get_scene_path(); std::wstring scenePath = get_scene_path();
if (!scenePath.empty()) {
if (!scenePath.empty())
{
scene_path_ = convert_w_string_to_string(scenePath); scene_path_ = convert_w_string_to_string(scenePath);
} }
std::ifstream inFile(scene_path_); std::ifstream inFile(scene_path_);
if (!inFile.is_open()) { if (!inFile.is_open()) {
Logger::Get().Log("Failed to open file for loading scene: " + scene_path_, __FILE__, __LINE__, Logger::LogLevel::Error); Logger::Get().Log("Failed to open file for loading scene: ", __FILE__, __LINE__, Logger::LogLevel::Error);
return false; return false;
} }
// Réinitialiser l'ID d'objet le plus élevé object_vec_.clear();
object_id_ = 0; object_id_ = 0;
// Récupérer l'EntityManager pour créer de nouvelles entités
auto entity_manager = app_->get_entity_manager();
// Supprimer toutes les entités existantes
entity_manager->Clear();
// Sauvegarder le répertoire de travail actuel // Sauvegarder le répertoire de travail actuel
std::wstring currentDirectory = w_folder_; std::wstring currentDirectory = w_folder_;
@ -107,42 +104,28 @@ bool scene_manager::load_scene() {
float mass; float mass;
bool physicsEnabled; bool physicsEnabled;
// Lire les données de base de l'entité // Lire les données de base de l'objet
iss >> id >> name iss >> id >> name
>> position.x >> position.y >> position.z >> position.x >> position.y >> position.z
>> rotation.x >> rotation.y >> rotation.z >> rotation.x >> rotation.y >> rotation.z
>> scale.x >> scale.y >> scale.z; >> scale.x >> scale.y >> scale.z
>> modelPath >> shaderTypeStr
// Lire le chemin du modèle - vérifier s'il est vide
iss >> modelPath;
// Si le chemin du modèle est vide ou commence par une lettre majuscule (probablement un type de shader),
// c'est qu'il a été omis - utilisez une valeur par défaut
if (modelPath.empty() || (modelPath[0] >= 'A' && modelPath[0] <= 'Z')) {
// Reculer le curseur de lecture pour lire le type de shader à la place
iss.seekg(-static_cast<int>(modelPath.length()), std::ios::cur);
modelPath = "assets/Model/TXT/cube.txt"; // Valeur par défaut
}
iss >> shaderTypeStr
>> boundingRadius >> objectTypeStr >> boundingRadius >> objectTypeStr
>> mass >> physicsEnabled; >> mass >> physicsEnabled;
if (iss.fail()) { if (iss.fail()) {
Logger::Get().Log("Failed to parse entity data: " + line, __FILE__, __LINE__, Logger::LogLevel::Error); Logger::Get().Log("Failed to parse object data", __FILE__, __LINE__, Logger::LogLevel::Error);
continue; continue;
} }
// Mettre à jour l'ID d'objet le plus élevé si nécessaire // Créer un nouvel objet
if (id >= object_id_) { object* newObject = new object();
object_id_ = id + 1;
}
// Convertir le chemin du modèle en wstring // Convertir le chemin du modèle en wstring
std::wstring wModelPath(modelPath.begin(), modelPath.end()); std::wstring wModelPath(modelPath.begin(), modelPath.end());
// Vérifier si le chemin est relatif // Vérifier si le chemin est relatif (ne commence pas par un disque comme C:)
if (modelPath != "NoModel" && modelPath.length() > 1 && modelPath[1] != ':') { if (modelPath.length() > 1 && modelPath[1] != ':') {
// C'est un chemin relatif, préfixer avec le répertoire de travail // C'est un chemin relatif, préfixer avec le répertoire de travail
if (currentDirectory.back() != L'/' && currentDirectory.back() != L'\\') { if (currentDirectory.back() != L'/' && currentDirectory.back() != L'\\') {
// Ajouter un séparateur si nécessaire // Ajouter un séparateur si nécessaire
@ -152,16 +135,16 @@ bool scene_manager::load_scene() {
} }
} }
// Créer le conteneur de textures pour stocker les chemins // Créer le conteneur de textures_ pour stocker les chemins
TextureContainer objectTextures; TextureContainer objectTextures;
// Vider les conteneurs de chemins de textures // IMPORTANT: Vider les conteneurs de chemins de textures_
objectTextures.diffusePaths.clear(); objectTextures.diffusePaths.clear();
objectTextures.normalPaths.clear(); objectTextures.normalPaths.clear();
objectTextures.specularPaths.clear(); objectTextures.specularPaths.clear();
objectTextures.alphaPaths.clear(); objectTextures.alphaPaths.clear();
// Lire les chemins des textures diffuses // Lire les chemins des textures_ diffuses
int diffuseTextureCount; int diffuseTextureCount;
iss >> diffuseTextureCount; iss >> diffuseTextureCount;
for (int i = 0; i < diffuseTextureCount; i++) { for (int i = 0; i < diffuseTextureCount; i++) {
@ -171,7 +154,7 @@ bool scene_manager::load_scene() {
objectTextures.diffusePaths.push_back(wTexturePath); objectTextures.diffusePaths.push_back(wTexturePath);
} }
// Lire les chemins des textures normales // Lire les chemins des textures_ normales
int normalTextureCount; int normalTextureCount;
iss >> normalTextureCount; iss >> normalTextureCount;
for (int i = 0; i < normalTextureCount; i++) { for (int i = 0; i < normalTextureCount; i++) {
@ -181,7 +164,7 @@ bool scene_manager::load_scene() {
objectTextures.normalPaths.push_back(wTexturePath); objectTextures.normalPaths.push_back(wTexturePath);
} }
// Lire les chemins des textures spéculaires // Lire les chemins des textures_ spéculaires
int specularTextureCount; int specularTextureCount;
iss >> specularTextureCount; iss >> specularTextureCount;
for (int i = 0; i < specularTextureCount; i++) { for (int i = 0; i < specularTextureCount; i++) {
@ -191,7 +174,7 @@ bool scene_manager::load_scene() {
objectTextures.specularPaths.push_back(wTexturePath); objectTextures.specularPaths.push_back(wTexturePath);
} }
// Lire les chemins des textures alpha // Lire les chemins des textures_ alpha
int alphaTextureCount; int alphaTextureCount;
iss >> alphaTextureCount; iss >> alphaTextureCount;
for (int i = 0; i < alphaTextureCount; i++) { for (int i = 0; i < alphaTextureCount; i++) {
@ -201,100 +184,60 @@ bool scene_manager::load_scene() {
objectTextures.alphaPaths.push_back(wTexturePath); objectTextures.alphaPaths.push_back(wTexturePath);
} }
// Vérifier si on a un modèle à charger // preload texture
if (modelPath == "NoModel") { if (!newObject->get_model()->PreloadTextures(direct_3d_->get_device(), direct_3d_->get_device_context(), objectTextures))
Logger::Get().Log("Skipping entity without model: " + name, __FILE__, __LINE__, Logger::LogLevel::Warning); {
continue; // Gérer l'erreur
return false;
} }
// Récupérer le cache de modèles de l'application // Initialiser l'objet avec le modèle et les chemins de textures_
auto& modelCache = app_->get_model_cache();
std::shared_ptr<model_class> sharedModel;
// Vérifier si le modèle existe déjà dans le cache
std::string modelKey = modelPath;
auto it = modelCache.find(modelKey);
if (it != modelCache.end()) {
// Utiliser le modèle existant du cache
Logger::Get().Log("Using cached model for: " + modelKey, __FILE__, __LINE__, Logger::LogLevel::Info);
sharedModel = it->second;
} else {
// Créer un nouveau modèle
char modelFilename[256]; char modelFilename[256];
size_t convertedChars = 0; size_t convertedChars = 0;
wcstombs_s(&convertedChars, modelFilename, sizeof(modelFilename), wModelPath.c_str(), _TRUNCATE); wcstombs_s(&convertedChars, modelFilename, sizeof(modelFilename), wModelPath.c_str(), _TRUNCATE);
Logger::Get().Log("Loading model: " + std::string(modelFilename), __FILE__, __LINE__, Logger::LogLevel::Info); Logger::Get().Log("Loading model: " + std::string(modelFilename), __FILE__, __LINE__, Logger::LogLevel::Info);
// Créer et initialiser le modèle // NE PAS charger les textures_ avant initialize
auto newModel = std::make_shared<model_class>(); // Laisser la méthode initialize s'en charger à partir des chemins
if (!newObject->Initialize(direct_3d_->get_device(), direct_3d_->get_device_context(), modelFilename, objectTextures)) {
// Précharger les textures Logger::Get().Log("Failed to initialize object: " + name, __FILE__, __LINE__, Logger::LogLevel::Error);
if (!newModel->PreloadTextures(direct_3d_->get_device(), direct_3d_->get_device_context(), objectTextures)) { delete newObject;
Logger::Get().Log("Failed to preload textures for: " + name, __FILE__, __LINE__, Logger::LogLevel::Error);
continue; continue;
} }
if (!newModel->Initialize(direct_3d_->get_device(), direct_3d_->get_device_context(), modelFilename, objectTextures)) { // Définir les propriétés de l'objet
Logger::Get().Log("Failed to initialize model: " + name, __FILE__, __LINE__, Logger::LogLevel::Error); newObject->SetId(id);
continue; newObject->SetName(name);
} newObject->SetPosition(XMLoadFloat3(&position));
newObject->SetRotation(XMLoadFloat3(&rotation));
newObject->SetScale(XMLoadFloat3(&scale));
newObject->SetModelPath(wModelPath);
newObject->SetActiveShader(newObject->StringToShaderType(shaderTypeStr));
newObject->SetBoundingRadius(boundingRadius);
newObject->SetType(newObject->StringToObjectType(objectTypeStr));
newObject->SetMass(mass);
newObject->SetPhysicsEnabled(physicsEnabled);
// Ajouter le modèle au cache // Mettre à jour l'ID global si nécessaire
modelCache[modelKey] = newModel; if (id >= object_id_) {
sharedModel = newModel; object_id_ = id + 1;
}
// Créer une nouvelle entité avec l'EntityManager
auto entity = entity_manager->CreateEntity();
// Ajouter un composant d'identité
auto identityComponent = entity->AddComponent<ecs::IdentityComponent>(id);
identityComponent->SetName(name);
identityComponent->SetType(ecs::IdentityComponent::StringToObjectType(objectTypeStr));
// Ajouter un composant de transformation
auto transformComponent = entity->AddComponent<ecs::TransformComponent>();
transformComponent->SetPosition(XMLoadFloat3(&position));
transformComponent->SetRotation(XMLoadFloat3(&rotation));
transformComponent->SetScale(XMLoadFloat3(&scale));
transformComponent->UpdateWorldMatrix();
// Ajouter un composant de rendu avec le modèle
auto renderComponent = entity->AddComponent<ecs::RenderComponent>();
renderComponent->InitializeWithModel(sharedModel);
// Ajouter un composant de shader
auto shaderComponent = entity->AddComponent<ecs::ShaderComponent>();
shaderComponent->SetActiveShader(ecs::ShaderComponent::StringToShaderType(shaderTypeStr));
// Ajouter un composant de chemin de modèle
auto modelPathComponent = entity->AddComponent<ecs::ModelPathComponent>();
modelPathComponent->SetPath(wModelPath);
// Ajouter un composant de physique si nécessaire
auto physicsComponent = entity->AddComponent<ecs::PhysicsComponent>();
physicsComponent->Initialize();
physicsComponent->SetMass(mass);
physicsComponent->SetBoundingRadius(boundingRadius);
physicsComponent->SetPhysicsEnabled(physicsEnabled);
Logger::Get().Log("Entity loaded: " + name + " with ID: " + std::to_string(id), __FILE__, __LINE__, Logger::LogLevel::Info);
}
// Mettre à jour l'ID global dans l'application
app_->set_object_id(object_id_); app_->set_object_id(object_id_);
}
// Mettre à jour les statistiques après le chargement object_vec_.push_back(newObject);
app_->update_stats_after_modification(); Logger::Get().Log("Loaded object: " + name, __FILE__, __LINE__, Logger::LogLevel::Info);
}
Logger::Get().Log("Scene loaded successfully from " + scene_path_, __FILE__, __LINE__, Logger::LogLevel::Info); // pass the vec to the application
app_->set_kobjects(object_vec_);
Logger::Get().Log("Scene loaded successfully from ", __FILE__, __LINE__, Logger::LogLevel::Info);
return true; return true;
} }
bool scene_manager::save_scene() { bool scene_manager::save_scene() {
entity_ = app_->get_entity_manager()->GetAllEntities();
if (scene_path_.empty()) { if (scene_path_.empty()) {
Logger::Get().Log("Scene path is empty. Cannot save scene.", __FILE__, __LINE__, Logger::LogLevel::Error); Logger::Get().Log("Scene path is empty. Cannot save scene.", __FILE__, __LINE__, Logger::LogLevel::Error);
@ -307,102 +250,56 @@ bool scene_manager::save_scene() {
return false; return false;
} }
for (const auto& object : entity_) { for (const auto& object : object_vec_) {
XMFLOAT3 position, scale, rotation; XMFLOAT3 position, scale, rotation;
int id = 0; XMStoreFloat3(&position, object->GetPosition());
int mass = 0; XMStoreFloat3(&scale, object->GetScale());
float boundingRadius = 0; XMStoreFloat3(&rotation, object->GetRotation());
std::string name = "NONE";
std::string shaderType = "NONE";
std::string objectType = "NONE";
std::wstring model_path = L"";
bool physics_enabled = false;
auto transform = object->GetComponent<ecs::TransformComponent>();
if (transform) {
// convert XMVECTOR to XMFLOAT3
XMStoreFloat3(&position, transform->GetPosition());
XMStoreFloat3(&rotation, transform->GetRotation());
XMStoreFloat3(&scale, transform->GetScale());
}
auto identity = object->GetComponent<ecs::IdentityComponent>();
if (identity) {
id = identity->GetId();
name = identity->GetName();
objectType = identity->ObjectTypeToString(identity->GetType());
}
auto model_path_component = object->GetComponent<ecs::ModelPathComponent>();
if (model_path_component) {
model_path = model_path_component->GetPath();
}
auto shader = object->GetComponent<ecs::ShaderComponent>();
if (shader)
{
shaderType = shader->ShaderTypeToString(shader->GetActiveShader());
}
auto physics = object->GetComponent<ecs::PhysicsComponent>();
if (physics) {
physics_enabled = physics->IsPhysicsEnabled();
mass = physics->GetMass();
boundingRadius = physics->GetBoundingRadius();
}
// Écrire les données de base de l'objet // Écrire les données de base de l'objet
outFile << id << " " outFile << object->GetId() << " "
<< name << " " << object->GetName() << " "
<< position.x << " " << position.y << " " << position.z << " " << position.x << " " << position.y << " " << position.z << " "
<< rotation.x << " " << rotation.y << " " << rotation.z << " " << rotation.x << " " << rotation.y << " " << rotation.z << " "
<< scale.x << " " << scale.y << " " << scale.z << " " << scale.x << " " << scale.y << " " << scale.z << " "
<< convert_w_string_to_string(model_path) << " " << convert_w_string_to_string(object->GetModelPath()) << " "
<< shaderType << " " << object->ShaderTypeToString(object->GetActiveShader()) << " "
<< boundingRadius << " " << object->GetBoundingRadius() << " "
<< objectType << " " << object->ObjectTypeToString(object->GetType()) << " "
<< mass << " " << object->GetMass() << " "
<< physics_enabled; << object->IsPhysicsEnabled();
// Sauvegarder les chemins des textures_ // Sauvegarder les chemins des textures_
// Format: nombre de textures_ diffuses, puis les chemins // Format: nombre de textures_ diffuses, puis les chemins
// Même chose pour les autres types de textures_ // Même chose pour les autres types de textures_
// Textures diffuses
auto render = object->GetComponent<ecs::RenderComponent>(); const auto& diffusePaths = object->get_model()->GetTextureContainer().GetPaths(TextureType::Diffuse);
if (render)
{
const auto& model = render->GetModel();
const auto& textureContainer = model->GetTextureContainer();
const auto& diffusePaths = textureContainer.GetPaths(TextureType::Diffuse);
outFile << " " << diffusePaths.size(); outFile << " " << diffusePaths.size();
for (const auto& path : diffusePaths) { for (const auto& path : diffusePaths) {
outFile << " " << convert_w_string_to_string(path); outFile << " " << convert_w_string_to_string(path);
} }
const auto& normalPaths = textureContainer.GetPaths(TextureType::Normal); // Textures normales
const auto& normalPaths = object->get_model()->GetTextureContainer().GetPaths(TextureType::Normal);
outFile << " " << normalPaths.size(); outFile << " " << normalPaths.size();
for (const auto& path : normalPaths) { for (const auto& path : normalPaths) {
outFile << " " << convert_w_string_to_string(path); outFile << " " << convert_w_string_to_string(path);
} }
const auto& specularPaths = textureContainer.GetPaths(TextureType::Specular);
// Textures spéculaires
const auto& specularPaths = object->get_model()->GetTextureContainer().GetPaths(TextureType::Specular);
outFile << " " << specularPaths.size(); outFile << " " << specularPaths.size();
for (const auto& path : specularPaths) { for (const auto& path : specularPaths) {
outFile << " " << convert_w_string_to_string(path); outFile << " " << convert_w_string_to_string(path);
} }
const auto& alphaPaths = textureContainer.GetPaths(TextureType::Alpha);
// Textures alpha
const auto& alphaPaths = object->get_model()->GetTextureContainer().GetPaths(TextureType::Alpha);
outFile << " " << alphaPaths.size(); outFile << " " << alphaPaths.size();
for (const auto& path : alphaPaths) { for (const auto& path : alphaPaths) {
outFile << " " << convert_w_string_to_string(path); outFile << " " << convert_w_string_to_string(path);
} }
}
outFile << std::endl; outFile << std::endl;
} }
@ -447,4 +344,3 @@ std::string scene_manager::convert_w_string_to_string(const std::wstring& wstr)
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &str[0], size_needed, NULL, NULL); WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &str[0], size_needed, NULL, NULL);
return str; return str;
} }

View File

@ -3,8 +3,6 @@
stats::stats() : fps_(nullptr), drawcalls_(0) stats::stats() : fps_(nullptr), drawcalls_(0)
{ {
total_triangle_count_ = std::make_shared<int>(0);
total_vertex_count_ = std::make_shared<int>(0);
} }
stats::~stats() stats::~stats()
@ -36,20 +34,13 @@ bool stats::initialize(application_class* app)
void stats::update_geometric_stats() void stats::update_geometric_stats()
{ {
// Utiliser le système ECS pour accéder aux entités avec des composants de rendu
if (app_ && app_->get_entity_manager())
{
*total_vertex_count_ = get_total_vertex_count();
*total_triangle_count_ = get_total_triangle_count();
update_visible_count(); object_vec_ = app_->get_kobjects();
cubes_vec_ = app_->get_cubes();
terrain_chunk_vec_ = app_->get_terrain_cubes();
Logger::Get().Log("Statistics updated: " + std::to_string(*total_vertex_count_) + " vertices, " + std::to_string(*total_triangle_count_) + " triangles", __FILE__, __LINE__, Logger::LogLevel::Debug); total_vertex_count_ = get_total_vertex_count();
} total_triangle_count_ = get_total_triangle_count();
}
void stats::update_visible_count()
{
visible_triangle_count_ = get_visible_triangle_count(); visible_triangle_count_ = get_visible_triangle_count();
} }
@ -66,143 +57,88 @@ void stats::update_display_stats()
int stats::get_total_vertex_count() const int stats::get_total_vertex_count() const
{ {
int totalVertices = 0; int totalVertices = 0;
// Utiliser le système ECS pour accéder aux entités avec des composants de rendu
if (app_ && app_->get_entity_manager())
{
auto entities = app_->get_entity_manager()->GetEntitiesWithComponent<ecs::RenderComponent>();
for (const auto& entity : entities)
{
auto renderComponent = entity->GetComponent<ecs::RenderComponent>();
if (renderComponent && renderComponent->GetModel())
{
totalVertices += renderComponent->GetModel()->GetVertexCount();
}
}
}
// Ajouter également les éventuels objets restants de l'ancien système
for (const auto& obj : object_vec_) for (const auto& obj : object_vec_)
{ {
if (obj && obj->get_model()) if (obj)
{ {
totalVertices += obj->get_model()->GetVertexCount(); totalVertices += obj->get_model()->GetVertexCount();
} }
} }
// Ajoutez le nombre de sommets pour les cubes
for (const auto& cube : cubes_vec_) for (const auto& cube : cubes_vec_)
{ {
if (cube && cube->get_model()) if (cube)
{ {
totalVertices += cube->get_model()->GetVertexCount(); totalVertices += cube->get_model()->GetVertexCount();
} }
} }
// Ajoutez le nombre de sommets pour le terrain
for (const auto& chunk : terrain_chunk_vec_) for (const auto& chunk : terrain_chunk_vec_)
{ {
if (chunk && chunk->get_model()) if (chunk)
{ {
totalVertices += chunk->get_model()->GetVertexCount(); totalVertices += chunk->get_model()->GetVertexCount();
} }
} }
return totalVertices; return totalVertices;
} }
int stats::get_total_triangle_count() const int stats::get_total_triangle_count() const
{ {
int totalTriangles = 0; int totalTriangles = 0;
// Utiliser le système ECS pour accéder aux entités avec des composants de rendu
if (app_ && app_->get_entity_manager())
{
auto entities = app_->get_entity_manager()->GetEntitiesWithComponent<ecs::RenderComponent>();
for (const auto& entity : entities)
{
auto renderComponent = entity->GetComponent<ecs::RenderComponent>();
if (renderComponent && renderComponent->GetModel())
{
// Dans une topologie de liste de triangles, chaque triangle utilise 3 indices
totalTriangles += renderComponent->GetModel()->GetIndexCount() / 3;
}
}
}
// Ajouter également les éventuels objets restants de l'ancien système
for (const auto& obj : object_vec_) for (const auto& obj : object_vec_)
{ {
if (obj && obj->get_model()) if (obj)
{ {
// Dans une topologie de liste de triangles, chaque triangle utilise 3 indices
totalTriangles += obj->get_model()->GetIndexCount() / 3; totalTriangles += obj->get_model()->GetIndexCount() / 3;
} }
} }
// Ajoutez le nombre de triangles pour les cubes
for (const auto& cube : cubes_vec_) for (const auto& cube : cubes_vec_)
{ {
if (cube && cube->get_model()) if (cube)
{ {
totalTriangles += cube->get_model()->GetIndexCount() / 3; totalTriangles += cube->get_model()->GetIndexCount() / 3;
} }
} }
// Ajoutez le nombre de triangles pour le terrain
for (const auto& chunk : terrain_chunk_vec_) for (const auto& chunk : terrain_chunk_vec_)
{ {
if (chunk && chunk->get_model()) if (chunk)
{ {
totalTriangles += chunk->get_model()->GetIndexCount() / 3; totalTriangles += chunk->get_model()->GetIndexCount() / 3;
} }
} }
return totalTriangles; return totalTriangles;
} }
int stats::get_visible_triangle_count() const int stats::get_visible_triangle_count() const
{ {
int visibleTriangles = 0; int visibleTriangles = 0;
// Utiliser le système ECS pour accéder aux entités avec des composants de rendu
if (app_ && app_->get_entity_manager())
{
auto entities = app_->get_entity_manager()->GetEntitiesWithComponent<ecs::RenderComponent>();
for (const auto& entity : entities)
{
auto renderComponent = entity->GetComponent<ecs::RenderComponent>();
if (renderComponent && renderComponent->GetModel() && renderComponent->IsVisible())
{
// Dans une topologie de liste de triangles, chaque triangle utilise 3 indices
visibleTriangles += renderComponent->GetModel()->GetIndexCount() / 3;
}
}
}
// Ajouter également les éventuels objets restants de l'ancien système
for (const auto& obj : object_vec_) for (const auto& obj : object_vec_)
{ {
if (obj && obj->get_model() && obj->IsVisible()) if (obj && obj->IsVisible())
{ {
visibleTriangles += obj->get_model()->GetIndexCount() / 3; visibleTriangles += obj->get_model()->GetIndexCount() / 3;
} }
} }
// Ajoutez le nombre de triangles visibles pour les cubes
for (const auto& cube : cubes_vec_) for (const auto& cube : cubes_vec_)
{ {
if (cube && cube->get_model() && cube->IsVisible()) if (cube && cube->IsVisible())
{ {
visibleTriangles += cube->get_model()->GetIndexCount() / 3; visibleTriangles += cube->get_model()->GetIndexCount() / 3;
} }
} }
// Ajoutez le nombre de triangles visibles pour le terrain
for (const auto& chunk : terrain_chunk_vec_) for (const auto& chunk : terrain_chunk_vec_)
{ {
if (chunk && chunk->get_model() && chunk->IsVisible()) if (chunk && chunk->IsVisible())
{ {
visibleTriangles += chunk->get_model()->GetIndexCount() / 3; visibleTriangles += chunk->get_model()->GetIndexCount() / 3;
} }
} }
return visibleTriangles; return visibleTriangles;
} }