From 618f5c7f43aa5731a1b472597a979553bb81d90a Mon Sep 17 00:00:00 2001 From: SirLynix Date: Sun, 8 May 2022 13:26:51 +0200 Subject: [PATCH 01/17] WIP --- include/ClientLib/ClientConsole.hpp | 2 +- include/ClientLib/ClientLayerEntity.hpp | 2 +- include/ClientLib/ClientMatch.hpp | 14 +- include/ClientLib/EscapeMenu.hpp | 2 +- include/ClientLib/LayerVisualEntity.hpp | 4 +- include/ClientLib/LayerVisualEntity.inl | 4 +- .../ClientLib/LocalPlayerInputController.hpp | 2 +- include/ClientLib/OptionWidget.hpp | 4 +- include/ClientLib/Scoreboard.hpp | 14 +- .../Scripting/ClientEditorEntityStore.hpp | 5 +- .../Scripting/ClientElementLibrary.hpp | 2 +- .../Scripting/ClientEntityLibrary.hpp | 2 +- .../ClientLib/Scripting/ClientEntityStore.hpp | 2 +- .../Scripting/ClientScriptingLibrary.hpp | 2 +- .../ClientLib/Scripting/ClientWeaponStore.hpp | 2 +- include/ClientLib/Scripting/ParticleGroup.hpp | 2 +- include/ClientLib/Scripting/Text.inl | 2 +- include/ClientLib/SoundEntity.hpp | 2 +- include/ClientLib/SoundEntity.inl | 2 +- include/ClientLib/VisualEntity.hpp | 2 +- include/ClientLib/VisualEntity.inl | 2 +- include/CoreLib/AssetStore.hpp | 16 +- include/CoreLib/AssetStore.inl | 62 +++-- .../CoreLib/BasicPlayerMovementController.hpp | 2 +- .../CoreLib/Components/AnimationComponent.hpp | 8 +- .../CoreLib/Components/AnimationComponent.inl | 5 +- include/CoreLib/Components/BaseComponent.hpp | 41 +++ include/CoreLib/Components/BaseComponent.inl | 47 ++++ .../Components/CollisionDataComponent.hpp | 12 +- .../Components/ConstraintComponent2D.hpp | 49 ++++ .../Components/ConstraintComponent2D.inl | 58 ++++ .../CoreLib/Components/CooldownComponent.hpp | 5 +- .../DestructionWatcherComponent.hpp | 30 +++ .../DestructionWatcherComponent.inl | 7 +- .../Components/EntityOwnerComponent.hpp | 16 +- .../Components/EntityOwnerComponent.inl | 22 +- .../CoreLib/Components/HealthComponent.hpp | 22 +- .../CoreLib/Components/HealthComponent.inl | 13 +- include/CoreLib/Components/InputComponent.hpp | 5 +- include/CoreLib/Components/MatchComponent.hpp | 5 +- .../Components/NetworkSyncComponent.hpp | 14 +- .../Components/NetworkSyncComponent.inl | 6 +- include/CoreLib/Components/OwnerComponent.hpp | 5 +- .../Components/PlayerControlledComponent.hpp | 5 +- .../Components/PlayerMovementComponent.hpp | 5 +- .../CoreLib/Components/ScriptComponent.hpp | 15 +- .../CoreLib/Components/ScriptComponent.inl | 3 +- .../CoreLib/Components/WeaponComponent.hpp | 13 +- .../CoreLib/Components/WeaponComponent.inl | 10 +- .../Components/WeaponWielderComponent.hpp | 29 +- .../Components/WeaponWielderComponent.inl | 22 +- include/CoreLib/CustomInputController.hpp | 2 +- include/CoreLib/EntityOwner.hpp | 37 +++ include/CoreLib/EntityOwner.inl | 35 +++ include/CoreLib/InputController.hpp | 4 +- .../CoreLib/LogSystem/EntityLogContext.hpp | 4 +- include/CoreLib/LogSystem/EntityLogger.hpp | 7 +- include/CoreLib/LogSystem/EntityLogger.inl | 4 +- include/CoreLib/LogSystem/Logger.hpp | 9 +- include/CoreLib/LogSystem/Logger.inl | 15 +- include/CoreLib/LogSystem/MatchLogger.hpp | 6 +- include/CoreLib/LogSystem/MatchLogger.inl | 8 +- include/CoreLib/Match.hpp | 21 +- include/CoreLib/Match.inl | 4 +- include/CoreLib/MatchClientVisibility.hpp | 3 +- include/CoreLib/MatchSessions.hpp | 6 +- include/CoreLib/NetworkReactor.hpp | 4 +- include/CoreLib/Player.hpp | 14 +- include/CoreLib/Player.inl | 7 +- include/CoreLib/PlayerInputController.hpp | 2 +- include/CoreLib/PlayerMovementController.hpp | 4 +- include/CoreLib/Protocol/Packets.hpp | 1 - .../Scripting/AbstractElementLibrary.hpp | 1 - .../Scripting/AbstractScriptingLibrary.hpp | 2 +- .../Scripting/AbstractScriptingLibrary.inl | 4 - include/CoreLib/Scripting/Constraint.hpp | 15 +- include/CoreLib/Scripting/Constraint.inl | 16 +- include/CoreLib/Scripting/NetworkPacket.inl | 4 +- include/CoreLib/Scripting/ScriptStore.hpp | 9 +- include/CoreLib/Scripting/ScriptStore.inl | 21 +- .../CoreLib/Scripting/ScriptingContext.hpp | 25 +- .../CoreLib/Scripting/ScriptingContext.inl | 4 +- include/CoreLib/Scripting/ScriptingUtils.hpp | 8 +- .../Scripting/ServerElementLibrary.hpp | 2 +- .../CoreLib/Scripting/ServerEntityLibrary.hpp | 14 +- .../CoreLib/Scripting/ServerEntityStore.hpp | 7 +- include/CoreLib/Scripting/ServerTexture.hpp | 4 +- include/CoreLib/Scripting/ServerTexture.inl | 2 +- .../CoreLib/Scripting/ServerWeaponStore.hpp | 3 +- .../Scripting/SharedElementLibrary.hpp | 2 +- .../CoreLib/Scripting/SharedEntityLibrary.hpp | 16 +- .../CoreLib/Scripting/SharedEntityStore.hpp | 6 +- .../CoreLib/Scripting/SharedWeaponStore.hpp | 4 +- include/CoreLib/ScriptingEnvironment.hpp | 2 +- include/CoreLib/SharedLayer.hpp | 8 +- include/CoreLib/SharedLayer.inl | 10 +- include/CoreLib/SharedMatch.hpp | 9 +- include/CoreLib/Systems/AnimationSystem.hpp | 7 +- include/CoreLib/Systems/InputSystem.hpp | 7 +- include/CoreLib/Systems/NetworkSyncSystem.hpp | 74 +++-- include/CoreLib/Systems/NetworkSyncSystem.inl | 16 +- .../CoreLib/Systems/PlayerMovementSystem.hpp | 5 +- include/CoreLib/Utility/VirtualDirectory.hpp | 63 ----- include/CoreLib/Utility/VirtualDirectory.inl | 242 ----------------- scripts/entities/sound.lua | 20 ++ src/Client/ClientApp.cpp | 2 +- src/Client/States/AbstractState.cpp | 4 +- src/Client/States/AbstractState.hpp | 9 +- src/Client/States/AbstractState.inl | 6 +- src/Client/States/Game/ConnectionState.cpp | 6 +- src/Client/States/Game/GameState.cpp | 2 +- src/Client/States/Game/GameState.hpp | 2 +- .../States/Game/ResourceDownloadState.cpp | 14 +- .../States/Game/ResourceDownloadState.hpp | 6 +- src/Client/States/JoinServerState.cpp | 8 +- src/Client/States/MainMenuState.cpp | 6 +- src/Client/States/ServerListState.cpp | 6 +- src/Client/States/ServerListState.hpp | 2 +- src/Client/States/StartServerState.cpp | 16 +- src/Client/States/StartServerState.hpp | 2 +- src/ClientLib/Chatbox.cpp | 2 +- src/ClientLib/ClientConsole.cpp | 2 +- src/ClientLib/ClientLayer.cpp | 4 +- src/ClientLib/ClientLayerEntity.cpp | 4 +- src/ClientLib/ClientMatch.cpp | 22 +- src/ClientLib/ClientSession.cpp | 2 +- .../Components/SoundEmitterComponent.cpp | 4 +- src/ClientLib/Console.cpp | 2 +- src/ClientLib/EscapeMenu.cpp | 2 +- src/ClientLib/HttpDownloadManager.cpp | 2 +- src/ClientLib/LocalPlayerInputController.cpp | 10 +- src/ClientLib/OptionWidget.cpp | 4 +- src/ClientLib/PacketDownloadManager.cpp | 2 +- src/ClientLib/Scoreboard.cpp | 12 +- .../Scripting/ClientEditorEntityStore.cpp | 6 +- .../Scripting/ClientElementLibrary.cpp | 26 +- .../Scripting/ClientEntityLibrary.cpp | 8 +- src/ClientLib/Scripting/ClientEntityStore.cpp | 4 +- .../Scripting/ClientScriptingLibrary.cpp | 12 +- .../Scripting/ClientWeaponLibrary.cpp | 4 +- src/ClientLib/Scripting/ClientWeaponStore.cpp | 4 +- src/ClientLib/Scripting/ParticleGroup.cpp | 2 +- src/ClientLib/Systems/FrameCallbackSystem.cpp | 2 +- .../Systems/PostFrameCallbackSystem.cpp | 2 +- src/ClientLib/Systems/SoundSystem.cpp | 2 +- .../Systems/VisualInterpolationSystem.cpp | 2 +- src/CoreLib/AssetStore.cpp | 2 +- src/CoreLib/BasicPlayerMovementController.cpp | 2 +- src/CoreLib/BurgApp.cpp | 22 -- src/CoreLib/Components/AnimationComponent.cpp | 2 - .../Components/CollisionDataComponent.cpp | 20 +- src/CoreLib/Components/CooldownComponent.cpp | 10 - .../Components/EntityOwnerComponent.cpp | 10 - src/CoreLib/Components/InputComponent.cpp | 10 - src/CoreLib/Components/MatchComponent.cpp | 10 - .../Components/NetworkSyncComponent.cpp | 10 - src/CoreLib/Components/OwnerComponent.cpp | 11 - .../Components/PlayerControlledComponent.cpp | 10 - .../Components/PlayerMovementComponent.cpp | 11 - src/CoreLib/Components/ScriptComponent.cpp | 13 +- src/CoreLib/Components/WeaponComponent.cpp | 10 - .../Components/WeaponWielderComponent.cpp | 34 +-- src/CoreLib/CustomInputController.cpp | 9 +- src/CoreLib/LogSystem/EntityLogger.cpp | 4 +- src/CoreLib/LogSystem/Logger.cpp | 6 +- src/CoreLib/LogSystem/MatchLogger.cpp | 4 +- src/CoreLib/Map.cpp | 16 +- src/CoreLib/MasterServerEntry.cpp | 2 +- src/CoreLib/Match.cpp | 35 ++- src/CoreLib/MatchClientSession.cpp | 4 +- src/CoreLib/MatchClientVisibility.cpp | 2 +- src/CoreLib/MatchSessions.cpp | 11 +- src/CoreLib/Mod.cpp | 2 +- src/CoreLib/NetworkReactor.cpp | 8 +- src/CoreLib/NetworkSessionManager.cpp | 2 +- src/CoreLib/Player.cpp | 54 ++-- src/CoreLib/PlayerInputController.cpp | 8 +- src/CoreLib/PlayerMovementController.cpp | 2 +- src/CoreLib/PropertyValues.cpp | 4 +- .../Scripting/AbstractElementLibrary.cpp | 2 - src/CoreLib/Scripting/Constraint.cpp | 21 +- src/CoreLib/Scripting/ScriptingContext.cpp | 175 +++++++----- src/CoreLib/Scripting/ScriptingUtils.cpp | 22 +- .../Scripting/ServerElementLibrary.cpp | 20 +- src/CoreLib/Scripting/ServerEntityLibrary.cpp | 30 +-- src/CoreLib/Scripting/ServerEntityStore.cpp | 82 +++--- .../Scripting/ServerScriptingLibrary.cpp | 12 +- src/CoreLib/Scripting/ServerWeaponLibrary.cpp | 8 +- src/CoreLib/Scripting/ServerWeaponStore.cpp | 4 +- .../Scripting/SharedElementLibrary.cpp | 40 +-- src/CoreLib/Scripting/SharedEntityLibrary.cpp | 90 +++---- src/CoreLib/Scripting/SharedEntityStore.cpp | 6 +- .../Scripting/SharedScriptingLibrary.cpp | 38 +-- src/CoreLib/Scripting/SharedWeaponLibrary.cpp | 6 +- src/CoreLib/Scripting/SharedWeaponStore.cpp | 4 +- src/CoreLib/ScriptingEnvironment.cpp | 3 +- src/CoreLib/SharedLayer.cpp | 12 +- src/CoreLib/Systems/AnimationSystem.cpp | 10 +- src/CoreLib/Systems/InputSystem.cpp | 2 +- src/CoreLib/Systems/NetworkSyncSystem.cpp | 16 +- src/CoreLib/Systems/PlayerMovementSystem.cpp | 19 +- src/CoreLib/Systems/TickCallbackSystem.cpp | 2 +- src/CoreLib/Systems/WeaponSystem.cpp | 4 +- src/CoreLib/TerrainLayer.cpp | 4 +- src/CoreLib/Utility/CrashHandlerWin32.cpp | 7 +- src/CoreLib/WebRequest.cpp | 10 +- src/CoreLib/WebService.cpp | 8 +- src/MapEditor/Gizmos/EditorGizmo.hpp | 2 +- src/MapEditor/Gizmos/EditorGizmo.inl | 2 +- src/MapEditor/Gizmos/PositionGizmo.cpp | 4 +- src/MapEditor/Logic/EntityEditorMode.cpp | 2 +- src/MapEditor/Logic/EntityEditorMode.hpp | 2 +- src/MapEditor/Logic/TileMapEditorMode.cpp | 4 +- src/MapEditor/Logic/TileMapEditorMode.hpp | 2 +- .../Scripting/EditorElementLibrary.cpp | 4 +- .../Scripting/EditorEntityLibrary.cpp | 4 +- .../Scripting/EditorEntityLibrary.hpp | 2 +- src/MapEditor/Scripting/EditorEntityStore.cpp | 6 +- src/MapEditor/Scripting/EditorEntityStore.hpp | 4 +- .../Scripting/EditorScriptingLibrary.cpp | 2 +- src/MapEditor/Widgets/EditorWindow.cpp | 4 +- src/MapEditor/Widgets/EditorWindowPrefabs.cpp | 4 +- src/MapEditor/Widgets/EntityInfoDialog.cpp | 2 +- src/MapEditor/Widgets/EntityInfoDialog.hpp | 4 +- src/MapEditor/Widgets/EntityInfoDialog.inl | 2 +- src/MapEditor/Widgets/MapCanvas.cpp | 14 +- src/MapEditor/Widgets/MapCanvas.hpp | 16 +- src/MapEditor/Widgets/MapCanvas.inl | 6 +- src/MapEditor/Widgets/MapCanvasLayer.cpp | 2 +- src/MapEditor/Widgets/PlayWindow.cpp | 2 +- src/MapEditor/Widgets/TileSelectionWidget.cpp | 2 +- xmake-repo/packages/n/nazaraengine/xmake.lua | 252 +++--------------- xmake-requires.lock | 155 +++-------- xmake.lua | 8 +- 234 files changed, 1426 insertions(+), 1799 deletions(-) create mode 100644 include/CoreLib/Components/BaseComponent.hpp create mode 100644 include/CoreLib/Components/BaseComponent.inl create mode 100644 include/CoreLib/Components/ConstraintComponent2D.hpp create mode 100644 include/CoreLib/Components/ConstraintComponent2D.inl create mode 100644 include/CoreLib/Components/DestructionWatcherComponent.hpp rename src/CoreLib/Components/HealthComponent.cpp => include/CoreLib/Components/DestructionWatcherComponent.inl (53%) create mode 100644 include/CoreLib/EntityOwner.hpp create mode 100644 include/CoreLib/EntityOwner.inl delete mode 100644 include/CoreLib/Utility/VirtualDirectory.hpp delete mode 100644 include/CoreLib/Utility/VirtualDirectory.inl create mode 100644 scripts/entities/sound.lua delete mode 100644 src/CoreLib/Components/CooldownComponent.cpp delete mode 100644 src/CoreLib/Components/EntityOwnerComponent.cpp delete mode 100644 src/CoreLib/Components/InputComponent.cpp delete mode 100644 src/CoreLib/Components/MatchComponent.cpp delete mode 100644 src/CoreLib/Components/NetworkSyncComponent.cpp delete mode 100644 src/CoreLib/Components/OwnerComponent.cpp delete mode 100644 src/CoreLib/Components/PlayerControlledComponent.cpp delete mode 100644 src/CoreLib/Components/PlayerMovementComponent.cpp delete mode 100644 src/CoreLib/Components/WeaponComponent.cpp diff --git a/include/ClientLib/ClientConsole.hpp b/include/ClientLib/ClientConsole.hpp index 92ddd392..2eba846a 100644 --- a/include/ClientLib/ClientConsole.hpp +++ b/include/ClientLib/ClientConsole.hpp @@ -20,7 +20,7 @@ namespace bw class BURGWAR_CLIENTLIB_API ClientConsole : public Console { public: - ClientConsole(const Logger& logger, Nz::RenderTarget* window, Ndk::Canvas* canvas, std::shared_ptr scriptingLibrary, const std::shared_ptr& scriptDir); + ClientConsole(const Logger& logger, Nz::RenderTarget* window, Ndk::Canvas* canvas, std::shared_ptr scriptingLibrary, const std::shared_ptr& scriptDir); ClientConsole(const ClientConsole&) = delete; ClientConsole(ClientConsole&&) = delete; ~ClientConsole() = default; diff --git a/include/ClientLib/ClientLayerEntity.hpp b/include/ClientLib/ClientLayerEntity.hpp index 0d67feb9..b3468412 100644 --- a/include/ClientLib/ClientLayerEntity.hpp +++ b/include/ClientLib/ClientLayerEntity.hpp @@ -31,7 +31,7 @@ namespace bw class BURGWAR_CLIENTLIB_API ClientLayerEntity final : public LayerVisualEntity { public: - ClientLayerEntity(ClientLayer& layer, const Ndk::EntityHandle& entity, Nz::UInt32 serverEntityId, EntityId uniqueId); + ClientLayerEntity(ClientLayer& layer, entt::entity entity, Nz::UInt32 serverEntityId, EntityId uniqueId); ClientLayerEntity(const ClientLayerEntity&) = delete; ClientLayerEntity(ClientLayerEntity&& entity) noexcept = default; ~ClientLayerEntity(); diff --git a/include/ClientLib/ClientMatch.hpp b/include/ClientLib/ClientMatch.hpp index 7f526b0a..9e881d3b 100644 --- a/include/ClientLib/ClientMatch.hpp +++ b/include/ClientLib/ClientMatch.hpp @@ -65,7 +65,7 @@ namespace bw Nz::UInt64 EstimateServerTick() const; - void ForEachEntity(std::function func) override; + void ForEachEntity(std::function func) override; template void ForEachPlayer(F&& func); inline Nz::UInt16 GetActiveLayer(); @@ -95,15 +95,15 @@ namespace bw void InitDebugGhosts(); - void LoadAssets(std::shared_ptr assetDir); - void LoadScripts(const std::shared_ptr& scriptDir); + void LoadAssets(std::shared_ptr assetDir); + void LoadScripts(const std::shared_ptr& scriptDir); inline void Quit(); void RegisterEntity(EntityId uniqueId, ClientLayerEntityHandle entity); - const Ndk::EntityHandle& RetrieveEntityByUniqueId(EntityId uniqueId) const override; - EntityId RetrieveUniqueIdByEntity(const Ndk::EntityHandle& entity) const override; + entt::entity RetrieveEntityByUniqueId(EntityId uniqueId) const override; + EntityId RetrieveUniqueIdByEntity(entt::entity entity) const override; void UnregisterEntity(EntityId uniqueId); @@ -181,7 +181,7 @@ namespace bw { struct Weapon { - Ndk::EntityHandle entity; + entt::entity entity; Nz::UInt8 category; }; @@ -213,7 +213,7 @@ namespace bw struct WeaponData { - Ndk::EntityHandle entity; + entt::entity entity; bool isAttacking; }; diff --git a/include/ClientLib/EscapeMenu.hpp b/include/ClientLib/EscapeMenu.hpp index 4e18ff61..dfa80539 100644 --- a/include/ClientLib/EscapeMenu.hpp +++ b/include/ClientLib/EscapeMenu.hpp @@ -50,7 +50,7 @@ namespace bw Ndk::ButtonWidget* m_leaveMatchButton; Ndk::ButtonWidget* m_optionsButton; Ndk::ButtonWidget* m_quitAppButton; - Ndk::BaseWidget* m_backgroundWidget; + Nz::BaseWidget* m_backgroundWidget; ClientEditorApp& m_app; OptionWidget* m_optionWidget; }; diff --git a/include/ClientLib/LayerVisualEntity.hpp b/include/ClientLib/LayerVisualEntity.hpp index b2ec575e..dd18d94b 100644 --- a/include/ClientLib/LayerVisualEntity.hpp +++ b/include/ClientLib/LayerVisualEntity.hpp @@ -32,7 +32,7 @@ namespace bw friend VisualEntity; public: - inline LayerVisualEntity(const Ndk::EntityHandle& entity, LayerIndex layerIndex, EntityId uniqueId); + inline LayerVisualEntity(entt::entity entity, LayerIndex layerIndex, EntityId uniqueId); LayerVisualEntity(const LayerVisualEntity&) = delete; LayerVisualEntity(LayerVisualEntity&& entity) noexcept; virtual ~LayerVisualEntity(); @@ -47,7 +47,7 @@ namespace bw template void ForEachRenderable(Func&& func) const; - inline const Ndk::EntityHandle& GetEntity() const; + inline entt::entity GetEntity() const; Nz::Boxf GetGlobalBounds() const; inline LayerIndex GetLayerIndex() const; Nz::Boxf GetLocalBounds() const; diff --git a/include/ClientLib/LayerVisualEntity.inl b/include/ClientLib/LayerVisualEntity.inl index 10cdd79a..6865b279 100644 --- a/include/ClientLib/LayerVisualEntity.inl +++ b/include/ClientLib/LayerVisualEntity.inl @@ -8,7 +8,7 @@ namespace bw { - inline LayerVisualEntity::LayerVisualEntity(const Ndk::EntityHandle& entity, LayerIndex layerIndex, EntityId uniqueId) : + inline LayerVisualEntity::LayerVisualEntity(entt::entity entity, LayerIndex layerIndex, EntityId uniqueId) : m_entity(entity), m_uniqueId(uniqueId), m_layerIndex(layerIndex) @@ -28,7 +28,7 @@ namespace bw func(std::as_const(renderableData.renderable), std::as_const(renderableData.offsetMatrix), std::as_const(renderableData.renderOrder)); } - inline const Ndk::EntityHandle& LayerVisualEntity::GetEntity() const + inline entt::entity LayerVisualEntity::GetEntity() const { return m_entity; } diff --git a/include/ClientLib/LocalPlayerInputController.hpp b/include/ClientLib/LocalPlayerInputController.hpp index ee5e2822..7742db9f 100644 --- a/include/ClientLib/LocalPlayerInputController.hpp +++ b/include/ClientLib/LocalPlayerInputController.hpp @@ -18,7 +18,7 @@ namespace bw LocalPlayerInputController() = default; ~LocalPlayerInputController() = default; - std::optional GenerateInputs(const Ndk::EntityHandle& entity) const override; + std::optional GenerateInputs(entt::registry& registry, entt::entity entity) const override; }; } diff --git a/include/ClientLib/OptionWidget.hpp b/include/ClientLib/OptionWidget.hpp index 65b25ab0..2f00624b 100644 --- a/include/ClientLib/OptionWidget.hpp +++ b/include/ClientLib/OptionWidget.hpp @@ -20,10 +20,10 @@ namespace bw { class ConfigFile; - class BURGWAR_CLIENTLIB_API OptionWidget : public Ndk::BaseWidget + class BURGWAR_CLIENTLIB_API OptionWidget : public Nz::BaseWidget { public: - OptionWidget(Ndk::BaseWidget* parent, ConfigFile& playerConfig); + OptionWidget(Nz::BaseWidget* parent, ConfigFile& playerConfig); OptionWidget(const OptionWidget&) = delete; OptionWidget(OptionWidget&&) = delete; ~OptionWidget() = default; diff --git a/include/ClientLib/Scoreboard.hpp b/include/ClientLib/Scoreboard.hpp index 03cdf2a3..3478d374 100644 --- a/include/ClientLib/Scoreboard.hpp +++ b/include/ClientLib/Scoreboard.hpp @@ -21,10 +21,10 @@ namespace bw using ScoreboardHandle = Nz::ObjectHandle; - class BURGWAR_CLIENTLIB_API Scoreboard : public Ndk::BaseWidget, public Nz::HandledObject + class BURGWAR_CLIENTLIB_API Scoreboard : public Nz::BaseWidget, public Nz::HandledObject { public: - Scoreboard(Ndk::BaseWidget* parent, const Logger& logger); + Scoreboard(Nz::BaseWidget* parent, const Logger& logger); Scoreboard(const Scoreboard&) = delete; Scoreboard(Scoreboard&&) = delete; ~Scoreboard(); @@ -57,7 +57,7 @@ namespace bw Ndk::LabelWidget* label; }; - Ndk::BaseWidget* background; + Nz::BaseWidget* background; std::optional color; std::size_t teamId; std::vector values; @@ -73,7 +73,7 @@ namespace bw { std::string name; Nz::Color color; - Ndk::BaseWidget* background; + Nz::BaseWidget* background; Ndk::ImageWidget* line; Ndk::LabelWidget* widget; }; @@ -81,9 +81,9 @@ namespace bw std::vector m_columns; std::vector> m_players; std::vector m_teams; - Ndk::BaseWidget* m_backgroundWidget; - Ndk::BaseWidget* m_columnBackgroundWidget; - Ndk::BaseWidget* m_contentWidget; + Nz::BaseWidget* m_backgroundWidget; + Nz::BaseWidget* m_columnBackgroundWidget; + Nz::BaseWidget* m_contentWidget; Ndk::ScrollAreaWidget* m_scrollArea; const Logger& m_logger; }; diff --git a/include/ClientLib/Scripting/ClientEditorEntityStore.hpp b/include/ClientLib/Scripting/ClientEditorEntityStore.hpp index c0144479..814400c6 100644 --- a/include/ClientLib/Scripting/ClientEditorEntityStore.hpp +++ b/include/ClientLib/Scripting/ClientEditorEntityStore.hpp @@ -12,7 +12,6 @@ #include #include #include -#include namespace bw { @@ -26,8 +25,8 @@ namespace bw ClientEditorEntityStore(ClientEditorEntityStore&&) = delete; ~ClientEditorEntityStore() = default; - bool InitializeEntity(const Ndk::EntityHandle& entity) const; - virtual const Ndk::EntityHandle& InstantiateEntity(Ndk::World& world, std::size_t entityIndex, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, const Ndk::EntityHandle& parentEntity = Ndk::EntityHandle::InvalidHandle) const; + bool InitializeEntity(entt::entity entity) const; + virtual entt::entity InstantiateEntity(entt::registry& registry, std::size_t entityIndex, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, entt::entity parentEntity = entt::null) const; protected: void InitializeElementTable(sol::main_table& elementTable) override; diff --git a/include/ClientLib/Scripting/ClientElementLibrary.hpp b/include/ClientLib/Scripting/ClientElementLibrary.hpp index f3db9960..80792cf8 100644 --- a/include/ClientLib/Scripting/ClientElementLibrary.hpp +++ b/include/ClientLib/Scripting/ClientElementLibrary.hpp @@ -24,7 +24,7 @@ namespace bw protected: virtual void RegisterClientLibrary(sol::table& elementTable); - void SetScale(const Ndk::EntityHandle& entity, float newScale) override; + void SetScale(entt::entity entity, float newScale) override; private: ClientAssetStore& m_assetStore; diff --git a/include/ClientLib/Scripting/ClientEntityLibrary.hpp b/include/ClientLib/Scripting/ClientEntityLibrary.hpp index 3afa1fb9..caed6701 100644 --- a/include/ClientLib/Scripting/ClientEntityLibrary.hpp +++ b/include/ClientLib/Scripting/ClientEntityLibrary.hpp @@ -24,7 +24,7 @@ namespace bw void RegisterLibrary(sol::table& elementMetatable) override; protected: - void InitRigidBody(lua_State* L, const Ndk::EntityHandle& entity, float mass) override; + void InitRigidBody(lua_State* L, entt::entity entity, float mass) override; private: void RegisterClientLibrary(sol::table& elementMetatable); diff --git a/include/ClientLib/Scripting/ClientEntityStore.hpp b/include/ClientLib/Scripting/ClientEntityStore.hpp index 3c2c3048..1d2c1d1d 100644 --- a/include/ClientLib/Scripting/ClientEntityStore.hpp +++ b/include/ClientLib/Scripting/ClientEntityStore.hpp @@ -27,7 +27,7 @@ namespace bw ClientEntityStore(ClientEntityStore&&) = delete; ~ClientEntityStore() = default; - std::optional InstantiateEntity(ClientLayer& layer, std::size_t elementIndex, Nz::UInt32 serverId, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, const PropertyValueMap& properties, const Ndk::EntityHandle& parentEntity = Ndk::EntityHandle::InvalidHandle) const; + std::optional InstantiateEntity(ClientLayer& layer, std::size_t elementIndex, Nz::UInt32 serverId, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, const PropertyValueMap& properties, entt::entity parentEntity = entt::null) const; }; } diff --git a/include/ClientLib/Scripting/ClientScriptingLibrary.hpp b/include/ClientLib/Scripting/ClientScriptingLibrary.hpp index dd277304..6ac85541 100644 --- a/include/ClientLib/Scripting/ClientScriptingLibrary.hpp +++ b/include/ClientLib/Scripting/ClientScriptingLibrary.hpp @@ -8,8 +8,8 @@ #define BURGWAR_CORELIB_CLIENTSCRIPTINGLIBRARY_HPP #include -#include #include +#include namespace bw { diff --git a/include/ClientLib/Scripting/ClientWeaponStore.hpp b/include/ClientLib/Scripting/ClientWeaponStore.hpp index f0d3b12c..3252f688 100644 --- a/include/ClientLib/Scripting/ClientWeaponStore.hpp +++ b/include/ClientLib/Scripting/ClientWeaponStore.hpp @@ -22,7 +22,7 @@ namespace bw inline ClientWeaponStore(ClientAssetStore& assetStore, const Logger& logger, std::shared_ptr context); ~ClientWeaponStore() = default; - std::optional InstantiateWeapon(ClientLayer& layer, std::size_t elementIndex, Nz::UInt32 serverId, EntityId uniqueId, const PropertyValueMap& properties, const Ndk::EntityHandle& parent); + std::optional InstantiateWeapon(ClientLayer& layer, std::size_t elementIndex, Nz::UInt32 serverId, EntityId uniqueId, const PropertyValueMap& properties, entt::entity parent); private: void InitializeElementTable(sol::main_table& elementTable) override; diff --git a/include/ClientLib/Scripting/ParticleGroup.hpp b/include/ClientLib/Scripting/ParticleGroup.hpp index 576a1dd9..d5acf13c 100644 --- a/include/ClientLib/Scripting/ParticleGroup.hpp +++ b/include/ClientLib/Scripting/ParticleGroup.hpp @@ -18,7 +18,7 @@ namespace bw class BURGWAR_CLIENTLIB_API ParticleGroup { public: - ParticleGroup(const ParticleRegistry& particleRegistry, const Ndk::EntityHandle& particleGroup); + ParticleGroup(const ParticleRegistry& particleRegistry, entt::entity particleGroup); ParticleGroup(const ParticleGroup&) = delete; ParticleGroup(ParticleGroup&&) noexcept = default; ~ParticleGroup() = default; diff --git a/include/ClientLib/Scripting/Text.inl b/include/ClientLib/Scripting/Text.inl index b1e38114..dd4856a5 100644 --- a/include/ClientLib/Scripting/Text.inl +++ b/include/ClientLib/Scripting/Text.inl @@ -26,7 +26,7 @@ namespace bw inline std::string Text::GetText() const { - return m_drawer.GetText().ToStdString(); + return m_drawer.GetText(); } inline void Text::Hide() diff --git a/include/ClientLib/SoundEntity.hpp b/include/ClientLib/SoundEntity.hpp index da8dcdf6..99437a5f 100644 --- a/include/ClientLib/SoundEntity.hpp +++ b/include/ClientLib/SoundEntity.hpp @@ -29,7 +29,7 @@ namespace bw SoundEntity(SoundEntity&& entity) noexcept; ~SoundEntity(); - inline const Ndk::EntityHandle& GetEntity() const; + inline entt::entity GetEntity() const; void PlaySound(std::size_t soundIndex, const Nz::SoundBufferRef& soundBuffer, bool isLooping, bool isSpatialized); diff --git a/include/ClientLib/SoundEntity.inl b/include/ClientLib/SoundEntity.inl index d9a7feae..98c1ce39 100644 --- a/include/ClientLib/SoundEntity.inl +++ b/include/ClientLib/SoundEntity.inl @@ -6,7 +6,7 @@ namespace bw { - inline const Ndk::EntityHandle& SoundEntity::GetEntity() const + inline entt::entity SoundEntity::GetEntity() const { return m_entity; } diff --git a/include/ClientLib/VisualEntity.hpp b/include/ClientLib/VisualEntity.hpp index 1d5e7792..6a6c2242 100644 --- a/include/ClientLib/VisualEntity.hpp +++ b/include/ClientLib/VisualEntity.hpp @@ -31,7 +31,7 @@ namespace bw VisualEntity(VisualEntity&& entity) noexcept; ~VisualEntity(); - inline const Ndk::EntityHandle& GetEntity() const; + inline entt::entity GetEntity() const; void Update(const Nz::Vector2f& position, const Nz::Quaternionf& rotation, const Nz::Vector2f& scale); diff --git a/include/ClientLib/VisualEntity.inl b/include/ClientLib/VisualEntity.inl index fe22ee13..ead0e6ad 100644 --- a/include/ClientLib/VisualEntity.inl +++ b/include/ClientLib/VisualEntity.inl @@ -6,7 +6,7 @@ namespace bw { - inline const Ndk::EntityHandle& VisualEntity::GetEntity() const + inline entt::entity VisualEntity::GetEntity() const { return m_entity; } diff --git a/include/CoreLib/AssetStore.hpp b/include/CoreLib/AssetStore.hpp index 1772bb12..fa75cba7 100644 --- a/include/CoreLib/AssetStore.hpp +++ b/include/CoreLib/AssetStore.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CORELIB_ASSETSTORE_HPP #include -#include +#include #include #include #include @@ -20,24 +20,24 @@ namespace bw class BURGWAR_CORELIB_API AssetStore { public: - inline AssetStore(const Logger& logger, std::shared_ptr assetDirectory); + inline AssetStore(const Logger& logger, std::shared_ptr assetDirectory); virtual ~AssetStore(); virtual void Clear(); - inline const std::shared_ptr& GetAssetDirectory() const; - const Nz::ImageRef& GetImage(const std::string& imagePath) const; + inline const std::shared_ptr& GetAssetDirectory() const; + const std::shared_ptr& GetImage(const std::string& imagePath) const; - inline void UpdateAssetDirectory(std::shared_ptr assetDirectory); + inline void UpdateAssetDirectory(std::shared_ptr assetDirectory); protected: - template const Nz::ObjectRef& GetResource(const std::string& resourcePath, tsl::hopscotch_map>& cache, const ParameterType& params) const; + template const std::shared_ptr& GetResource(const std::string& resourcePath, tsl::hopscotch_map>& cache, const ParameterType& params) const; const Logger& m_logger; private: - mutable tsl::hopscotch_map m_images; - mutable std::shared_ptr m_assetDirectory; + mutable tsl::hopscotch_map> m_images; + mutable std::shared_ptr m_assetDirectory; }; } diff --git a/include/CoreLib/AssetStore.inl b/include/CoreLib/AssetStore.inl index dc915f98..6a52cc70 100644 --- a/include/CoreLib/AssetStore.inl +++ b/include/CoreLib/AssetStore.inl @@ -9,55 +9,61 @@ namespace bw { - inline AssetStore::AssetStore(const Logger& logger, std::shared_ptr assetDirectory) : + inline AssetStore::AssetStore(const Logger& logger, std::shared_ptr assetDirectory) : m_logger(logger), m_assetDirectory(std::move(assetDirectory)) { } - inline const std::shared_ptr& bw::AssetStore::GetAssetDirectory() const + inline const std::shared_ptr& bw::AssetStore::GetAssetDirectory() const { return m_assetDirectory; } - inline void AssetStore::UpdateAssetDirectory(std::shared_ptr assetDirectory) + inline void AssetStore::UpdateAssetDirectory(std::shared_ptr assetDirectory) { m_assetDirectory = std::move(assetDirectory); } template - const Nz::ObjectRef& AssetStore::GetResource(const std::string& resourcePath, tsl::hopscotch_map>& cache, const ParameterType& params) const + const std::shared_ptr& AssetStore::GetResource(const std::string& resourcePath, tsl::hopscotch_map>& cache, const ParameterType& params) const { - static Nz::ObjectRef InvalidResource; + static std::shared_ptr InvalidResource; if (auto it = cache.find(resourcePath); it != cache.end()) return it->second; - VirtualDirectory::Entry entry; - if (!m_assetDirectory->GetEntry(resourcePath, &entry)) - return InvalidResource; - - auto resource = std::visit([&](auto&& arg) -> Nz::ObjectRef + std::shared_ptr resource; + auto LoadResource = [&](const Nz::VirtualDirectory::Entry& entry) { - using T = std::decay_t; - if constexpr (std::is_same_v) - { - bwLog(m_logger, LogLevel::Info, "Loading asset from memory"); - return ResourceType::LoadFromMemory(arg.data(), arg.size(), params); - } - else if constexpr (std::is_same_v) + return std::visit([&](auto&& arg) { - bwLog(m_logger, LogLevel::Info, "Loading asset from {}", arg.generic_u8string()); - return ResourceType::LoadFromFile(arg.generic_u8string(), params); - } - else if constexpr (std::is_same_v) - { - return nullptr; - } - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); - }, entry); + using T = std::decay_t; + + if constexpr (std::is_same_v) + { + bwLog(m_logger, LogLevel::Info, "Loading asset from memory"); + return (resource = ResourceType::LoadFromMemory(arg.data, arg.size, params)) != nullptr; + } + else if constexpr (std::is_same_v) + { + bwLog(m_logger, LogLevel::Info, "Loading asset from memory"); + return (resource = ResourceType::LoadFromMemory(arg.data.data(), arg.data.size(), params)) != nullptr; + } + else if constexpr (std::is_same_v) + { + bwLog(m_logger, LogLevel::Info, "Loading asset from {}", arg.filePath.generic_u8string()); + return (resource = ResourceType::LoadFromFile(arg.filePath.generic_u8string(), params)) != nullptr; + } + else if constexpr (std::is_same_v || std::is_same_v) + { + return false; + } + else + static_assert(AlwaysFalse::value, "non-exhaustive visitor"); + }, entry); + }; - if (!resource) + if (!m_assetDirectory->GetEntry(resourcePath, LoadResource)) return InvalidResource; return cache.emplace(resourcePath, std::move(resource)).first->second; diff --git a/include/CoreLib/BasicPlayerMovementController.hpp b/include/CoreLib/BasicPlayerMovementController.hpp index 9088f861..367804eb 100644 --- a/include/CoreLib/BasicPlayerMovementController.hpp +++ b/include/CoreLib/BasicPlayerMovementController.hpp @@ -18,7 +18,7 @@ namespace bw BasicPlayerMovementController() = default; ~BasicPlayerMovementController() = default; - bool PreSolveCollision(PlayerMovementComponent& playerMovement, const Ndk::EntityHandle& collisionBody, Nz::Arbiter2D& arbiter) const override; + bool PreSolveCollision(PlayerMovementComponent& playerMovement, entt::entity collisionBody, Nz::Arbiter2D& arbiter) const override; void UpdateVelocity(const PlayerInputData& inputs, PlayerMovementComponent& playerMovement, Nz::RigidBody2D& rigidBody, const Nz::Vector2f& gravity, float damping, float dt) const override; }; diff --git a/include/CoreLib/Components/AnimationComponent.hpp b/include/CoreLib/Components/AnimationComponent.hpp index 52788247..b93fe4d3 100644 --- a/include/CoreLib/Components/AnimationComponent.hpp +++ b/include/CoreLib/Components/AnimationComponent.hpp @@ -8,8 +8,8 @@ #define BURGWAR_CORELIB_COMPONENTS_ANIMATIONCOMPONENT_HPP #include +#include #include -#include #include #include @@ -17,12 +17,12 @@ namespace bw { class AnimationStore; - class BURGWAR_CORELIB_API AnimationComponent : public Ndk::Component + class BURGWAR_CORELIB_API AnimationComponent : public BaseComponent { friend class AnimationSystem; public: - inline AnimationComponent(std::shared_ptr animStore); + inline AnimationComponent(entt::registry& registry, entt::entity entity, std::shared_ptr animStore); inline AnimationComponent(const AnimationComponent& animation); ~AnimationComponent() = default; @@ -34,8 +34,6 @@ namespace bw void Play(std::size_t animId, Nz::UInt64 animStartTime); - static Ndk::ComponentIndex componentIndex; - NazaraSignal(OnAnimationEnd, AnimationComponent* /*emitter*/); NazaraSignal(OnAnimationStart, AnimationComponent* /*emitter*/); diff --git a/include/CoreLib/Components/AnimationComponent.inl b/include/CoreLib/Components/AnimationComponent.inl index 5551019d..bf07f78e 100644 --- a/include/CoreLib/Components/AnimationComponent.inl +++ b/include/CoreLib/Components/AnimationComponent.inl @@ -3,15 +3,18 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include +#include namespace bw { - inline AnimationComponent::AnimationComponent(std::shared_ptr animStore) : + inline AnimationComponent::AnimationComponent(entt::registry& registry, entt::entity entity, std::shared_ptr animStore) : + BaseComponent(registry, entity), m_animationStore(std::move(animStore)) { } inline AnimationComponent::AnimationComponent(const AnimationComponent& animation) : + BaseComponent(animation), m_playingAnimation(animation.m_playingAnimation), m_animationStore(animation.m_animationStore) { diff --git a/include/CoreLib/Components/BaseComponent.hpp b/include/CoreLib/Components/BaseComponent.hpp new file mode 100644 index 00000000..b494f6ef --- /dev/null +++ b/include/CoreLib/Components/BaseComponent.hpp @@ -0,0 +1,41 @@ +// Copyright (C) 2020 Jérôme Leclercq +// This file is part of the "Burgwar" project +// For conditions of distribution and use, see copyright notice in LICENSE + +#pragma once + +#ifndef BURGWAR_CORELIB_COMPONENTS_BASECOMPONENT_HPP +#define BURGWAR_CORELIB_COMPONENTS_BASECOMPONENT_HPP + +#include +#include +#include + +namespace bw +{ + class BURGWAR_CORELIB_API BaseComponent + { + public: + inline BaseComponent(entt::registry& registry, entt::entity entity); + inline BaseComponent(const BaseComponent& component); + inline BaseComponent(BaseComponent&& component) noexcept; + ~BaseComponent() = default; + + inline entt::entity GetEntity() const; + inline entt::registry& GetRegistry(); + inline entt::registry& GetRegistry() const; + + void KillEntity(); + + BaseComponent& operator=(const BaseComponent&) = delete; + BaseComponent& operator=(BaseComponent&&) = delete; + + private: + entt::entity m_entity; + entt::registry& m_registry; + }; +} + +#include + +#endif diff --git a/include/CoreLib/Components/BaseComponent.inl b/include/CoreLib/Components/BaseComponent.inl new file mode 100644 index 00000000..37d208d0 --- /dev/null +++ b/include/CoreLib/Components/BaseComponent.inl @@ -0,0 +1,47 @@ +// Copyright (C) 2020 Jérôme Leclercq +// This file is part of the "Burgwar" project +// For conditions of distribution and use, see copyright notice in LICENSE + +#include +#include + +namespace bw +{ + inline BaseComponent::BaseComponent(entt::registry& registry, entt::entity entity) : + m_entity(entity), + m_registry(registry) + { + } + + inline BaseComponent::BaseComponent(const BaseComponent& component) : + m_entity(component.m_entity), + m_registry(component.m_registry) + { + } + + inline BaseComponent::BaseComponent(BaseComponent&& component) noexcept : + m_entity(component.m_entity), + m_registry(component.m_registry) + { + } + + inline entt::entity BaseComponent::GetEntity() const + { + return m_entity; + } + + inline entt::registry& BaseComponent::GetRegistry() + { + return m_registry; + } + + inline entt::registry& BaseComponent::GetRegistry() const + { + return m_registry; + } + + inline void BaseComponent::KillEntity() + { + m_registry.destroy(m_entity); + } +} diff --git a/include/CoreLib/Components/CollisionDataComponent.hpp b/include/CoreLib/Components/CollisionDataComponent.hpp index d245724a..4554cc96 100644 --- a/include/CoreLib/Components/CollisionDataComponent.hpp +++ b/include/CoreLib/Components/CollisionDataComponent.hpp @@ -10,29 +10,31 @@ #include #include #include -#include #include namespace bw { - class BURGWAR_CORELIB_API CollisionDataComponent : public Ndk::Component + class BURGWAR_CORELIB_API CollisionDataComponent { friend class ColliderSystem; public: CollisionDataComponent() = default; + CollisionDataComponent(const CollisionDataComponent&) = default; + CollisionDataComponent(CollisionDataComponent&&) = default; ~CollisionDataComponent() = default; inline void AddCollider(Collider collider); - Nz::Collider2DRef BuildCollider(float scale = 1.f) const; + std::shared_ptr BuildCollider(float scale = 1.f) const; inline const std::vector& GetColliders() const; - static Ndk::ComponentIndex componentIndex; + CollisionDataComponent& operator=(const CollisionDataComponent&) = default; + CollisionDataComponent& operator=(CollisionDataComponent&&) = default; private: - static Nz::Collider2DRef ToCollider(const Collider& collider, float scale); + static std::shared_ptr ToCollider(const Collider& collider, float scale); std::vector m_colliders; }; diff --git a/include/CoreLib/Components/ConstraintComponent2D.hpp b/include/CoreLib/Components/ConstraintComponent2D.hpp new file mode 100644 index 00000000..f3174b47 --- /dev/null +++ b/include/CoreLib/Components/ConstraintComponent2D.hpp @@ -0,0 +1,49 @@ +// Copyright (C) 2019 Jérôme Leclercq +// This file is part of the "Nazara Development Kit" +// For conditions of distribution and use, see copyright notice in Prerequisites.hpp + +#pragma once + +#ifndef BURGWAR_CORELIB_CONSTRAINTCOMPONENT2D_HPP +#define BURGWAR_CORELIB_CONSTRAINTCOMPONENT2D_HPP + +#include +#include +#include +#include +#include +#include +#include + +namespace bw +{ + class BURGWAR_CORELIB_API ConstraintComponent2D + { + public: + ConstraintComponent2D() = default; + ConstraintComponent2D(const ConstraintComponent2D&) = delete; + ConstraintComponent2D(ConstraintComponent2D&& joint) noexcept = default; + + template T* CreateConstraint(entt::registry& registry, entt::entity first, entt::entity second, Args&&... args); + bool RemoveConstraint(Nz::Constraint2D* constraint); + + ConstraintComponent2D& operator=(const ConstraintComponent2D& joint) = delete; + ConstraintComponent2D& operator=(ConstraintComponent2D&& joint) noexcept = default; + + + private: + struct ConstraintData + { + std::unique_ptr constraint; + + NazaraSlot(DestructionWatcherComponent, OnDestruction, onBodyADestruction); + NazaraSlot(DestructionWatcherComponent, OnDestruction, onBodyBDestruction); + }; + + std::vector m_constraints; + }; +} + +#include + +#endif // NDK_COMPONENTS_CONSTRAINTCOMPONENT2D_HPP diff --git a/include/CoreLib/Components/ConstraintComponent2D.inl b/include/CoreLib/Components/ConstraintComponent2D.inl new file mode 100644 index 00000000..365fdf87 --- /dev/null +++ b/include/CoreLib/Components/ConstraintComponent2D.inl @@ -0,0 +1,58 @@ +// Copyright (C) 2019 Jérôme Leclercq +// This file is part of the "Nazara Development Kit" +// For conditions of distribution and use, see copyright notice in Prerequisites.hpp + +#include +#include +#include + +namespace bw +{ + template + T* ConstraintComponent2D::CreateConstraint(entt::registry& registry, entt::entity first, entt::entity second, Args&& ...args) + { + auto FetchBody = [&](entt::entity entity) -> Nz::RigidBody2D* + { + if (Nz::RigidBody2DComponent* physBodyA = registry.try_get(entity)) + return physBodyA; + + return nullptr; + }; + + Nz::RigidBody2D* firstBody = FetchBody(first); + NazaraAssert(firstBody, "First entity has no CollisionComponent2D nor PhysicsComponent2D component"); + + Nz::RigidBody2D* secondBody = FetchBody(second); + NazaraAssert(secondBody, "Second entity has no CollisionComponent2D nor PhysicsComponent2D component"); + + auto& constraintData = m_constraints.emplace_back(); + constraintData.constraint = std::make_unique(*firstBody, *secondBody, std::forward(args)...); + + if (DestructionWatcherComponent* deathComponent = registry.try_get(first)) + { + constraintData.onBodyADestruction.Connect(deathComponent->OnDestruction, [this, constraint = constraintData.constraint.get()](DestructionWatcherComponent* /*emitter*/) + { + RemoveConstraint(constraint); + }); + } + + if (DestructionWatcherComponent* deathComponent = registry.try_get(second)) + { + constraintData.onBodyBDestruction.Connect(deathComponent->OnDestruction, [this, constraint = constraintData.constraint.get()](DestructionWatcherComponent* /*emitter*/) + { + RemoveConstraint(constraint); + }); + } + + return static_cast(constraintData.constraint.get()); + } + + inline bool ConstraintComponent2D::RemoveConstraint(Nz::Constraint2D* constraintPtr) + { + auto it = std::find_if(m_constraints.begin(), m_constraints.end(), [constraintPtr](const ConstraintData& constraintData) { return constraintData.constraint.get() == constraintPtr; }); + if (it != m_constraints.end()) + m_constraints.erase(it); + + return !m_constraints.empty(); + } +} diff --git a/include/CoreLib/Components/CooldownComponent.hpp b/include/CoreLib/Components/CooldownComponent.hpp index 769885f7..f722ffe8 100644 --- a/include/CoreLib/Components/CooldownComponent.hpp +++ b/include/CoreLib/Components/CooldownComponent.hpp @@ -8,11 +8,10 @@ #define BURGWAR_CORELIB_COMPONENTS_COOLDOWNCOMPONENT_HPP #include -#include namespace bw { - class BURGWAR_CORELIB_API CooldownComponent : public Ndk::Component + class BURGWAR_CORELIB_API CooldownComponent { public: inline CooldownComponent(Nz::UInt32 cooldown); @@ -23,8 +22,6 @@ namespace bw inline bool Trigger(Nz::UInt64 currentTime); - static Ndk::ComponentIndex componentIndex; - private: Nz::UInt32 m_cooldown; Nz::UInt64 m_nextTriggerTime; diff --git a/include/CoreLib/Components/DestructionWatcherComponent.hpp b/include/CoreLib/Components/DestructionWatcherComponent.hpp new file mode 100644 index 00000000..7482ac15 --- /dev/null +++ b/include/CoreLib/Components/DestructionWatcherComponent.hpp @@ -0,0 +1,30 @@ +// Copyright (C) 2020 Jérôme Leclercq +// This file is part of the "Burgwar" project +// For conditions of distribution and use, see copyright notice in LICENSE + +#pragma once + +#ifndef BURGWAR_CORELIB_COMPONENTS_DESTRUCTIONWATCHERCOMPONENT_HPP +#define BURGWAR_CORELIB_COMPONENTS_DESTRUCTIONWATCHERCOMPONENT_HPP + +#include +#include +#include +#include + +namespace bw +{ + class BURGWAR_CORELIB_API DestructionWatcherComponent : public BaseComponent + { + public: + using BaseComponent::BaseComponent; + DestructionWatcherComponent(const DestructionWatcherComponent&) = delete; + inline ~DestructionWatcherComponent(); + + NazaraSignal(OnDestruction, DestructionWatcherComponent* /*emitter*/); + }; +} + +#include + +#endif diff --git a/src/CoreLib/Components/HealthComponent.cpp b/include/CoreLib/Components/DestructionWatcherComponent.inl similarity index 53% rename from src/CoreLib/Components/HealthComponent.cpp rename to include/CoreLib/Components/DestructionWatcherComponent.inl index fd603cd2..58ff9aa7 100644 --- a/src/CoreLib/Components/HealthComponent.cpp +++ b/include/CoreLib/Components/DestructionWatcherComponent.inl @@ -2,9 +2,12 @@ // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE -#include +#include namespace bw { - Ndk::ComponentIndex HealthComponent::componentIndex; + inline DestructionWatcherComponent::~DestructionWatcherComponent() + { + OnDestruction(this); + } } diff --git a/include/CoreLib/Components/EntityOwnerComponent.hpp b/include/CoreLib/Components/EntityOwnerComponent.hpp index c9a4ded1..8c07f79d 100644 --- a/include/CoreLib/Components/EntityOwnerComponent.hpp +++ b/include/CoreLib/Components/EntityOwnerComponent.hpp @@ -8,24 +8,22 @@ #define BURGWAR_CORELIB_COMPONENTS_ENTITYOWNERCOMPONENT_HPP #include -#include -#include +#include +#include namespace bw { - class BURGWAR_CORELIB_API EntityOwnerComponent : public Ndk::Component + class BURGWAR_CORELIB_API EntityOwnerComponent : public BaseComponent { public: - EntityOwnerComponent() = default; - inline EntityOwnerComponent(const EntityOwnerComponent&); + using BaseComponent::BaseComponent; + EntityOwnerComponent(const EntityOwnerComponent&) = delete; ~EntityOwnerComponent() = default; - inline void Register(const Ndk::EntityHandle& entity); - - static Ndk::ComponentIndex componentIndex; + inline void Register(entt::entity entity); private: - std::vector m_ownedEntities; + std::vector m_ownedEntities; }; } diff --git a/include/CoreLib/Components/EntityOwnerComponent.inl b/include/CoreLib/Components/EntityOwnerComponent.inl index ef94aad7..7351fa55 100644 --- a/include/CoreLib/Components/EntityOwnerComponent.inl +++ b/include/CoreLib/Components/EntityOwnerComponent.inl @@ -6,25 +6,9 @@ namespace bw { - inline EntityOwnerComponent::EntityOwnerComponent(const EntityOwnerComponent&) + inline void EntityOwnerComponent::Register(entt::entity entity) { - } - - inline void EntityOwnerComponent::Register(const Ndk::EntityHandle& entity) - { - if (entity) - { - // Try to reuse expired handles before adding an entry - for (auto& ownerHandle : m_ownedEntities) - { - if (!ownerHandle) - { - ownerHandle = entity; - return; - } - } - - m_ownedEntities.emplace_back(entity); - } + // Try to reuse expired handles before adding an entry + m_ownedEntities.emplace_back(GetRegistry(), entity); } } diff --git a/include/CoreLib/Components/HealthComponent.hpp b/include/CoreLib/Components/HealthComponent.hpp index d7c25286..6e25e367 100644 --- a/include/CoreLib/Components/HealthComponent.hpp +++ b/include/CoreLib/Components/HealthComponent.hpp @@ -8,31 +8,29 @@ #define BURGWAR_CORELIB_COMPONENTS_HEALTHCOMPONENT_HPP #include +#include #include -#include namespace bw { - class BURGWAR_CORELIB_API HealthComponent : public Ndk::Component + class BURGWAR_CORELIB_API HealthComponent : public BaseComponent { public: - inline HealthComponent(Nz::UInt16 maxHealth); - inline HealthComponent(const HealthComponent&); + inline HealthComponent(entt::registry& registry, entt::entity entity, Nz::UInt16 maxHealth); + inline HealthComponent(const HealthComponent& health); - inline void Damage(Nz::UInt16 damage, const Ndk::EntityHandle& attacker); + inline void Damage(Nz::UInt16 damage, entt::entity attacker); inline Nz::UInt16 GetHealth() const; inline float GetHealthPct() const; inline Nz::UInt16 GetMaxHealth() const; - inline void Heal(Nz::UInt16 heal, const Ndk::EntityHandle& healer); + inline void Heal(Nz::UInt16 heal, entt::entity healer); - static Ndk::ComponentIndex componentIndex; - - NazaraSignal(OnDamage, HealthComponent* /*emitter*/, Nz::UInt16& /*damage*/, const Ndk::EntityHandle& /*attacker*/); - NazaraSignal(OnDying, HealthComponent* /*emitter*/, const Ndk::EntityHandle& /*attacker*/); - NazaraSignal(OnDied, const HealthComponent* /*emitter*/, const Ndk::EntityHandle& /*attacker*/); - NazaraSignal(OnHealthChange, HealthComponent* /*emitter*/, Nz::UInt16 /*newHealth*/, const Ndk::EntityHandle& /*source*/); + NazaraSignal(OnDamage, HealthComponent* /*emitter*/, Nz::UInt16& /*damage*/, entt::entity /*attacker*/); + NazaraSignal(OnDying, HealthComponent* /*emitter*/, entt::entity /*attacker*/); + NazaraSignal(OnDie, const HealthComponent* /*emitter*/, entt::entity /*attacker*/); + NazaraSignal(OnHealthChange, HealthComponent* /*emitter*/, Nz::UInt16 /*newHealth*/, entt::entity /*source*/); private: Nz::UInt16 m_currentHealth; diff --git a/include/CoreLib/Components/HealthComponent.inl b/include/CoreLib/Components/HealthComponent.inl index 8908dbee..9d5015c2 100644 --- a/include/CoreLib/Components/HealthComponent.inl +++ b/include/CoreLib/Components/HealthComponent.inl @@ -6,19 +6,21 @@ namespace bw { - inline HealthComponent::HealthComponent(Nz::UInt16 maxHealth) : + inline HealthComponent::HealthComponent(entt::registry& registry, entt::entity entity, Nz::UInt16 maxHealth) : + BaseComponent(registry, entity), m_currentHealth(maxHealth), m_maxHealth(maxHealth) { } inline HealthComponent::HealthComponent(const HealthComponent& health) : + BaseComponent(health), m_currentHealth(health.m_currentHealth), m_maxHealth(health.m_maxHealth) { } - inline void HealthComponent::Damage(Nz::UInt16 damage, const Ndk::EntityHandle& attacker) + inline void HealthComponent::Damage(Nz::UInt16 damage, entt::entity attacker) { OnDamage(this, damage, attacker); @@ -40,10 +42,7 @@ namespace bw // Recheck health in case a slot gave us health if (m_currentHealth == 0) - { - OnDied(this, attacker); - m_entity->Kill(); - } + OnDie(this, attacker); } } } @@ -63,7 +62,7 @@ namespace bw return m_maxHealth; } - inline void HealthComponent::Heal(Nz::UInt16 heal, const Ndk::EntityHandle& healer) + inline void HealthComponent::Heal(Nz::UInt16 heal, entt::entity healer) { Nz::UInt16 newHealth = m_currentHealth + heal; if (newHealth < m_currentHealth) diff --git a/include/CoreLib/Components/InputComponent.hpp b/include/CoreLib/Components/InputComponent.hpp index 592ce53e..6e2194c2 100644 --- a/include/CoreLib/Components/InputComponent.hpp +++ b/include/CoreLib/Components/InputComponent.hpp @@ -11,13 +11,12 @@ #include #include #include -#include #include #include namespace bw { - class BURGWAR_CORELIB_API InputComponent : public Ndk::Component + class BURGWAR_CORELIB_API InputComponent { public: inline InputComponent(std::shared_ptr inputController); @@ -30,8 +29,6 @@ namespace bw inline void UpdateInputs(const PlayerInputData& inputData); inline void UpdatePreviousInputs(const PlayerInputData& inputData); - static Ndk::ComponentIndex componentIndex; - NazaraSignal(OnInputUpdate, InputComponent* /*input*/); private: diff --git a/include/CoreLib/Components/MatchComponent.hpp b/include/CoreLib/Components/MatchComponent.hpp index 622d78aa..29731c0d 100644 --- a/include/CoreLib/Components/MatchComponent.hpp +++ b/include/CoreLib/Components/MatchComponent.hpp @@ -10,13 +10,12 @@ #include #include #include -#include namespace bw { class Match; - class BURGWAR_CORELIB_API MatchComponent : public Ndk::Component + class BURGWAR_CORELIB_API MatchComponent { public: inline MatchComponent(Match& match, LayerIndex layerIndex, EntityId uniqueId); @@ -26,8 +25,6 @@ namespace bw inline Match& GetMatch() const; inline EntityId GetUniqueId() const; - static Ndk::ComponentIndex componentIndex; - private: EntityId m_uniqueId; Match& m_match; diff --git a/include/CoreLib/Components/NetworkSyncComponent.hpp b/include/CoreLib/Components/NetworkSyncComponent.hpp index 920878c5..cc2b679e 100644 --- a/include/CoreLib/Components/NetworkSyncComponent.hpp +++ b/include/CoreLib/Components/NetworkSyncComponent.hpp @@ -9,30 +9,28 @@ #include #include -#include +#include #include namespace bw { - class BURGWAR_CORELIB_API NetworkSyncComponent : public Ndk::Component + class BURGWAR_CORELIB_API NetworkSyncComponent { public: - inline NetworkSyncComponent(std::string entityClass, const Ndk::EntityHandle& parent = Ndk::EntityHandle::InvalidHandle); + inline NetworkSyncComponent(std::string entityClass, entt::entity parent = entt::null); ~NetworkSyncComponent() = default; inline const std::string& GetEntityClass() const; - inline const Ndk::EntityHandle& GetParent() const; + inline entt::entity GetParent() const; inline void Invalidate(); - inline void UpdateParent(const Ndk::EntityHandle& parent); - - static Ndk::ComponentIndex componentIndex; + inline void UpdateParent(entt::entity parent); NazaraSignal(OnInvalidated, NetworkSyncComponent* /*emitter*/); private: - Ndk::EntityHandle m_parent; + entt::entity m_parent; std::string m_entityClass; }; } diff --git a/include/CoreLib/Components/NetworkSyncComponent.inl b/include/CoreLib/Components/NetworkSyncComponent.inl index 5633b954..9413621b 100644 --- a/include/CoreLib/Components/NetworkSyncComponent.inl +++ b/include/CoreLib/Components/NetworkSyncComponent.inl @@ -6,7 +6,7 @@ namespace bw { - inline NetworkSyncComponent::NetworkSyncComponent(std::string entityClass, const Ndk::EntityHandle& parent) : + inline NetworkSyncComponent::NetworkSyncComponent(std::string entityClass, entt::entity parent) : m_parent(parent), m_entityClass(entityClass) { @@ -17,7 +17,7 @@ namespace bw return m_entityClass; } - inline const Ndk::EntityHandle& NetworkSyncComponent::GetParent() const + inline entt::entity NetworkSyncComponent::GetParent() const { return m_parent; } @@ -27,7 +27,7 @@ namespace bw OnInvalidated(this); } - inline void NetworkSyncComponent::UpdateParent(const Ndk::EntityHandle& parent) + inline void NetworkSyncComponent::UpdateParent(entt::entity parent) { m_parent = parent; //TODO: network event diff --git a/include/CoreLib/Components/OwnerComponent.hpp b/include/CoreLib/Components/OwnerComponent.hpp index cebc5f27..113943ea 100644 --- a/include/CoreLib/Components/OwnerComponent.hpp +++ b/include/CoreLib/Components/OwnerComponent.hpp @@ -9,12 +9,11 @@ #include #include -#include #include namespace bw { - class BURGWAR_CORELIB_API OwnerComponent : public Ndk::Component + class BURGWAR_CORELIB_API OwnerComponent { public: OwnerComponent(PlayerHandle owner); @@ -22,8 +21,6 @@ namespace bw inline Player* GetOwner() const; - static Ndk::ComponentIndex componentIndex; - private: PlayerHandle m_owner; }; diff --git a/include/CoreLib/Components/PlayerControlledComponent.hpp b/include/CoreLib/Components/PlayerControlledComponent.hpp index f8117b5f..7ed27dc8 100644 --- a/include/CoreLib/Components/PlayerControlledComponent.hpp +++ b/include/CoreLib/Components/PlayerControlledComponent.hpp @@ -9,12 +9,11 @@ #include #include -#include #include namespace bw { - class BURGWAR_CORELIB_API PlayerControlledComponent : public Ndk::Component + class BURGWAR_CORELIB_API PlayerControlledComponent { public: PlayerControlledComponent(PlayerHandle owner); @@ -22,8 +21,6 @@ namespace bw inline Player* GetOwner() const; - static Ndk::ComponentIndex componentIndex; - private: PlayerHandle m_owner; }; diff --git a/include/CoreLib/Components/PlayerMovementComponent.hpp b/include/CoreLib/Components/PlayerMovementComponent.hpp index a5e03469..17b2e1fa 100644 --- a/include/CoreLib/Components/PlayerMovementComponent.hpp +++ b/include/CoreLib/Components/PlayerMovementComponent.hpp @@ -9,7 +9,6 @@ #include #include -#include #include #include @@ -17,7 +16,7 @@ namespace bw { class PlayerMovementController; - class BURGWAR_CORELIB_API PlayerMovementComponent : public Ndk::Component + class BURGWAR_CORELIB_API PlayerMovementComponent { public: PlayerMovementComponent(); @@ -47,8 +46,6 @@ namespace bw inline bool WasJumping() const; - static Ndk::ComponentIndex componentIndex; - private: std::shared_ptr m_controller; Nz::Vector2f m_targetVelocity; diff --git a/include/CoreLib/Components/ScriptComponent.hpp b/include/CoreLib/Components/ScriptComponent.hpp index d1ffced7..e11a9e1f 100644 --- a/include/CoreLib/Components/ScriptComponent.hpp +++ b/include/CoreLib/Components/ScriptComponent.hpp @@ -13,7 +13,6 @@ #include #include #include -#include #include #include #include @@ -22,12 +21,14 @@ namespace bw { - class BURGWAR_CORELIB_API ScriptComponent : public Ndk::Component + class BURGWAR_CORELIB_API ScriptComponent { friend class TickCallbackSystem; public: ScriptComponent(const Logger& logger, std::shared_ptr element, std::shared_ptr context, sol::table entityTable, PropertyValueMap properties); + ScriptComponent(const ScriptComponent&) = delete; + ScriptComponent(ScriptComponent&&) noexcept = default; ~ScriptComponent(); template @@ -57,21 +58,23 @@ namespace bw inline bool UnregisterCallbackCustom(std::size_t eventIndex, std::size_t callbackId); inline void UpdateElement(std::shared_ptr element); - void UpdateEntity(const Ndk::EntityHandle& entity); + void UpdateEntity(entt::entity entity); - static Ndk::ComponentIndex componentIndex; + ScriptComponent& operator=(const ScriptComponent&) = delete; + ScriptComponent& operator=(ScriptComponent&&) noexcept = default; + + static constexpr auto in_place_delete = true; private: inline bool CanTriggerTick(float elapsedTime); - void OnAttached() override; std::array, ElementEventCount> m_eventCallbacks; std::vector> m_customEventCallbacks; std::shared_ptr m_element; std::shared_ptr m_context; + std::unique_ptr m_logger; std::size_t m_nextCallbackId; sol::table m_entityTable; - EntityLogger m_logger; PropertyValueMap m_properties; float m_timeBeforeTick; }; diff --git a/include/CoreLib/Components/ScriptComponent.inl b/include/CoreLib/Components/ScriptComponent.inl index 0915244b..389957e2 100644 --- a/include/CoreLib/Components/ScriptComponent.inl +++ b/include/CoreLib/Components/ScriptComponent.inl @@ -173,7 +173,8 @@ namespace bw inline const EntityLogger& ScriptComponent::GetLogger() const { - return m_logger; + assert(m_logger); + return *m_logger; } inline std::optional> ScriptComponent::GetProperty(const std::string& keyName) const diff --git a/include/CoreLib/Components/WeaponComponent.hpp b/include/CoreLib/Components/WeaponComponent.hpp index 0a652a6a..62f65b96 100644 --- a/include/CoreLib/Components/WeaponComponent.hpp +++ b/include/CoreLib/Components/WeaponComponent.hpp @@ -8,7 +8,6 @@ #define BURGWAR_CORELIB_COMPONENTS_WEAPONCOMPONENT_HPP #include -#include namespace bw { @@ -20,14 +19,14 @@ namespace bw Max = SingleShotRepeat }; - class BURGWAR_CORELIB_API WeaponComponent : public Ndk::Component + class BURGWAR_CORELIB_API WeaponComponent { public: - inline WeaponComponent(Ndk::EntityHandle owner, WeaponAttackMode attackMode); + inline WeaponComponent(entt::entity owner, WeaponAttackMode attackMode); ~WeaponComponent() = default; inline WeaponAttackMode GetAttackMode() const; - inline const Ndk::EntityHandle& GetOwner() const; + inline entt::entity GetOwner() const; inline bool IsActive() const; inline bool IsAttacking() const; @@ -35,12 +34,10 @@ namespace bw inline void SetActive(bool isActive); inline void SetAttacking(bool isAttacking); - inline void UpdateOwner(Ndk::EntityHandle owner); - - static Ndk::ComponentIndex componentIndex; + inline void UpdateOwner(entt::entity owner); private: - Ndk::EntityHandle m_owner; + entt::entity m_owner; WeaponAttackMode m_attackMode; bool m_isActive; bool m_isAttacking; diff --git a/include/CoreLib/Components/WeaponComponent.inl b/include/CoreLib/Components/WeaponComponent.inl index 445f7cbb..861a315d 100644 --- a/include/CoreLib/Components/WeaponComponent.inl +++ b/include/CoreLib/Components/WeaponComponent.inl @@ -6,8 +6,8 @@ namespace bw { - inline WeaponComponent::WeaponComponent(Ndk::EntityHandle owner, WeaponAttackMode attackMode) : - m_owner(std::move(owner)), + inline WeaponComponent::WeaponComponent(entt::entity owner, WeaponAttackMode attackMode) : + m_owner(owner), m_attackMode(attackMode), m_isActive(false), m_isAttacking(false) @@ -19,7 +19,7 @@ namespace bw return m_attackMode; } - inline const Ndk::EntityHandle& WeaponComponent::GetOwner() const + inline entt::entity WeaponComponent::GetOwner() const { return m_owner; } @@ -46,8 +46,8 @@ namespace bw m_isAttacking = isAttacking; } - inline void WeaponComponent::UpdateOwner(Ndk::EntityHandle owner) + inline void WeaponComponent::UpdateOwner(entt::entity owner) { - m_owner = std::move(owner); + m_owner = owner; } } diff --git a/include/CoreLib/Components/WeaponWielderComponent.hpp b/include/CoreLib/Components/WeaponWielderComponent.hpp index 824dd20c..7556b192 100644 --- a/include/CoreLib/Components/WeaponWielderComponent.hpp +++ b/include/CoreLib/Components/WeaponWielderComponent.hpp @@ -8,28 +8,31 @@ #define BURGWAR_CORELIB_COMPONENTS_WEAPONWIELDERCOMPONENT_HPP #include +#include +#include +#include #include -#include -#include +#include #include +#include #include #include - + namespace bw { - class BURGWAR_CORELIB_API WeaponWielderComponent : public Ndk::Component + class BURGWAR_CORELIB_API WeaponWielderComponent : public BaseComponent { public: - using WeaponInitCallback = std::function; + using WeaponInitCallback = tl::function_ref; - inline WeaponWielderComponent(); + inline WeaponWielderComponent(entt::registry& registry, entt::entity entity); inline WeaponWielderComponent(const WeaponWielderComponent& weaponWielder); ~WeaponWielderComponent() = default; - inline const Ndk::EntityHandle& GetActiveWeapon() const; + inline entt::entity GetActiveWeapon() const; inline std::size_t GetSelectedWeapon() const; - inline const Ndk::EntityHandle& GetWeapon(std::size_t weaponIndex) const; - inline const std::vector& GetWeapons() const; + inline entt::entity GetWeapon(std::size_t weaponIndex) const; + inline const std::vector& GetWeapons() const; inline std::size_t GetWeaponCount() const; inline const Nz::Vector2f& GetWeaponOffset() const; @@ -38,7 +41,7 @@ namespace bw inline bool HasActiveWeapon() const; inline bool HasWeapon(const std::string& weaponClass) const; - void OverrideEntities(const std::function& callback); + void OverrideEntities(const std::function& callback); void RemoveWeapon(const std::string& weaponClass); @@ -46,8 +49,6 @@ namespace bw inline bool SelectWeapon(const std::string& weaponClass); inline void SetWeaponOffset(const Nz::Vector2f& weaponOffset); - static Ndk::ComponentIndex componentIndex; - static constexpr std::size_t NoWeapon = std::numeric_limits::max(); NazaraSignal(OnNewWeaponSelection, WeaponWielderComponent* /*wielder*/, std::size_t /*newWeaponIndex*/); @@ -55,10 +56,10 @@ namespace bw NazaraSignal(OnWeaponRemove, WeaponWielderComponent* /*wielder*/, const std::string& /*weaponClass*/, std::size_t /*weaponIndex*/); private: - Nz::Vector2f m_weaponOffset; std::size_t m_activeWeaponIndex; - std::vector m_weapons; + std::vector m_weapons; tsl::hopscotch_map m_weaponByName; + Nz::Vector2f m_weaponOffset; }; } diff --git a/include/CoreLib/Components/WeaponWielderComponent.inl b/include/CoreLib/Components/WeaponWielderComponent.inl index ac6aa142..c4f79275 100644 --- a/include/CoreLib/Components/WeaponWielderComponent.inl +++ b/include/CoreLib/Components/WeaponWielderComponent.inl @@ -6,25 +6,27 @@ namespace bw { - inline WeaponWielderComponent::WeaponWielderComponent() : - m_weaponOffset(Nz::Vector2f::Zero()), - m_activeWeaponIndex(NoWeapon) + inline WeaponWielderComponent::WeaponWielderComponent(entt::registry& registry, entt::entity entity) : + BaseComponent(registry, entity), + m_activeWeaponIndex(NoWeapon), + m_weaponOffset(Nz::Vector2f::Zero()) { } inline WeaponWielderComponent::WeaponWielderComponent(const WeaponWielderComponent& weaponWielder) : - m_weaponOffset(weaponWielder.m_weaponOffset), + BaseComponent(weaponWielder), m_activeWeaponIndex(weaponWielder.m_activeWeaponIndex), - m_weaponByName(weaponWielder.m_weaponByName) + m_weaponByName(weaponWielder.m_weaponByName), + m_weaponOffset(weaponWielder.m_weaponOffset) { //FIXME: - for (const Ndk::EntityHandle& entity : weaponWielder.m_weapons) + for (entt::entity entity : weaponWielder.m_weapons) m_weapons.emplace_back(entity); } - inline const Ndk::EntityHandle& WeaponWielderComponent::GetActiveWeapon() const + inline entt::entity WeaponWielderComponent::GetActiveWeapon() const { - return (m_activeWeaponIndex != NoWeapon) ? m_weapons[m_activeWeaponIndex] : Ndk::EntityHandle::InvalidHandle; + return (m_activeWeaponIndex != NoWeapon) ? m_weapons[m_activeWeaponIndex].GetEntity() : entt::null; } inline std::size_t WeaponWielderComponent::GetSelectedWeapon() const @@ -32,13 +34,13 @@ namespace bw return m_activeWeaponIndex; } - inline const Ndk::EntityHandle& WeaponWielderComponent::GetWeapon(std::size_t weaponIndex) const + inline entt::entity WeaponWielderComponent::GetWeapon(std::size_t weaponIndex) const { assert(weaponIndex < m_weapons.size()); return m_weapons[weaponIndex]; } - inline const std::vector& WeaponWielderComponent::GetWeapons() const + inline const std::vector& WeaponWielderComponent::GetWeapons() const { return m_weapons; } diff --git a/include/CoreLib/CustomInputController.hpp b/include/CoreLib/CustomInputController.hpp index 638373e1..999927d2 100644 --- a/include/CoreLib/CustomInputController.hpp +++ b/include/CoreLib/CustomInputController.hpp @@ -18,7 +18,7 @@ namespace bw inline CustomInputController(sol::main_protected_function callback); ~CustomInputController() = default; - std::optional GenerateInputs(const Ndk::EntityHandle& entity) const override; + std::optional GenerateInputs(entt::registry& registry, entt::entity entity) const override; private: sol::main_protected_function m_callback; diff --git a/include/CoreLib/EntityOwner.hpp b/include/CoreLib/EntityOwner.hpp new file mode 100644 index 00000000..40d80faf --- /dev/null +++ b/include/CoreLib/EntityOwner.hpp @@ -0,0 +1,37 @@ +// Copyright (C) 2020 Jérôme Leclercq +// This file is part of the "Burgwar" project +// For conditions of distribution and use, see copyright notice in LICENSE + +#pragma once + +#ifndef BURGWAR_CORELIB_ENTITYOWNER_HPP +#define BURGWAR_CORELIB_ENTITYOWNER_HPP + +#include + +namespace bw +{ + class EntityOwner + { + public: + inline EntityOwner(entt::registry& registry, entt::entity entity); + EntityOwner(const EntityOwner&) = delete; + inline EntityOwner(EntityOwner&& entityOwner) noexcept; + inline ~EntityOwner(); + + inline entt::entity GetEntity() const; + + operator entt::entity() const; + + EntityOwner& operator=(const EntityOwner&) = delete; + EntityOwner& operator=(EntityOwner&&) = delete; + + private: + entt::entity m_entity; + entt::registry& m_registry; + }; +} + +#include + +#endif diff --git a/include/CoreLib/EntityOwner.inl b/include/CoreLib/EntityOwner.inl new file mode 100644 index 00000000..65ca10e5 --- /dev/null +++ b/include/CoreLib/EntityOwner.inl @@ -0,0 +1,35 @@ +// Copyright (C) 2016 Jérôme Leclercq +// This file is part of the "Burgwar" project +// For conditions of distribution and use, see copyright notice in Prerequisites.hpp + +#include + +namespace bw +{ + inline EntityOwner::EntityOwner(entt::registry& registry, entt::entity entity) : + m_entity(entity), + m_registry(registry) + { + } + + inline EntityOwner::EntityOwner(EntityOwner&& entityOwner) noexcept : + m_entity(entityOwner.m_entity), + m_registry(entityOwner.m_registry) + { + } + + inline EntityOwner::~EntityOwner() + { + m_registry.destroy(m_entity); + } + + inline entt::entity EntityOwner::GetEntity() const + { + return m_entity; + } + + inline EntityOwner::operator entt::entity() const + { + return m_entity; + } +} diff --git a/include/CoreLib/InputController.hpp b/include/CoreLib/InputController.hpp index 99b9ad30..5867e236 100644 --- a/include/CoreLib/InputController.hpp +++ b/include/CoreLib/InputController.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include namespace bw @@ -20,7 +20,7 @@ namespace bw InputController() = default; virtual ~InputController(); - virtual std::optional GenerateInputs(const Ndk::EntityHandle& entity) const = 0; + virtual std::optional GenerateInputs(entt::registry& registry, entt::entity entity) const = 0; }; } diff --git a/include/CoreLib/LogSystem/EntityLogContext.hpp b/include/CoreLib/LogSystem/EntityLogContext.hpp index a77ec8a5..d11e5fb8 100644 --- a/include/CoreLib/LogSystem/EntityLogContext.hpp +++ b/include/CoreLib/LogSystem/EntityLogContext.hpp @@ -9,13 +9,13 @@ #include #include -#include +#include namespace bw { struct EntityLogContext : MatchLogContext { - Ndk::EntityHandle entity; + entt::entity entity; }; } diff --git a/include/CoreLib/LogSystem/EntityLogger.hpp b/include/CoreLib/LogSystem/EntityLogger.hpp index 78fc27a6..c6dd2f60 100644 --- a/include/CoreLib/LogSystem/EntityLogger.hpp +++ b/include/CoreLib/LogSystem/EntityLogger.hpp @@ -10,25 +10,26 @@ #include #include #include +#include namespace bw { class BURGWAR_CORELIB_API EntityLogger : public LoggerProxy { public: - inline EntityLogger(Ndk::EntityHandle entity, const Logger& logParent); + inline EntityLogger(entt::entity entity, const Logger& logParent); EntityLogger(const EntityLogger&) = default; EntityLogger(EntityLogger&&) = default; ~EntityLogger() = default; void InitializeContext(LogContext& context) const override; - inline void UpdateEntity(Ndk::EntityHandle newEntity); + inline void UpdateEntity(entt::entity newEntity); private: void OverrideContent(const LogContext& context, std::string& content) const override; - Ndk::EntityHandle m_entity; + entt::entity m_entity; }; } diff --git a/include/CoreLib/LogSystem/EntityLogger.inl b/include/CoreLib/LogSystem/EntityLogger.inl index f6631eb3..a7e8a4ad 100644 --- a/include/CoreLib/LogSystem/EntityLogger.inl +++ b/include/CoreLib/LogSystem/EntityLogger.inl @@ -6,13 +6,13 @@ namespace bw { - inline EntityLogger::EntityLogger(Ndk::EntityHandle entity, const Logger& logParent) : + inline EntityLogger::EntityLogger(entt::entity entity, const Logger& logParent) : LoggerProxy(logParent), m_entity(std::move(entity)) { } - inline void EntityLogger::UpdateEntity(Ndk::EntityHandle newEntity) + inline void EntityLogger::UpdateEntity(entt::entity newEntity) { m_entity = newEntity; } diff --git a/include/CoreLib/LogSystem/Logger.hpp b/include/CoreLib/LogSystem/Logger.hpp index 4dc4389c..53529bb9 100644 --- a/include/CoreLib/LogSystem/Logger.hpp +++ b/include/CoreLib/LogSystem/Logger.hpp @@ -38,8 +38,8 @@ namespace bw friend class LoggerProxy; public: - inline Logger(BurgApp& app, LogSide logSide, std::size_t contextSize = sizeof(bw::LogContext)); - inline Logger(BurgApp& app, LogSide logSide, const AbstractLogger& logParent, std::size_t contextSize = sizeof(bw::LogContext)); + inline Logger(BurgApp& app, LogSide logSide); + inline Logger(BurgApp& app, LogSide logSide, const AbstractLogger& logParent); Logger(const Logger&) = delete; Logger(Logger&&) noexcept = default; ~Logger() = default; @@ -61,17 +61,16 @@ namespace bw Logger& operator=(Logger&&) = delete; protected: - template T* AllocateContext(Nz::MemoryPool& pool) const; + template T* AllocateContext() const; template LogContextPtr PushCustomContext() const; virtual void InitializeContext(LogContext& context) const; - virtual LogContext* NewContext(Nz::MemoryPool& pool) const; + virtual LogContext* NewContext() const; virtual void OverrideContent(const LogContext& context, std::string& content) const; private: void FreeContext(LogContext* context) const; - mutable Nz::MemoryPool m_contextPool; BurgApp& m_app; LogLevel m_minimumLogLevel; Nz::MovablePtr m_logParent; diff --git a/include/CoreLib/LogSystem/Logger.inl b/include/CoreLib/LogSystem/Logger.inl index 8b3947f8..c271b3b3 100644 --- a/include/CoreLib/LogSystem/Logger.inl +++ b/include/CoreLib/LogSystem/Logger.inl @@ -7,17 +7,16 @@ namespace bw { - inline Logger::Logger(BurgApp& app, LogSide logSide, std::size_t contextSize) : + inline Logger::Logger(BurgApp& app, LogSide logSide) : AbstractLogger(logSide), - m_contextPool(static_cast(contextSize), 4), m_app(app), m_minimumLogLevel(LogLevel::Debug), m_logParent(nullptr) { } - inline Logger::Logger(BurgApp& app, LogSide logSide, const AbstractLogger& logParent, std::size_t contextSize) : - Logger(app, logSide, contextSize) + inline Logger::Logger(BurgApp& app, LogSide logSide, const AbstractLogger& logParent) : + Logger(app, logSide) { m_logParent = &logParent; } @@ -29,11 +28,11 @@ namespace bw } template - T* Logger::AllocateContext(Nz::MemoryPool& pool) const + T* Logger::AllocateContext() const { static_assert(std::is_base_of_v); - T* logContext = pool.New(); + T* logContext = new T; InitializeContext(*logContext); return logContext; @@ -42,12 +41,12 @@ namespace bw template LogContextPtr Logger::PushCustomContext() const { - return LogContextPtr(this, AllocateContext(m_contextPool)); + return LogContextPtr(this, AllocateContext()); } inline LogContextPtr Logger::PushContext() const { - return LogContextPtr(this, NewContext(m_contextPool)); + return LogContextPtr(this, NewContext()); } inline void Logger::RegisterSink(std::shared_ptr sinkPtr) diff --git a/include/CoreLib/LogSystem/MatchLogger.hpp b/include/CoreLib/LogSystem/MatchLogger.hpp index 0e28e4a7..b8bd1111 100644 --- a/include/CoreLib/LogSystem/MatchLogger.hpp +++ b/include/CoreLib/LogSystem/MatchLogger.hpp @@ -16,8 +16,8 @@ namespace bw class BURGWAR_CORELIB_API MatchLogger : public Logger { public: - inline MatchLogger(BurgApp& app, SharedMatch& sharedMatch, LogSide logSide, std::size_t contextSize = sizeof(bw::MatchLogContext)); - inline MatchLogger(BurgApp& app, SharedMatch& sharedMatch, LogSide logSide, const AbstractLogger& logParent, std::size_t contextSize = sizeof(bw::MatchLogContext)); + inline MatchLogger(BurgApp& app, SharedMatch& sharedMatch, LogSide logSide); + inline MatchLogger(BurgApp& app, SharedMatch& sharedMatch, LogSide logSide, const AbstractLogger& logParent); MatchLogger(const MatchLogger&) = delete; MatchLogger(MatchLogger&&) noexcept = default; ~MatchLogger() = default; @@ -26,7 +26,7 @@ namespace bw private: void InitializeContext(LogContext& context) const override; - LogContext* NewContext(Nz::MemoryPool& pool) const override; + LogContext* NewContext() const override; void OverrideContent(const LogContext& context, std::string& content) const override; SharedMatch& m_sharedMatch; diff --git a/include/CoreLib/LogSystem/MatchLogger.inl b/include/CoreLib/LogSystem/MatchLogger.inl index 242a1a6f..6f84f16e 100644 --- a/include/CoreLib/LogSystem/MatchLogger.inl +++ b/include/CoreLib/LogSystem/MatchLogger.inl @@ -6,14 +6,14 @@ namespace bw { - inline MatchLogger::MatchLogger(BurgApp& app, SharedMatch& sharedMatch, LogSide logSide, std::size_t contextSize) : - Logger(app, logSide, contextSize), + inline MatchLogger::MatchLogger(BurgApp& app, SharedMatch& sharedMatch, LogSide logSide) : + Logger(app, logSide), m_sharedMatch(sharedMatch) { } - inline MatchLogger::MatchLogger(BurgApp& app, SharedMatch& sharedMatch, LogSide logSide, const AbstractLogger& logParent, std::size_t contextSize) : - Logger(app, logSide, logParent, contextSize), + inline MatchLogger::MatchLogger(BurgApp& app, SharedMatch& sharedMatch, LogSide logSide, const AbstractLogger& logParent) : + Logger(app, logSide, logParent), m_sharedMatch(sharedMatch) { } diff --git a/include/CoreLib/Match.hpp b/include/CoreLib/Match.hpp index 4c54032d..e7460e87 100644 --- a/include/CoreLib/Match.hpp +++ b/include/CoreLib/Match.hpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -73,11 +74,11 @@ namespace bw Player* CreatePlayer(MatchClientSession& session, Nz::UInt8 localIndex, std::string name); - void ForEachEntity(std::function func) override; + void ForEachEntity(tl::function_ref func) override; template void ForEachPlayer(F&& func, bool onlyReady = true); inline BurgApp& GetApp(); - inline const std::shared_ptr& GetAssetDirectory() const; + inline const std::shared_ptr& GetAssetDirectory() const; inline AssetStore& GetAssetStore(); bool GetClientAsset(const std::string& filePath, const ClientAsset** clientScriptData); bool GetClientScript(const std::string& filePath, const ClientScript** clientScriptData); @@ -93,7 +94,7 @@ namespace bw inline const ModSettings& GetModSettings() const; const NetworkStringStore& GetNetworkStringStore() const override; inline Player* GetPlayerByIndex(Nz::UInt16 playerIndex); - inline const std::shared_ptr& GetScriptDirectory() const; + inline const std::shared_ptr& GetScriptDirectory() const; inline const std::shared_ptr& GetScriptingLibrary() const; inline MatchSessions& GetSessions(); inline const MatchSessions& GetSessions() const; @@ -108,7 +109,7 @@ namespace bw void RegisterClientAsset(std::string assetPath); void RegisterClientScript(std::string scriptPath); - void RegisterEntity(EntityId uniqueId, Ndk::EntityHandle entity); + void RegisterEntity(EntityId uniqueId, entt::entity entity); void RegisterNetworkString(std::string string); void ReloadAssets(); @@ -118,8 +119,8 @@ namespace bw void RemovePlayer(Player* player, DisconnectionReason disconnection); void ResetTerrain(); - const Ndk::EntityHandle& RetrieveEntityByUniqueId(EntityId uniqueId) const override; - EntityId RetrieveUniqueIdByEntity(const Ndk::EntityHandle& entity) const override; + entt::entity RetrieveEntityByUniqueId(EntityId uniqueId) const override; + EntityId RetrieveUniqueIdByEntity(entt::entity entity) const override; bool Update(float elapsedTime); @@ -186,9 +187,9 @@ namespace bw struct Entity { - Ndk::EntityHandle entity; + entt::entity entity; - NazaraSlot(Ndk::Entity, OnEntityDestruction, onDestruction); + NazaraSlot(DestructionWatcherComponent, OnDestruction, onDestruction); }; std::shared_ptr m_scriptingContext; //< Must be over script based classes @@ -199,8 +200,8 @@ namespace bw std::size_t m_maxPlayerCount; std::shared_ptr m_gamemode; std::shared_ptr m_scriptingLibrary; - std::shared_ptr m_assetDirectory; - std::shared_ptr m_scriptDirectory; + std::shared_ptr m_assetDirectory; + std::shared_ptr m_scriptDirectory; std::string m_name; std::unique_ptr m_terrain; std::vector> m_enabledMods; diff --git a/include/CoreLib/Match.inl b/include/CoreLib/Match.inl index 58c4ed24..35e120af 100644 --- a/include/CoreLib/Match.inl +++ b/include/CoreLib/Match.inl @@ -42,7 +42,7 @@ namespace bw return m_app; } - inline const std::shared_ptr& Match::GetAssetDirectory() const + inline const std::shared_ptr& Match::GetAssetDirectory() const { return m_assetDirectory; } @@ -105,7 +105,7 @@ namespace bw return m_settings; } - inline const std::shared_ptr& Match::GetScriptDirectory() const + inline const std::shared_ptr& Match::GetScriptDirectory() const { return m_scriptDirectory; } diff --git a/include/CoreLib/MatchClientVisibility.hpp b/include/CoreLib/MatchClientVisibility.hpp index b79980d6..bfd95be9 100644 --- a/include/CoreLib/MatchClientVisibility.hpp +++ b/include/CoreLib/MatchClientVisibility.hpp @@ -17,7 +17,6 @@ #include #include #include -#include #include #include #include @@ -99,7 +98,7 @@ namespace bw void BuildMovementPacket(Packets::MatchState::Entity& packetData, const NetworkSyncSystem::EntityMovement& eventData); void FillEntityData(const NetworkSyncSystem::EntityCreation& creationEvent, Packets::Helper::EntityData& entityData); void HandleEntityCreation(LayerIndex layerIndex, const NetworkSyncSystem::EntityCreation& eventData); - void HandleEntityRemove(LayerIndex layerIndex, Ndk::EntityId entityId, bool deathEvent); + void HandleEntityRemove(LayerIndex layerIndex, entt::entity entityId, bool deathEvent); template void PushLayerEntities(std::vector& packetEntities, LayerIndex layerIndex, PendingCreationEventMap& pendingCreationMap); void SendMatchState(); diff --git a/include/CoreLib/MatchSessions.hpp b/include/CoreLib/MatchSessions.hpp index e920e1a5..7de224e4 100644 --- a/include/CoreLib/MatchSessions.hpp +++ b/include/CoreLib/MatchSessions.hpp @@ -8,6 +8,7 @@ #define BURGWAR_SERVER_SESSIONMANAGER_HPP #include +#include #include #include #include @@ -20,13 +21,12 @@ namespace bw { class Logger; class Match; - class MatchClientSession; class BURGWAR_CORELIB_API MatchSessions { public: MatchSessions(Match& match); - ~MatchSessions(); + ~MatchSessions() = default; void Clear(); @@ -45,7 +45,7 @@ namespace bw std::vector> m_managers; Match& m_match; PlayerCommandStore m_commandStore; - Nz::MemoryPool m_sessionPool; + Nz::MemoryPool m_sessionPool; tsl::hopscotch_map m_sessionIdToSession; }; } diff --git a/include/CoreLib/NetworkReactor.hpp b/include/CoreLib/NetworkReactor.hpp index a7e19fc5..19c9aa02 100644 --- a/include/CoreLib/NetworkReactor.hpp +++ b/include/CoreLib/NetworkReactor.hpp @@ -8,11 +8,11 @@ #define BURGWAR_CORELIB_NETWORK_REACTOR_HPP #include -#include #include #include #include #include +#include #include #include @@ -134,13 +134,13 @@ namespace bw std::atomic_bool m_running; std::size_t m_firstId; + std::thread m_thread; std::vector m_clients; moodycamel::ConcurrentQueue m_connectionRequests; moodycamel::ConcurrentQueue m_incomingQueue; moodycamel::ConcurrentQueue m_outgoingQueue; Nz::ENetHost m_host; Nz::NetProtocol m_protocol; - Nz::Thread m_thread; }; } diff --git a/include/CoreLib/Player.hpp b/include/CoreLib/Player.hpp index c52270bc..e048363e 100644 --- a/include/CoreLib/Player.hpp +++ b/include/CoreLib/Player.hpp @@ -7,6 +7,7 @@ #ifndef BURGWAR_CLIENTLIB_PLAYER_HPP #define BURGWAR_CLIENTLIB_PLAYER_HPP +#include #include #include #include @@ -15,7 +16,6 @@ #include #include #include -#include #include #include #include @@ -39,7 +39,7 @@ namespace bw Player(Player&&) noexcept = default; ~Player(); - inline const Ndk::EntityHandle& GetControlledEntity() const; + inline entt::entity GetControlledEntity() const; inline const PlayerInputData& GetInputs() const; inline LayerIndex GetLayerIndex() const; inline Nz::UInt8 GetLocalIndex() const; @@ -65,7 +65,7 @@ namespace bw std::string ToString() const; - void UpdateControlledEntity(const Ndk::EntityHandle& entity, bool sendPacket = true, bool ignoreLayerUpdate = false); + void UpdateControlledEntity(entt::entity entity, bool sendPacket = true, bool ignoreLayerUpdate = false); void UpdateLayerVisibility(LayerIndex layerIndex, bool isVisible); inline void UpdateInputs(const PlayerInputData& inputData); void UpdateName(std::string newName); @@ -77,19 +77,19 @@ namespace bw static constexpr std::size_t NoWeapon = WeaponWielderComponent::NoWeapon; private: - void OnDeath(const Ndk::EntityHandle& attacker); + void OnDeath(entt::entity attacker); void SetReady(); - NazaraSlot(Ndk::Entity, OnEntityDestruction, m_onPlayerEntityDestruction); - NazaraSlot(HealthComponent, OnDied, m_onPlayerEntityDied); + //NazaraSlot(Ndk::Entity, OnEntityDestruction, m_onPlayerEntityDestruction); + NazaraSlot(HealthComponent, OnDie, m_onPlayerEntityDie); NazaraSlot(WeaponWielderComponent, OnWeaponAdded, m_onWeaponAdded); NazaraSlot(WeaponWielderComponent, OnWeaponRemove, m_onWeaponRemove); + std::optional m_playerEntity; std::optional m_scriptingEnvironment; LayerIndex m_layerIndex; std::size_t m_playerIndex; std::string m_name; - Ndk::EntityOwner m_playerEntity; Nz::Bitset m_visibleLayers; Nz::UInt8 m_localIndex; Match& m_match; diff --git a/include/CoreLib/Player.inl b/include/CoreLib/Player.inl index 483a1348..6de7bd8f 100644 --- a/include/CoreLib/Player.inl +++ b/include/CoreLib/Player.inl @@ -6,9 +6,12 @@ namespace bw { - inline const Ndk::EntityHandle& Player::GetControlledEntity() const + inline entt::entity Player::GetControlledEntity() const { - return m_playerEntity; + if (m_playerEntity) + return m_playerEntity->GetEntity(); + else + return entt::null; } inline const PlayerInputData& Player::GetInputs() const diff --git a/include/CoreLib/PlayerInputController.hpp b/include/CoreLib/PlayerInputController.hpp index 4ae61faa..4199d3d5 100644 --- a/include/CoreLib/PlayerInputController.hpp +++ b/include/CoreLib/PlayerInputController.hpp @@ -17,7 +17,7 @@ namespace bw PlayerInputController() = default; ~PlayerInputController() = default; - std::optional GenerateInputs(const Ndk::EntityHandle& entity) const override; + std::optional GenerateInputs(entt::registry& registry, entt::entity entity) const override; }; } diff --git a/include/CoreLib/PlayerMovementController.hpp b/include/CoreLib/PlayerMovementController.hpp index 6b02eb8d..030d556d 100644 --- a/include/CoreLib/PlayerMovementController.hpp +++ b/include/CoreLib/PlayerMovementController.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include namespace Nz { @@ -28,7 +28,7 @@ namespace bw PlayerMovementController() = default; virtual ~PlayerMovementController(); - virtual bool PreSolveCollision(PlayerMovementComponent& playerMovement, const Ndk::EntityHandle& collisionBody, Nz::Arbiter2D& arbiter) const; + virtual bool PreSolveCollision(PlayerMovementComponent& playerMovement, entt::entity collisionBody, Nz::Arbiter2D& arbiter) const; virtual void UpdateVelocity(const PlayerInputData& inputs, PlayerMovementComponent& playerMovement, Nz::RigidBody2D& rigidBody, const Nz::Vector2f& gravity, float damping, float dt) const = 0; }; diff --git a/include/CoreLib/Protocol/Packets.hpp b/include/CoreLib/Protocol/Packets.hpp index 5c268850..f9cb7b77 100644 --- a/include/CoreLib/Protocol/Packets.hpp +++ b/include/CoreLib/Protocol/Packets.hpp @@ -15,7 +15,6 @@ #include #include #include -#include #include #include #include diff --git a/include/CoreLib/Scripting/AbstractElementLibrary.hpp b/include/CoreLib/Scripting/AbstractElementLibrary.hpp index 619fce03..accdd2c4 100644 --- a/include/CoreLib/Scripting/AbstractElementLibrary.hpp +++ b/include/CoreLib/Scripting/AbstractElementLibrary.hpp @@ -9,7 +9,6 @@ #include #include -#include #include #include diff --git a/include/CoreLib/Scripting/AbstractScriptingLibrary.hpp b/include/CoreLib/Scripting/AbstractScriptingLibrary.hpp index 7d8fe5d0..efb9a1f7 100644 --- a/include/CoreLib/Scripting/AbstractScriptingLibrary.hpp +++ b/include/CoreLib/Scripting/AbstractScriptingLibrary.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CORELIB_SCRIPTING_ABSTRACTSCRIPTINGLIBRARY_HPP #include -#include +#include #include #include diff --git a/include/CoreLib/Scripting/AbstractScriptingLibrary.inl b/include/CoreLib/Scripting/AbstractScriptingLibrary.inl index 51b460a5..bed4d6d8 100644 --- a/include/CoreLib/Scripting/AbstractScriptingLibrary.inl +++ b/include/CoreLib/Scripting/AbstractScriptingLibrary.inl @@ -9,7 +9,6 @@ #include #include #include -#include #include #include #include @@ -38,9 +37,6 @@ namespace bw namespace sol { - template <> - struct is_automagical : std::false_type {}; - template <> struct is_automagical : std::false_type {}; diff --git a/include/CoreLib/Scripting/Constraint.hpp b/include/CoreLib/Scripting/Constraint.hpp index 23560dce..9731e07c 100644 --- a/include/CoreLib/Scripting/Constraint.hpp +++ b/include/CoreLib/Scripting/Constraint.hpp @@ -9,14 +9,14 @@ #include #include -#include +#include namespace bw { class BURGWAR_CORELIB_API Constraint { public: - Constraint(Ndk::EntityHandle entity, Nz::Constraint2DHandle constraint); + Constraint(entt::registry& registry, entt::entity entity, Nz::Constraint2DHandle constraint); Constraint(const Constraint&) = delete; Constraint(Constraint&& constraint) noexcept; virtual ~Constraint(); @@ -47,14 +47,15 @@ namespace bw private: NazaraSlot(Nz::HandledObject, OnHandledObjectDestruction, m_onDestruction); - Ndk::EntityHandle m_entity; + entt::entity m_entity; + entt::registry& m_registry; Nz::Constraint2DHandle m_constraint; }; class BURGWAR_CORELIB_API DampedSpringConstraint : public Constraint { public: - inline DampedSpringConstraint(Ndk::EntityHandle entity, Nz::DampedSpringConstraint2D* constraint); + inline DampedSpringConstraint(entt::registry& registry, entt::entity entity, Nz::DampedSpringConstraint2D* constraint); DampedSpringConstraint(DampedSpringConstraint&&) noexcept = default; ~DampedSpringConstraint() = default; @@ -65,7 +66,7 @@ namespace bw class BURGWAR_CORELIB_API PinConstraint : public Constraint { public: - inline PinConstraint(Ndk::EntityHandle entity, Nz::PinConstraint2D* constraint); + inline PinConstraint(entt::registry& registry, entt::entity entity, Nz::PinConstraint2D* constraint); PinConstraint(PinConstraint&&) noexcept = default; ~PinConstraint() = default; @@ -80,7 +81,7 @@ namespace bw class BURGWAR_CORELIB_API PivotConstraint : public Constraint { public: - inline PivotConstraint(Ndk::EntityHandle entity, Nz::PivotConstraint2D* constraint); + inline PivotConstraint(entt::registry& registry, entt::entity entity, Nz::PivotConstraint2D* constraint); PivotConstraint(PivotConstraint&&) noexcept = default; ~PivotConstraint() = default; @@ -91,7 +92,7 @@ namespace bw class BURGWAR_CORELIB_API RotaryLimitConstraint : public Constraint { public: - inline RotaryLimitConstraint(Ndk::EntityHandle entity, Nz::RotaryLimitConstraint2D* constraint); + inline RotaryLimitConstraint(entt::registry& registry, entt::entity entity, Nz::RotaryLimitConstraint2D* constraint); RotaryLimitConstraint(RotaryLimitConstraint&&) noexcept = default; ~RotaryLimitConstraint() = default; diff --git a/include/CoreLib/Scripting/Constraint.inl b/include/CoreLib/Scripting/Constraint.inl index 0ad2bb86..98946c41 100644 --- a/include/CoreLib/Scripting/Constraint.inl +++ b/include/CoreLib/Scripting/Constraint.inl @@ -26,23 +26,23 @@ namespace bw return static_cast(m_constraint.GetObject()); } - inline DampedSpringConstraint::DampedSpringConstraint(Ndk::EntityHandle entity, Nz::DampedSpringConstraint2D* constraint) : - Constraint(std::move(entity), constraint->CreateHandle()) + inline DampedSpringConstraint::DampedSpringConstraint(entt::registry& registry, entt::entity entity, Nz::DampedSpringConstraint2D* constraint) : + Constraint(registry, entity, constraint->CreateHandle()) { } - inline PinConstraint::PinConstraint(Ndk::EntityHandle entity, Nz::PinConstraint2D* constraint) : - Constraint(std::move(entity), constraint->CreateHandle()) + inline PinConstraint::PinConstraint(entt::registry& registry, entt::entity entity, Nz::PinConstraint2D* constraint) : + Constraint(registry, entity, constraint->CreateHandle()) { } - inline PivotConstraint::PivotConstraint(Ndk::EntityHandle entity, Nz::PivotConstraint2D* constraint) : - Constraint(std::move(entity), constraint->CreateHandle()) + inline PivotConstraint::PivotConstraint(entt::registry& registry, entt::entity entity, Nz::PivotConstraint2D* constraint) : + Constraint(registry, entity, constraint->CreateHandle()) { } - inline RotaryLimitConstraint::RotaryLimitConstraint(Ndk::EntityHandle entity, Nz::RotaryLimitConstraint2D* constraint) : - Constraint(std::move(entity), constraint->CreateHandle()) + inline RotaryLimitConstraint::RotaryLimitConstraint(entt::registry& registry, entt::entity entity, Nz::RotaryLimitConstraint2D* constraint) : + Constraint(registry, entity, constraint->CreateHandle()) { } } diff --git a/include/CoreLib/Scripting/NetworkPacket.inl b/include/CoreLib/Scripting/NetworkPacket.inl index 27ac4d18..9d43c584 100644 --- a/include/CoreLib/Scripting/NetworkPacket.inl +++ b/include/CoreLib/Scripting/NetworkPacket.inl @@ -10,14 +10,14 @@ namespace bw { inline NetworkPacket::NetworkPacket(std::string packetName) : m_content(std::make_unique()), - m_stream(m_content.get(), Nz::OpenModeFlags(Nz::OpenMode_WriteOnly)), + m_stream(m_content.get(), Nz::OpenModeFlags(Nz::OpenMode::WriteOnly)), m_packetName(std::move(packetName)) { } inline NetworkPacket::NetworkPacket(std::string packetName, const std::vector& content) : m_content(std::make_unique(content.data(), content.size())), - m_stream(m_content.get(), Nz::OpenModeFlags(Nz::OpenMode_ReadOnly)), + m_stream(m_content.get(), Nz::OpenModeFlags(Nz::OpenMode::ReadOnly)), m_packetName(std::move(packetName)) { } diff --git a/include/CoreLib/Scripting/ScriptStore.hpp b/include/CoreLib/Scripting/ScriptStore.hpp index 7aefeffb..79de248b 100644 --- a/include/CoreLib/Scripting/ScriptStore.hpp +++ b/include/CoreLib/Scripting/ScriptStore.hpp @@ -12,7 +12,6 @@ #include #include #include -#include #include #include #include @@ -21,8 +20,6 @@ namespace bw { - class VirtualDirectory; - template class ScriptStore { @@ -49,16 +46,16 @@ namespace bw void Resolve(); - void UpdateEntityElement(const Ndk::EntityHandle& entity); + void UpdateEntityElement(entt::entity entity); static constexpr std::size_t InvalidIndex = std::numeric_limits::max(); protected: virtual std::shared_ptr CreateElement() const; - const Ndk::EntityHandle& CreateEntity(Ndk::World& world, std::shared_ptr element, PropertyValueMap properties) const; + entt::entity CreateEntity(entt::registry& registry, std::shared_ptr element, PropertyValueMap properties) const; virtual void InitializeElementTable(sol::main_table& elementTable); virtual void InitializeElement(sol::main_table& elementTable, Element& element) = 0; - bool InitializeEntity(const Element& entityClass, const Ndk::EntityHandle& entity) const; + bool InitializeEntity(const Element& entityClass, entt::entity entity) const; sol::state& GetLuaState(); const std::shared_ptr& GetScriptingContext() const; diff --git a/include/CoreLib/Scripting/ScriptStore.inl b/include/CoreLib/Scripting/ScriptStore.inl index 971d71d4..30d6e5c7 100644 --- a/include/CoreLib/Scripting/ScriptStore.inl +++ b/include/CoreLib/Scripting/ScriptStore.inl @@ -6,9 +6,8 @@ #include #include #include -#include +#include #include -#include #include #include #include @@ -69,7 +68,7 @@ namespace bw } template - inline void ScriptStore::UpdateEntityElement(const Ndk::EntityHandle& entity) + inline void ScriptStore::UpdateEntityElement(entt::entity entity) { assert(entity->HasComponent()); @@ -93,12 +92,12 @@ namespace bw const auto& scriptDir = m_context->GetScriptDirectory(); VirtualDirectory::Entry entry; - if (scriptDir->GetEntry(directoryPath.generic_u8string(), &entry) && std::holds_alternative(entry)) + if (scriptDir->GetEntry(directoryPath.generic_u8string(), &entry) && std::holds_alternative(entry)) { - VirtualDirectory::VirtualDirectoryEntry& directory = std::get(entry); - directory->Foreach([&](const std::string& entryName, const VirtualDirectory::Entry& entry) + VirtualDirectory::DirectoryEntry& directory = std::get(entry); + directory->Foreach([&](const std::string& entryName, const Nz::VirtualDirectory::Entry& entry) { - LoadElement(std::holds_alternative(entry), directoryPath / entryName); + LoadElement(std::holds_alternative(entry), directoryPath / entryName); }); } } @@ -258,9 +257,9 @@ namespace bw } template - const Ndk::EntityHandle& ScriptStore::CreateEntity(Ndk::World& world, std::shared_ptr element, PropertyValueMap properties) const + entt::entity ScriptStore::CreateEntity(entt::registry& registry, std::shared_ptr element, PropertyValueMap properties) const { - const Ndk::EntityHandle& entity = world.CreateEntity(); + entt::entity entity = registry.create(); PropertyValueMap filteredProperties; //< Without potential unused properties (FIXME: Is it really necessary?) @@ -313,7 +312,7 @@ namespace bw entityTable["_Entity"] = entity; entityTable[sol::metatable_key] = element->elementTable; - entity->AddComponent(m_logger, std::move(element), scriptingContext, std::move(entityTable), std::move(filteredProperties)); + registry.emplace(m_logger, std::move(element), scriptingContext, std::move(entityTable), std::move(filteredProperties)); return entity; } @@ -527,7 +526,7 @@ namespace bw } template - bool ScriptStore::InitializeEntity(const Element& entityClass, const Ndk::EntityHandle& entity) const + bool ScriptStore::InitializeEntity(const Element& entityClass, entt::entity entity) const { auto& entityScript = entity->GetComponent(); if (!entityScript.ExecuteCallback()) diff --git a/include/CoreLib/Scripting/ScriptingContext.hpp b/include/CoreLib/Scripting/ScriptingContext.hpp index addd49b2..16147d15 100644 --- a/include/CoreLib/Scripting/ScriptingContext.hpp +++ b/include/CoreLib/Scripting/ScriptingContext.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include @@ -27,7 +27,7 @@ namespace bw struct FileLoadCoroutine; using PrintFunction = std::function; - ScriptingContext(const Logger& logger, std::shared_ptr scriptDir); + ScriptingContext(const Logger& logger, std::shared_ptr scriptDir); ~ScriptingContext(); template sol::coroutine CreateCoroutine(Args&&... args); @@ -38,7 +38,7 @@ namespace bw inline const std::filesystem::path& GetCurrentFolder() const; inline sol::state& GetLuaState(); inline const sol::state& GetLuaState() const; - inline const std::shared_ptr& GetScriptDirectory() const; + inline const std::shared_ptr& GetScriptDirectory() const; tl::expected Load(const std::filesystem::path& file, bool logError = true); std::optional Load(const std::filesystem::path& file, Async); @@ -53,7 +53,7 @@ namespace bw inline void SetPrintFunction(PrintFunction function); void Update(); - inline void UpdateScriptDirectory(std::shared_ptr scriptDir); + inline void UpdateScriptDirectory(std::shared_ptr scriptDir); struct FileLoadCoroutine { @@ -65,19 +65,22 @@ namespace bw private: sol::thread& CreateThread(); - tl::expected LoadFile(std::filesystem::path path, const VirtualDirectory::FileContentEntry& entry); - std::optional LoadFile(std::filesystem::path path, const VirtualDirectory::FileContentEntry& entry, Async); - tl::expected LoadFile(std::filesystem::path path, const VirtualDirectory::PhysicalFileEntry& entry); - std::optional LoadFile(std::filesystem::path path, const VirtualDirectory::PhysicalFileEntry& entry, Async); + tl::expected LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::DataPointerEntry& entry); + std::optional LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::DataPointerEntry& entry, Async); + tl::expected LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::FileContentEntry& entry); + std::optional LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::FileContentEntry& entry, Async); + tl::expected LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::PhysicalFileEntry& entry); + std::optional LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::PhysicalFileEntry& entry, Async); tl::expected LoadFile(std::filesystem::path path, const std::string_view& content); std::optional LoadFile(std::filesystem::path path, const std::string_view& content, Async); - void LoadDirectory(std::filesystem::path path, const VirtualDirectory::VirtualDirectoryEntry& folder); - std::string ReadFile(const std::filesystem::path& path, const VirtualDirectory::PhysicalFileEntry& entry); + void LoadDirectory(std::filesystem::path path, const Nz::VirtualDirectory::DirectoryEntry& folder); + void LoadDirectory(std::filesystem::path path, const Nz::VirtualDirectory::PhysicalDirectoryEntry& folder); + std::string ReadFile(const std::filesystem::path& path, const Nz::VirtualDirectory::PhysicalFileEntry& entry); std::filesystem::path m_currentFile; std::filesystem::path m_currentFolder; PrintFunction m_printFunction; - std::shared_ptr m_scriptDirectory; + std::shared_ptr m_scriptDirectory; std::vector> m_libraries; std::vector m_availableThreads; std::vector m_runningThreads; diff --git a/include/CoreLib/Scripting/ScriptingContext.inl b/include/CoreLib/Scripting/ScriptingContext.inl index 440aea09..cbe83312 100644 --- a/include/CoreLib/Scripting/ScriptingContext.inl +++ b/include/CoreLib/Scripting/ScriptingContext.inl @@ -63,7 +63,7 @@ namespace bw return m_luaState; } - inline const std::shared_ptr& ScriptingContext::GetScriptDirectory() const + inline const std::shared_ptr& ScriptingContext::GetScriptDirectory() const { return m_scriptDirectory; } @@ -78,7 +78,7 @@ namespace bw m_printFunction = std::move(function); } - inline void ScriptingContext::UpdateScriptDirectory(std::shared_ptr scriptDir) + inline void ScriptingContext::UpdateScriptDirectory(std::shared_ptr scriptDir) { m_scriptDirectory = std::move(scriptDir); } diff --git a/include/CoreLib/Scripting/ScriptingUtils.hpp b/include/CoreLib/Scripting/ScriptingUtils.hpp index 453f97bf..f72ccfa7 100644 --- a/include/CoreLib/Scripting/ScriptingUtils.hpp +++ b/include/CoreLib/Scripting/ScriptingUtils.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CORELIB_SCRIPTING_UTILS_HPP #include -#include +#include #include #include #include @@ -19,11 +19,11 @@ namespace bw struct ScriptedElement; BURGWAR_CORELIB_API std::shared_ptr AssertScriptElement(const sol::table& entityTable); - BURGWAR_CORELIB_API Ndk::EntityHandle AssertScriptEntity(const sol::table& entityTable); + BURGWAR_CORELIB_API entt::entity AssertScriptEntity(entt::registry& registry, const sol::table& entityTable); BURGWAR_CORELIB_API std::shared_ptr RetrieveScriptElement(const sol::table& entityTable); - BURGWAR_CORELIB_API Ndk::EntityHandle RetrieveScriptEntity(const sol::table& entityTable); + BURGWAR_CORELIB_API entt::entity RetrieveScriptEntity(const sol::table& entityTable); - BURGWAR_CORELIB_API std::optional TranslateEntityToLua(const Ndk::EntityHandle& entity); + BURGWAR_CORELIB_API std::optional TranslateEntityToLua(entt::registry& registry, entt::entity entity); template [[noreturn]] void TriggerLuaError(lua_State* L, const char* format, Args&&... args); [[noreturn]] BURGWAR_CORELIB_API void TriggerLuaError(lua_State* L, const std::string& errMessage); [[noreturn]] BURGWAR_CORELIB_API void TriggerLuaArgError(lua_State* L, int argIndex, const char* errMessage); diff --git a/include/CoreLib/Scripting/ServerElementLibrary.hpp b/include/CoreLib/Scripting/ServerElementLibrary.hpp index 7649d160..6a617466 100644 --- a/include/CoreLib/Scripting/ServerElementLibrary.hpp +++ b/include/CoreLib/Scripting/ServerElementLibrary.hpp @@ -23,7 +23,7 @@ namespace bw private: void RegisterServerLibrary(sol::table& elementTable); - void SetScale(const Ndk::EntityHandle& entity, float newScale) override; + void SetScale(entt::entity entity, float newScale) override; }; } diff --git a/include/CoreLib/Scripting/ServerEntityLibrary.hpp b/include/CoreLib/Scripting/ServerEntityLibrary.hpp index 6118780e..1c6d9920 100644 --- a/include/CoreLib/Scripting/ServerEntityLibrary.hpp +++ b/include/CoreLib/Scripting/ServerEntityLibrary.hpp @@ -23,13 +23,13 @@ namespace bw private: void RegisterServerLibrary(sol::table& elementMetatable); - void SetDirection(lua_State* L, const Ndk::EntityHandle& entity, const Nz::Vector2f& upVector) override; - void SetMass(lua_State* L, const Ndk::EntityHandle& entity, float mass, bool recomputeMomentOfInertia) override; - void SetMomentOfInertia(lua_State* L, const Ndk::EntityHandle& entity, float momentOfInertia) override; - void SetPosition(lua_State* L, const Ndk::EntityHandle& entity, const Nz::Vector2f& position) override; - void SetRotation(lua_State* L, const Ndk::EntityHandle& entity, const Nz::DegreeAnglef& rotation) override; - void UpdatePlayerJumpHeight(lua_State* L, const Ndk::EntityHandle& entity, float jumpHeight, float jumpHeightBoost) override; - void UpdatePlayerMovement(lua_State* L, const Ndk::EntityHandle& entity, float movementSpeed) override; + void SetDirection(lua_State* L, entt::entity entity, const Nz::Vector2f& upVector) override; + void SetMass(lua_State* L, entt::entity entity, float mass, bool recomputeMomentOfInertia) override; + void SetMomentOfInertia(lua_State* L, entt::entity entity, float momentOfInertia) override; + void SetPosition(lua_State* L, entt::entity entity, const Nz::Vector2f& position) override; + void SetRotation(lua_State* L, entt::entity entity, const Nz::DegreeAnglef& rotation) override; + void UpdatePlayerJumpHeight(lua_State* L, entt::entity entity, float jumpHeight, float jumpHeightBoost) override; + void UpdatePlayerMovement(lua_State* L, entt::entity entity, float movementSpeed) override; }; } diff --git a/include/CoreLib/Scripting/ServerEntityStore.hpp b/include/CoreLib/Scripting/ServerEntityStore.hpp index 05d45ea9..3a2eb9b4 100644 --- a/include/CoreLib/Scripting/ServerEntityStore.hpp +++ b/include/CoreLib/Scripting/ServerEntityStore.hpp @@ -11,7 +11,6 @@ #include #include #include -#include namespace bw { @@ -23,9 +22,9 @@ namespace bw inline ServerEntityStore(const Logger& logger, std::shared_ptr context); ~ServerEntityStore() = default; - const Ndk::EntityHandle& CreateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, const Ndk::EntityHandle& parent = Ndk::EntityHandle::InvalidHandle) const; - bool InitializeEntity(const Ndk::EntityHandle& entity) const; - const Ndk::EntityHandle& InstantiateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, const Ndk::EntityHandle& parent = Ndk::EntityHandle::InvalidHandle) const; + entt::entity CreateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, entt::entity parent = entt::null) const; + bool InitializeEntity(entt::registry& registry, entt::entity entity) const; + entt::entity InstantiateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, entt::entity parent = entt::null) const; private: void InitializeElementTable(sol::main_table& elementTable) override; diff --git a/include/CoreLib/Scripting/ServerTexture.hpp b/include/CoreLib/Scripting/ServerTexture.hpp index 1485a1ba..97b8081d 100644 --- a/include/CoreLib/Scripting/ServerTexture.hpp +++ b/include/CoreLib/Scripting/ServerTexture.hpp @@ -15,7 +15,7 @@ namespace bw class BURGWAR_CORELIB_API ServerTexture { public: - inline ServerTexture(Nz::ImageRef image); + inline ServerTexture(std::shared_ptr image); ServerTexture(const ServerTexture&) = default; ServerTexture(ServerTexture&&) = default; ~ServerTexture() = default; @@ -26,7 +26,7 @@ namespace bw ServerTexture& operator=(ServerTexture&&) = default; private: - Nz::ImageRef m_image; + std::shared_ptr m_image; }; } diff --git a/include/CoreLib/Scripting/ServerTexture.inl b/include/CoreLib/Scripting/ServerTexture.inl index 9dc74cc2..54287152 100644 --- a/include/CoreLib/Scripting/ServerTexture.inl +++ b/include/CoreLib/Scripting/ServerTexture.inl @@ -6,7 +6,7 @@ namespace bw { - inline ServerTexture::ServerTexture(Nz::ImageRef texture) : + inline ServerTexture::ServerTexture(std::shared_ptr texture) : m_image(std::move(texture)) { } diff --git a/include/CoreLib/Scripting/ServerWeaponStore.hpp b/include/CoreLib/Scripting/ServerWeaponStore.hpp index a45f52a7..5e8e37f1 100644 --- a/include/CoreLib/Scripting/ServerWeaponStore.hpp +++ b/include/CoreLib/Scripting/ServerWeaponStore.hpp @@ -9,7 +9,6 @@ #include #include -#include namespace bw { @@ -22,7 +21,7 @@ namespace bw inline ServerWeaponStore(const Logger& logger, std::shared_ptr context); ~ServerWeaponStore() = default; - const Ndk::EntityHandle& InstantiateWeapon(TerrainLayer& layer, std::size_t weaponIndex, EntityId uniqueId, const PropertyValueMap& properties, const Ndk::EntityHandle& parent); + entt::entity InstantiateWeapon(TerrainLayer& layer, std::size_t weaponIndex, EntityId uniqueId, const PropertyValueMap& properties, entt::entity parent); private: void InitializeElement(sol::main_table& elementTable, ScriptedWeapon& weapon) override; diff --git a/include/CoreLib/Scripting/SharedElementLibrary.hpp b/include/CoreLib/Scripting/SharedElementLibrary.hpp index d456e36b..bbad986a 100644 --- a/include/CoreLib/Scripting/SharedElementLibrary.hpp +++ b/include/CoreLib/Scripting/SharedElementLibrary.hpp @@ -23,7 +23,7 @@ namespace bw void RegisterLibrary(sol::table& elementMetatable) override; protected: - virtual void SetScale(const Ndk::EntityHandle& entity, float newScale) = 0; + virtual void SetScale(entt::entity entity, float newScale) = 0; private: void RegisterCommonLibrary(sol::table& elementMetatable); diff --git a/include/CoreLib/Scripting/SharedEntityLibrary.hpp b/include/CoreLib/Scripting/SharedEntityLibrary.hpp index 2ac4fe94..674280ef 100644 --- a/include/CoreLib/Scripting/SharedEntityLibrary.hpp +++ b/include/CoreLib/Scripting/SharedEntityLibrary.hpp @@ -22,14 +22,14 @@ namespace bw void RegisterLibrary(sol::table& elementMetatable) override; protected: - virtual void InitRigidBody(lua_State* L, const Ndk::EntityHandle& entity, float mass); - virtual void SetDirection(lua_State* L, const Ndk::EntityHandle& entity, const Nz::Vector2f& upVector); - virtual void SetMass(lua_State* L, const Ndk::EntityHandle& entity, float mass, bool recomputeMomentOfInertia); - virtual void SetMomentOfInertia(lua_State* L, const Ndk::EntityHandle& entity, float momentOfInertia); - virtual void SetPosition(lua_State* L, const Ndk::EntityHandle& entity, const Nz::Vector2f& position); - virtual void SetRotation(lua_State* L, const Ndk::EntityHandle& entity, const Nz::DegreeAnglef& rotation); - virtual void UpdatePlayerJumpHeight(lua_State* L, const Ndk::EntityHandle& entity, float jumpHeight, float jumpHeightBoost); - virtual void UpdatePlayerMovement(lua_State* L, const Ndk::EntityHandle& entity, float movementSpeed); + virtual void InitRigidBody(lua_State* L, entt::entity entity, float mass); + virtual void SetDirection(lua_State* L, entt::entity entity, const Nz::Vector2f& upVector); + virtual void SetMass(lua_State* L, entt::entity entity, float mass, bool recomputeMomentOfInertia); + virtual void SetMomentOfInertia(lua_State* L, entt::entity entity, float momentOfInertia); + virtual void SetPosition(lua_State* L, entt::entity entity, const Nz::Vector2f& position); + virtual void SetRotation(lua_State* L, entt::entity entity, const Nz::DegreeAnglef& rotation); + virtual void UpdatePlayerJumpHeight(lua_State* L, entt::entity entity, float jumpHeight, float jumpHeightBoost); + virtual void UpdatePlayerMovement(lua_State* L, entt::entity entity, float movementSpeed); private: void RegisterSharedLibrary(sol::table& elementMetatable); diff --git a/include/CoreLib/Scripting/SharedEntityStore.hpp b/include/CoreLib/Scripting/SharedEntityStore.hpp index 9267fc70..2f2549f6 100644 --- a/include/CoreLib/Scripting/SharedEntityStore.hpp +++ b/include/CoreLib/Scripting/SharedEntityStore.hpp @@ -10,8 +10,6 @@ #include #include #include -#include -#include namespace bw { @@ -22,9 +20,9 @@ namespace bw ~SharedEntityStore() = default; protected: - virtual void BindCallbacks(const ScriptedEntity& entityClass, const Ndk::EntityHandle& entity) const; + virtual void BindCallbacks(const ScriptedEntity& entityClass, entt::entity entity) const; void InitializeElement(sol::main_table& elementTable, ScriptedEntity& element) override = 0; - bool InitializeEntity(const ScriptedEntity& entityClass, const Ndk::EntityHandle& entity) const; + bool InitializeEntity(const ScriptedEntity& entityClass, entt::entity entity) const; }; } diff --git a/include/CoreLib/Scripting/SharedWeaponStore.hpp b/include/CoreLib/Scripting/SharedWeaponStore.hpp index 72c60ab9..a918823e 100644 --- a/include/CoreLib/Scripting/SharedWeaponStore.hpp +++ b/include/CoreLib/Scripting/SharedWeaponStore.hpp @@ -10,8 +10,6 @@ #include #include #include -#include -#include namespace bw { @@ -23,7 +21,7 @@ namespace bw protected: void InitializeElement(sol::main_table& elementTable, ScriptedWeapon& weapon) override = 0; - bool InitializeWeapon(const ScriptedWeapon& weaponClass, const Ndk::EntityHandle& entity, const Ndk::EntityHandle& parent); + bool InitializeWeapon(const ScriptedWeapon& weaponClass, entt::entity entity, entt::entity parent); }; } diff --git a/include/CoreLib/ScriptingEnvironment.hpp b/include/CoreLib/ScriptingEnvironment.hpp index 1da0fd85..6526e276 100644 --- a/include/CoreLib/ScriptingEnvironment.hpp +++ b/include/CoreLib/ScriptingEnvironment.hpp @@ -23,7 +23,7 @@ namespace bw public: using OutputCallback = std::function; - ScriptingEnvironment(const Logger& logger, std::shared_ptr scriptingLibrary, const std::shared_ptr& scriptDir); + ScriptingEnvironment(const Logger& logger, std::shared_ptr scriptingLibrary, const std::shared_ptr& scriptDir); ScriptingEnvironment(const ScriptingEnvironment&) = delete; ScriptingEnvironment(ScriptingEnvironment&&) = default; ~ScriptingEnvironment() = default; diff --git a/include/CoreLib/SharedLayer.hpp b/include/CoreLib/SharedLayer.hpp index 8e39d505..c2dce466 100644 --- a/include/CoreLib/SharedLayer.hpp +++ b/include/CoreLib/SharedLayer.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include namespace bw { @@ -27,8 +27,8 @@ namespace bw inline LayerIndex GetLayerIndex() const; inline SharedMatch& GetMatch(); - Ndk::World& GetWorld(); - const Ndk::World& GetWorld() const; + inline entt::registry& GetWorld(); + inline const entt::registry& GetWorld() const; virtual void TickUpdate(float elapsedTime); @@ -37,7 +37,7 @@ namespace bw private: SharedMatch& m_match; - Ndk::World m_world; + entt::registry m_registry; LayerIndex m_layerIndex; }; } diff --git a/include/CoreLib/SharedLayer.inl b/include/CoreLib/SharedLayer.inl index 204ee4e4..70f8d23b 100644 --- a/include/CoreLib/SharedLayer.inl +++ b/include/CoreLib/SharedLayer.inl @@ -10,7 +10,7 @@ namespace bw template void SharedLayer::ForEachEntity(F&& func) { - for (const Ndk::EntityHandle& entity : m_world.GetEntities()) + for (entt::entity entity : m_world.GetEntities()) func(entity); } @@ -24,13 +24,13 @@ namespace bw return m_match; } - inline Ndk::World& SharedLayer::GetWorld() + inline entt::registry& SharedLayer::GetWorld() { - return m_world; + return m_registry; } - inline const Ndk::World& SharedLayer::GetWorld() const + inline const entt::registry& SharedLayer::GetWorld() const { - return m_world; + return m_registry; } } diff --git a/include/CoreLib/SharedMatch.hpp b/include/CoreLib/SharedMatch.hpp index bd0066d0..e8622fee 100644 --- a/include/CoreLib/SharedMatch.hpp +++ b/include/CoreLib/SharedMatch.hpp @@ -13,7 +13,8 @@ #include #include #include -#include +#include +#include namespace bw { @@ -32,7 +33,7 @@ namespace bw SharedMatch(SharedMatch&&) = delete; virtual ~SharedMatch(); - virtual void ForEachEntity(std::function func) = 0; + virtual void ForEachEntity(tl::function_ref func) = 0; inline Nz::UInt64 GetCurrentTick() const; inline Nz::UInt64 GetCurrentTime() const; @@ -54,8 +55,8 @@ namespace bw virtual SharedWeaponStore& GetWeaponStore() = 0; virtual const SharedWeaponStore& GetWeaponStore() const = 0; - virtual const Ndk::EntityHandle& RetrieveEntityByUniqueId(EntityId uniqueId) const = 0; - virtual EntityId RetrieveUniqueIdByEntity(const Ndk::EntityHandle& entity) const = 0; + virtual entt::entity RetrieveEntityByUniqueId(EntityId uniqueId) const = 0; + virtual EntityId RetrieveUniqueIdByEntity(entt::entity entity) const = 0; void Update(float elapsedTime); diff --git a/include/CoreLib/Systems/AnimationSystem.hpp b/include/CoreLib/Systems/AnimationSystem.hpp index f87e0056..28f910cf 100644 --- a/include/CoreLib/Systems/AnimationSystem.hpp +++ b/include/CoreLib/Systems/AnimationSystem.hpp @@ -8,23 +8,20 @@ #define BURGWAR_CLIENTLIB_SYSTEMS_ANIMATIONSYSTEM_HPP #include -#include #include namespace bw { class SharedMatch; - class BURGWAR_CORELIB_API AnimationSystem : public Ndk::System + class BURGWAR_CORELIB_API AnimationSystem { public: AnimationSystem(SharedMatch& match); ~AnimationSystem() = default; - static Ndk::SystemIndex systemIndex; - private: - void OnUpdate(float elapsedTime) override; + void OnUpdate(float elapsedTime); SharedMatch& m_match; }; diff --git a/include/CoreLib/Systems/InputSystem.hpp b/include/CoreLib/Systems/InputSystem.hpp index 52622a69..eeb9c5e2 100644 --- a/include/CoreLib/Systems/InputSystem.hpp +++ b/include/CoreLib/Systems/InputSystem.hpp @@ -8,21 +8,18 @@ #define BURGWAR_CORELIB_SYSTEMS_INPUTSYSTEM_HPP #include -#include #include namespace bw { - class BURGWAR_CORELIB_API InputSystem : public Ndk::System + class BURGWAR_CORELIB_API InputSystem { public: InputSystem(); ~InputSystem() = default; - static Ndk::SystemIndex systemIndex; - private: - void OnUpdate(float elapsedTime) override; + void OnUpdate(float elapsedTime); }; } diff --git a/include/CoreLib/Systems/NetworkSyncSystem.hpp b/include/CoreLib/Systems/NetworkSyncSystem.hpp index bf9fa9f2..00410138 100644 --- a/include/CoreLib/Systems/NetworkSyncSystem.hpp +++ b/include/CoreLib/Systems/NetworkSyncSystem.hpp @@ -18,8 +18,8 @@ #include #include #include -#include #include +#include #include #include #include @@ -30,7 +30,7 @@ namespace bw class Player; class TerrainLayer; - class BURGWAR_CORELIB_API NetworkSyncSystem : public Ndk::System + class BURGWAR_CORELIB_API NetworkSyncSystem { public: struct EntityCreation; @@ -48,11 +48,9 @@ namespace bw void MoveEntities(const std::function& callback) const; - inline void NotifyPhysicsUpdate(const Ndk::EntityHandle& entity); - inline void NotifyMovementUpdate(const Ndk::EntityHandle& entity); - inline void NotifyScaleUpdate(const Ndk::EntityHandle& entity); - - static Ndk::SystemIndex systemIndex; + inline void NotifyPhysicsUpdate(entt::entity entity); + inline void NotifyMovementUpdate(entt::entity entity); + inline void NotifyScaleUpdate(entt::entity entity); struct HealthProperties { @@ -76,49 +74,49 @@ namespace bw struct EntityPlayAnimation { - Ndk::EntityId entityId; + entt::entity entityId; std::size_t animId; Nz::UInt64 startTime; }; struct EntityCreation { - Ndk::EntityId entityId; + entt::entity entityId; EntityId uniqueId; Nz::RadianAnglef rotation; Nz::Vector2f position; float scale; Player* playerOwner; - std::optional parent; - std::optional weapon; + std::optional parent; + std::optional weapon; std::optional healthProperties; std::optional inputs; std::optional playerMovement; std::optional physicsProperties; std::string entityClass; tsl::hopscotch_map properties; - std::vector> dependentIds; + std::vector> dependentIds; }; struct EntityDeath { - Ndk::EntityId entityId; + entt::entity entityId; }; struct EntityDestruction { - Ndk::EntityId entityId; + entt::entity entityId; }; struct EntityHealth { - Ndk::EntityId entityId; + entt::entity entityId; Nz::UInt16 currentHealth; }; struct EntityInputs { - Ndk::EntityId entityId; + entt::entity entityId; PlayerInputData inputs; }; @@ -131,7 +129,7 @@ namespace bw float movementSpeed; }; - Ndk::EntityId entityId; + entt::entity entityId; bool isAsleep; float mass; float momentOfInertia; @@ -140,19 +138,19 @@ namespace bw struct EntityScale { - Ndk::EntityId entityId; + entt::entity entityId; float newScale; }; struct EntityWeapon { - Ndk::EntityId entityId; - std::optional weaponId; + entt::entity entityId; + std::optional weaponId; }; struct EntityMovement { - Ndk::EntityId entityId; + entt::entity entityId; Nz::RadianAnglef rotation; Nz::Vector2f position; std::optional playerMovement; @@ -171,35 +169,35 @@ namespace bw NazaraSignal(OnEntitiesWeaponUpdate, NetworkSyncSystem* /*emitter*/, const EntityWeapon* /*events*/, std::size_t /*entityCount*/); private: - void BuildEvent(EntityCreation& creationEvent, Ndk::Entity* entity) const; - void BuildEvent(EntityDeath& deathEvent, Ndk::Entity* entity) const; - void BuildEvent(EntityDestruction& deleteEvent, Ndk::Entity* entity) const; - void BuildEvent(EntityMovement& movementEvent, Ndk::Entity* entity) const; + void BuildEvent(EntityCreation& creationEvent, entt::entity entity) const; + void BuildEvent(EntityDeath& deathEvent, entt::entity entity) const; + void BuildEvent(EntityDestruction& deleteEvent, entt::entity entity) const; + void BuildEvent(EntityMovement& movementEvent, entt::entity entity) const; - void OnEntityAdded(Ndk::Entity* entity) override; - void OnEntityRemoved(Ndk::Entity* entity) override; - void OnUpdate(float elapsedTime) override; + //void OnEntityAdded(entt::entity entity) override; + //void OnEntityRemoved(entt::entity entity) override; + //void OnUpdate(float elapsedTime) override; struct EntitySlots { NazaraSlot(AnimationComponent, OnAnimationStart, onAnimationStart); - NazaraSlot(HealthComponent, OnDied, onDied); + NazaraSlot(HealthComponent, OnDie, onDied); NazaraSlot(HealthComponent, OnHealthChange, onHealthChange); NazaraSlot(InputComponent, OnInputUpdate, onInputUpdate); NazaraSlot(NetworkSyncComponent, OnInvalidated, onInvalidated); NazaraSlot(WeaponWielderComponent, OnNewWeaponSelection, onNewWeaponSelection); }; - tsl::hopscotch_map m_entitySlots; + tsl::hopscotch_map m_entitySlots; - Ndk::EntityList m_inputUpdateEntities; - Ndk::EntityList m_healthUpdateEntities; - Ndk::EntityList m_movedStaticEntities; - Ndk::EntityList m_physicsEntities; - Ndk::EntityList m_physicsUpdateEntities; - Ndk::EntityList m_scaleUpdateEntities; - Ndk::EntityList m_staticEntities; - Ndk::EntityList m_weaponUpdateEntities; + tsl::hopscotch_set m_inputUpdateEntities; + tsl::hopscotch_set m_healthUpdateEntities; + tsl::hopscotch_set m_movedStaticEntities; + tsl::hopscotch_set m_physicsEntities; + tsl::hopscotch_set m_physicsUpdateEntities; + tsl::hopscotch_set m_scaleUpdateEntities; + tsl::hopscotch_set m_staticEntities; + tsl::hopscotch_set m_weaponUpdateEntities; mutable std::vector m_creationEvents; mutable std::vector m_destructionEvents; std::vector m_healthEvents; diff --git a/include/CoreLib/Systems/NetworkSyncSystem.inl b/include/CoreLib/Systems/NetworkSyncSystem.inl index 2ccb89a1..2f0f6d72 100644 --- a/include/CoreLib/Systems/NetworkSyncSystem.inl +++ b/include/CoreLib/Systems/NetworkSyncSystem.inl @@ -16,21 +16,21 @@ namespace bw return m_layer; } - inline void NetworkSyncSystem::NotifyPhysicsUpdate(const Ndk::EntityHandle& entity) + inline void NetworkSyncSystem::NotifyPhysicsUpdate(entt::entity entity) { - if (m_physicsEntities.Has(entity)) - m_physicsUpdateEntities.Insert(entity); + if (m_physicsEntities.contains(entity)) + m_physicsUpdateEntities.insert(entity); } - inline void NetworkSyncSystem::NotifyMovementUpdate(const Ndk::EntityHandle& entity) + inline void NetworkSyncSystem::NotifyMovementUpdate(entt::entity entity) { // Dynamic entities are sent regulary, only send static for now (TODO: Handle teleportation this way) - if (m_staticEntities.Has(entity)) - m_movedStaticEntities.Insert(entity); + if (m_staticEntities.contains(entity)) + m_movedStaticEntities.insert(entity); } - inline void NetworkSyncSystem::NotifyScaleUpdate(const Ndk::EntityHandle& entity) + inline void NetworkSyncSystem::NotifyScaleUpdate(entt::entity entity) { - m_scaleUpdateEntities.Insert(entity); + m_scaleUpdateEntities.insert(entity); } } diff --git a/include/CoreLib/Systems/PlayerMovementSystem.hpp b/include/CoreLib/Systems/PlayerMovementSystem.hpp index f1253d35..0e64237c 100644 --- a/include/CoreLib/Systems/PlayerMovementSystem.hpp +++ b/include/CoreLib/Systems/PlayerMovementSystem.hpp @@ -8,19 +8,16 @@ #define BURGWAR_CLIENTLIB_SYSTEMS_PLAYERMOVEMENT_HPP #include -#include #include namespace bw { - class BURGWAR_CORELIB_API PlayerMovementSystem : public Ndk::System + class BURGWAR_CORELIB_API PlayerMovementSystem { public: PlayerMovementSystem(); ~PlayerMovementSystem() = default; - static Ndk::SystemIndex systemIndex; - private: void OnEntityAdded(Ndk::Entity* entity) override; void OnEntityRemoved(Ndk::Entity* entity) override; diff --git a/include/CoreLib/Utility/VirtualDirectory.hpp b/include/CoreLib/Utility/VirtualDirectory.hpp deleted file mode 100644 index 5d68fdf0..00000000 --- a/include/CoreLib/Utility/VirtualDirectory.hpp +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#pragma once - -#ifndef BURGWAR_CORELIB_VIRTUALDIRECTORY_HPP -#define BURGWAR_CORELIB_VIRTUALDIRECTORY_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace bw -{ - class BURGWAR_CORELIB_API VirtualDirectory : public std::enable_shared_from_this - { - public: - using FileContentEntry = std::vector; - using PhysicalFileEntry = std::filesystem::path; - using VirtualDirectoryEntry = std::shared_ptr; - - using Entry = std::variant; - - inline VirtualDirectory(VirtualDirectoryEntry parentDirectory = nullptr); - inline VirtualDirectory(std::filesystem::path physicalPath, VirtualDirectoryEntry parentDirectory = nullptr); - ~VirtualDirectory() = default; - - template void Foreach(F&& cb, bool includeDots = false); - - inline bool GetEntry(const std::string_view& path, Entry* entry); - - inline VirtualDirectoryEntry& StoreDirectory(const std::string_view& path, VirtualDirectoryEntry directory); - inline VirtualDirectoryEntry& StoreDirectory(const std::string_view& path, std::filesystem::path directoryPath); - inline FileContentEntry& StoreFile(const std::string_view& path, FileContentEntry file); - inline PhysicalFileEntry& StoreFile(const std::string_view& path, std::filesystem::path filePath); - - private: - inline void EnsureDots(); - inline bool RetrieveDirectory(const std::string_view& path, bool allowCreation, std::shared_ptr& directory, std::string_view& entryName); - inline bool GetEntryInternal(const std::string_view& name, Entry* entry); - inline VirtualDirectoryEntry& StoreDirectoryInternal(std::string name, std::filesystem::path directoryPath); - inline VirtualDirectoryEntry& StoreDirectoryInternal(std::string name, VirtualDirectoryEntry directory); - inline FileContentEntry& StoreFileInternal(std::string name, FileContentEntry file); - inline PhysicalFileEntry& StoreFileInternal(std::string name, std::filesystem::path file); - - template static bool SplitPath(std::string_view path, F1&& dirCB, F2&& fileCB); - - std::map> m_content; - std::optional m_physicalPath; - VirtualDirectoryEntry m_parent; - bool m_wereDotRegistered; - }; -} - -#include - -#endif diff --git a/include/CoreLib/Utility/VirtualDirectory.inl b/include/CoreLib/Utility/VirtualDirectory.inl deleted file mode 100644 index b83922fa..00000000 --- a/include/CoreLib/Utility/VirtualDirectory.inl +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include -#include - -namespace bw -{ - inline VirtualDirectory::VirtualDirectory(VirtualDirectoryEntry parentDirectory) : - m_parent(std::move(parentDirectory)), - m_wereDotRegistered(false) - { - } - - inline VirtualDirectory::VirtualDirectory(std::filesystem::path physicalPath, VirtualDirectoryEntry parentDirectory) : - m_physicalPath(std::move(physicalPath)), - m_parent(std::move(parentDirectory)), - m_wereDotRegistered(false) - { - } - - template - void VirtualDirectory::Foreach(F&& cb, bool includeDots) - { - if (includeDots) - EnsureDots(); - - for (auto&& pair : m_content) - { - if (!includeDots && (pair.first == "." || pair.first == "..")) - continue; - - cb(pair.first, pair.second); - } - - if (m_physicalPath) - { - for (auto&& physicalEntry : std::filesystem::directory_iterator(*m_physicalPath)) - { - Entry entry; - - std::string filename = physicalEntry.path().filename().generic_u8string(); - if (m_content.find(filename) != m_content.end()) - continue; //< Physical file/directory has been overriden by a virtual one - - if (physicalEntry.is_regular_file()) - entry.emplace(physicalEntry.path()); - else if (physicalEntry.is_directory()) - { - // FIXME: Allocating a shared_ptr on iteration is bad, not sure about a workaround - entry.emplace(std::make_shared(physicalEntry.path(), shared_from_this())); - } - else - continue; - - cb(physicalEntry.path().filename().generic_u8string(), entry); - } - } - } - - inline bool VirtualDirectory::GetEntry(const std::string_view& path, Entry* entry) - { - std::shared_ptr dir; - std::string_view entryName; - if (!RetrieveDirectory(path, false, dir, entryName)) - return false; - - if (!dir->GetEntryInternal(entryName, entry)) - return false; - - return true; - } - - inline auto VirtualDirectory::StoreDirectory(const std::string_view& path, VirtualDirectoryEntry directory) -> VirtualDirectoryEntry& - { - std::shared_ptr dir; - std::string_view entryName; - if (!RetrieveDirectory(path, true, dir, entryName)) - throw std::runtime_error("invalid path"); - - return dir->StoreDirectoryInternal(std::string(entryName), std::move(directory)); - } - - inline auto VirtualDirectory::StoreDirectory(const std::string_view& path, std::filesystem::path directoryPath) -> VirtualDirectoryEntry& - { - std::shared_ptr dir; - std::string_view entryName; - if (!RetrieveDirectory(path, true, dir, entryName)) - throw std::runtime_error("invalid path"); - - return dir->StoreDirectoryInternal(std::string(entryName), std::move(directoryPath)); - } - - inline auto VirtualDirectory::StoreFile(const std::string_view& path, FileContentEntry file) -> FileContentEntry& - { - std::shared_ptr dir; - std::string_view entryName; - if (!RetrieveDirectory(path, true, dir, entryName)) - throw std::runtime_error("invalid path"); - - return dir->StoreFileInternal(std::string(entryName), std::move(file)); - } - - inline auto VirtualDirectory::StoreFile(const std::string_view& path, std::filesystem::path filePath) -> PhysicalFileEntry& - { - std::shared_ptr dir; - std::string_view entryName; - if (!RetrieveDirectory(path, true, dir, entryName)) - throw std::runtime_error("invalid path"); - - return dir->StoreFileInternal(std::string(entryName), std::move(filePath)); - } - - inline void VirtualDirectory::EnsureDots() - { - if (!m_wereDotRegistered) - { - StoreDirectoryInternal(".", shared_from_this()); - if (m_parent) - StoreDirectoryInternal("..", m_parent); - else - StoreDirectoryInternal("..", shared_from_this()); - - m_wereDotRegistered = true; - } - } - - inline bool VirtualDirectory::RetrieveDirectory(const std::string_view& path, bool allowCreation, std::shared_ptr& directory, std::string_view& entryName) - { - directory = shared_from_this(); - - return SplitPath(path, [&](std::string_view dirName) - { - Entry entry; - if (directory->GetEntryInternal(dirName, &entry)) - { - if (auto dir = std::get_if(&entry)) - directory = *dir; - else - return false; - } - else - { - if (allowCreation) - { - auto newDirectory = std::make_shared(directory); - directory = directory->StoreDirectoryInternal(std::string(dirName), newDirectory); - } - else - return false; - } - - return true; - }, - [&](std::string_view name) - { - entryName = name; - }); - } - - inline bool VirtualDirectory::GetEntryInternal(const std::string_view& name, Entry* entry) - { - EnsureDots(); - - auto it = m_content.find(name); - if (it != m_content.end()) - { - *entry = it->second; - return true; - } - else - { - if (m_physicalPath) - { - std::filesystem::path entryPath = *m_physicalPath / name; - - if (std::filesystem::is_regular_file(entryPath)) - entry->emplace(entryPath); - else if (std::filesystem::is_directory(entryPath)) - { - // FIXME: Allocating a shared_ptr on iteration is bad, not sure about a workaround - *entry = StoreDirectoryInternal(std::string(name), entryPath); - } - else - return false; - - return true; - } - - return false; - } - } - - inline auto VirtualDirectory::StoreDirectoryInternal(std::string name, std::filesystem::path directoryPath) -> VirtualDirectoryEntry& - { - assert(name.find_first_of("\\/:") == name.npos); - - auto it = m_content.insert_or_assign(std::move(name), std::make_shared(directoryPath, shared_from_this())).first; - return std::get(it->second); - } - - inline auto VirtualDirectory::StoreDirectoryInternal(std::string name, VirtualDirectoryEntry directory) -> VirtualDirectoryEntry& - { - assert(name.find_first_of("\\/:") == name.npos); - - auto it = m_content.insert_or_assign(std::move(name), std::move(directory)).first; - return std::get(it->second); - } - - inline auto VirtualDirectory::StoreFileInternal(std::string name, FileContentEntry file) -> FileContentEntry& - { - assert(name.find_first_of("\\/:") == name.npos); - - auto it = m_content.insert_or_assign(std::move(name), std::move(file)).first; - return std::get(it->second); - } - - inline auto VirtualDirectory::StoreFileInternal(std::string name, std::filesystem::path file) -> PhysicalFileEntry& - { - assert(name.find_first_of("\\/:") == name.npos); - - auto it = m_content.insert_or_assign(std::move(name), std::move(file)).first; - return std::get(it->second); - } - - template - inline bool VirtualDirectory::SplitPath(std::string_view path, F1&& dirCB, F2&& lastCB) - { - std::size_t pos; - while ((pos = path.find_first_of("\\/:")) != std::string::npos) - { - if (!dirCB(path.substr(0, pos))) - return false; - - path = path.substr(pos + 1); - } - - lastCB(path); - return true; - } -} diff --git a/scripts/entities/sound.lua b/scripts/entities/sound.lua new file mode 100644 index 00000000..8139081a --- /dev/null +++ b/scripts/entities/sound.lua @@ -0,0 +1,20 @@ +RegisterClientScript() + +local entity = ScriptedEntity({ + IsNetworked = true, + Properties = { + { Name = "soundPath", Type = PropertyType.String, Shared = true }, -- TODO: Improve using networked string + { Name = "isLooping", Type = PropertyType.Boolean, Default = false, Shared = true }, + { Name = "isSpatialized", Type = PropertyType.Boolean, Default = true, Shared = true }, + } +}) + +if (CLIENT) then + entity:OnAsync("Init", function (self) + self.Sound = self:PlaySound(self:GetProperty("soundPath"), true, self:GetProperty("isLooping"), self:GetProperty("isSpatialized")) + end) + + entity:On("Destroyed", function (self) + self.Sound:Stop() + end) +end diff --git a/src/Client/ClientApp.cpp b/src/Client/ClientApp.cpp index 44f05682..8da0eee5 100644 --- a/src/Client/ClientApp.cpp +++ b/src/Client/ClientApp.cpp @@ -66,7 +66,7 @@ namespace bw renderSystem.SetDefaultBackground(nullptr); renderSystem.SetGlobalUp(Nz::Vector3f::Down()); - const Ndk::EntityHandle& camera2D = world.CreateEntity(); + entt::entity camera2D = world.CreateEntity(); auto& cameraComponent2D = camera2D->AddComponent(); cameraComponent2D.SetProjectionType(Nz::ProjectionType_Orthogonal); diff --git a/src/Client/States/AbstractState.cpp b/src/Client/States/AbstractState.cpp index 408ff649..fcd45ed9 100644 --- a/src/Client/States/AbstractState.cpp +++ b/src/Client/States/AbstractState.cpp @@ -38,7 +38,7 @@ namespace bw for (auto it = m_entities.begin(); it != m_entities.end();) { - const Ndk::EntityHandle& entity = *it; + entt::entity entity = *it; if (entity) { entity->Enable(); @@ -63,7 +63,7 @@ namespace bw for (auto it = m_entities.begin(); it != m_entities.end();) { - const Ndk::EntityHandle& entity = *it; + entt::entity entity = *it; if (entity) { entity->Disable(); diff --git a/src/Client/States/AbstractState.hpp b/src/Client/States/AbstractState.hpp index 91d610e3..8f872d21 100644 --- a/src/Client/States/AbstractState.hpp +++ b/src/Client/States/AbstractState.hpp @@ -8,8 +8,7 @@ #define BURGWAR_STATES_ABSTRACTSTATE_HPP #include -#include -#include +#include #include #include #include @@ -25,9 +24,9 @@ namespace bw protected: template void ConnectSignal(T& signal, Args&&... args); - inline const Ndk::EntityHandle& CreateEntity(); + inline entt::entity CreateEntity(); template T* CreateWidget(Args&&... args); - inline void DestroyWidget(Ndk::BaseWidget* widget); + inline void DestroyWidget(Nz::BaseWidget* widget); inline StateData& GetStateData(); inline const StateData& GetStateData() const; @@ -44,7 +43,7 @@ namespace bw struct WidgetEntry { - Ndk::BaseWidget* widget; + Nz::BaseWidget* widget; bool wasVisible = true; }; diff --git a/src/Client/States/AbstractState.inl b/src/Client/States/AbstractState.inl index 4902b69b..8fe16623 100644 --- a/src/Client/States/AbstractState.inl +++ b/src/Client/States/AbstractState.inl @@ -27,16 +27,16 @@ namespace bw return widget; } - inline const Ndk::EntityHandle& AbstractState::CreateEntity() + inline entt::entity AbstractState::CreateEntity() { - const Ndk::EntityHandle& entity = m_stateData->world->CreateEntity(); + entt::entity entity = m_stateData->world->CreateEntity(); entity->Enable(m_isVisible); m_entities.emplace_back(entity); return entity; } - inline void AbstractState::DestroyWidget(Ndk::BaseWidget* widget) + inline void AbstractState::DestroyWidget(Nz::BaseWidget* widget) { auto it = std::find_if(m_widgets.begin(), m_widgets.end(), [&](const WidgetEntry& widgetEntity) { return widgetEntity.widget == widget; }); assert(it != m_widgets.end()); diff --git a/src/Client/States/Game/ConnectionState.cpp b/src/Client/States/Game/ConnectionState.cpp index 2cd08db0..74c6880e 100644 --- a/src/Client/States/Game/ConnectionState.cpp +++ b/src/Client/States/Game/ConnectionState.cpp @@ -100,7 +100,7 @@ namespace bw bwLog(GetStateData().app->GetLogger(), LogLevel::Debug, "resolving {0}:{1}...", m_resolvingData->serverName.hostname, name.port); Nz::ResolveError resolveError; - std::vector serverAddresses = Nz::IpAddress::ResolveHostname(Nz::NetProtocol_Any, m_resolvingData->serverName.hostname, Nz::String::Number(name.port), &resolveError); + std::vector serverAddresses = Nz::IpAddress::ResolveHostname(Nz::NetProtocol::Any, m_resolvingData->serverName.hostname, Nz::String::Number(name.port), &resolveError); if (serverAddresses.empty()) { m_resolvingData->result = tl::unexpected(Nz::ErrorToString(resolveError)); @@ -128,7 +128,7 @@ namespace bw ClientApp* app = GetStateData().app; auto& networkManager = app->GetReactorManager(); - bwLog(GetStateData().app->GetLogger(), LogLevel::Debug, "connecting to {0}...", address.ToString().ToStdString()); + bwLog(GetStateData().app->GetLogger(), LogLevel::Debug, "connecting to {0}...", address.ToString()); auto sessionBridge = networkManager.ConnectToServer(address, 0); if (sessionBridge) @@ -136,7 +136,7 @@ namespace bw m_clientSession->Connect(std::move(sessionBridge)); m_timeBeforeGivingUp = 10.f; - UpdateStatus("Connecting to " + address.ToString().ToStdString() + "...", Nz::Color::White); + UpdateStatus("Connecting to " + address.ToString() + "...", Nz::Color::White); } else HandleConnectionFailure(); diff --git a/src/Client/States/Game/GameState.cpp b/src/Client/States/Game/GameState.cpp index ba30b418..63aa32fc 100644 --- a/src/Client/States/Game/GameState.cpp +++ b/src/Client/States/Game/GameState.cpp @@ -10,7 +10,7 @@ namespace bw { - GameState::GameState(std::shared_ptr stateDataPtr, std::shared_ptr clientSession, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData, std::shared_ptr assetDirectory, std::shared_ptr scriptDirectory) : + GameState::GameState(std::shared_ptr stateDataPtr, std::shared_ptr clientSession, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData, std::shared_ptr assetDirectory, std::shared_ptr scriptDirectory) : AbstractState(std::move(stateDataPtr)), m_clientSession(std::move(clientSession)) { diff --git a/src/Client/States/Game/GameState.hpp b/src/Client/States/Game/GameState.hpp index 636046fc..f0df6183 100644 --- a/src/Client/States/Game/GameState.hpp +++ b/src/Client/States/Game/GameState.hpp @@ -19,7 +19,7 @@ namespace bw class GameState final : public AbstractState { public: - GameState(std::shared_ptr stateDataPtr, std::shared_ptr clientSession, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData, std::shared_ptr assetDirectory, std::shared_ptr scriptDirectory); + GameState(std::shared_ptr stateDataPtr, std::shared_ptr clientSession, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData, std::shared_ptr assetDirectory, std::shared_ptr scriptDirectory); ~GameState() = default; inline const std::shared_ptr& GetMatch(); diff --git a/src/Client/States/Game/ResourceDownloadState.cpp b/src/Client/States/Game/ResourceDownloadState.cpp index b73d1c52..57c7e59c 100644 --- a/src/Client/States/Game/ResourceDownloadState.cpp +++ b/src/Client/States/Game/ResourceDownloadState.cpp @@ -3,12 +3,12 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include #include #include #include #include #include +#include #include namespace bw @@ -191,7 +191,7 @@ namespace bw m_clientSession->Disconnect(); } - void ResourceDownloadState::RegisterFiles(const std::vector& files, const std::shared_ptr& resourceDir, const std::shared_ptr& targetDir, const std::string& cacheDir, FileMap& fileMap, bool keepInMemory) + void ResourceDownloadState::RegisterFiles(const std::vector& files, const std::shared_ptr& resourceDir, const std::shared_ptr& targetDir, const std::string& cacheDir, FileMap& fileMap, bool keepInMemory) { assert(!m_downloadManagers.empty()); @@ -209,7 +209,7 @@ namespace bw bool isFilePresent = std::visit([&](auto&& arg) { using T = std::decay_t; - if constexpr (std::is_same_v) + if constexpr (std::is_same_v) { std::size_t fileSize = arg.size(); if (fileSize != resource.size) @@ -225,7 +225,7 @@ namespace bw targetDir->StoreFile(resource.path, arg); return true; } - else if constexpr (std::is_same_v) + else if constexpr (std::is_same_v) { if (keepInMemory) { @@ -233,7 +233,7 @@ namespace bw std::vector content; Nz::File file(arg.generic_u8string()); - if (!file.Open(Nz::OpenMode_ReadOnly)) + if (!file.Open(Nz::OpenMode::ReadOnly)) return false; content.resize(file.GetSize()); @@ -263,7 +263,7 @@ namespace bw return true; } } - else if constexpr (std::is_same_v) + else if constexpr (std::is_same_v) { return false; } @@ -277,7 +277,7 @@ namespace bw } // Try to find file in cache - std::string hexChecksum = expectedChecksum.ToHex().ToStdString(); + std::string hexChecksum = expectedChecksum.ToHex(); std::filesystem::path cachePath = cacheDir / std::filesystem::u8path(resource.path); cachePath.replace_extension(hexChecksum + cachePath.extension().generic_u8string()); diff --git a/src/Client/States/Game/ResourceDownloadState.hpp b/src/Client/States/Game/ResourceDownloadState.hpp index 2e80c3b1..2d7b2dbe 100644 --- a/src/Client/States/Game/ResourceDownloadState.hpp +++ b/src/Client/States/Game/ResourceDownloadState.hpp @@ -40,7 +40,7 @@ namespace bw void OnCancelled() override; - void RegisterFiles(const std::vector& files, const std::shared_ptr& resourceDir, const std::shared_ptr& targetDir, const std::string& cacheDir, FileMap& fileMap, bool keepInMemory); + void RegisterFiles(const std::vector& files, const std::shared_ptr& resourceDir, const std::shared_ptr& targetDir, const std::string& cacheDir, FileMap& fileMap, bool keepInMemory); bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; using CancelableState::UpdateStatus; @@ -49,8 +49,8 @@ namespace bw FileMap m_assetData; FileMap m_scriptData; std::shared_ptr m_clientSession; - std::shared_ptr m_targetAssetDirectory; - std::shared_ptr m_targetScriptDirectory; + std::shared_ptr m_targetAssetDirectory; + std::shared_ptr m_targetScriptDirectory; std::vector> m_downloadManagers; Packets::AuthSuccess m_authSuccess; Packets::MatchData m_matchData; diff --git a/src/Client/States/JoinServerState.cpp b/src/Client/States/JoinServerState.cpp index 48665433..53657f35 100644 --- a/src/Client/States/JoinServerState.cpp +++ b/src/Client/States/JoinServerState.cpp @@ -106,7 +106,7 @@ namespace bw void JoinServerState::OnConnectionPressed() { - std::string serverHostname = m_serverAddressArea->GetText().ToStdString(); + std::string serverHostname = m_serverAddressArea->GetText(); if (serverHostname.empty()) { UpdateStatus("Error: blank server address", Nz::Color::Red); @@ -123,7 +123,7 @@ namespace bw long long rawPort; if (!serverPort.ToInteger(&rawPort) || rawPort <= 0 || rawPort > 0xFFFF) { - UpdateStatus("Error: " + serverPort.ToStdString() + " is not a valid port", Nz::Color::Red); + UpdateStatus("Error: " + serverPort + " is not a valid port", Nz::Color::Red); return; } @@ -147,14 +147,14 @@ namespace bw constexpr float padding = 10.f; - std::array widgets = { + std::array widgets = { m_statusLabel, m_serverAddressLayout, m_connectionButton }; float totalSize = padding * (widgets.size() - 1); - for (Ndk::BaseWidget* widget : widgets) + for (Nz::BaseWidget* widget : widgets) totalSize += widget->GetSize().y; Nz::Vector2f cursor = center; diff --git a/src/Client/States/MainMenuState.cpp b/src/Client/States/MainMenuState.cpp index d087857d..55e6b8d1 100644 --- a/src/Client/States/MainMenuState.cpp +++ b/src/Client/States/MainMenuState.cpp @@ -103,7 +103,7 @@ namespace bw constexpr float padding = 10.f; - std::array widgets = { + std::array widgets = { m_startServerButton, m_joinServerButton, m_optionButton, @@ -112,7 +112,7 @@ namespace bw float maxWidth = 0.f; float totalSize = padding * (widgets.size() - 1); - for (Ndk::BaseWidget* widget : widgets) + for (Nz::BaseWidget* widget : widgets) { Nz::Vector2f size = widget->GetSize(); @@ -123,7 +123,7 @@ namespace bw Nz::Vector2f cursor = center; cursor.y -= totalSize / 2.f; - for (Ndk::BaseWidget* widget : widgets) + for (Nz::BaseWidget* widget : widgets) { widget->Resize({ maxWidth, widget->GetHeight() }); widget->SetPosition({ 0.f, cursor.y, 0.f }); diff --git a/src/Client/States/ServerListState.cpp b/src/Client/States/ServerListState.cpp index 242d37cb..8238e4c5 100644 --- a/src/Client/States/ServerListState.cpp +++ b/src/Client/States/ServerListState.cpp @@ -30,7 +30,7 @@ namespace bw else bwLog(GetStateData().app->GetLogger(), LogLevel::Warning, "web services are not initialized, server listing will not work"); - m_serverListWidget = GetStateData().canvas->Add(); + m_serverListWidget = GetStateData().canvas->Add(); m_serverListScrollbar = CreateWidget(m_serverListWidget); m_serverListScrollbar->EnableBackground(true); @@ -148,13 +148,13 @@ namespace bw m_serverListWidget->Resize({ maxWidth, heightCursor.y }); - std::array widgets = { + std::array widgets = { m_backButton, m_directConnectButton }; float totalSize = padding * (widgets.size() - 1); - for (Ndk::BaseWidget* widget : widgets) + for (Nz::BaseWidget* widget : widgets) totalSize += widget->GetSize().x; Nz::Vector2f cursor; diff --git a/src/Client/States/ServerListState.hpp b/src/Client/States/ServerListState.hpp index c280796f..5738c05d 100644 --- a/src/Client/States/ServerListState.hpp +++ b/src/Client/States/ServerListState.hpp @@ -53,7 +53,7 @@ namespace bw bool receivedData = false; //< Did we already successfully refresh from this master server? }; - Ndk::BaseWidget* m_serverListWidget; + Nz::BaseWidget* m_serverListWidget; Ndk::ButtonWidget* m_backButton; Ndk::ButtonWidget* m_directConnectButton; Ndk::ScrollAreaWidget* m_serverListScrollbar; diff --git a/src/Client/States/StartServerState.cpp b/src/Client/States/StartServerState.cpp index 289293b3..c5284b9d 100644 --- a/src/Client/States/StartServerState.cpp +++ b/src/Client/States/StartServerState.cpp @@ -30,7 +30,7 @@ namespace bw m_statusLabel = CreateWidget(); m_statusLabel->Hide(); - m_background = CreateWidget(); + m_background = CreateWidget(); m_background->EnableBackground(true); m_background->SetBackgroundColor(Nz::Color(0, 0, 0, 100)); @@ -161,14 +161,14 @@ namespace bw { ClientApp* app = GetStateData().app; - std::string gamemode = m_gamemodeArea->GetText().ToStdString(); + std::string gamemode = m_gamemodeArea->GetText(); if (gamemode.empty()) { UpdateStatus("Error: blank gamemode", Nz::Color::Red); return; } - std::string map = m_mapArea->GetText().ToStdString(); + std::string map = m_mapArea->GetText(); if (map.empty()) { UpdateStatus("Error: blank map", Nz::Color::Red); @@ -185,7 +185,7 @@ namespace bw long long rawPort; if (!serverPort.ToInteger(&rawPort) || rawPort < 0 || rawPort > 0xFFFF) { - UpdateStatus("Error: " + serverPort.ToStdString() + " is not a valid port", Nz::Color::Red); + UpdateStatus("Error: " + serverPort + " is not a valid port", Nz::Color::Red); return; } @@ -196,7 +196,7 @@ namespace bw std::string serverDesc; if (listServer) { - serverName = m_nameArea->GetText().ToStdString(); + serverName = m_nameArea->GetText(); if (serverName.empty()) { UpdateStatus("Error: blank server name", Nz::Color::Red); @@ -209,7 +209,7 @@ namespace bw return; } - serverDesc = m_descriptionArea->GetText().ToStdString(); + serverDesc = m_descriptionArea->GetText(); if (serverDesc.size() > 1024) { UpdateStatus("Error: server description is too long", Nz::Color::Red); @@ -274,7 +274,7 @@ namespace bw constexpr float padding = 10.f; - std::array widgets = { + std::array widgets = { m_title, m_gamemodeArea, m_mapArea, @@ -286,7 +286,7 @@ namespace bw }; float totalSize = padding * (widgets.size() - 1); - for (Ndk::BaseWidget* widget : widgets) + for (Nz::BaseWidget* widget : widgets) { if (widget) totalSize += widget->GetSize().y; diff --git a/src/Client/States/StartServerState.hpp b/src/Client/States/StartServerState.hpp index dfa3453c..8c5916d0 100644 --- a/src/Client/States/StartServerState.hpp +++ b/src/Client/States/StartServerState.hpp @@ -38,7 +38,7 @@ namespace bw Ndk::BoxLayout* m_descriptionLayout; Ndk::BoxLayout* m_nameLayout; Ndk::BoxLayout* m_serverConfigLayout; - Ndk::BaseWidget* m_background; + Nz::BaseWidget* m_background; Ndk::ButtonWidget* m_backButton; Ndk::ButtonWidget* m_startServerButton; Ndk::CheckboxWidget* m_listServerCheckbox; diff --git a/src/ClientLib/Chatbox.cpp b/src/ClientLib/Chatbox.cpp index 46bf93b3..5d173702 100644 --- a/src/ClientLib/Chatbox.cpp +++ b/src/ClientLib/Chatbox.cpp @@ -116,7 +116,7 @@ namespace bw { Nz::String text = m_chatEnteringBox->GetText(); if (!text.IsEmpty()) - OnChatMessage(text.ToStdString()); + OnChatMessage(text); } void Chatbox::OnRenderTargetSizeChange(const Nz::RenderTarget* renderTarget) diff --git a/src/ClientLib/ClientConsole.cpp b/src/ClientLib/ClientConsole.cpp index 5302b85e..76fd98cb 100644 --- a/src/ClientLib/ClientConsole.cpp +++ b/src/ClientLib/ClientConsole.cpp @@ -6,7 +6,7 @@ namespace bw { - ClientConsole::ClientConsole(const Logger& logger, Nz::RenderTarget* window, Ndk::Canvas* canvas, std::shared_ptr scriptingLibrary, const std::shared_ptr& scriptDir) : + ClientConsole::ClientConsole(const Logger& logger, Nz::RenderTarget* window, Ndk::Canvas* canvas, std::shared_ptr scriptingLibrary, const std::shared_ptr& scriptDir) : Console(window, canvas), m_environment(logger, std::move(scriptingLibrary), scriptDir) { diff --git a/src/ClientLib/ClientLayer.cpp b/src/ClientLib/ClientLayer.cpp index cdd13a82..f6b4e158 100644 --- a/src/ClientLib/ClientLayer.cpp +++ b/src/ClientLib/ClientLayer.cpp @@ -245,7 +245,7 @@ namespace bw // Entity if (std::size_t elementIndex = entityStore.GetElementIndex(entityClass); elementIndex != ClientEntityStore::InvalidIndex) { - auto entity = entityStore.InstantiateEntity(*this, elementIndex, entityId, uniqueId, entityData.position, entityData.rotation, scale, properties, (parent) ? parent->GetEntity() : Ndk::EntityHandle::InvalidHandle); + auto entity = entityStore.InstantiateEntity(*this, elementIndex, entityId, uniqueId, entityData.position, entityData.rotation, scale, properties, (parent) ? parent->GetEntity() : entt::null); if (!entity) { bwLog(GetMatch().GetLogger(), LogLevel::Error, "Failed to instantiate entity {0} of type {1}", uniqueId, entityClass); @@ -485,7 +485,7 @@ namespace bw ClientLayerEntity& localEntity = *entityOpt; if (localEntity.IsPhysical()) { - const Ndk::EntityHandle& entity = localEntity.GetEntity(); + entt::entity entity = localEntity.GetEntity(); auto& entityPhys = entity->GetComponent(); entityPhys.SetMass(packet.mass, false); diff --git a/src/ClientLib/ClientLayerEntity.cpp b/src/ClientLib/ClientLayerEntity.cpp index f9f9619a..f27bf866 100644 --- a/src/ClientLib/ClientLayerEntity.cpp +++ b/src/ClientLib/ClientLayerEntity.cpp @@ -18,7 +18,7 @@ namespace bw { - ClientLayerEntity::ClientLayerEntity(ClientLayer& layer, const Ndk::EntityHandle& entity, Nz::UInt32 serverEntityId, EntityId uniqueId) : + ClientLayerEntity::ClientLayerEntity(ClientLayer& layer, entt::entity entity, Nz::UInt32 serverEntityId, EntityId uniqueId) : LayerVisualEntity(entity, layer.GetLayerIndex(), uniqueId), m_serverEntityId(serverEntityId), m_layer(layer) @@ -47,7 +47,7 @@ namespace bw { if (!m_ghostEntity) { - const Ndk::EntityHandle& ghostEntity = GetEntity()->GetWorld()->CreateEntity(); + entt::entity ghostEntity = GetEntity()->GetWorld()->CreateEntity(); ghostEntity->AddComponent(); m_ghostEntity = std::make_unique(m_layer, ghostEntity, ClientsideId, m_layer.GetClientMatch().AllocateClientUniqueId()); diff --git a/src/ClientLib/ClientMatch.cpp b/src/ClientLib/ClientMatch.cpp index 9221059e..e2061904 100644 --- a/src/ClientLib/ClientMatch.cpp +++ b/src/ClientLib/ClientMatch.cpp @@ -198,7 +198,7 @@ namespace bw m_gamemode.reset(); } - void ClientMatch::ForEachEntity(std::function func) + void ClientMatch::ForEachEntity(std::function func) { for (auto& layer : m_layers) { @@ -259,7 +259,7 @@ namespace bw void ClientMatch::InitDebugGhosts() { m_debug.emplace(); - if (m_debug->socket.Create(Nz::NetProtocol_IPv4)) + if (m_debug->socket.Create(Nz::NetProtocol::IPv4)) { m_debug->socket.EnableBlocking(false); @@ -289,7 +289,7 @@ namespace bw } } - void ClientMatch::LoadAssets(std::shared_ptr assetDir) + void ClientMatch::LoadAssets(std::shared_ptr assetDir) { if (!m_assetStore) { @@ -303,7 +303,7 @@ namespace bw } } - void ClientMatch::LoadScripts(const std::shared_ptr& scriptDir) + void ClientMatch::LoadScripts(const std::shared_ptr& scriptDir) { assert(m_assetStore); @@ -365,7 +365,7 @@ namespace bw sol::state& state = m_scriptingContext->GetLuaState(); state["engine_AnimateRotation"] = LuaFunction([&](const sol::table& entityTable, float fromAngle, float toAngle, float duration, sol::main_protected_function callback) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); m_animationManager.PushAnimation(duration, [=](float ratio) { @@ -391,7 +391,7 @@ namespace bw state["engine_AnimatePositionByOffsetSq"] = LuaFunction([&](const sol::table& entityTable, const Nz::Vector2f& fromOffset, const Nz::Vector2f& toOffset, float duration, sol::main_protected_function callback) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); m_animationManager.PushAnimation(duration, [=](float ratio) { @@ -453,7 +453,7 @@ namespace bw m_localPlayers[localIndex].inputPoller = std::move(inputPoller); }); - ForEachEntity([this](const Ndk::EntityHandle& entity) + ForEachEntity([this](entt::entity entity) { if (entity->HasComponent()) { @@ -480,16 +480,16 @@ namespace bw m_entitiesByUniqueId.emplace(uniqueId, std::move(entity)); } - const Ndk::EntityHandle& ClientMatch::RetrieveEntityByUniqueId(EntityId uniqueId) const + entt::entity ClientMatch::RetrieveEntityByUniqueId(EntityId uniqueId) const { auto it = m_entitiesByUniqueId.find(uniqueId); if (it == m_entitiesByUniqueId.end()) - return Ndk::EntityHandle::InvalidHandle; + return entt::null; return it.value()->GetEntity(); } - EntityId ClientMatch::RetrieveUniqueIdByEntity(const Ndk::EntityHandle& entity) const + EntityId ClientMatch::RetrieveUniqueIdByEntity(entt::entity entity) const { if (!entity || !entity->HasComponent()) return InvalidEntityId; @@ -1377,7 +1377,7 @@ namespace bw /*Nz::Vector2f posDiff = entityData.position - packetEntity.position; Nz::RadianAnglef rotDiff = entityData.rotation - packetEntity.rotation; - bwLog(GetLogger(), LogLevel::Debug, "Prediction error for entity #{} (position diff: {}, rotation diff: {})", uniqueId, posDiff.ToString().ToStdString(), rotDiff.ToString().ToStdString());*/ + bwLog(GetLogger(), LogLevel::Debug, "Prediction error for entity #{} (position diff: {}, rotation diff: {})", uniqueId, posDiff.ToString(), rotDiff.ToString());*/ return true; } } diff --git a/src/ClientLib/ClientSession.cpp b/src/ClientLib/ClientSession.cpp index fb95eeda..1d805fd6 100644 --- a/src/ClientLib/ClientSession.cpp +++ b/src/ClientLib/ClientSession.cpp @@ -5,10 +5,10 @@ #include #include #include -#include #include #include #include +#include #include namespace bw diff --git a/src/ClientLib/Components/SoundEmitterComponent.cpp b/src/ClientLib/Components/SoundEmitterComponent.cpp index 91f5bc4a..5bce2953 100644 --- a/src/ClientLib/Components/SoundEmitterComponent.cpp +++ b/src/ClientLib/Components/SoundEmitterComponent.cpp @@ -10,7 +10,7 @@ namespace bw { Nz::UInt32 SoundEmitterComponent::PlaySound(const Nz::SoundBufferRef& soundBuffer, const Nz::Vector3f& soundPosition, bool attachedToEntity, bool isLooping, bool isSpatialized) { - const Ndk::EntityHandle& entity = GetEntity(); + entt::entity entity = GetEntity(); if (!entity) return SoundSystem::InvalidSoundId; @@ -30,7 +30,7 @@ namespace bw if (it == m_sounds.end()) return; //< Sound can have been removed by the sound system - const Ndk::EntityHandle& entity = GetEntity(); + entt::entity entity = GetEntity(); if (entity) { auto& soundSystem = entity->GetWorld()->GetSystem(); diff --git a/src/ClientLib/Console.cpp b/src/ClientLib/Console.cpp index 335d4fb6..891c8951 100644 --- a/src/ClientLib/Console.cpp +++ b/src/ClientLib/Console.cpp @@ -15,7 +15,7 @@ namespace bw m_widget->OnCommand.Connect([this](Ndk::Console*, const Nz::String& command) { if (m_callback) - m_callback(command.ToStdString()); + m_callback(command); }); // Connect every slot diff --git a/src/ClientLib/EscapeMenu.cpp b/src/ClientLib/EscapeMenu.cpp index 583c302d..b80eb4e2 100644 --- a/src/ClientLib/EscapeMenu.cpp +++ b/src/ClientLib/EscapeMenu.cpp @@ -12,7 +12,7 @@ namespace bw EscapeMenu::EscapeMenu(ClientEditorApp& clientEditorApp, Ndk::Canvas* canvas) : m_app(clientEditorApp) { - m_backgroundWidget = canvas->Add(); + m_backgroundWidget = canvas->Add(); m_backgroundWidget->EnableBackground(true); m_backgroundWidget->SetBackgroundColor(Nz::Color(0, 0, 0, 160)); diff --git a/src/ClientLib/HttpDownloadManager.cpp b/src/ClientLib/HttpDownloadManager.cpp index 62fd3a8b..5c0fb5c5 100644 --- a/src/ClientLib/HttpDownloadManager.cpp +++ b/src/ClientLib/HttpDownloadManager.cpp @@ -200,7 +200,7 @@ namespace bw request.fileIndex = m_nextFileIndex; request.hash->Begin(); - request.file.Open(filePath, Nz::OpenMode_WriteOnly | Nz::OpenMode_Truncate); + request.file.Open(filePath, Nz::OpenMode::WriteOnly | Nz::OpenMode::Truncate); request.keepInMemory = pendingDownload.keepInMemory; m_webService.AddRequest(std::move(webRequest)); diff --git a/src/ClientLib/LocalPlayerInputController.cpp b/src/ClientLib/LocalPlayerInputController.cpp index 3586399e..d3b7f2ab 100644 --- a/src/ClientLib/LocalPlayerInputController.cpp +++ b/src/ClientLib/LocalPlayerInputController.cpp @@ -9,15 +9,15 @@ namespace bw { - std::optional LocalPlayerInputController::GenerateInputs(const Ndk::EntityHandle& entity) const + std::optional LocalPlayerInputController::GenerateInputs(entt::registry& registry, entt::entity entity) const { assert(entity); - if (!entity->HasComponent()) + LocalPlayerControlledComponent* controlledComponent = registry.try_get(entity); + if (!controlledComponent) return std::nullopt; //< Don't override inputs (for non-local player controlled entities) - LocalPlayerControlledComponent& controlledComponent = entity->GetComponent(); - ClientMatch& clientMatch = controlledComponent.GetClientMatch(); - Nz::UInt8 localPlayerIndex = controlledComponent.GetLocalPlayerIndex(); + ClientMatch& clientMatch = controlledComponent->GetClientMatch(); + Nz::UInt8 localPlayerIndex = controlledComponent->GetLocalPlayerIndex(); return clientMatch.GetLocalPlayerInputs(localPlayerIndex); } diff --git a/src/ClientLib/OptionWidget.cpp b/src/ClientLib/OptionWidget.cpp index e8adb0c5..049ae1f5 100644 --- a/src/ClientLib/OptionWidget.cpp +++ b/src/ClientLib/OptionWidget.cpp @@ -15,7 +15,7 @@ namespace bw constexpr float optionSpace = 10.f; } - OptionWidget::OptionWidget(Ndk::BaseWidget* parent, ConfigFile& playerConfig) : + OptionWidget::OptionWidget(Nz::BaseWidget* parent, ConfigFile& playerConfig) : BaseWidget(parent), m_activeSection(nullptr), m_playerConfig(playerConfig), @@ -184,7 +184,7 @@ namespace bw if (m_ignoreWidgetUpdate) return; - m_updatedValues[keyName] = text.ToStdString(); + m_updatedValues[keyName] = text; }); m_activeSection->options.emplace_back(std::move(option)); diff --git a/src/ClientLib/PacketDownloadManager.cpp b/src/ClientLib/PacketDownloadManager.cpp index 81cd7184..f4e4e5a3 100644 --- a/src/ClientLib/PacketDownloadManager.cpp +++ b/src/ClientLib/PacketDownloadManager.cpp @@ -124,7 +124,7 @@ namespace bw throw std::runtime_error("failed to create client script cache directory: " + clientFolderPath.generic_u8string()); } - if (!m_outputFile.Open(filePath, Nz::OpenMode_Truncate | Nz::OpenMode_WriteOnly)) + if (!m_outputFile.Open(filePath, Nz::OpenMode::Truncate | Nz::OpenMode::WriteOnly)) throw std::runtime_error("failed to open file " + filePath); } else if constexpr (std::is_same_v) diff --git a/src/ClientLib/Scoreboard.cpp b/src/ClientLib/Scoreboard.cpp index 375ac7a1..366c302c 100644 --- a/src/ClientLib/Scoreboard.cpp +++ b/src/ClientLib/Scoreboard.cpp @@ -11,19 +11,19 @@ namespace bw { - Scoreboard::Scoreboard(Ndk::BaseWidget* parent, const Logger& logger) : + Scoreboard::Scoreboard(Nz::BaseWidget* parent, const Logger& logger) : BaseWidget(parent), m_logger(logger) { - m_backgroundWidget = Add(); + m_backgroundWidget = Add(); m_backgroundWidget->EnableBackground(true); m_backgroundWidget->SetBackgroundColor(Nz::Color(80, 80, 80, 200)); - m_columnBackgroundWidget = Add(); + m_columnBackgroundWidget = Add(); m_columnBackgroundWidget->EnableBackground(true); m_columnBackgroundWidget->SetBackgroundColor(Nz::Color(20, 20, 20, 127)); - m_contentWidget = Add(); + m_contentWidget = Add(); m_scrollArea = Add(m_contentWidget); m_scrollArea->EnableScrollbar(true); @@ -63,7 +63,7 @@ namespace bw teamData.color = color; teamData.name = std::move(name); - teamData.background = m_contentWidget->Add(); + teamData.background = m_contentWidget->Add(); teamData.line = m_contentWidget->Add(); teamData.line->SetColor(teamData.color); @@ -85,7 +85,7 @@ namespace bw UnregisterPlayer(playerIndex); auto& playerData = m_players[playerIndex].emplace(); - playerData.background = m_contentWidget->Add(); + playerData.background = m_contentWidget->Add(); playerData.background->EnableBackground(isLocalPlayer); playerData.background->SetBackgroundColor(Nz::Color(255, 255, 255, 60)); playerData.color = color; diff --git a/src/ClientLib/Scripting/ClientEditorEntityStore.cpp b/src/ClientLib/Scripting/ClientEditorEntityStore.cpp index 96211c13..64b1c4fa 100644 --- a/src/ClientLib/Scripting/ClientEditorEntityStore.cpp +++ b/src/ClientLib/Scripting/ClientEditorEntityStore.cpp @@ -15,7 +15,7 @@ namespace bw { - bool ClientEditorEntityStore::InitializeEntity(const Ndk::EntityHandle& entity) const + bool ClientEditorEntityStore::InitializeEntity(entt::entity entity) const { auto& scriptComponent = entity->GetComponent(); if (!InitializeEntity(static_cast(*scriptComponent.GetElement()), entity)) @@ -27,14 +27,14 @@ namespace bw return true; } - const Ndk::EntityHandle& ClientEditorEntityStore::InstantiateEntity(Ndk::World& world, std::size_t entityIndex, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, const Ndk::EntityHandle& parentEntity) const + entt::entity ClientEditorEntityStore::InstantiateEntity(Ndk::World& world, std::size_t entityIndex, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, entt::entity parentEntity) const { const auto& entityClass = GetElement(entityIndex); bool hasInputs = entityClass->elementTable.get_or("HasInputs", false); bool playerControlled = entityClass->elementTable.get_or("PlayerControlled", false); - const Ndk::EntityHandle& entity = CreateEntity(world, entityClass, std::move(properties)); + entt::entity entity = CreateEntity(world, entityClass, std::move(properties)); auto& nodeComponent = entity->AddComponent(); nodeComponent.SetPosition(position); diff --git a/src/ClientLib/Scripting/ClientElementLibrary.cpp b/src/ClientLib/Scripting/ClientElementLibrary.cpp index 881ed5d3..e954ad22 100644 --- a/src/ClientLib/Scripting/ClientElementLibrary.cpp +++ b/src/ClientLib/Scripting/ClientElementLibrary.cpp @@ -34,7 +34,7 @@ namespace bw { elementTable["AddModel"] = LuaFunction([this](const sol::table& entityTable, const sol::table& parameters) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); std::string modelPath = parameters["ModelPath"]; int renderOrder = parameters.get_or("RenderOrder", 0); @@ -58,13 +58,13 @@ namespace bw if (Nz::NumberEquals(pushbackForce, 0.f)) return; - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); Ndk::World* world = entity->GetWorld(); assert(world); Ndk::EntityList hitEntities; //< FIXME: RegionQuery hit multiples entities - world->GetSystem().RegionQuery(damageZone, 0, 0xFFFFFFFF, 0xFFFFFFFF, [&](const Ndk::EntityHandle& hitEntity) + world->GetSystem().RegionQuery(damageZone, 0, 0xFFFFFFFF, 0xFFFFFFFF, [&](entt::entity hitEntity) { if (hitEntities.Has(hitEntity)) return; @@ -81,7 +81,7 @@ namespace bw elementTable["AddSprite"] = LuaFunction([this](const sol::table& entityTable, const sol::table& parameters) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); std::string texturePath = parameters.get_or("TexturePath", std::string{}); int renderOrder = parameters.get_or("RenderOrder", 0); @@ -166,7 +166,7 @@ namespace bw elementTable["AddText"] = LuaFunction([this](const sol::table& entityTable, const sol::table& parameters) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); std::string fontName = parameters.get_or("Font", std::string{}); int renderOrder = parameters.get_or("RenderOrder", 0); @@ -226,7 +226,7 @@ namespace bw elementTable["GetGlobalBounds"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); auto& visualComponent = entity->GetComponent(); const auto& layerVisualHandle = visualComponent.GetLayerVisual(); @@ -244,14 +244,14 @@ namespace bw elementTable["GetLayerIndex"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); return entity->GetComponent().GetLayerIndex(); }); elementTable["GetLocalBounds"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); auto& visualComponent = entity->GetComponent(); const auto& layerVisualHandle = visualComponent.GetLayerVisual(); @@ -264,7 +264,7 @@ namespace bw elementTable["GetOwner"] = LuaFunction([](sol::this_state s, const sol::table& table) -> sol::object { - Ndk::EntityHandle entity = AssertScriptEntity(table); + entt::entity entity = AssertScriptEntity(table); if (!entity->HasComponent()) return sol::nil; @@ -274,7 +274,7 @@ namespace bw elementTable["GetProperty"] = LuaFunction([](sol::this_state s, const sol::table& table, const std::string& propertyName) -> sol::object { - Ndk::EntityHandle entity = AssertScriptEntity(table); + entt::entity entity = AssertScriptEntity(table); auto& entityScript = entity->GetComponent(); @@ -298,7 +298,7 @@ namespace bw elementTable["PlaySound"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, const std::string& soundPath, bool isAttachedToEntity, bool isLooping, bool isSpatialized) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); auto& entityMatch = entity->GetComponent(); const Nz::SoundBufferRef& soundBuffer = m_assetStore.GetSoundBuffer(soundPath); @@ -322,7 +322,7 @@ namespace bw }); } - void ClientElementLibrary::SetScale(const Ndk::EntityHandle& entity, float newScale) + void ClientElementLibrary::SetScale(entt::entity entity, float newScale) { auto& visualComponent = entity->GetComponent(); visualComponent.GetLayerVisual()->UpdateScale(newScale); @@ -330,7 +330,7 @@ namespace bw if (entity->HasComponent()) { auto& wielderComponent = entity->GetComponent(); - for (const Ndk::EntityHandle& weapon : wielderComponent.GetWeapons()) + for (entt::entity weapon : wielderComponent.GetWeapons()) SetScale(weapon, newScale); } } diff --git a/src/ClientLib/Scripting/ClientEntityLibrary.cpp b/src/ClientLib/Scripting/ClientEntityLibrary.cpp index 0907c697..9a7a8877 100644 --- a/src/ClientLib/Scripting/ClientEntityLibrary.cpp +++ b/src/ClientLib/Scripting/ClientEntityLibrary.cpp @@ -33,7 +33,7 @@ namespace bw RegisterClientLibrary(elementMetatable); } - void ClientEntityLibrary::InitRigidBody(lua_State* L, const Ndk::EntityHandle& entity, float mass) + void ClientEntityLibrary::InitRigidBody(lua_State* L, entt::entity entity, float mass) { SharedEntityLibrary::InitRigidBody(L, entity, mass); @@ -45,7 +45,7 @@ namespace bw { elementMetatable["AddLayer"] = LuaFunction([](sol::this_state L, const sol::table& entityTable, const sol::table& parameters) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); auto& clientMatch = entity->GetComponent().GetClientMatch(); @@ -66,7 +66,7 @@ namespace bw elementMetatable["AddTilemap"] = LuaFunction([this](const sol::table& entityTable, const Nz::Vector2ui& mapSize, const Nz::Vector2f& cellSize, const sol::table& content, const std::vector& tiles, int renderOrder = 0) -> sol::optional { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); // Compute tilemap tsl::hopscotch_map materials; @@ -137,7 +137,7 @@ namespace bw elementMetatable["ClearLayers"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) entity->GetComponent().Clear(); diff --git a/src/ClientLib/Scripting/ClientEntityStore.cpp b/src/ClientLib/Scripting/ClientEntityStore.cpp index 62aedd5b..2bd1774a 100644 --- a/src/ClientLib/Scripting/ClientEntityStore.cpp +++ b/src/ClientLib/Scripting/ClientEntityStore.cpp @@ -10,9 +10,9 @@ namespace bw { - std::optional ClientEntityStore::InstantiateEntity(ClientLayer& layer, std::size_t elementIndex, Nz::UInt32 serverId, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, const PropertyValueMap& properties, const Ndk::EntityHandle& parentEntity) const + std::optional ClientEntityStore::InstantiateEntity(ClientLayer& layer, std::size_t elementIndex, Nz::UInt32 serverId, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, const PropertyValueMap& properties, entt::entity parentEntity) const { - const Ndk::EntityHandle& entity = ClientEditorEntityStore::InstantiateEntity(layer.GetWorld(), elementIndex, position, rotation, scale, properties, parentEntity); + entt::entity entity = ClientEditorEntityStore::InstantiateEntity(layer.GetWorld(), elementIndex, position, rotation, scale, properties, parentEntity); if (!entity) return std::nullopt; diff --git a/src/ClientLib/Scripting/ClientScriptingLibrary.cpp b/src/ClientLib/Scripting/ClientScriptingLibrary.cpp index dccad085..a8d104a6 100644 --- a/src/ClientLib/Scripting/ClientScriptingLibrary.cpp +++ b/src/ClientLib/Scripting/ClientScriptingLibrary.cpp @@ -133,7 +133,7 @@ namespace bw if (!entityOpt) TriggerLuaError(L, "failed to create \"" + entityType + "\""); - const Ndk::EntityHandle& entity = layer.RegisterEntity(std::move(entityOpt.value())).GetEntity(); + entt::entity entity = layer.RegisterEntity(std::move(entityOpt.value())).GetEntity(); if (lifeOwner) { @@ -250,7 +250,7 @@ namespace bw TriggerLuaArgError(L, 2, "Invalid particle type \"" + particleType + "\""); Ndk::World& world = match.GetRenderWorld(); - const Ndk::EntityHandle& particleGroupEntity = world.CreateEntity(); + entt::entity particleGroupEntity = world.CreateEntity(); auto& particleGroup = particleGroupEntity->AddComponent(maxParticleCount, layout); particleGroup.SetRenderer(Nz::ParticleFunctionRenderer::New([](const Nz::ParticleGroup& /*group*/, const Nz::ParticleMapper& /*mapper*/, unsigned int /*startId*/, unsigned int /*endId*/, Nz::AbstractRenderQueue* /*renderQueue*/) @@ -288,17 +288,17 @@ namespace bw bool loaded = std::visit([&](auto&& arg) { using T = std::decay_t; - if constexpr (std::is_same_v) + if constexpr (std::is_same_v) { bwLog(m_logger, LogLevel::Info, "Loading asset from memory"); return music.OpenFromMemory(arg.data(), arg.size()); } - else if constexpr (std::is_same_v) + else if constexpr (std::is_same_v) { bwLog(m_logger, LogLevel::Info, "Loading asset from {}", arg.generic_u8string()); return music.OpenFromFile(arg.generic_u8string()); } - else if constexpr (std::is_same_v) + else if constexpr (std::is_same_v) { return false; } @@ -382,7 +382,7 @@ namespace bw if (controlledEntityId == InvalidEntityId) return sol::nil; - const Ndk::EntityHandle& controlledEntity = GetMatch().RetrieveEntityByUniqueId(controlledEntityId); + entt::entity controlledEntity = GetMatch().RetrieveEntityByUniqueId(controlledEntityId); if (!controlledEntity) return sol::nil; diff --git a/src/ClientLib/Scripting/ClientWeaponLibrary.cpp b/src/ClientLib/Scripting/ClientWeaponLibrary.cpp index 1ba158fa..1b296225 100644 --- a/src/ClientLib/Scripting/ClientWeaponLibrary.cpp +++ b/src/ClientLib/Scripting/ClientWeaponLibrary.cpp @@ -30,7 +30,7 @@ namespace bw { auto shootFunc = [](const sol::table& weaponTable, Nz::Vector2f startPos, Nz::Vector2f direction, Nz::UInt16 /*damage*/, float pushbackForce = 0.f) { - Ndk::EntityHandle entity = AssertScriptEntity(weaponTable); + entt::entity entity = AssertScriptEntity(weaponTable); Ndk::World* world = entity->GetWorld(); assert(world); @@ -44,7 +44,7 @@ namespace bw { hitDistance *= hitInfo.fraction; - const Ndk::EntityHandle& hitEntity = hitInfo.body; + entt::entity hitEntity = hitInfo.body; if (hitEntity->HasComponent()) { diff --git a/src/ClientLib/Scripting/ClientWeaponStore.cpp b/src/ClientLib/Scripting/ClientWeaponStore.cpp index 2bdc38de..d1fc08e6 100644 --- a/src/ClientLib/Scripting/ClientWeaponStore.cpp +++ b/src/ClientLib/Scripting/ClientWeaponStore.cpp @@ -18,7 +18,7 @@ namespace bw { - std::optional ClientWeaponStore::InstantiateWeapon(ClientLayer& layer, std::size_t entityIndex, Nz::UInt32 serverId, EntityId uniqueId, const PropertyValueMap& properties, const Ndk::EntityHandle& parent) + std::optional ClientWeaponStore::InstantiateWeapon(ClientLayer& layer, std::size_t entityIndex, Nz::UInt32 serverId, EntityId uniqueId, const PropertyValueMap& properties, entt::entity parent) { const auto& weaponClass = GetElement(entityIndex); @@ -33,7 +33,7 @@ namespace bw Nz::Vector2f burgerSize = sprite->GetSize(); sprite->SetOrigin(weaponClass->spriteOrigin); - const Ndk::EntityHandle& weapon = CreateEntity(layer.GetWorld(), weaponClass, properties); + entt::entity weapon = CreateEntity(layer.GetWorld(), weaponClass, properties); ClientLayerEntity layerEntity(layer, weapon, serverId, uniqueId); layerEntity.AttachRenderable(sprite, Nz::Matrix4f::Identity(), -1); diff --git a/src/ClientLib/Scripting/ParticleGroup.cpp b/src/ClientLib/Scripting/ParticleGroup.cpp index 45810f3d..57f56cf1 100644 --- a/src/ClientLib/Scripting/ParticleGroup.cpp +++ b/src/ClientLib/Scripting/ParticleGroup.cpp @@ -10,7 +10,7 @@ namespace bw { - ParticleGroup::ParticleGroup(const ParticleRegistry& particleRegistry, const Ndk::EntityHandle& particleGroup) : + ParticleGroup::ParticleGroup(const ParticleRegistry& particleRegistry, entt::entity particleGroup) : m_entity(particleGroup), m_registry(particleRegistry) { diff --git a/src/ClientLib/Systems/FrameCallbackSystem.cpp b/src/ClientLib/Systems/FrameCallbackSystem.cpp index f7ce2be2..fb93b3c0 100644 --- a/src/ClientLib/Systems/FrameCallbackSystem.cpp +++ b/src/ClientLib/Systems/FrameCallbackSystem.cpp @@ -33,7 +33,7 @@ namespace bw void FrameCallbackSystem::OnUpdate(float /*elapsedTime*/) { - for (const Ndk::EntityHandle& entity : m_frameUpdateEntities) + for (entt::entity entity : m_frameUpdateEntities) { auto& scriptComponent = entity->GetComponent(); diff --git a/src/ClientLib/Systems/PostFrameCallbackSystem.cpp b/src/ClientLib/Systems/PostFrameCallbackSystem.cpp index 15a01256..3fd648bd 100644 --- a/src/ClientLib/Systems/PostFrameCallbackSystem.cpp +++ b/src/ClientLib/Systems/PostFrameCallbackSystem.cpp @@ -33,7 +33,7 @@ namespace bw void PostFrameCallbackSystem::OnUpdate(float /*elapsedTime*/) { - for (const Ndk::EntityHandle& entity : m_frameUpdateEntities) + for (entt::entity entity : m_frameUpdateEntities) { auto& scriptComponent = entity->GetComponent(); diff --git a/src/ClientLib/Systems/SoundSystem.cpp b/src/ClientLib/Systems/SoundSystem.cpp index 186fab3a..9b29ce98 100644 --- a/src/ClientLib/Systems/SoundSystem.cpp +++ b/src/ClientLib/Systems/SoundSystem.cpp @@ -132,7 +132,7 @@ namespace bw m_playingSounds.erase(soundEntry.playingSoundId); } - for (const Ndk::EntityHandle& movableEntity : m_movableEntities) + for (entt::entity movableEntity : m_movableEntities) { auto& nodeComponent = movableEntity->GetComponent(); auto& soundEmitterComponent = movableEntity->GetComponent(); diff --git a/src/ClientLib/Systems/VisualInterpolationSystem.cpp b/src/ClientLib/Systems/VisualInterpolationSystem.cpp index 6422ba7e..45c11636 100644 --- a/src/ClientLib/Systems/VisualInterpolationSystem.cpp +++ b/src/ClientLib/Systems/VisualInterpolationSystem.cpp @@ -30,7 +30,7 @@ namespace bw float C = 10.f; float factor = 1.f - std::exp(-elapsedTime * C); - for (const Ndk::EntityHandle& entity : GetEntities()) + for (entt::entity entity : GetEntities()) { auto& entityLerp = entity->GetComponent(); auto& entityNode = entity->GetComponent(); diff --git a/src/CoreLib/AssetStore.cpp b/src/CoreLib/AssetStore.cpp index 4abeab28..2b91ea34 100644 --- a/src/CoreLib/AssetStore.cpp +++ b/src/CoreLib/AssetStore.cpp @@ -13,7 +13,7 @@ namespace bw m_images.clear(); } - const Nz::ImageRef& AssetStore::GetImage(const std::string& imagePath) const + const std::shared_ptr& AssetStore::GetImage(const std::string& imagePath) const { Nz::ImageParams loaderParameters; diff --git a/src/CoreLib/BasicPlayerMovementController.cpp b/src/CoreLib/BasicPlayerMovementController.cpp index 1a171010..19460a0d 100644 --- a/src/CoreLib/BasicPlayerMovementController.cpp +++ b/src/CoreLib/BasicPlayerMovementController.cpp @@ -10,7 +10,7 @@ namespace bw { - bool BasicPlayerMovementController::PreSolveCollision(PlayerMovementComponent& playerMovement, const Ndk::EntityHandle& /*collisionBody*/, Nz::Arbiter2D& arbiter) const + bool BasicPlayerMovementController::PreSolveCollision(PlayerMovementComponent& playerMovement, entt::entity /*collisionBody*/, Nz::Arbiter2D& arbiter) const { Nz::Vector2f up = Nz::Vector2f::UnitY(); diff --git a/src/CoreLib/BurgApp.cpp b/src/CoreLib/BurgApp.cpp index e8d6c9da..db57aaf9 100644 --- a/src/CoreLib/BurgApp.cpp +++ b/src/CoreLib/BurgApp.cpp @@ -27,7 +27,6 @@ #include #include #include -#include #include #include @@ -64,27 +63,6 @@ namespace bw m_logger.RegisterSink(std::make_shared()); m_logger.SetMinimumLogLevel(LogLevel::Debug); - Ndk::InitializeComponent("Anim"); - Ndk::InitializeComponent("CollData"); - Ndk::InitializeComponent("Cooldown"); - Ndk::InitializeComponent("EntOwner"); - Ndk::InitializeComponent("Health"); - Ndk::InitializeComponent("Input"); - Ndk::InitializeComponent("Match"); - Ndk::InitializeComponent("NetSync"); - Ndk::InitializeComponent("Owner"); - Ndk::InitializeComponent("PlyCtrl"); - Ndk::InitializeComponent("PlyMvt"); - Ndk::InitializeComponent("Script"); - Ndk::InitializeComponent("Weapon"); - Ndk::InitializeComponent("WepnWiel"); - Ndk::InitializeSystem(); - Ndk::InitializeSystem(); - Ndk::InitializeSystem(); - Ndk::InitializeSystem(); - Ndk::InitializeSystem(); - Ndk::InitializeSystem(); - std::string error; if (WebService::Initialize(&error)) { diff --git a/src/CoreLib/Components/AnimationComponent.cpp b/src/CoreLib/Components/AnimationComponent.cpp index 0dbf8bce..3d0c56fd 100644 --- a/src/CoreLib/Components/AnimationComponent.cpp +++ b/src/CoreLib/Components/AnimationComponent.cpp @@ -30,6 +30,4 @@ namespace bw m_playingAnimation.reset(); } } - - Ndk::ComponentIndex AnimationComponent::componentIndex; } diff --git a/src/CoreLib/Components/CollisionDataComponent.cpp b/src/CoreLib/Components/CollisionDataComponent.cpp index eb8ffc36..6c778125 100644 --- a/src/CoreLib/Components/CollisionDataComponent.cpp +++ b/src/CoreLib/Components/CollisionDataComponent.cpp @@ -7,7 +7,7 @@ namespace bw { - Nz::Collider2DRef CollisionDataComponent::BuildCollider(float scale) const + std::shared_ptr CollisionDataComponent::BuildCollider(float scale) const { if (m_colliders.empty()) { @@ -23,29 +23,29 @@ namespace bw { // Multiple colliders - std::vector simpleColliders; + std::vector> simpleColliders; simpleColliders.reserve(m_colliders.size()); for (const auto& collider : m_colliders) simpleColliders.emplace_back(ToCollider(collider, scale)); - Nz::CompoundCollider2DRef compound = Nz::CompoundCollider2D::New(std::move(simpleColliders)); + std::shared_ptr compound = std::make_shared(std::move(simpleColliders)); compound->OverridesCollisionProperties(false); return compound; } } - Nz::Collider2DRef CollisionDataComponent::ToCollider(const Collider& collider, float scale) + std::shared_ptr CollisionDataComponent::ToCollider(const Collider& collider, float scale) { - return std::visit([&](auto&& arg) -> Nz::Collider2DRef + return std::visit([&](auto&& arg) -> std::shared_ptr { using T = std::decay_t; - Nz::Collider2DRef collider; + std::shared_ptr collider; if constexpr (std::is_same_v) - collider = Nz::CircleCollider2D::New(arg.radius * scale, arg.offset * scale); + collider = std::make_shared(arg.radius * scale, arg.offset * scale); else if constexpr (std::is_same_v) { Nz::Rectf scaledRect = arg.data; @@ -54,10 +54,10 @@ namespace bw scaledRect.width *= scale; scaledRect.height *= scale; - collider = Nz::BoxCollider2D::New(scaledRect); + collider = std::make_shared(scaledRect); } else if constexpr (std::is_same_v) - collider = Nz::SegmentCollider2D::New(arg.from * scale, arg.fromNeighbor * scale, arg.to * scale, arg.toNeighbor * scale); + collider = std::make_shared(arg.from * scale, arg.fromNeighbor * scale, arg.to * scale, arg.toNeighbor * scale); else static_assert(AlwaysFalse::value, "non-exhaustive visitor"); @@ -71,7 +71,5 @@ namespace bw }, collider); } - - Ndk::ComponentIndex CollisionDataComponent::componentIndex; } diff --git a/src/CoreLib/Components/CooldownComponent.cpp b/src/CoreLib/Components/CooldownComponent.cpp deleted file mode 100644 index 516ee328..00000000 --- a/src/CoreLib/Components/CooldownComponent.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - Ndk::ComponentIndex CooldownComponent::componentIndex; -} diff --git a/src/CoreLib/Components/EntityOwnerComponent.cpp b/src/CoreLib/Components/EntityOwnerComponent.cpp deleted file mode 100644 index d93ea1b4..00000000 --- a/src/CoreLib/Components/EntityOwnerComponent.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - Ndk::ComponentIndex EntityOwnerComponent::componentIndex; -} diff --git a/src/CoreLib/Components/InputComponent.cpp b/src/CoreLib/Components/InputComponent.cpp deleted file mode 100644 index 15e6d470..00000000 --- a/src/CoreLib/Components/InputComponent.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - Ndk::ComponentIndex InputComponent::componentIndex; -} diff --git a/src/CoreLib/Components/MatchComponent.cpp b/src/CoreLib/Components/MatchComponent.cpp deleted file mode 100644 index f5da1f7a..00000000 --- a/src/CoreLib/Components/MatchComponent.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - Ndk::ComponentIndex MatchComponent::componentIndex; -} diff --git a/src/CoreLib/Components/NetworkSyncComponent.cpp b/src/CoreLib/Components/NetworkSyncComponent.cpp deleted file mode 100644 index 4a798124..00000000 --- a/src/CoreLib/Components/NetworkSyncComponent.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - Ndk::ComponentIndex NetworkSyncComponent::componentIndex; -} diff --git a/src/CoreLib/Components/OwnerComponent.cpp b/src/CoreLib/Components/OwnerComponent.cpp deleted file mode 100644 index a5174f78..00000000 --- a/src/CoreLib/Components/OwnerComponent.cpp +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - Ndk::ComponentIndex OwnerComponent::componentIndex; -} - diff --git a/src/CoreLib/Components/PlayerControlledComponent.cpp b/src/CoreLib/Components/PlayerControlledComponent.cpp deleted file mode 100644 index a8876006..00000000 --- a/src/CoreLib/Components/PlayerControlledComponent.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - Ndk::ComponentIndex PlayerControlledComponent::componentIndex; -} diff --git a/src/CoreLib/Components/PlayerMovementComponent.cpp b/src/CoreLib/Components/PlayerMovementComponent.cpp deleted file mode 100644 index 9300f67c..00000000 --- a/src/CoreLib/Components/PlayerMovementComponent.cpp +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - Ndk::ComponentIndex PlayerMovementComponent::componentIndex; -} - diff --git a/src/CoreLib/Components/ScriptComponent.cpp b/src/CoreLib/Components/ScriptComponent.cpp index c5bb62ef..c4460b3f 100644 --- a/src/CoreLib/Components/ScriptComponent.cpp +++ b/src/CoreLib/Components/ScriptComponent.cpp @@ -13,25 +13,18 @@ namespace bw m_context(std::move(context)), m_nextCallbackId(m_element->nextCallbackId), m_entityTable(std::move(entityTable)), - m_logger(Ndk::EntityHandle::InvalidHandle, logger), m_properties(std::move(properties)), m_timeBeforeTick(0.f) { + m_logger = std::make_unique(entt::null, logger); } ScriptComponent::~ScriptComponent() = default; - void ScriptComponent::UpdateEntity(const Ndk::EntityHandle& entity) + void ScriptComponent::UpdateEntity(entt::entity entity) { m_entityTable["_Entity"] = entity; - m_logger.UpdateEntity(entity); + m_logger->UpdateEntity(entity); } - - void ScriptComponent::OnAttached() - { - UpdateEntity(m_entity); - } - - Ndk::ComponentIndex ScriptComponent::componentIndex; } diff --git a/src/CoreLib/Components/WeaponComponent.cpp b/src/CoreLib/Components/WeaponComponent.cpp deleted file mode 100644 index 87092e9c..00000000 --- a/src/CoreLib/Components/WeaponComponent.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - Ndk::ComponentIndex WeaponComponent::componentIndex; -} diff --git a/src/CoreLib/Components/WeaponWielderComponent.cpp b/src/CoreLib/Components/WeaponWielderComponent.cpp index 37ef3d34..ccf21117 100644 --- a/src/CoreLib/Components/WeaponWielderComponent.cpp +++ b/src/CoreLib/Components/WeaponWielderComponent.cpp @@ -13,13 +13,13 @@ namespace bw if (HasWeapon(weaponClass)) return NoWeapon; - Ndk::EntityHandle weapon = callback(weaponClass); - if (!weapon) + entt::entity weapon = callback(weaponClass); + if (weapon == entt::null) return NoWeapon; //FIXME: New weapons should be resized to match the player size - assert(weapon->HasComponent()); + assert(GetRegistry().try_get(weapon)); std::size_t weaponIndex = m_weapons.size(); m_weapons.emplace_back(weapon); @@ -29,7 +29,7 @@ namespace bw return weaponIndex; } - void WeaponWielderComponent::OverrideEntities(const std::function& callback) + void WeaponWielderComponent::OverrideEntities(const std::function& callback) { for (auto& weapon : m_weapons) callback(weapon); @@ -65,17 +65,16 @@ namespace bw assert(weaponId < m_weapons.size() || weaponId == NoWeapon); if (m_activeWeaponIndex != weaponId) { + auto& registry = GetRegistry(); + if (m_activeWeaponIndex != NoWeapon) { - const Ndk::EntityHandle& previousWeapon = m_weapons[m_activeWeaponIndex]; - auto& weaponComponent = previousWeapon->GetComponent(); + entt::entity previousWeapon = m_weapons[m_activeWeaponIndex]; + auto& weaponComponent = registry.get(previousWeapon); weaponComponent.SetActive(false); - if (previousWeapon->HasComponent()) - { - auto& weaponScript = previousWeapon->GetComponent(); - weaponScript.ExecuteCallback(); - } + if (ScriptComponent* scriptComponent = registry.try_get(previousWeapon)) + scriptComponent->ExecuteCallback(); } OnNewWeaponSelection(this, weaponId); @@ -83,18 +82,13 @@ namespace bw if (m_activeWeaponIndex != NoWeapon) { - const Ndk::EntityHandle& newWeapon = m_weapons[m_activeWeaponIndex]; - auto& weaponComponent = newWeapon->GetComponent(); + entt::entity newWeapon = m_weapons[m_activeWeaponIndex]; + auto& weaponComponent = registry.get(newWeapon); weaponComponent.SetActive(true); - if (newWeapon->HasComponent()) - { - auto& weaponScript = newWeapon->GetComponent(); - weaponScript.ExecuteCallback(); - } + if (ScriptComponent* scriptComponent = registry.try_get(newWeapon)) + scriptComponent->ExecuteCallback(); } } } - - Ndk::ComponentIndex WeaponWielderComponent::componentIndex; } diff --git a/src/CoreLib/CustomInputController.cpp b/src/CoreLib/CustomInputController.cpp index b99445ae..423838be 100644 --- a/src/CoreLib/CustomInputController.cpp +++ b/src/CoreLib/CustomInputController.cpp @@ -9,17 +9,16 @@ namespace bw { - std::optional CustomInputController::GenerateInputs(const Ndk::EntityHandle& entity) const + std::optional CustomInputController::GenerateInputs(entt::registry& registry, entt::entity entity) const { - assert(entity); - auto entityTable = TranslateEntityToLua(entity); + auto entityTable = TranslateEntityToLua(registry, entity); if (!entityTable) return std::nullopt; sol::protected_function_result result = m_callback(*entityTable); if (!result.valid()) { - auto& entityScript = entity->GetComponent(); + auto& entityScript = registry.get(entity); sol::error err = result; bwLog(entityScript.GetLogger(), LogLevel::Error, "CustomInputController failed: {}", err.what()); @@ -29,7 +28,7 @@ namespace bw auto inputsOpt = result.get>(); if (!inputsOpt) { - auto& entityScript = entity->GetComponent(); + auto& entityScript = registry.get(entity); bwLog(entityScript.GetLogger(), LogLevel::Error, "CustomInputController must return players inputs"); return PlayerInputData{}; diff --git a/src/CoreLib/LogSystem/EntityLogger.cpp b/src/CoreLib/LogSystem/EntityLogger.cpp index 55752e47..ef0fa8cc 100644 --- a/src/CoreLib/LogSystem/EntityLogger.cpp +++ b/src/CoreLib/LogSystem/EntityLogger.cpp @@ -11,8 +11,8 @@ namespace bw { const EntityLogContext& entityContext = static_cast(context); - if (entityContext.entity) - content = "[Entity " + std::to_string(entityContext.entity->GetId()) + "] " + content; + if (entityContext.entity != entt::null) + content = "[Entity " + std::to_string(static_cast(entityContext.entity)) + "] " + content; else content = "[Entity ] " + content; diff --git a/src/CoreLib/LogSystem/Logger.cpp b/src/CoreLib/LogSystem/Logger.cpp index 8c5a9d8f..b6303f50 100644 --- a/src/CoreLib/LogSystem/Logger.cpp +++ b/src/CoreLib/LogSystem/Logger.cpp @@ -37,9 +37,9 @@ namespace bw return true; } - LogContext* Logger::NewContext(Nz::MemoryPool& pool) const + LogContext* Logger::NewContext() const { - return AllocateContext(pool); + return AllocateContext(); } void Logger::InitializeContext(LogContext& context) const @@ -104,6 +104,6 @@ namespace bw void Logger::FreeContext(LogContext* context) const { - m_contextPool.Delete(context); + delete context; } } diff --git a/src/CoreLib/LogSystem/MatchLogger.cpp b/src/CoreLib/LogSystem/MatchLogger.cpp index 6e3529b2..50ecf5b2 100644 --- a/src/CoreLib/LogSystem/MatchLogger.cpp +++ b/src/CoreLib/LogSystem/MatchLogger.cpp @@ -24,9 +24,9 @@ namespace bw Logger::OverrideContent(context, content); } - LogContext* MatchLogger::NewContext(Nz::MemoryPool& pool) const + LogContext* MatchLogger::NewContext() const { - return AllocateContext(pool); + return AllocateContext(); } void MatchLogger::InitializeContext(LogContext& context) const diff --git a/src/CoreLib/Map.cpp b/src/CoreLib/Map.cpp index b5f71938..35a81e41 100644 --- a/src/CoreLib/Map.cpp +++ b/src/CoreLib/Map.cpp @@ -105,12 +105,12 @@ namespace bw bool Map::Compile(const std::filesystem::path& outputPath) { - Nz::File infoFile(outputPath.generic_u8string(), Nz::OpenMode_WriteOnly | Nz::OpenMode_Truncate); + Nz::File infoFile(outputPath.generic_u8string(), Nz::OpenMode::WriteOnly | Nz::OpenMode::Truncate); if (!infoFile.IsOpen()) return false; Nz::ByteStream stream(&infoFile); - stream.SetDataEndianness(Nz::Endianness_LittleEndian); + stream.SetDataEndianness(Nz::Endianness::LittleEndian); stream.Write("Burgrmap", 8); stream << MapFileVersion; @@ -233,7 +233,7 @@ namespace bw std::string content = Serialize(*this).dump(1, '\t'); - Nz::File infoFile((mapFolderPath / "info.json").generic_u8string(), Nz::OpenMode_WriteOnly | Nz::OpenMode_Truncate); + Nz::File infoFile((mapFolderPath / "info.json").generic_u8string(), Nz::OpenMode::WriteOnly | Nz::OpenMode::Truncate); if (!infoFile.IsOpen()) return false; @@ -447,14 +447,14 @@ namespace bw void Map::LoadFromBinaryInternal(const std::filesystem::path& mapFile) { - Nz::File infoFile(mapFile.generic_u8string(), Nz::OpenMode_ReadOnly); + Nz::File infoFile(mapFile.generic_u8string(), Nz::OpenMode::ReadOnly); if (!infoFile.IsOpen()) throw std::runtime_error("failed to open map file"); - Nz::ErrorFlags errFlags(Nz::ErrorFlag_ThrowException); + Nz::ErrorFlags errFlags(Nz::ErrorMode::ThrowException); Nz::ByteStream stream(&infoFile); - stream.SetDataEndianness(Nz::Endianness_LittleEndian); + stream.SetDataEndianness(Nz::Endianness::LittleEndian); std::array signature; if (stream.Read(signature.data(), signature.size()) != signature.size()) @@ -605,7 +605,7 @@ namespace bw { std::vector content; - Nz::File infoFile((mapFolder / "info.json").generic_u8string(), Nz::OpenMode_ReadOnly); + Nz::File infoFile((mapFolder / "info.json").generic_u8string(), Nz::OpenMode::ReadOnly); if (!infoFile.IsOpen()) throw std::runtime_error("failed to open info.json file"); @@ -629,7 +629,7 @@ namespace bw std::string filepathStr = filepath.generic_u8string(); Nz::File file(filepath.generic_u8string()); - if (!file.Open(Nz::OpenMode_ReadOnly)) + if (!file.Open(Nz::OpenMode::ReadOnly)) throw std::runtime_error("failed to open map script " + filepathStr); content.resize(file.GetSize()); diff --git a/src/CoreLib/MasterServerEntry.cpp b/src/CoreLib/MasterServerEntry.cpp index f7ba09a6..ebb28616 100644 --- a/src/CoreLib/MasterServerEntry.cpp +++ b/src/CoreLib/MasterServerEntry.cpp @@ -115,7 +115,7 @@ namespace bw bwLog(m_match.GetLogger(), LogLevel::Error, "failed to register ipv4 to master server {0}: {1}", m_masterServerURL, result.GetErrorMessage()); }); - request->ForceProtocol(Nz::NetProtocol_IPv4); //< Just in case + request->ForceProtocol(Nz::NetProtocol::IPv4); //< Just in case nlohmann::json requestData; requestData["update_token"] = updateToken; diff --git a/src/CoreLib/Match.cpp b/src/CoreLib/Match.cpp index f1b68e40..86579409 100644 --- a/src/CoreLib/Match.cpp +++ b/src/CoreLib/Match.cpp @@ -177,13 +177,12 @@ namespace bw return player; } - void Match::ForEachEntity(std::function func) + void Match::ForEachEntity(tl::function_ref func) { for (LayerIndex i = 0; i < m_terrain->GetLayerCount(); ++i) { auto& layer = m_terrain->GetLayer(i); - for (const Ndk::EntityHandle& entity : layer.GetWorld().GetEntities()) - func(entity); + layer.GetWorld().each(func); } } @@ -257,7 +256,7 @@ namespace bw void Match::InitDebugGhosts() { m_debug.emplace(Debug{}); //< Weird clang bug - if (m_debug->socket.Create(Nz::NetProtocol_IPv4)) + if (m_debug->socket.Create(Nz::NetProtocol::IPv4)) m_debug->socket.EnableBlocking(false); else { @@ -271,18 +270,18 @@ namespace bw if (m_clientAssets.find(assetPath) != m_clientAssets.end()) return; - VirtualDirectory::Entry entry; + Nz::VirtualDirectory::Entry entry; if (!m_assetDirectory->GetEntry(assetPath, &entry)) throw std::runtime_error(assetPath + " is not a file"); std::vector content; - if (!std::holds_alternative(entry)) + if (!std::holds_alternative(entry)) throw std::runtime_error(assetPath + " is not a file"); - std::filesystem::path filepath = std::get(entry); + std::filesystem::path filepath = std::get(entry); Nz::UInt64 assetSize = std::filesystem::file_size(filepath); - Nz::ByteArray assetHash = Nz::File::ComputeHash(Nz::HashType_SHA1, filepath.generic_u8string()); + Nz::ByteArray assetHash = Nz::File::ComputeHash(Nz::HashType::SHA1, filepath.generic_u8string()); RegisterClientAssetInternal(std::move(assetPath), assetSize, std::move(assetHash), std::move(filepath)); } @@ -292,8 +291,8 @@ namespace bw if (m_clientScripts.find(scriptPath) != m_clientScripts.end()) return; - VirtualDirectory::Entry entry; - if (!m_scriptDirectory->GetEntry(scriptPath, &entry)) + Nz::VirtualDirectory::Entry entry; + if (!m_assetDirectory->GetEntry(scriptPath, &entry)) throw std::runtime_error(scriptPath + " is not a file"); std::vector content; @@ -304,7 +303,7 @@ namespace bw const std::filesystem::path& filepath = std::get(entry); Nz::File file(filepath.generic_u8string()); - if (!file.Open(Nz::OpenMode_ReadOnly)) + if (!file.Open(Nz::OpenMode::ReadOnly)) throw std::runtime_error("failed to open " + filepath.generic_u8string()); content.resize(file.GetSize()); @@ -325,7 +324,7 @@ namespace bw m_clientScripts.emplace(std::move(scriptPath), std::move(clientScriptData)); } - void Match::RegisterEntity(EntityId uniqueId, Ndk::EntityHandle entity) + void Match::RegisterEntity(EntityId uniqueId, entt::entity entity) { assert(m_entitiesByUniqueId.find(uniqueId) == m_entitiesByUniqueId.end()); @@ -506,7 +505,7 @@ namespace bw if (m_terrain) { - ForEachEntity([this](const Ndk::EntityHandle& entity) + ForEachEntity([this](entt::entity entity) { if (entity->HasComponent()) { @@ -623,16 +622,16 @@ namespace bw m_gamemode->ExecuteCallback(); } - const Ndk::EntityHandle& Match::RetrieveEntityByUniqueId(EntityId uniqueId) const + entt::entity Match::RetrieveEntityByUniqueId(EntityId uniqueId) const { auto it = m_entitiesByUniqueId.find(uniqueId); if (it == m_entitiesByUniqueId.end()) - return Ndk::EntityHandle::InvalidHandle; + return entt::null; return it.value().entity; } - EntityId Match::RetrieveUniqueIdByEntity(const Ndk::EntityHandle& entity) const + EntityId Match::RetrieveUniqueIdByEntity(entt::entity entity) const { if (!entity || !entity->HasComponent()) return InvalidEntityId; @@ -677,7 +676,7 @@ namespace bw for (LayerIndex i = 0; i < m_terrain->GetLayerCount(); ++i) { auto& layer = m_terrain->GetLayer(i); - layer.ForEachEntity([&](const Ndk::EntityHandle& entity) + layer.ForEachEntity([&](entt::entity entity) { if (!entity->HasComponent() || !entity->HasComponent()) return; @@ -817,7 +816,7 @@ namespace bw if (player == newPlayer) return; - const Ndk::EntityHandle& controlledEntity = player->GetControlledEntity(); + entt::entity controlledEntity = player->GetControlledEntity(); if (!controlledEntity) return; diff --git a/src/CoreLib/MatchClientSession.cpp b/src/CoreLib/MatchClientSession.cpp index 28f1fc44..dc51c458 100644 --- a/src/CoreLib/MatchClientSession.cpp +++ b/src/CoreLib/MatchClientSession.cpp @@ -253,7 +253,7 @@ namespace bw Player* player = m_players[packet.localIndex]; - const Ndk::EntityHandle& controlledEntity = player->GetControlledEntity(); + entt::entity controlledEntity = player->GetControlledEntity(); if (!controlledEntity) return; @@ -309,7 +309,7 @@ namespace bw } //FIXME: Use fragments instead of sending the whole file at once - Nz::File file(filePath.generic_u8string(), Nz::OpenMode_ReadOnly); + Nz::File file(filePath.generic_u8string(), Nz::OpenMode::ReadOnly); if (!file.IsOpen()) { bwLog(m_match.GetLogger(), LogLevel::Error, "Failed to open {}", filePath.generic_u8string()); diff --git a/src/CoreLib/MatchClientVisibility.cpp b/src/CoreLib/MatchClientVisibility.cpp index 3c1d5f98..4c0a198a 100644 --- a/src/CoreLib/MatchClientVisibility.cpp +++ b/src/CoreLib/MatchClientVisibility.cpp @@ -287,7 +287,7 @@ namespace bw if (m_clientVisibleLayers.UnboundedTest(i)) { - for (const Ndk::EntityHandle& entity : syncSystem.GetEntities()) + for (entt::entity entity : syncSystem.GetEntities()) layer.visibleEntities.emplace(entity->GetId(), Layer::VisibleEntityData{}); continue; diff --git a/src/CoreLib/MatchSessions.cpp b/src/CoreLib/MatchSessions.cpp index 7bf1edb8..9f5ae1ab 100644 --- a/src/CoreLib/MatchSessions.cpp +++ b/src/CoreLib/MatchSessions.cpp @@ -17,16 +17,9 @@ namespace bw { } - MatchSessions::~MatchSessions() - { - Clear(); - } - void MatchSessions::Clear() { - for (const auto& pair : m_sessionIdToSession) - m_sessionPool.Delete(pair.second); - + m_sessionPool.Clear(); m_sessionIdToSession.clear(); } @@ -39,7 +32,7 @@ namespace bw MatchClientSession* MatchSessions::CreateSession(std::shared_ptr bridge) { std::size_t sessionId = m_nextSessionId++; - MatchClientSession* session = m_sessionPool.New(m_match, sessionId, m_commandStore, std::move(bridge)); + MatchClientSession* session = m_sessionPool.Allocate(m_match, sessionId, m_commandStore, std::move(bridge)); m_sessionIdToSession.insert_or_assign(sessionId, session); diff --git a/src/CoreLib/Mod.cpp b/src/CoreLib/Mod.cpp index 68baaaa5..bf2b2cca 100644 --- a/src/CoreLib/Mod.cpp +++ b/src/CoreLib/Mod.cpp @@ -49,7 +49,7 @@ namespace bw { std::vector content; - Nz::File infoFile((modDirectory / "info.json").generic_u8string(), Nz::OpenMode_ReadOnly); + Nz::File infoFile((modDirectory / "info.json").generic_u8string(), Nz::OpenMode::ReadOnly); if (!infoFile.IsOpen()) throw std::runtime_error("failed to open info.json file"); diff --git a/src/CoreLib/NetworkReactor.cpp b/src/CoreLib/NetworkReactor.cpp index b8a008a3..6578a060 100644 --- a/src/CoreLib/NetworkReactor.cpp +++ b/src/CoreLib/NetworkReactor.cpp @@ -21,20 +21,20 @@ namespace bw if (!m_host.Create(protocol, port, maxClient, NetworkChannelCount)) throw std::runtime_error("failed to start reactor"); } - else if (!m_host.Create((protocol == Nz::NetProtocol_IPv4) ? Nz::IpAddress::LoopbackIpV4 : Nz::IpAddress::LoopbackIpV6, maxClient, NetworkChannelCount)) + else if (!m_host.Create((protocol == Nz::NetProtocol::IPv4) ? Nz::IpAddress::LoopbackIpV4 : Nz::IpAddress::LoopbackIpV6, maxClient, NetworkChannelCount)) throw std::runtime_error("failed to start reactor"); m_clients.resize(maxClient, nullptr); m_running.store(true, std::memory_order_release); - m_thread = Nz::Thread(&NetworkReactor::WorkerThread, this); - m_thread.SetName("NetworkReactor"); + m_thread = std::thread(&NetworkReactor::WorkerThread, this); + //m_thread.SetName("NetworkReactor"); } NetworkReactor::~NetworkReactor() { m_running.store(false, std::memory_order_relaxed); - m_thread.Join(); + m_thread.join(); } std::size_t NetworkReactor::ConnectTo(Nz::IpAddress address, Nz::UInt32 data) diff --git a/src/CoreLib/NetworkSessionManager.cpp b/src/CoreLib/NetworkSessionManager.cpp index 3d55965a..494caa3e 100644 --- a/src/CoreLib/NetworkSessionManager.cpp +++ b/src/CoreLib/NetworkSessionManager.cpp @@ -13,7 +13,7 @@ namespace bw { NetworkSessionManager::NetworkSessionManager(MatchSessions* owner, Nz::UInt16 port, std::size_t maxClient) : SessionManager(owner), - m_reactor(0, Nz::NetProtocol_Any, port, maxClient) + m_reactor(0, Nz::NetProtocol::Any, port, maxClient) { } diff --git a/src/CoreLib/Player.cpp b/src/CoreLib/Player.cpp index 7795e2a7..c6435d61 100644 --- a/src/CoreLib/Player.cpp +++ b/src/CoreLib/Player.cpp @@ -3,11 +3,6 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include -#include -#include -#include -#include #include #include #include @@ -28,6 +23,10 @@ #include #include #include +#include +#include +#include +#include namespace bw { @@ -60,7 +59,7 @@ namespace bw { const std::string& scriptFolder = m_match.GetApp().GetConfig().GetStringValue("Resources.ScriptDirectory"); - m_scriptingEnvironment.emplace(m_match.GetLogger(), m_match.GetScriptingLibrary(), std::make_shared(scriptFolder)); + m_scriptingEnvironment.emplace(m_match.GetLogger(), m_match.GetScriptingLibrary(), std::make_shared(scriptFolder)); m_scriptingEnvironment->SetOutputCallback([ply = CreateHandle()](const std::string& text, Nz::Color color) { if (!ply) @@ -92,9 +91,11 @@ namespace bw if (m_playerEntity) { Terrain& terrain = m_match.GetTerrain(); - Ndk::World& world = terrain.GetLayer(layerIndex).GetWorld(); + entt::registry& world = terrain.GetLayer(layerIndex).GetWorld(); - const Ndk::EntityHandle& newPlayerEntity = world.CloneEntity(m_playerEntity); +#if 0 + + entt::entity newPlayerEntity = world.CloneEntity(m_playerEntity); /*const auto& componentBits = m_playerEntity->GetComponentBits(); for (std::size_t i = componentBits.FindFirst(); i != componentBits.npos; i = componentBits.FindNext(i)) { @@ -131,11 +132,13 @@ namespace bw }); } +#endif + m_shouldSendWeapons = true; } } else - m_playerEntity.Reset(); + m_playerEntity.reset(); m_layerIndex = layerIndex; @@ -165,18 +168,25 @@ namespace bw weaponPacket.layerIndex = m_layerIndex; Nz::Bitset weaponIds; - if (m_playerEntity && m_playerEntity->HasComponent()) + if (m_playerEntity) { - auto& weaponWielder = m_playerEntity->GetComponent(); - - for (const Ndk::EntityHandle& weapon : weaponWielder.GetWeapons()) + entt::registry& registry = m_playerEntity->GetRegistry(); + if (WeaponWielderComponent* weaponWielder = registry.try_get(m_playerEntity->GetEntity())) { - assert(weapon); + for (entt::entity weapon : weaponWielder->GetWeapons()) + { + assert(registry.valid(weapon)); - weaponPacket.weaponEntities.emplace_back(Nz::UInt32(weapon->GetId())); - weaponIds.UnboundedSet(weapon->GetId()); + weaponPacket.weaponEntities.emplace_back(Nz::UInt32(weapon->GetId())); + weaponIds.UnboundedSet(weapon->GetId()); + } } } + // && m_playerEntity->HasComponent()) + { + auto& weaponWielder = m_playerEntity->GetComponent(); + + } m_session.GetVisibility().PushEntitiesPacket(m_layerIndex, std::move(weaponIds), std::move(weaponPacket)); @@ -194,7 +204,7 @@ namespace bw return "Player(" + m_name + ")"; } - void Player::UpdateControlledEntity(const Ndk::EntityHandle& entity, bool sendPacket, bool ignoreLayerUpdate) + void Player::UpdateControlledEntity(entt::entity entity, bool sendPacket, bool ignoreLayerUpdate) { MatchClientVisibility& visibility = m_session.GetVisibility(); @@ -207,7 +217,7 @@ namespace bw visibility.SetEntityControlledStatus(matchComponent.GetLayerIndex(), m_playerEntity->GetId(), false); } - m_playerEntity = Ndk::EntityHandle::InvalidHandle; + m_playerEntity = entt::null; m_onPlayerEntityDied.Disconnect(); m_onPlayerEntityDestruction.Disconnect(); m_onWeaponAdded.Disconnect(); @@ -244,7 +254,7 @@ namespace bw { auto& healthComponent = m_playerEntity->GetComponent(); - m_onPlayerEntityDied.Connect(healthComponent.OnDied, [this](const HealthComponent* /*health*/, const Ndk::EntityHandle& attacker) + m_onPlayerEntityDied.Connect(healthComponent.OnDied, [this](const HealthComponent* /*health*/, entt::entity attacker) { OnDeath(attacker); }); @@ -252,7 +262,7 @@ namespace bw m_onPlayerEntityDestruction.Connect(m_playerEntity->OnEntityDestruction, [this](Ndk::Entity* /*entity*/) { - OnDeath(Ndk::EntityHandle::InvalidHandle); + OnDeath(entt::null); }); visibility.SetEntityControlledStatus(matchComponent.GetLayerIndex(), m_playerEntity->GetId(), true); @@ -315,11 +325,11 @@ namespace bw m_match.BroadcastPacket(nameUpdatePacket); } - void Player::OnDeath(const Ndk::EntityHandle& attacker) + void Player::OnDeath(entt::entity attacker) { assert(m_playerEntity); - UpdateControlledEntity(Ndk::EntityHandle::InvalidHandle, false); + UpdateControlledEntity(entt::null, false); Packets::ChatMessage chatPacket; if (attacker && attacker->HasComponent()) diff --git a/src/CoreLib/PlayerInputController.cpp b/src/CoreLib/PlayerInputController.cpp index edbc26be..501d7cbf 100644 --- a/src/CoreLib/PlayerInputController.cpp +++ b/src/CoreLib/PlayerInputController.cpp @@ -8,13 +8,13 @@ namespace bw { - std::optional PlayerInputController::GenerateInputs(const Ndk::EntityHandle& entity) const + std::optional PlayerInputController::GenerateInputs(entt::registry& registry, entt::entity entity) const { - assert(entity); - if (!entity->HasComponent()) + PlayerControlledComponent* playerControlled = registry.try_get(entity); + if (!playerControlled) return std::nullopt; - Player* player = entity->GetComponent().GetOwner(); + Player* player = playerControlled->GetOwner(); if (!player) // TODO: Log error return PlayerInputData{}; diff --git a/src/CoreLib/PlayerMovementController.cpp b/src/CoreLib/PlayerMovementController.cpp index 5c781f66..4155a6fc 100644 --- a/src/CoreLib/PlayerMovementController.cpp +++ b/src/CoreLib/PlayerMovementController.cpp @@ -8,7 +8,7 @@ namespace bw { PlayerMovementController::~PlayerMovementController() = default; - bool PlayerMovementController::PreSolveCollision(PlayerMovementComponent& /*playerMovement*/, const Ndk::EntityHandle& /*collisionBody*/, Nz::Arbiter2D& /*arbiter*/) const + bool PlayerMovementController::PreSolveCollision(PlayerMovementComponent& /*playerMovement*/, entt::entity /*collisionBody*/, Nz::Arbiter2D& /*arbiter*/) const { return true; } diff --git a/src/CoreLib/PropertyValues.cpp b/src/CoreLib/PropertyValues.cpp index f0394efc..60f3bb9f 100644 --- a/src/CoreLib/PropertyValues.cpp +++ b/src/CoreLib/PropertyValues.cpp @@ -45,7 +45,7 @@ namespace bw if (!match) throw std::runtime_error("This context only accepts InvalidEntityId constant"); - const Ndk::EntityHandle& entity = RetrieveScriptEntity(value); + entt::entity entity = RetrieveScriptEntity(value); return match->RetrieveUniqueIdByEntity(entity); } } @@ -92,7 +92,7 @@ namespace bw if (uniqueId == InvalidEntityId) return sol::make_object(lua, InvalidEntityId); - const Ndk::EntityHandle& entity = match->RetrieveEntityByUniqueId(uniqueId); + entt::entity entity = match->RetrieveEntityByUniqueId(uniqueId); if (!entity || !entity->HasComponent()) return sol::make_object(lua, InvalidEntityId); diff --git a/src/CoreLib/Scripting/AbstractElementLibrary.cpp b/src/CoreLib/Scripting/AbstractElementLibrary.cpp index 19f7b068..77465573 100644 --- a/src/CoreLib/Scripting/AbstractElementLibrary.cpp +++ b/src/CoreLib/Scripting/AbstractElementLibrary.cpp @@ -3,8 +3,6 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include -#include namespace bw { diff --git a/src/CoreLib/Scripting/Constraint.cpp b/src/CoreLib/Scripting/Constraint.cpp index 7f4b1d9e..a9c1865b 100644 --- a/src/CoreLib/Scripting/Constraint.cpp +++ b/src/CoreLib/Scripting/Constraint.cpp @@ -3,12 +3,13 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include namespace bw { - Constraint::Constraint(Ndk::EntityHandle entity, Nz::Constraint2DHandle constraint) : - m_entity(std::move(entity)), + Constraint::Constraint(entt::registry& registry, entt::entity entity, Nz::Constraint2DHandle constraint) : + m_entity(entity), + m_registry(registry), m_constraint(std::move(constraint)) { m_onDestruction.Connect(m_constraint->OnHandledObjectDestruction, [this](Nz::HandledObject*) { @@ -17,7 +18,8 @@ namespace bw } Constraint::Constraint(Constraint&& constraint) noexcept : - m_entity(std::move(constraint.m_entity)), + m_entity(constraint.m_entity), + m_registry(constraint.m_registry), m_constraint(std::move(constraint.m_constraint)) { constraint.m_onDestruction.Disconnect(); @@ -63,8 +65,11 @@ namespace bw if (!IsValid()) return; - if (m_entity && !m_entity->GetComponent().RemoveConstraint(m_constraint)) - m_entity->Kill(); + if (m_registry.valid(m_entity)) + { + if (!m_registry.get(m_entity).RemoveConstraint(m_constraint)) + m_registry.destroy(m_entity); + } } void Constraint::SetErrorBias(float errorBias) @@ -87,8 +92,8 @@ namespace bw void Constraint::KillEntity() { - if (m_entity) - m_entity->Kill(); + if (m_registry.valid(m_entity)) + m_registry.destroy(m_entity); } diff --git a/src/CoreLib/Scripting/ScriptingContext.cpp b/src/CoreLib/Scripting/ScriptingContext.cpp index e7c48480..6cac09b5 100644 --- a/src/CoreLib/Scripting/ScriptingContext.cpp +++ b/src/CoreLib/Scripting/ScriptingContext.cpp @@ -17,7 +17,7 @@ namespace bw std::size_t MaxInactiveCoroutines = 20; } - ScriptingContext::ScriptingContext(const Logger& logger, std::shared_ptr scriptDir) : + ScriptingContext::ScriptingContext(const Logger& logger, std::shared_ptr scriptDir) : m_scriptDirectory(std::move(scriptDir)), m_logger(logger) { @@ -35,29 +35,33 @@ namespace bw tl::expected ScriptingContext::Load(const std::filesystem::path& file, bool logError) { - VirtualDirectory::Entry entry; - if (!m_scriptDirectory->GetEntry(file.generic_u8string(), &entry)) + tl::expected result; + + auto Callback = [&](const Nz::VirtualDirectory::Entry& entry) + { + result = std::visit([&](auto&& arg) -> tl::expected + { + using T = std::decay_t; + + if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) + return LoadFile(file, arg); + else if constexpr (std::is_same_v || std::is_same_v) + return tl::unexpected(file.generic_u8string() + " is a directory, expected a file"); + else + static_assert(AlwaysFalse::value, "non-exhaustive visitor"); + + }, entry); + }; + + if (!m_scriptDirectory->GetEntry(file.generic_u8string(), Callback)) { - tl::expected result = tl::unexpected("unknown path " + file.generic_u8string()); + result = tl::unexpected("unknown path " + file.generic_u8string()); if (logError && !result) bwLog(m_logger, LogLevel::Error, "failed to load {}: {}", file.generic_u8string(), result.error()); return result; } - auto result = std::visit([&](auto&& arg) -> tl::expected - { - using T = std::decay_t; - - if constexpr (std::is_same_v || std::is_same_v) - return LoadFile(file, arg); - else if constexpr (std::is_same_v) - return tl::unexpected(file.generic_u8string() + " is a directory, expected a file"); - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); - - }, entry); - if (logError && !result) bwLog(m_logger, LogLevel::Error, "failed to load {}: {}", file.generic_u8string(), result.error()); @@ -66,61 +70,82 @@ namespace bw auto ScriptingContext::Load(const std::filesystem::path& file, Async) -> std::optional { - VirtualDirectory::Entry entry; - if (!m_scriptDirectory->GetEntry(file.generic_u8string(), &entry)) + std::optional result; + + auto Callback = [&](const Nz::VirtualDirectory::Entry& entry) + { + result = std::visit([&](auto&& arg) -> std::optional + { + using T = std::decay_t; + + if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) + return LoadFile(file, arg, Async{}); + else if constexpr (std::is_same_v || std::is_same_v) + { + bwLog(m_logger, LogLevel::Error, "{0} is a directory, expected a file", file.generic_u8string()); + return {}; + } + else + static_assert(AlwaysFalse::value, "non-exhaustive visitor"); + + }, entry); + }; + + if (!m_scriptDirectory->GetEntry(file.generic_u8string(), Callback)) { bwLog(m_logger, LogLevel::Error, "Unknown path {0}", file.generic_u8string()); return {}; } - - return std::visit([&](auto&& arg) -> std::optional - { - using T = std::decay_t; - if constexpr (std::is_same_v || std::is_same_v) - return LoadFile(file, arg, Async{}); - else if constexpr (std::is_same_v) - { - bwLog(m_logger, LogLevel::Error, "{0} is a directory, expected a file", file.generic_u8string()); - return {}; - } - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); - }, entry); + return result; } bool ScriptingContext::LoadDirectory(const std::filesystem::path& folder) { - VirtualDirectory::Entry entry; - if (!m_scriptDirectory->GetEntry(folder.generic_u8string(), &entry)) + auto Callback = [&](const Nz::VirtualDirectory::Entry& entry) { - bwLog(m_logger, LogLevel::Error, "unknown path {0}", folder.generic_u8string()); - return false; - } + std::visit([&](auto&& arg) + { + using T = std::decay_t; + + if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) + bwLog(m_logger, LogLevel::Error, "{0} is a file, expected a directory", folder.generic_u8string()); + else if constexpr (std::is_same_v || std::is_same_v) + LoadDirectory(folder, arg); + else + static_assert(AlwaysFalse::value, "non-exhaustive visitor"); + + }, entry); + }; - if (!std::holds_alternative(entry)) + if (!m_scriptDirectory->GetEntry(folder.generic_u8string(), Callback)) { - bwLog(m_logger, LogLevel::Error, "{0} is not a directory", folder.generic_u8string()); + bwLog(m_logger, LogLevel::Error, "unknown path {0}", folder.generic_u8string()); return false; } - LoadDirectory(folder, std::get(entry)); return true; } bool ScriptingContext::LoadDirectoryOpt(const std::filesystem::path& folder) { - VirtualDirectory::Entry entry; - if (!m_scriptDirectory->GetEntry(folder.generic_u8string(), &entry)) - return true; - - if (!std::holds_alternative(entry)) + auto Callback = [&](const Nz::VirtualDirectory::Entry& entry) { - bwLog(m_logger, LogLevel::Error, "{0} is not a directory", folder.generic_u8string()); - return false; - } + std::visit([&](auto&& arg) + { + using T = std::decay_t; - LoadDirectory(folder, std::get(entry)); + if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) + bwLog(m_logger, LogLevel::Error, "{0} is a file, expected a directory", folder.generic_u8string()); + else if constexpr (std::is_same_v || std::is_same_v) + LoadDirectory(folder, arg); + else + static_assert(AlwaysFalse::value, "non-exhaustive visitor"); + + }, entry); + }; + + m_scriptDirectory->GetEntry(folder.generic_u8string(), Callback); return true; } @@ -193,17 +218,27 @@ namespace bw return (!m_availableThreads.empty()) ? PopThread() : AllocateThread(); } - tl::expected ScriptingContext::LoadFile(std::filesystem::path path, const VirtualDirectory::FileContentEntry& entry) + tl::expected ScriptingContext::LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::DataPointerEntry& entry) { - return LoadFile(std::move(path), std::string_view(reinterpret_cast(entry.data()), entry.size())); + return LoadFile(std::move(path), std::string_view(reinterpret_cast(entry.data), entry.size)); } - auto ScriptingContext::LoadFile(std::filesystem::path path, const VirtualDirectory::FileContentEntry& entry, Async) -> std::optional + auto ScriptingContext::LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::DataPointerEntry& entry, Async) -> std::optional { - return LoadFile(std::move(path), std::string_view(reinterpret_cast(entry.data()), entry.size()), Async{}); + return LoadFile(std::move(path), std::string_view(reinterpret_cast(entry.data), entry.size), Async{}); } - tl::expected ScriptingContext::LoadFile(std::filesystem::path path, const VirtualDirectory::PhysicalFileEntry& entry) + tl::expected ScriptingContext::LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::FileContentEntry& entry) + { + return LoadFile(std::move(path), std::string_view(reinterpret_cast(entry.data.data()), entry.data.size())); + } + + auto ScriptingContext::LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::FileContentEntry& entry, Async) -> std::optional + { + return LoadFile(std::move(path), std::string_view(reinterpret_cast(entry.data.data()), entry.data.size()), Async{}); + } + + tl::expected ScriptingContext::LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::PhysicalFileEntry& entry) { std::string fileContent = ReadFile(path, entry); if (fileContent.empty()) @@ -212,7 +247,7 @@ namespace bw return LoadFile(std::move(path), std::string_view(fileContent)); } - auto ScriptingContext::LoadFile(std::filesystem::path path, const VirtualDirectory::PhysicalFileEntry& entry, Async) -> std::optional + auto ScriptingContext::LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::PhysicalFileEntry& entry, Async) -> std::optional { std::string fileContent = ReadFile(path, entry); if (fileContent.empty()) @@ -264,18 +299,18 @@ namespace bw }; } - void ScriptingContext::LoadDirectory(std::filesystem::path path, const VirtualDirectory::VirtualDirectoryEntry& folder) + void ScriptingContext::LoadDirectory(std::filesystem::path path, const Nz::VirtualDirectory::DirectoryEntry& folder) { - folder->Foreach([&](const std::string& entryName, VirtualDirectory::Entry& entry) + folder.directory->Foreach([&](std::string_view entryName, const Nz::VirtualDirectory::Entry& entry) { std::filesystem::path entryPath = path / entryName; auto result = std::visit([&](auto&& arg) -> tl::expected { using T = std::decay_t; - if constexpr (std::is_same_v || std::is_same_v) + if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) return LoadFile(entryPath, arg); - else if constexpr (std::is_same_v) + else if constexpr (std::is_same_v || std::is_same_v) { LoadDirectory(entryPath, arg); return sol::nil; @@ -290,10 +325,24 @@ namespace bw }); } - std::string ScriptingContext::ReadFile(const std::filesystem::path& path, const VirtualDirectory::PhysicalFileEntry& entry) + void ScriptingContext::LoadDirectory(std::filesystem::path path, const Nz::VirtualDirectory::PhysicalDirectoryEntry& folder) + { + for (const auto& entry : std::filesystem::recursive_directory_iterator(folder.filePath)) + { + if (!entry.is_regular_file()) + continue; + + Nz::VirtualDirectory::PhysicalFileEntry physicalEntry; + physicalEntry.filePath = entry.path(); + + LoadFile(physicalEntry.filePath.parent_path(), physicalEntry); + } + } + + std::string ScriptingContext::ReadFile(const std::filesystem::path& path, const Nz::VirtualDirectory::PhysicalFileEntry& entry) { - Nz::File file(entry.generic_u8string()); - if (!file.Open(Nz::OpenMode_ReadOnly)) + Nz::File file(entry.filePath.generic_u8string()); + if (!file.Open(Nz::OpenMode::ReadOnly)) { bwLog(m_logger, LogLevel::Error, "Failed to load {0}: failed to open file", path.generic_u8string()); return {}; diff --git a/src/CoreLib/Scripting/ScriptingUtils.cpp b/src/CoreLib/Scripting/ScriptingUtils.cpp index a4bdb89a..4c52230c 100644 --- a/src/CoreLib/Scripting/ScriptingUtils.cpp +++ b/src/CoreLib/Scripting/ScriptingUtils.cpp @@ -16,10 +16,10 @@ namespace bw return element; } - Ndk::EntityHandle AssertScriptEntity(const sol::table& entityTable) + entt::entity AssertScriptEntity(entt::registry& registry, const sol::table& entityTable) { - Ndk::EntityHandle entity = RetrieveScriptEntity(entityTable); - if (!entity || !entity->HasComponent()) + entt::entity entity = RetrieveScriptEntity(entityTable); + if (entity == entt::null || !registry.try_get(entity)) TriggerLuaError(entityTable.lua_state(), "invalid entity"); return entity; @@ -34,22 +34,24 @@ namespace bw return entityObject.as>(); } - Ndk::EntityHandle RetrieveScriptEntity(const sol::table& entityTable) + entt::entity RetrieveScriptEntity(const sol::table& entityTable) { sol::object entityObject = entityTable["_Entity"]; if (!entityObject) - return Ndk::EntityHandle::InvalidHandle; + return entt::null; - return entityObject.as(); + return static_cast(entityObject.as()); } - std::optional TranslateEntityToLua(const Ndk::EntityHandle& entity) + std::optional TranslateEntityToLua(entt::registry& registry, entt::entity entity) { - if (!entity || !entity->HasComponent()) + if (entity == entt::null) return std::nullopt; - auto& entityScript = entity->GetComponent(); - return entityScript.GetTable(); + if (ScriptComponent* scriptComponent = registry.try_get(entity)) + return scriptComponent->GetTable(); + else + return std::nullopt; } [[noreturn]] void TriggerLuaError(lua_State* L, const std::string& errMessage) diff --git a/src/CoreLib/Scripting/ServerElementLibrary.cpp b/src/CoreLib/Scripting/ServerElementLibrary.cpp index 76162848..11ea9425 100644 --- a/src/CoreLib/Scripting/ServerElementLibrary.cpp +++ b/src/CoreLib/Scripting/ServerElementLibrary.cpp @@ -33,12 +33,12 @@ namespace bw { auto DealDamage = [](const sol::table& entityTable, const Nz::Vector2f& origin, Nz::UInt16 damage, Nz::Rectf damageZone, float pushbackForce = 0.f) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); Ndk::World* world = entity->GetWorld(); assert(world); Ndk::EntityList hitEntities; //< FIXME: RegionQuery hit multiples entities - world->GetSystem().RegionQuery(damageZone, 0, 0xFFFFFFFF, 0xFFFFFFFF, [&](const Ndk::EntityHandle& hitEntity) + world->GetSystem().RegionQuery(damageZone, 0, 0xFFFFFFFF, 0xFFFFFFFF, [&](entt::entity hitEntity) { if (hitEntities.Has(hitEntity)) return; @@ -62,7 +62,7 @@ namespace bw elementTable["DumpCreationInfo"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) -> sol::object { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent() || !entity->HasComponent() || !entity->HasComponent()) return sol::nil; @@ -103,14 +103,14 @@ namespace bw elementTable["GetLayerIndex"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); return entity->GetComponent().GetLayerIndex(); }); elementTable["GetProperty"] = LuaFunction([](sol::this_state s, const sol::table& table, const std::string& propertyName) -> sol::object { - Ndk::EntityHandle entity = AssertScriptEntity(table); + entt::entity entity = AssertScriptEntity(table); auto& entityScript = entity->GetComponent(); @@ -134,7 +134,7 @@ namespace bw elementTable["GetOwner"] = LuaFunction([](sol::this_state s, const sol::table& table) -> sol::object { - Ndk::EntityHandle entity = AssertScriptEntity(table); + entt::entity entity = AssertScriptEntity(table); if (!entity->HasComponent()) return sol::nil; @@ -144,8 +144,8 @@ namespace bw elementTable["SetParent"] = LuaFunction([](const sol::table& entityTable, const sol::table& parentTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); - const Ndk::EntityHandle& parent = AssertScriptEntity(parentTable); + entt::entity entity = AssertScriptEntity(entityTable); + entt::entity parent = AssertScriptEntity(parentTable); entity->GetComponent().SetParent(parent, true); if (entity->HasComponent()) @@ -153,7 +153,7 @@ namespace bw }); } - void ServerElementLibrary::SetScale(const Ndk::EntityHandle& entity, float newScale) + void ServerElementLibrary::SetScale(entt::entity entity, float newScale) { if (entity->HasComponent()) { @@ -182,7 +182,7 @@ namespace bw if (entity->HasComponent()) { auto& wielderComponent = entity->GetComponent(); - for (const Ndk::EntityHandle& weapon : wielderComponent.GetWeapons()) + for (entt::entity weapon : wielderComponent.GetWeapons()) SetScale(weapon, newScale); } } diff --git a/src/CoreLib/Scripting/ServerEntityLibrary.cpp b/src/CoreLib/Scripting/ServerEntityLibrary.cpp index 146ff077..5a39af91 100644 --- a/src/CoreLib/Scripting/ServerEntityLibrary.cpp +++ b/src/CoreLib/Scripting/ServerEntityLibrary.cpp @@ -24,7 +24,7 @@ namespace bw { entityMetatable["GetWeaponCount"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) -> std::size_t { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity is not a weapon wielder"); @@ -34,7 +34,7 @@ namespace bw entityMetatable["GiveWeapon"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, std::string weaponClass) -> bool { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity is not a weapon wielder"); @@ -52,13 +52,13 @@ namespace bw // Create weapon std::size_t weaponEntityIndex = weaponStore.GetElementIndex(weaponClass); if (weaponEntityIndex == ServerEntityStore::InvalidIndex) - return Ndk::EntityHandle::InvalidHandle; + return entt::null; EntityId uniqueId = match.AllocateUniqueId(); - const Ndk::EntityHandle& weapon = weaponStore.InstantiateWeapon(terrain.GetLayer(entityMatch.GetLayerIndex()), weaponEntityIndex, uniqueId, {}, entity); + entt::entity weapon = weaponStore.InstantiateWeapon(terrain.GetLayer(entityMatch.GetLayerIndex()), weaponEntityIndex, uniqueId, {}, entity); if (!weapon) - return Ndk::EntityHandle::InvalidHandle; + return entt::null; match.RegisterEntity(uniqueId, weapon); if (entity->HasComponent()) @@ -75,7 +75,7 @@ namespace bw entityMetatable["HasWeapon"] = LuaFunction([](sol::this_state L, const sol::table& entityTable, const std::string& weaponClass) -> bool { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity is not a weapon wielder"); @@ -85,7 +85,7 @@ namespace bw entityMetatable["RemoveWeapon"] = LuaFunction([](sol::this_state L, const sol::table& entityTable, const std::string& weaponClass) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity is not a weapon wielder"); @@ -95,7 +95,7 @@ namespace bw entityMetatable["SelectWeapon"] = LuaFunction([](sol::this_state L, const sol::table& entityTable, const std::string& weaponClass) -> bool { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity is not a weapon wielder"); @@ -104,7 +104,7 @@ namespace bw }); } - void ServerEntityLibrary::SetDirection(lua_State* L, const Ndk::EntityHandle& entity, const Nz::Vector2f& upVector) + void ServerEntityLibrary::SetDirection(lua_State* L, entt::entity entity, const Nz::Vector2f& upVector) { SharedEntityLibrary::SetDirection(L, entity, upVector); @@ -112,7 +112,7 @@ namespace bw world->GetSystem().NotifyMovementUpdate(entity); } - void ServerEntityLibrary::SetMass(lua_State* L, const Ndk::EntityHandle& entity, float mass, bool recomputeMomentOfInertia) + void ServerEntityLibrary::SetMass(lua_State* L, entt::entity entity, float mass, bool recomputeMomentOfInertia) { SharedEntityLibrary::SetMass(L, entity, mass, recomputeMomentOfInertia); @@ -120,7 +120,7 @@ namespace bw world->GetSystem().NotifyPhysicsUpdate(entity); } - void ServerEntityLibrary::SetMomentOfInertia(lua_State* L, const Ndk::EntityHandle& entity, float momentOfInertia) + void ServerEntityLibrary::SetMomentOfInertia(lua_State* L, entt::entity entity, float momentOfInertia) { SharedEntityLibrary::SetMomentOfInertia(L, entity, momentOfInertia); @@ -128,7 +128,7 @@ namespace bw world->GetSystem().NotifyPhysicsUpdate(entity); } - void ServerEntityLibrary::SetPosition(lua_State* L, const Ndk::EntityHandle& entity, const Nz::Vector2f& position) + void ServerEntityLibrary::SetPosition(lua_State* L, entt::entity entity, const Nz::Vector2f& position) { SharedEntityLibrary::SetPosition(L, entity, position); @@ -136,7 +136,7 @@ namespace bw world->GetSystem().NotifyMovementUpdate(entity); } - void ServerEntityLibrary::SetRotation(lua_State* L, const Ndk::EntityHandle& entity, const Nz::DegreeAnglef& rotation) + void ServerEntityLibrary::SetRotation(lua_State* L, entt::entity entity, const Nz::DegreeAnglef& rotation) { SharedEntityLibrary::SetRotation(L, entity, rotation); @@ -144,7 +144,7 @@ namespace bw world->GetSystem().NotifyMovementUpdate(entity); } - void ServerEntityLibrary::UpdatePlayerJumpHeight(lua_State* L, const Ndk::EntityHandle& entity, float jumpHeight, float jumpHeightBoost) + void ServerEntityLibrary::UpdatePlayerJumpHeight(lua_State* L, entt::entity entity, float jumpHeight, float jumpHeightBoost) { SharedEntityLibrary::UpdatePlayerJumpHeight(L, entity, jumpHeight, jumpHeightBoost); @@ -152,7 +152,7 @@ namespace bw world->GetSystem().NotifyPhysicsUpdate(entity); } - void ServerEntityLibrary::UpdatePlayerMovement(lua_State* L, const Ndk::EntityHandle& entity, float movementSpeed) + void ServerEntityLibrary::UpdatePlayerMovement(lua_State* L, entt::entity entity, float movementSpeed) { SharedEntityLibrary::UpdatePlayerMovement(L, entity, movementSpeed); diff --git a/src/CoreLib/Scripting/ServerEntityStore.cpp b/src/CoreLib/Scripting/ServerEntityStore.cpp index 8ff43739..ca3b12d2 100644 --- a/src/CoreLib/Scripting/ServerEntityStore.cpp +++ b/src/CoreLib/Scripting/ServerEntityStore.cpp @@ -3,8 +3,6 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include -#include #include #include #include @@ -16,97 +14,107 @@ #include #include #include +#include +#include +#include namespace bw { - const Ndk::EntityHandle& ServerEntityStore::CreateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, const Ndk::EntityHandle& parent) const + entt::entity ServerEntityStore::CreateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, entt::entity parent) const { const auto& entityClass = GetElement(entityIndex); bool hasInputs = entityClass->elementTable.get_or("HasInputs", false); bool playerControlled = entityClass->elementTable.get_or("PlayerControlled", false); - const Ndk::EntityHandle& entity = SharedEntityStore::CreateEntity(layer.GetWorld(), entityClass, properties); - entity->AddComponent(layer.GetMatch(), layer.GetLayerIndex(), uniqueId); + entt::registry& registry = layer.GetWorld(); + + entt::entity entity = SharedEntityStore::CreateEntity(layer.GetWorld(), entityClass, properties); + registry.emplace(entity, layer.GetMatch(), layer.GetLayerIndex(), uniqueId); - auto& node = entity->AddComponent(); + auto& node = registry.emplace(entity); node.SetPosition(position); node.SetRotation(rotation); - if (parent) - node.SetParent(parent); + if (parent != entt::null) + node.SetParent(registry, parent); if (entityClass->maxHealth > 0) { - auto& healthComponent = entity->AddComponent(entityClass->maxHealth); - healthComponent.OnDamage.Connect([](HealthComponent* health, Nz::UInt16& damageValue, const Ndk::EntityHandle& source) + auto& healthComponent = registry.emplace(entity, registry, entity, entityClass->maxHealth); + healthComponent.OnDamage.Connect([](HealthComponent* health, Nz::UInt16& damageValue, entt::entity source) { - auto& entityScript = health->GetEntity()->GetComponent(); + entt::registry& registry = health->GetRegistry(); + auto& entityScript = registry.get(health->GetEntity()); - if (auto ret = entityScript.ExecuteCallback(damageValue, TranslateEntityToLua(source)); ret.has_value()) + if (auto ret = entityScript.ExecuteCallback(damageValue, TranslateEntityToLua(registry, source)); ret.has_value()) damageValue = *ret; }); - healthComponent.OnHealthChange.Connect([](HealthComponent* health, Nz::UInt16 newHealth, const Ndk::EntityHandle& source) + healthComponent.OnHealthChange.Connect([](HealthComponent* health, Nz::UInt16 newHealth, entt::entity source) { - auto& entityScript = health->GetEntity()->GetComponent(); + entt::registry& registry = health->GetRegistry(); + auto& entityScript = registry.get(health->GetEntity()); - entityScript.ExecuteCallback(newHealth, TranslateEntityToLua(source)); + entityScript.ExecuteCallback(newHealth, TranslateEntityToLua(registry, source)); }); - healthComponent.OnDying.Connect([&](HealthComponent* health, const Ndk::EntityHandle& attacker) + healthComponent.OnDying.Connect([&](HealthComponent* health, entt::entity attacker) { - const Ndk::EntityHandle& entity = health->GetEntity(); - auto& entityScript = entity->GetComponent(); + entt::registry& registry = health->GetRegistry(); + auto& entityScript = registry.get(health->GetEntity()); - entityScript.ExecuteCallback(TranslateEntityToLua(attacker)); + entityScript.ExecuteCallback(TranslateEntityToLua(registry, attacker)); }); - healthComponent.OnDied.Connect([&](const HealthComponent* health, const Ndk::EntityHandle& attacker) + healthComponent.OnDie.Connect([&](const HealthComponent* health, entt::entity attacker) { - const Ndk::EntityHandle& entity = health->GetEntity(); - auto& entityScript = entity->GetComponent(); + entt::registry& registry = health->GetRegistry(); + auto& entityScript = registry.get(health->GetEntity()); - entityScript.ExecuteCallback(TranslateEntityToLua(attacker)); + entityScript.ExecuteCallback(TranslateEntityToLua(registry, attacker)); }); } if (entityClass->isNetworked) { // Not quite sure about this, maybe parent handling should be automatic? - if (parent && parent->HasComponent()) - entity->AddComponent(entityClass->fullName, parent); + + if (parent != entt::null && registry.try_get(parent)) + registry.emplace(entity, entityClass->fullName, parent); else - entity->AddComponent(entityClass->fullName); + registry.emplace(entity, entityClass->fullName); } if (playerControlled) - entity->AddComponent(); + registry.emplace(entity); if (hasInputs) - entity->AddComponent(std::make_shared()); + registry.emplace(entity, std::make_shared()); bwLog(GetLogger(), LogLevel::Debug, "Created entity {} on layer {} of type {}", uniqueId, layer.GetLayerIndex(), GetElement(entityIndex)->fullName); return entity; } - bool ServerEntityStore::InitializeEntity(const Ndk::EntityHandle& entity) const + bool ServerEntityStore::InitializeEntity(entt::registry& registry, entt::entity entity) const { - const auto& entityScript = entity->GetComponent(); + const auto& entityScript = registry.get(entity); return SharedEntityStore::InitializeEntity(static_cast(*entityScript.GetElement()), entity); } - const Ndk::EntityHandle& ServerEntityStore::InstantiateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, const Ndk::EntityHandle& parent) const + entt::entity ServerEntityStore::InstantiateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, entt::entity parent) const { - const Ndk::EntityHandle& entity = CreateEntity(layer, entityIndex, uniqueId, position, rotation, properties, parent); - if (!entity) - return Ndk::EntityHandle::InvalidHandle; + entt::registry& registry = layer.GetWorld(); + + entt::entity entity = CreateEntity(layer, entityIndex, uniqueId, position, rotation, properties, parent); + if (entity != entt::null) + return entt::null; - if (!InitializeEntity(entity)) + if (!InitializeEntity(registry, entity)) { - entity->Kill(); - return Ndk::EntityHandle::InvalidHandle; + registry.destroy(entity); + return entt::null; } return entity; diff --git a/src/CoreLib/Scripting/ServerScriptingLibrary.cpp b/src/CoreLib/Scripting/ServerScriptingLibrary.cpp index 3fd2d532..4ab8f61f 100644 --- a/src/CoreLib/Scripting/ServerScriptingLibrary.cpp +++ b/src/CoreLib/Scripting/ServerScriptingLibrary.cpp @@ -50,7 +50,7 @@ namespace bw { library["GetTexture"] = LuaFunction([this](const std::string& texturePath) -> std::optional { - const Nz::ImageRef& image = m_assetStore.GetImage(texturePath); + const std::shared_ptr& image = m_assetStore.GetImage(texturePath); if (image) return ServerTexture(image); else @@ -211,7 +211,7 @@ namespace bw EntityId uniqueId = match.AllocateUniqueId(); - const Ndk::EntityHandle& entity = entityStore.InstantiateEntity(match.GetLayer(layerIndex), elementIndex, uniqueId, position, rotation, entityProperties, parentEntity); + entt::entity entity = entityStore.InstantiateEntity(match.GetLayer(layerIndex), elementIndex, uniqueId, position, rotation, entityProperties, parentEntity); if (!entity) TriggerLuaError(L, "failed to create \"" + entityType + "\""); @@ -270,7 +270,7 @@ namespace bw // Create weapon EntityId uniqueId = match.AllocateUniqueId(); - const Ndk::EntityHandle& weapon = weaponStore.InstantiateWeapon(layer, elementIndex, uniqueId, std::move(entityProperties), owner); + entt::entity weapon = weaponStore.InstantiateWeapon(layer, elementIndex, uniqueId, std::move(entityProperties), owner); if (!weapon) TriggerLuaError(L, "failed to create \"" + entityType + "\""); @@ -351,7 +351,7 @@ namespace bw "new", sol::no_constructor, "GetControlledEntity", LuaFunction([](const Player& player) -> sol::object { - const Ndk::EntityHandle& controlledEntity = player.GetControlledEntity(); + entt::entity controlledEntity = player.GetControlledEntity(); if (!controlledEntity) return sol::nil; @@ -381,12 +381,12 @@ namespace bw { if (entityTable) { - const Ndk::EntityHandle& entity = AssertScriptEntity(entityTable.value()); + entt::entity entity = AssertScriptEntity(entityTable.value()); player.UpdateControlledEntity(entity); } else - player.UpdateControlledEntity(Ndk::EntityHandle::InvalidHandle); + player.UpdateControlledEntity(entt::null); }), "UpdateLayerVisibility", LuaFunction(&Player::UpdateLayerVisibility) ); diff --git a/src/CoreLib/Scripting/ServerWeaponLibrary.cpp b/src/CoreLib/Scripting/ServerWeaponLibrary.cpp index 6d71acc2..f94fb06c 100644 --- a/src/CoreLib/Scripting/ServerWeaponLibrary.cpp +++ b/src/CoreLib/Scripting/ServerWeaponLibrary.cpp @@ -26,7 +26,7 @@ namespace bw { elementMetatable["IsPlayingAnimation"] = LuaFunction([](const sol::table& weaponTable) { - Ndk::EntityHandle entity = AssertScriptEntity(weaponTable); + entt::entity entity = AssertScriptEntity(weaponTable); if (!entity->HasComponent()) return false; @@ -35,7 +35,7 @@ namespace bw elementMetatable["PlayAnim"] = LuaFunction([&](const sol::table& weaponTable, const std::string& animationName) { - Ndk::EntityHandle entity = AssertScriptEntity(weaponTable); + entt::entity entity = AssertScriptEntity(weaponTable); if (!entity->HasComponent()) throw std::runtime_error("Entity has no animations"); @@ -50,7 +50,7 @@ namespace bw auto shootFunc = [](const sol::table& weaponTable, Nz::Vector2f startPos, Nz::Vector2f direction, Nz::UInt16 damage, float pushbackForce = 0.f) { - Ndk::EntityHandle entity = AssertScriptEntity(weaponTable); + entt::entity entity = AssertScriptEntity(weaponTable); Ndk::World* world = entity->GetWorld(); assert(world); @@ -60,7 +60,7 @@ namespace bw if (physSystem.RaycastQueryFirst(startPos, startPos + direction * 1000.f, 1.f, 0, 0xFFFFFFFF, 0xFFFFFFFF, &hitInfo)) { - const Ndk::EntityHandle& hitEntity = hitInfo.body; + entt::entity hitEntity = hitInfo.body; if (hitEntity->HasComponent()) hitEntity->GetComponent().Damage(damage, entity); diff --git a/src/CoreLib/Scripting/ServerWeaponStore.cpp b/src/CoreLib/Scripting/ServerWeaponStore.cpp index 35ec4a31..ffefebf7 100644 --- a/src/CoreLib/Scripting/ServerWeaponStore.cpp +++ b/src/CoreLib/Scripting/ServerWeaponStore.cpp @@ -19,11 +19,11 @@ namespace bw { - const Ndk::EntityHandle& ServerWeaponStore::InstantiateWeapon(TerrainLayer& layer, std::size_t weaponIndex, EntityId uniqueId, const PropertyValueMap& properties, const Ndk::EntityHandle& parent) + entt::entity ServerWeaponStore::InstantiateWeapon(TerrainLayer& layer, std::size_t weaponIndex, EntityId uniqueId, const PropertyValueMap& properties, entt::entity parent) { const auto& weaponClass = GetElement(weaponIndex); - const Ndk::EntityHandle& weapon = CreateEntity(layer.GetWorld(), weaponClass, properties); + entt::entity weapon = CreateEntity(layer.GetWorld(), weaponClass, properties); weapon->AddComponent(layer.GetMatch(), layer.GetLayerIndex(), uniqueId); weapon->AddComponent(weaponClass->fullName, parent); diff --git a/src/CoreLib/Scripting/SharedElementLibrary.cpp b/src/CoreLib/Scripting/SharedElementLibrary.cpp index 16f1bde8..3455eb17 100644 --- a/src/CoreLib/Scripting/SharedElementLibrary.cpp +++ b/src/CoreLib/Scripting/SharedElementLibrary.cpp @@ -26,8 +26,8 @@ namespace bw { elementMetatable["DeleteOnRemove"] = LuaFunction([](const sol::table& entityTable, const sol::table& targetEntityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); - const Ndk::EntityHandle& targetEntity = AssertScriptEntity(targetEntityTable); + entt::entity entity = AssertScriptEntity(entityTable); + entt::entity targetEntity = AssertScriptEntity(targetEntityTable); if (!entity->HasComponent()) entity->AddComponent(); @@ -37,13 +37,13 @@ namespace bw elementMetatable["Disable"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); entity->Disable(); }); elementMetatable["Disconnect"] = LuaFunction([&](const sol::table& entityTable, const ElementEventConnection& eventConnection) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); entity->Invalidate(); auto& entityScript = entity->GetComponent(); @@ -62,13 +62,13 @@ namespace bw elementMetatable["Enable"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); entity->Enable(); }); elementMetatable["GetDirection"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); auto& nodeComponent = entity->GetComponent(); @@ -81,7 +81,7 @@ namespace bw elementMetatable["GetPosition"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); auto& nodeComponent = entity->GetComponent(); return Nz::Vector2f(nodeComponent.GetPosition(Nz::CoordSys_Global)); @@ -89,7 +89,7 @@ namespace bw elementMetatable["GetRotation"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); auto& nodeComponent = entity->GetComponent(); return Nz::DegreeAnglef(AngleFromQuaternion(nodeComponent.GetRotation(Nz::CoordSys_Global))); //GetComponent(); Nz::Vector2f scale = Nz::Vector2f(nodeComponent.GetScale(Nz::CoordSys_Global)); @@ -106,13 +106,13 @@ namespace bw elementMetatable["IsEnabled"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); return entity->IsEnabled(); }); elementMetatable["IsLookingRight"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); auto& nodeComponent = entity->GetComponent(); return nodeComponent.GetScale().x > 0.f; @@ -120,13 +120,13 @@ namespace bw elementMetatable["IsValid"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = RetrieveScriptEntity(entityTable); + entt::entity entity = RetrieveScriptEntity(entityTable); return entity.IsValid(); }); elementMetatable["Kill"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) { auto& entityHealth = entity->GetComponent(); @@ -148,19 +148,19 @@ namespace bw elementMetatable["SetLifeTime"] = LuaFunction([](const sol::table& entityTable, float lifetime) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); entity->AddComponent(lifetime); }); elementMetatable["SetScale"] = LuaFunction([&](const sol::table& entityTable, float scale) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); SetScale(entity, scale); }); elementMetatable["ToLocalPosition"] = LuaFunction([](const sol::table& entityTable, const Nz::Vector2f& globalPosition) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); auto& nodeComponent = entity->GetComponent(); return Nz::Vector2f(nodeComponent.ToLocalPosition(globalPosition)); @@ -168,7 +168,7 @@ namespace bw elementMetatable["ToGlobalPosition"] = LuaFunction([](const sol::table& entityTable, const Nz::Vector2f& localPosition) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); auto& nodeComponent = entity->GetComponent(); return Nz::Vector2f(nodeComponent.ToGlobalPosition(localPosition)); @@ -176,7 +176,7 @@ namespace bw elementMetatable["Trigger"] = LuaFunction([](const sol::table& entityTable, const std::string_view& event, sol::variadic_args parameters) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); auto& entityScript = entity->GetComponent(); const auto& element = entityScript.GetElement(); @@ -210,7 +210,7 @@ namespace bw return eventData.index; }; - if (Ndk::EntityHandle entity = RetrieveScriptEntity(entityTable)) + if (entt::entity entity = RetrieveScriptEntity(entityTable)) { auto& entityScript = entity->GetComponent(); std::size_t eventIndex = RetrieveEventIndex(entityScript.GetElement()); @@ -248,7 +248,7 @@ namespace bw if (async && HasReturnValue(scriptingEvent)) TriggerLuaArgError(L, 2, "events returning a value cannot be async"); - if (Ndk::EntityHandle entity = RetrieveScriptEntity(entityTable)) + if (entt::entity entity = RetrieveScriptEntity(entityTable)) { auto& entityScript = entity->GetComponent(); std::size_t callbackId = entityScript.RegisterCallback(scriptingEvent, std::move(callback), async); diff --git a/src/CoreLib/Scripting/SharedEntityLibrary.cpp b/src/CoreLib/Scripting/SharedEntityLibrary.cpp index cb0b2a24..d3a68e53 100644 --- a/src/CoreLib/Scripting/SharedEntityLibrary.cpp +++ b/src/CoreLib/Scripting/SharedEntityLibrary.cpp @@ -159,7 +159,7 @@ namespace bw RegisterSharedLibrary(elementMetatable); } - void SharedEntityLibrary::InitRigidBody(lua_State* /*L*/, const Ndk::EntityHandle& entity, float mass) + void SharedEntityLibrary::InitRigidBody(lua_State* /*L*/, entt::entity entity, float mass) { auto& entityNode = entity->GetComponent(); auto& entityPhys = entity->AddComponent(); @@ -169,7 +169,7 @@ namespace bw entityPhys.SetRotation(AngleFromQuaternion(entityNode.GetRotation(Nz::CoordSys_Global))); } - void SharedEntityLibrary::SetDirection(lua_State* L, const Ndk::EntityHandle& entity, const Nz::Vector2f& upVector) + void SharedEntityLibrary::SetDirection(lua_State* L, entt::entity entity, const Nz::Vector2f& upVector) { Nz::RadianAnglef angle(std::atan2(upVector.y, upVector.x) + float(M_PI) / 2.f); @@ -183,7 +183,7 @@ namespace bw nodeComponent.SetRotation(angle); } - void SharedEntityLibrary::SetMass(lua_State* /*L*/, const Ndk::EntityHandle& entity, float mass, bool recomputeMomentOfInertia) + void SharedEntityLibrary::SetMass(lua_State* /*L*/, entt::entity entity, float mass, bool recomputeMomentOfInertia) { if (entity->HasComponent()) { @@ -192,7 +192,7 @@ namespace bw } } - void SharedEntityLibrary::SetMomentOfInertia(lua_State* /*L*/, const Ndk::EntityHandle& entity, float momentOfInertia) + void SharedEntityLibrary::SetMomentOfInertia(lua_State* /*L*/, entt::entity entity, float momentOfInertia) { if (entity->HasComponent()) { @@ -201,7 +201,7 @@ namespace bw } } - void SharedEntityLibrary::SetPosition(lua_State* L, const Ndk::EntityHandle& entity, const Nz::Vector2f& position) + void SharedEntityLibrary::SetPosition(lua_State* L, entt::entity entity, const Nz::Vector2f& position) { if (entity->HasComponent()) { @@ -213,7 +213,7 @@ namespace bw nodeComponent.SetPosition(position); } - void SharedEntityLibrary::SetRotation(lua_State* L, const Ndk::EntityHandle& entity, const Nz::DegreeAnglef& rotation) + void SharedEntityLibrary::SetRotation(lua_State* L, entt::entity entity, const Nz::DegreeAnglef& rotation) { if (entity->HasComponent()) { @@ -225,7 +225,7 @@ namespace bw nodeComponent.SetRotation(rotation); } - void SharedEntityLibrary::UpdatePlayerJumpHeight(lua_State* L, const Ndk::EntityHandle& entity, float jumpHeight, float jumpHeightBoost) + void SharedEntityLibrary::UpdatePlayerJumpHeight(lua_State* L, entt::entity entity, float jumpHeight, float jumpHeightBoost) { if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity has no player movement"); @@ -235,7 +235,7 @@ namespace bw playerMovementComponent.UpdateJumpBoostHeight(jumpHeightBoost); } - void SharedEntityLibrary::UpdatePlayerMovement(lua_State* L, const Ndk::EntityHandle& entity, float movementSpeed) + void SharedEntityLibrary::UpdatePlayerMovement(lua_State* L, entt::entity entity, float movementSpeed) { if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity has no player movement"); @@ -248,7 +248,7 @@ namespace bw { elementMetatable["AddForce"] = LuaFunction([this](const sol::table& entityTable, const Nz::Vector2f& force) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) { @@ -259,7 +259,7 @@ namespace bw elementMetatable["ApplyImpulse"] = LuaFunction([this](const sol::table& entityTable, const Nz::Vector2f& force) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) { @@ -270,17 +270,17 @@ namespace bw elementMetatable["Damage"] = LuaFunction([](const sol::table& entityTable, Nz::UInt16 damage, std::optional attackerEntity) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) return; auto& entityHealth = entity->GetComponent(); - entityHealth.Damage(damage, (attackerEntity) ? RetrieveScriptEntity(*attackerEntity) : Ndk::EntityHandle::InvalidHandle); + entityHealth.Damage(damage, (attackerEntity) ? RetrieveScriptEntity(*attackerEntity) : entt::null); }); elementMetatable["ForceSleep"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) { @@ -291,7 +291,7 @@ namespace bw elementMetatable["GetColliders"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) -> sol::object { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) return sol::nil; @@ -302,7 +302,7 @@ namespace bw elementMetatable["GetInputController"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity has no inputs"); @@ -312,7 +312,7 @@ namespace bw elementMetatable["GetHealth"] = LuaFunction([](const sol::table& entityTable) -> Nz::UInt16 { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) return 0; @@ -322,7 +322,7 @@ namespace bw elementMetatable["GetMass"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) -> sol::object { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) { @@ -335,7 +335,7 @@ namespace bw elementMetatable["GetMomentOfInertia"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) -> sol::object { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) { @@ -348,7 +348,7 @@ namespace bw elementMetatable["GetPlayerMovementController"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity has no player movement"); @@ -358,7 +358,7 @@ namespace bw elementMetatable["GetPlayerMovementSpeed"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity has no player movement"); @@ -368,7 +368,7 @@ namespace bw elementMetatable["GetPlayerJumpHeight"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity has no player movement"); @@ -382,14 +382,14 @@ namespace bw elementMetatable["GetUpVector"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); auto& nodeComponent = entity->GetComponent(); return Nz::Vector2f(nodeComponent.GetUp()); }); elementMetatable["GetVelocity"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) return Nz::Vector2f::Zero(); @@ -399,17 +399,17 @@ namespace bw elementMetatable["Heal"] = LuaFunction([](const sol::table& entityTable, Nz::UInt16 value, std::optional healerEntity) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) return; auto& entityHealth = entity->GetComponent(); - entityHealth.Heal(value, (healerEntity) ? RetrieveScriptEntity(*healerEntity) : Ndk::EntityHandle::InvalidHandle); + entityHealth.Heal(value, (healerEntity) ? RetrieveScriptEntity(*healerEntity) : entt::null); }); elementMetatable["InitWeaponWielder"] = LuaFunction([](const sol::table& entityTable, const sol::table& wielderData) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); auto& wielderComponent = entity->AddComponent(); wielderComponent.SetWeaponOffset(wielderData["WeaponOffset"]); @@ -417,7 +417,7 @@ namespace bw elementMetatable["IsFullHealth"] = LuaFunction([](const sol::table& entityTable) -> bool { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) return false; @@ -427,14 +427,14 @@ namespace bw elementMetatable["InitRigidBody"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, float mass) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); this->InitRigidBody(L, entity, mass); }); elementMetatable["IsPlayerOnGround"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity has no player movement"); @@ -444,7 +444,7 @@ namespace bw elementMetatable["IsSleeping"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) return entity->GetComponent().IsSleeping(); else @@ -453,7 +453,7 @@ namespace bw elementMetatable["OverrideMovementController"] = LuaFunction([this](const sol::table& entityTable, sol::main_protected_function fn) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) { @@ -486,13 +486,13 @@ namespace bw elementMetatable["Remove"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); entity->Kill(); }); elementMetatable["SetAngularVelocity"] = LuaFunction([](const sol::table& entityTable, const Nz::DegreeAnglef& velocity) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) return; @@ -502,7 +502,7 @@ namespace bw elementMetatable["SetColliders"] = LuaFunction([](sol::this_state L, const sol::table& entityTable, const sol::table& colliderTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); std::size_t colliderCount = colliderTable.size(); @@ -546,7 +546,7 @@ namespace bw elementMetatable["SetDirection"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, const Nz::Vector2f& upVector) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity) return; @@ -555,7 +555,7 @@ namespace bw auto SetMass = [this](sol::this_state L, const sol::table& entityTable, float mass, bool recomputeMomentOfInertia = false) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); this->SetMass(L, entity, mass, recomputeMomentOfInertia); }; @@ -570,7 +570,7 @@ namespace bw elementMetatable["SetMomentOfInertia"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, float momentum) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (momentum < 0.f) TriggerLuaArgError(L, 2, "moment of inertia must be positive"); @@ -580,7 +580,7 @@ namespace bw elementMetatable["SetPosition"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, const Nz::Vector2f& position) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity) return; @@ -589,7 +589,7 @@ namespace bw elementMetatable["SetRotation"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, const Nz::DegreeAnglef& rotation) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity) return; @@ -598,7 +598,7 @@ namespace bw elementMetatable["SetVelocity"] = LuaFunction([](const sol::table& entityTable, const Nz::Vector2f& velocity) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity || !entity->HasComponent()) return; @@ -608,7 +608,7 @@ namespace bw elementMetatable["UpdateInputs"] = LuaFunction([](const sol::table& entityTable, const PlayerInputData& inputs) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity || !entity->HasComponent()) return; @@ -618,7 +618,7 @@ namespace bw elementMetatable["UpdateInputController"] = LuaFunction([this](const sol::table& entityTable, std::shared_ptr controller) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity || !entity->HasComponent()) return; @@ -628,7 +628,7 @@ namespace bw elementMetatable["UpdatePlayerMovementController"] = LuaFunction([](sol::this_state L, const sol::table& entityTable, sol::optional> controller) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity has no player movement"); @@ -640,13 +640,13 @@ namespace bw elementMetatable["UpdatePlayerMovementSpeed"] = LuaFunction([&](sol::this_state L, const sol::table& entityTable, float newSpeed) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); return UpdatePlayerMovement(L, entity, newSpeed); }); elementMetatable["UpdatePlayerJumpHeight"] = LuaFunction([&](sol::this_state L, const sol::table& entityTable, float newJumpHeight, float newJumpBoostHeight) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); return UpdatePlayerJumpHeight(L, entity, newJumpHeight, newJumpBoostHeight); }); } diff --git a/src/CoreLib/Scripting/SharedEntityStore.cpp b/src/CoreLib/Scripting/SharedEntityStore.cpp index ef404c6f..e8f7286b 100644 --- a/src/CoreLib/Scripting/SharedEntityStore.cpp +++ b/src/CoreLib/Scripting/SharedEntityStore.cpp @@ -18,14 +18,14 @@ namespace bw ReloadLibraries(); // This function creates the metatable } - void SharedEntityStore::BindCallbacks(const ScriptedEntity& /*entityClass*/, const Ndk::EntityHandle& entity) const + void SharedEntityStore::BindCallbacks(const ScriptedEntity& /*entityClass*/, entt::entity entity) const { if (entity->HasComponent()) { InputComponent& entityInputs = entity->GetComponent(); entityInputs.OnInputUpdate.Connect([](InputComponent* input) { - const Ndk::EntityHandle& entity = input->GetEntity(); + entt::entity entity = input->GetEntity(); auto& entityScript = entity->GetComponent(); entityScript.ExecuteCallback(input->GetInputs()); @@ -37,7 +37,7 @@ namespace bw { } - bool SharedEntityStore::InitializeEntity(const ScriptedEntity& entityClass, const Ndk::EntityHandle& entity) const + bool SharedEntityStore::InitializeEntity(const ScriptedEntity& entityClass, entt::entity entity) const { if (!ScriptStore::InitializeEntity(entityClass, entity)) return false; diff --git a/src/CoreLib/Scripting/SharedScriptingLibrary.cpp b/src/CoreLib/Scripting/SharedScriptingLibrary.cpp index c86d3250..8dad59c6 100644 --- a/src/CoreLib/Scripting/SharedScriptingLibrary.cpp +++ b/src/CoreLib/Scripting/SharedScriptingLibrary.cpp @@ -158,7 +158,7 @@ namespace bw "ReadEntity", LuaFunction([&](IncomingNetworkPacket& incomingPacket) -> sol::object { Nz::Int64 entityId = incomingPacket.ReadCompressedInteger(); - const Ndk::EntityHandle& entity = m_match.RetrieveEntityByUniqueId(entityId); + entt::entity entity = m_match.RetrieveEntityByUniqueId(entityId); if (entity && entity->HasComponent()) return entity->GetComponent().GetTable(); else @@ -180,7 +180,7 @@ namespace bw "WriteEntity", LuaFunction([&](OutgoingNetworkPacket& outgoingPacket, const sol::table& entityTable) { - const Ndk::EntityHandle& entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); outgoingPacket.WriteCompressedInteger(m_match.RetrieveUniqueIdByEntity(entity)); }) ); @@ -239,7 +239,7 @@ namespace bw sol::table result = state.create_table(); std::size_t index = 1; - auto entityFunc = [&](const Ndk::EntityHandle& entity) + auto entityFunc = [&](entt::entity entity) { if (!entity->HasComponent()) return; @@ -268,7 +268,7 @@ namespace bw sol::table result = state.create_table(); std::size_t index = 1; - auto entityFunc = [&](const Ndk::EntityHandle& entity) + auto entityFunc = [&](entt::entity entity) { if (!entity->HasComponent()) return; @@ -344,13 +344,13 @@ namespace bw { library["CreateDampenedSpringConstraint"] = LuaFunction([](sol::this_state L, const sol::table& firstEntityTable, const sol::table& secondEntityTable, const Nz::Vector2f& firstAnchor, const Nz::Vector2f& secondAnchor, float restLength, float stiffness, float damping) { - const Ndk::EntityHandle& firstEntity = AssertScriptEntity(firstEntityTable); - const Ndk::EntityHandle& secondEntity = AssertScriptEntity(secondEntityTable); + entt::entity firstEntity = AssertScriptEntity(firstEntityTable); + entt::entity secondEntity = AssertScriptEntity(secondEntityTable); if (firstEntity == secondEntity) TriggerLuaArgError(L, 1, "Cannot apply a constraint to the same entity"); - const Ndk::EntityHandle& constraintEntity = firstEntity->GetWorld()->CreateEntity(); + entt::entity constraintEntity = firstEntity->GetWorld()->CreateEntity(); auto& constraintComponent = constraintEntity->AddComponent(); return DampedSpringConstraint(constraintEntity, constraintComponent.CreateConstraint(firstEntity, secondEntity, firstAnchor, secondAnchor, restLength, stiffness, damping)); @@ -358,13 +358,13 @@ namespace bw library["CreatePinConstraint"] = LuaFunction([](sol::this_state L, const sol::table& firstEntityTable, const sol::table& secondEntityTable, const Nz::Vector2f& firstAnchor, const Nz::Vector2f& secondAnchor) { - const Ndk::EntityHandle& firstEntity = AssertScriptEntity(firstEntityTable); - const Ndk::EntityHandle& secondEntity = AssertScriptEntity(secondEntityTable); + entt::entity firstEntity = AssertScriptEntity(firstEntityTable); + entt::entity secondEntity = AssertScriptEntity(secondEntityTable); if (firstEntity == secondEntity) TriggerLuaArgError(L, 1, "Cannot apply a constraint to the same entity"); - const Ndk::EntityHandle& constraintEntity = firstEntity->GetWorld()->CreateEntity(); + entt::entity constraintEntity = firstEntity->GetWorld()->CreateEntity(); auto& constraintComponent = constraintEntity->AddComponent(); return PinConstraint(constraintEntity, constraintComponent.CreateConstraint(firstEntity, secondEntity, firstAnchor, secondAnchor)); @@ -372,13 +372,13 @@ namespace bw library["CreatePivotConstraint"] = LuaFunction([](sol::this_state L, const sol::table& firstEntityTable, const sol::table& secondEntityTable, const Nz::Vector2f& firstAnchor, const Nz::Vector2f& secondAnchor) { - const Ndk::EntityHandle& firstEntity = AssertScriptEntity(firstEntityTable); - const Ndk::EntityHandle& secondEntity = AssertScriptEntity(secondEntityTable); + entt::entity firstEntity = AssertScriptEntity(firstEntityTable); + entt::entity secondEntity = AssertScriptEntity(secondEntityTable); if (firstEntity == secondEntity) TriggerLuaArgError(L, 1, "Cannot apply a constraint to the same entity"); - const Ndk::EntityHandle& constraintEntity = firstEntity->GetWorld()->CreateEntity(); + entt::entity constraintEntity = firstEntity->GetWorld()->CreateEntity(); auto& constraintComponent = constraintEntity->AddComponent(); return PivotConstraint(constraintEntity, constraintComponent.CreateConstraint(firstEntity, secondEntity, firstAnchor, secondAnchor)); @@ -386,13 +386,13 @@ namespace bw library["CreateRotaryLimitConstraint"] = LuaFunction([](sol::this_state L, const sol::table& firstEntityTable, const sol::table& secondEntityTable, const Nz::RadianAnglef& minAngle, const Nz::RadianAnglef& maxAngle) { - const Ndk::EntityHandle& firstEntity = AssertScriptEntity(firstEntityTable); - const Ndk::EntityHandle& secondEntity = AssertScriptEntity(secondEntityTable); + entt::entity firstEntity = AssertScriptEntity(firstEntityTable); + entt::entity secondEntity = AssertScriptEntity(secondEntityTable); if (firstEntity == secondEntity) TriggerLuaArgError(L, 1, "Cannot apply a constraint to the same entity"); - const Ndk::EntityHandle& constraintEntity = firstEntity->GetWorld()->CreateEntity(); + entt::entity constraintEntity = firstEntity->GetWorld()->CreateEntity(); auto& constraintComponent = constraintEntity->AddComponent(); return RotaryLimitConstraint(constraintEntity, constraintComponent.CreateConstraint(firstEntity, secondEntity, minAngle, maxAngle)); @@ -409,7 +409,7 @@ namespace bw Ndk::EntityList hitEntities; //< FIXME: RegionQuery hit multiples entities sol::state_view state(L); - auto resultCallback = [&](const Ndk::EntityHandle& hitEntity) + auto resultCallback = [&](entt::entity hitEntity) { if (hitEntities.Has(hitEntity)) return; @@ -447,7 +447,7 @@ namespace bw result["hitPos"] = hitInfo.hitPos; result["hitNormal"] = hitInfo.hitNormal; - const Ndk::EntityHandle& hitEntity = hitInfo.body; + entt::entity hitEntity = hitInfo.body; if (hitEntity->HasComponent()) result["hitEntity"] = hitEntity->GetComponent().GetTable(); @@ -470,7 +470,7 @@ namespace bw sol::state_view state(L); auto resultCallback = [&](const Ndk::PhysicsSystem2D::RaycastHit& hitInfo) { - const Ndk::EntityHandle& hitEntity = hitInfo.body; + entt::entity hitEntity = hitInfo.body; if (hitEntities.Has(hitEntity)) return; diff --git a/src/CoreLib/Scripting/SharedWeaponLibrary.cpp b/src/CoreLib/Scripting/SharedWeaponLibrary.cpp index 318479cc..0632862b 100644 --- a/src/CoreLib/Scripting/SharedWeaponLibrary.cpp +++ b/src/CoreLib/Scripting/SharedWeaponLibrary.cpp @@ -24,9 +24,9 @@ namespace bw { elementMetatable["GetOwnerEntity"] = LuaFunction([](const sol::table& weaponTable) -> sol::object { - Ndk::EntityHandle entity = AssertScriptEntity(weaponTable); + entt::entity entity = AssertScriptEntity(weaponTable); - const Ndk::EntityHandle& ownerEntity = entity->GetComponent().GetOwner(); + entt::entity ownerEntity = entity->GetComponent().GetOwner(); if (!ownerEntity) return sol::nil; @@ -35,7 +35,7 @@ namespace bw elementMetatable["SetNextTriggerTime"] = LuaFunction([](const sol::table& weaponTable, Nz::UInt64 nextTriggerTime) { - Ndk::EntityHandle entity = AssertScriptEntity(weaponTable); + entt::entity entity = AssertScriptEntity(weaponTable); entity->GetComponent().SetNextTriggerTime(nextTriggerTime); }); diff --git a/src/CoreLib/Scripting/SharedWeaponStore.cpp b/src/CoreLib/Scripting/SharedWeaponStore.cpp index c401c0f2..00ca2c53 100644 --- a/src/CoreLib/Scripting/SharedWeaponStore.cpp +++ b/src/CoreLib/Scripting/SharedWeaponStore.cpp @@ -58,7 +58,7 @@ namespace bw weapon.animationStartFunction = elementTable.get_or("OnAnimationStart", sol::main_protected_function{}); } - bool SharedWeaponStore::InitializeWeapon(const ScriptedWeapon& weaponClass, const Ndk::EntityHandle& entity, const Ndk::EntityHandle& parent) + bool SharedWeaponStore::InitializeWeapon(const ScriptedWeapon& weaponClass, entt::entity entity, entt::entity parent) { entity->AddComponent(weaponClass.cooldown); @@ -85,7 +85,7 @@ namespace bw { anim.OnAnimationStart.Connect([this, callback = weaponClass.animationStartFunction](AnimationComponent* anim) { - const Ndk::EntityHandle& entity = anim->GetEntity(); + entt::entity entity = anim->GetEntity(); auto& scriptComponent = entity->GetComponent(); auto co = scriptComponent.GetContext()->CreateCoroutine(callback); diff --git a/src/CoreLib/ScriptingEnvironment.cpp b/src/CoreLib/ScriptingEnvironment.cpp index 0dfc259c..771ad458 100644 --- a/src/CoreLib/ScriptingEnvironment.cpp +++ b/src/CoreLib/ScriptingEnvironment.cpp @@ -3,12 +3,11 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include #include namespace bw { - ScriptingEnvironment::ScriptingEnvironment(const Logger& logger, std::shared_ptr scriptingLibrary, const std::shared_ptr& scriptDir) + ScriptingEnvironment::ScriptingEnvironment(const Logger& logger, std::shared_ptr scriptingLibrary, const std::shared_ptr& scriptDir) { m_scriptingContext = std::make_shared(logger, scriptDir); m_scriptingContext->LoadLibrary(std::move(scriptingLibrary)); diff --git a/src/CoreLib/SharedLayer.cpp b/src/CoreLib/SharedLayer.cpp index 2e06222f..663f8d38 100644 --- a/src/CoreLib/SharedLayer.cpp +++ b/src/CoreLib/SharedLayer.cpp @@ -40,11 +40,11 @@ namespace bw physics.SetStepSize(match.GetTickDuration()); Ndk::PhysicsSystem2D::Callback triggerCallbacks; - triggerCallbacks.startCallback = [](Ndk::PhysicsSystem2D& /*world*/, Nz::Arbiter2D& /*arbiter*/, const Ndk::EntityHandle& bodyA, const Ndk::EntityHandle& bodyB, void* /*userdata*/) + triggerCallbacks.startCallback = [](Ndk::PhysicsSystem2D& /*world*/, Nz::Arbiter2D& /*arbiter*/, entt::entity bodyA, entt::entity bodyB, void* /*userdata*/) { bool shouldCollide = true; - auto HandleCollision = [&](const Ndk::EntityHandle& first, const Ndk::EntityHandle& second) + auto HandleCollision = [&](entt::entity first, entt::entity second) { if (first->HasComponent() && second->HasComponent()) { @@ -62,9 +62,9 @@ namespace bw return shouldCollide; }; - triggerCallbacks.endCallback = [](Ndk::PhysicsSystem2D& /*world*/, Nz::Arbiter2D& /*arbiter*/, const Ndk::EntityHandle& bodyA, const Ndk::EntityHandle& bodyB, void* /*userdata*/) + triggerCallbacks.endCallback = [](Ndk::PhysicsSystem2D& /*world*/, Nz::Arbiter2D& /*arbiter*/, entt::entity bodyA, entt::entity bodyB, void* /*userdata*/) { - auto HandleCollision = [&](const Ndk::EntityHandle& first, const Ndk::EntityHandle& second) + auto HandleCollision = [&](entt::entity first, entt::entity second) { if (first->HasComponent() && second->HasComponent()) { @@ -81,11 +81,11 @@ namespace bw physics.RegisterCallbacks(1, triggerCallbacks); - triggerCallbacks.preSolveCallback = [](Ndk::PhysicsSystem2D& /*world*/, Nz::Arbiter2D& arbiter, const Ndk::EntityHandle& bodyA, const Ndk::EntityHandle& bodyB, void* /*userdata*/) + triggerCallbacks.preSolveCallback = [](Ndk::PhysicsSystem2D& /*world*/, Nz::Arbiter2D& arbiter, entt::entity bodyA, entt::entity bodyB, void* /*userdata*/) { bool shouldCollide = true; - auto HandleCollision = [&](const Ndk::EntityHandle& first, const Ndk::EntityHandle& second) + auto HandleCollision = [&](entt::entity first, entt::entity second) { if (first->HasComponent()) { diff --git a/src/CoreLib/Systems/AnimationSystem.cpp b/src/CoreLib/Systems/AnimationSystem.cpp index 133f5b37..627c6730 100644 --- a/src/CoreLib/Systems/AnimationSystem.cpp +++ b/src/CoreLib/Systems/AnimationSystem.cpp @@ -11,20 +11,16 @@ namespace bw AnimationSystem::AnimationSystem(SharedMatch& match) : m_match(match) { - Requires(); - SetMaximumUpdateRate(100.f); } void AnimationSystem::OnUpdate(float /*elapsedTime*/) { - Nz::UInt64 now = m_match.GetCurrentTime(); + /*Nz::UInt64 now = m_match.GetCurrentTime(); - for (const Ndk::EntityHandle& entity : GetEntities()) + for (entt::entity entity : GetEntities()) { auto& animComponent = entity->GetComponent(); animComponent.Update(now); - } + }*/ } - - Ndk::SystemIndex AnimationSystem::systemIndex; } diff --git a/src/CoreLib/Systems/InputSystem.cpp b/src/CoreLib/Systems/InputSystem.cpp index 36a30873..877b2e14 100644 --- a/src/CoreLib/Systems/InputSystem.cpp +++ b/src/CoreLib/Systems/InputSystem.cpp @@ -16,7 +16,7 @@ namespace bw void InputSystem::OnUpdate(float /*elapsedTime*/) { - for (const Ndk::EntityHandle& entity : GetEntities()) + for (entt::entity entity : GetEntities()) { auto& inputComponent = entity->GetComponent(); if (const auto& controller = inputComponent.GetController()) diff --git a/src/CoreLib/Systems/NetworkSyncSystem.cpp b/src/CoreLib/Systems/NetworkSyncSystem.cpp index e1aaab7d..1bbf4954 100644 --- a/src/CoreLib/Systems/NetworkSyncSystem.cpp +++ b/src/CoreLib/Systems/NetworkSyncSystem.cpp @@ -28,7 +28,7 @@ namespace bw { m_creationEvents.clear(); - for (const Ndk::EntityHandle& entity : GetEntities()) + for (entt::entity entity : GetEntities()) { EntityCreation& creationEvent = m_creationEvents.emplace_back(); BuildEvent(creationEvent, entity); @@ -41,7 +41,7 @@ namespace bw { m_destructionEvents.clear(); - for (const Ndk::EntityHandle& entity : GetEntities()) + for (entt::entity entity : GetEntities()) { EntityDestruction& destructionEvent = m_destructionEvents.emplace_back(); BuildEvent(destructionEvent, entity); @@ -54,7 +54,7 @@ namespace bw { m_movementEvents.clear(); - for (const Ndk::EntityHandle& entity : m_physicsEntities) + for (entt::entity entity : m_physicsEntities) { auto& entityPhys = entity->GetComponent(); if (entityPhys.IsSleeping()) @@ -76,7 +76,7 @@ namespace bw auto& entityMatch = entity->GetComponent(); creationEvent.uniqueId = entityMatch.GetUniqueId(); - if (const Ndk::EntityHandle& parent = syncComponent.GetParent()) + if (entt::entity parent = syncComponent.GetParent()) { assert(parent->GetWorld() == entity->GetWorld()); creationEvent.parent = parent->GetId(); @@ -152,7 +152,7 @@ namespace bw auto RegisterDependentId = [&](EntityId entityId) { - const Ndk::EntityHandle& propertyEntity = m_layer.GetMatch().RetrieveEntityByUniqueId(entityId); + entt::entity propertyEntity = m_layer.GetMatch().RetrieveEntityByUniqueId(entityId); if (propertyEntity) { auto& propertyEntityMatch = propertyEntity->GetComponent(); @@ -185,7 +185,7 @@ namespace bw { auto& entityWeaponWielder = entity->GetComponent(); - if (const Ndk::EntityHandle& activeWeapon = entityWeaponWielder.GetActiveWeapon()) + if (entt::entity activeWeapon = entityWeaponWielder.GetActiveWeapon()) creationEvent.weapon = activeWeapon->GetId(); } } @@ -265,7 +265,7 @@ namespace bw { auto& entityHealth = entity->GetComponent(); - slots.onDied.Connect(entityHealth.OnDied, [&](const HealthComponent* health, const Ndk::EntityHandle& /*attacker*/) + slots.onDied.Connect(entityHealth.OnDied, [&](const HealthComponent* health, entt::entity /*attacker*/) { EntityDeath deathEvent; BuildEvent(deathEvent, health->GetEntity()); @@ -273,7 +273,7 @@ namespace bw OnEntityDeath(this, deathEvent); }); - slots.onHealthChange.Connect(entityHealth.OnHealthChange, [&](HealthComponent* health, Nz::UInt16 /*newHealth*/, const Ndk::EntityHandle& /*dealer*/) + slots.onHealthChange.Connect(entityHealth.OnHealthChange, [&](HealthComponent* health, Nz::UInt16 /*newHealth*/, entt::entity /*dealer*/) { m_healthUpdateEntities.Insert(health->GetEntity()); }); diff --git a/src/CoreLib/Systems/PlayerMovementSystem.cpp b/src/CoreLib/Systems/PlayerMovementSystem.cpp index 8f8fd628..183bada6 100644 --- a/src/CoreLib/Systems/PlayerMovementSystem.cpp +++ b/src/CoreLib/Systems/PlayerMovementSystem.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include #include @@ -13,13 +12,13 @@ namespace bw { PlayerMovementSystem::PlayerMovementSystem() { - Requires(); - SetUpdateOrder(50); //< Execute after physics but before rendering + //Requires(); + //SetUpdateOrder(50); //< Execute after physics but before rendering } void PlayerMovementSystem::OnEntityAdded(Ndk::Entity* entity) { - Ndk::PhysicsComponent2D& entityPhys = entity->GetComponent(); + /*Ndk::PhysicsComponent2D& entityPhys = entity->GetComponent(); entityPhys.SetVelocityFunction([entity = entity->CreateHandle()](Nz::RigidBody2D& rigidBody, const Nz::Vector2f& gravity, float damping, float dt) { auto& movementComponent = entity->GetComponent(); @@ -34,24 +33,24 @@ namespace bw } else rigidBody.UpdateVelocity(gravity, damping, dt); - }); + });*/ } void PlayerMovementSystem::OnEntityRemoved(Ndk::Entity* entity) { - if (!entity->HasComponent()) + /*if (!entity->HasComponent()) return; Ndk::PhysicsComponent2D& entityPhys = entity->GetComponent(); if (!entityPhys.IsValid()) return; - entityPhys.ResetVelocityFunction(); + entityPhys.ResetVelocityFunction();*/ } void PlayerMovementSystem::OnUpdate(float /*elapsedTime*/) { - for (const Ndk::EntityHandle& entity : GetEntities()) + /*for (entt::entity entity : GetEntities()) { auto& inputComponent = entity->GetComponent(); auto& playerMovement = entity->GetComponent(); @@ -75,8 +74,6 @@ namespace bw if (playerMovement.UpdateFacingRightState(inputs.isLookingRight)) nodeComponent.Scale(-1.f, 1.f); - } + }*/ } - - Ndk::SystemIndex PlayerMovementSystem::systemIndex; } diff --git a/src/CoreLib/Systems/TickCallbackSystem.cpp b/src/CoreLib/Systems/TickCallbackSystem.cpp index a59956db..c8b9bd32 100644 --- a/src/CoreLib/Systems/TickCallbackSystem.cpp +++ b/src/CoreLib/Systems/TickCallbackSystem.cpp @@ -33,7 +33,7 @@ namespace bw void TickCallbackSystem::OnUpdate(float elapsedTime) { - for (const Ndk::EntityHandle& entity : m_tickableEntities) + for (entt::entity entity : m_tickableEntities) { auto& scriptComponent = entity->GetComponent(); if (!scriptComponent.CanTriggerTick(elapsedTime)) //GetComponent(); if (!weaponComponent.IsActive()) continue; - if (const Ndk::EntityHandle& owner = weaponComponent.GetOwner()) + if (entt::entity owner = weaponComponent.GetOwner()) { InputComponent& ownerInputs = owner->GetComponent(); Ndk::NodeComponent& ownerNode = owner->GetComponent(); diff --git a/src/CoreLib/TerrainLayer.cpp b/src/CoreLib/TerrainLayer.cpp index 7e14498c..6b382980 100644 --- a/src/CoreLib/TerrainLayer.cpp +++ b/src/CoreLib/TerrainLayer.cpp @@ -50,7 +50,7 @@ namespace bw try { - const Ndk::EntityHandle& entity = entityStore.CreateEntity(*this, entityTypeIndex, entityData.uniqueId, entityData.position, entityData.rotation, entityData.properties); + entt::entity entity = entityStore.CreateEntity(*this, entityTypeIndex, entityData.uniqueId, entityData.position, entityData.rotation, entityData.properties); if (entity) match.RegisterEntity(entityData.uniqueId, entity); } @@ -64,7 +64,7 @@ namespace bw void TerrainLayer::InitializeEntities() { auto& entityStore = GetMatch().GetEntityStore(); - for (const Ndk::EntityHandle& entity : GetWorld().GetEntities()) + for (entt::entity entity : GetWorld().GetEntities()) { if (!entityStore.InitializeEntity(entity)) entity->Kill(); diff --git a/src/CoreLib/Utility/CrashHandlerWin32.cpp b/src/CoreLib/Utility/CrashHandlerWin32.cpp index b8bc279c..e30cd8f7 100644 --- a/src/CoreLib/Utility/CrashHandlerWin32.cpp +++ b/src/CoreLib/Utility/CrashHandlerWin32.cpp @@ -3,6 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include +#include #ifdef NAZARA_PLATFORM_WINDOWS @@ -109,7 +110,7 @@ namespace bw if (success) std::fwprintf(stderr, L"Unhandled exception triggered: crashDump %ls generated\n", filename); else - std::fprintf(stderr, "CrashDump: MiniDumpWriteDump failed: %u (%s)\n", GetLastError(), Nz::Error::GetLastSystemError().GetConstBuffer()); + std::fprintf(stderr, "CrashDump: MiniDumpWriteDump failed: %u (%s)\n", GetLastError(), Nz::Error::GetLastSystemError().c_str()); } void GenerateCrashlog(const wchar_t* filename, EXCEPTION_POINTERS* e, DWORD /*crashedThread*/) @@ -172,7 +173,7 @@ namespace bw ss << "Game version: " << GameMajorVersion << "." << GameMinorVersion << "." << GamePatchVersion << " (" << GameVersion << ")" << "\n"; ss << "Build info: " << GetBuildInfo() << "\n"; - ss << "CPU: " << Nz::HardwareInfo::GetProcessorBrandString().ToStdString() << "\n"; + ss << "CPU: " << Nz::HardwareInfo::GetProcessorBrandString() << "\n"; ss << "\n"; @@ -321,7 +322,7 @@ namespace bw { if (!m_windbg.Load("Dbghelp.dll")) { - fprintf(stderr, "failed to load Dbghelp.dll: %s\nCrashDump will not be generated.\n", m_windbg.GetLastError().GetConstBuffer()); + fprintf(stderr, "failed to load Dbghelp.dll: %s\nCrashDump will not be generated.\n", m_windbg.GetLastError().c_str()); return false; } diff --git a/src/CoreLib/WebRequest.cpp b/src/CoreLib/WebRequest.cpp index e9093906..f0e3ce50 100644 --- a/src/CoreLib/WebRequest.cpp +++ b/src/CoreLib/WebRequest.cpp @@ -28,24 +28,24 @@ namespace bw void WebRequest::ForceProtocol(Nz::NetProtocol protocol) { - assert(protocol != Nz::NetProtocol_Unknown); + assert(protocol != Nz::NetProtocol::Unknown); auto& libcurl = WebService::GetLibcurl(); switch (protocol) { - case Nz::NetProtocol_Any: + case Nz::NetProtocol::Any: libcurl.easy_setopt(m_curlHandle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER); break; - case Nz::NetProtocol_IPv4: + case Nz::NetProtocol::IPv4: libcurl.easy_setopt(m_curlHandle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); break; - case Nz::NetProtocol_IPv6: + case Nz::NetProtocol::IPv6: libcurl.easy_setopt(m_curlHandle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6); break; - case Nz::NetProtocol_Unknown: + case Nz::NetProtocol::Unknown: break; } } diff --git a/src/CoreLib/WebService.cpp b/src/CoreLib/WebService.cpp index 57820987..b1b4e0a0 100644 --- a/src/CoreLib/WebService.cpp +++ b/src/CoreLib/WebService.cpp @@ -103,7 +103,7 @@ namespace bw std::unique_ptr libcurl = std::make_unique(); for (const char* libname : { "libcurl" NAZARA_DYNLIB_EXTENSION, "libcurl-d" NAZARA_DYNLIB_EXTENSION }) { - Nz::ErrorFlags errFlags(Nz::ErrorFlag_Silent); + Nz::ErrorFlags errFlags(Nz::ErrorMode::Silent); if (libcurl->library.Load(libname)) break; } @@ -111,16 +111,16 @@ namespace bw if (!libcurl->library.IsLoaded()) { if (error) - *error = "failed to load libcurl: " + libcurl->library.GetLastError().ToStdString(); + *error = "failed to load libcurl: " + libcurl->library.GetLastError(); return false; } - auto LoadFunction = [&](auto& funcPtr, const std::string& symbolName) + auto LoadFunction = [&](auto& funcPtr, const char* symbolName) { funcPtr = reinterpret_cast>(libcurl->library.GetSymbol(symbolName)); if (!funcPtr) - throw std::runtime_error("failed to load " + symbolName + " from curl"); + throw std::runtime_error("failed to load " + std::string(symbolName) + " from curl"); }; try diff --git a/src/MapEditor/Gizmos/EditorGizmo.hpp b/src/MapEditor/Gizmos/EditorGizmo.hpp index f96b0a2e..802c5e96 100644 --- a/src/MapEditor/Gizmos/EditorGizmo.hpp +++ b/src/MapEditor/Gizmos/EditorGizmo.hpp @@ -20,7 +20,7 @@ namespace bw EditorGizmo(Ndk::World& renderWorld, std::vector entities); virtual ~EditorGizmo(); - inline const Ndk::EntityHandle& GetSelectionOverlayEntity() const; + inline entt::entity GetSelectionOverlayEntity() const; inline const std::vector& GetTargetEntities() const; virtual bool OnMouseButtonPressed(const Nz::WindowEvent::MouseButtonEvent& mouseButton) = 0; diff --git a/src/MapEditor/Gizmos/EditorGizmo.inl b/src/MapEditor/Gizmos/EditorGizmo.inl index 7bfdc533..75324e3a 100644 --- a/src/MapEditor/Gizmos/EditorGizmo.inl +++ b/src/MapEditor/Gizmos/EditorGizmo.inl @@ -6,7 +6,7 @@ namespace bw { - inline const Ndk::EntityHandle& EditorGizmo::GetSelectionOverlayEntity() const + inline entt::entity EditorGizmo::GetSelectionOverlayEntity() const { return m_selectionOverlayEntity; } diff --git a/src/MapEditor/Gizmos/PositionGizmo.cpp b/src/MapEditor/Gizmos/PositionGizmo.cpp index dc27ae02..0f8f0796 100644 --- a/src/MapEditor/Gizmos/PositionGizmo.cpp +++ b/src/MapEditor/Gizmos/PositionGizmo.cpp @@ -44,7 +44,7 @@ namespace bw m_allowedMovements[MovementType::YAxis].Set(0.f, 1.f); m_allowedMovements[MovementType::XYAxis].Set(1.f, 1.f); - const Ndk::EntityHandle& selectionOverlayEntity = GetSelectionOverlayEntity(); + entt::entity selectionOverlayEntity = GetSelectionOverlayEntity(); m_arrowEntity = selectionOverlayEntity->GetWorld()->CreateEntity(); auto& gfx = m_arrowEntity->AddComponent(); @@ -167,7 +167,7 @@ namespace bw { Nz::Vector2f newPosition = ComputeNewPosition(mouseMoved.x, mouseMoved.y); - const Ndk::EntityHandle& selectionOverlayEntity = GetSelectionOverlayEntity(); + entt::entity selectionOverlayEntity = GetSelectionOverlayEntity(); auto& node = selectionOverlayEntity->GetComponent(); node.SetPosition(newPosition); diff --git a/src/MapEditor/Logic/EntityEditorMode.cpp b/src/MapEditor/Logic/EntityEditorMode.cpp index 69843432..a59b8a7d 100644 --- a/src/MapEditor/Logic/EntityEditorMode.cpp +++ b/src/MapEditor/Logic/EntityEditorMode.cpp @@ -9,7 +9,7 @@ namespace bw { - EntityEditorMode::EntityEditorMode(const Ndk::EntityHandle& targetEntity, EditorWindow& editorWindow) : + EntityEditorMode::EntityEditorMode(entt::entity targetEntity, EditorWindow& editorWindow) : EditorMode(editorWindow), m_targetEntity(targetEntity) { diff --git a/src/MapEditor/Logic/EntityEditorMode.hpp b/src/MapEditor/Logic/EntityEditorMode.hpp index ffe1534a..e47006d8 100644 --- a/src/MapEditor/Logic/EntityEditorMode.hpp +++ b/src/MapEditor/Logic/EntityEditorMode.hpp @@ -21,7 +21,7 @@ namespace bw class EntityEditorMode : public EditorMode { public: - EntityEditorMode(const Ndk::EntityHandle& targetEntity, EditorWindow& editorWindow); + EntityEditorMode(entt::entity targetEntity, EditorWindow& editorWindow); ~EntityEditorMode() = default; void OnEnter() override; diff --git a/src/MapEditor/Logic/TileMapEditorMode.cpp b/src/MapEditor/Logic/TileMapEditorMode.cpp index b7d28f37..bda075e5 100644 --- a/src/MapEditor/Logic/TileMapEditorMode.cpp +++ b/src/MapEditor/Logic/TileMapEditorMode.cpp @@ -16,13 +16,13 @@ namespace bw { - TileMapEditorMode::TileMapEditorMode(EditorWindow& editor, const Ndk::EntityHandle& targetEntity, TileMapData tilemapData, const std::vector& materials, const std::vector& tiles) : + TileMapEditorMode::TileMapEditorMode(EditorWindow& editor, entt::entity targetEntity, TileMapData tilemapData, const std::vector& materials, const std::vector& tiles) : EntityEditorMode(targetEntity, editor), m_editionMode(EditionMode::None), m_tilemapData(std::move(tilemapData)), m_clearMode(false) { - Nz::ImageRef eraserImage = Nz::ImageLibrary::Get("Eraser"); + std::shared_ptr eraserImage = Nz::ImageLibrary::Get("Eraser"); if (eraserImage) { m_eraserCursor = Nz::Cursor::New(); diff --git a/src/MapEditor/Logic/TileMapEditorMode.hpp b/src/MapEditor/Logic/TileMapEditorMode.hpp index 6dee539c..65ca8388 100644 --- a/src/MapEditor/Logic/TileMapEditorMode.hpp +++ b/src/MapEditor/Logic/TileMapEditorMode.hpp @@ -25,7 +25,7 @@ namespace bw class TileMapEditorMode : public EntityEditorMode { public: - TileMapEditorMode(EditorWindow& editor, const Ndk::EntityHandle& targetEntity, TileMapData tilemapData, const std::vector& materials, const std::vector& tiles); + TileMapEditorMode(EditorWindow& editor, entt::entity targetEntity, TileMapData tilemapData, const std::vector& materials, const std::vector& tiles); ~TileMapEditorMode() = default; void EnableClearMode(bool clearMode); diff --git a/src/MapEditor/Scripting/EditorElementLibrary.cpp b/src/MapEditor/Scripting/EditorElementLibrary.cpp index c04afbd1..fbefc713 100644 --- a/src/MapEditor/Scripting/EditorElementLibrary.cpp +++ b/src/MapEditor/Scripting/EditorElementLibrary.cpp @@ -19,14 +19,14 @@ namespace bw elementMetatable["GetLayerIndex"] = LuaFunction([](const sol::table& entityTable) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); return entity->GetComponent().GetLayerIndex(); }); elementMetatable["GetProperty"] = LuaFunction([](sol::this_state s, const sol::table& table, const std::string& propertyName) -> sol::object { - Ndk::EntityHandle entity = AssertScriptEntity(table); + entt::entity entity = AssertScriptEntity(table); auto& entityScript = entity->GetComponent(); diff --git a/src/MapEditor/Scripting/EditorEntityLibrary.cpp b/src/MapEditor/Scripting/EditorEntityLibrary.cpp index 5e29a8eb..48a4a971 100644 --- a/src/MapEditor/Scripting/EditorEntityLibrary.cpp +++ b/src/MapEditor/Scripting/EditorEntityLibrary.cpp @@ -20,7 +20,7 @@ namespace bw RegisterEditorLibrary(elementMetatable); } - void EditorEntityLibrary::InitRigidBody(lua_State* /*L*/, const Ndk::EntityHandle& /*entity*/, float /*mass*/) + void EditorEntityLibrary::InitRigidBody(lua_State* /*L*/, entt::entity /*entity*/, float /*mass*/) { // Do nothing } @@ -31,7 +31,7 @@ namespace bw elementMetatable["AddLayer"] = LuaFunction([&](sol::this_state L, const sol::table& entityTable, const sol::table& parameters) { - Ndk::EntityHandle entity = AssertScriptEntity(entityTable); + entt::entity entity = AssertScriptEntity(entityTable); MapCanvas& mapCanvas = *m_editorWindow.GetMapCanvas(); diff --git a/src/MapEditor/Scripting/EditorEntityLibrary.hpp b/src/MapEditor/Scripting/EditorEntityLibrary.hpp index cb2d80ef..e6a467be 100644 --- a/src/MapEditor/Scripting/EditorEntityLibrary.hpp +++ b/src/MapEditor/Scripting/EditorEntityLibrary.hpp @@ -24,7 +24,7 @@ namespace bw void RegisterLibrary(sol::table& elementMetatable) override; protected: - void InitRigidBody(lua_State* L, const Ndk::EntityHandle& entity, float mass) override; + void InitRigidBody(lua_State* L, entt::entity entity, float mass) override; private: void RegisterEditorLibrary(sol::table& elementMetatable); diff --git a/src/MapEditor/Scripting/EditorEntityStore.cpp b/src/MapEditor/Scripting/EditorEntityStore.cpp index dd566d65..51eb6434 100644 --- a/src/MapEditor/Scripting/EditorEntityStore.cpp +++ b/src/MapEditor/Scripting/EditorEntityStore.cpp @@ -11,9 +11,9 @@ namespace bw { - std::optional EditorEntityStore::Instantiate(LayerIndex layerIndex, Ndk::World& world, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, const Ndk::EntityHandle& parent) const + std::optional EditorEntityStore::Instantiate(LayerIndex layerIndex, Ndk::World& world, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, entt::entity parent) const { - const Ndk::EntityHandle& entity = ClientEditorEntityStore::InstantiateEntity(world, entityIndex, position, rotation, scale, std::move(properties), parent); + entt::entity entity = ClientEditorEntityStore::InstantiateEntity(world, entityIndex, position, rotation, scale, std::move(properties), parent); if (!entity) return std::nullopt; @@ -27,7 +27,7 @@ namespace bw return visualEntity; } - void EditorEntityStore::BindCallbacks(const ScriptedEntity& /*entityClass*/, const Ndk::EntityHandle& /*entity*/) const + void EditorEntityStore::BindCallbacks(const ScriptedEntity& /*entityClass*/, entt::entity /*entity*/) const { // Don't bind any callback in the editor } diff --git a/src/MapEditor/Scripting/EditorEntityStore.hpp b/src/MapEditor/Scripting/EditorEntityStore.hpp index a8ef3ac9..d0a5357e 100644 --- a/src/MapEditor/Scripting/EditorEntityStore.hpp +++ b/src/MapEditor/Scripting/EditorEntityStore.hpp @@ -20,10 +20,10 @@ namespace bw inline EditorEntityStore(MapCanvas& mapCanvas, ClientAssetStore& assetStore, const Logger& logger, std::shared_ptr context); ~EditorEntityStore() = default; - std::optional Instantiate(LayerIndex layerIndex, Ndk::World& world, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, const Ndk::EntityHandle& parent = Ndk::EntityHandle::InvalidHandle) const; + std::optional Instantiate(LayerIndex layerIndex, Ndk::World& world, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, entt::entity parent = entt::null) const; private: - void BindCallbacks(const ScriptedEntity& entityClass, const Ndk::EntityHandle& entity) const override; + void BindCallbacks(const ScriptedEntity& entityClass, entt::entity entity) const override; std::shared_ptr CreateElement() const override; void InitializeElement(sol::main_table& elementTable, ScriptedEntity& element) override; diff --git a/src/MapEditor/Scripting/EditorScriptingLibrary.cpp b/src/MapEditor/Scripting/EditorScriptingLibrary.cpp index b9b16ffb..cd456c65 100644 --- a/src/MapEditor/Scripting/EditorScriptingLibrary.cpp +++ b/src/MapEditor/Scripting/EditorScriptingLibrary.cpp @@ -95,7 +95,7 @@ namespace bw sol::state& state = context.GetLuaState(); state.new_usertype("TileMapEditorMode", - "new", sol::factories([](EditorWindow& editor, const Ndk::EntityHandle& targetEntity, TileMapData tilemapData, const std::vector& materials, const std::vector& tiles) -> std::shared_ptr + "new", sol::factories([](EditorWindow& editor, entt::entity targetEntity, TileMapData tilemapData, const std::vector& materials, const std::vector& tiles) -> std::shared_ptr { return std::make_shared(editor, targetEntity, std::move(tilemapData), materials, tiles); }), diff --git a/src/MapEditor/Widgets/EditorWindow.cpp b/src/MapEditor/Widgets/EditorWindow.cpp index 0b02ad61..de2ede12 100644 --- a/src/MapEditor/Widgets/EditorWindow.cpp +++ b/src/MapEditor/Widgets/EditorWindow.cpp @@ -647,7 +647,7 @@ namespace bw std::string filepathStr = filepath.generic_u8string(); Nz::File file(filepath.generic_u8string()); - if (!file.Open(Nz::OpenMode_ReadOnly)) + if (!file.Open(Nz::OpenMode::ReadOnly)) { bwLog(GetLogger(), LogLevel::Warning, "failed to open script {} when preparing map test", filepathStr); continue; @@ -1173,7 +1173,7 @@ namespace bw EntityInfo entityInfo; entityInfo.position = AlignPosition(GetCameraCenter(), layer.positionAlignment); - createEntityDialog->Open(workingMap.GetFreeUniqueId(), layerIndex, entityInfo, Ndk::EntityHandle::InvalidHandle, [this, layerIndex](EntityInfoDialog* /*createEntityDialog*/, EntityInfo&& entityInfo, EntityInfoUpdateFlags /*dummy*/) + createEntityDialog->Open(workingMap.GetFreeUniqueId(), layerIndex, entityInfo, entt::null, [this, layerIndex](EntityInfoDialog* /*createEntityDialog*/, EntityInfo&& entityInfo, EntityInfoUpdateFlags /*dummy*/) { Map& map = GetWorkingMapMut(); std::size_t entityIndex = map.GetEntityCount(layerIndex); diff --git a/src/MapEditor/Widgets/EditorWindowPrefabs.cpp b/src/MapEditor/Widgets/EditorWindowPrefabs.cpp index 9521396e..2700e4d2 100644 --- a/src/MapEditor/Widgets/EditorWindowPrefabs.cpp +++ b/src/MapEditor/Widgets/EditorWindowPrefabs.cpp @@ -129,7 +129,7 @@ namespace bw std::string content = Map::Serialize(prefab).dump(1, '\t'); - Nz::File infoFile(path.toStdString(), Nz::OpenMode_WriteOnly | Nz::OpenMode_Truncate); + Nz::File infoFile(path.toStdString(), Nz::OpenMode::WriteOnly | Nz::OpenMode::Truncate); if (!infoFile.IsOpen()) { QMessageBox::critical(m_parent, tr("Failed to save prefab"), tr("An error occurred while opening the prefab file")); @@ -160,7 +160,7 @@ namespace bw if (prefabPath.isEmpty()) return; - Nz::File infoFile(prefabPath.toStdString(), Nz::OpenMode_ReadOnly); + Nz::File infoFile(prefabPath.toStdString(), Nz::OpenMode::ReadOnly); if (!infoFile.IsOpen()) { QMessageBox::critical(m_parent, tr("Failed to load prefab"), tr("An error occurred while opening the prefab file")); diff --git a/src/MapEditor/Widgets/EntityInfoDialog.cpp b/src/MapEditor/Widgets/EntityInfoDialog.cpp index ca11c84f..734f09e6 100644 --- a/src/MapEditor/Widgets/EntityInfoDialog.cpp +++ b/src/MapEditor/Widgets/EntityInfoDialog.cpp @@ -1257,7 +1257,7 @@ namespace bw return std::make_pair(propertyData.type, propertyData.isArray); } - void EntityInfoDialog::Open(EntityId uniqueId, LayerIndex layerIndex, std::optional info, const Ndk::EntityHandle& targetEntity, Callback callback) + void EntityInfoDialog::Open(EntityId uniqueId, LayerIndex layerIndex, std::optional info, entt::entity targetEntity, Callback callback) { m_entityLayer = layerIndex; m_entityUniqueId = uniqueId; diff --git a/src/MapEditor/Widgets/EntityInfoDialog.hpp b/src/MapEditor/Widgets/EntityInfoDialog.hpp index 60d830d3..b4af0caf 100644 --- a/src/MapEditor/Widgets/EntityInfoDialog.hpp +++ b/src/MapEditor/Widgets/EntityInfoDialog.hpp @@ -59,9 +59,9 @@ namespace bw const PropertyValue& GetProperty(const std::string& propertyName) const; std::pair GetPropertyType(const std::string& propertyName) const; - inline const Ndk::EntityHandle& GetTargetEntity() const; + inline entt::entity GetTargetEntity() const; - void Open(EntityId uniqueId, LayerIndex layerIndex, std::optional info, const Ndk::EntityHandle& targetEntity, Callback callback); + void Open(EntityId uniqueId, LayerIndex layerIndex, std::optional info, entt::entity targetEntity, Callback callback); void UpdatePosition(const Nz::Vector2f& position); void UpdateRotation(const Nz::DegreeAnglef& rotation); diff --git a/src/MapEditor/Widgets/EntityInfoDialog.inl b/src/MapEditor/Widgets/EntityInfoDialog.inl index 40c72ca2..2bfca6ee 100644 --- a/src/MapEditor/Widgets/EntityInfoDialog.inl +++ b/src/MapEditor/Widgets/EntityInfoDialog.inl @@ -21,7 +21,7 @@ namespace bw return m_entityInfo.rotation; } - const Ndk::EntityHandle& EntityInfoDialog::GetTargetEntity() const + entt::entity EntityInfoDialog::GetTargetEntity() const { return m_targetEntity; } diff --git a/src/MapEditor/Widgets/MapCanvas.cpp b/src/MapEditor/Widgets/MapCanvas.cpp index 7cd0569b..c1c01d39 100644 --- a/src/MapEditor/Widgets/MapCanvas.cpp +++ b/src/MapEditor/Widgets/MapCanvas.cpp @@ -99,7 +99,7 @@ namespace bw m_entityGizmo.reset(); } - const Ndk::EntityHandle& MapCanvas::CreateEntity(LayerIndex layerIndex, EntityId uniqueId, const std::string& entityClass, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, PropertyValueMap properties) + entt::entity MapCanvas::CreateEntity(LayerIndex layerIndex, EntityId uniqueId, const std::string& entityClass, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, PropertyValueMap properties) { assert(layerIndex < m_layers.size()); auto& layer = m_layers[layerIndex]; @@ -170,11 +170,11 @@ namespace bw m_isPhysicsDebugDrawEnabled = enable; } - void MapCanvas::ForEachEntity(std::function func) + void MapCanvas::ForEachEntity(std::function func) { for (auto&& [uniqueId, visualEntityHandle] : m_entitiesByUniqueId) { - const Ndk::EntityHandle& entity = visualEntityHandle->GetEntity(); + entt::entity entity = visualEntityHandle->GetEntity(); if (!entity) continue; @@ -284,7 +284,7 @@ namespace bw m_weaponStore->LoadDirectory("weapons"); m_weaponStore->Resolve(); - ForEachEntity([this](const Ndk::EntityHandle& entity) + ForEachEntity([this](entt::entity entity) { if (entity->HasComponent()) m_entityStore->UpdateEntityElement(entity); @@ -307,11 +307,11 @@ namespace bw m_layers.emplace_back(*this, LayerIndex(i)); } - const Ndk::EntityHandle& MapCanvas::RetrieveEntityByUniqueId(EntityId uniqueId) const + entt::entity MapCanvas::RetrieveEntityByUniqueId(EntityId uniqueId) const { auto it = m_entitiesByUniqueId.find(uniqueId); if (it == m_entitiesByUniqueId.end()) - return Ndk::EntityHandle::InvalidHandle; + return entt::null; return it.value()->GetEntity(); } @@ -325,7 +325,7 @@ namespace bw return it->second; } - EntityId MapCanvas::RetrieveUniqueIdByEntity(const Ndk::EntityHandle& entity) const + EntityId MapCanvas::RetrieveUniqueIdByEntity(entt::entity entity) const { if (!entity || !entity->HasComponent()) return InvalidEntityId; diff --git a/src/MapEditor/Widgets/MapCanvas.hpp b/src/MapEditor/Widgets/MapCanvas.hpp index bc64c27c..3f176970 100644 --- a/src/MapEditor/Widgets/MapCanvas.hpp +++ b/src/MapEditor/Widgets/MapCanvas.hpp @@ -38,19 +38,19 @@ namespace bw void Clear(); void ClearEntitySelection(); - const Ndk::EntityHandle& CreateEntity(LayerIndex layerIndex, EntityId uniqueId, const std::string& entityClass, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, PropertyValueMap properties); + entt::entity CreateEntity(LayerIndex layerIndex, EntityId uniqueId, const std::string& entityClass, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, PropertyValueMap properties); void DeleteEntity(EntityId uniqueId); void EditEntitiesPosition(const std::vector& entityIds); void EnablePhysicsDebugDraw(bool enable); - void ForEachEntity(std::function func) override; + void ForEachEntity(std::function func) override; template void ForEachEntity(F&& func); template void ForEachMapEntity(F&& func); MapCanvasLayer* GetActiveLayer(); const MapCanvasLayer* GetActiveLayer() const; - inline const std::shared_ptr& GetAssetDirectory(); + inline const std::shared_ptr& GetAssetDirectory(); EditorEntityStore& GetEntityStore() override; const EditorEntityStore& GetEntityStore() const override; MapCanvasLayer& GetLayer(LayerIndex layerIndex) override; @@ -59,7 +59,7 @@ namespace bw const NetworkStringStore& GetNetworkStringStore() const override; inline ScriptingContext& GetScriptingContext(); inline const ScriptingContext& GetScriptingContext() const; - inline const std::shared_ptr& GetScriptDirectory(); + inline const std::shared_ptr& GetScriptDirectory(); std::shared_ptr GetSharedGamemode() const override; ClientWeaponStore& GetWeaponStore() override; const ClientWeaponStore& GetWeaponStore() const override; @@ -67,9 +67,9 @@ namespace bw void ReloadScripts(); void ResetLayers(std::size_t layerCount); - const Ndk::EntityHandle& RetrieveEntityByUniqueId(EntityId uniqueId) const override; + entt::entity RetrieveEntityByUniqueId(EntityId uniqueId) const override; const LayerVisualEntityHandle& RetrieveLayerEntityByUniqueId(EntityId uniqueId) const; - EntityId RetrieveUniqueIdByEntity(const Ndk::EntityHandle& entity) const override; + EntityId RetrieveUniqueIdByEntity(entt::entity entity) const override; void ShowGrid(bool show); @@ -113,8 +113,8 @@ namespace bw std::optional m_currentLayer; std::shared_ptr m_gamemode; std::shared_ptr m_scriptingContext; - std::shared_ptr m_assetDirectory; - std::shared_ptr m_scriptDirectory; + std::shared_ptr m_assetDirectory; + std::shared_ptr m_scriptDirectory; tsl::hopscotch_map m_entitiesByUniqueId; std::vector m_layers; std::unique_ptr m_entityGizmo; diff --git a/src/MapEditor/Widgets/MapCanvas.inl b/src/MapEditor/Widgets/MapCanvas.inl index 175d819e..03af76cb 100644 --- a/src/MapEditor/Widgets/MapCanvas.inl +++ b/src/MapEditor/Widgets/MapCanvas.inl @@ -9,7 +9,7 @@ namespace bw template void MapCanvas::ForEachEntity(F&& func) { - for (const Ndk::EntityHandle& entity : GetWorld().GetEntities()) + for (entt::entity entity : GetWorld().GetEntities()) func(entity); } @@ -40,7 +40,7 @@ namespace bw return &m_layers[layerIndex]; } - inline const std::shared_ptr& MapCanvas::GetAssetDirectory() + inline const std::shared_ptr& MapCanvas::GetAssetDirectory() { return m_assetDirectory; } @@ -55,7 +55,7 @@ namespace bw return *m_scriptingContext; } - inline const std::shared_ptr& MapCanvas::GetScriptDirectory() + inline const std::shared_ptr& MapCanvas::GetScriptDirectory() { return m_scriptDirectory; } diff --git a/src/MapEditor/Widgets/MapCanvasLayer.cpp b/src/MapEditor/Widgets/MapCanvasLayer.cpp index 9d0ffb67..cf93459a 100644 --- a/src/MapEditor/Widgets/MapCanvasLayer.cpp +++ b/src/MapEditor/Widgets/MapCanvasLayer.cpp @@ -39,7 +39,7 @@ namespace bw { bwLog(m_mapCanvas.GetLogger(), LogLevel::Error, "Failed to instantiate entity of type {}: {}", entityClass, e.what()); - const Ndk::EntityHandle& dummyEntity = GetWorld().CreateEntity(); + entt::entity dummyEntity = GetWorld().CreateEntity(); dummyEntity->AddComponent(); LayerVisualEntity visualEntity(dummyEntity, GetLayerIndex(), uniqueId); diff --git a/src/MapEditor/Widgets/PlayWindow.cpp b/src/MapEditor/Widgets/PlayWindow.cpp index 54b39226..46a1efed 100644 --- a/src/MapEditor/Widgets/PlayWindow.cpp +++ b/src/MapEditor/Widgets/PlayWindow.cpp @@ -28,7 +28,7 @@ namespace bw renderSystem.SetDefaultBackground(nullptr); renderSystem.SetGlobalUp(Nz::Vector3f::Down()); - const Ndk::EntityHandle& camera2D = m_world.CreateEntity(); + entt::entity camera2D = m_world.CreateEntity(); camera2D->AddComponent(); auto& cameraComponent2D = camera2D->AddComponent(); diff --git a/src/MapEditor/Widgets/TileSelectionWidget.cpp b/src/MapEditor/Widgets/TileSelectionWidget.cpp index d2900941..d8d9762e 100644 --- a/src/MapEditor/Widgets/TileSelectionWidget.cpp +++ b/src/MapEditor/Widgets/TileSelectionWidget.cpp @@ -88,7 +88,7 @@ namespace bw matIndex++; } - const Ndk::EntityHandle& tilemapEntity = m_tileSelectionCanvas->GetWorld().CreateEntity(); + entt::entity tilemapEntity = m_tileSelectionCanvas->GetWorld().CreateEntity(); tilemapEntity->AddComponent(); tilemapEntity->AddComponent().Attach(tileMap); tilemapEntity->Disable(); diff --git a/xmake-repo/packages/n/nazaraengine/xmake.lua b/xmake-repo/packages/n/nazaraengine/xmake.lua index 4d6a57af..fa4821b8 100644 --- a/xmake-repo/packages/n/nazaraengine/xmake.lua +++ b/xmake-repo/packages/n/nazaraengine/xmake.lua @@ -10,51 +10,30 @@ package("nazaraengine") add_configs("audio", {description = "Includes the audio module", default = true, type = "boolean"}) add_configs("graphics", {description = "Includes the graphics module", default = true, type = "boolean"}) - add_configs("lua", {description = "Includes the lua module", default = true, type = "boolean"}) add_configs("network", {description = "Includes the network module", default = true, type = "boolean"}) add_configs("physics2d", {description = "Includes the 2D physics module", default = true, type = "boolean"}) add_configs("physics3d", {description = "Includes the 3D physics module", default = true, type = "boolean"}) add_configs("platform", {description = "Includes the platform module", default = true, type = "boolean"}) add_configs("renderer", {description = "Includes the renderer module", default = true, type = "boolean"}) - add_configs("noise", {description = "Includes the noise module", default = true, type = "boolean"}) - add_configs("sdk", {description = "Includes the SDK", default = true, type = "boolean"}) - add_configs("server", {description = "Only includes server modules (takes priority over other options)", default = false, type = "boolean"}) add_configs("utility", {description = "Includes the utility module", default = true, type = "boolean"}) - add_configs("clientsdk", {description = "Includes the Client SDK", default = true, type = "boolean"}) add_configs("plugin-assimp", {description = "Includes the assimp plugin", default = false, type = "boolean"}) if is_plat("linux") then add_syslinks("pthread") end - local function has_clientsdk(package) - return not package:config("server") or package:config("sdk") - end - - local function has_sdk(package) - return package:config("sdk") or has_clientsdk(package) - end - local function has_audio(package) - return not package:config("server") and (package:config("audio") or has_sdk(package)) + return not package:config("server") and (package:config("audio")) end local function has_graphics(package) - return not package:config("server") and (package:config("graphics") or has_sdk(package)) - end - - local function has_lua(package) - return package:config("lua") or has_sdk(package) + return not package:config("server") and (package:config("graphics")) end local function has_network(package) return package:config("network") end - local function has_noise(package) - return package:config("noise") - end - local function has_renderer(package) return not package:config("server") and (package:config("renderer") or has_graphics(package)) end @@ -64,11 +43,11 @@ package("nazaraengine") end local function has_physics2d(package) - return package:config("physics2d") or has_sdk(package) + return package:config("physics2d") end local function has_physics3d(package) - return package:config("physics3d") or has_sdk(package) + return package:config("physics3d") end local function has_utility(package) @@ -80,6 +59,21 @@ package("nazaraengine") end on_load("windows", "linux", "macosx", "mingw", function (package) + local nazaradir = os.getenv("NAZARA_ENGINE_PATH") or "C:/Projets/Perso/NazaraNext/NazaraEngine" + if not nazaradir then + raise("missing NAZARA_ENGINE_PATH") + end + package:set("installdir", nazaradir) + end) + + on_fetch(function (package) + local defines = {} + local includedirs = package:installdir("include") + local links = {} + local libprefix = package:debug() and "debug" or "releasedbg" + local linkdirs = package:installdir("bin/" .. package:plat() .. "_" .. package:arch() .. "_" .. libprefix) + local syslinks = {} + local prefix = "Nazara" local suffix = package:config("shared") and "" or "-s" @@ -88,223 +82,53 @@ package("nazaraengine") end if not package:config("shared") then - package:add("defines", "NAZARA_STATIC") - end - - if has_clientsdk(package) then - package:add("links", prefix .. "ClientSDK" .. suffix) - end - - if has_sdk(package) then - package:add("links", prefix .. "SDK" .. suffix) + table.insert(defines, "NAZARA_STATIC") end if has_audio(package) then - package:add("links", prefix .. "Audio" .. suffix) - end - - if has_lua(package) then - --package:add("deps", "lua") - package:add("links", prefix .. "Lua" .. suffix) + table.insert(links, prefix .. "Audio" .. suffix) end if has_network(package) then - package:add("links", prefix .. "Network" .. suffix) - end - - if has_noise(package) then - package:add("links", prefix .. "Noise" .. suffix) + table.insert(links, prefix .. "Network" .. suffix) end if has_physics2d(package) then - package:add("links", prefix .. "Physics2D" .. suffix) + table.insert(links, prefix .. "Physics2D" .. suffix) end if has_physics3d(package) then - package:add("links", prefix .. "Physics3D" .. suffix) + table.insert(links, prefix .. "Physics3D" .. suffix) end if has_graphics(package) then - package:add("links", prefix .. "Graphics" .. suffix) + table.insert(links, prefix .. "Graphics" .. suffix) end if has_renderer(package) then - package:add("links", prefix .. "Renderer" .. suffix) + table.insert(links, prefix .. "Renderer" .. suffix) if package:is_plat("windows", "mingw") then - package:add("syslinks", "gdi32", "user32", "advapi32") + table.insert(syslinks, "gdi32") + table.insert(syslinks, "user32") + table.insert(syslinks, "advapi32") end end if has_platform(package) then - --if package:is_plat("linux") then - -- package:add("deps", "libsdl") - --end - - package:add("links", prefix .. "Platform" .. suffix) + table.insert(links, prefix .. "Platform" .. suffix) end if has_utility(package) then - --if package:is_plat("linux") then - -- package:add("deps", "freetype") - --end - - package:add("links", prefix .. "Utility" .. suffix) - end - - if has_assimp_plugin(package) then - if package:is_plat("linux") then - package:add("deps", "assimp") - end - end - - package:add("links", prefix .. "Core" .. suffix) - end) - - on_install("windows", "linux", "mingw", function (package) - -- Remove potential leftovers from previous build - os.rm("lib") - - local premakeOptions = {"--verbose", "--excludes-examples", " --excludes-tests"} - if not has_audio(package) then - table.insert(premakeOptions, "--excludes-module-audio") - end - - if not has_graphics(package) then - table.insert(premakeOptions, "--excludes-module-graphics") - end - - if not has_lua(package) then - table.insert(premakeOptions, "--excludes-externlib-lua") - table.insert(premakeOptions, "--excludes-module-lua") - end - - if not has_network(package) then - table.insert(premakeOptions, "--excludes-module-network") + table.insert(links, prefix .. "Utility" .. suffix) end - if not has_noise(package) then - table.insert(premakeOptions, "--excludes-module-noise") - end - - if not has_platform(package) then - table.insert(premakeOptions, "--excludes-module-platform") - end - - if not has_physics2d(package) then - table.insert(premakeOptions, "--excludes-externlib-chipmunk") - table.insert(premakeOptions, "--excludes-module-physics2d") - end + table.insert(links, prefix .. "Core" .. suffix) - if not has_physics3d(package) then - table.insert(premakeOptions, "--excludes-externlib-newton") - table.insert(premakeOptions, "--excludes-module-physics3d") - end - - if not has_renderer(package) then - table.insert(premakeOptions, "--excludes-module-renderer") - end - - if not has_utility(package) then - table.insert(premakeOptions, "--excludes-externlib-stb_image") - table.insert(premakeOptions, "--excludes-module-utility") - end - - if not has_assimp_plugin(package) then - table.insert(premakeOptions, "--excludes-tool-assimp") - end - - if not has_sdk(package) then - table.insert(premakeOptions, "--excludes-tool-sdk") - end - - if not has_clientsdk(package) then - table.insert(premakeOptions, "--excludes-tool-clientsdk") - end - - local archName = { - x86 = "x86", - x86_64 = "x64", - x64 = "x64" + return { + defines = defines, + includedirs = includedirs, + links = links, + linkdirs = linkdirs, + syslinks = syslinks } - - local premakeArch = assert(archName[package:arch()]) - local libDir - - local premakeExecutable = is_host("windows") and "./premake5.exe" or "./premake5-linux64" - - -- patch Newton MinGW defines check - io.replace("thirdparty/src/newton/dgCore/dgTypes.cpp", [[#if (defined (_MSC_VER) || defined (_MINGW_32_VER) || defined (_MINGW_64_VER))]], [[#if (defined (_MSC_VER) || defined (__MINGW32__) || defined (__MINGW64__))]], {plain=true}) - - os.cd("build") - if package:is_plat("windows") then - os.vrun(premakeExecutable .. " " .. table.concat(premakeOptions, " ") .. " vs2019") - os.cd("vs2019") - - local configs = {} - local arch = package:is_arch("x86") and "Win32" or "x64" - local mode = (package:debug() and "Debug" or "Release") .. (package:config("shared") and "Dynamic" or "Static") - - table.insert(configs, "/property:Configuration=" .. mode) - table.insert(configs, "/property:Platform=" .. arch) - - import("package.tools.msbuild").build(package, configs) - - libDir = "msvc" - elseif package:is_plat("linux", "mingw") then - os.vrun(premakeExecutable .. " " .. table.concat(premakeOptions, " ") .. " gmake2") - os.cd("gmake2") - - local configs = {} - table.insert(configs, "config=" .. (package:debug() and "debug" or "release") .. (package:config("shared") and "dynamic" or "static") .. "_" .. premakeArch) - - -- mingw-make doesn't seem to like parallel building (or maybe it's premake?) - if package:is_plat("mingw") then - local opt = package:is_plat("mingw") and {jobs=1} or nil - import("package.tools.make").build(package, table.join(configs, {"chipmunk"}), opt) - end - - import("package.tools.make").build(package, configs, opt) - - libDir = package:is_plat("mingw") and "mingw" or "gmake" - else - os.raise("unexpected platform") - end - - os.cd("../../") - os.cp("include/Nazara", package:installdir("include")) - os.cp("SDK/include/NDK", package:installdir("include")) - - if package:is_plat("windows") then - os.cp("lib/" .. libDir .. "/" .. premakeArch .. "/*.dll", package:installdir("bin")) - os.cp("lib/" .. libDir .. "/" .. premakeArch .. "/*.lib", package:installdir("lib")) - else - os.cp("lib/" .. libDir .. "/" .. premakeArch .. "/*", package:installdir("lib")) - end - - if package:is_plat("windows", "mingw") then - if has_audio(package) then - os.cp("thirdparty/lib/common/" .. premakeArch .. "/soft_oal.dll", package:installdir("bin")) - end - - if has_platform(package) then - os.cp("thirdparty/lib/common/" .. premakeArch .. "/SDL2.dll", package:installdir("bin")) - end - - if has_utility(package) then - os.cp("thirdparty/lib/common/" .. premakeArch .. "/libsndfile-1.dll", package:installdir("bin")) - end - - if has_assimp_plugin(package) then - os.cp("thirdparty/lib/common/" .. premakeArch .. "/assimp.dll", package:installdir("bin")) - end - end - end) - - on_test(function (package) - assert(package:check_cxxsnippets({test = [[ - void test(int args, char** argv) { - Nz::Clock c; - c.Restart(); - } - ]]}, {includes = "Nazara/Core.hpp"})) end) diff --git a/xmake-requires.lock b/xmake-requires.lock index eb85d68d..e0bc93fa 100644 --- a/xmake-requires.lock +++ b/xmake-requires.lock @@ -6,16 +6,16 @@ ["cmake#31fecfc4"] = { repo = { branch = "master", - commit = "8d4f0875fe9a3c63be4948cefca9f232954e3e87", + commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", url = "https://gitlab.com/tboox/xmake-repo.git" }, - version = "3.21.0" + version = "3.22.1" }, ["concurrentqueue#31fecfc4"] = { branch = "master", repo = { branch = "master", - commit = "8d4f0875fe9a3c63be4948cefca9f232954e3e87", + commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", url = "https://gitlab.com/tboox/xmake-repo.git" }, version = "master" @@ -23,7 +23,7 @@ ["cxxopts#31fecfc4"] = { repo = { branch = "master", - commit = "8d4f0875fe9a3c63be4948cefca9f232954e3e87", + commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", url = "https://gitlab.com/tboox/xmake-repo.git" }, version = "v2.2.0" @@ -31,15 +31,15 @@ ["fmt#7572102e"] = { repo = { branch = "master", - commit = "8d4f0875fe9a3c63be4948cefca9f232954e3e87", + commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", url = "https://gitlab.com/tboox/xmake-repo.git" }, - version = "8.0.1" + version = "8.1.1" }, ["hopscotch-map#31fecfc4"] = { repo = { branch = "master", - commit = "8d4f0875fe9a3c63be4948cefca9f232954e3e87", + commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", url = "https://gitlab.com/tboox/xmake-repo.git" }, version = "v2.3.0" @@ -47,10 +47,10 @@ ["libcurl#31fecfc4"] = { repo = { branch = "master", - commit = "8d4f0875fe9a3c63be4948cefca9f232954e3e87", + commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", url = "https://gitlab.com/tboox/xmake-repo.git" }, - version = "7.73.0" + version = "7.82.0" }, ["nazaraengine 2021.08.28#31fecfc4"] = { repo = { @@ -67,23 +67,23 @@ ["nlohmann_json#31fecfc4"] = { repo = { branch = "master", - commit = "8d4f0875fe9a3c63be4948cefca9f232954e3e87", + commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", url = "https://gitlab.com/tboox/xmake-repo.git" }, - version = "v3.10.0" + version = "v3.10.5" }, ["openssl#31fecfc4"] = { repo = { branch = "master", - commit = "8d4f0875fe9a3c63be4948cefca9f232954e3e87", + commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", url = "https://gitlab.com/tboox/xmake-repo.git" }, - version = "1.1.1k" + version = "1.1.1m" }, ["sol2 v3.2.1#72267bd5"] = { repo = { branch = "master", - commit = "8d4f0875fe9a3c63be4948cefca9f232954e3e87", + commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", url = "https://gitlab.com/tboox/xmake-repo.git" }, version = "v3.2.1" @@ -91,7 +91,7 @@ ["tl_expected#31fecfc4"] = { repo = { branch = "master", - commit = "8d4f0875fe9a3c63be4948cefca9f232954e3e87", + commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", url = "https://gitlab.com/tboox/xmake-repo.git" }, version = "v1.0.0" @@ -99,26 +99,26 @@ ["tl_function_ref#31fecfc4"] = { repo = { branch = "master", - commit = "8d4f0875fe9a3c63be4948cefca9f232954e3e87", + commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", url = "https://gitlab.com/tboox/xmake-repo.git" }, version = "v1.0.0" } }, - ["mingw|x86_64"] = { + ["windows|x64"] = { ["cmake#31fecfc4"] = { repo = { branch = "master", - commit = "7753c8b6b3a3f95d1aaf7b8b806ff47902e7ea4d", + commit = "4dd06825e3c821732a036da0760c48b1521cab40", url = "https://github.com/xmake-io/xmake-repo.git" }, - version = "3.21.0" + version = "3.22.1" }, ["concurrentqueue#31fecfc4"] = { branch = "master", repo = { branch = "master", - commit = "7753c8b6b3a3f95d1aaf7b8b806ff47902e7ea4d", + commit = "cdb9b43c6328aa32e9fae40de406e84beb98d77e", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "master" @@ -126,110 +126,23 @@ ["cxxopts#31fecfc4"] = { repo = { branch = "master", - commit = "7753c8b6b3a3f95d1aaf7b8b806ff47902e7ea4d", + commit = "b94e5581b481e06a70edc525b74c67020d64d23d", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v2.2.0" }, - ["fmt#7572102e"] = { - repo = { - branch = "master", - commit = "7753c8b6b3a3f95d1aaf7b8b806ff47902e7ea4d", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "8.0.1" - }, - ["hopscotch-map#31fecfc4"] = { - repo = { - branch = "master", - commit = "7753c8b6b3a3f95d1aaf7b8b806ff47902e7ea4d", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v2.3.0" - }, - ["libcurl#31fecfc4"] = { - repo = { - branch = "master", - commit = "7753c8b6b3a3f95d1aaf7b8b806ff47902e7ea4d", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "7.73.0" - }, - ["nazaraengine 2021.06.10#31fecfc4"] = { - repo = { - url = "xmake-repo" - }, - version = "2021.06.10" - }, - ["nazaraengine~server 2021.06.10#e1c6474d"] = { - repo = { - url = "xmake-repo" - }, - version = "2021.06.10" - }, - ["nlohmann_json#31fecfc4"] = { - repo = { - branch = "master", - commit = "7753c8b6b3a3f95d1aaf7b8b806ff47902e7ea4d", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v3.10.0" - }, - ["sol2 v3.2.1#72267bd5"] = { - repo = { - branch = "master", - commit = "7753c8b6b3a3f95d1aaf7b8b806ff47902e7ea4d", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v3.2.1" - }, - ["tl_expected#31fecfc4"] = { + ["entt#31fecfc4"] = { repo = { branch = "master", - commit = "7753c8b6b3a3f95d1aaf7b8b806ff47902e7ea4d", + commit = "424c353c446f4440eef01d68a60693e5ade990cf", url = "https://github.com/xmake-io/xmake-repo.git" }, - version = "v1.0.0" - }, - ["tl_function_ref#31fecfc4"] = { - repo = { - branch = "master", - commit = "7753c8b6b3a3f95d1aaf7b8b806ff47902e7ea4d", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v1.0.0" - } - }, - ["windows|x64"] = { - ["cmake#31fecfc4"] = { - repo = { - branch = "master", - commit = "a866090956c8d7375e71feafa27455697fb938b6", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "3.21.0" - }, - ["concurrentqueue#31fecfc4"] = { - branch = "master", - repo = { - branch = "master", - commit = "a4fff5567e56215dcf9549eba60cf8597021223f", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "master" - }, - ["cxxopts#31fecfc4"] = { - repo = { - branch = "master", - commit = "a4fff5567e56215dcf9549eba60cf8597021223f", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v2.2.0" + version = "v3.9.0" }, ["fmt#7572102e"] = { repo = { branch = "master", - commit = "a866090956c8d7375e71feafa27455697fb938b6", + commit = "cdb9b43c6328aa32e9fae40de406e84beb98d77e", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "8.1.1" @@ -237,7 +150,7 @@ ["hopscotch-map#31fecfc4"] = { repo = { branch = "master", - commit = "a4fff5567e56215dcf9549eba60cf8597021223f", + commit = "cdb9b43c6328aa32e9fae40de406e84beb98d77e", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v2.3.0" @@ -245,18 +158,18 @@ ["libcurl#31fecfc4"] = { repo = { branch = "master", - commit = "a866090956c8d7375e71feafa27455697fb938b6", + commit = "cdb9b43c6328aa32e9fae40de406e84beb98d77e", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "7.82.0" }, - ["nazaraengine 2021.08.28#31fecfc4"] = { + ["nazaraengine#31fecfc4"] = { repo = { url = "xmake-repo" }, version = "2021.08.28" }, - ["nazaraengine~server 2021.08.28#e1c6474d"] = { + ["nazaraengine~server#df983b2f"] = { repo = { url = "xmake-repo" }, @@ -265,7 +178,7 @@ ["nlohmann_json#31fecfc4"] = { repo = { branch = "master", - commit = "a866090956c8d7375e71feafa27455697fb938b6", + commit = "a73dc9a151cd3d46e8edb8153b800659115726d3", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v3.10.5" @@ -273,7 +186,7 @@ ["sol2 v3.2.1#72267bd5"] = { repo = { branch = "master", - commit = "a4fff5567e56215dcf9549eba60cf8597021223f", + commit = "cdb9b43c6328aa32e9fae40de406e84beb98d77e", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v3.2.1" @@ -282,7 +195,7 @@ branch = "master", repo = { branch = "master", - commit = "a4fff5567e56215dcf9549eba60cf8597021223f", + commit = "cdb9b43c6328aa32e9fae40de406e84beb98d77e", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "master" @@ -290,7 +203,7 @@ ["tl_expected#31fecfc4"] = { repo = { branch = "master", - commit = "a4fff5567e56215dcf9549eba60cf8597021223f", + commit = "cdb9b43c6328aa32e9fae40de406e84beb98d77e", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v1.0.0" @@ -298,7 +211,7 @@ ["tl_function_ref#31fecfc4"] = { repo = { branch = "master", - commit = "a4fff5567e56215dcf9549eba60cf8597021223f", + commit = "cdb9b43c6328aa32e9fae40de406e84beb98d77e", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v1.0.0" diff --git a/xmake.lua b/xmake.lua index 0765a75b..ae9c084b 100644 --- a/xmake.lua +++ b/xmake.lua @@ -9,11 +9,11 @@ add_repositories("burgwar-repo xmake-repo") set_project("BurgWar") set_version("0.2.0") -add_requires("cxxopts", "concurrentqueue", "hopscotch-map", "nlohmann_json", "tl_expected", "tl_function_ref") +add_requires("cxxopts", "concurrentqueue", "entt", "hopscotch-map", "nlohmann_json", "tl_expected", "tl_function_ref") add_requires("fmt", { configs = { header_only = false, pic = true } }) add_requires("libcurl", { optional = true }) -add_requires("nazaraengine 2021.08.28", { alias = "nazara" }) -add_requires("nazaraengine~server 2021.08.28", { alias = "nazaraserver", configs = { server = true } }) +add_requires("nazaraengine", { alias = "nazara" }) +add_requires("nazaraengine~server", { alias = "nazaraserver", configs = { audio = false, graphics = false, platform = false, renderer = false } }) add_requires("sol2 v3.2.1", { verify = false, configs = { includes_lua = false } }) if is_plat("windows") then @@ -104,7 +104,7 @@ target("CoreLib") add_headerfiles("include/(CoreLib/**.hpp)", "include/(CoreLib/**.inl)") add_headerfiles("src/CoreLib/**.hpp", "src/CoreLib/**.inl") add_files("src/CoreLib/**.cpp") - add_packages("concurrentqueue", "fmt", "hopscotch-map", "nlohmann_json", "sol2", "tl_expected", { public = true }) + add_packages("concurrentqueue", "entt", "fmt", "hopscotch-map", "nlohmann_json", "sol2", "tl_expected", "tl_function_ref", { public = true }) add_packages("nazaraserver") add_packages("libcurl", { public = true, links = {} }) From 8e886c28ae7092c4b674da8536b63b906498f4c8 Mon Sep 17 00:00:00 2001 From: SirLynix Date: Thu, 19 May 2022 18:30:15 +0200 Subject: [PATCH 02/17] WIP --- .../CoreLib/Components/AnimationComponent.hpp | 2 +- .../CoreLib/Components/AnimationComponent.inl | 4 +- include/CoreLib/Components/BaseComponent.hpp | 18 +-- include/CoreLib/Components/BaseComponent.inl | 30 ++--- include/CoreLib/Match.hpp | 10 +- include/CoreLib/Player.hpp | 2 +- include/CoreLib/Player.inl | 2 +- include/CoreLib/Scripting/ScriptStore.hpp | 3 +- include/CoreLib/Scripting/ScriptStore.inl | 4 +- include/CoreLib/Scripting/ScriptingUtils.hpp | 5 +- .../CoreLib/Scripting/ServerEntityStore.hpp | 4 +- .../CoreLib/Scripting/ServerWeaponStore.hpp | 2 +- .../CoreLib/Scripting/SharedEntityStore.hpp | 4 +- include/CoreLib/SharedMatch.hpp | 6 +- .../States/Game/ResourceDownloadState.cpp | 8 +- src/Client/States/ServerListState.cpp | 2 +- src/ClientLib/ClientLayerSound.cpp | 4 +- src/ClientLib/HttpDownloadManager.cpp | 2 +- src/ClientLib/LayerVisualEntity.cpp | 12 +- src/ClientLib/PacketDownloadManager.cpp | 2 +- .../Scripting/ClientElementLibrary.cpp | 4 +- src/ClientLib/SoundEntity.cpp | 4 +- src/ClientLib/VisualEntity.cpp | 6 +- src/CoreLib/Match.cpp | 114 +++++++++--------- src/CoreLib/Scripting/ScriptingUtils.cpp | 10 +- .../Scripting/ServerElementLibrary.cpp | 2 +- src/CoreLib/Scripting/ServerEntityLibrary.cpp | 33 ++--- src/CoreLib/Scripting/ServerWeaponStore.cpp | 4 +- .../Scripting/SharedElementLibrary.cpp | 8 +- src/CoreLib/Scripting/SharedEntityLibrary.cpp | 2 +- src/CoreLib/Scripting/SharedEntityStore.cpp | 7 +- src/CoreLib/Systems/WeaponSystem.cpp | 2 +- src/MapEditor/Gizmos/PositionGizmo.cpp | 8 +- src/MapEditor/Widgets/EditorWindow.cpp | 2 +- 34 files changed, 161 insertions(+), 171 deletions(-) diff --git a/include/CoreLib/Components/AnimationComponent.hpp b/include/CoreLib/Components/AnimationComponent.hpp index b93fe4d3..7caba9fe 100644 --- a/include/CoreLib/Components/AnimationComponent.hpp +++ b/include/CoreLib/Components/AnimationComponent.hpp @@ -22,7 +22,7 @@ namespace bw friend class AnimationSystem; public: - inline AnimationComponent(entt::registry& registry, entt::entity entity, std::shared_ptr animStore); + inline AnimationComponent(entt::handle entity, std::shared_ptr animStore); inline AnimationComponent(const AnimationComponent& animation); ~AnimationComponent() = default; diff --git a/include/CoreLib/Components/AnimationComponent.inl b/include/CoreLib/Components/AnimationComponent.inl index bf07f78e..a4787878 100644 --- a/include/CoreLib/Components/AnimationComponent.inl +++ b/include/CoreLib/Components/AnimationComponent.inl @@ -7,8 +7,8 @@ namespace bw { - inline AnimationComponent::AnimationComponent(entt::registry& registry, entt::entity entity, std::shared_ptr animStore) : - BaseComponent(registry, entity), + inline AnimationComponent::AnimationComponent(entt::handle entity, std::shared_ptr animStore) : + BaseComponent(entity), m_animationStore(std::move(animStore)) { } diff --git a/include/CoreLib/Components/BaseComponent.hpp b/include/CoreLib/Components/BaseComponent.hpp index b494f6ef..6284a4cf 100644 --- a/include/CoreLib/Components/BaseComponent.hpp +++ b/include/CoreLib/Components/BaseComponent.hpp @@ -16,23 +16,23 @@ namespace bw class BURGWAR_CORELIB_API BaseComponent { public: - inline BaseComponent(entt::registry& registry, entt::entity entity); - inline BaseComponent(const BaseComponent& component); - inline BaseComponent(BaseComponent&& component) noexcept; + inline BaseComponent(entt::handle handle); + BaseComponent(const BaseComponent&) = default; + BaseComponent(BaseComponent&&) noexcept = default; ~BaseComponent() = default; inline entt::entity GetEntity() const; - inline entt::registry& GetRegistry(); - inline entt::registry& GetRegistry() const; + inline entt::handle GetHandle() const; + inline entt::registry* GetRegistry(); + inline entt::registry* GetRegistry() const; void KillEntity(); - BaseComponent& operator=(const BaseComponent&) = delete; - BaseComponent& operator=(BaseComponent&&) = delete; + BaseComponent& operator=(const BaseComponent&) = default; + BaseComponent& operator=(BaseComponent&&) = default; private: - entt::entity m_entity; - entt::registry& m_registry; + entt::handle m_handle; }; } diff --git a/include/CoreLib/Components/BaseComponent.inl b/include/CoreLib/Components/BaseComponent.inl index 37d208d0..8a56c85f 100644 --- a/include/CoreLib/Components/BaseComponent.inl +++ b/include/CoreLib/Components/BaseComponent.inl @@ -7,41 +7,33 @@ namespace bw { - inline BaseComponent::BaseComponent(entt::registry& registry, entt::entity entity) : - m_entity(entity), - m_registry(registry) + inline BaseComponent::BaseComponent(entt::handle handle) : + m_handle(handle) { } - inline BaseComponent::BaseComponent(const BaseComponent& component) : - m_entity(component.m_entity), - m_registry(component.m_registry) - { - } - - inline BaseComponent::BaseComponent(BaseComponent&& component) noexcept : - m_entity(component.m_entity), - m_registry(component.m_registry) + inline entt::entity BaseComponent::GetEntity() const { + return m_handle; } - inline entt::entity BaseComponent::GetEntity() const + inline entt::handle BaseComponent::GetHandle() const { - return m_entity; + return m_handle; } - inline entt::registry& BaseComponent::GetRegistry() + inline entt::registry* BaseComponent::GetRegistry() { - return m_registry; + return m_handle.registry(); } - inline entt::registry& BaseComponent::GetRegistry() const + inline entt::registry* BaseComponent::GetRegistry() const { - return m_registry; + return m_handle.registry(); } inline void BaseComponent::KillEntity() { - m_registry.destroy(m_entity); + m_handle.destroy(); } } diff --git a/include/CoreLib/Match.hpp b/include/CoreLib/Match.hpp index e7460e87..5b5630b7 100644 --- a/include/CoreLib/Match.hpp +++ b/include/CoreLib/Match.hpp @@ -74,7 +74,7 @@ namespace bw Player* CreatePlayer(MatchClientSession& session, Nz::UInt8 localIndex, std::string name); - void ForEachEntity(tl::function_ref func) override; + void ForEachEntity(tl::function_ref func) override; template void ForEachPlayer(F&& func, bool onlyReady = true); inline BurgApp& GetApp(); @@ -109,7 +109,7 @@ namespace bw void RegisterClientAsset(std::string assetPath); void RegisterClientScript(std::string scriptPath); - void RegisterEntity(EntityId uniqueId, entt::entity entity); + void RegisterEntity(EntityId uniqueId, entt::handle entity); void RegisterNetworkString(std::string string); void ReloadAssets(); @@ -119,8 +119,8 @@ namespace bw void RemovePlayer(Player* player, DisconnectionReason disconnection); void ResetTerrain(); - entt::entity RetrieveEntityByUniqueId(EntityId uniqueId) const override; - EntityId RetrieveUniqueIdByEntity(entt::entity entity) const override; + entt::handle RetrieveEntityByUniqueId(EntityId uniqueId) const override; + EntityId RetrieveUniqueIdByEntity(entt::handle entity) const override; bool Update(float elapsedTime); @@ -187,7 +187,7 @@ namespace bw struct Entity { - entt::entity entity; + entt::handle entity; NazaraSlot(DestructionWatcherComponent, OnDestruction, onDestruction); }; diff --git a/include/CoreLib/Player.hpp b/include/CoreLib/Player.hpp index e048363e..966724e3 100644 --- a/include/CoreLib/Player.hpp +++ b/include/CoreLib/Player.hpp @@ -39,7 +39,7 @@ namespace bw Player(Player&&) noexcept = default; ~Player(); - inline entt::entity GetControlledEntity() const; + inline entt::handle GetControlledEntity() const; inline const PlayerInputData& GetInputs() const; inline LayerIndex GetLayerIndex() const; inline Nz::UInt8 GetLocalIndex() const; diff --git a/include/CoreLib/Player.inl b/include/CoreLib/Player.inl index 6de7bd8f..1de71060 100644 --- a/include/CoreLib/Player.inl +++ b/include/CoreLib/Player.inl @@ -6,7 +6,7 @@ namespace bw { - inline entt::entity Player::GetControlledEntity() const + inline entt::handle Player::GetControlledEntity() const { if (m_playerEntity) return m_playerEntity->GetEntity(); diff --git a/include/CoreLib/Scripting/ScriptStore.hpp b/include/CoreLib/Scripting/ScriptStore.hpp index 79de248b..0909b6ed 100644 --- a/include/CoreLib/Scripting/ScriptStore.hpp +++ b/include/CoreLib/Scripting/ScriptStore.hpp @@ -7,6 +7,7 @@ #ifndef BURGWAR_CORELIB_SCRIPTING_SCRIPTSTORE_HPP #define BURGWAR_CORELIB_SCRIPTING_SCRIPTSTORE_HPP +#include #include #include #include @@ -52,7 +53,7 @@ namespace bw protected: virtual std::shared_ptr CreateElement() const; - entt::entity CreateEntity(entt::registry& registry, std::shared_ptr element, PropertyValueMap properties) const; + entt::handle CreateEntity(entt::registry& registry, std::shared_ptr element, PropertyValueMap properties) const; virtual void InitializeElementTable(sol::main_table& elementTable); virtual void InitializeElement(sol::main_table& elementTable, Element& element) = 0; bool InitializeEntity(const Element& entityClass, entt::entity entity) const; diff --git a/include/CoreLib/Scripting/ScriptStore.inl b/include/CoreLib/Scripting/ScriptStore.inl index 30d6e5c7..8b29420f 100644 --- a/include/CoreLib/Scripting/ScriptStore.inl +++ b/include/CoreLib/Scripting/ScriptStore.inl @@ -257,9 +257,9 @@ namespace bw } template - entt::entity ScriptStore::CreateEntity(entt::registry& registry, std::shared_ptr element, PropertyValueMap properties) const + entt::handle ScriptStore::CreateEntity(entt::registry& registry, std::shared_ptr element, PropertyValueMap properties) const { - entt::entity entity = registry.create(); + entt::handle entity(registry, registry.create()); PropertyValueMap filteredProperties; //< Without potential unused properties (FIXME: Is it really necessary?) diff --git a/include/CoreLib/Scripting/ScriptingUtils.hpp b/include/CoreLib/Scripting/ScriptingUtils.hpp index f72ccfa7..aa1dc116 100644 --- a/include/CoreLib/Scripting/ScriptingUtils.hpp +++ b/include/CoreLib/Scripting/ScriptingUtils.hpp @@ -8,6 +8,7 @@ #define BURGWAR_CORELIB_SCRIPTING_UTILS_HPP #include +#include #include #include #include @@ -19,9 +20,9 @@ namespace bw struct ScriptedElement; BURGWAR_CORELIB_API std::shared_ptr AssertScriptElement(const sol::table& entityTable); - BURGWAR_CORELIB_API entt::entity AssertScriptEntity(entt::registry& registry, const sol::table& entityTable); + BURGWAR_CORELIB_API entt::handle AssertScriptEntity(const sol::table& entityTable); BURGWAR_CORELIB_API std::shared_ptr RetrieveScriptElement(const sol::table& entityTable); - BURGWAR_CORELIB_API entt::entity RetrieveScriptEntity(const sol::table& entityTable); + BURGWAR_CORELIB_API entt::handle RetrieveScriptEntity(const sol::table& entityTable); BURGWAR_CORELIB_API std::optional TranslateEntityToLua(entt::registry& registry, entt::entity entity); template [[noreturn]] void TriggerLuaError(lua_State* L, const char* format, Args&&... args); diff --git a/include/CoreLib/Scripting/ServerEntityStore.hpp b/include/CoreLib/Scripting/ServerEntityStore.hpp index 3a2eb9b4..7ef048af 100644 --- a/include/CoreLib/Scripting/ServerEntityStore.hpp +++ b/include/CoreLib/Scripting/ServerEntityStore.hpp @@ -22,9 +22,9 @@ namespace bw inline ServerEntityStore(const Logger& logger, std::shared_ptr context); ~ServerEntityStore() = default; - entt::entity CreateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, entt::entity parent = entt::null) const; + entt::handle CreateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, entt::handle parent = {}) const; bool InitializeEntity(entt::registry& registry, entt::entity entity) const; - entt::entity InstantiateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, entt::entity parent = entt::null) const; + entt::handle InstantiateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, entt::handle parent = {}) const; private: void InitializeElementTable(sol::main_table& elementTable) override; diff --git a/include/CoreLib/Scripting/ServerWeaponStore.hpp b/include/CoreLib/Scripting/ServerWeaponStore.hpp index 5e8e37f1..f201a6cb 100644 --- a/include/CoreLib/Scripting/ServerWeaponStore.hpp +++ b/include/CoreLib/Scripting/ServerWeaponStore.hpp @@ -21,7 +21,7 @@ namespace bw inline ServerWeaponStore(const Logger& logger, std::shared_ptr context); ~ServerWeaponStore() = default; - entt::entity InstantiateWeapon(TerrainLayer& layer, std::size_t weaponIndex, EntityId uniqueId, const PropertyValueMap& properties, entt::entity parent); + entt::handle InstantiateWeapon(TerrainLayer& layer, std::size_t weaponIndex, EntityId uniqueId, const PropertyValueMap& properties, entt::entity parent); private: void InitializeElement(sol::main_table& elementTable, ScriptedWeapon& weapon) override; diff --git a/include/CoreLib/Scripting/SharedEntityStore.hpp b/include/CoreLib/Scripting/SharedEntityStore.hpp index 2f2549f6..027c9a83 100644 --- a/include/CoreLib/Scripting/SharedEntityStore.hpp +++ b/include/CoreLib/Scripting/SharedEntityStore.hpp @@ -20,9 +20,9 @@ namespace bw ~SharedEntityStore() = default; protected: - virtual void BindCallbacks(const ScriptedEntity& entityClass, entt::entity entity) const; + virtual void BindCallbacks(const ScriptedEntity& entityClass, entt::handle entity) const; void InitializeElement(sol::main_table& elementTable, ScriptedEntity& element) override = 0; - bool InitializeEntity(const ScriptedEntity& entityClass, entt::entity entity) const; + bool InitializeEntity(const ScriptedEntity& entityClass, entt::handle entity) const; }; } diff --git a/include/CoreLib/SharedMatch.hpp b/include/CoreLib/SharedMatch.hpp index e8622fee..7099c2fb 100644 --- a/include/CoreLib/SharedMatch.hpp +++ b/include/CoreLib/SharedMatch.hpp @@ -33,7 +33,7 @@ namespace bw SharedMatch(SharedMatch&&) = delete; virtual ~SharedMatch(); - virtual void ForEachEntity(tl::function_ref func) = 0; + virtual void ForEachEntity(tl::function_ref func) = 0; inline Nz::UInt64 GetCurrentTick() const; inline Nz::UInt64 GetCurrentTime() const; @@ -55,8 +55,8 @@ namespace bw virtual SharedWeaponStore& GetWeaponStore() = 0; virtual const SharedWeaponStore& GetWeaponStore() const = 0; - virtual entt::entity RetrieveEntityByUniqueId(EntityId uniqueId) const = 0; - virtual EntityId RetrieveUniqueIdByEntity(entt::entity entity) const = 0; + virtual entt::handle RetrieveEntityByUniqueId(EntityId uniqueId) const = 0; + virtual EntityId RetrieveUniqueIdByEntity(entt::handle entity) const = 0; void Update(float elapsedTime); diff --git a/src/Client/States/Game/ResourceDownloadState.cpp b/src/Client/States/Game/ResourceDownloadState.cpp index 57c7e59c..6bb3c7be 100644 --- a/src/Client/States/Game/ResourceDownloadState.cpp +++ b/src/Client/States/Game/ResourceDownloadState.cpp @@ -215,7 +215,7 @@ namespace bw if (fileSize != resource.size) return false; - auto hash = Nz::AbstractHash::Get(Nz::HashType_SHA1); + auto hash = Nz::AbstractHash::Get(Nz::HashType::SHA1); hash->Begin(); hash->Append(arg.data(), arg.size()); @@ -240,7 +240,7 @@ namespace bw if (file.Read(content.data(), content.size()) != content.size()) return false; - auto fileHash = Nz::AbstractHash::Get(Nz::HashType_SHA1); + auto fileHash = Nz::AbstractHash::Get(Nz::HashType::SHA1); fileHash->Begin(); fileHash->Append(content.data(), content.size()); @@ -256,7 +256,7 @@ namespace bw if (fileSize != resource.size) return false; - if (expectedChecksum != Nz::File::ComputeHash(Nz::HashType_SHA1, arg.generic_u8string())) + if (expectedChecksum != Nz::File::ComputeHash(Nz::HashType::SHA1, arg.generic_u8string())) return false; targetDir->StoreFile(resource.path, arg); @@ -287,7 +287,7 @@ namespace bw std::size_t fileSize = std::filesystem::file_size(cachePath); if (fileSize == resource.size) { - if (expectedChecksum == Nz::File::ComputeHash(Nz::HashType_SHA1, cachePath.generic_u8string())) + if (expectedChecksum == Nz::File::ComputeHash(Nz::HashType::SHA1, cachePath.generic_u8string())) { targetDir->StoreFile(resource.path, cachePath); continue; diff --git a/src/Client/States/ServerListState.cpp b/src/Client/States/ServerListState.cpp index 8238e4c5..6dce178d 100644 --- a/src/Client/States/ServerListState.cpp +++ b/src/Client/States/ServerListState.cpp @@ -159,7 +159,7 @@ namespace bw Nz::Vector2f cursor; cursor.x = center.x - totalSize / 2.f; - cursor.y = m_serverListScrollbar->GetPosition(Nz::CoordSys_Global).y + m_serverListScrollbar->GetSize().y + padding; + cursor.y = m_serverListScrollbar->GetPosition(Nz::CoordSys::Global).y + m_serverListScrollbar->GetSize().y + padding; m_backButton->SetPosition({ cursor.x, cursor.y, 0.f }); cursor.x += m_backButton->GetSize().x + padding; diff --git a/src/ClientLib/ClientLayerSound.cpp b/src/ClientLib/ClientLayerSound.cpp index 1758baff..d1d1c1cf 100644 --- a/src/ClientLib/ClientLayerSound.cpp +++ b/src/ClientLib/ClientLayerSound.cpp @@ -89,7 +89,7 @@ namespace bw } } - Nz::Vector2f position = Nz::Vector2f(m_node.GetPosition(Nz::CoordSys_Global)); + Nz::Vector2f position = Nz::Vector2f(m_node.GetPosition(Nz::CoordSys::Global)); for (SoundEntity* soundEntity : m_soundEntities) soundEntity->Update(position); @@ -110,7 +110,7 @@ namespace bw assert(std::find(m_soundEntities.begin(), m_soundEntities.end(), sound) == m_soundEntities.end()); m_soundEntities.push_back(sound); - Nz::Vector2f position = Nz::Vector2f(m_node.GetPosition(Nz::CoordSys_Global)); + Nz::Vector2f position = Nz::Vector2f(m_node.GetPosition(Nz::CoordSys::Global)); sound->Update(position); } diff --git a/src/ClientLib/HttpDownloadManager.cpp b/src/ClientLib/HttpDownloadManager.cpp index 5c0fb5c5..4b95aeb9 100644 --- a/src/ClientLib/HttpDownloadManager.cpp +++ b/src/ClientLib/HttpDownloadManager.cpp @@ -30,7 +30,7 @@ namespace bw for (std::size_t i = 0; i < maxSimultaneousDownload; ++i) { auto& request = m_requests.emplace_back(); - request.hash = Nz::AbstractHash::Get(Nz::HashType_SHA1); + request.hash = Nz::AbstractHash::Get(Nz::HashType::SHA1); } } diff --git a/src/ClientLib/LayerVisualEntity.cpp b/src/ClientLib/LayerVisualEntity.cpp index 097133bb..fdc3b8f0 100644 --- a/src/ClientLib/LayerVisualEntity.cpp +++ b/src/ClientLib/LayerVisualEntity.cpp @@ -162,9 +162,9 @@ namespace bw { auto& entityNode = m_entity->GetComponent(); - Nz::Vector2f position = Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys_Global)); - Nz::Vector2f scale = Nz::Vector2f(entityNode.GetScale(Nz::CoordSys_Global)); - Nz::Quaternionf rotation = entityNode.GetRotation(Nz::CoordSys_Global); + Nz::Vector2f position = Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys::Global)); + Nz::Vector2f scale = Nz::Vector2f(entityNode.GetScale(Nz::CoordSys::Global)); + Nz::Quaternionf rotation = entityNode.GetRotation(Nz::CoordSys::Global); for (VisualEntity* visualEntity : m_visualEntities) visualEntity->Update(position, rotation, scale); @@ -287,9 +287,9 @@ namespace bw visualEntity->Enable(IsEnabled()); auto& entityNode = m_entity->GetComponent(); - Nz::Vector2f position = Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys_Global)); - Nz::Vector2f scale = Nz::Vector2f(entityNode.GetScale(Nz::CoordSys_Global)); - Nz::Quaternionf rotation = entityNode.GetRotation(Nz::CoordSys_Global); + Nz::Vector2f position = Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys::Global)); + Nz::Vector2f scale = Nz::Vector2f(entityNode.GetScale(Nz::CoordSys::Global)); + Nz::Quaternionf rotation = entityNode.GetRotation(Nz::CoordSys::Global); visualEntity->Update(position, rotation, scale); diff --git a/src/ClientLib/PacketDownloadManager.cpp b/src/ClientLib/PacketDownloadManager.cpp index f4e4e5a3..774efc17 100644 --- a/src/ClientLib/PacketDownloadManager.cpp +++ b/src/ClientLib/PacketDownloadManager.cpp @@ -11,7 +11,7 @@ namespace bw m_clientSession(std::move(clientSession)), m_nextFileIndex(0) { - m_hash = Nz::AbstractHash::Get(Nz::HashType_SHA1); + m_hash = Nz::AbstractHash::Get(Nz::HashType::SHA1); m_onDownloadFragmentSlot.Connect(m_clientSession->OnDownloadClientFileFragment, [this](ClientSession*, const Packets::DownloadClientFileFragment& packet) { diff --git a/src/ClientLib/Scripting/ClientElementLibrary.cpp b/src/ClientLib/Scripting/ClientElementLibrary.cpp index e954ad22..b453d002 100644 --- a/src/ClientLib/Scripting/ClientElementLibrary.cpp +++ b/src/ClientLib/Scripting/ClientElementLibrary.cpp @@ -74,7 +74,7 @@ namespace bw if (hitEntity->HasComponent()) { Ndk::PhysicsComponent2D& hitEntityPhys = hitEntity->GetComponent(); - hitEntityPhys.AddImpulse(Nz::Vector2f::Normalize(hitEntityPhys.GetMassCenter(Nz::CoordSys_Global) - origin) * pushbackForce); + hitEntityPhys.AddImpulse(Nz::Vector2f::Normalize(hitEntityPhys.GetMassCenter(Nz::CoordSys::Global) - origin) * pushbackForce); } }); }; @@ -234,7 +234,7 @@ namespace bw { // Fallback on position auto& nodeComponent = entity->GetComponent(); - Nz::Vector2f position = Nz::Vector2f(nodeComponent.GetPosition(Nz::CoordSys_Global)); + Nz::Vector2f position = Nz::Vector2f(nodeComponent.GetPosition(Nz::CoordSys::Global)); return Nz::Rectf(position.x, position.y, 0.f, 0.f); } diff --git a/src/ClientLib/SoundEntity.cpp b/src/ClientLib/SoundEntity.cpp index c17f2e8c..5f64dce3 100644 --- a/src/ClientLib/SoundEntity.cpp +++ b/src/ClientLib/SoundEntity.cpp @@ -66,8 +66,8 @@ namespace bw visualNode.SetPosition(position); // Make sure parenting doesn't change our depth - Nz::Vector3f globalPosition = visualNode.GetPosition(Nz::CoordSys_Global); + Nz::Vector3f globalPosition = visualNode.GetPosition(Nz::CoordSys::Global); globalPosition.z = m_depth; - visualNode.SetPosition(globalPosition, Nz::CoordSys_Global); + visualNode.SetPosition(globalPosition, Nz::CoordSys::Global); } } diff --git a/src/ClientLib/VisualEntity.cpp b/src/ClientLib/VisualEntity.cpp index 773b667d..2231c43b 100644 --- a/src/ClientLib/VisualEntity.cpp +++ b/src/ClientLib/VisualEntity.cpp @@ -50,16 +50,16 @@ namespace bw visualNode.SetRotation(rotation); visualNode.SetScale(scale); - Nz::Vector2f absolutePosition = Nz::Vector2f(visualNode.GetPosition(Nz::CoordSys_Global)); + Nz::Vector2f absolutePosition = Nz::Vector2f(visualNode.GetPosition(Nz::CoordSys::Global)); absolutePosition.x = std::floor(absolutePosition.x); absolutePosition.y = std::floor(absolutePosition.y); - visualNode.SetPosition(absolutePosition, Nz::CoordSys_Global); + visualNode.SetPosition(absolutePosition, Nz::CoordSys::Global); if (!m_hoveringRenderables.empty()) { auto& visualGfx = m_entity->GetComponent(); - Nz::Vector3f absoluteScale = visualNode.GetScale(Nz::CoordSys_Global); + Nz::Vector3f absoluteScale = visualNode.GetScale(Nz::CoordSys::Global); Nz::Vector2f positiveScale(std::abs(absoluteScale.x), std::abs(absoluteScale.y)); const Nz::Boxf& aabb = visualGfx.GetAABB(); diff --git a/src/CoreLib/Match.cpp b/src/CoreLib/Match.cpp index 86579409..7bac388d 100644 --- a/src/CoreLib/Match.cpp +++ b/src/CoreLib/Match.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include #include #include #include @@ -22,7 +21,9 @@ #include #include #include -#include +#include +#include +#include #include #include #include @@ -177,12 +178,16 @@ namespace bw return player; } - void Match::ForEachEntity(tl::function_ref func) + void Match::ForEachEntity(tl::function_ref func) { for (LayerIndex i = 0; i < m_terrain->GetLayerCount(); ++i) { auto& layer = m_terrain->GetLayer(i); - layer.GetWorld().each(func); + entt::registry& registry = layer.GetWorld(); + registry.each([&](entt::entity entity) + { + func(entt::handle(registry, entity)); + }); } } @@ -270,72 +275,59 @@ namespace bw if (m_clientAssets.find(assetPath) != m_clientAssets.end()) return; - Nz::VirtualDirectory::Entry entry; - if (!m_assetDirectory->GetEntry(assetPath, &entry)) - throw std::runtime_error(assetPath + " is not a file"); + bool found = m_assetDirectory->GetEntry(assetPath, [&](const Nz::VirtualDirectory::Entry& entry) + { + if (!std::holds_alternative(entry)) + throw std::runtime_error(assetPath + " is not a file"); - std::vector content; - if (!std::holds_alternative(entry)) - throw std::runtime_error(assetPath + " is not a file"); + const std::filesystem::path& filepath = std::get(entry).filePath; - std::filesystem::path filepath = std::get(entry); + Nz::UInt64 assetSize = std::filesystem::file_size(filepath); + Nz::ByteArray assetHash = Nz::File::ComputeHash(Nz::HashType::SHA1, filepath.generic_u8string()); - Nz::UInt64 assetSize = std::filesystem::file_size(filepath); - Nz::ByteArray assetHash = Nz::File::ComputeHash(Nz::HashType::SHA1, filepath.generic_u8string()); + RegisterClientAssetInternal(std::move(assetPath), assetSize, std::move(assetHash), filepath); + }); - RegisterClientAssetInternal(std::move(assetPath), assetSize, std::move(assetHash), std::move(filepath)); + if (!found) + throw std::runtime_error(assetPath + " is not a file"); } void Match::RegisterClientScript(std::string scriptPath) { if (m_clientScripts.find(scriptPath) != m_clientScripts.end()) return; - - Nz::VirtualDirectory::Entry entry; - if (!m_assetDirectory->GetEntry(scriptPath, &entry)) - throw std::runtime_error(scriptPath + " is not a file"); - - std::vector content; - if (std::holds_alternative(entry)) - content = std::get(entry); - else if (std::holds_alternative(entry)) + + bool found = m_scriptDirectory->GetFileContent(scriptPath, [&](const void* data, std::size_t size) { - const std::filesystem::path& filepath = std::get(entry); - - Nz::File file(filepath.generic_u8string()); - if (!file.Open(Nz::OpenMode::ReadOnly)) - throw std::runtime_error("failed to open " + filepath.generic_u8string()); + const Nz::UInt8* ptr = static_cast(data); - content.resize(file.GetSize()); - if (file.Read(content.data(), content.size()) != content.size()) - throw std::runtime_error("failed to read " + filepath.generic_u8string()); - } - else - throw std::runtime_error(scriptPath + " is not a file"); + auto hash = Nz::AbstractHash::Get(Nz::HashType::SHA1); + hash->Begin(); + hash->Append(ptr, size); - auto hash = Nz::AbstractHash::Get(Nz::HashType_SHA1); - hash->Begin(); - hash->Append(content.data(), content.size()); + ClientScript clientScriptData; + clientScriptData.checksum = hash->End(); + clientScriptData.content.assign(ptr, ptr + size); - ClientScript clientScriptData; - clientScriptData.checksum = hash->End(); - clientScriptData.content = std::move(content); + m_clientScripts.emplace(std::move(scriptPath), std::move(clientScriptData)); + }); - m_clientScripts.emplace(std::move(scriptPath), std::move(clientScriptData)); + if (!found) + throw std::runtime_error(scriptPath + " is not a file"); } - void Match::RegisterEntity(EntityId uniqueId, entt::entity entity) + void Match::RegisterEntity(EntityId uniqueId, entt::handle entity) { assert(m_entitiesByUniqueId.find(uniqueId) == m_entitiesByUniqueId.end()); Entity& entityData = m_entitiesByUniqueId.emplace(uniqueId, Entity{}).first.value(); - entityData.entity = std::move(entity); - entityData.onDestruction.Connect(entityData.entity->OnEntityDestruction, [this, uniqueId](Ndk::Entity* entity) + entityData.entity = entity; + entityData.onDestruction.Connect(entity.get().OnDestruction, [this, entity, uniqueId]() { // Don't trigger the Destroyed event when resetting map if (!m_isResetting) { - auto& entityScript = entity->GetComponent(); + auto& entityScript = entity.get(); entityScript.ExecuteCallback(); } @@ -358,7 +350,7 @@ namespace bw { const std::string& assetDirectory = m_app.GetConfig().GetStringValue("Resources.AssetDirectory"); - m_assetDirectory = std::make_shared(assetDirectory); + m_assetDirectory = std::make_shared(assetDirectory); for (const auto& modPtr : m_enabledMods) { for (const auto& [assetPath, physicalPath] : modPtr->GetAssets()) @@ -395,7 +387,7 @@ namespace bw Nz::ByteArray expectedChecksum(asset.sha1Checksum.size(), 0); std::memcpy(expectedChecksum.GetBuffer(), asset.sha1Checksum.data(), asset.sha1Checksum.size()); - Nz::ByteArray fileChecksum = Nz::File::ComputeHash(Nz::HashType_SHA1, assetPath.generic_u8string()); + Nz::ByteArray fileChecksum = Nz::File::ComputeHash(Nz::HashType::SHA1, assetPath.generic_u8string()); if (fileChecksum != expectedChecksum) { bwLog(GetLogger(), LogLevel::Error, "Map asset doesn't match file ({0}): checksum doesn't match", asset.filepath, asset.size, fileSize); @@ -430,7 +422,7 @@ namespace bw const std::string& scriptFolder = m_app.GetConfig().GetStringValue("Resources.ScriptDirectory"); - m_scriptDirectory = std::make_shared(scriptFolder); + m_scriptDirectory = std::make_shared(scriptFolder); for (const auto& modPtr : m_enabledMods) { for (const auto& [scriptPath, physicalPath] : modPtr->GetScripts()) @@ -505,9 +497,9 @@ namespace bw if (m_terrain) { - ForEachEntity([this](entt::entity entity) + ForEachEntity([this](entt::handle entity) { - if (entity->HasComponent()) + if (entity.try_get()) { // Warning: ugly (FIXME) m_entityStore->UpdateEntityElement(entity); @@ -622,7 +614,7 @@ namespace bw m_gamemode->ExecuteCallback(); } - entt::entity Match::RetrieveEntityByUniqueId(EntityId uniqueId) const + entt::handle Match::RetrieveEntityByUniqueId(EntityId uniqueId) const { auto it = m_entitiesByUniqueId.find(uniqueId); if (it == m_entitiesByUniqueId.end()) @@ -631,12 +623,16 @@ namespace bw return it.value().entity; } - EntityId Match::RetrieveUniqueIdByEntity(entt::entity entity) const + EntityId Match::RetrieveUniqueIdByEntity(entt::handle entity) const { - if (!entity || !entity->HasComponent()) + if (!entity) + return InvalidEntityId; + + MatchComponent* matchComponent = entity.try_get(); + if (!matchComponent) return InvalidEntityId; - return entity->GetComponent().GetUniqueId(); + return matchComponent->GetUniqueId(); } bool Match::Update(float elapsedTime) @@ -676,7 +672,7 @@ namespace bw for (LayerIndex i = 0; i < m_terrain->GetLayerCount(); ++i) { auto& layer = m_terrain->GetLayer(i); - layer.ForEachEntity([&](entt::entity entity) + layer.ForEachEntity([&](entt::handle entity) { if (!entity->HasComponent() || !entity->HasComponent()) return; @@ -708,8 +704,8 @@ namespace bw } else { - entityPosition = Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys_Global)); - entityRotation = AngleFromQuaternion(entityNode.GetRotation(Nz::CoordSys_Global)); + entityPosition = Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys::Global)); + entityRotation = AngleFromQuaternion(entityNode.GetRotation(Nz::CoordSys::Global)); } debugPacket << entityPosition << entityRotation; @@ -816,11 +812,11 @@ namespace bw if (player == newPlayer) return; - entt::entity controlledEntity = player->GetControlledEntity(); + entt::handle controlledEntity = player->GetControlledEntity(); if (!controlledEntity) return; - auto& entityMatch = controlledEntity->GetComponent(); + auto& entityMatch = controlledEntity.get(); Packets::PlayerControlEntity controlledEntityUpdate; controlledEntityUpdate.playerIndex = static_cast(player->GetPlayerIndex()); diff --git a/src/CoreLib/Scripting/ScriptingUtils.cpp b/src/CoreLib/Scripting/ScriptingUtils.cpp index 4c52230c..8b139de3 100644 --- a/src/CoreLib/Scripting/ScriptingUtils.cpp +++ b/src/CoreLib/Scripting/ScriptingUtils.cpp @@ -16,10 +16,10 @@ namespace bw return element; } - entt::entity AssertScriptEntity(entt::registry& registry, const sol::table& entityTable) + entt::handle AssertScriptEntity(const sol::table& entityTable) { - entt::entity entity = RetrieveScriptEntity(entityTable); - if (entity == entt::null || !registry.try_get(entity)) + entt::handle entity = RetrieveScriptEntity(entityTable); + if (entity == entt::null) TriggerLuaError(entityTable.lua_state(), "invalid entity"); return entity; @@ -34,13 +34,13 @@ namespace bw return entityObject.as>(); } - entt::entity RetrieveScriptEntity(const sol::table& entityTable) + entt::handle RetrieveScriptEntity(const sol::table& entityTable) { sol::object entityObject = entityTable["_Entity"]; if (!entityObject) return entt::null; - return static_cast(entityObject.as()); + return entityObject.as(); } std::optional TranslateEntityToLua(entt::registry& registry, entt::entity entity) diff --git a/src/CoreLib/Scripting/ServerElementLibrary.cpp b/src/CoreLib/Scripting/ServerElementLibrary.cpp index 11ea9425..46d8b3b6 100644 --- a/src/CoreLib/Scripting/ServerElementLibrary.cpp +++ b/src/CoreLib/Scripting/ServerElementLibrary.cpp @@ -51,7 +51,7 @@ namespace bw if (hitEntity->HasComponent()) { Ndk::PhysicsComponent2D& hitEntityPhys = hitEntity->GetComponent(); - hitEntityPhys.AddImpulse(Nz::Vector2f::Normalize(hitEntityPhys.GetMassCenter(Nz::CoordSys_Global) - origin) * pushbackForce); + hitEntityPhys.AddImpulse(Nz::Vector2f::Normalize(hitEntityPhys.GetMassCenter(Nz::CoordSys::Global) - origin) * pushbackForce); } }); }; diff --git a/src/CoreLib/Scripting/ServerEntityLibrary.cpp b/src/CoreLib/Scripting/ServerEntityLibrary.cpp index 5a39af91..93d58540 100644 --- a/src/CoreLib/Scripting/ServerEntityLibrary.cpp +++ b/src/CoreLib/Scripting/ServerEntityLibrary.cpp @@ -24,28 +24,29 @@ namespace bw { entityMetatable["GetWeaponCount"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) -> std::size_t { - entt::entity entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + entt::handle entity = AssertScriptEntity(entityTable); + WeaponWielderComponent* weaponWielder = entity.TryGetComponent(); + if (!weaponWielder) TriggerLuaArgError(L, 1, "entity is not a weapon wielder"); - auto& weaponWielder = entity->GetComponent(); - return weaponWielder.GetWeaponCount(); + return weaponWielder->GetWeaponCount(); }); entityMetatable["GiveWeapon"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, std::string weaponClass) -> bool { - entt::entity entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + entt::handle entity = AssertScriptEntity(entityTable); + WeaponWielderComponent* weaponWielder = entity.TryGetComponent(); + if (!weaponWielder) TriggerLuaArgError(L, 1, "entity is not a weapon wielder"); - assert(entity->HasComponent()); //< All scripted entities have a match component - auto& entityMatch = entity->GetComponent(); + auto& entityMatch = entity.GetComponent(); - auto& weaponWielder = entity->GetComponent(); - std::size_t weaponIndex = weaponWielder.GiveWeapon(weaponClass, [&] (const std::string& weaponClass) -> Ndk::EntityHandle + std::size_t weaponIndex = weaponWielder->GiveWeapon(weaponClass, [&] (const std::string& weaponClass) -> entt::entity { Match& match = entityMatch.GetMatch(); Terrain& terrain = match.GetTerrain(); + TerrainLayer& terrainLayer = terrain.GetLayer(entityMatch.GetLayerIndex()); + entt::registry& registry = terrainLayer.GetWorld(); ServerWeaponStore& weaponStore = match.GetWeaponStore(); @@ -56,15 +57,15 @@ namespace bw EntityId uniqueId = match.AllocateUniqueId(); - entt::entity weapon = weaponStore.InstantiateWeapon(terrain.GetLayer(entityMatch.GetLayerIndex()), weaponEntityIndex, uniqueId, {}, entity); - if (!weapon) + entt::handle weapon = weaponStore.InstantiateWeapon(terrainLayer, weaponEntityIndex, uniqueId, {}, entity.GetEntity()); + if (weapon == entt::null) return entt::null; - match.RegisterEntity(uniqueId, weapon); - if (entity->HasComponent()) + match.RegisterEntity(uniqueId, entt::handle(registry, weapon)); + if (OwnerComponent* ownerComponent = entity.TryGetComponent()) { - if (Player* owner = entity->GetComponent().GetOwner()) - weapon->AddComponent(owner->CreateHandle()); + if (Player* owner = ownerComponent->GetOwner()) + registry.emplace(weapon, owner->CreateHandle()); } return weapon; diff --git a/src/CoreLib/Scripting/ServerWeaponStore.cpp b/src/CoreLib/Scripting/ServerWeaponStore.cpp index ffefebf7..c04f9c62 100644 --- a/src/CoreLib/Scripting/ServerWeaponStore.cpp +++ b/src/CoreLib/Scripting/ServerWeaponStore.cpp @@ -19,11 +19,11 @@ namespace bw { - entt::entity ServerWeaponStore::InstantiateWeapon(TerrainLayer& layer, std::size_t weaponIndex, EntityId uniqueId, const PropertyValueMap& properties, entt::entity parent) + entt::handle ServerWeaponStore::InstantiateWeapon(TerrainLayer& layer, std::size_t weaponIndex, EntityId uniqueId, const PropertyValueMap& properties, entt::entity parent) { const auto& weaponClass = GetElement(weaponIndex); - entt::entity weapon = CreateEntity(layer.GetWorld(), weaponClass, properties); + entt::handle weapon = CreateEntity(layer.GetWorld(), weaponClass, properties); weapon->AddComponent(layer.GetMatch(), layer.GetLayerIndex(), uniqueId); weapon->AddComponent(weaponClass->fullName, parent); diff --git a/src/CoreLib/Scripting/SharedElementLibrary.cpp b/src/CoreLib/Scripting/SharedElementLibrary.cpp index 3455eb17..3226ebf3 100644 --- a/src/CoreLib/Scripting/SharedElementLibrary.cpp +++ b/src/CoreLib/Scripting/SharedElementLibrary.cpp @@ -72,7 +72,7 @@ namespace bw auto& nodeComponent = entity->GetComponent(); - Nz::Vector2f direction(nodeComponent.GetRotation(Nz::CoordSys_Global) * Nz::Vector2f::UnitX()); + Nz::Vector2f direction(nodeComponent.GetRotation(Nz::CoordSys::Global) * Nz::Vector2f::UnitX()); if (nodeComponent.GetScale().x < 0.f) direction = -direction; @@ -84,7 +84,7 @@ namespace bw entt::entity entity = AssertScriptEntity(entityTable); auto& nodeComponent = entity->GetComponent(); - return Nz::Vector2f(nodeComponent.GetPosition(Nz::CoordSys_Global)); + return Nz::Vector2f(nodeComponent.GetPosition(Nz::CoordSys::Global)); }); elementMetatable["GetRotation"] = LuaFunction([](const sol::table& entityTable) @@ -92,7 +92,7 @@ namespace bw entt::entity entity = AssertScriptEntity(entityTable); auto& nodeComponent = entity->GetComponent(); - return Nz::DegreeAnglef(AngleFromQuaternion(nodeComponent.GetRotation(Nz::CoordSys_Global))); //GetComponent(); - Nz::Vector2f scale = Nz::Vector2f(nodeComponent.GetScale(Nz::CoordSys_Global)); + Nz::Vector2f scale = Nz::Vector2f(nodeComponent.GetScale(Nz::CoordSys::Global)); return std::abs(scale.y); }); diff --git a/src/CoreLib/Scripting/SharedEntityLibrary.cpp b/src/CoreLib/Scripting/SharedEntityLibrary.cpp index d3a68e53..d78caa60 100644 --- a/src/CoreLib/Scripting/SharedEntityLibrary.cpp +++ b/src/CoreLib/Scripting/SharedEntityLibrary.cpp @@ -166,7 +166,7 @@ namespace bw entityPhys.SetMass(mass); // Temp fix because Nazara - entityPhys.SetRotation(AngleFromQuaternion(entityNode.GetRotation(Nz::CoordSys_Global))); + entityPhys.SetRotation(AngleFromQuaternion(entityNode.GetRotation(Nz::CoordSys::Global))); } void SharedEntityLibrary::SetDirection(lua_State* L, entt::entity entity, const Nz::Vector2f& upVector) diff --git a/src/CoreLib/Scripting/SharedEntityStore.cpp b/src/CoreLib/Scripting/SharedEntityStore.cpp index e8f7286b..b5ebe380 100644 --- a/src/CoreLib/Scripting/SharedEntityStore.cpp +++ b/src/CoreLib/Scripting/SharedEntityStore.cpp @@ -18,12 +18,11 @@ namespace bw ReloadLibraries(); // This function creates the metatable } - void SharedEntityStore::BindCallbacks(const ScriptedEntity& /*entityClass*/, entt::entity entity) const + void SharedEntityStore::BindCallbacks(const ScriptedEntity& /*entityClass*/, entt::handle entity) const { - if (entity->HasComponent()) + if (InputComponent* entityInputs = entity.try_get()) { - InputComponent& entityInputs = entity->GetComponent(); - entityInputs.OnInputUpdate.Connect([](InputComponent* input) + entityInputs->OnInputUpdate.Connect([](InputComponent* input) { entt::entity entity = input->GetEntity(); auto& entityScript = entity->GetComponent(); diff --git a/src/CoreLib/Systems/WeaponSystem.cpp b/src/CoreLib/Systems/WeaponSystem.cpp index 4ee59ff7..be688268 100644 --- a/src/CoreLib/Systems/WeaponSystem.cpp +++ b/src/CoreLib/Systems/WeaponSystem.cpp @@ -37,7 +37,7 @@ namespace bw const auto& previousInputs = ownerInputs.GetPreviousInputs(); Nz::RadianAnglef angle(std::atan2(inputs.aimDirection.y, inputs.aimDirection.x)); - if (std::signbit(ownerNode.GetScale(Nz::CoordSys_Global).x) != std::signbit(weaponNode.GetScale(Nz::CoordSys_Global).x)) + if (std::signbit(ownerNode.GetScale(Nz::CoordSys::Global).x) != std::signbit(weaponNode.GetScale(Nz::CoordSys::Global).x)) weaponNode.Scale(-1.f, 1.f); if (weaponNode.GetScale().x < 0.f) diff --git a/src/MapEditor/Gizmos/PositionGizmo.cpp b/src/MapEditor/Gizmos/PositionGizmo.cpp index 0f8f0796..fac5db3c 100644 --- a/src/MapEditor/Gizmos/PositionGizmo.cpp +++ b/src/MapEditor/Gizmos/PositionGizmo.cpp @@ -57,12 +57,12 @@ namespace bw node.SetInheritScale(false); node.SetParent(selectionOverlayEntity); - Nz::Vector2f arrowPosition = Nz::Vector2f(node.GetPosition(Nz::CoordSys_Global)); + Nz::Vector2f arrowPosition = Nz::Vector2f(node.GetPosition(Nz::CoordSys::Global)); for (const LayerVisualEntityHandle& visualEntity : GetTargetEntities()) { auto& entityNode = visualEntity->GetEntity()->GetComponent(); - m_entitiesOffsets.push_back(Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys_Global)) - arrowPosition); + m_entitiesOffsets.push_back(Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys::Global)) - arrowPosition); } } @@ -95,7 +95,7 @@ namespace bw if (m_movementType != MovementType::None) { auto& node = GetSelectionOverlayEntity()->GetComponent(); - m_originalPosition = Nz::Vector2f(node.GetPosition(Nz::CoordSys_Global)); + m_originalPosition = Nz::Vector2f(node.GetPosition(Nz::CoordSys::Global)); m_movementStartPos = m_camera.Unproject({ float(mouseButton.x), float(mouseButton.y) }); return true; @@ -175,7 +175,7 @@ namespace bw for (std::size_t i = 0; i < targetEntities.size(); ++i) { auto& entityNode = targetEntities[i]->GetEntity()->GetComponent(); - entityNode.SetPosition(newPosition + m_entitiesOffsets[i], Nz::CoordSys_Global); + entityNode.SetPosition(newPosition + m_entitiesOffsets[i], Nz::CoordSys::Global); targetEntities[i]->SyncVisuals(); } diff --git a/src/MapEditor/Widgets/EditorWindow.cpp b/src/MapEditor/Widgets/EditorWindow.cpp index de2ede12..e00c18b8 100644 --- a/src/MapEditor/Widgets/EditorWindow.cpp +++ b/src/MapEditor/Widgets/EditorWindow.cpp @@ -712,7 +712,7 @@ namespace bw std::vector& assets = map.GetAssets(); assets.clear(); - auto hash = Nz::AbstractHash::Get(Nz::HashType_SHA1); + auto hash = Nz::AbstractHash::Get(Nz::HashType::SHA1); for (const std::string& texturePath : textures) { From cb47a9bbd692674910e68193e63991698df687b0 Mon Sep 17 00:00:00 2001 From: Lynix Date: Thu, 19 May 2022 20:32:06 +0200 Subject: [PATCH 03/17] WIP --- .../ClientLib/LocalPlayerInputController.hpp | 2 +- .../CoreLib/Components/HealthComponent.hpp | 2 +- .../CoreLib/Components/HealthComponent.inl | 4 ++-- .../Components/NetworkSyncComponent.hpp | 10 ++++---- .../Components/NetworkSyncComponent.inl | 14 +++++++---- .../Components/WeaponWielderComponent.hpp | 6 ++--- .../Components/WeaponWielderComponent.inl | 12 +++++----- include/CoreLib/CustomInputController.hpp | 2 +- include/CoreLib/EntityOwner.hpp | 9 ++++--- include/CoreLib/EntityOwner.inl | 15 ++++++------ include/CoreLib/InputController.hpp | 2 +- include/CoreLib/PlayerInputController.hpp | 2 +- include/CoreLib/Scripting/Constraint.hpp | 13 +++++----- include/CoreLib/Scripting/Constraint.inl | 16 ++++++------- include/CoreLib/Scripting/ScriptingUtils.hpp | 3 +-- .../CoreLib/Scripting/ServerEntityStore.hpp | 2 +- .../CoreLib/Systems/PlayerMovementSystem.hpp | 5 +++- src/ClientLib/LocalPlayerInputController.cpp | 2 +- src/CoreLib/CustomInputController.cpp | 4 ++-- src/CoreLib/Match.cpp | 24 +++++++++---------- src/CoreLib/PlayerInputController.cpp | 2 +- src/CoreLib/Scripting/Constraint.cpp | 14 +++++------ src/CoreLib/Scripting/ScriptingUtils.cpp | 6 ++--- src/CoreLib/Scripting/ServerEntityStore.cpp | 4 ++-- 24 files changed, 90 insertions(+), 85 deletions(-) diff --git a/include/ClientLib/LocalPlayerInputController.hpp b/include/ClientLib/LocalPlayerInputController.hpp index 7742db9f..7259d491 100644 --- a/include/ClientLib/LocalPlayerInputController.hpp +++ b/include/ClientLib/LocalPlayerInputController.hpp @@ -18,7 +18,7 @@ namespace bw LocalPlayerInputController() = default; ~LocalPlayerInputController() = default; - std::optional GenerateInputs(entt::registry& registry, entt::entity entity) const override; + std::optional GenerateInputs(entt::handle entity) const override; }; } diff --git a/include/CoreLib/Components/HealthComponent.hpp b/include/CoreLib/Components/HealthComponent.hpp index 6e25e367..80366bf6 100644 --- a/include/CoreLib/Components/HealthComponent.hpp +++ b/include/CoreLib/Components/HealthComponent.hpp @@ -16,7 +16,7 @@ namespace bw class BURGWAR_CORELIB_API HealthComponent : public BaseComponent { public: - inline HealthComponent(entt::registry& registry, entt::entity entity, Nz::UInt16 maxHealth); + inline HealthComponent(entt::handle entity, Nz::UInt16 maxHealth); inline HealthComponent(const HealthComponent& health); inline void Damage(Nz::UInt16 damage, entt::entity attacker); diff --git a/include/CoreLib/Components/HealthComponent.inl b/include/CoreLib/Components/HealthComponent.inl index 9d5015c2..f8258aeb 100644 --- a/include/CoreLib/Components/HealthComponent.inl +++ b/include/CoreLib/Components/HealthComponent.inl @@ -6,8 +6,8 @@ namespace bw { - inline HealthComponent::HealthComponent(entt::registry& registry, entt::entity entity, Nz::UInt16 maxHealth) : - BaseComponent(registry, entity), + inline HealthComponent::HealthComponent(entt::handle entity, Nz::UInt16 maxHealth) : + BaseComponent(entity), m_currentHealth(maxHealth), m_maxHealth(maxHealth) { diff --git a/include/CoreLib/Components/NetworkSyncComponent.hpp b/include/CoreLib/Components/NetworkSyncComponent.hpp index cc2b679e..00fbe614 100644 --- a/include/CoreLib/Components/NetworkSyncComponent.hpp +++ b/include/CoreLib/Components/NetworkSyncComponent.hpp @@ -17,21 +17,23 @@ namespace bw class BURGWAR_CORELIB_API NetworkSyncComponent { public: - inline NetworkSyncComponent(std::string entityClass, entt::entity parent = entt::null); + inline NetworkSyncComponent(Nz::UInt32 networkId, std::string entityClass, entt::handle parent = {}); ~NetworkSyncComponent() = default; inline const std::string& GetEntityClass() const; - inline entt::entity GetParent() const; + inline Nz::UInt32 GetNetworkId() const; + inline entt::handle GetParent() const; inline void Invalidate(); - inline void UpdateParent(entt::entity parent); + inline void UpdateParent(entt::handle parent); NazaraSignal(OnInvalidated, NetworkSyncComponent* /*emitter*/); private: - entt::entity m_parent; std::string m_entityClass; + entt::handle m_parent; + Nz::UInt32 m_networkId; }; } diff --git a/include/CoreLib/Components/NetworkSyncComponent.inl b/include/CoreLib/Components/NetworkSyncComponent.inl index 9413621b..0d8ddd1e 100644 --- a/include/CoreLib/Components/NetworkSyncComponent.inl +++ b/include/CoreLib/Components/NetworkSyncComponent.inl @@ -6,9 +6,10 @@ namespace bw { - inline NetworkSyncComponent::NetworkSyncComponent(std::string entityClass, entt::entity parent) : + inline NetworkSyncComponent::NetworkSyncComponent(Nz::UInt32 networkId, std::string entityClass, entt::handle parent) : + m_entityClass(entityClass), m_parent(parent), - m_entityClass(entityClass) + m_networkId(networkId) { } @@ -17,7 +18,12 @@ namespace bw return m_entityClass; } - inline entt::entity NetworkSyncComponent::GetParent() const + inline Nz::UInt32 NetworkSyncComponent::GetNetworkId() const + { + return m_networkId; + } + + inline entt::handle NetworkSyncComponent::GetParent() const { return m_parent; } @@ -27,7 +33,7 @@ namespace bw OnInvalidated(this); } - inline void NetworkSyncComponent::UpdateParent(entt::entity parent) + inline void NetworkSyncComponent::UpdateParent(entt::handle parent) { m_parent = parent; //TODO: network event diff --git a/include/CoreLib/Components/WeaponWielderComponent.hpp b/include/CoreLib/Components/WeaponWielderComponent.hpp index 7556b192..a6b6bb5b 100644 --- a/include/CoreLib/Components/WeaponWielderComponent.hpp +++ b/include/CoreLib/Components/WeaponWielderComponent.hpp @@ -25,13 +25,13 @@ namespace bw public: using WeaponInitCallback = tl::function_ref; - inline WeaponWielderComponent(entt::registry& registry, entt::entity entity); + inline WeaponWielderComponent(entt::handle entity); inline WeaponWielderComponent(const WeaponWielderComponent& weaponWielder); ~WeaponWielderComponent() = default; - inline entt::entity GetActiveWeapon() const; + inline entt::handle GetActiveWeapon() const; inline std::size_t GetSelectedWeapon() const; - inline entt::entity GetWeapon(std::size_t weaponIndex) const; + inline entt::handle GetWeapon(std::size_t weaponIndex) const; inline const std::vector& GetWeapons() const; inline std::size_t GetWeaponCount() const; inline const Nz::Vector2f& GetWeaponOffset() const; diff --git a/include/CoreLib/Components/WeaponWielderComponent.inl b/include/CoreLib/Components/WeaponWielderComponent.inl index c4f79275..1132691a 100644 --- a/include/CoreLib/Components/WeaponWielderComponent.inl +++ b/include/CoreLib/Components/WeaponWielderComponent.inl @@ -6,8 +6,8 @@ namespace bw { - inline WeaponWielderComponent::WeaponWielderComponent(entt::registry& registry, entt::entity entity) : - BaseComponent(registry, entity), + inline WeaponWielderComponent::WeaponWielderComponent(entt::handle entity) : + BaseComponent(entity), m_activeWeaponIndex(NoWeapon), m_weaponOffset(Nz::Vector2f::Zero()) { @@ -20,13 +20,13 @@ namespace bw m_weaponOffset(weaponWielder.m_weaponOffset) { //FIXME: - for (entt::entity entity : weaponWielder.m_weapons) + for (entt::handle entity : weaponWielder.m_weapons) m_weapons.emplace_back(entity); } - inline entt::entity WeaponWielderComponent::GetActiveWeapon() const + inline entt::handle WeaponWielderComponent::GetActiveWeapon() const { - return (m_activeWeaponIndex != NoWeapon) ? m_weapons[m_activeWeaponIndex].GetEntity() : entt::null; + return (m_activeWeaponIndex != NoWeapon) ? m_weapons[m_activeWeaponIndex].GetEntity() : entt::handle{}; } inline std::size_t WeaponWielderComponent::GetSelectedWeapon() const @@ -34,7 +34,7 @@ namespace bw return m_activeWeaponIndex; } - inline entt::entity WeaponWielderComponent::GetWeapon(std::size_t weaponIndex) const + inline entt::handle WeaponWielderComponent::GetWeapon(std::size_t weaponIndex) const { assert(weaponIndex < m_weapons.size()); return m_weapons[weaponIndex]; diff --git a/include/CoreLib/CustomInputController.hpp b/include/CoreLib/CustomInputController.hpp index 999927d2..06f94514 100644 --- a/include/CoreLib/CustomInputController.hpp +++ b/include/CoreLib/CustomInputController.hpp @@ -18,7 +18,7 @@ namespace bw inline CustomInputController(sol::main_protected_function callback); ~CustomInputController() = default; - std::optional GenerateInputs(entt::registry& registry, entt::entity entity) const override; + std::optional GenerateInputs(entt::handle entity) const override; private: sol::main_protected_function m_callback; diff --git a/include/CoreLib/EntityOwner.hpp b/include/CoreLib/EntityOwner.hpp index 40d80faf..92a61dd9 100644 --- a/include/CoreLib/EntityOwner.hpp +++ b/include/CoreLib/EntityOwner.hpp @@ -14,21 +14,20 @@ namespace bw class EntityOwner { public: - inline EntityOwner(entt::registry& registry, entt::entity entity); + inline EntityOwner(entt::handle entity); EntityOwner(const EntityOwner&) = delete; inline EntityOwner(EntityOwner&& entityOwner) noexcept; inline ~EntityOwner(); - inline entt::entity GetEntity() const; + inline entt::handle GetEntity() const; - operator entt::entity() const; + operator entt::handle() const; EntityOwner& operator=(const EntityOwner&) = delete; EntityOwner& operator=(EntityOwner&&) = delete; private: - entt::entity m_entity; - entt::registry& m_registry; + entt::handle m_entity; }; } diff --git a/include/CoreLib/EntityOwner.inl b/include/CoreLib/EntityOwner.inl index 65ca10e5..3932ff1f 100644 --- a/include/CoreLib/EntityOwner.inl +++ b/include/CoreLib/EntityOwner.inl @@ -6,29 +6,28 @@ namespace bw { - inline EntityOwner::EntityOwner(entt::registry& registry, entt::entity entity) : - m_entity(entity), - m_registry(registry) + inline EntityOwner::EntityOwner(entt::handle entity) : + m_entity(entity) { } inline EntityOwner::EntityOwner(EntityOwner&& entityOwner) noexcept : - m_entity(entityOwner.m_entity), - m_registry(entityOwner.m_registry) + m_entity(entityOwner.m_entity) { } inline EntityOwner::~EntityOwner() { - m_registry.destroy(m_entity); + if (m_entity.valid()) + m_entity.destroy(); } - inline entt::entity EntityOwner::GetEntity() const + inline entt::handle EntityOwner::GetEntity() const { return m_entity; } - inline EntityOwner::operator entt::entity() const + inline EntityOwner::operator entt::handle() const { return m_entity; } diff --git a/include/CoreLib/InputController.hpp b/include/CoreLib/InputController.hpp index 5867e236..645cf26f 100644 --- a/include/CoreLib/InputController.hpp +++ b/include/CoreLib/InputController.hpp @@ -20,7 +20,7 @@ namespace bw InputController() = default; virtual ~InputController(); - virtual std::optional GenerateInputs(entt::registry& registry, entt::entity entity) const = 0; + virtual std::optional GenerateInputs(entt::handle entity) const = 0; }; } diff --git a/include/CoreLib/PlayerInputController.hpp b/include/CoreLib/PlayerInputController.hpp index 4199d3d5..0677a407 100644 --- a/include/CoreLib/PlayerInputController.hpp +++ b/include/CoreLib/PlayerInputController.hpp @@ -17,7 +17,7 @@ namespace bw PlayerInputController() = default; ~PlayerInputController() = default; - std::optional GenerateInputs(entt::registry& registry, entt::entity entity) const override; + std::optional GenerateInputs(entt::handle entity) const override; }; } diff --git a/include/CoreLib/Scripting/Constraint.hpp b/include/CoreLib/Scripting/Constraint.hpp index 9731e07c..437d914f 100644 --- a/include/CoreLib/Scripting/Constraint.hpp +++ b/include/CoreLib/Scripting/Constraint.hpp @@ -16,7 +16,7 @@ namespace bw class BURGWAR_CORELIB_API Constraint { public: - Constraint(entt::registry& registry, entt::entity entity, Nz::Constraint2DHandle constraint); + Constraint(entt::handle entity, Nz::Constraint2DHandle constraint); Constraint(const Constraint&) = delete; Constraint(Constraint&& constraint) noexcept; virtual ~Constraint(); @@ -47,15 +47,14 @@ namespace bw private: NazaraSlot(Nz::HandledObject, OnHandledObjectDestruction, m_onDestruction); - entt::entity m_entity; - entt::registry& m_registry; + entt::handle m_entity; Nz::Constraint2DHandle m_constraint; }; class BURGWAR_CORELIB_API DampedSpringConstraint : public Constraint { public: - inline DampedSpringConstraint(entt::registry& registry, entt::entity entity, Nz::DampedSpringConstraint2D* constraint); + inline DampedSpringConstraint(entt::handle entity, Nz::DampedSpringConstraint2D* constraint); DampedSpringConstraint(DampedSpringConstraint&&) noexcept = default; ~DampedSpringConstraint() = default; @@ -66,7 +65,7 @@ namespace bw class BURGWAR_CORELIB_API PinConstraint : public Constraint { public: - inline PinConstraint(entt::registry& registry, entt::entity entity, Nz::PinConstraint2D* constraint); + inline PinConstraint(entt::handle entity, Nz::PinConstraint2D* constraint); PinConstraint(PinConstraint&&) noexcept = default; ~PinConstraint() = default; @@ -81,7 +80,7 @@ namespace bw class BURGWAR_CORELIB_API PivotConstraint : public Constraint { public: - inline PivotConstraint(entt::registry& registry, entt::entity entity, Nz::PivotConstraint2D* constraint); + inline PivotConstraint(entt::handle entity, Nz::PivotConstraint2D* constraint); PivotConstraint(PivotConstraint&&) noexcept = default; ~PivotConstraint() = default; @@ -92,7 +91,7 @@ namespace bw class BURGWAR_CORELIB_API RotaryLimitConstraint : public Constraint { public: - inline RotaryLimitConstraint(entt::registry& registry, entt::entity entity, Nz::RotaryLimitConstraint2D* constraint); + inline RotaryLimitConstraint(entt::handle entity, Nz::RotaryLimitConstraint2D* constraint); RotaryLimitConstraint(RotaryLimitConstraint&&) noexcept = default; ~RotaryLimitConstraint() = default; diff --git a/include/CoreLib/Scripting/Constraint.inl b/include/CoreLib/Scripting/Constraint.inl index 98946c41..247da371 100644 --- a/include/CoreLib/Scripting/Constraint.inl +++ b/include/CoreLib/Scripting/Constraint.inl @@ -26,23 +26,23 @@ namespace bw return static_cast(m_constraint.GetObject()); } - inline DampedSpringConstraint::DampedSpringConstraint(entt::registry& registry, entt::entity entity, Nz::DampedSpringConstraint2D* constraint) : - Constraint(registry, entity, constraint->CreateHandle()) + inline DampedSpringConstraint::DampedSpringConstraint(entt::handle entity, Nz::DampedSpringConstraint2D* constraint) : + Constraint(entity, constraint->CreateHandle()) { } - inline PinConstraint::PinConstraint(entt::registry& registry, entt::entity entity, Nz::PinConstraint2D* constraint) : - Constraint(registry, entity, constraint->CreateHandle()) + inline PinConstraint::PinConstraint(entt::handle entity, Nz::PinConstraint2D* constraint) : + Constraint(entity, constraint->CreateHandle()) { } - inline PivotConstraint::PivotConstraint(entt::registry& registry, entt::entity entity, Nz::PivotConstraint2D* constraint) : - Constraint(registry, entity, constraint->CreateHandle()) + inline PivotConstraint::PivotConstraint(entt::handle entity, Nz::PivotConstraint2D* constraint) : + Constraint(entity, constraint->CreateHandle()) { } - inline RotaryLimitConstraint::RotaryLimitConstraint(entt::registry& registry, entt::entity entity, Nz::RotaryLimitConstraint2D* constraint) : - Constraint(registry, entity, constraint->CreateHandle()) + inline RotaryLimitConstraint::RotaryLimitConstraint(entt::handle entity, Nz::RotaryLimitConstraint2D* constraint) : + Constraint(entity, constraint->CreateHandle()) { } } diff --git a/include/CoreLib/Scripting/ScriptingUtils.hpp b/include/CoreLib/Scripting/ScriptingUtils.hpp index aa1dc116..f6366b10 100644 --- a/include/CoreLib/Scripting/ScriptingUtils.hpp +++ b/include/CoreLib/Scripting/ScriptingUtils.hpp @@ -8,7 +8,6 @@ #define BURGWAR_CORELIB_SCRIPTING_UTILS_HPP #include -#include #include #include #include @@ -24,7 +23,7 @@ namespace bw BURGWAR_CORELIB_API std::shared_ptr RetrieveScriptElement(const sol::table& entityTable); BURGWAR_CORELIB_API entt::handle RetrieveScriptEntity(const sol::table& entityTable); - BURGWAR_CORELIB_API std::optional TranslateEntityToLua(entt::registry& registry, entt::entity entity); + BURGWAR_CORELIB_API std::optional TranslateEntityToLua(entt::handle entity); template [[noreturn]] void TriggerLuaError(lua_State* L, const char* format, Args&&... args); [[noreturn]] BURGWAR_CORELIB_API void TriggerLuaError(lua_State* L, const std::string& errMessage); [[noreturn]] BURGWAR_CORELIB_API void TriggerLuaArgError(lua_State* L, int argIndex, const char* errMessage); diff --git a/include/CoreLib/Scripting/ServerEntityStore.hpp b/include/CoreLib/Scripting/ServerEntityStore.hpp index 7ef048af..236c05dd 100644 --- a/include/CoreLib/Scripting/ServerEntityStore.hpp +++ b/include/CoreLib/Scripting/ServerEntityStore.hpp @@ -23,7 +23,7 @@ namespace bw ~ServerEntityStore() = default; entt::handle CreateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, entt::handle parent = {}) const; - bool InitializeEntity(entt::registry& registry, entt::entity entity) const; + bool InitializeEntity(entt::handle entity) const; entt::handle InstantiateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, entt::handle parent = {}) const; private: diff --git a/include/CoreLib/Systems/PlayerMovementSystem.hpp b/include/CoreLib/Systems/PlayerMovementSystem.hpp index 0e64237c..d8b62ccb 100644 --- a/include/CoreLib/Systems/PlayerMovementSystem.hpp +++ b/include/CoreLib/Systems/PlayerMovementSystem.hpp @@ -8,6 +8,7 @@ #define BURGWAR_CLIENTLIB_SYSTEMS_PLAYERMOVEMENT_HPP #include +#include #include namespace bw @@ -15,13 +16,15 @@ namespace bw class BURGWAR_CORELIB_API PlayerMovementSystem { public: - PlayerMovementSystem(); + PlayerMovementSystem(entt::registry& registry); ~PlayerMovementSystem() = default; private: void OnEntityAdded(Ndk::Entity* entity) override; void OnEntityRemoved(Ndk::Entity* entity) override; void OnUpdate(float elapsedTime) override; + + entt::registry& m_registry; }; } diff --git a/src/ClientLib/LocalPlayerInputController.cpp b/src/ClientLib/LocalPlayerInputController.cpp index d3b7f2ab..240a56c2 100644 --- a/src/ClientLib/LocalPlayerInputController.cpp +++ b/src/ClientLib/LocalPlayerInputController.cpp @@ -9,7 +9,7 @@ namespace bw { - std::optional LocalPlayerInputController::GenerateInputs(entt::registry& registry, entt::entity entity) const + std::optional LocalPlayerInputController::GenerateInputs(entt::handle entity) const { assert(entity); LocalPlayerControlledComponent* controlledComponent = registry.try_get(entity); diff --git a/src/CoreLib/CustomInputController.cpp b/src/CoreLib/CustomInputController.cpp index 423838be..cc00e86e 100644 --- a/src/CoreLib/CustomInputController.cpp +++ b/src/CoreLib/CustomInputController.cpp @@ -9,9 +9,9 @@ namespace bw { - std::optional CustomInputController::GenerateInputs(entt::registry& registry, entt::entity entity) const + std::optional CustomInputController::GenerateInputs(entt::handle entity) const { - auto entityTable = TranslateEntityToLua(registry, entity); + auto entityTable = TranslateEntityToLua(entity); if (!entityTable) return std::nullopt; diff --git a/src/CoreLib/Match.cpp b/src/CoreLib/Match.cpp index 7bac388d..24d8bf35 100644 --- a/src/CoreLib/Match.cpp +++ b/src/CoreLib/Match.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -674,19 +675,20 @@ namespace bw auto& layer = m_terrain->GetLayer(i); layer.ForEachEntity([&](entt::handle entity) { - if (!entity->HasComponent() || !entity->HasComponent()) + Nz::NodeComponent* entityNode = entity.try_get(); + NetworkSyncComponent* entitySync = entity.try_get(); + if (!entityNode || !entitySync) return; - auto& entityNode = entity->GetComponent(); - entityCount++; CompressedUnsigned layerId(i); - CompressedUnsigned entityId(entity->GetId()); + CompressedUnsigned entityId(entity->GetId()); //< TODO debugPacket << layerId; debugPacket << entityId; - bool isPhysical = entity->HasComponent(); + Nz::RigidBody2DComponent* entityPhys = entity.try_get(); + bool isPhysical = (entityPhys != nullptr); debugPacket << isPhysical; @@ -695,17 +697,15 @@ namespace bw if (isPhysical) { - auto& entityPhys = entity->GetComponent(); - - entityPosition = entityPhys.GetPosition(); - entityRotation = entityPhys.GetRotation(); + entityPosition = entityPhys->GetPosition(); + entityRotation = entityPhys->GetRotation(); - debugPacket << entityPhys.GetVelocity() << entityPhys.GetAngularVelocity(); + debugPacket << entityPhys->GetVelocity() << entityPhys->GetAngularVelocity(); } else { - entityPosition = Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys::Global)); - entityRotation = AngleFromQuaternion(entityNode.GetRotation(Nz::CoordSys::Global)); + entityPosition = Nz::Vector2f(entityNode->GetPosition(Nz::CoordSys::Global)); + entityRotation = AngleFromQuaternion(entityNode->GetRotation(Nz::CoordSys::Global)); } debugPacket << entityPosition << entityRotation; diff --git a/src/CoreLib/PlayerInputController.cpp b/src/CoreLib/PlayerInputController.cpp index 501d7cbf..40c18665 100644 --- a/src/CoreLib/PlayerInputController.cpp +++ b/src/CoreLib/PlayerInputController.cpp @@ -8,7 +8,7 @@ namespace bw { - std::optional PlayerInputController::GenerateInputs(entt::registry& registry, entt::entity entity) const + std::optional PlayerInputController::GenerateInputs(entt::handle entity) const { PlayerControlledComponent* playerControlled = registry.try_get(entity); if (!playerControlled) diff --git a/src/CoreLib/Scripting/Constraint.cpp b/src/CoreLib/Scripting/Constraint.cpp index a9c1865b..4f43397a 100644 --- a/src/CoreLib/Scripting/Constraint.cpp +++ b/src/CoreLib/Scripting/Constraint.cpp @@ -7,9 +7,8 @@ namespace bw { - Constraint::Constraint(entt::registry& registry, entt::entity entity, Nz::Constraint2DHandle constraint) : + Constraint::Constraint(entt::handle entity, Nz::Constraint2DHandle constraint) : m_entity(entity), - m_registry(registry), m_constraint(std::move(constraint)) { m_onDestruction.Connect(m_constraint->OnHandledObjectDestruction, [this](Nz::HandledObject*) { @@ -19,7 +18,6 @@ namespace bw Constraint::Constraint(Constraint&& constraint) noexcept : m_entity(constraint.m_entity), - m_registry(constraint.m_registry), m_constraint(std::move(constraint.m_constraint)) { constraint.m_onDestruction.Disconnect(); @@ -65,10 +63,10 @@ namespace bw if (!IsValid()) return; - if (m_registry.valid(m_entity)) + if (m_entity.valid()) { - if (!m_registry.get(m_entity).RemoveConstraint(m_constraint)) - m_registry.destroy(m_entity); + if (!m_entity.get().RemoveConstraint(m_constraint)) + m_entity.destroy(); } } @@ -92,8 +90,8 @@ namespace bw void Constraint::KillEntity() { - if (m_registry.valid(m_entity)) - m_registry.destroy(m_entity); + if (m_entity.valid()) + m_entity.destroy(); } diff --git a/src/CoreLib/Scripting/ScriptingUtils.cpp b/src/CoreLib/Scripting/ScriptingUtils.cpp index 8b139de3..9db75859 100644 --- a/src/CoreLib/Scripting/ScriptingUtils.cpp +++ b/src/CoreLib/Scripting/ScriptingUtils.cpp @@ -43,12 +43,12 @@ namespace bw return entityObject.as(); } - std::optional TranslateEntityToLua(entt::registry& registry, entt::entity entity) + std::optional TranslateEntityToLua(entt::handle entity) { - if (entity == entt::null) + if (!entity) return std::nullopt; - if (ScriptComponent* scriptComponent = registry.try_get(entity)) + if (ScriptComponent* scriptComponent = entity.try_get()) return scriptComponent->GetTable(); else return std::nullopt; diff --git a/src/CoreLib/Scripting/ServerEntityStore.cpp b/src/CoreLib/Scripting/ServerEntityStore.cpp index ca3b12d2..25893504 100644 --- a/src/CoreLib/Scripting/ServerEntityStore.cpp +++ b/src/CoreLib/Scripting/ServerEntityStore.cpp @@ -97,7 +97,7 @@ namespace bw return entity; } - bool ServerEntityStore::InitializeEntity(entt::registry& registry, entt::entity entity) const + bool ServerEntityStore::InitializeEntity(entt::handle entity) const { const auto& entityScript = registry.get(entity); return SharedEntityStore::InitializeEntity(static_cast(*entityScript.GetElement()), entity); @@ -111,7 +111,7 @@ namespace bw if (entity != entt::null) return entt::null; - if (!InitializeEntity(registry, entity)) + if (!InitializeEntity(entity)) { registry.destroy(entity); return entt::null; From 09e17e57a0108d2f5a882822aef25084985c2731 Mon Sep 17 00:00:00 2001 From: Lynix Date: Sun, 5 Jun 2022 22:32:58 +0200 Subject: [PATCH 04/17] WIP --- include/ClientLib/Chatbox.hpp | 2 +- include/ClientLib/ClientEditorLayer.hpp | 4 +- include/ClientLib/ClientLayer.hpp | 4 +- include/ClientLib/ClientSession.hpp | 2 +- include/ClientLib/Console.hpp | 2 +- include/ClientLib/DownloadManager.hpp | 2 +- include/ClientLib/EscapeMenu.hpp | 2 +- include/ClientLib/HttpDownloadManager.hpp | 2 +- include/ClientLib/InputPoller.hpp | 2 +- include/ClientLib/LocalSessionManager.hpp | 2 +- include/ClientLib/OptionWidget.hpp | 2 +- include/ClientLib/PacketDownloadManager.hpp | 2 +- include/ClientLib/Scripting/Music.hpp | 2 +- include/ClientLib/Systems/SoundSystem.hpp | 2 +- include/ClientLib/VisualLayer.hpp | 2 +- include/CoreLib/AnimationManager.hpp | 2 +- .../CoreLib/Components/AnimationComponent.hpp | 2 +- include/CoreLib/Components/BaseComponent.hpp | 2 +- .../DestructionWatcherComponent.hpp | 2 +- .../CoreLib/Components/HealthComponent.hpp | 2 +- include/CoreLib/Components/InputComponent.hpp | 2 +- .../Components/NetworkSyncComponent.hpp | 2 +- .../Components/WeaponWielderComponent.hpp | 2 +- include/CoreLib/ConfigFile.hpp | 4 +- include/CoreLib/LogSystem/LogContextPtr.hpp | 2 +- include/CoreLib/LogSystem/Logger.hpp | 4 +- include/CoreLib/Match.hpp | 2 +- include/CoreLib/MatchClientVisibility.hpp | 4 +- include/CoreLib/MatchSessions.hpp | 2 +- include/CoreLib/NetworkSessionManager.hpp | 2 +- include/CoreLib/Player.hpp | 2 +- include/CoreLib/Scripting/ScriptStore.inl | 2 +- .../CoreLib/Scripting/ScriptingContext.inl | 2 +- .../CoreLib/Scripting/SharedEntityLibrary.hpp | 17 +- include/CoreLib/SessionBridge.hpp | 2 +- include/CoreLib/SessionManager.hpp | 2 +- include/CoreLib/Systems/NetworkSyncSystem.hpp | 2 +- .../CoreLib/Systems/PlayerMovementSystem.hpp | 11 +- include/CoreLib/WebRequest.hpp | 2 +- include/CoreLib/WebRequestResult.hpp | 2 +- include/CoreLib/WebService.hpp | 2 +- src/ClientLib/Scripting/ParticleRegistry.cpp | 2 +- src/CoreLib/Map.cpp | 2 +- src/CoreLib/Player.cpp | 2 +- src/CoreLib/Scripting/ScriptingContext.cpp | 2 +- src/CoreLib/Scripting/SharedEntityLibrary.cpp | 220 +++++++++--------- src/CoreLib/Scripting/SharedWeaponStore.cpp | 2 +- src/CoreLib/Systems/PlayerMovementSystem.cpp | 2 +- src/CoreLib/Systems/WeaponSystem.cpp | 2 +- src/MapEditor/Gizmos/PositionGizmo.hpp | 2 +- src/MapEditor/Logic/SelectionEditorMode.hpp | 2 +- src/MapEditor/Widgets/TileSelectionWidget.hpp | 2 +- xmake-repo/packages/n/nazaraengine/xmake.lua | 2 +- xmake-requires.lock | 69 +++++- xmake.lua | 6 +- 55 files changed, 240 insertions(+), 193 deletions(-) diff --git a/include/ClientLib/Chatbox.hpp b/include/ClientLib/Chatbox.hpp index 17485b1f..ba36aad4 100644 --- a/include/ClientLib/Chatbox.hpp +++ b/include/ClientLib/Chatbox.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CLIENTLIB_CHATBOX_HPP #include -#include +#include #include #include #include diff --git a/include/ClientLib/ClientEditorLayer.hpp b/include/ClientLib/ClientEditorLayer.hpp index 6569f5aa..0488724c 100644 --- a/include/ClientLib/ClientEditorLayer.hpp +++ b/include/ClientLib/ClientEditorLayer.hpp @@ -10,8 +10,8 @@ #include #include #include -#include -#include +#include +#include namespace bw { diff --git a/include/ClientLib/ClientLayer.hpp b/include/ClientLib/ClientLayer.hpp index e2bd79e3..42ce8280 100644 --- a/include/ClientLib/ClientLayer.hpp +++ b/include/ClientLib/ClientLayer.hpp @@ -7,8 +7,8 @@ #ifndef BURGWAR_CLIENTLIB_CLIENTLAYER_HPP #define BURGWAR_CLIENTLIB_CLIENTLAYER_HPP -#include -#include +#include +#include #include #include #include diff --git a/include/ClientLib/ClientSession.hpp b/include/ClientLib/ClientSession.hpp index 058f8716..874235d3 100644 --- a/include/ClientLib/ClientSession.hpp +++ b/include/ClientLib/ClientSession.hpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/ClientLib/Console.hpp b/include/ClientLib/Console.hpp index e1e0e98f..1f5ec847 100644 --- a/include/ClientLib/Console.hpp +++ b/include/ClientLib/Console.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CLIENTLIB_CONSOLE_HPP #include -#include +#include #include #include #include diff --git a/include/ClientLib/DownloadManager.hpp b/include/ClientLib/DownloadManager.hpp index a0f41373..4eb882b6 100644 --- a/include/ClientLib/DownloadManager.hpp +++ b/include/ClientLib/DownloadManager.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include diff --git a/include/ClientLib/EscapeMenu.hpp b/include/ClientLib/EscapeMenu.hpp index dfa80539..894f1662 100644 --- a/include/ClientLib/EscapeMenu.hpp +++ b/include/ClientLib/EscapeMenu.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CLIENTLIB_ESCAPEMENU_HPP #include -#include +#include #include #include #include diff --git a/include/ClientLib/HttpDownloadManager.hpp b/include/ClientLib/HttpDownloadManager.hpp index 2eceb1b3..33f14558 100644 --- a/include/ClientLib/HttpDownloadManager.hpp +++ b/include/ClientLib/HttpDownloadManager.hpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include diff --git a/include/ClientLib/InputPoller.hpp b/include/ClientLib/InputPoller.hpp index f98344e1..aa4d153b 100644 --- a/include/ClientLib/InputPoller.hpp +++ b/include/ClientLib/InputPoller.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include namespace bw diff --git a/include/ClientLib/LocalSessionManager.hpp b/include/ClientLib/LocalSessionManager.hpp index af7fdaa2..8596f42f 100644 --- a/include/ClientLib/LocalSessionManager.hpp +++ b/include/ClientLib/LocalSessionManager.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include diff --git a/include/ClientLib/OptionWidget.hpp b/include/ClientLib/OptionWidget.hpp index 2f00624b..99ae70dc 100644 --- a/include/ClientLib/OptionWidget.hpp +++ b/include/ClientLib/OptionWidget.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CLIENTLIB_OPTIONMENU_HPP #include -#include +#include #include #include #include diff --git a/include/ClientLib/PacketDownloadManager.hpp b/include/ClientLib/PacketDownloadManager.hpp index 06b393cc..81409d6d 100644 --- a/include/ClientLib/PacketDownloadManager.hpp +++ b/include/ClientLib/PacketDownloadManager.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/ClientLib/Scripting/Music.hpp b/include/ClientLib/Scripting/Music.hpp index 7c49da0f..0dfe8c0a 100644 --- a/include/ClientLib/Scripting/Music.hpp +++ b/include/ClientLib/Scripting/Music.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include namespace bw { diff --git a/include/ClientLib/Systems/SoundSystem.hpp b/include/ClientLib/Systems/SoundSystem.hpp index 9a700892..dcfd9f12 100644 --- a/include/ClientLib/Systems/SoundSystem.hpp +++ b/include/ClientLib/Systems/SoundSystem.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include diff --git a/include/ClientLib/VisualLayer.hpp b/include/ClientLib/VisualLayer.hpp index 6c5e0d18..9a1b4c6c 100644 --- a/include/ClientLib/VisualLayer.hpp +++ b/include/ClientLib/VisualLayer.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CLIENTLIB_VISUALLAYER_HPP #include -#include +#include namespace bw { diff --git a/include/CoreLib/AnimationManager.hpp b/include/CoreLib/AnimationManager.hpp index 365afa3f..57769b69 100644 --- a/include/CoreLib/AnimationManager.hpp +++ b/include/CoreLib/AnimationManager.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CORELIB_ANIMATIONMANAGER_HPP #include -#include +#include #include #include diff --git a/include/CoreLib/Components/AnimationComponent.hpp b/include/CoreLib/Components/AnimationComponent.hpp index 7caba9fe..8fd6d753 100644 --- a/include/CoreLib/Components/AnimationComponent.hpp +++ b/include/CoreLib/Components/AnimationComponent.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include diff --git a/include/CoreLib/Components/BaseComponent.hpp b/include/CoreLib/Components/BaseComponent.hpp index 6284a4cf..2e065147 100644 --- a/include/CoreLib/Components/BaseComponent.hpp +++ b/include/CoreLib/Components/BaseComponent.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CORELIB_COMPONENTS_BASECOMPONENT_HPP #include -#include +#include #include namespace bw diff --git a/include/CoreLib/Components/DestructionWatcherComponent.hpp b/include/CoreLib/Components/DestructionWatcherComponent.hpp index 7482ac15..2340fac8 100644 --- a/include/CoreLib/Components/DestructionWatcherComponent.hpp +++ b/include/CoreLib/Components/DestructionWatcherComponent.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include namespace bw { diff --git a/include/CoreLib/Components/HealthComponent.hpp b/include/CoreLib/Components/HealthComponent.hpp index 80366bf6..0d83b03e 100644 --- a/include/CoreLib/Components/HealthComponent.hpp +++ b/include/CoreLib/Components/HealthComponent.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include namespace bw { diff --git a/include/CoreLib/Components/InputComponent.hpp b/include/CoreLib/Components/InputComponent.hpp index 6e2194c2..fef586ca 100644 --- a/include/CoreLib/Components/InputComponent.hpp +++ b/include/CoreLib/Components/InputComponent.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include diff --git a/include/CoreLib/Components/NetworkSyncComponent.hpp b/include/CoreLib/Components/NetworkSyncComponent.hpp index 00fbe614..08fade80 100644 --- a/include/CoreLib/Components/NetworkSyncComponent.hpp +++ b/include/CoreLib/Components/NetworkSyncComponent.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CORELIB_COMPONENTS_NETWORKSYNCCOMPONENT_HPP #include -#include +#include #include #include diff --git a/include/CoreLib/Components/WeaponWielderComponent.hpp b/include/CoreLib/Components/WeaponWielderComponent.hpp index a6b6bb5b..21fc7832 100644 --- a/include/CoreLib/Components/WeaponWielderComponent.hpp +++ b/include/CoreLib/Components/WeaponWielderComponent.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/CoreLib/ConfigFile.hpp b/include/CoreLib/ConfigFile.hpp index b8977310..ca7214ca 100644 --- a/include/CoreLib/ConfigFile.hpp +++ b/include/CoreLib/ConfigFile.hpp @@ -8,8 +8,8 @@ #define BURGWAR_CORELIB_CONFIGFILE_HPP #include -#include -#include +#include +#include #include #include #include diff --git a/include/CoreLib/LogSystem/LogContextPtr.hpp b/include/CoreLib/LogSystem/LogContextPtr.hpp index 48066d4f..49081847 100644 --- a/include/CoreLib/LogSystem/LogContextPtr.hpp +++ b/include/CoreLib/LogSystem/LogContextPtr.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include namespace bw { diff --git a/include/CoreLib/LogSystem/Logger.hpp b/include/CoreLib/LogSystem/Logger.hpp index 53529bb9..7a0b374c 100644 --- a/include/CoreLib/LogSystem/Logger.hpp +++ b/include/CoreLib/LogSystem/Logger.hpp @@ -12,8 +12,8 @@ #include #include #include -#include -#include +#include +#include #include #include #include diff --git a/include/CoreLib/Match.hpp b/include/CoreLib/Match.hpp index 5b5630b7..138c13c2 100644 --- a/include/CoreLib/Match.hpp +++ b/include/CoreLib/Match.hpp @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/CoreLib/MatchClientVisibility.hpp b/include/CoreLib/MatchClientVisibility.hpp index bfd95be9..cc9d38e1 100644 --- a/include/CoreLib/MatchClientVisibility.hpp +++ b/include/CoreLib/MatchClientVisibility.hpp @@ -14,9 +14,9 @@ #include #include #include -#include +#include #include -#include +#include #include #include #include diff --git a/include/CoreLib/MatchSessions.hpp b/include/CoreLib/MatchSessions.hpp index 7de224e4..25c43a2f 100644 --- a/include/CoreLib/MatchSessions.hpp +++ b/include/CoreLib/MatchSessions.hpp @@ -13,7 +13,7 @@ #include #include #include -#include +#include #include #include diff --git a/include/CoreLib/NetworkSessionManager.hpp b/include/CoreLib/NetworkSessionManager.hpp index 1e10694c..4c5f91ee 100644 --- a/include/CoreLib/NetworkSessionManager.hpp +++ b/include/CoreLib/NetworkSessionManager.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include namespace bw diff --git a/include/CoreLib/Player.hpp b/include/CoreLib/Player.hpp index 966724e3..5f9488ed 100644 --- a/include/CoreLib/Player.hpp +++ b/include/CoreLib/Player.hpp @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/CoreLib/Scripting/ScriptStore.inl b/include/CoreLib/Scripting/ScriptStore.inl index 8b29420f..1add0b0d 100644 --- a/include/CoreLib/Scripting/ScriptStore.inl +++ b/include/CoreLib/Scripting/ScriptStore.inl @@ -7,7 +7,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/CoreLib/Scripting/ScriptingContext.inl b/include/CoreLib/Scripting/ScriptingContext.inl index cbe83312..9f199f43 100644 --- a/include/CoreLib/Scripting/ScriptingContext.inl +++ b/include/CoreLib/Scripting/ScriptingContext.inl @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/CoreLib/Scripting/SharedEntityLibrary.hpp b/include/CoreLib/Scripting/SharedEntityLibrary.hpp index 674280ef..726f23ce 100644 --- a/include/CoreLib/Scripting/SharedEntityLibrary.hpp +++ b/include/CoreLib/Scripting/SharedEntityLibrary.hpp @@ -10,6 +10,7 @@ #include #include #include +#include namespace bw { @@ -22,14 +23,14 @@ namespace bw void RegisterLibrary(sol::table& elementMetatable) override; protected: - virtual void InitRigidBody(lua_State* L, entt::entity entity, float mass); - virtual void SetDirection(lua_State* L, entt::entity entity, const Nz::Vector2f& upVector); - virtual void SetMass(lua_State* L, entt::entity entity, float mass, bool recomputeMomentOfInertia); - virtual void SetMomentOfInertia(lua_State* L, entt::entity entity, float momentOfInertia); - virtual void SetPosition(lua_State* L, entt::entity entity, const Nz::Vector2f& position); - virtual void SetRotation(lua_State* L, entt::entity entity, const Nz::DegreeAnglef& rotation); - virtual void UpdatePlayerJumpHeight(lua_State* L, entt::entity entity, float jumpHeight, float jumpHeightBoost); - virtual void UpdatePlayerMovement(lua_State* L, entt::entity entity, float movementSpeed); + virtual void InitRigidBody(lua_State* L, entt::handle entity, float mass); + virtual void SetDirection(lua_State* L, entt::handle entity, const Nz::Vector2f& upVector); + virtual void SetMass(lua_State* L, entt::handle entity, float mass, bool recomputeMomentOfInertia); + virtual void SetMomentOfInertia(lua_State* L, entt::handle entity, float momentOfInertia); + virtual void SetPosition(lua_State* L, entt::handle entity, const Nz::Vector2f& position); + virtual void SetRotation(lua_State* L, entt::handle entity, const Nz::DegreeAnglef& rotation); + virtual void UpdatePlayerJumpHeight(lua_State* L, entt::handle entity, float jumpHeight, float jumpHeightBoost); + virtual void UpdatePlayerMovement(lua_State* L, entt::handle entity, float movementSpeed); private: void RegisterSharedLibrary(sol::table& elementMetatable); diff --git a/include/CoreLib/SessionBridge.hpp b/include/CoreLib/SessionBridge.hpp index 9d0fe7dc..39de418b 100644 --- a/include/CoreLib/SessionBridge.hpp +++ b/include/CoreLib/SessionBridge.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include namespace bw { diff --git a/include/CoreLib/SessionManager.hpp b/include/CoreLib/SessionManager.hpp index 0bdb4598..0e1ce20e 100644 --- a/include/CoreLib/SessionManager.hpp +++ b/include/CoreLib/SessionManager.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include namespace bw diff --git a/include/CoreLib/Systems/NetworkSyncSystem.hpp b/include/CoreLib/Systems/NetworkSyncSystem.hpp index 00410138..1f1d3c98 100644 --- a/include/CoreLib/Systems/NetworkSyncSystem.hpp +++ b/include/CoreLib/Systems/NetworkSyncSystem.hpp @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/CoreLib/Systems/PlayerMovementSystem.hpp b/include/CoreLib/Systems/PlayerMovementSystem.hpp index d8b62ccb..fcb89ac5 100644 --- a/include/CoreLib/Systems/PlayerMovementSystem.hpp +++ b/include/CoreLib/Systems/PlayerMovementSystem.hpp @@ -4,8 +4,8 @@ #pragma once -#ifndef BURGWAR_CLIENTLIB_SYSTEMS_PLAYERMOVEMENT_HPP -#define BURGWAR_CLIENTLIB_SYSTEMS_PLAYERMOVEMENT_HPP +#ifndef BURGWAR_CORELIB_SYSTEMS_PLAYERMOVEMENT_HPP +#define BURGWAR_CORELIB_SYSTEMS_PLAYERMOVEMENT_HPP #include #include @@ -24,6 +24,13 @@ namespace bw void OnEntityRemoved(Ndk::Entity* entity) override; void OnUpdate(float elapsedTime) override; + entt::connection m_inputDestroyConnection; + entt::connection m_graphicsDestroyConnection; + entt::connection m_lightDestroyConnection; + entt::connection m_nodeDestroyConnection; + entt::observer m_cameraConstructObserver; + entt::observer m_graphicsConstructObserver; + entt::observer m_lightConstructObserver; entt::registry& m_registry; }; } diff --git a/include/CoreLib/WebRequest.hpp b/include/CoreLib/WebRequest.hpp index 8be55164..c1fabbf8 100644 --- a/include/CoreLib/WebRequest.hpp +++ b/include/CoreLib/WebRequest.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include diff --git a/include/CoreLib/WebRequestResult.hpp b/include/CoreLib/WebRequestResult.hpp index 1b8ed226..54529a62 100644 --- a/include/CoreLib/WebRequestResult.hpp +++ b/include/CoreLib/WebRequestResult.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CORELIB_WEBREQUESTRESULT_HPP #include -#include +#include #include #include #include diff --git a/include/CoreLib/WebService.hpp b/include/CoreLib/WebService.hpp index 75b909d9..987acf18 100644 --- a/include/CoreLib/WebService.hpp +++ b/include/CoreLib/WebService.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include using CURLM = void; diff --git a/src/ClientLib/Scripting/ParticleRegistry.cpp b/src/ClientLib/Scripting/ParticleRegistry.cpp index 5390dbbf..59b23280 100644 --- a/src/ClientLib/Scripting/ParticleRegistry.cpp +++ b/src/ClientLib/Scripting/ParticleRegistry.cpp @@ -331,7 +331,7 @@ namespace bw auto velPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Velocity); auto& gen = GetRandomGenerator(); - std::uniform_real_distribution disAngle(-float(M_PI), float(M_PI)); + std::uniform_real_distribution disAngle(-Nz::Pi, Nz::Pi); std::uniform_real_distribution disLength(minSpeed, maxSpeed); for (unsigned int i = startId; i <= endId; ++i) diff --git a/src/CoreLib/Map.cpp b/src/CoreLib/Map.cpp index 35a81e41..7219fba8 100644 --- a/src/CoreLib/Map.cpp +++ b/src/CoreLib/Map.cpp @@ -6,7 +6,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/CoreLib/Player.cpp b/src/CoreLib/Player.cpp index c6435d61..dfc4533b 100644 --- a/src/CoreLib/Player.cpp +++ b/src/CoreLib/Player.cpp @@ -23,7 +23,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/CoreLib/Scripting/ScriptingContext.cpp b/src/CoreLib/Scripting/ScriptingContext.cpp index 6cac09b5..efe59394 100644 --- a/src/CoreLib/Scripting/ScriptingContext.cpp +++ b/src/CoreLib/Scripting/ScriptingContext.cpp @@ -6,7 +6,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/CoreLib/Scripting/SharedEntityLibrary.cpp b/src/CoreLib/Scripting/SharedEntityLibrary.cpp index d78caa60..42e6eb3c 100644 --- a/src/CoreLib/Scripting/SharedEntityLibrary.cpp +++ b/src/CoreLib/Scripting/SharedEntityLibrary.cpp @@ -15,10 +15,9 @@ #include #include #include -#include -#include -#include -#include +#include +#include +#include #include namespace bw @@ -159,174 +158,165 @@ namespace bw RegisterSharedLibrary(elementMetatable); } - void SharedEntityLibrary::InitRigidBody(lua_State* /*L*/, entt::entity entity, float mass) + void SharedEntityLibrary::InitRigidBody(lua_State* /*L*/, entt::handle entity, float mass) { - auto& entityNode = entity->GetComponent(); - auto& entityPhys = entity->AddComponent(); + auto& entityNode = entity.get(); + auto& entityPhys = entity.emplace(); entityPhys.SetMass(mass); // Temp fix because Nazara entityPhys.SetRotation(AngleFromQuaternion(entityNode.GetRotation(Nz::CoordSys::Global))); } - void SharedEntityLibrary::SetDirection(lua_State* L, entt::entity entity, const Nz::Vector2f& upVector) + void SharedEntityLibrary::SetDirection(lua_State* L, entt::handle entity, const Nz::Vector2f& upVector) { - Nz::RadianAnglef angle(std::atan2(upVector.y, upVector.x) + float(M_PI) / 2.f); + Nz::RadianAnglef angle(std::atan2(upVector.y, upVector.x) + Nz::Pi / 2.f); - if (entity->HasComponent()) - { - auto& physComponent = entity->GetComponent(); - physComponent.SetRotation(angle); - } + if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + rigidBody->SetRotation(angle); - auto& nodeComponent = entity->GetComponent(); + auto& nodeComponent = entity.get(); nodeComponent.SetRotation(angle); } - void SharedEntityLibrary::SetMass(lua_State* /*L*/, entt::entity entity, float mass, bool recomputeMomentOfInertia) + void SharedEntityLibrary::SetMass(lua_State* /*L*/, entt::handle entity, float mass, bool recomputeMomentOfInertia) { - if (entity->HasComponent()) - { - auto& physComponent = entity->GetComponent(); - physComponent.SetMass(mass, recomputeMomentOfInertia); - } + Nz::RigidBody2DComponent* rigidBody = entity.try_get(); + if (!rigidBody) + return; + + rigidBody->SetMass(mass, recomputeMomentOfInertia); } - void SharedEntityLibrary::SetMomentOfInertia(lua_State* /*L*/, entt::entity entity, float momentOfInertia) + void SharedEntityLibrary::SetMomentOfInertia(lua_State* /*L*/, entt::handle entity, float momentOfInertia) { - if (entity->HasComponent()) - { - auto& physComponent = entity->GetComponent(); - physComponent.SetMomentOfInertia(momentOfInertia); - } + Nz::RigidBody2DComponent* rigidBody = entity.try_get(); + if (!rigidBody) + return; + + rigidBody->SetMomentOfInertia(momentOfInertia); } - void SharedEntityLibrary::SetPosition(lua_State* L, entt::entity entity, const Nz::Vector2f& position) + void SharedEntityLibrary::SetPosition(lua_State* L, entt::handle entity, const Nz::Vector2f& position) { - if (entity->HasComponent()) - { - auto& physComponent = entity->GetComponent(); - physComponent.SetPosition(position); - } + if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + rigidBody->SetPosition(position); - auto& nodeComponent = entity->GetComponent(); + auto& nodeComponent = entity.get(); nodeComponent.SetPosition(position); } - void SharedEntityLibrary::SetRotation(lua_State* L, entt::entity entity, const Nz::DegreeAnglef& rotation) + void SharedEntityLibrary::SetRotation(lua_State* L, entt::handle entity, const Nz::DegreeAnglef& rotation) { - if (entity->HasComponent()) - { - auto& physComponent = entity->GetComponent(); - physComponent.SetRotation(rotation); - } + if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + rigidBody->SetRotation(rotation); - auto& nodeComponent = entity->GetComponent(); + auto& nodeComponent = entity.get(); nodeComponent.SetRotation(rotation); } - void SharedEntityLibrary::UpdatePlayerJumpHeight(lua_State* L, entt::entity entity, float jumpHeight, float jumpHeightBoost) + void SharedEntityLibrary::UpdatePlayerJumpHeight(lua_State* L, entt::handle entity, float jumpHeight, float jumpHeightBoost) { - if (!entity->HasComponent()) + PlayerMovementComponent* playerMovementComponent = entity.try_get(); + if (!playerMovementComponent) TriggerLuaArgError(L, 1, "entity has no player movement"); - auto& playerMovementComponent = entity->GetComponent(); - playerMovementComponent.UpdateJumpHeight(jumpHeight); - playerMovementComponent.UpdateJumpBoostHeight(jumpHeightBoost); + playerMovementComponent->UpdateJumpHeight(jumpHeight); + playerMovementComponent->UpdateJumpBoostHeight(jumpHeightBoost); } - void SharedEntityLibrary::UpdatePlayerMovement(lua_State* L, entt::entity entity, float movementSpeed) + void SharedEntityLibrary::UpdatePlayerMovement(lua_State* L, entt::handle entity, float movementSpeed) { - if (!entity->HasComponent()) + PlayerMovementComponent* playerMovementComponent = entity.try_get(); + if (!playerMovementComponent) TriggerLuaArgError(L, 1, "entity has no player movement"); - auto& playerMovementComponent = entity->GetComponent(); - playerMovementComponent.UpdateMovementSpeed(movementSpeed); + playerMovementComponent->UpdateMovementSpeed(movementSpeed); } void SharedEntityLibrary::RegisterSharedLibrary(sol::table& elementMetatable) { elementMetatable["AddForce"] = LuaFunction([this](const sol::table& entityTable, const Nz::Vector2f& force) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) { - Ndk::PhysicsComponent2D& hitEntityPhys = entity->GetComponent(); + Ndk::PhysicsComponent2D& hitEntityPhys = entity.get(); hitEntityPhys.AddForce(force); } }); elementMetatable["ApplyImpulse"] = LuaFunction([this](const sol::table& entityTable, const Nz::Vector2f& force) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) { - Ndk::PhysicsComponent2D& hitEntityPhys = entity->GetComponent(); + Ndk::PhysicsComponent2D& hitEntityPhys = entity.get(); hitEntityPhys.AddImpulse(force); } }); elementMetatable["Damage"] = LuaFunction([](const sol::table& entityTable, Nz::UInt16 damage, std::optional attackerEntity) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) return; - auto& entityHealth = entity->GetComponent(); + auto& entityHealth = entity.get(); entityHealth.Damage(damage, (attackerEntity) ? RetrieveScriptEntity(*attackerEntity) : entt::null); }); elementMetatable["ForceSleep"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) { - auto& physComponent = entity->GetComponent(); + auto& physComponent = entity.get(); physComponent.ForceSleep(); } }); elementMetatable["GetColliders"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) -> sol::object { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) return sol::nil; sol::state_view state(L); - return ColliderToTable(state, entity->GetComponent().GetColliders()); + return ColliderToTable(state, entity.get().GetColliders()); }); elementMetatable["GetInputController"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity has no inputs"); - return entity->GetComponent().GetController(); + return entity.get().GetController(); }); elementMetatable["GetHealth"] = LuaFunction([](const sol::table& entityTable) -> Nz::UInt16 { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) return 0; - auto& entityHealth = entity->GetComponent(); + auto& entityHealth = entity.get(); return entityHealth.GetHealth(); }); elementMetatable["GetMass"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) -> sol::object { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) { - auto& physComponent = entity->GetComponent(); + auto& physComponent = entity.get(); return sol::make_object(L, physComponent.GetMass()); } else @@ -335,11 +325,11 @@ namespace bw elementMetatable["GetMomentOfInertia"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) -> sol::object { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) { - auto& physComponent = entity->GetComponent(); + auto& physComponent = entity.get(); return sol::make_object(L, physComponent.GetMomentOfInertia()); } else @@ -348,32 +338,32 @@ namespace bw elementMetatable["GetPlayerMovementController"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity has no player movement"); - return entity->GetComponent().GetController(); + return entity.get().GetController(); }); elementMetatable["GetPlayerMovementSpeed"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity has no player movement"); - return entity->GetComponent().GetMovementSpeed(); + return entity.get().GetMovementSpeed(); }); elementMetatable["GetPlayerJumpHeight"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity has no player movement"); - auto& movementComponent = entity->GetComponent(); + auto& movementComponent = entity.get(); float jumpHeight = movementComponent.GetJumpHeight(); float jumpBoostHeigh = movementComponent.GetJumpBoostHeight(); @@ -382,87 +372,87 @@ namespace bw elementMetatable["GetUpVector"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); - auto& nodeComponent = entity->GetComponent(); + entt::handle entity = AssertScriptEntity(entityTable); + auto& nodeComponent = entity.get(); return Nz::Vector2f(nodeComponent.GetUp()); }); elementMetatable["GetVelocity"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) return Nz::Vector2f::Zero(); - auto& physComponent = entity->GetComponent(); + auto& physComponent = entity.get(); return physComponent.GetVelocity(); }); elementMetatable["Heal"] = LuaFunction([](const sol::table& entityTable, Nz::UInt16 value, std::optional healerEntity) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) return; - auto& entityHealth = entity->GetComponent(); + auto& entityHealth = entity.get(); entityHealth.Heal(value, (healerEntity) ? RetrieveScriptEntity(*healerEntity) : entt::null); }); elementMetatable["InitWeaponWielder"] = LuaFunction([](const sol::table& entityTable, const sol::table& wielderData) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); - auto& wielderComponent = entity->AddComponent(); + auto& wielderComponent = entity.emplace(); wielderComponent.SetWeaponOffset(wielderData["WeaponOffset"]); }); elementMetatable["IsFullHealth"] = LuaFunction([](const sol::table& entityTable) -> bool { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) return false; - auto& entityHealth = entity->GetComponent(); + auto& entityHealth = entity.get(); return entityHealth.GetHealth() >= entityHealth.GetMaxHealth(); }); elementMetatable["InitRigidBody"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, float mass) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); this->InitRigidBody(L, entity, mass); }); elementMetatable["IsPlayerOnGround"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity has no player movement"); - return entity->GetComponent().IsOnGround(); + return entity.get().IsOnGround(); }); elementMetatable["IsSleeping"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) - return entity->GetComponent().IsSleeping(); + return entity.get().IsSleeping(); else return false; }); elementMetatable["OverrideMovementController"] = LuaFunction([this](const sol::table& entityTable, sol::main_protected_function fn) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) { - Ndk::PhysicsComponent2D& hitEntityPhys = entity->GetComponent(); + Ndk::PhysicsComponent2D& hitEntityPhys = entity.get(); if (fn) { hitEntityPhys.SetVelocityFunction([entity, fn = std::move(fn)](Nz::RigidBody2D& body2D, const Nz::Vector2f& gravity, float damping, float deltaTime) { - auto& entityScript = entity->GetComponent(); + auto& entityScript = entity.get(); Nz::Vector2f overridedGravity = gravity; float overridedDamping = damping; @@ -486,28 +476,28 @@ namespace bw elementMetatable["Remove"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); entity->Kill(); }); elementMetatable["SetAngularVelocity"] = LuaFunction([](const sol::table& entityTable, const Nz::DegreeAnglef& velocity) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) return; - auto& physComponent = entity->GetComponent(); + auto& physComponent = entity.get(); physComponent.SetAngularVelocity(velocity); }); elementMetatable["SetColliders"] = LuaFunction([](sol::this_state L, const sol::table& entityTable, const sol::table& colliderTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); std::size_t colliderCount = colliderTable.size(); - auto& entityNode = entity->GetComponent(); - auto& entityCollData = entity->AddComponent(); + auto& entityNode = entity.get(); + auto& entityCollData = entity.emplace(); if (colliderCount <= 1) { @@ -541,12 +531,12 @@ namespace bw } } - entity->AddComponent(entityCollData.BuildCollider(entityNode.GetScale().y)); + entity.emplace(entityCollData.BuildCollider(entityNode.GetScale().y)); }); elementMetatable["SetDirection"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, const Nz::Vector2f& upVector) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity) return; @@ -555,7 +545,7 @@ namespace bw auto SetMass = [this](sol::this_state L, const sol::table& entityTable, float mass, bool recomputeMomentOfInertia = false) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); this->SetMass(L, entity, mass, recomputeMomentOfInertia); }; @@ -570,7 +560,7 @@ namespace bw elementMetatable["SetMomentOfInertia"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, float momentum) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (momentum < 0.f) TriggerLuaArgError(L, 2, "moment of inertia must be positive"); @@ -580,7 +570,7 @@ namespace bw elementMetatable["SetPosition"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, const Nz::Vector2f& position) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity) return; @@ -589,7 +579,7 @@ namespace bw elementMetatable["SetRotation"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, const Nz::DegreeAnglef& rotation) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity) return; @@ -598,55 +588,55 @@ namespace bw elementMetatable["SetVelocity"] = LuaFunction([](const sol::table& entityTable, const Nz::Vector2f& velocity) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity || !entity->HasComponent()) return; - auto& physComponent = entity->GetComponent(); + auto& physComponent = entity.get(); physComponent.SetVelocity(velocity); }); elementMetatable["UpdateInputs"] = LuaFunction([](const sol::table& entityTable, const PlayerInputData& inputs) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity || !entity->HasComponent()) return; - auto& entityInputs = entity->GetComponent(); + auto& entityInputs = entity.get(); entityInputs.UpdateInputs(inputs); }); elementMetatable["UpdateInputController"] = LuaFunction([this](const sol::table& entityTable, std::shared_ptr controller) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity || !entity->HasComponent()) return; - auto& entityInputs = entity->GetComponent(); + auto& entityInputs = entity.get(); entityInputs.UpdateController(std::move(controller)); }); elementMetatable["UpdatePlayerMovementController"] = LuaFunction([](sol::this_state L, const sol::table& entityTable, sol::optional> controller) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (!entity->HasComponent()) TriggerLuaArgError(L, 1, "entity has no player movement"); if (controller) - return entity->GetComponent().UpdateController(std::move(*controller)); + return entity.get().UpdateController(std::move(*controller)); else - return entity->GetComponent().UpdateController(nullptr); + return entity.get().UpdateController(nullptr); }); elementMetatable["UpdatePlayerMovementSpeed"] = LuaFunction([&](sol::this_state L, const sol::table& entityTable, float newSpeed) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); return UpdatePlayerMovement(L, entity, newSpeed); }); elementMetatable["UpdatePlayerJumpHeight"] = LuaFunction([&](sol::this_state L, const sol::table& entityTable, float newJumpHeight, float newJumpBoostHeight) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); return UpdatePlayerJumpHeight(L, entity, newJumpHeight, newJumpBoostHeight); }); } diff --git a/src/CoreLib/Scripting/SharedWeaponStore.cpp b/src/CoreLib/Scripting/SharedWeaponStore.cpp index 00ca2c53..7f7c133d 100644 --- a/src/CoreLib/Scripting/SharedWeaponStore.cpp +++ b/src/CoreLib/Scripting/SharedWeaponStore.cpp @@ -9,7 +9,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/CoreLib/Systems/PlayerMovementSystem.cpp b/src/CoreLib/Systems/PlayerMovementSystem.cpp index 183bada6..7c5439d3 100644 --- a/src/CoreLib/Systems/PlayerMovementSystem.cpp +++ b/src/CoreLib/Systems/PlayerMovementSystem.cpp @@ -10,7 +10,7 @@ namespace bw { - PlayerMovementSystem::PlayerMovementSystem() + PlayerMovementSystem::PlayerMovementSystem(entt::registry& registry) { //Requires(); //SetUpdateOrder(50); //< Execute after physics but before rendering diff --git a/src/CoreLib/Systems/WeaponSystem.cpp b/src/CoreLib/Systems/WeaponSystem.cpp index be688268..30aaee75 100644 --- a/src/CoreLib/Systems/WeaponSystem.cpp +++ b/src/CoreLib/Systems/WeaponSystem.cpp @@ -41,7 +41,7 @@ namespace bw weaponNode.Scale(-1.f, 1.f); if (weaponNode.GetScale().x < 0.f) - angle += Nz::RadianAnglef(float(M_PI)); + angle += Nz::RadianAnglef(Nz::Pi); weaponNode.SetRotation(angle); diff --git a/src/MapEditor/Gizmos/PositionGizmo.hpp b/src/MapEditor/Gizmos/PositionGizmo.hpp index 422e71a7..7816add9 100644 --- a/src/MapEditor/Gizmos/PositionGizmo.hpp +++ b/src/MapEditor/Gizmos/PositionGizmo.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/MapEditor/Logic/SelectionEditorMode.hpp b/src/MapEditor/Logic/SelectionEditorMode.hpp index e53a6cc0..6a83fe8e 100644 --- a/src/MapEditor/Logic/SelectionEditorMode.hpp +++ b/src/MapEditor/Logic/SelectionEditorMode.hpp @@ -8,7 +8,7 @@ #define BURGWAR_MAPEDITOR_SCRIPTING_SELECTION_EDITOR_MODE_HPP #include -#include +#include namespace bw { diff --git a/src/MapEditor/Widgets/TileSelectionWidget.hpp b/src/MapEditor/Widgets/TileSelectionWidget.hpp index 1e35256d..8a5c0a8b 100644 --- a/src/MapEditor/Widgets/TileSelectionWidget.hpp +++ b/src/MapEditor/Widgets/TileSelectionWidget.hpp @@ -7,7 +7,7 @@ #ifndef BURGWAR_MAPEDITOR_WIDGETS_TILESELECTIONWIDGET_HPP #define BURGWAR_MAPEDITOR_WIDGETS_TILESELECTIONWIDGET_HPP -#include +#include #include #include #include diff --git a/xmake-repo/packages/n/nazaraengine/xmake.lua b/xmake-repo/packages/n/nazaraengine/xmake.lua index fa4821b8..6a53b656 100644 --- a/xmake-repo/packages/n/nazaraengine/xmake.lua +++ b/xmake-repo/packages/n/nazaraengine/xmake.lua @@ -60,7 +60,7 @@ package("nazaraengine") on_load("windows", "linux", "macosx", "mingw", function (package) local nazaradir = os.getenv("NAZARA_ENGINE_PATH") or "C:/Projets/Perso/NazaraNext/NazaraEngine" - if not nazaradir then + if not os.isdir(nazaradir) then raise("missing NAZARA_ENGINE_PATH") end package:set("installdir", nazaradir) diff --git a/xmake-requires.lock b/xmake-requires.lock index e0bc93fa..3a8a1988 100644 --- a/xmake-requires.lock +++ b/xmake-requires.lock @@ -109,7 +109,7 @@ ["cmake#31fecfc4"] = { repo = { branch = "master", - commit = "4dd06825e3c821732a036da0760c48b1521cab40", + commit = "84816643e18c08dc36896a8362c1f2eab945364c", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "3.22.1" @@ -118,7 +118,7 @@ branch = "master", repo = { branch = "master", - commit = "cdb9b43c6328aa32e9fae40de406e84beb98d77e", + commit = "52f61c7e552ca64212ebc7d819faa6692943a52b", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "master" @@ -126,15 +126,23 @@ ["cxxopts#31fecfc4"] = { repo = { branch = "master", - commit = "b94e5581b481e06a70edc525b74c67020d64d23d", + commit = "52f61c7e552ca64212ebc7d819faa6692943a52b", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v2.2.0" }, + ["efsw#31fecfc4"] = { + repo = { + branch = "master", + commit = "a866090956c8d7375e71feafa27455697fb938b6", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "1.1.0" + }, ["entt#31fecfc4"] = { repo = { branch = "master", - commit = "424c353c446f4440eef01d68a60693e5ade990cf", + commit = "c62703f4efa4275cab3009a5f41b76ebe3791a92", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v3.9.0" @@ -142,15 +150,23 @@ ["fmt#7572102e"] = { repo = { branch = "master", - commit = "cdb9b43c6328aa32e9fae40de406e84beb98d77e", + commit = "4023b478acb08700c7ddd302d12101f19a4190f6", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "8.1.1" }, + ["frozen#31fecfc4"] = { + repo = { + branch = "master", + commit = "a73dc9a151cd3d46e8edb8153b800659115726d3", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "1.1.1" + }, ["hopscotch-map#31fecfc4"] = { repo = { branch = "master", - commit = "cdb9b43c6328aa32e9fae40de406e84beb98d77e", + commit = "52f61c7e552ca64212ebc7d819faa6692943a52b", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v2.3.0" @@ -158,7 +174,7 @@ ["libcurl#31fecfc4"] = { repo = { branch = "master", - commit = "cdb9b43c6328aa32e9fae40de406e84beb98d77e", + commit = "4023b478acb08700c7ddd302d12101f19a4190f6", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "7.82.0" @@ -175,18 +191,47 @@ }, version = "2021.08.28" }, + ["nazarautils#31fecfc4"] = { + repo = { + commit = "15982f784152309b48de0111fb3d2e076583b999", + url = "https://github.com/NazaraEngine/xmake-repo" + }, + version = "2022.05.26" + }, + ["nazarautils#c806eb3e"] = { + repo = { + commit = "15982f784152309b48de0111fb3d2e076583b999", + url = "https://github.com/NazaraEngine/xmake-repo" + }, + version = "2022.05.26" + }, ["nlohmann_json#31fecfc4"] = { repo = { branch = "master", - commit = "a73dc9a151cd3d46e8edb8153b800659115726d3", + commit = "4023b478acb08700c7ddd302d12101f19a4190f6", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v3.10.5" }, + ["nzsl#c806eb3e"] = { + repo = { + commit = "94c34c4a3a02a0a5de61c0a88a63774c67b83a45", + url = "https://github.com/NazaraEngine/xmake-repo" + }, + version = "2022.06.05" + }, + ["ordered_map#31fecfc4"] = { + repo = { + branch = "master", + commit = "42bf1fa0b15d271c477bfc17315d0a778a256edd", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "v1.0.0" + }, ["sol2 v3.2.1#72267bd5"] = { repo = { branch = "master", - commit = "cdb9b43c6328aa32e9fae40de406e84beb98d77e", + commit = "52f61c7e552ca64212ebc7d819faa6692943a52b", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v3.2.1" @@ -195,7 +240,7 @@ branch = "master", repo = { branch = "master", - commit = "cdb9b43c6328aa32e9fae40de406e84beb98d77e", + commit = "52f61c7e552ca64212ebc7d819faa6692943a52b", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "master" @@ -203,7 +248,7 @@ ["tl_expected#31fecfc4"] = { repo = { branch = "master", - commit = "cdb9b43c6328aa32e9fae40de406e84beb98d77e", + commit = "52f61c7e552ca64212ebc7d819faa6692943a52b", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v1.0.0" @@ -211,7 +256,7 @@ ["tl_function_ref#31fecfc4"] = { repo = { branch = "master", - commit = "cdb9b43c6328aa32e9fae40de406e84beb98d77e", + commit = "52f61c7e552ca64212ebc7d819faa6692943a52b", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v1.0.0" diff --git a/xmake.lua b/xmake.lua index ae9c084b..b111fbc0 100644 --- a/xmake.lua +++ b/xmake.lua @@ -9,6 +9,9 @@ add_repositories("burgwar-repo xmake-repo") set_project("BurgWar") set_version("0.2.0") +add_repositories("nazara-engine-repo https://github.com/NazaraEngine/xmake-repo") +add_requires("nazarautils", "nzsl", { debug = is_mode("debug") }) + add_requires("cxxopts", "concurrentqueue", "entt", "hopscotch-map", "nlohmann_json", "tl_expected", "tl_function_ref") add_requires("fmt", { configs = { header_only = false, pic = true } }) add_requires("libcurl", { optional = true }) @@ -106,6 +109,7 @@ target("CoreLib") add_files("src/CoreLib/**.cpp") add_packages("concurrentqueue", "entt", "fmt", "hopscotch-map", "nlohmann_json", "sol2", "tl_expected", "tl_function_ref", { public = true }) add_packages("nazaraserver") + add_packages("nazarautils", { public = true }) add_packages("libcurl", { public = true, links = {} }) if is_plat("windows") then @@ -182,7 +186,7 @@ target("ClientLib") add_headerfiles("include/(ClientLib/**.hpp)", "include/(ClientLib/**.inl)") add_headerfiles("src/ClientLib/**.hpp", "src/ClientLib/**.inl") add_files("src/ClientLib/**.cpp") - add_packages("nazara", { public = true }) + add_packages("nzsl", "nazara", { public = true }) target("Main") set_group("Common") From 9c863ad657332d8c56b2fa82bb0d47eee683eb23 Mon Sep 17 00:00:00 2001 From: SirLynix Date: Thu, 30 Jun 2022 17:49:50 +0200 Subject: [PATCH 05/17] Update .gitignore --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index f77b8e8c..43cbec43 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ Xmake.Custom.props Xmake.Custom.targets build src/CoreLib/VersionData.hpp +vsxmake*/ # Game binaries Assets/* @@ -45,6 +46,7 @@ Makefile *.VC.opendb *.VC.db* *.leu +*.vsidx # VS Code .vscode From cd51d1d82f64533d7a917f766182ec75ad8470ea Mon Sep 17 00:00:00 2001 From: SirLynix Date: Sat, 2 Jul 2022 19:08:28 +0200 Subject: [PATCH 06/17] WIP --- include/ClientLib/Camera.hpp | 2 +- include/ClientLib/ClientMatch.hpp | 4 +- include/ClientLib/ClientMatch.inl | 2 +- .../Components/VisibleLayerComponent.hpp | 4 +- .../Components/VisibleLayerComponent.inl | 2 +- include/ClientLib/SoundEntity.hpp | 4 +- include/ClientLib/VisualEntity.hpp | 4 +- .../DestructionWatcherComponent.hpp | 4 + .../Components/EntityOwnerComponent.hpp | 6 +- .../Components/EntityOwnerComponent.inl | 4 +- .../CoreLib/Components/HealthComponent.hpp | 12 +- .../CoreLib/Components/HealthComponent.inl | 4 +- include/CoreLib/Components/InputComponent.hpp | 5 +- include/CoreLib/Components/InputComponent.inl | 5 +- include/CoreLib/Components/MatchComponent.hpp | 8 +- include/CoreLib/Components/MatchComponent.inl | 4 +- .../Components/NetworkSyncComponent.hpp | 15 +- .../Components/NetworkSyncComponent.inl | 21 +- .../CoreLib/Components/ScriptComponent.inl | 10 +- .../CoreLib/Components/WeaponComponent.hpp | 9 +- .../CoreLib/Components/WeaponComponent.inl | 6 +- .../Components/WeaponWielderComponent.hpp | 6 +- include/CoreLib/EntityOwner.hpp | 4 +- include/CoreLib/EntityOwner.inl | 17 + include/CoreLib/Map.inl | 2 +- include/CoreLib/MatchClientSession.hpp | 4 +- include/CoreLib/MatchClientSession.inl | 5 - include/CoreLib/MatchClientVisibility.hpp | 28 +- include/CoreLib/MatchSessions.hpp | 2 - include/CoreLib/MatchSessions.inl | 4 +- include/CoreLib/Player.hpp | 7 +- include/CoreLib/Player.inl | 2 +- include/CoreLib/Scripting/ScriptStore.hpp | 6 +- include/CoreLib/Scripting/ScriptStore.inl | 60 ++-- .../Scripting/ServerElementLibrary.hpp | 2 +- .../CoreLib/Scripting/ServerEntityLibrary.hpp | 14 +- .../CoreLib/Scripting/ServerWeaponStore.hpp | 2 +- .../Scripting/SharedElementLibrary.hpp | 3 +- include/CoreLib/Scripting/SharedGamemode.inl | 2 +- .../CoreLib/Scripting/SharedWeaponStore.hpp | 2 +- include/CoreLib/SharedLayer.hpp | 7 + include/CoreLib/SharedLayer.inl | 16 +- include/CoreLib/Systems/AnimationSystem.hpp | 8 +- include/CoreLib/Systems/AnimationSystem.inl | 5 + include/CoreLib/Systems/InputSystem.hpp | 9 +- include/CoreLib/Systems/InputSystem.inl | 4 + include/CoreLib/Systems/NetworkSyncSystem.hpp | 56 ++-- include/CoreLib/Systems/NetworkSyncSystem.inl | 12 +- .../CoreLib/Systems/PlayerMovementSystem.hpp | 25 +- .../CoreLib/Systems/TickCallbackSystem.hpp | 21 +- include/CoreLib/Systems/WeaponSystem.hpp | 12 +- include/CoreLib/Systems/WeaponSystem.inl | 5 + include/CoreLib/Terrain.hpp | 2 +- include/CoreLib/Terrain.inl | 4 +- include/CoreLib/TerrainLayer.hpp | 2 + include/CoreLib/TerrainLayer.inl | 4 + include/CoreLib/Utility/CircularBuffer.inl | 4 +- src/Client/ClientApp.cpp | 2 +- src/Client/States/BackgroundState.cpp | 4 +- src/Client/States/Game/ConnectedState.cpp | 4 +- src/Client/States/StateData.hpp | 2 +- src/ClientLib/Camera.cpp | 12 +- src/ClientLib/ClientEditorLayer.cpp | 10 +- src/ClientLib/ClientLayer.cpp | 4 +- src/ClientLib/ClientMatch.cpp | 8 +- .../Components/VisibleLayerComponent.cpp | 4 +- src/ClientLib/LayerVisualEntity.cpp | 16 +- src/ClientLib/Scoreboard.cpp | 2 +- .../Scripting/ClientEditorEntityStore.cpp | 4 +- .../Scripting/ClientElementLibrary.cpp | 28 +- .../Scripting/ClientEntityLibrary.cpp | 8 +- src/ClientLib/Scripting/ClientEntityStore.cpp | 2 +- .../Scripting/ClientScriptingLibrary.cpp | 2 +- .../Scripting/ClientWeaponLibrary.cpp | 6 +- src/ClientLib/SoundEntity.cpp | 12 +- src/ClientLib/Systems/SoundSystem.cpp | 6 +- .../Systems/VisualInterpolationSystem.cpp | 6 +- src/ClientLib/VisualEntity.cpp | 12 +- .../Components/NetworkSyncComponent.cpp | 23 ++ .../Components/WeaponWielderComponent.cpp | 20 +- src/CoreLib/CustomInputController.cpp | 4 +- src/CoreLib/LogSystem/StdSink.cpp | 2 +- src/CoreLib/Match.cpp | 16 +- src/CoreLib/MatchClientSession.cpp | 7 +- src/CoreLib/MatchClientVisibility.cpp | 44 +-- src/CoreLib/MatchSessions.cpp | 20 +- src/CoreLib/Player.cpp | 99 +++--- src/CoreLib/PlayerInputController.cpp | 2 +- src/CoreLib/PropertyValues.cpp | 13 +- src/CoreLib/Scripting/ScriptingUtils.cpp | 4 +- .../Scripting/ServerElementLibrary.cpp | 107 +++---- src/CoreLib/Scripting/ServerEntityLibrary.cpp | 94 +++--- src/CoreLib/Scripting/ServerEntityStore.cpp | 63 ++-- src/CoreLib/Scripting/ServerGamemode.cpp | 1 - .../Scripting/ServerScriptingLibrary.cpp | 41 ++- src/CoreLib/Scripting/ServerWeaponLibrary.cpp | 28 +- src/CoreLib/Scripting/ServerWeaponStore.cpp | 11 +- .../Scripting/SharedElementLibrary.cpp | 98 +++--- src/CoreLib/Scripting/SharedEntityLibrary.cpp | 203 ++++++------ src/CoreLib/Scripting/SharedEntityStore.cpp | 8 +- src/CoreLib/Scripting/SharedGamemode.cpp | 2 - .../Scripting/SharedScriptingLibrary.cpp | 76 +++-- src/CoreLib/Scripting/SharedWeaponLibrary.cpp | 14 +- src/CoreLib/Scripting/SharedWeaponStore.cpp | 25 +- src/CoreLib/SharedLayer.cpp | 30 +- src/CoreLib/SharedMatch.cpp | 3 +- src/CoreLib/Systems/AnimationSystem.cpp | 16 +- src/CoreLib/Systems/InputSystem.cpp | 17 +- src/CoreLib/Systems/NetworkSyncSystem.cpp | 302 ++++++++++-------- src/CoreLib/Systems/PlayerMovementSystem.cpp | 98 ++++-- src/CoreLib/Systems/TickCallbackSystem.cpp | 36 ++- src/CoreLib/Systems/WeaponSystem.cpp | 31 +- src/CoreLib/Terrain.cpp | 14 +- src/CoreLib/TerrainLayer.cpp | 24 +- src/MapEditor/Enums.hpp | 2 +- src/MapEditor/Gizmos/EditorGizmo.cpp | 6 +- src/MapEditor/Gizmos/EditorGizmo.hpp | 2 +- src/MapEditor/Gizmos/PositionGizmo.cpp | 6 +- src/MapEditor/Gizmos/PositionGizmo.hpp | 2 +- src/MapEditor/Logic/TileMapEditorMode.cpp | 4 +- .../Scripting/EditorElementLibrary.cpp | 8 +- .../Scripting/EditorEntityLibrary.cpp | 2 +- src/MapEditor/Scripting/EditorEntityStore.cpp | 2 +- src/MapEditor/Scripting/EditorEntityStore.hpp | 2 +- src/MapEditor/Widgets/EditorWindow.cpp | 2 +- src/MapEditor/Widgets/EntityInfoDialog.hpp | 2 +- src/MapEditor/Widgets/MapCanvas.cpp | 6 +- src/MapEditor/Widgets/MapCanvasLayer.cpp | 2 +- src/MapEditor/Widgets/PlayWindow.cpp | 2 +- src/MapEditor/Widgets/PlayWindow.hpp | 2 +- src/MapEditor/Widgets/ScrollCanvas.cpp | 6 +- src/MapEditor/Widgets/ScrollCanvas.hpp | 4 +- src/MapEditor/Widgets/TileSelectionWidget.cpp | 8 +- src/MapEditor/Widgets/WorldCanvas.cpp | 2 +- src/MapEditor/Widgets/WorldCanvas.hpp | 6 +- src/MapEditor/Widgets/WorldCanvas.inl | 4 +- xmake-repo/packages/n/nazaraengine/xmake.lua | 2 + xmake.lua | 2 +- 138 files changed, 1262 insertions(+), 1077 deletions(-) create mode 100644 src/CoreLib/Components/NetworkSyncComponent.cpp diff --git a/include/ClientLib/Camera.hpp b/include/ClientLib/Camera.hpp index 864285fa..84d498f7 100644 --- a/include/ClientLib/Camera.hpp +++ b/include/ClientLib/Camera.hpp @@ -24,7 +24,7 @@ namespace bw class BURGWAR_CLIENTLIB_API Camera : public Nz::HandledObject { public: - Camera(Ndk::World& world, Nz::RenderTarget* renderTarget, bool perspective); + Camera(entt::registry& world, Nz::RenderTarget* renderTarget, bool perspective); Camera(const Camera&) = delete; Camera(Camera&&) = delete; ~Camera() = default; diff --git a/include/ClientLib/ClientMatch.hpp b/include/ClientLib/ClientMatch.hpp index 9e881d3b..c2bd2105 100644 --- a/include/ClientLib/ClientMatch.hpp +++ b/include/ClientLib/ClientMatch.hpp @@ -88,7 +88,7 @@ namespace bw inline ParticleRegistry& GetParticleRegistry(); inline const ParticleRegistry& GetParticleRegistry() const; inline ClientPlayer* GetPlayerByIndex(Nz::UInt16 playerIndex); - inline Ndk::World& GetRenderWorld(); + inline entt::registry& GetRenderWorld(); std::shared_ptr GetSharedGamemode() const override; ClientWeaponStore& GetWeaponStore() override; const ClientWeaponStore& GetWeaponStore() const override; @@ -286,7 +286,7 @@ namespace bw std::vector m_tickPredictions; Ndk::Canvas* m_canvas; Ndk::EntityHandle m_currentLayer; - Ndk::World m_renderWorld; + entt::registry m_renderWorld; Nz::ColorBackgroundRef m_colorBackground; EntityId m_freeClientId; Nz::RenderTarget* m_renderTarget; diff --git a/include/ClientLib/ClientMatch.inl b/include/ClientLib/ClientMatch.inl index bac43cfc..868d4f5b 100644 --- a/include/ClientLib/ClientMatch.inl +++ b/include/ClientLib/ClientMatch.inl @@ -112,7 +112,7 @@ namespace bw return &m_matchPlayers[playerIndex].value(); } - inline Ndk::World& ClientMatch::GetRenderWorld() + inline entt::registry& ClientMatch::GetRenderWorld() { return m_renderWorld; } diff --git a/include/ClientLib/Components/VisibleLayerComponent.hpp b/include/ClientLib/Components/VisibleLayerComponent.hpp index edaf5c6c..2ba91039 100644 --- a/include/ClientLib/Components/VisibleLayerComponent.hpp +++ b/include/ClientLib/Components/VisibleLayerComponent.hpp @@ -24,7 +24,7 @@ namespace bw class BURGWAR_CLIENTLIB_API VisibleLayerComponent : public Ndk::Component { public: - inline VisibleLayerComponent(Ndk::World& renderWorld); + inline VisibleLayerComponent(entt::registry& renderWorld); ~VisibleLayerComponent() = default; void Clear(); @@ -68,7 +68,7 @@ namespace bw //FIXME (shared_ptr => unique_ptr) std::vector> m_visibleLayers; - Ndk::World& m_renderWorld; + entt::registry& m_renderWorld; }; } diff --git a/include/ClientLib/Components/VisibleLayerComponent.inl b/include/ClientLib/Components/VisibleLayerComponent.inl index 7031c2c6..110a6ecf 100644 --- a/include/ClientLib/Components/VisibleLayerComponent.inl +++ b/include/ClientLib/Components/VisibleLayerComponent.inl @@ -6,7 +6,7 @@ namespace bw { - inline VisibleLayerComponent::VisibleLayerComponent(Ndk::World& renderWorld) : + inline VisibleLayerComponent::VisibleLayerComponent(entt::registry& renderWorld) : m_renderWorld(renderWorld) { } diff --git a/include/ClientLib/SoundEntity.hpp b/include/ClientLib/SoundEntity.hpp index 99437a5f..28e4d5bb 100644 --- a/include/ClientLib/SoundEntity.hpp +++ b/include/ClientLib/SoundEntity.hpp @@ -23,8 +23,8 @@ namespace bw friend ClientLayerSound; public: - SoundEntity(Ndk::World& renderWorld, ClientLayerSoundHandle layerEntityHandle, float depth = 0.f); - SoundEntity(Ndk::World& renderWorld, ClientLayerSoundHandle layerEntityHandle, const Nz::Node& parentNode, float depth = 0.f); + SoundEntity(entt::registry& renderWorld, ClientLayerSoundHandle layerEntityHandle, float depth = 0.f); + SoundEntity(entt::registry& renderWorld, ClientLayerSoundHandle layerEntityHandle, const Nz::Node& parentNode, float depth = 0.f); SoundEntity(const SoundEntity&) = delete; SoundEntity(SoundEntity&& entity) noexcept; ~SoundEntity(); diff --git a/include/ClientLib/VisualEntity.hpp b/include/ClientLib/VisualEntity.hpp index 6a6c2242..43e7eafc 100644 --- a/include/ClientLib/VisualEntity.hpp +++ b/include/ClientLib/VisualEntity.hpp @@ -25,8 +25,8 @@ namespace bw friend LayerVisualEntity; public: - VisualEntity(Ndk::World& renderWorld, LayerVisualEntityHandle visualEntityHandle, int baseRenderOrder = 0); - VisualEntity(Ndk::World& renderWorld, LayerVisualEntityHandle visualEntityHandle, const Nz::Node& parentNode, int baseRenderOrder = 0); + VisualEntity(entt::registry& renderWorld, LayerVisualEntityHandle visualEntityHandle, int baseRenderOrder = 0); + VisualEntity(entt::registry& renderWorld, LayerVisualEntityHandle visualEntityHandle, const Nz::Node& parentNode, int baseRenderOrder = 0); VisualEntity(const VisualEntity&) = delete; VisualEntity(VisualEntity&& entity) noexcept; ~VisualEntity(); diff --git a/include/CoreLib/Components/DestructionWatcherComponent.hpp b/include/CoreLib/Components/DestructionWatcherComponent.hpp index 2340fac8..12470f42 100644 --- a/include/CoreLib/Components/DestructionWatcherComponent.hpp +++ b/include/CoreLib/Components/DestructionWatcherComponent.hpp @@ -19,8 +19,12 @@ namespace bw public: using BaseComponent::BaseComponent; DestructionWatcherComponent(const DestructionWatcherComponent&) = delete; + DestructionWatcherComponent(DestructionWatcherComponent&&) noexcept = default; inline ~DestructionWatcherComponent(); + DestructionWatcherComponent& operator=(const DestructionWatcherComponent&) = delete; + DestructionWatcherComponent& operator=(DestructionWatcherComponent&&) noexcept = default; + NazaraSignal(OnDestruction, DestructionWatcherComponent* /*emitter*/); }; } diff --git a/include/CoreLib/Components/EntityOwnerComponent.hpp b/include/CoreLib/Components/EntityOwnerComponent.hpp index 8c07f79d..6073808b 100644 --- a/include/CoreLib/Components/EntityOwnerComponent.hpp +++ b/include/CoreLib/Components/EntityOwnerComponent.hpp @@ -18,9 +18,13 @@ namespace bw public: using BaseComponent::BaseComponent; EntityOwnerComponent(const EntityOwnerComponent&) = delete; + EntityOwnerComponent(EntityOwnerComponent&&) noexcept = default; ~EntityOwnerComponent() = default; - inline void Register(entt::entity entity); + inline void Register(entt::handle entity); + + EntityOwnerComponent& operator=(const EntityOwnerComponent&) = delete; + EntityOwnerComponent& operator=(EntityOwnerComponent&&) noexcept = default; private: std::vector m_ownedEntities; diff --git a/include/CoreLib/Components/EntityOwnerComponent.inl b/include/CoreLib/Components/EntityOwnerComponent.inl index 7351fa55..c1064df7 100644 --- a/include/CoreLib/Components/EntityOwnerComponent.inl +++ b/include/CoreLib/Components/EntityOwnerComponent.inl @@ -6,9 +6,9 @@ namespace bw { - inline void EntityOwnerComponent::Register(entt::entity entity) + inline void EntityOwnerComponent::Register(entt::handle entity) { // Try to reuse expired handles before adding an entry - m_ownedEntities.emplace_back(GetRegistry(), entity); + m_ownedEntities.emplace_back(entity); } } diff --git a/include/CoreLib/Components/HealthComponent.hpp b/include/CoreLib/Components/HealthComponent.hpp index 0d83b03e..cda226ad 100644 --- a/include/CoreLib/Components/HealthComponent.hpp +++ b/include/CoreLib/Components/HealthComponent.hpp @@ -19,18 +19,18 @@ namespace bw inline HealthComponent(entt::handle entity, Nz::UInt16 maxHealth); inline HealthComponent(const HealthComponent& health); - inline void Damage(Nz::UInt16 damage, entt::entity attacker); + inline void Damage(Nz::UInt16 damage, entt::handle attacker); inline Nz::UInt16 GetHealth() const; inline float GetHealthPct() const; inline Nz::UInt16 GetMaxHealth() const; - inline void Heal(Nz::UInt16 heal, entt::entity healer); + inline void Heal(Nz::UInt16 heal, entt::handle healer); - NazaraSignal(OnDamage, HealthComponent* /*emitter*/, Nz::UInt16& /*damage*/, entt::entity /*attacker*/); - NazaraSignal(OnDying, HealthComponent* /*emitter*/, entt::entity /*attacker*/); - NazaraSignal(OnDie, const HealthComponent* /*emitter*/, entt::entity /*attacker*/); - NazaraSignal(OnHealthChange, HealthComponent* /*emitter*/, Nz::UInt16 /*newHealth*/, entt::entity /*source*/); + NazaraSignal(OnDamage, HealthComponent* /*emitter*/, Nz::UInt16& /*damage*/, entt::handle /*attacker*/); + NazaraSignal(OnDying, HealthComponent* /*emitter*/, entt::handle /*attacker*/); + NazaraSignal(OnDie, const HealthComponent* /*emitter*/, entt::handle /*attacker*/); + NazaraSignal(OnHealthChange, HealthComponent* /*emitter*/, Nz::UInt16 /*newHealth*/, entt::handle /*source*/); private: Nz::UInt16 m_currentHealth; diff --git a/include/CoreLib/Components/HealthComponent.inl b/include/CoreLib/Components/HealthComponent.inl index f8258aeb..ace99f17 100644 --- a/include/CoreLib/Components/HealthComponent.inl +++ b/include/CoreLib/Components/HealthComponent.inl @@ -20,7 +20,7 @@ namespace bw { } - inline void HealthComponent::Damage(Nz::UInt16 damage, entt::entity attacker) + inline void HealthComponent::Damage(Nz::UInt16 damage, entt::handle attacker) { OnDamage(this, damage, attacker); @@ -62,7 +62,7 @@ namespace bw return m_maxHealth; } - inline void HealthComponent::Heal(Nz::UInt16 heal, entt::entity healer) + inline void HealthComponent::Heal(Nz::UInt16 heal, entt::handle healer) { Nz::UInt16 newHealth = m_currentHealth + heal; if (newHealth < m_currentHealth) diff --git a/include/CoreLib/Components/InputComponent.hpp b/include/CoreLib/Components/InputComponent.hpp index fef586ca..1ac99ddb 100644 --- a/include/CoreLib/Components/InputComponent.hpp +++ b/include/CoreLib/Components/InputComponent.hpp @@ -10,16 +10,17 @@ #include #include #include +#include #include #include #include namespace bw { - class BURGWAR_CORELIB_API InputComponent + class BURGWAR_CORELIB_API InputComponent : public BaseComponent { public: - inline InputComponent(std::shared_ptr inputController); + inline InputComponent(entt::handle handle, std::shared_ptr inputController); inline const std::shared_ptr& GetController() const; inline const PlayerInputData& GetInputs() const; diff --git a/include/CoreLib/Components/InputComponent.inl b/include/CoreLib/Components/InputComponent.inl index d2853773..662bb057 100644 --- a/include/CoreLib/Components/InputComponent.inl +++ b/include/CoreLib/Components/InputComponent.inl @@ -6,7 +6,8 @@ namespace bw { - inline InputComponent::InputComponent(std::shared_ptr inputController) : + inline InputComponent::InputComponent(entt::handle handle, std::shared_ptr inputController) : + BaseComponent(handle), m_inputIndex(0), m_inputController(std::move(inputController)) { @@ -43,7 +44,7 @@ namespace bw if (++m_inputIndex >= m_inputData.size()) m_inputIndex = 0; - m_inputData[m_inputIndex] = std::move(inputData); + m_inputData[m_inputIndex] = inputData; OnInputUpdate(this); } diff --git a/include/CoreLib/Components/MatchComponent.hpp b/include/CoreLib/Components/MatchComponent.hpp index 29731c0d..36b400df 100644 --- a/include/CoreLib/Components/MatchComponent.hpp +++ b/include/CoreLib/Components/MatchComponent.hpp @@ -10,6 +10,7 @@ #include #include #include +#include namespace bw { @@ -19,15 +20,20 @@ namespace bw { public: inline MatchComponent(Match& match, LayerIndex layerIndex, EntityId uniqueId); + MatchComponent(const MatchComponent&) = delete; + MatchComponent(MatchComponent&&) noexcept = default; ~MatchComponent() = default; inline LayerIndex GetLayerIndex() const; inline Match& GetMatch() const; inline EntityId GetUniqueId() const; + MatchComponent& operator=(const MatchComponent&) = delete; + MatchComponent& operator=(MatchComponent&&) noexcept = default; + private: + Nz::MovablePtr m_match; EntityId m_uniqueId; - Match& m_match; LayerIndex m_layerIndex; }; } diff --git a/include/CoreLib/Components/MatchComponent.inl b/include/CoreLib/Components/MatchComponent.inl index fc65f0c0..b950a22d 100644 --- a/include/CoreLib/Components/MatchComponent.inl +++ b/include/CoreLib/Components/MatchComponent.inl @@ -7,8 +7,8 @@ namespace bw { inline MatchComponent::MatchComponent(Match& match, LayerIndex layerIndex, EntityId uniqueId) : + m_match(&match), m_uniqueId(uniqueId), - m_match(match), m_layerIndex(layerIndex) { } @@ -20,7 +20,7 @@ namespace bw inline Match& MatchComponent::GetMatch() const { - return m_match; + return *m_match; } inline EntityId MatchComponent::GetUniqueId() const diff --git a/include/CoreLib/Components/NetworkSyncComponent.hpp b/include/CoreLib/Components/NetworkSyncComponent.hpp index 08fade80..c8f5915a 100644 --- a/include/CoreLib/Components/NetworkSyncComponent.hpp +++ b/include/CoreLib/Components/NetworkSyncComponent.hpp @@ -8,17 +8,22 @@ #define BURGWAR_CORELIB_COMPONENTS_NETWORKSYNCCOMPONENT_HPP #include +#include #include #include #include namespace bw { + class NetworkSyncSystem; + class BURGWAR_CORELIB_API NetworkSyncComponent { public: - inline NetworkSyncComponent(Nz::UInt32 networkId, std::string entityClass, entt::handle parent = {}); - ~NetworkSyncComponent() = default; + NetworkSyncComponent(NetworkSyncSystem& networkSync, std::string entityClass, entt::handle parent = {}); + NetworkSyncComponent(const NetworkSyncComponent&) = delete; + inline NetworkSyncComponent(NetworkSyncComponent&& networkComponent) noexcept; + ~NetworkSyncComponent(); inline const std::string& GetEntityClass() const; inline Nz::UInt32 GetNetworkId() const; @@ -28,11 +33,17 @@ namespace bw inline void UpdateParent(entt::handle parent); + NetworkSyncComponent& operator=(const NetworkSyncComponent&) = delete; + inline NetworkSyncComponent& operator=(NetworkSyncComponent&& networkComponent) noexcept; + NazaraSignal(OnInvalidated, NetworkSyncComponent* /*emitter*/); private: + static constexpr Nz::UInt32 InvalidNetworkId = 0xFFFFFFFF; + std::string m_entityClass; entt::handle m_parent; + Nz::MovablePtr m_networkSystem; Nz::UInt32 m_networkId; }; } diff --git a/include/CoreLib/Components/NetworkSyncComponent.inl b/include/CoreLib/Components/NetworkSyncComponent.inl index 0d8ddd1e..fa2ae4f3 100644 --- a/include/CoreLib/Components/NetworkSyncComponent.inl +++ b/include/CoreLib/Components/NetworkSyncComponent.inl @@ -3,13 +3,15 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include +#include namespace bw { - inline NetworkSyncComponent::NetworkSyncComponent(Nz::UInt32 networkId, std::string entityClass, entt::handle parent) : - m_entityClass(entityClass), - m_parent(parent), - m_networkId(networkId) + inline NetworkSyncComponent::NetworkSyncComponent(NetworkSyncComponent&& networkComponent) noexcept : + m_entityClass(std::move(networkComponent.m_entityClass)), + m_parent(std::move(networkComponent.m_parent)), + m_networkId(std::exchange(networkComponent.m_networkId, InvalidNetworkId)), + m_networkSystem(std::move(networkComponent.m_networkSystem)) { } @@ -38,4 +40,15 @@ namespace bw m_parent = parent; //TODO: network event } + + inline NetworkSyncComponent& NetworkSyncComponent::operator=(NetworkSyncComponent&& networkComponent) noexcept + { + m_entityClass = std::move(networkComponent.m_entityClass); + m_parent = std::move(networkComponent.m_parent); + m_networkSystem = std::move(networkComponent.m_networkSystem); + + std::swap(m_networkId, networkComponent.m_networkId); + + return *this; + } } diff --git a/include/CoreLib/Components/ScriptComponent.inl b/include/CoreLib/Components/ScriptComponent.inl index 389957e2..e3b5dc15 100644 --- a/include/CoreLib/Components/ScriptComponent.inl +++ b/include/CoreLib/Components/ScriptComponent.inl @@ -32,7 +32,7 @@ namespace bw if (!callbackResult.valid()) { sol::error err = callbackResult; - bwLog(m_logger, LogLevel::Error, "{} callback failed: {}", ToString(Event), err.what()); + bwLog(*m_logger, LogLevel::Error, "{} callback failed: {}", ToString(Event), err.what()); if constexpr (!EventData::FatalError) continue; @@ -63,7 +63,7 @@ namespace bw if (!callbackResult.valid()) { sol::error err = callbackResult; - bwLog(m_logger, LogLevel::Error, "{} callback failed: {}", ToString(Event), err.what()); + bwLog(*m_logger, LogLevel::Error, "{} callback failed: {}", ToString(Event), err.what()); if constexpr (!EventData::FatalError) continue; @@ -110,7 +110,7 @@ namespace bw if (!callbackResult.valid()) { sol::error err = callbackResult; - bwLog(m_logger, LogLevel::Error, "{} callback failed: {}", eventData.name, err.what()); + bwLog(*m_logger, LogLevel::Error, "{} callback failed: {}", eventData.name, err.what()); continue; } @@ -135,7 +135,7 @@ namespace bw if (!callbackResult.valid()) { sol::error err = callbackResult; - bwLog(m_logger, LogLevel::Error, "{} callback failed: {}", eventData.name, err.what()); + bwLog(*m_logger, LogLevel::Error, "{} callback failed: {}", eventData.name, err.what()); continue; } @@ -146,7 +146,7 @@ namespace bw if (!callbackResult.valid()) { sol::error err = callbackResult; - bwLog(m_logger, LogLevel::Error, "{} combinator failed: {}", eventData.name, err.what()); + bwLog(*m_logger, LogLevel::Error, "{} combinator failed: {}", eventData.name, err.what()); continue; } diff --git a/include/CoreLib/Components/WeaponComponent.hpp b/include/CoreLib/Components/WeaponComponent.hpp index 62f65b96..91140a7b 100644 --- a/include/CoreLib/Components/WeaponComponent.hpp +++ b/include/CoreLib/Components/WeaponComponent.hpp @@ -8,6 +8,7 @@ #define BURGWAR_CORELIB_COMPONENTS_WEAPONCOMPONENT_HPP #include +#include namespace bw { @@ -22,11 +23,11 @@ namespace bw class BURGWAR_CORELIB_API WeaponComponent { public: - inline WeaponComponent(entt::entity owner, WeaponAttackMode attackMode); + inline WeaponComponent(entt::handle owner, WeaponAttackMode attackMode); ~WeaponComponent() = default; inline WeaponAttackMode GetAttackMode() const; - inline entt::entity GetOwner() const; + inline entt::handle GetOwner() const; inline bool IsActive() const; inline bool IsAttacking() const; @@ -34,10 +35,10 @@ namespace bw inline void SetActive(bool isActive); inline void SetAttacking(bool isAttacking); - inline void UpdateOwner(entt::entity owner); + inline void UpdateOwner(entt::handle owner); private: - entt::entity m_owner; + entt::handle m_owner; WeaponAttackMode m_attackMode; bool m_isActive; bool m_isAttacking; diff --git a/include/CoreLib/Components/WeaponComponent.inl b/include/CoreLib/Components/WeaponComponent.inl index 861a315d..e9d7fe5d 100644 --- a/include/CoreLib/Components/WeaponComponent.inl +++ b/include/CoreLib/Components/WeaponComponent.inl @@ -6,7 +6,7 @@ namespace bw { - inline WeaponComponent::WeaponComponent(entt::entity owner, WeaponAttackMode attackMode) : + inline WeaponComponent::WeaponComponent(entt::handle owner, WeaponAttackMode attackMode) : m_owner(owner), m_attackMode(attackMode), m_isActive(false), @@ -19,7 +19,7 @@ namespace bw return m_attackMode; } - inline entt::entity WeaponComponent::GetOwner() const + inline entt::handle WeaponComponent::GetOwner() const { return m_owner; } @@ -46,7 +46,7 @@ namespace bw m_isAttacking = isAttacking; } - inline void WeaponComponent::UpdateOwner(entt::entity owner) + inline void WeaponComponent::UpdateOwner(entt::handle owner) { m_owner = owner; } diff --git a/include/CoreLib/Components/WeaponWielderComponent.hpp b/include/CoreLib/Components/WeaponWielderComponent.hpp index 21fc7832..b9ccc3e2 100644 --- a/include/CoreLib/Components/WeaponWielderComponent.hpp +++ b/include/CoreLib/Components/WeaponWielderComponent.hpp @@ -23,10 +23,11 @@ namespace bw class BURGWAR_CORELIB_API WeaponWielderComponent : public BaseComponent { public: - using WeaponInitCallback = tl::function_ref; + using WeaponInitCallback = tl::function_ref; inline WeaponWielderComponent(entt::handle entity); inline WeaponWielderComponent(const WeaponWielderComponent& weaponWielder); + WeaponWielderComponent(WeaponWielderComponent&&) noexcept = default; ~WeaponWielderComponent() = default; inline entt::handle GetActiveWeapon() const; @@ -49,6 +50,9 @@ namespace bw inline bool SelectWeapon(const std::string& weaponClass); inline void SetWeaponOffset(const Nz::Vector2f& weaponOffset); + WeaponWielderComponent& operator=(const WeaponWielderComponent&) = delete; + WeaponWielderComponent& operator=(WeaponWielderComponent&&) noexcept = default; + static constexpr std::size_t NoWeapon = std::numeric_limits::max(); NazaraSignal(OnNewWeaponSelection, WeaponWielderComponent* /*wielder*/, std::size_t /*newWeaponIndex*/); diff --git a/include/CoreLib/EntityOwner.hpp b/include/CoreLib/EntityOwner.hpp index 92a61dd9..8354d964 100644 --- a/include/CoreLib/EntityOwner.hpp +++ b/include/CoreLib/EntityOwner.hpp @@ -22,9 +22,11 @@ namespace bw inline entt::handle GetEntity() const; operator entt::handle() const; + entt::handle* operator->(); + const entt::handle* operator->() const; EntityOwner& operator=(const EntityOwner&) = delete; - EntityOwner& operator=(EntityOwner&&) = delete; + inline EntityOwner& operator=(EntityOwner&& entityOwner) noexcept; private: entt::handle m_entity; diff --git a/include/CoreLib/EntityOwner.inl b/include/CoreLib/EntityOwner.inl index 3932ff1f..4f3f0d92 100644 --- a/include/CoreLib/EntityOwner.inl +++ b/include/CoreLib/EntityOwner.inl @@ -31,4 +31,21 @@ namespace bw { return m_entity; } + + inline entt::handle* EntityOwner::operator->() + { + return &m_entity; + } + + inline const entt::handle* EntityOwner::operator->() const + { + return &m_entity; + } + + inline EntityOwner& EntityOwner::operator=(EntityOwner&& entityOwner) noexcept + { + m_entity = entityOwner.m_entity; + + return *this; + } } diff --git a/include/CoreLib/Map.inl b/include/CoreLib/Map.inl index ef0d4109..97746eae 100644 --- a/include/CoreLib/Map.inl +++ b/include/CoreLib/Map.inl @@ -136,7 +136,7 @@ namespace bw return layer; } - template + template auto Map::EmplaceEntity(LayerIndex layerIndex, std::size_t entityIndex, Args&&... args) -> Entity& { auto& layer = GetLayer(layerIndex); diff --git a/include/CoreLib/MatchClientSession.hpp b/include/CoreLib/MatchClientSession.hpp index e9e92f1d..e798e98f 100644 --- a/include/CoreLib/MatchClientSession.hpp +++ b/include/CoreLib/MatchClientSession.hpp @@ -34,7 +34,7 @@ namespace bw friend PlayerCommandStore; public: - MatchClientSession(Match& match, std::size_t sessionId, PlayerCommandStore& commandStore, std::shared_ptr bridge); + MatchClientSession(Match& match, PlayerCommandStore& commandStore, std::shared_ptr bridge); MatchClientSession(const MatchClientSession&) = delete; MatchClientSession(MatchClientSession&&) = delete; ~MatchClientSession(); @@ -46,7 +46,6 @@ namespace bw inline Nz::UInt16 GetLastInputTick() const; inline Nz::UInt32 GetPing() const; inline const SessionBridge& GetSessionBridge() const; - inline std::size_t GetSessionId() const; inline MatchClientVisibility& GetVisibility(); inline const MatchClientVisibility& GetVisibility() const; @@ -92,7 +91,6 @@ namespace bw CircularBuffer m_queuedInputs; Match& m_match; PlayerCommandStore& m_commandStore; - std::size_t m_sessionId; std::shared_ptr m_bridge; std::unique_ptr m_visibility; //std::vector m_pendingAssetRequest; diff --git a/include/CoreLib/MatchClientSession.inl b/include/CoreLib/MatchClientSession.inl index 5763f37c..fe92e59d 100644 --- a/include/CoreLib/MatchClientSession.inl +++ b/include/CoreLib/MatchClientSession.inl @@ -32,11 +32,6 @@ namespace bw return *m_bridge; } - inline std::size_t MatchClientSession::GetSessionId() const - { - return m_sessionId; - } - inline MatchClientVisibility& MatchClientSession::GetVisibility() { return *m_visibility; diff --git a/include/CoreLib/MatchClientVisibility.hpp b/include/CoreLib/MatchClientVisibility.hpp index cc9d38e1..6930affb 100644 --- a/include/CoreLib/MatchClientVisibility.hpp +++ b/include/CoreLib/MatchClientVisibility.hpp @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include #include #include @@ -98,7 +98,7 @@ namespace bw void BuildMovementPacket(Packets::MatchState::Entity& packetData, const NetworkSyncSystem::EntityMovement& eventData); void FillEntityData(const NetworkSyncSystem::EntityCreation& creationEvent, Packets::Helper::EntityData& entityData); void HandleEntityCreation(LayerIndex layerIndex, const NetworkSyncSystem::EntityCreation& eventData); - void HandleEntityRemove(LayerIndex layerIndex, entt::entity entityId, bool deathEvent); + void HandleEntityRemove(LayerIndex layerIndex, Nz::UInt32 networkId, bool deathEvent); template void PushLayerEntities(std::vector& packetEntities, LayerIndex layerIndex, PendingCreationEventMap& pendingCreationMap); void SendMatchState(); @@ -125,16 +125,16 @@ namespace bw std::size_t visibilityCounter = 1; PendingCreationEventMap creationEvents; - tsl::hopscotch_map inputUpdateEvents; - tsl::hopscotch_map healthUpdateEvents; - tsl::hopscotch_map staticMovementUpdateEvents; - tsl::hopscotch_map playAnimationEvents; - tsl::hopscotch_map physicsEvents; - tsl::hopscotch_map scaleEvents; - tsl::hopscotch_map weaponEvents; - tsl::hopscotch_map visibleEntities; - tsl::hopscotch_set deathEvents; - tsl::hopscotch_set destructionEvents; + tsl::hopscotch_map inputUpdateEvents; + tsl::hopscotch_map healthUpdateEvents; + tsl::hopscotch_map staticMovementUpdateEvents; + tsl::hopscotch_map playAnimationEvents; + tsl::hopscotch_map physicsEvents; + tsl::hopscotch_map scaleEvents; + tsl::hopscotch_map weaponEvents; + tsl::hopscotch_map visibleEntities; + tsl::hopscotch_set deathEvents; + tsl::hopscotch_set destructionEvents; NazaraSlot(NetworkSyncSystem, OnEntityCreated, onEntityCreatedSlot); NazaraSlot(NetworkSyncSystem, OnEntityDeath, onEntityDeath); @@ -153,8 +153,8 @@ namespace bw Nz::Bitset m_clientVisibleLayers; Nz::Flags m_pendingEvents; tsl::hopscotch_map> m_layers; - tsl::hopscotch_map> m_pendingEntitiesEvent; - tsl::hopscotch_set m_controlledEntities; + tsl::hopscotch_map> m_pendingEntitiesEvent; + tsl::hopscotch_set m_controlledEntities; std::vector m_pendingLayerUpdates; std::vector m_multiplePendingEntitiesEvent; std::vector m_priorityMovementData; diff --git a/include/CoreLib/MatchSessions.hpp b/include/CoreLib/MatchSessions.hpp index 25c43a2f..64b7eb4e 100644 --- a/include/CoreLib/MatchSessions.hpp +++ b/include/CoreLib/MatchSessions.hpp @@ -41,12 +41,10 @@ namespace bw void Poll(); private: - std::size_t m_nextSessionId; std::vector> m_managers; Match& m_match; PlayerCommandStore m_commandStore; Nz::MemoryPool m_sessionPool; - tsl::hopscotch_map m_sessionIdToSession; }; } diff --git a/include/CoreLib/MatchSessions.inl b/include/CoreLib/MatchSessions.inl index 66dfbd63..3df3e6b8 100644 --- a/include/CoreLib/MatchSessions.inl +++ b/include/CoreLib/MatchSessions.inl @@ -16,8 +16,8 @@ namespace bw template void MatchSessions::ForEachSession(F&& cb) { - for (const auto& pair : m_sessionIdToSession) - cb(pair.second); + for (MatchClientSession& session : m_sessionPool) + cb(session); } inline Match& MatchSessions::GetMatch() diff --git a/include/CoreLib/Player.hpp b/include/CoreLib/Player.hpp index 5f9488ed..c2f7e99b 100644 --- a/include/CoreLib/Player.hpp +++ b/include/CoreLib/Player.hpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -65,7 +66,7 @@ namespace bw std::string ToString() const; - void UpdateControlledEntity(entt::entity entity, bool sendPacket = true, bool ignoreLayerUpdate = false); + void UpdateControlledEntity(entt::handle entity, bool sendPacket = true, bool ignoreLayerUpdate = false); void UpdateLayerVisibility(LayerIndex layerIndex, bool isVisible); inline void UpdateInputs(const PlayerInputData& inputData); void UpdateName(std::string newName); @@ -77,10 +78,10 @@ namespace bw static constexpr std::size_t NoWeapon = WeaponWielderComponent::NoWeapon; private: - void OnDeath(entt::entity attacker); + void OnDeath(entt::handle attacker); void SetReady(); - //NazaraSlot(Ndk::Entity, OnEntityDestruction, m_onPlayerEntityDestruction); + NazaraSlot(DestructionWatcherComponent, OnDestruction, m_onPlayerEntityDestruction); NazaraSlot(HealthComponent, OnDie, m_onPlayerEntityDie); NazaraSlot(WeaponWielderComponent, OnWeaponAdded, m_onWeaponAdded); NazaraSlot(WeaponWielderComponent, OnWeaponRemove, m_onWeaponRemove); diff --git a/include/CoreLib/Player.inl b/include/CoreLib/Player.inl index 1de71060..cd23aeb2 100644 --- a/include/CoreLib/Player.inl +++ b/include/CoreLib/Player.inl @@ -11,7 +11,7 @@ namespace bw if (m_playerEntity) return m_playerEntity->GetEntity(); else - return entt::null; + return {}; } inline const PlayerInputData& Player::GetInputs() const diff --git a/include/CoreLib/Scripting/ScriptStore.hpp b/include/CoreLib/Scripting/ScriptStore.hpp index 0909b6ed..0addebb8 100644 --- a/include/CoreLib/Scripting/ScriptStore.hpp +++ b/include/CoreLib/Scripting/ScriptStore.hpp @@ -7,12 +7,12 @@ #ifndef BURGWAR_CORELIB_SCRIPTING_SCRIPTSTORE_HPP #define BURGWAR_CORELIB_SCRIPTING_SCRIPTSTORE_HPP -#include #include #include #include #include #include +#include #include #include #include @@ -47,7 +47,7 @@ namespace bw void Resolve(); - void UpdateEntityElement(entt::entity entity); + void UpdateEntityElement(entt::handle entity); static constexpr std::size_t InvalidIndex = std::numeric_limits::max(); @@ -56,7 +56,7 @@ namespace bw entt::handle CreateEntity(entt::registry& registry, std::shared_ptr element, PropertyValueMap properties) const; virtual void InitializeElementTable(sol::main_table& elementTable); virtual void InitializeElement(sol::main_table& elementTable, Element& element) = 0; - bool InitializeEntity(const Element& entityClass, entt::entity entity) const; + bool InitializeEntity(const Element& entityClass, entt::handle entity) const; sol::state& GetLuaState(); const std::shared_ptr& GetScriptingContext() const; diff --git a/include/CoreLib/Scripting/ScriptStore.inl b/include/CoreLib/Scripting/ScriptStore.inl index 1add0b0d..102b6aeb 100644 --- a/include/CoreLib/Scripting/ScriptStore.inl +++ b/include/CoreLib/Scripting/ScriptStore.inl @@ -67,39 +67,24 @@ namespace bw return m_logger; } - template - inline void ScriptStore::UpdateEntityElement(entt::entity entity) - { - assert(entity->HasComponent()); - - auto& entityScript = entity->GetComponent(); - const auto& entityElement = entityScript.GetElement(); - - if (auto it = m_elementsByName.find(entityElement->fullName); it != m_elementsByName.end()) - { - const auto& newElement = m_elements[it->second]; - - sol::table& entityTable = entityScript.GetTable(); - entityTable[sol::metatable_key] = newElement->elementTable; - - entityScript.UpdateElement(newElement); - } - } - template void ScriptStore::LoadDirectory(const std::filesystem::path& directoryPath) { const auto& scriptDir = m_context->GetScriptDirectory(); - VirtualDirectory::Entry entry; - if (scriptDir->GetEntry(directoryPath.generic_u8string(), &entry) && std::holds_alternative(entry)) + auto callback = [&](const Nz::VirtualDirectory::Entry& entry) { - VirtualDirectory::DirectoryEntry& directory = std::get(entry); - directory->Foreach([&](const std::string& entryName, const Nz::VirtualDirectory::Entry& entry) + if (std::holds_alternative(entry)) { - LoadElement(std::holds_alternative(entry), directoryPath / entryName); - }); - } + const Nz::VirtualDirectory::DirectoryEntry& directoryEntry = std::get(entry); + directoryEntry.directory->Foreach([&](std::string_view entryName, const Nz::VirtualDirectory::Entry& entry) + { + LoadElement(std::holds_alternative(entry), directoryPath / entryName); + }); + } + }; + + scriptDir->GetEntry(directoryPath.generic_u8string(), callback); } template @@ -250,6 +235,23 @@ namespace bw m_pendingElements.clear(); } + template + void ScriptStore::UpdateEntityElement(entt::handle entity) + { + auto& entityScript = entity.get(); + const auto& entityElement = entityScript.GetElement(); + + if (auto it = m_elementsByName.find(entityElement->fullName); it != m_elementsByName.end()) + { + const auto& newElement = m_elements[it->second]; + + sol::table& entityTable = entityScript.GetTable(); + entityTable[sol::metatable_key] = newElement->elementTable; + + entityScript.UpdateElement(newElement); + } + } + template std::shared_ptr ScriptStore::CreateElement() const { @@ -312,7 +314,7 @@ namespace bw entityTable["_Entity"] = entity; entityTable[sol::metatable_key] = element->elementTable; - registry.emplace(m_logger, std::move(element), scriptingContext, std::move(entityTable), std::move(filteredProperties)); + registry.emplace(entity, m_logger, std::move(element), scriptingContext, std::move(entityTable), std::move(filteredProperties)); return entity; } @@ -526,9 +528,9 @@ namespace bw } template - bool ScriptStore::InitializeEntity(const Element& entityClass, entt::entity entity) const + bool ScriptStore::InitializeEntity(const Element& entityClass, entt::handle entity) const { - auto& entityScript = entity->GetComponent(); + auto& entityScript = entity.get(); if (!entityScript.ExecuteCallback()) { //TODO: Retrieve error message diff --git a/include/CoreLib/Scripting/ServerElementLibrary.hpp b/include/CoreLib/Scripting/ServerElementLibrary.hpp index 6a617466..be6c8170 100644 --- a/include/CoreLib/Scripting/ServerElementLibrary.hpp +++ b/include/CoreLib/Scripting/ServerElementLibrary.hpp @@ -23,7 +23,7 @@ namespace bw private: void RegisterServerLibrary(sol::table& elementTable); - void SetScale(entt::entity entity, float newScale) override; + void SetScale(entt::handle entity, float newScale) override; }; } diff --git a/include/CoreLib/Scripting/ServerEntityLibrary.hpp b/include/CoreLib/Scripting/ServerEntityLibrary.hpp index 1c6d9920..291eecb5 100644 --- a/include/CoreLib/Scripting/ServerEntityLibrary.hpp +++ b/include/CoreLib/Scripting/ServerEntityLibrary.hpp @@ -23,13 +23,13 @@ namespace bw private: void RegisterServerLibrary(sol::table& elementMetatable); - void SetDirection(lua_State* L, entt::entity entity, const Nz::Vector2f& upVector) override; - void SetMass(lua_State* L, entt::entity entity, float mass, bool recomputeMomentOfInertia) override; - void SetMomentOfInertia(lua_State* L, entt::entity entity, float momentOfInertia) override; - void SetPosition(lua_State* L, entt::entity entity, const Nz::Vector2f& position) override; - void SetRotation(lua_State* L, entt::entity entity, const Nz::DegreeAnglef& rotation) override; - void UpdatePlayerJumpHeight(lua_State* L, entt::entity entity, float jumpHeight, float jumpHeightBoost) override; - void UpdatePlayerMovement(lua_State* L, entt::entity entity, float movementSpeed) override; + void SetDirection(lua_State* L, entt::handle entity, const Nz::Vector2f& upVector) override; + void SetMass(lua_State* L, entt::handle entity, float mass, bool recomputeMomentOfInertia) override; + void SetMomentOfInertia(lua_State* L, entt::handle entity, float momentOfInertia) override; + void SetPosition(lua_State* L, entt::handle entity, const Nz::Vector2f& position) override; + void SetRotation(lua_State* L, entt::handle entity, const Nz::DegreeAnglef& rotation) override; + void UpdatePlayerJumpHeight(lua_State* L, entt::handle entity, float jumpHeight, float jumpHeightBoost) override; + void UpdatePlayerMovement(lua_State* L, entt::handle entity, float movementSpeed) override; }; } diff --git a/include/CoreLib/Scripting/ServerWeaponStore.hpp b/include/CoreLib/Scripting/ServerWeaponStore.hpp index f201a6cb..3e6b5ada 100644 --- a/include/CoreLib/Scripting/ServerWeaponStore.hpp +++ b/include/CoreLib/Scripting/ServerWeaponStore.hpp @@ -21,7 +21,7 @@ namespace bw inline ServerWeaponStore(const Logger& logger, std::shared_ptr context); ~ServerWeaponStore() = default; - entt::handle InstantiateWeapon(TerrainLayer& layer, std::size_t weaponIndex, EntityId uniqueId, const PropertyValueMap& properties, entt::entity parent); + entt::handle InstantiateWeapon(TerrainLayer& layer, std::size_t weaponIndex, EntityId uniqueId, const PropertyValueMap& properties, entt::handle parent); private: void InitializeElement(sol::main_table& elementTable, ScriptedWeapon& weapon) override; diff --git a/include/CoreLib/Scripting/SharedElementLibrary.hpp b/include/CoreLib/Scripting/SharedElementLibrary.hpp index bbad986a..593f8565 100644 --- a/include/CoreLib/Scripting/SharedElementLibrary.hpp +++ b/include/CoreLib/Scripting/SharedElementLibrary.hpp @@ -9,6 +9,7 @@ #include #include +#include namespace bw { @@ -23,7 +24,7 @@ namespace bw void RegisterLibrary(sol::table& elementMetatable) override; protected: - virtual void SetScale(entt::entity entity, float newScale) = 0; + virtual void SetScale(entt::handle entity, float newScale) = 0; private: void RegisterCommonLibrary(sol::table& elementMetatable); diff --git a/include/CoreLib/Scripting/SharedGamemode.inl b/include/CoreLib/Scripting/SharedGamemode.inl index 4c4d075e..2f8b3d7f 100644 --- a/include/CoreLib/Scripting/SharedGamemode.inl +++ b/include/CoreLib/Scripting/SharedGamemode.inl @@ -82,7 +82,7 @@ namespace bw return combinedResult; } - template + template std::optional bw::SharedGamemode::ExecuteCustomCallback(std::size_t eventIndex, Args... args) //< FIXME: Not const because of a bug in sol { if (eventIndex >= m_customEventCallbacks.size()) diff --git a/include/CoreLib/Scripting/SharedWeaponStore.hpp b/include/CoreLib/Scripting/SharedWeaponStore.hpp index a918823e..b69e2672 100644 --- a/include/CoreLib/Scripting/SharedWeaponStore.hpp +++ b/include/CoreLib/Scripting/SharedWeaponStore.hpp @@ -21,7 +21,7 @@ namespace bw protected: void InitializeElement(sol::main_table& elementTable, ScriptedWeapon& weapon) override = 0; - bool InitializeWeapon(const ScriptedWeapon& weaponClass, entt::entity entity, entt::entity parent); + bool InitializeWeapon(const ScriptedWeapon& weaponClass, entt::handle entity, entt::handle parent); }; } diff --git a/include/CoreLib/SharedLayer.hpp b/include/CoreLib/SharedLayer.hpp index c2dce466..5db58e3d 100644 --- a/include/CoreLib/SharedLayer.hpp +++ b/include/CoreLib/SharedLayer.hpp @@ -9,6 +9,8 @@ #include #include +#include +#include #include namespace bw @@ -27,6 +29,7 @@ namespace bw inline LayerIndex GetLayerIndex() const; inline SharedMatch& GetMatch(); + inline Nz::Physics2DSystem& GetPhysicsSystem(); inline entt::registry& GetWorld(); inline const entt::registry& GetWorld() const; @@ -35,9 +38,13 @@ namespace bw SharedLayer& operator=(const SharedLayer&) = delete; SharedLayer& operator=(SharedLayer&&) = delete; + protected: + inline Nz::SystemGraph& GetSystemGraph(); + private: SharedMatch& m_match; entt::registry m_registry; + Nz::SystemGraph m_systemGraph; LayerIndex m_layerIndex; }; } diff --git a/include/CoreLib/SharedLayer.inl b/include/CoreLib/SharedLayer.inl index 70f8d23b..7ba889dc 100644 --- a/include/CoreLib/SharedLayer.inl +++ b/include/CoreLib/SharedLayer.inl @@ -10,8 +10,10 @@ namespace bw template void SharedLayer::ForEachEntity(F&& func) { - for (entt::entity entity : m_world.GetEntities()) - func(entity); + m_registry.each([&](entt::entity entity) + { + func(entt::handle(m_registry, entity)); + }); } inline LayerIndex SharedLayer::GetLayerIndex() const @@ -23,6 +25,11 @@ namespace bw { return m_match; } + + inline Nz::Physics2DSystem& SharedLayer::GetPhysicsSystem() + { + return m_systemGraph.GetSystem(); + } inline entt::registry& SharedLayer::GetWorld() { @@ -33,4 +40,9 @@ namespace bw { return m_registry; } + + inline Nz::SystemGraph& SharedLayer::GetSystemGraph() + { + return m_systemGraph; + } } diff --git a/include/CoreLib/Systems/AnimationSystem.hpp b/include/CoreLib/Systems/AnimationSystem.hpp index 28f910cf..e1f4dc69 100644 --- a/include/CoreLib/Systems/AnimationSystem.hpp +++ b/include/CoreLib/Systems/AnimationSystem.hpp @@ -8,6 +8,7 @@ #define BURGWAR_CLIENTLIB_SYSTEMS_ANIMATIONSYSTEM_HPP #include +#include #include namespace bw @@ -17,12 +18,13 @@ namespace bw class BURGWAR_CORELIB_API AnimationSystem { public: - AnimationSystem(SharedMatch& match); + inline AnimationSystem(entt::registry& registry, SharedMatch& match); ~AnimationSystem() = default; - private: - void OnUpdate(float elapsedTime); + void Update(float elapsedTime); + private: + entt::registry& m_registry; SharedMatch& m_match; }; } diff --git a/include/CoreLib/Systems/AnimationSystem.inl b/include/CoreLib/Systems/AnimationSystem.inl index 42284320..7d6ef60b 100644 --- a/include/CoreLib/Systems/AnimationSystem.inl +++ b/include/CoreLib/Systems/AnimationSystem.inl @@ -6,4 +6,9 @@ namespace bw { + inline AnimationSystem::AnimationSystem(entt::registry& registry, SharedMatch& match) : + m_registry(registry), + m_match(match) + { + } } diff --git a/include/CoreLib/Systems/InputSystem.hpp b/include/CoreLib/Systems/InputSystem.hpp index eeb9c5e2..6581d559 100644 --- a/include/CoreLib/Systems/InputSystem.hpp +++ b/include/CoreLib/Systems/InputSystem.hpp @@ -8,6 +8,7 @@ #define BURGWAR_CORELIB_SYSTEMS_INPUTSYSTEM_HPP #include +#include #include namespace bw @@ -15,11 +16,15 @@ namespace bw class BURGWAR_CORELIB_API InputSystem { public: - InputSystem(); + static constexpr Nz::Int64 ExecutionOrder = -1000; + + inline InputSystem(entt::registry& registry); ~InputSystem() = default; + void Update(float elapsedTime); + private: - void OnUpdate(float elapsedTime); + entt::registry& m_registry; }; } diff --git a/include/CoreLib/Systems/InputSystem.inl b/include/CoreLib/Systems/InputSystem.inl index acd62841..ef8a431b 100644 --- a/include/CoreLib/Systems/InputSystem.inl +++ b/include/CoreLib/Systems/InputSystem.inl @@ -6,4 +6,8 @@ namespace bw { + inline InputSystem::InputSystem(entt::registry& registry) : + m_registry(registry) + { + } } diff --git a/include/CoreLib/Systems/NetworkSyncSystem.hpp b/include/CoreLib/Systems/NetworkSyncSystem.hpp index 1f1d3c98..2cbca772 100644 --- a/include/CoreLib/Systems/NetworkSyncSystem.hpp +++ b/include/CoreLib/Systems/NetworkSyncSystem.hpp @@ -15,9 +15,11 @@ #include #include #include +#include #include #include #include +#include #include #include #include @@ -32,12 +34,17 @@ namespace bw class BURGWAR_CORELIB_API NetworkSyncSystem { + friend class NetworkSyncComponent; + public: + static constexpr Nz::Int64 ExecutionOrder = 100; + struct EntityCreation; struct EntityDestruction; struct EntityMovement; - NetworkSyncSystem(TerrainLayer& layer); + NetworkSyncSystem(entt::registry& registry, TerrainLayer& layer); + NetworkSyncSystem(const NetworkSyncSystem&) = delete; ~NetworkSyncSystem() = default; void CreateEntities(const std::function& callback) const; @@ -48,10 +55,14 @@ namespace bw void MoveEntities(const std::function& callback) const; - inline void NotifyPhysicsUpdate(entt::entity entity); inline void NotifyMovementUpdate(entt::entity entity); + inline void NotifyPhysicsUpdate(entt::entity entity); inline void NotifyScaleUpdate(entt::entity entity); + void Update(float elapsedTime); + + NetworkSyncSystem& operator=(const NetworkSyncSystem&) = delete; + struct HealthProperties { Nz::UInt16 currentHealth; @@ -74,49 +85,49 @@ namespace bw struct EntityPlayAnimation { - entt::entity entityId; + Nz::UInt32 entityId; std::size_t animId; Nz::UInt64 startTime; }; struct EntityCreation { - entt::entity entityId; + Nz::UInt32 entityId; EntityId uniqueId; Nz::RadianAnglef rotation; Nz::Vector2f position; float scale; Player* playerOwner; - std::optional parent; - std::optional weapon; + std::optional parent; + std::optional weapon; std::optional healthProperties; std::optional inputs; std::optional playerMovement; std::optional physicsProperties; std::string entityClass; tsl::hopscotch_map properties; - std::vector> dependentIds; + std::vector> dependentIds; }; struct EntityDeath { - entt::entity entityId; + Nz::UInt32 entityId; }; struct EntityDestruction { - entt::entity entityId; + Nz::UInt32 entityId; }; struct EntityHealth { - entt::entity entityId; + Nz::UInt32 entityId; Nz::UInt16 currentHealth; }; struct EntityInputs { - entt::entity entityId; + Nz::UInt32 entityId; PlayerInputData inputs; }; @@ -129,7 +140,7 @@ namespace bw float movementSpeed; }; - entt::entity entityId; + Nz::UInt32 entityId; bool isAsleep; float mass; float momentOfInertia; @@ -138,19 +149,19 @@ namespace bw struct EntityScale { - entt::entity entityId; + Nz::UInt32 entityId; float newScale; }; struct EntityWeapon { - entt::entity entityId; - std::optional weaponId; + Nz::UInt32 entityId; + std::optional weaponId; }; struct EntityMovement { - entt::entity entityId; + Nz::UInt32 entityId; Nz::RadianAnglef rotation; Nz::Vector2f position; std::optional playerMovement; @@ -169,14 +180,17 @@ namespace bw NazaraSignal(OnEntitiesWeaponUpdate, NetworkSyncSystem* /*emitter*/, const EntityWeapon* /*events*/, std::size_t /*entityCount*/); private: + Nz::UInt32 AllocateNetworkId(); + void BuildEvent(EntityCreation& creationEvent, entt::entity entity) const; void BuildEvent(EntityDeath& deathEvent, entt::entity entity) const; void BuildEvent(EntityDestruction& deleteEvent, entt::entity entity) const; void BuildEvent(EntityMovement& movementEvent, entt::entity entity) const; - //void OnEntityAdded(entt::entity entity) override; - //void OnEntityRemoved(entt::entity entity) override; - //void OnUpdate(float elapsedTime) override; + void FreeNetworkId(Nz::UInt32 networkId); + + void HandleNewEntity(entt::entity entity); + void OnComponentRemoved(entt::entity entity); struct EntitySlots { @@ -188,8 +202,10 @@ namespace bw NazaraSlot(WeaponWielderComponent, OnNewWeaponSelection, onNewWeaponSelection); }; + entt::observer m_observer; + entt::registry& m_registry; + Nz::Bitset m_freeNetworkIds; tsl::hopscotch_map m_entitySlots; - tsl::hopscotch_set m_inputUpdateEntities; tsl::hopscotch_set m_healthUpdateEntities; tsl::hopscotch_set m_movedStaticEntities; diff --git a/include/CoreLib/Systems/NetworkSyncSystem.inl b/include/CoreLib/Systems/NetworkSyncSystem.inl index 2f0f6d72..c3adbc27 100644 --- a/include/CoreLib/Systems/NetworkSyncSystem.inl +++ b/include/CoreLib/Systems/NetworkSyncSystem.inl @@ -16,12 +16,6 @@ namespace bw return m_layer; } - inline void NetworkSyncSystem::NotifyPhysicsUpdate(entt::entity entity) - { - if (m_physicsEntities.contains(entity)) - m_physicsUpdateEntities.insert(entity); - } - inline void NetworkSyncSystem::NotifyMovementUpdate(entt::entity entity) { // Dynamic entities are sent regulary, only send static for now (TODO: Handle teleportation this way) @@ -29,6 +23,12 @@ namespace bw m_movedStaticEntities.insert(entity); } + inline void NetworkSyncSystem::NotifyPhysicsUpdate(entt::entity entity) + { + if (m_physicsEntities.contains(entity)) + m_physicsUpdateEntities.insert(entity); + } + inline void NetworkSyncSystem::NotifyScaleUpdate(entt::entity entity) { m_scaleUpdateEntities.insert(entity); diff --git a/include/CoreLib/Systems/PlayerMovementSystem.hpp b/include/CoreLib/Systems/PlayerMovementSystem.hpp index fcb89ac5..d8505d12 100644 --- a/include/CoreLib/Systems/PlayerMovementSystem.hpp +++ b/include/CoreLib/Systems/PlayerMovementSystem.hpp @@ -4,34 +4,35 @@ #pragma once -#ifndef BURGWAR_CORELIB_SYSTEMS_PLAYERMOVEMENT_HPP -#define BURGWAR_CORELIB_SYSTEMS_PLAYERMOVEMENT_HPP +#ifndef BURGWAR_CLIENTLIB_SYSTEMS_PLAYERMOVEMENT_HPP +#define BURGWAR_CLIENTLIB_SYSTEMS_PLAYERMOVEMENT_HPP #include #include +#include #include namespace bw { class BURGWAR_CORELIB_API PlayerMovementSystem { + static constexpr Nz::Int64 ExecutionOrder = 50; + public: PlayerMovementSystem(entt::registry& registry); - ~PlayerMovementSystem() = default; + ~PlayerMovementSystem(); + + void Update(float elapsedTime); private: - void OnEntityAdded(Ndk::Entity* entity) override; - void OnEntityRemoved(Ndk::Entity* entity) override; - void OnUpdate(float elapsedTime) override; + void OnMovementDestroy(entt::registry& registry, entt::entity entity); + void OnInputDestroy(entt::registry& registry, entt::entity entity); entt::connection m_inputDestroyConnection; - entt::connection m_graphicsDestroyConnection; - entt::connection m_lightDestroyConnection; - entt::connection m_nodeDestroyConnection; - entt::observer m_cameraConstructObserver; - entt::observer m_graphicsConstructObserver; - entt::observer m_lightConstructObserver; + entt::connection m_movementDestroyConnection; + entt::observer m_controllerObserver; entt::registry& m_registry; + std::unordered_set m_inputControlledEntities; }; } diff --git a/include/CoreLib/Systems/TickCallbackSystem.hpp b/include/CoreLib/Systems/TickCallbackSystem.hpp index aa1ccf1c..d06cf29b 100644 --- a/include/CoreLib/Systems/TickCallbackSystem.hpp +++ b/include/CoreLib/Systems/TickCallbackSystem.hpp @@ -8,28 +8,29 @@ #define BURGWAR_CORELIB_SYSTEMS_TICKCALLBACKSYSTEM_HPP #include -#include -#include +#include +#include #include namespace bw { class SharedMatch; - class BURGWAR_CORELIB_API TickCallbackSystem : public Ndk::System + class BURGWAR_CORELIB_API TickCallbackSystem { public: - TickCallbackSystem(SharedMatch& match); - ~TickCallbackSystem() = default; + TickCallbackSystem(entt::registry& registry, SharedMatch& match); + ~TickCallbackSystem(); - static Ndk::SystemIndex systemIndex; + void Update(float elapsedTime); private: - void OnEntityRemoved(Ndk::Entity* entity) override; - void OnEntityValidation(Ndk::Entity* entity, bool justAdded) override; - void OnUpdate(float elapsedTime) override; + void OnScriptDestroy(entt::registry& registry, entt::entity entity); - Ndk::EntityList m_tickableEntities; + std::unordered_set m_tickableEntities; + entt::connection m_scriptDestroyConnection; + entt::observer m_scriptObserver; + entt::registry& m_registry; SharedMatch& m_match; }; } diff --git a/include/CoreLib/Systems/WeaponSystem.hpp b/include/CoreLib/Systems/WeaponSystem.hpp index 787d2e26..75c8d80e 100644 --- a/include/CoreLib/Systems/WeaponSystem.hpp +++ b/include/CoreLib/Systems/WeaponSystem.hpp @@ -8,25 +8,23 @@ #define BURGWAR_CORELIB_SYSTEMS_WEAPONSYSTEM_HPP #include -#include -#include +#include #include namespace bw { class SharedMatch; - class BURGWAR_CORELIB_API WeaponSystem : public Ndk::System + class BURGWAR_CORELIB_API WeaponSystem { public: - WeaponSystem(SharedMatch& match); + inline WeaponSystem(entt::registry& registry, SharedMatch& match); ~WeaponSystem() = default; - static Ndk::SystemIndex systemIndex; + void Update(float elapsedTime); private: - void OnUpdate(float elapsedTime) override; - + entt::registry& m_registry; SharedMatch& m_match; }; } diff --git a/include/CoreLib/Systems/WeaponSystem.inl b/include/CoreLib/Systems/WeaponSystem.inl index d287a7c9..d62dee74 100644 --- a/include/CoreLib/Systems/WeaponSystem.inl +++ b/include/CoreLib/Systems/WeaponSystem.inl @@ -6,4 +6,9 @@ namespace bw { + inline WeaponSystem::WeaponSystem(entt::registry& registry, SharedMatch& match) : + m_registry(registry), + m_match(match) + { + } } diff --git a/include/CoreLib/Terrain.hpp b/include/CoreLib/Terrain.hpp index 4cf25146..859a8a2f 100644 --- a/include/CoreLib/Terrain.hpp +++ b/include/CoreLib/Terrain.hpp @@ -38,7 +38,7 @@ namespace bw private: Map& m_map; - std::vector m_layers; //< Shouldn't resize because of raw pointer in Player + std::vector> m_layers; }; } diff --git a/include/CoreLib/Terrain.inl b/include/CoreLib/Terrain.inl index 18bc66f6..48e37436 100644 --- a/include/CoreLib/Terrain.inl +++ b/include/CoreLib/Terrain.inl @@ -10,13 +10,13 @@ namespace bw inline TerrainLayer& Terrain::GetLayer(LayerIndex layerIndex) { assert(layerIndex < m_layers.size()); - return m_layers[layerIndex]; + return *m_layers[layerIndex]; } inline const TerrainLayer& Terrain::GetLayer(LayerIndex layerIndex) const { assert(layerIndex < m_layers.size()); - return m_layers[layerIndex]; + return *m_layers[layerIndex]; } inline LayerIndex Terrain::GetLayerCount() const diff --git a/include/CoreLib/TerrainLayer.hpp b/include/CoreLib/TerrainLayer.hpp index 9d8850fd..70026527 100644 --- a/include/CoreLib/TerrainLayer.hpp +++ b/include/CoreLib/TerrainLayer.hpp @@ -10,6 +10,7 @@ #include #include #include +#include namespace bw { @@ -27,6 +28,7 @@ namespace bw ~TerrainLayer() = default; Match& GetMatch(); + inline NetworkSyncSystem& GetNetworkSyncSystem(); void ResetEntities(); diff --git a/include/CoreLib/TerrainLayer.inl b/include/CoreLib/TerrainLayer.inl index d8c56b28..09bb4690 100644 --- a/include/CoreLib/TerrainLayer.inl +++ b/include/CoreLib/TerrainLayer.inl @@ -6,4 +6,8 @@ namespace bw { + inline NetworkSyncSystem& TerrainLayer::GetNetworkSyncSystem() + { + return GetSystemGraph().GetSystem(); + } } diff --git a/include/CoreLib/Utility/CircularBuffer.inl b/include/CoreLib/Utility/CircularBuffer.inl index 6a811f1f..9086919a 100644 --- a/include/CoreLib/Utility/CircularBuffer.inl +++ b/include/CoreLib/Utility/CircularBuffer.inl @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include #include namespace bw @@ -43,7 +43,7 @@ namespace bw } template - template + template void CircularBuffer::Enqueue(Args&&... args) { if (IsFull()) diff --git a/src/Client/ClientApp.cpp b/src/Client/ClientApp.cpp index 8da0eee5..2fa2f4a1 100644 --- a/src/Client/ClientApp.cpp +++ b/src/Client/ClientApp.cpp @@ -60,7 +60,7 @@ namespace bw m_mainWindow->EnableVerticalSync(vsync); m_mainWindow->SetFramerateLimit(fpsLimit); - Ndk::World& world = AddWorld(); + entt::registry& world = AddWorld(); Ndk::RenderSystem& renderSystem = world.AddSystem(); renderSystem.SetDefaultBackground(nullptr); diff --git a/src/Client/States/BackgroundState.cpp b/src/Client/States/BackgroundState.cpp index 7b3f0add..0398c322 100644 --- a/src/Client/States/BackgroundState.cpp +++ b/src/Client/States/BackgroundState.cpp @@ -6,7 +6,7 @@ #include #include #include -#include +#include #include #include #include @@ -67,7 +67,7 @@ namespace bw m_backgroundSprite->SetSize(newSize); - m_spriteEntity->GetComponent().SetPosition(canvasSize / 2.f - newSize / 2.f); + m_spriteentity.get().SetPosition(canvasSize / 2.f - newSize / 2.f); } } } diff --git a/src/Client/States/Game/ConnectedState.cpp b/src/Client/States/Game/ConnectedState.cpp index 2c47af68..9dc1704f 100644 --- a/src/Client/States/Game/ConnectedState.cpp +++ b/src/Client/States/Game/ConnectedState.cpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include namespace bw { @@ -53,7 +53,7 @@ namespace bw float cursor = 0.f; if (m_connectionLostEntity) { - auto& entityNode = m_connectionLostEntity->GetComponent(); + auto& entityNode = m_connectionLostentity.get(); entityNode.SetPosition(windowSize.x - m_connectionLostSprite->GetSize().x - 10.f, cursor); cursor += m_connectionLostSprite->GetSize().y; diff --git a/src/Client/States/StateData.hpp b/src/Client/States/StateData.hpp index cb0bee5d..95bab9d6 100644 --- a/src/Client/States/StateData.hpp +++ b/src/Client/States/StateData.hpp @@ -20,7 +20,7 @@ namespace bw { std::optional canvas; ClientApp* app; - Ndk::WorldHandle world; + entt::registryHandle world; Nz::RenderWindow* window; }; } diff --git a/src/ClientLib/Camera.cpp b/src/ClientLib/Camera.cpp index fe64e2e8..c1c9b39d 100644 --- a/src/ClientLib/Camera.cpp +++ b/src/ClientLib/Camera.cpp @@ -5,11 +5,11 @@ #include #include #include -#include +#include namespace bw { - Camera::Camera(Ndk::World& world, Nz::RenderTarget* renderTarget, bool perspective) : + Camera::Camera(entt::registry& world, Nz::RenderTarget* renderTarget, bool perspective) : m_isPerspective(!perspective), // To enable it after m_zoomFactor(1.f) { @@ -49,7 +49,7 @@ namespace bw Nz::Vector2f Camera::GetPosition() const { - auto& entityNode = m_cameraEntity->GetComponent(); + auto& entityNode = m_cameraentity.get(); return Nz::Vector2f(entityNode.GetPosition()); } @@ -73,7 +73,7 @@ namespace bw void Camera::MoveBy(const Nz::Vector2f& offset) { - auto& entityNode = m_cameraEntity->GetComponent(); + auto& entityNode = m_cameraentity.get(); MoveToPosition(Nz::Vector2f(entityNode.GetPosition()) + offset); } @@ -86,7 +86,7 @@ namespace bw OnCameraMove(this, position); - auto& entityNode = m_cameraEntity->GetComponent(); + auto& entityNode = m_cameraentity.get(); entityNode.SetPosition(position); } @@ -147,7 +147,7 @@ namespace bw void Camera::UpdateZoomFactor() { auto& entityCamera = m_cameraEntity->GetComponent(); - auto& entityNode = m_cameraEntity->GetComponent(); + auto& entityNode = m_cameraentity.get(); Nz::Vector2f viewportSize = Nz::Vector2f(entityCamera.GetTarget()->GetSize()) / m_zoomFactor; //viewportSize.x = std::round(viewportSize.x); diff --git a/src/ClientLib/ClientEditorLayer.cpp b/src/ClientLib/ClientEditorLayer.cpp index af0aee6f..3a1ac814 100644 --- a/src/ClientLib/ClientEditorLayer.cpp +++ b/src/ClientLib/ClientEditorLayer.cpp @@ -13,7 +13,7 @@ namespace bw ClientEditorLayer::ClientEditorLayer(SharedMatch& match, LayerIndex layerIndex) : SharedLayer(match, layerIndex) { - Ndk::World& world = GetWorld(); + entt::registry& world = GetWorld(); world.AddSystem(); world.AddSystem(); world.AddSystem(); @@ -21,7 +21,7 @@ namespace bw void ClientEditorLayer::FrameUpdate(float elapsedTime) { - Ndk::World& world = GetWorld(); + entt::registry& world = GetWorld(); world.ForEachSystem([](Ndk::BaseSystem& system) { system.Enable(false); @@ -35,7 +35,7 @@ namespace bw void ClientEditorLayer::PreFrameUpdate(float elapsedTime) { - Ndk::World& world = GetWorld(); + entt::registry& world = GetWorld(); world.ForEachSystem([](Ndk::BaseSystem& system) { system.Enable(false); @@ -48,7 +48,7 @@ namespace bw void ClientEditorLayer::PostFrameUpdate(float elapsedTime) { - Ndk::World& world = GetWorld(); + entt::registry& world = GetWorld(); world.ForEachSystem([](Ndk::BaseSystem& system) { system.Enable(false); @@ -61,7 +61,7 @@ namespace bw void ClientEditorLayer::TickUpdate(float elapsedTime) { - Ndk::World& world = GetWorld(); + entt::registry& world = GetWorld(); world.ForEachSystem([](Ndk::BaseSystem& system) { system.Enable(true); diff --git a/src/ClientLib/ClientLayer.cpp b/src/ClientLib/ClientLayer.cpp index f6b4e158..920e3fc7 100644 --- a/src/ClientLib/ClientLayer.cpp +++ b/src/ClientLib/ClientLayer.cpp @@ -13,7 +13,7 @@ #include #include #include -#include +#include #include #include @@ -25,7 +25,7 @@ namespace bw m_isEnabled(false), m_isPredictionEnabled(false) { - Ndk::World& world = GetWorld(); + entt::registry& world = GetWorld(); world.AddSystem(); world.AddSystem(); world.AddSystem(); diff --git a/src/ClientLib/ClientMatch.cpp b/src/ClientLib/ClientMatch.cpp index e2061904..982bdedd 100644 --- a/src/ClientLib/ClientMatch.cpp +++ b/src/ClientLib/ClientMatch.cpp @@ -365,7 +365,7 @@ namespace bw sol::state& state = m_scriptingContext->GetLuaState(); state["engine_AnimateRotation"] = LuaFunction([&](const sol::table& entityTable, float fromAngle, float toAngle, float duration, sol::main_protected_function callback) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); m_animationManager.PushAnimation(duration, [=](float ratio) { @@ -373,7 +373,7 @@ namespace bw return false; float newAngle = Nz::Lerp(fromAngle, toAngle, ratio); - auto& nodeComponent = entity->GetComponent(); + auto& nodeComponent = entity.get(); nodeComponent.SetRotation(Nz::DegreeAnglef(newAngle)); return true; @@ -391,7 +391,7 @@ namespace bw state["engine_AnimatePositionByOffsetSq"] = LuaFunction([&](const sol::table& entityTable, const Nz::Vector2f& fromOffset, const Nz::Vector2f& toOffset, float duration, sol::main_protected_function callback) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); m_animationManager.PushAnimation(duration, [=](float ratio) { @@ -399,7 +399,7 @@ namespace bw return false; Nz::Vector2f offset = Nz::Lerp(fromOffset, toOffset, ratio * ratio); //< FIXME - auto& nodeComponent = entity->GetComponent(); + auto& nodeComponent = entity.get(); nodeComponent.SetInitialPosition(offset); //< FIXME return true; diff --git a/src/ClientLib/Components/VisibleLayerComponent.cpp b/src/ClientLib/Components/VisibleLayerComponent.cpp index 37a029b3..b2c58e30 100644 --- a/src/ClientLib/Components/VisibleLayerComponent.cpp +++ b/src/ClientLib/Components/VisibleLayerComponent.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include namespace bw { @@ -69,7 +69,7 @@ namespace bw { assert(visibleLayer); - auto& nodeComponent = m_entity->GetComponent(); + auto& nodeComponent = m_entity.get(); visibleLayer->baseNode.SetParent(nodeComponent); visibleLayer->baseNode.SetScale(scale); diff --git a/src/ClientLib/LayerVisualEntity.cpp b/src/ClientLib/LayerVisualEntity.cpp index fdc3b8f0..c4f2b60b 100644 --- a/src/ClientLib/LayerVisualEntity.cpp +++ b/src/ClientLib/LayerVisualEntity.cpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include namespace bw { @@ -102,7 +102,7 @@ namespace bw Nz::Boxf LayerVisualEntity::GetGlobalBounds() const { - auto& entityNode = m_entity->GetComponent(); + auto& entityNode = m_entity.get(); Nz::Matrix4f worldMatrix = Nz::Matrix4f::ConcatenateAffine(s_coordinateMatrix, entityNode.GetTransformMatrix()); Nz::Vector3f globalPos = worldMatrix.GetTranslation(); @@ -160,7 +160,7 @@ namespace bw void LayerVisualEntity::SyncVisuals() { - auto& entityNode = m_entity->GetComponent(); + auto& entityNode = m_entity.get(); Nz::Vector2f position = Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys::Global)); Nz::Vector2f scale = Nz::Vector2f(entityNode.GetScale(Nz::CoordSys::Global)); @@ -221,12 +221,12 @@ namespace bw scriptComponent.ExecuteCallback(newScale); } - auto& node = m_entity->GetComponent(); + auto& node = m_entity.get(); Nz::Vector2f scale = Nz::Vector2f(node.GetScale()); scale.x = std::copysign(newScale, scale.x); scale.y = std::copysign(newScale, scale.y); - node.SetScale(scale, Nz::CoordSys_Local); + node.SetScale(scale, Nz::CoordSys::Local); if (m_entity->HasComponent()) { @@ -247,7 +247,7 @@ namespace bw } else { - auto& entityNode = m_entity->GetComponent(); + auto& entityNode = m_entity.get(); entityNode.SetPosition(position); entityNode.SetRotation(rotation); } @@ -265,7 +265,7 @@ namespace bw } else { - auto& entityNode = m_entity->GetComponent(); + auto& entityNode = m_entity.get(); entityNode.SetPosition(position); entityNode.SetRotation(rotation); } @@ -286,7 +286,7 @@ namespace bw visualEntity->Enable(IsEnabled()); - auto& entityNode = m_entity->GetComponent(); + auto& entityNode = m_entity.get(); Nz::Vector2f position = Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys::Global)); Nz::Vector2f scale = Nz::Vector2f(entityNode.GetScale(Nz::CoordSys::Global)); Nz::Quaternionf rotation = entityNode.GetRotation(Nz::CoordSys::Global); diff --git a/src/ClientLib/Scoreboard.cpp b/src/ClientLib/Scoreboard.cpp index 366c302c..7e9a072e 100644 --- a/src/ClientLib/Scoreboard.cpp +++ b/src/ClientLib/Scoreboard.cpp @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/ClientLib/Scripting/ClientEditorEntityStore.cpp b/src/ClientLib/Scripting/ClientEditorEntityStore.cpp index 64b1c4fa..cb8f5933 100644 --- a/src/ClientLib/Scripting/ClientEditorEntityStore.cpp +++ b/src/ClientLib/Scripting/ClientEditorEntityStore.cpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include namespace bw @@ -27,7 +27,7 @@ namespace bw return true; } - entt::entity ClientEditorEntityStore::InstantiateEntity(Ndk::World& world, std::size_t entityIndex, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, entt::entity parentEntity) const + entt::entity ClientEditorEntityStore::InstantiateEntity(entt::registry& world, std::size_t entityIndex, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, entt::entity parentEntity) const { const auto& entityClass = GetElement(entityIndex); diff --git a/src/ClientLib/Scripting/ClientElementLibrary.cpp b/src/ClientLib/Scripting/ClientElementLibrary.cpp index b453d002..c8c0b65c 100644 --- a/src/ClientLib/Scripting/ClientElementLibrary.cpp +++ b/src/ClientLib/Scripting/ClientElementLibrary.cpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include #include #include @@ -34,7 +34,7 @@ namespace bw { elementTable["AddModel"] = LuaFunction([this](const sol::table& entityTable, const sol::table& parameters) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); std::string modelPath = parameters["ModelPath"]; int renderOrder = parameters.get_or("RenderOrder", 0); @@ -58,8 +58,8 @@ namespace bw if (Nz::NumberEquals(pushbackForce, 0.f)) return; - entt::entity entity = AssertScriptEntity(entityTable); - Ndk::World* world = entity->GetWorld(); + entt::handle entity = AssertScriptEntity(entityTable); + entt::registry* world = entity->GetWorld(); assert(world); Ndk::EntityList hitEntities; //< FIXME: RegionQuery hit multiples entities @@ -81,7 +81,7 @@ namespace bw elementTable["AddSprite"] = LuaFunction([this](const sol::table& entityTable, const sol::table& parameters) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); std::string texturePath = parameters.get_or("TexturePath", std::string{}); int renderOrder = parameters.get_or("RenderOrder", 0); @@ -166,7 +166,7 @@ namespace bw elementTable["AddText"] = LuaFunction([this](const sol::table& entityTable, const sol::table& parameters) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); std::string fontName = parameters.get_or("Font", std::string{}); int renderOrder = parameters.get_or("RenderOrder", 0); @@ -226,14 +226,14 @@ namespace bw elementTable["GetGlobalBounds"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); auto& visualComponent = entity->GetComponent(); const auto& layerVisualHandle = visualComponent.GetLayerVisual(); if (!layerVisualHandle) { // Fallback on position - auto& nodeComponent = entity->GetComponent(); + auto& nodeComponent = entity.get(); Nz::Vector2f position = Nz::Vector2f(nodeComponent.GetPosition(Nz::CoordSys::Global)); return Nz::Rectf(position.x, position.y, 0.f, 0.f); } @@ -244,14 +244,14 @@ namespace bw elementTable["GetLayerIndex"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); return entity->GetComponent().GetLayerIndex(); }); elementTable["GetLocalBounds"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); auto& visualComponent = entity->GetComponent(); const auto& layerVisualHandle = visualComponent.GetLayerVisual(); @@ -264,7 +264,7 @@ namespace bw elementTable["GetOwner"] = LuaFunction([](sol::this_state s, const sol::table& table) -> sol::object { - entt::entity entity = AssertScriptEntity(table); + entt::handle entity = AssertScriptEntity(table); if (!entity->HasComponent()) return sol::nil; @@ -274,7 +274,7 @@ namespace bw elementTable["GetProperty"] = LuaFunction([](sol::this_state s, const sol::table& table, const std::string& propertyName) -> sol::object { - entt::entity entity = AssertScriptEntity(table); + entt::handle entity = AssertScriptEntity(table); auto& entityScript = entity->GetComponent(); @@ -298,14 +298,14 @@ namespace bw elementTable["PlaySound"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, const std::string& soundPath, bool isAttachedToEntity, bool isLooping, bool isSpatialized) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); auto& entityMatch = entity->GetComponent(); const Nz::SoundBufferRef& soundBuffer = m_assetStore.GetSoundBuffer(soundPath); if (!soundBuffer) TriggerLuaArgError(L, 1, "failed to load " + soundPath); - auto& entityNode = entity->GetComponent(); + auto& entityNode = entity.get(); auto& layer = entityMatch.GetLayer(); diff --git a/src/ClientLib/Scripting/ClientEntityLibrary.cpp b/src/ClientLib/Scripting/ClientEntityLibrary.cpp index 9a7a8877..01103441 100644 --- a/src/ClientLib/Scripting/ClientEntityLibrary.cpp +++ b/src/ClientLib/Scripting/ClientEntityLibrary.cpp @@ -21,7 +21,7 @@ #include #include #include -#include +#include #include namespace bw @@ -45,7 +45,7 @@ namespace bw { elementMetatable["AddLayer"] = LuaFunction([](sol::this_state L, const sol::table& entityTable, const sol::table& parameters) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); auto& clientMatch = entity->GetComponent().GetClientMatch(); @@ -66,7 +66,7 @@ namespace bw elementMetatable["AddTilemap"] = LuaFunction([this](const sol::table& entityTable, const Nz::Vector2ui& mapSize, const Nz::Vector2f& cellSize, const sol::table& content, const std::vector& tiles, int renderOrder = 0) -> sol::optional { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); // Compute tilemap tsl::hopscotch_map materials; @@ -137,7 +137,7 @@ namespace bw elementMetatable["ClearLayers"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); if (entity->HasComponent()) entity->GetComponent().Clear(); diff --git a/src/ClientLib/Scripting/ClientEntityStore.cpp b/src/ClientLib/Scripting/ClientEntityStore.cpp index 2bd1774a..3ee987f3 100644 --- a/src/ClientLib/Scripting/ClientEntityStore.cpp +++ b/src/ClientLib/Scripting/ClientEntityStore.cpp @@ -6,7 +6,7 @@ #include #include #include -#include +#include namespace bw { diff --git a/src/ClientLib/Scripting/ClientScriptingLibrary.cpp b/src/ClientLib/Scripting/ClientScriptingLibrary.cpp index a8d104a6..5b57469f 100644 --- a/src/ClientLib/Scripting/ClientScriptingLibrary.cpp +++ b/src/ClientLib/Scripting/ClientScriptingLibrary.cpp @@ -249,7 +249,7 @@ namespace bw if (!layout) TriggerLuaArgError(L, 2, "Invalid particle type \"" + particleType + "\""); - Ndk::World& world = match.GetRenderWorld(); + entt::registry& world = match.GetRenderWorld(); entt::entity particleGroupEntity = world.CreateEntity(); auto& particleGroup = particleGroupEntity->AddComponent(maxParticleCount, layout); diff --git a/src/ClientLib/Scripting/ClientWeaponLibrary.cpp b/src/ClientLib/Scripting/ClientWeaponLibrary.cpp index 1b296225..50c1d991 100644 --- a/src/ClientLib/Scripting/ClientWeaponLibrary.cpp +++ b/src/ClientLib/Scripting/ClientWeaponLibrary.cpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include #include @@ -30,8 +30,8 @@ namespace bw { auto shootFunc = [](const sol::table& weaponTable, Nz::Vector2f startPos, Nz::Vector2f direction, Nz::UInt16 /*damage*/, float pushbackForce = 0.f) { - entt::entity entity = AssertScriptEntity(weaponTable); - Ndk::World* world = entity->GetWorld(); + entt::handle entity = AssertScriptEntity(weaponTable); + entt::registry* world = entity->GetWorld(); assert(world); auto& physSystem = world->GetSystem(); diff --git a/src/ClientLib/SoundEntity.cpp b/src/ClientLib/SoundEntity.cpp index 5f64dce3..423f8da4 100644 --- a/src/ClientLib/SoundEntity.cpp +++ b/src/ClientLib/SoundEntity.cpp @@ -5,12 +5,12 @@ #include #include #include -#include +#include #include namespace bw { - SoundEntity::SoundEntity(Ndk::World& renderWorld, ClientLayerSoundHandle layerSoundHandle, float depth) : + SoundEntity::SoundEntity(entt::registry& renderWorld, ClientLayerSoundHandle layerSoundHandle, float depth) : m_entity(renderWorld.CreateEntity()), m_layerSound(std::move(layerSoundHandle)), m_depth(depth) @@ -21,10 +21,10 @@ namespace bw m_layerSound->RegisterAudibleSound(this); } - SoundEntity::SoundEntity(Ndk::World& renderWorld, ClientLayerSoundHandle layerSoundHandle, const Nz::Node& parentNode, float depth) : + SoundEntity::SoundEntity(entt::registry& renderWorld, ClientLayerSoundHandle layerSoundHandle, const Nz::Node& parentNode, float depth) : SoundEntity(renderWorld, std::move(layerSoundHandle), depth) { - m_entity->GetComponent().SetParent(parentNode); + m_entity.get().SetParent(parentNode); } SoundEntity::SoundEntity(SoundEntity&& entity) noexcept : @@ -47,7 +47,7 @@ namespace bw if (soundIndex >= m_soundIds.size()) m_soundIds.resize(soundIndex + 1); - auto& nodeComponent = m_entity->GetComponent(); + auto& nodeComponent = m_entity.get(); auto& soundEmitterComponent = m_entity->GetComponent(); m_soundIds[soundIndex] = soundEmitterComponent.PlaySound(soundBuffer, nodeComponent.GetPosition(), true, isLooping, isSpatialized); } @@ -62,7 +62,7 @@ namespace bw void SoundEntity::Update(const Nz::Vector2f& position) { - auto& visualNode = m_entity->GetComponent(); + auto& visualNode = m_entity.get(); visualNode.SetPosition(position); // Make sure parenting doesn't change our depth diff --git a/src/ClientLib/Systems/SoundSystem.cpp b/src/ClientLib/Systems/SoundSystem.cpp index 9b29ce98..6812c1f4 100644 --- a/src/ClientLib/Systems/SoundSystem.cpp +++ b/src/ClientLib/Systems/SoundSystem.cpp @@ -6,7 +6,7 @@ #include #include #include -#include +#include #include #include @@ -113,7 +113,7 @@ namespace bw { m_movableEntities.Insert(entity); - auto& nodeComponent = entity->GetComponent(); + auto& nodeComponent = entity.get(); auto& soundEmitterComponent = entity->GetComponent(); soundEmitterComponent.UpdateLastPosition(nodeComponent.GetPosition()); @@ -134,7 +134,7 @@ namespace bw for (entt::entity movableEntity : m_movableEntities) { - auto& nodeComponent = movableEntity->GetComponent(); + auto& nodeComponent = movableentity.get(); auto& soundEmitterComponent = movableEntity->GetComponent(); Nz::Vector3f entityPos = nodeComponent.GetPosition(); diff --git a/src/ClientLib/Systems/VisualInterpolationSystem.cpp b/src/ClientLib/Systems/VisualInterpolationSystem.cpp index 45c11636..314673c9 100644 --- a/src/ClientLib/Systems/VisualInterpolationSystem.cpp +++ b/src/ClientLib/Systems/VisualInterpolationSystem.cpp @@ -6,7 +6,7 @@ #include #include #include -#include +#include #include #include @@ -19,7 +19,7 @@ namespace bw void VisualInterpolationSystem::OnEntityAdded(Ndk::Entity* entity) { - auto& entityNode = entity->GetComponent(); + auto& entityNode = entity.get(); auto& entityLerp = entity->GetComponent(); entityLerp.UpdateLastStates(Nz::Vector2f(entityNode.GetPosition()), AngleFromQuaternion(entityNode.GetRotation())); @@ -33,7 +33,7 @@ namespace bw for (entt::entity entity : GetEntities()) { auto& entityLerp = entity->GetComponent(); - auto& entityNode = entity->GetComponent(); + auto& entityNode = entity.get(); auto& entityPhysics = entity->GetComponent(); // x = x + (target-x) * (1-Exp(-deltaTime*C)) diff --git a/src/ClientLib/VisualEntity.cpp b/src/ClientLib/VisualEntity.cpp index 2231c43b..d8caf8d6 100644 --- a/src/ClientLib/VisualEntity.cpp +++ b/src/ClientLib/VisualEntity.cpp @@ -5,12 +5,12 @@ #include #include #include -#include +#include #include namespace bw { - VisualEntity::VisualEntity(Ndk::World& renderWorld, LayerVisualEntityHandle visualEntityHandle, int baseRenderOrder) : + VisualEntity::VisualEntity(entt::registry& renderWorld, LayerVisualEntityHandle visualEntityHandle, int baseRenderOrder) : m_entity(renderWorld.CreateEntity()), m_visualEntity(std::move(visualEntityHandle)), m_baseRenderOrder(baseRenderOrder) @@ -21,10 +21,10 @@ namespace bw m_visualEntity->RegisterVisualEntity(this); } - VisualEntity::VisualEntity(Ndk::World& renderWorld, LayerVisualEntityHandle visualEntityHandle, const Nz::Node& parentNode, int baseRenderOrder) : + VisualEntity::VisualEntity(entt::registry& renderWorld, LayerVisualEntityHandle visualEntityHandle, const Nz::Node& parentNode, int baseRenderOrder) : VisualEntity(renderWorld, std::move(visualEntityHandle), baseRenderOrder) { - m_entity->GetComponent().SetParent(parentNode); + m_entity.get().SetParent(parentNode); } VisualEntity::VisualEntity(VisualEntity&& entity) noexcept : @@ -45,7 +45,7 @@ namespace bw void VisualEntity::Update(const Nz::Vector2f& position, const Nz::Quaternionf& rotation, const Nz::Vector2f& scale) { - auto& visualNode = m_entity->GetComponent(); + auto& visualNode = m_entity.get(); visualNode.SetPosition(position); visualNode.SetRotation(rotation); visualNode.SetScale(scale); @@ -68,7 +68,7 @@ namespace bw for (auto& hoveringRenderable : m_hoveringRenderables) { - auto& node = hoveringRenderable.entity->GetComponent(); + auto& node = hoveringRenderable.entity.get(); node.SetPosition(center.x, center.y - halfHeight - absoluteScale.y * hoveringRenderable.offset); node.SetScale(positiveScale); } diff --git a/src/CoreLib/Components/NetworkSyncComponent.cpp b/src/CoreLib/Components/NetworkSyncComponent.cpp new file mode 100644 index 00000000..dc878c25 --- /dev/null +++ b/src/CoreLib/Components/NetworkSyncComponent.cpp @@ -0,0 +1,23 @@ +// Copyright (C) 2020 Jérôme Leclercq +// This file is part of the "Burgwar" project +// For conditions of distribution and use, see copyright notice in LICENSE + +#include +#include + +namespace bw +{ + NetworkSyncComponent::NetworkSyncComponent(NetworkSyncSystem& networkSystem, std::string entityClass, entt::handle parent) : + m_entityClass(entityClass), + m_parent(parent), + m_networkSystem(&networkSystem) + { + m_networkId = m_networkSystem->AllocateNetworkId(); + } + + NetworkSyncComponent::~NetworkSyncComponent() + { + if (m_networkId != InvalidNetworkId) + m_networkSystem->FreeNetworkId(m_networkId); + } +} diff --git a/src/CoreLib/Components/WeaponWielderComponent.cpp b/src/CoreLib/Components/WeaponWielderComponent.cpp index ccf21117..784facc9 100644 --- a/src/CoreLib/Components/WeaponWielderComponent.cpp +++ b/src/CoreLib/Components/WeaponWielderComponent.cpp @@ -13,13 +13,13 @@ namespace bw if (HasWeapon(weaponClass)) return NoWeapon; - entt::entity weapon = callback(weaponClass); - if (weapon == entt::null) + entt::handle weapon = callback(weaponClass); + if (!weapon) return NoWeapon; //FIXME: New weapons should be resized to match the player size - assert(GetRegistry().try_get(weapon)); + assert(weapon.try_get()); std::size_t weaponIndex = m_weapons.size(); m_weapons.emplace_back(weapon); @@ -65,15 +65,15 @@ namespace bw assert(weaponId < m_weapons.size() || weaponId == NoWeapon); if (m_activeWeaponIndex != weaponId) { - auto& registry = GetRegistry(); + entt::registry* registry = GetRegistry(); if (m_activeWeaponIndex != NoWeapon) { - entt::entity previousWeapon = m_weapons[m_activeWeaponIndex]; - auto& weaponComponent = registry.get(previousWeapon); + entt::handle previousWeapon = m_weapons[m_activeWeaponIndex]; + auto& weaponComponent = registry->get(previousWeapon); weaponComponent.SetActive(false); - if (ScriptComponent* scriptComponent = registry.try_get(previousWeapon)) + if (ScriptComponent* scriptComponent = registry->try_get(previousWeapon)) scriptComponent->ExecuteCallback(); } @@ -82,11 +82,11 @@ namespace bw if (m_activeWeaponIndex != NoWeapon) { - entt::entity newWeapon = m_weapons[m_activeWeaponIndex]; - auto& weaponComponent = registry.get(newWeapon); + entt::handle newWeapon = m_weapons[m_activeWeaponIndex]; + auto& weaponComponent = registry->get(newWeapon); weaponComponent.SetActive(true); - if (ScriptComponent* scriptComponent = registry.try_get(newWeapon)) + if (ScriptComponent* scriptComponent = registry->try_get(newWeapon)) scriptComponent->ExecuteCallback(); } } diff --git a/src/CoreLib/CustomInputController.cpp b/src/CoreLib/CustomInputController.cpp index cc00e86e..fae4cf1a 100644 --- a/src/CoreLib/CustomInputController.cpp +++ b/src/CoreLib/CustomInputController.cpp @@ -18,7 +18,7 @@ namespace bw sol::protected_function_result result = m_callback(*entityTable); if (!result.valid()) { - auto& entityScript = registry.get(entity); + auto& entityScript = entity.get(); sol::error err = result; bwLog(entityScript.GetLogger(), LogLevel::Error, "CustomInputController failed: {}", err.what()); @@ -28,7 +28,7 @@ namespace bw auto inputsOpt = result.get>(); if (!inputsOpt) { - auto& entityScript = registry.get(entity); + auto& entityScript = entity.get(); bwLog(entityScript.GetLogger(), LogLevel::Error, "CustomInputController must return players inputs"); return PlayerInputData{}; diff --git a/src/CoreLib/LogSystem/StdSink.cpp b/src/CoreLib/LogSystem/StdSink.cpp index 28931890..1ed4cc2b 100644 --- a/src/CoreLib/LogSystem/StdSink.cpp +++ b/src/CoreLib/LogSystem/StdSink.cpp @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/CoreLib/Match.cpp b/src/CoreLib/Match.cpp index 24d8bf35..43cfba77 100644 --- a/src/CoreLib/Match.cpp +++ b/src/CoreLib/Match.cpp @@ -323,11 +323,13 @@ namespace bw Entity& entityData = m_entitiesByUniqueId.emplace(uniqueId, Entity{}).first.value(); entityData.entity = entity; - entityData.onDestruction.Connect(entity.get().OnDestruction, [this, entity, uniqueId]() + entityData.onDestruction.Connect(entity.get().OnDestruction, [this, uniqueId](DestructionWatcherComponent* watcher) { // Don't trigger the Destroyed event when resetting map if (!m_isResetting) { + entt::handle entity = watcher->GetHandle(); + auto& entityScript = entity.get(); entityScript.ExecuteCallback(); } @@ -619,7 +621,7 @@ namespace bw { auto it = m_entitiesByUniqueId.find(uniqueId); if (it == m_entitiesByUniqueId.end()) - return entt::null; + return {}; return it.value().entity; } @@ -683,7 +685,7 @@ namespace bw entityCount++; CompressedUnsigned layerId(i); - CompressedUnsigned entityId(entity->GetId()); //< TODO + CompressedUnsigned entityId(entitySync->GetNetworkId()); debugPacket << layerId; debugPacket << entityId; @@ -830,9 +832,9 @@ namespace bw { float elapsedTime = GetTickDuration(); - m_sessions.ForEachSession([&](MatchClientSession* session) + m_sessions.ForEachSession([&](MatchClientSession& session) { - session->OnTick(elapsedTime); + session.OnTick(elapsedTime); }); ForEachPlayer([&](Player* player) @@ -844,9 +846,9 @@ namespace bw m_terrain->Update(elapsedTime); - m_sessions.ForEachSession([&](MatchClientSession* session) + m_sessions.ForEachSession([&](MatchClientSession& session) { - session->Update(elapsedTime); + session.Update(elapsedTime); }); } diff --git a/src/CoreLib/MatchClientSession.cpp b/src/CoreLib/MatchClientSession.cpp index dc51c458..167abf92 100644 --- a/src/CoreLib/MatchClientSession.cpp +++ b/src/CoreLib/MatchClientSession.cpp @@ -24,11 +24,10 @@ namespace namespace bw { - MatchClientSession::MatchClientSession(Match& match, std::size_t sessionId, PlayerCommandStore& commandStore, std::shared_ptr bridge) : + MatchClientSession::MatchClientSession(Match& match, PlayerCommandStore& commandStore, std::shared_ptr bridge) : m_queuedInputs(4), m_match(match), m_commandStore(commandStore), - m_sessionId(sessionId), m_bridge(std::move(bridge)), m_ping(0), m_peerInfoUpdateCounter(0.f) @@ -253,11 +252,11 @@ namespace bw Player* player = m_players[packet.localIndex]; - entt::entity controlledEntity = player->GetControlledEntity(); + entt::handle controlledEntity = player->GetControlledEntity(); if (!controlledEntity) return; - auto& entityWeapons = controlledEntity->GetComponent(); + auto& entityWeapons = controlledEntity.get(); if (packet.newWeaponIndex >= entityWeapons.GetWeaponCount() && packet.newWeaponIndex != packet.NoWeapon) return; diff --git a/src/CoreLib/MatchClientVisibility.cpp b/src/CoreLib/MatchClientVisibility.cpp index 4c0a198a..d59c5b04 100644 --- a/src/CoreLib/MatchClientVisibility.cpp +++ b/src/CoreLib/MatchClientVisibility.cpp @@ -3,11 +3,12 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include -#include #include #include #include +#include +#include +#include #include #include @@ -78,7 +79,7 @@ namespace bw /* Create all newly visible entities */ TerrainLayer& terrainLayer = terrain.GetLayer(layerIndex); - NetworkSyncSystem& syncSystem = terrainLayer.GetWorld().GetSystem(); + NetworkSyncSystem& syncSystem = terrainLayer.GetNetworkSyncSystem(); layer.onEntityCreatedSlot.Connect(syncSystem.OnEntityCreated, [this](NetworkSyncSystem* syncSystem, const NetworkSyncSystem::EntityCreation& entityCreation) { @@ -279,7 +280,7 @@ namespace bw /* Create all newly visible entities */ TerrainLayer& terrainLayer = terrain.GetLayer(layerIndex); - NetworkSyncSystem& syncSystem = terrainLayer.GetWorld().GetSystem(); + entt::registry& registry = terrainLayer.GetWorld(); auto layerIt = m_layers.find(layerIndex); assert(layerIt != m_layers.end()); @@ -287,8 +288,9 @@ namespace bw if (m_clientVisibleLayers.UnboundedTest(i)) { - for (entt::entity entity : syncSystem.GetEntities()) - layer.visibleEntities.emplace(entity->GetId(), Layer::VisibleEntityData{}); + auto view = registry.view(); + for (entt::entity entity : view) + layer.visibleEntities.emplace(view.get(entity).GetNetworkId(), Layer::VisibleEntityData{}); continue; } @@ -635,7 +637,7 @@ namespace bw weaponPacket.stateTick = networkTick; auto& weaponData = pair.second; - weaponPacket.weaponEntityId = (weaponData.weaponId.has_value()) ? weaponData.weaponId.value() : Packets::EntityWeapon::NoWeapon; + weaponPacket.weaponEntityId = weaponData.weaponId.value_or(Packets::EntityWeapon::NoWeapon); m_session.SendPacket(weaponPacket); } @@ -720,13 +722,13 @@ namespace bw m_pendingEvents.Set(VisibilityEventType::Creation); } - void MatchClientVisibility::HandleEntityRemove(LayerIndex layerIndex, Ndk::EntityId entityId, bool deathEvent) + void MatchClientVisibility::HandleEntityRemove(LayerIndex layerIndex, Nz::UInt32 networkId, bool deathEvent) { assert(m_layers.find(layerIndex) != m_layers.end()); Layer& layer = *m_layers[layerIndex]; // Only send entity destruction packet if this entity was already created client-side - auto it = layer.creationEvents.find(entityId); + auto it = layer.creationEvents.find(networkId); if (it != layer.creationEvents.end()) layer.creationEvents.erase(it); else @@ -736,26 +738,26 @@ namespace bw if (deathEvent) { - layer.deathEvents.insert(entityId); + layer.deathEvents.insert(networkId); m_pendingEvents.Set(VisibilityEventType::Death); } else { - layer.destructionEvents.insert(entityId); + layer.destructionEvents.insert(networkId); m_pendingEvents.Set(VisibilityEventType::Destruction); } } - Nz::UInt64 entityKey = Nz::UInt64(layerIndex) << 32 | entityId; + Nz::UInt64 entityKey = Nz::UInt64(layerIndex) << 32 | networkId; m_controlledEntities.erase(entityKey); - layer.inputUpdateEvents.erase(entityId); - layer.healthUpdateEvents.erase(entityId); - layer.physicsEvents.erase(entityId); - layer.playAnimationEvents.erase(entityId); - layer.staticMovementUpdateEvents.erase(entityId); - layer.visibleEntities.erase(entityId); - layer.weaponEvents.erase(entityId); + layer.inputUpdateEvents.erase(networkId); + layer.healthUpdateEvents.erase(networkId); + layer.physicsEvents.erase(networkId); + layer.playAnimationEvents.erase(networkId); + layer.staticMovementUpdateEvents.erase(networkId); + layer.visibleEntities.erase(networkId); + layer.weaponEvents.erase(networkId); } template @@ -765,7 +767,7 @@ namespace bw assert(layerIndex < terrain.GetLayerCount()); TerrainLayer& terrainLayer = terrain.GetLayer(layerIndex); - NetworkSyncSystem& syncSystem = terrainLayer.GetWorld().GetSystem(); + NetworkSyncSystem& syncSystem = terrainLayer.GetNetworkSyncSystem(); auto layerIt = m_layers.find(layerIndex); assert(layerIt != m_layers.end()); @@ -866,7 +868,7 @@ namespace bw layer.staticMovementUpdateEvents.clear(); TerrainLayer& terrainLayer = terrain.GetLayer(layerIndex); - const NetworkSyncSystem& syncSystem = terrainLayer.GetWorld().GetSystem(); + const NetworkSyncSystem& syncSystem = terrainLayer.GetNetworkSyncSystem(); syncSystem.MoveEntities([&](const NetworkSyncSystem::EntityMovement* entitiesMovement, std::size_t entityCount) { diff --git a/src/CoreLib/MatchSessions.cpp b/src/CoreLib/MatchSessions.cpp index 9f5ae1ab..1db03756 100644 --- a/src/CoreLib/MatchSessions.cpp +++ b/src/CoreLib/MatchSessions.cpp @@ -10,17 +10,15 @@ namespace bw { MatchSessions::MatchSessions(Match& match) : - m_nextSessionId(0), m_match(match), m_commandStore(m_match.GetLogger()), - m_sessionPool(sizeof(MatchClientSession)) + m_sessionPool(1024) { } void MatchSessions::Clear() { m_sessionPool.Clear(); - m_sessionIdToSession.clear(); } void MatchSessions::Poll() @@ -31,23 +29,19 @@ namespace bw MatchClientSession* MatchSessions::CreateSession(std::shared_ptr bridge) { - std::size_t sessionId = m_nextSessionId++; - MatchClientSession* session = m_sessionPool.Allocate(m_match, sessionId, m_commandStore, std::move(bridge)); + std::size_t allocationIndex; + MatchClientSession* session = m_sessionPool.Allocate(allocationIndex, m_match, m_commandStore, std::move(bridge)); - m_sessionIdToSession.insert_or_assign(sessionId, session); - - bwLog(m_match.GetLogger(), LogLevel::Info, "Created session #{0}", sessionId); + bwLog(m_match.GetLogger(), LogLevel::Info, "Created session #{0}", allocationIndex); return session; } void MatchSessions::DeleteSession(MatchClientSession* session) { - std::size_t sessionId = session->GetSessionId(); - m_sessionIdToSession.erase(sessionId); - - m_sessionPool.Delete(session); + std::size_t allocationIndex = m_sessionPool.RetrieveEntryIndex(session); + m_sessionPool.Free(allocationIndex); - bwLog(m_match.GetLogger(), LogLevel::Info, "Deleted session #{0}", sessionId); + bwLog(m_match.GetLogger(), LogLevel::Info, "Deleted session #{0}", allocationIndex); } } diff --git a/src/CoreLib/Player.cpp b/src/CoreLib/Player.cpp index dfc4533b..0cd16321 100644 --- a/src/CoreLib/Player.cpp +++ b/src/CoreLib/Player.cpp @@ -124,7 +124,7 @@ namespace bw weaponEntity = world.CloneEntity(weaponEntity); weaponEntity->AddComponent(m_match, layerIndex, weaponUniqueId); - weaponEntity->GetComponent().SetParent(newPlayerEntity); + weaponentity.get().SetParent(newPlayerEntity); weaponEntity->GetComponent().UpdateParent(newPlayerEntity); weaponEntity->GetComponent().UpdateOwner(newPlayerEntity); @@ -170,23 +170,20 @@ namespace bw Nz::Bitset weaponIds; if (m_playerEntity) { - entt::registry& registry = m_playerEntity->GetRegistry(); - if (WeaponWielderComponent* weaponWielder = registry.try_get(m_playerEntity->GetEntity())) + entt::registry* registry = m_playerEntity->GetEntity().registry(); + if (WeaponWielderComponent* weaponWielder = registry->try_get(m_playerEntity->GetEntity())) { - for (entt::entity weapon : weaponWielder->GetWeapons()) + for (entt::handle weapon : weaponWielder->GetWeapons()) { - assert(registry.valid(weapon)); + assert(weapon.valid()); - weaponPacket.weaponEntities.emplace_back(Nz::UInt32(weapon->GetId())); - weaponIds.UnboundedSet(weapon->GetId()); + auto& weaponNetwork = weapon.get(); + + weaponPacket.weaponEntities.emplace_back(weaponNetwork.GetNetworkId()); + weaponIds.UnboundedSet(weaponNetwork.GetNetworkId()); } } } - // && m_playerEntity->HasComponent()) - { - auto& weaponWielder = m_playerEntity->GetComponent(); - - } m_session.GetVisibility().PushEntitiesPacket(m_layerIndex, std::move(weaponIds), std::move(weaponPacket)); @@ -204,21 +201,24 @@ namespace bw return "Player(" + m_name + ")"; } - void Player::UpdateControlledEntity(entt::entity entity, bool sendPacket, bool ignoreLayerUpdate) + void Player::UpdateControlledEntity(entt::handle entity, bool sendPacket, bool ignoreLayerUpdate) { MatchClientVisibility& visibility = m_session.GetVisibility(); if (m_playerEntity) { - m_playerEntity->RemoveComponent(); - m_playerEntity->RemoveComponent(); + EntityOwner& playerEntity = *m_playerEntity; + + playerEntity->remove(); + playerEntity->remove(); - auto& matchComponent = m_playerEntity->GetComponent(); - visibility.SetEntityControlledStatus(matchComponent.GetLayerIndex(), m_playerEntity->GetId(), false); + auto& matchComponent = playerEntity->get(); + auto& networkComponent = playerEntity->get(); + visibility.SetEntityControlledStatus(matchComponent.GetLayerIndex(), networkComponent.GetNetworkId(), false); } - m_playerEntity = entt::null; - m_onPlayerEntityDied.Disconnect(); + m_playerEntity.reset(); + m_onPlayerEntityDie.Disconnect(); m_onPlayerEntityDestruction.Disconnect(); m_onWeaponAdded.Disconnect(); m_onWeaponRemove.Disconnect(); @@ -226,7 +226,7 @@ namespace bw EntityId entityUniqueId = InvalidEntityId; if (entity) { - auto& matchComponent = entity->GetComponent(); + auto& matchComponent = entity.get(); if (!ignoreLayerUpdate) MoveToLayer(matchComponent.GetLayerIndex()); @@ -234,38 +234,36 @@ namespace bw m_playerEntity = entity; //< FIXME (deferred because of MoveToLayer) - if (m_playerEntity->HasComponent()) + if (WeaponWielderComponent* weaponWielder = entity.try_get()) { - auto& weaponWielder = m_playerEntity->GetComponent(); - auto onWeaponSetUpdate = [&](WeaponWielderComponent* /*wielder*/, const std::string& /*weaponClass*/, std::size_t /*weaponIndex*/) { m_shouldSendWeapons = true; }; - m_onWeaponAdded.Connect(weaponWielder.OnWeaponAdded, onWeaponSetUpdate); - m_onWeaponRemove.Connect(weaponWielder.OnWeaponRemove, onWeaponSetUpdate); + m_onWeaponAdded.Connect(weaponWielder->OnWeaponAdded, onWeaponSetUpdate); + m_onWeaponRemove.Connect(weaponWielder->OnWeaponRemove, onWeaponSetUpdate); } - m_playerEntity->AddComponent(CreateHandle()); - m_playerEntity->AddComponent(CreateHandle()); + entity.emplace(CreateHandle()); + entity.emplace(CreateHandle()); - if (m_playerEntity->HasComponent()) + if (HealthComponent* healthComponent = entity.try_get()) { - auto& healthComponent = m_playerEntity->GetComponent(); - - m_onPlayerEntityDied.Connect(healthComponent.OnDied, [this](const HealthComponent* /*health*/, entt::entity attacker) + m_onPlayerEntityDie.Connect(healthComponent->OnDie, [this](const HealthComponent* /*health*/, entt::handle attacker) { OnDeath(attacker); }); } - m_onPlayerEntityDestruction.Connect(m_playerEntity->OnEntityDestruction, [this](Ndk::Entity* /*entity*/) + auto& destructionWatcher = entity.get_or_emplace(entity); + m_onPlayerEntityDestruction.Connect(destructionWatcher.OnDestruction, [this](DestructionWatcherComponent* /*destructionWatcher*/) { - OnDeath(entt::null); + OnDeath({}); }); - visibility.SetEntityControlledStatus(matchComponent.GetLayerIndex(), m_playerEntity->GetId(), true); + auto& networkComponent = entity.get(); + visibility.SetEntityControlledStatus(matchComponent.GetLayerIndex(), networkComponent.GetNetworkId(), true); } if (sendPacket) @@ -274,10 +272,13 @@ namespace bw controlEntity.localIndex = m_localIndex; if (m_playerEntity) { - auto& matchComponent = m_playerEntity->GetComponent(); + EntityOwner& playerEntity = *m_playerEntity; + + auto& matchComponent = playerEntity->get(); + auto& networkComponent = playerEntity->get(); controlEntity.layerIndex = matchComponent.GetLayerIndex(); - controlEntity.entityId = static_cast(entity->GetId()); + controlEntity.entityId = networkComponent.GetNetworkId(); visibility.PushEntityPacket(matchComponent.GetLayerIndex(), controlEntity.entityId, controlEntity); } @@ -325,19 +326,23 @@ namespace bw m_match.BroadcastPacket(nameUpdatePacket); } - void Player::OnDeath(entt::entity attacker) + void Player::OnDeath(entt::handle attacker) { assert(m_playerEntity); - UpdateControlledEntity(entt::null, false); + UpdateControlledEntity(entt::handle{}, false); Packets::ChatMessage chatPacket; - if (attacker && attacker->HasComponent()) + if (attacker) { - auto& ownerComponent = attacker->GetComponent(); - Player* playerKiller = ownerComponent.GetOwner(); - if (playerKiller != this) - chatPacket.content = playerKiller->GetName() + " killed " + GetName(); + if (OwnerComponent* ownerComponent = attacker.try_get()) + { + Player* playerKiller = ownerComponent->GetOwner(); + if (playerKiller != this) + chatPacket.content = playerKiller->GetName() + " killed " + GetName(); + else + chatPacket.content = GetName() + " suicided"; + } else chatPacket.content = GetName() + " suicided"; } @@ -349,10 +354,12 @@ namespace bw otherPlayer->SendPacket(chatPacket); }); - if (attacker && attacker->HasComponent()) + if (attacker) { - auto& attackerScript = attacker->GetComponent(); - m_match.GetGamemode()->ExecuteCallback(CreateHandle(), attackerScript.GetTable()); + if (ScriptComponent* attackerScript = attacker.try_get()) + m_match.GetGamemode()->ExecuteCallback(CreateHandle(), attackerScript->GetTable()); + else + m_match.GetGamemode()->ExecuteCallback(CreateHandle(), sol::nil); } else m_match.GetGamemode()->ExecuteCallback(CreateHandle(), sol::nil); diff --git a/src/CoreLib/PlayerInputController.cpp b/src/CoreLib/PlayerInputController.cpp index 40c18665..1e2ea01f 100644 --- a/src/CoreLib/PlayerInputController.cpp +++ b/src/CoreLib/PlayerInputController.cpp @@ -10,7 +10,7 @@ namespace bw { std::optional PlayerInputController::GenerateInputs(entt::handle entity) const { - PlayerControlledComponent* playerControlled = registry.try_get(entity); + PlayerControlledComponent* playerControlled = entity.try_get(); if (!playerControlled) return std::nullopt; diff --git a/src/CoreLib/PropertyValues.cpp b/src/CoreLib/PropertyValues.cpp index 60f3bb9f..911d8177 100644 --- a/src/CoreLib/PropertyValues.cpp +++ b/src/CoreLib/PropertyValues.cpp @@ -45,7 +45,7 @@ namespace bw if (!match) throw std::runtime_error("This context only accepts InvalidEntityId constant"); - entt::entity entity = RetrieveScriptEntity(value); + entt::handle entity = RetrieveScriptEntity(value); return match->RetrieveUniqueIdByEntity(entity); } } @@ -92,12 +92,15 @@ namespace bw if (uniqueId == InvalidEntityId) return sol::make_object(lua, InvalidEntityId); - entt::entity entity = match->RetrieveEntityByUniqueId(uniqueId); - if (!entity || !entity->HasComponent()) + entt::handle entity = match->RetrieveEntityByUniqueId(uniqueId); + if (!entity) return sol::make_object(lua, InvalidEntityId); - auto& entityScript = entity->GetComponent(); - return sol::table(lua, entityScript.GetTable()); + ScriptComponent* entityScript = entity.try_get(); + if (!entityScript) + return sol::make_object(lua, InvalidEntityId); + + return sol::table(lua, entityScript->GetTable()); } }; diff --git a/src/CoreLib/Scripting/ScriptingUtils.cpp b/src/CoreLib/Scripting/ScriptingUtils.cpp index 9db75859..4db7e26a 100644 --- a/src/CoreLib/Scripting/ScriptingUtils.cpp +++ b/src/CoreLib/Scripting/ScriptingUtils.cpp @@ -19,7 +19,7 @@ namespace bw entt::handle AssertScriptEntity(const sol::table& entityTable) { entt::handle entity = RetrieveScriptEntity(entityTable); - if (entity == entt::null) + if (!entity) TriggerLuaError(entityTable.lua_state(), "invalid entity"); return entity; @@ -38,7 +38,7 @@ namespace bw { sol::object entityObject = entityTable["_Entity"]; if (!entityObject) - return entt::null; + return {}; return entityObject.as(); } diff --git a/src/CoreLib/Scripting/ServerElementLibrary.cpp b/src/CoreLib/Scripting/ServerElementLibrary.cpp index 46d8b3b6..f873ce71 100644 --- a/src/CoreLib/Scripting/ServerElementLibrary.cpp +++ b/src/CoreLib/Scripting/ServerElementLibrary.cpp @@ -13,11 +13,9 @@ #include #include #include -#include -#include -#include -#include -#include +#include +#include +#include #include namespace bw @@ -33,12 +31,10 @@ namespace bw { auto DealDamage = [](const sol::table& entityTable, const Nz::Vector2f& origin, Nz::UInt16 damage, Nz::Rectf damageZone, float pushbackForce = 0.f) { - entt::entity entity = AssertScriptEntity(entityTable); - Ndk::World* world = entity->GetWorld(); - assert(world); + entt::handle entity = AssertScriptEntity(entityTable); - Ndk::EntityList hitEntities; //< FIXME: RegionQuery hit multiples entities - world->GetSystem().RegionQuery(damageZone, 0, 0xFFFFFFFF, 0xFFFFFFFF, [&](entt::entity hitEntity) + /*Ndk::EntityList hitEntities; //< FIXME: RegionQuery hit multiples entities + world->GetSystem().RegionQuery(damageZone, 0, 0xFFFFFFFF, 0xFFFFFFFF, [&](entt::handle hitEntity) { if (hitEntities.Has(hitEntity)) return; @@ -53,7 +49,9 @@ namespace bw Ndk::PhysicsComponent2D& hitEntityPhys = hitEntity->GetComponent(); hitEntityPhys.AddImpulse(Nz::Vector2f::Normalize(hitEntityPhys.GetMassCenter(Nz::CoordSys::Global) - origin) * pushbackForce); } - }); + });*/ + + // Entt FIXME }; elementTable["DealDamage"] = sol::overload( @@ -62,32 +60,32 @@ namespace bw elementTable["DumpCreationInfo"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) -> sol::object { - entt::entity entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent() || !entity->HasComponent() || !entity->HasComponent()) - return sol::nil; + entt::handle entity = AssertScriptEntity(entityTable); - auto& entityNode = entity->GetComponent(); - auto& entityMatch = entity->GetComponent(); - auto& entityScript = entity->GetComponent(); + Nz::NodeComponent* entityNode = entity.try_get(); + MatchComponent* entityMatch = entity.try_get(); + ScriptComponent* entityScript = entity.try_get(); + if (!entityScript || !entityMatch || !entityNode) + return sol::nil; - Match& match = entityMatch.GetMatch(); - const auto& element = entityScript.GetElement(); + Match& match = entityMatch->GetMatch(); + const auto& element = entityScript->GetElement(); sol::state_view state(L); sol::table resultTable = state.create_table(6, 0); resultTable["Type"] = element->fullName; - resultTable["LayerIndex"] = entityMatch.GetLayerIndex(); - resultTable["Position"] = Nz::Vector2f(entityNode.GetPosition()); - resultTable["Rotation"] = AngleFromQuaternion(entityNode.GetRotation()); + resultTable["LayerIndex"] = entityMatch->GetLayerIndex(); + resultTable["Position"] = Nz::Vector2f(entityNode->GetPosition()); + resultTable["Rotation"] = AngleFromQuaternion(entityNode->GetRotation()); - if (entity->HasComponent()) + if (OwnerComponent* entityOwner = entity.try_get()) { - if (Player* owner = entity->GetComponent().GetOwner()) + if (Player* owner = entityOwner->GetOwner()) resultTable["Owner"] = owner->CreateHandle(); } - const auto& entityProperties = entityScript.GetProperties(); + const auto& entityProperties = entityScript->GetProperties(); if (!entityProperties.empty()) { sol::table propertyTable = state.create_table(int(entityProperties.size()), 0); @@ -103,16 +101,16 @@ namespace bw elementTable["GetLayerIndex"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); - return entity->GetComponent().GetLayerIndex(); + return entity.get().GetLayerIndex(); }); elementTable["GetProperty"] = LuaFunction([](sol::this_state s, const sol::table& table, const std::string& propertyName) -> sol::object { - entt::entity entity = AssertScriptEntity(table); + entt::handle entity = AssertScriptEntity(table); - auto& entityScript = entity->GetComponent(); + auto& entityScript = entity.get(); auto propertyVal = entityScript.GetProperty(propertyName); if (propertyVal.has_value()) @@ -121,8 +119,8 @@ namespace bw const PropertyValue& property = propertyVal.value(); Match* match; - if (entity->HasComponent()) - match = &entity->GetComponent().GetMatch(); + if (MatchComponent* entityMatch = entity.try_get()) + match = &entityMatch->GetMatch(); else match = nullptr; @@ -134,55 +132,52 @@ namespace bw elementTable["GetOwner"] = LuaFunction([](sol::this_state s, const sol::table& table) -> sol::object { - entt::entity entity = AssertScriptEntity(table); + entt::handle entity = AssertScriptEntity(table); - if (!entity->HasComponent()) + OwnerComponent* entityOwner = entity.try_get(); + if (!entityOwner) return sol::nil; - return sol::make_object(s, entity->GetComponent().GetOwner()->CreateHandle()); + return sol::make_object(s, entityOwner->GetOwner()->CreateHandle()); }); elementTable["SetParent"] = LuaFunction([](const sol::table& entityTable, const sol::table& parentTable) { - entt::entity entity = AssertScriptEntity(entityTable); - entt::entity parent = AssertScriptEntity(parentTable); + entt::handle entity = AssertScriptEntity(entityTable); + entt::handle parent = AssertScriptEntity(parentTable); - entity->GetComponent().SetParent(parent, true); - if (entity->HasComponent()) - entity->GetComponent().UpdateParent(parent); + entity.get().SetParent(parent, true); + if (NetworkSyncComponent* syncComponent = entity.try_get()) + syncComponent->UpdateParent(parent); }); } - void ServerElementLibrary::SetScale(entt::entity entity, float newScale) + void ServerElementLibrary::SetScale(entt::handle entity, float newScale) { - if (entity->HasComponent()) - { - auto& scriptComponent = entity->GetComponent(); - scriptComponent.ExecuteCallback(newScale); - } + if (ScriptComponent* scriptComponent = entity.try_get()) + scriptComponent->ExecuteCallback(newScale); - auto& node = entity->GetComponent(); + auto& node = entity.get(); Nz::Vector2f scale = Nz::Vector2f(node.GetScale()); scale.x = std::copysign(newScale, scale.x); scale.y = std::copysign(newScale, scale.y); - node.SetScale(scale, Nz::CoordSys_Local); + node.SetScale(scale, Nz::CoordSys::Local); - if (entity->HasComponent()) + if (CollisionDataComponent* entityCollData = entity.try_get()) { - auto& entityCollData = entity->GetComponent(); - auto& entityCollider = entity->GetComponent(); + auto& entityCollider = entity.get(); - entityCollider.SetGeom(entityCollData.BuildCollider(newScale), false, false); + entityCollider.SetGeom(entityCollData->BuildCollider(newScale), false, false); } - Ndk::World* world = entity->GetWorld(); - world->GetSystem().NotifyScaleUpdate(entity); + // entt FIXME + //entt::registry* world = entity->GetWorld(); + //world->GetSystem().NotifyScaleUpdate(entity); - if (entity->HasComponent()) + if (WeaponWielderComponent* wielderComponent = entity.try_get()) { - auto& wielderComponent = entity->GetComponent(); - for (entt::entity weapon : wielderComponent.GetWeapons()) + for (entt::handle weapon : wielderComponent->GetWeapons()) SetScale(weapon, newScale); } } diff --git a/src/CoreLib/Scripting/ServerEntityLibrary.cpp b/src/CoreLib/Scripting/ServerEntityLibrary.cpp index 93d58540..1f1c7a53 100644 --- a/src/CoreLib/Scripting/ServerEntityLibrary.cpp +++ b/src/CoreLib/Scripting/ServerEntityLibrary.cpp @@ -25,7 +25,7 @@ namespace bw entityMetatable["GetWeaponCount"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) -> std::size_t { entt::handle entity = AssertScriptEntity(entityTable); - WeaponWielderComponent* weaponWielder = entity.TryGetComponent(); + WeaponWielderComponent* weaponWielder = entity.try_get(); if (!weaponWielder) TriggerLuaArgError(L, 1, "entity is not a weapon wielder"); @@ -35,13 +35,13 @@ namespace bw entityMetatable["GiveWeapon"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, std::string weaponClass) -> bool { entt::handle entity = AssertScriptEntity(entityTable); - WeaponWielderComponent* weaponWielder = entity.TryGetComponent(); + WeaponWielderComponent* weaponWielder = entity.try_get(); if (!weaponWielder) TriggerLuaArgError(L, 1, "entity is not a weapon wielder"); - auto& entityMatch = entity.GetComponent(); + auto& entityMatch = entity.get(); - std::size_t weaponIndex = weaponWielder->GiveWeapon(weaponClass, [&] (const std::string& weaponClass) -> entt::entity + std::size_t weaponIndex = weaponWielder->GiveWeapon(weaponClass, [&] (const std::string& weaponClass) -> entt::handle { Match& match = entityMatch.GetMatch(); Terrain& terrain = match.GetTerrain(); @@ -53,16 +53,16 @@ namespace bw // Create weapon std::size_t weaponEntityIndex = weaponStore.GetElementIndex(weaponClass); if (weaponEntityIndex == ServerEntityStore::InvalidIndex) - return entt::null; + return entt::handle{}; EntityId uniqueId = match.AllocateUniqueId(); - entt::handle weapon = weaponStore.InstantiateWeapon(terrainLayer, weaponEntityIndex, uniqueId, {}, entity.GetEntity()); - if (weapon == entt::null) - return entt::null; + entt::handle weapon = weaponStore.InstantiateWeapon(terrainLayer, weaponEntityIndex, uniqueId, {}, entity); + if (!weapon) + return entt::handle{}; match.RegisterEntity(uniqueId, entt::handle(registry, weapon)); - if (OwnerComponent* ownerComponent = entity.TryGetComponent()) + if (OwnerComponent* ownerComponent = entity.try_get()) { if (Player* owner = ownerComponent->GetOwner()) registry.emplace(weapon, owner->CreateHandle()); @@ -76,88 +76,98 @@ namespace bw entityMetatable["HasWeapon"] = LuaFunction([](sol::this_state L, const sol::table& entityTable, const std::string& weaponClass) -> bool { - entt::entity entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + entt::handle entity = AssertScriptEntity(entityTable); + + WeaponWielderComponent* weaponWielder = entity.try_get(); + if (!weaponWielder) TriggerLuaArgError(L, 1, "entity is not a weapon wielder"); - auto& weaponWielder = entity->GetComponent(); - return weaponWielder.HasWeapon(weaponClass); + return weaponWielder->HasWeapon(weaponClass); }); entityMetatable["RemoveWeapon"] = LuaFunction([](sol::this_state L, const sol::table& entityTable, const std::string& weaponClass) { - entt::entity entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + entt::handle entity = AssertScriptEntity(entityTable); + + WeaponWielderComponent* weaponWielder = entity.try_get(); + if (!weaponWielder) TriggerLuaArgError(L, 1, "entity is not a weapon wielder"); - auto& weaponWielder = entity->GetComponent(); - weaponWielder.RemoveWeapon(weaponClass); + weaponWielder->RemoveWeapon(weaponClass); }); entityMetatable["SelectWeapon"] = LuaFunction([](sol::this_state L, const sol::table& entityTable, const std::string& weaponClass) -> bool { - entt::entity entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + entt::handle entity = AssertScriptEntity(entityTable); + + WeaponWielderComponent* weaponWielder = entity.try_get(); + if (!weaponWielder) TriggerLuaArgError(L, 1, "entity is not a weapon wielder"); - auto& weaponWielder = entity->GetComponent(); - return weaponWielder.SelectWeapon(weaponClass); + return weaponWielder->SelectWeapon(weaponClass); }); } - void ServerEntityLibrary::SetDirection(lua_State* L, entt::entity entity, const Nz::Vector2f& upVector) + void ServerEntityLibrary::SetDirection(lua_State* L, entt::handle entity, const Nz::Vector2f& upVector) { SharedEntityLibrary::SetDirection(L, entity, upVector); - Ndk::World* world = entity->GetWorld(); - world->GetSystem().NotifyMovementUpdate(entity); + // EnTT FIXME + //entt::registry* world = entity->GetWorld(); + //world->GetSystem().NotifyMovementUpdate(entity); } - void ServerEntityLibrary::SetMass(lua_State* L, entt::entity entity, float mass, bool recomputeMomentOfInertia) + void ServerEntityLibrary::SetMass(lua_State* L, entt::handle entity, float mass, bool recomputeMomentOfInertia) { SharedEntityLibrary::SetMass(L, entity, mass, recomputeMomentOfInertia); - Ndk::World* world = entity->GetWorld(); - world->GetSystem().NotifyPhysicsUpdate(entity); + // EnTT FIXME + //entt::registry* world = entity->GetWorld(); + //world->GetSystem().NotifyPhysicsUpdate(entity); } - void ServerEntityLibrary::SetMomentOfInertia(lua_State* L, entt::entity entity, float momentOfInertia) + void ServerEntityLibrary::SetMomentOfInertia(lua_State* L, entt::handle entity, float momentOfInertia) { SharedEntityLibrary::SetMomentOfInertia(L, entity, momentOfInertia); - Ndk::World* world = entity->GetWorld(); - world->GetSystem().NotifyPhysicsUpdate(entity); + // EnTT FIXME + //entt::registry* world = entity->GetWorld(); + //world->GetSystem().NotifyPhysicsUpdate(entity); } - void ServerEntityLibrary::SetPosition(lua_State* L, entt::entity entity, const Nz::Vector2f& position) + void ServerEntityLibrary::SetPosition(lua_State* L, entt::handle entity, const Nz::Vector2f& position) { SharedEntityLibrary::SetPosition(L, entity, position); - Ndk::World* world = entity->GetWorld(); - world->GetSystem().NotifyMovementUpdate(entity); + // EnTT FIXME + //entt::registry* world = entity->GetWorld(); + //world->GetSystem().NotifyMovementUpdate(entity); } - void ServerEntityLibrary::SetRotation(lua_State* L, entt::entity entity, const Nz::DegreeAnglef& rotation) + void ServerEntityLibrary::SetRotation(lua_State* L, entt::handle entity, const Nz::DegreeAnglef& rotation) { SharedEntityLibrary::SetRotation(L, entity, rotation); - Ndk::World* world = entity->GetWorld(); - world->GetSystem().NotifyMovementUpdate(entity); + // EnTT FIXME + //entt::registry* world = entity->GetWorld(); + //world->GetSystem().NotifyMovementUpdate(entity); } - void ServerEntityLibrary::UpdatePlayerJumpHeight(lua_State* L, entt::entity entity, float jumpHeight, float jumpHeightBoost) + void ServerEntityLibrary::UpdatePlayerJumpHeight(lua_State* L, entt::handle entity, float jumpHeight, float jumpHeightBoost) { SharedEntityLibrary::UpdatePlayerJumpHeight(L, entity, jumpHeight, jumpHeightBoost); - Ndk::World* world = entity->GetWorld(); - world->GetSystem().NotifyPhysicsUpdate(entity); + // EnTT FIXME + //entt::registry* world = entity->GetWorld(); + //world->GetSystem().NotifyPhysicsUpdate(entity); } - void ServerEntityLibrary::UpdatePlayerMovement(lua_State* L, entt::entity entity, float movementSpeed) + void ServerEntityLibrary::UpdatePlayerMovement(lua_State* L, entt::handle entity, float movementSpeed) { SharedEntityLibrary::UpdatePlayerMovement(L, entity, movementSpeed); - Ndk::World* world = entity->GetWorld(); - world->GetSystem().NotifyPhysicsUpdate(entity); + // EnTT FIXME + //entt::registry* world = entity->GetWorld(); + //world->GetSystem().NotifyPhysicsUpdate(entity); } } diff --git a/src/CoreLib/Scripting/ServerEntityStore.cpp b/src/CoreLib/Scripting/ServerEntityStore.cpp index 25893504..003f2039 100644 --- a/src/CoreLib/Scripting/ServerEntityStore.cpp +++ b/src/CoreLib/Scripting/ServerEntityStore.cpp @@ -20,7 +20,7 @@ namespace bw { - entt::entity ServerEntityStore::CreateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, entt::entity parent) const + entt::handle ServerEntityStore::CreateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, entt::handle parent) const { const auto& entityClass = GetElement(entityIndex); @@ -29,68 +29,65 @@ namespace bw entt::registry& registry = layer.GetWorld(); - entt::entity entity = SharedEntityStore::CreateEntity(layer.GetWorld(), entityClass, properties); - registry.emplace(entity, layer.GetMatch(), layer.GetLayerIndex(), uniqueId); + entt::handle entity = SharedEntityStore::CreateEntity(layer.GetWorld(), entityClass, properties); + entity.emplace(layer.GetMatch(), layer.GetLayerIndex(), uniqueId); auto& node = registry.emplace(entity); node.SetPosition(position); node.SetRotation(rotation); - if (parent != entt::null) - node.SetParent(registry, parent); + if (parent) + node.SetParent(parent); if (entityClass->maxHealth > 0) { - auto& healthComponent = registry.emplace(entity, registry, entity, entityClass->maxHealth); - healthComponent.OnDamage.Connect([](HealthComponent* health, Nz::UInt16& damageValue, entt::entity source) + auto& healthComponent = entity.emplace(entity, entityClass->maxHealth); + healthComponent.OnDamage.Connect([](HealthComponent* health, Nz::UInt16& damageValue, entt::handle source) { - entt::registry& registry = health->GetRegistry(); - auto& entityScript = registry.get(health->GetEntity()); + auto& entityScript = health->GetHandle().get(); - if (auto ret = entityScript.ExecuteCallback(damageValue, TranslateEntityToLua(registry, source)); ret.has_value()) + if (auto ret = entityScript.ExecuteCallback(damageValue, TranslateEntityToLua(source)); ret.has_value()) damageValue = *ret; }); - healthComponent.OnHealthChange.Connect([](HealthComponent* health, Nz::UInt16 newHealth, entt::entity source) + healthComponent.OnHealthChange.Connect([](HealthComponent* health, Nz::UInt16 newHealth, entt::handle source) { - entt::registry& registry = health->GetRegistry(); - auto& entityScript = registry.get(health->GetEntity()); + auto& entityScript = health->GetHandle().get(); - entityScript.ExecuteCallback(newHealth, TranslateEntityToLua(registry, source)); + entityScript.ExecuteCallback(newHealth, TranslateEntityToLua(source)); }); - healthComponent.OnDying.Connect([&](HealthComponent* health, entt::entity attacker) + healthComponent.OnDying.Connect([&](HealthComponent* health, entt::handle attacker) { - entt::registry& registry = health->GetRegistry(); - auto& entityScript = registry.get(health->GetEntity()); + auto& entityScript = health->GetHandle().get(); - entityScript.ExecuteCallback(TranslateEntityToLua(registry, attacker)); + entityScript.ExecuteCallback(TranslateEntityToLua(attacker)); }); - healthComponent.OnDie.Connect([&](const HealthComponent* health, entt::entity attacker) + healthComponent.OnDie.Connect([&](const HealthComponent* health, entt::handle attacker) { - entt::registry& registry = health->GetRegistry(); - auto& entityScript = registry.get(health->GetEntity()); + auto& entityScript = health->GetHandle().get(); - entityScript.ExecuteCallback(TranslateEntityToLua(registry, attacker)); + entityScript.ExecuteCallback(TranslateEntityToLua(attacker)); }); } if (entityClass->isNetworked) { // Not quite sure about this, maybe parent handling should be automatic? + NetworkSyncSystem& networkSyncSystem = layer.GetNetworkSyncSystem(); - if (parent != entt::null && registry.try_get(parent)) - registry.emplace(entity, entityClass->fullName, parent); + if (parent && parent.try_get()) + entity.emplace(networkSyncSystem, entityClass->fullName, parent); else - registry.emplace(entity, entityClass->fullName); + entity.emplace(networkSyncSystem, entityClass->fullName); } if (playerControlled) - registry.emplace(entity); + entity.emplace(); if (hasInputs) - registry.emplace(entity, std::make_shared()); + entity.emplace(entity, std::make_shared()); bwLog(GetLogger(), LogLevel::Debug, "Created entity {} on layer {} of type {}", uniqueId, layer.GetLayerIndex(), GetElement(entityIndex)->fullName); @@ -99,22 +96,22 @@ namespace bw bool ServerEntityStore::InitializeEntity(entt::handle entity) const { - const auto& entityScript = registry.get(entity); + const auto& entityScript = entity.get(); return SharedEntityStore::InitializeEntity(static_cast(*entityScript.GetElement()), entity); } - entt::entity ServerEntityStore::InstantiateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, entt::entity parent) const + entt::handle ServerEntityStore::InstantiateEntity(TerrainLayer& layer, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const PropertyValueMap& properties, entt::handle parent) const { entt::registry& registry = layer.GetWorld(); - entt::entity entity = CreateEntity(layer, entityIndex, uniqueId, position, rotation, properties, parent); - if (entity != entt::null) - return entt::null; + entt::handle entity = CreateEntity(layer, entityIndex, uniqueId, position, rotation, properties, parent); + if (entity) + return entt::handle{}; if (!InitializeEntity(entity)) { registry.destroy(entity); - return entt::null; + return entt::handle{}; } return entity; diff --git a/src/CoreLib/Scripting/ServerGamemode.cpp b/src/CoreLib/Scripting/ServerGamemode.cpp index 9558505c..1f6825cc 100644 --- a/src/CoreLib/Scripting/ServerGamemode.cpp +++ b/src/CoreLib/Scripting/ServerGamemode.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #include #include diff --git a/src/CoreLib/Scripting/ServerScriptingLibrary.cpp b/src/CoreLib/Scripting/ServerScriptingLibrary.cpp index 4ab8f61f..956b215e 100644 --- a/src/CoreLib/Scripting/ServerScriptingLibrary.cpp +++ b/src/CoreLib/Scripting/ServerScriptingLibrary.cpp @@ -187,7 +187,7 @@ namespace bw Nz::DegreeAnglef rotation = parameters.get_or("Rotation", Nz::DegreeAnglef::Zero()); Nz::Vector2f position = parameters.get_or("Position", Nz::Vector2f::Zero()); - Ndk::EntityHandle lifeOwner; + entt::handle lifeOwner; if (std::optional lifeOwnerEntitytable = parameters.get_or>("LifeOwner", std::nullopt); lifeOwnerEntitytable) lifeOwner = AssertScriptEntity(*lifeOwnerEntitytable); @@ -205,30 +205,25 @@ namespace bw } } - Ndk::EntityHandle parentEntity; + entt::handle parentEntity; if (std::optional propertyTableOpt = parameters.get_or>("Parent", std::nullopt); propertyTableOpt) parentEntity = AssertScriptEntity(propertyTableOpt.value()); EntityId uniqueId = match.AllocateUniqueId(); - entt::entity entity = entityStore.InstantiateEntity(match.GetLayer(layerIndex), elementIndex, uniqueId, position, rotation, entityProperties, parentEntity); + entt::handle entity = entityStore.InstantiateEntity(match.GetLayer(layerIndex), elementIndex, uniqueId, position, rotation, entityProperties, parentEntity); if (!entity) TriggerLuaError(L, "failed to create \"" + entityType + "\""); if (owner) - entity->AddComponent(std::move(owner)); + entity.emplace(std::move(owner)); match.RegisterEntity(uniqueId, entity); if (lifeOwner) - { - if (!lifeOwner->HasComponent()) - lifeOwner->AddComponent(); - - lifeOwner->GetComponent().Register(entity); - } + lifeOwner.get_or_emplace(lifeOwner).Register(entity); - auto& scriptComponent = entity->GetComponent(); + auto& scriptComponent = entity.get(); return scriptComponent.GetTable(); }); @@ -261,8 +256,8 @@ namespace bw } } - Ndk::EntityHandle owner = AssertScriptEntity(parameters["Owner"]); - auto& ownerMatchComponent = owner->GetComponent(); + entt::handle owner = AssertScriptEntity(parameters["Owner"]); + auto& ownerMatchComponent = owner.get(); LayerIndex layerIndex = ownerMatchComponent.GetLayerIndex(); auto& layer = match.GetTerrain().GetLayer(layerIndex); @@ -270,21 +265,21 @@ namespace bw // Create weapon EntityId uniqueId = match.AllocateUniqueId(); - entt::entity weapon = weaponStore.InstantiateWeapon(layer, elementIndex, uniqueId, std::move(entityProperties), owner); + entt::handle weapon = weaponStore.InstantiateWeapon(layer, elementIndex, uniqueId, std::move(entityProperties), owner); if (!weapon) TriggerLuaError(L, "failed to create \"" + entityType + "\""); - weapon->GetComponent().SetActive(true); + weapon.get().SetActive(true); match.RegisterEntity(uniqueId, weapon); - if (owner->HasComponent()) + if (OwnerComponent* ownerComponent = owner.try_get()) { - if (Player* ownerPlayer = owner->GetComponent().GetOwner()) - weapon->AddComponent(ownerPlayer->CreateHandle()); + if (Player* ownerPlayer = ownerComponent->GetOwner()) + weapon.emplace(ownerPlayer->CreateHandle()); } - auto& scriptComponent = weapon->GetComponent(); + auto& scriptComponent = weapon.get(); return scriptComponent.GetTable(); }); @@ -351,11 +346,11 @@ namespace bw "new", sol::no_constructor, "GetControlledEntity", LuaFunction([](const Player& player) -> sol::object { - entt::entity controlledEntity = player.GetControlledEntity(); + entt::handle controlledEntity = player.GetControlledEntity(); if (!controlledEntity) return sol::nil; - auto& scriptComponent = controlledEntity->GetComponent(); + auto& scriptComponent = controlledEntity.get(); return scriptComponent.GetTable(); }), "GetLayerIndex", LuaFunction(&Player::GetLayerIndex), @@ -381,12 +376,12 @@ namespace bw { if (entityTable) { - entt::entity entity = AssertScriptEntity(entityTable.value()); + entt::handle entity = AssertScriptEntity(entityTable.value()); player.UpdateControlledEntity(entity); } else - player.UpdateControlledEntity(entt::null); + player.UpdateControlledEntity(entt::handle{}); }), "UpdateLayerVisibility", LuaFunction(&Player::UpdateLayerVisibility) ); diff --git a/src/CoreLib/Scripting/ServerWeaponLibrary.cpp b/src/CoreLib/Scripting/ServerWeaponLibrary.cpp index f94fb06c..4483b4ae 100644 --- a/src/CoreLib/Scripting/ServerWeaponLibrary.cpp +++ b/src/CoreLib/Scripting/ServerWeaponLibrary.cpp @@ -8,9 +8,6 @@ #include #include #include -#include -#include -#include #include namespace bw @@ -26,32 +23,35 @@ namespace bw { elementMetatable["IsPlayingAnimation"] = LuaFunction([](const sol::table& weaponTable) { - entt::entity entity = AssertScriptEntity(weaponTable); - if (!entity->HasComponent()) + entt::handle entity = AssertScriptEntity(weaponTable); + + AnimationComponent* entityAnimation = entity.try_get(); + if (!entityAnimation) return false; - return entity->GetComponent().IsPlaying(); + return entityAnimation->IsPlaying(); }); elementMetatable["PlayAnim"] = LuaFunction([&](const sol::table& weaponTable, const std::string& animationName) { - entt::entity entity = AssertScriptEntity(weaponTable); - if (!entity->HasComponent()) + entt::handle entity = AssertScriptEntity(weaponTable); + + AnimationComponent* entityAnimation = entity.try_get(); + if (!entityAnimation) throw std::runtime_error("Entity has no animations"); - auto& entityAnimation = entity->GetComponent(); - const auto& animationStore = entityAnimation.GetAnimationStore(); + const auto& animationStore = entityAnimation->GetAnimationStore(); if (std::size_t animId = animationStore->FindAnimationByName(animationName); animId != animationStore->InvalidId) - entityAnimation.Play(animId, m_match.GetCurrentTime()); + entityAnimation->Play(animId, m_match.GetCurrentTime()); else throw std::runtime_error("Entity has no animation \"" + animationName + "\""); }); auto shootFunc = [](const sol::table& weaponTable, Nz::Vector2f startPos, Nz::Vector2f direction, Nz::UInt16 damage, float pushbackForce = 0.f) { - entt::entity entity = AssertScriptEntity(weaponTable); - Ndk::World* world = entity->GetWorld(); + entt::handle entity = AssertScriptEntity(weaponTable); + /*entt::registry* world = entity->GetWorld(); assert(world); auto& physSystem = world->GetSystem(); @@ -70,7 +70,7 @@ namespace bw Ndk::PhysicsComponent2D& hitEntityPhys = hitEntity->GetComponent(); hitEntityPhys.AddImpulse(Nz::Vector2f::Normalize(hitInfo.hitPos - startPos) * pushbackForce); } - } + }*/ }; elementMetatable["Shoot"] = sol::overload( diff --git a/src/CoreLib/Scripting/ServerWeaponStore.cpp b/src/CoreLib/Scripting/ServerWeaponStore.cpp index c04f9c62..b7dd2ee1 100644 --- a/src/CoreLib/Scripting/ServerWeaponStore.cpp +++ b/src/CoreLib/Scripting/ServerWeaponStore.cpp @@ -13,19 +13,18 @@ #include #include #include -#include -#include -#include namespace bw { - entt::handle ServerWeaponStore::InstantiateWeapon(TerrainLayer& layer, std::size_t weaponIndex, EntityId uniqueId, const PropertyValueMap& properties, entt::entity parent) + entt::handle ServerWeaponStore::InstantiateWeapon(TerrainLayer& layer, std::size_t weaponIndex, EntityId uniqueId, const PropertyValueMap& properties, entt::handle parent) { const auto& weaponClass = GetElement(weaponIndex); + auto& networkSyncSystem = layer.GetNetworkSyncSystem(); + entt::handle weapon = CreateEntity(layer.GetWorld(), weaponClass, properties); - weapon->AddComponent(layer.GetMatch(), layer.GetLayerIndex(), uniqueId); - weapon->AddComponent(weaponClass->fullName, parent); + weapon.emplace(layer.GetMatch(), layer.GetLayerIndex(), uniqueId); + weapon.emplace(networkSyncSystem, weaponClass->fullName, parent); SharedWeaponStore::InitializeWeapon(*weaponClass, weapon, parent); diff --git a/src/CoreLib/Scripting/SharedElementLibrary.cpp b/src/CoreLib/Scripting/SharedElementLibrary.cpp index 3226ebf3..25930895 100644 --- a/src/CoreLib/Scripting/SharedElementLibrary.cpp +++ b/src/CoreLib/Scripting/SharedElementLibrary.cpp @@ -9,8 +9,8 @@ #include #include #include -#include -#include +//#include +#include #include namespace bw @@ -26,27 +26,24 @@ namespace bw { elementMetatable["DeleteOnRemove"] = LuaFunction([](const sol::table& entityTable, const sol::table& targetEntityTable) { - entt::entity entity = AssertScriptEntity(entityTable); - entt::entity targetEntity = AssertScriptEntity(targetEntityTable); + entt::handle entity = AssertScriptEntity(entityTable); + entt::handle targetEntity = AssertScriptEntity(targetEntityTable); - if (!entity->HasComponent()) - entity->AddComponent(); - - entity->GetComponent().Register(targetEntity); + entity.get_or_emplace(entity).Register(targetEntity); }); elementMetatable["Disable"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); - entity->Disable(); + entt::handle entity = AssertScriptEntity(entityTable); + //entity->Disable(); + //TODO }); elementMetatable["Disconnect"] = LuaFunction([&](const sol::table& entityTable, const ElementEventConnection& eventConnection) { - entt::entity entity = AssertScriptEntity(entityTable); - entity->Invalidate(); + entt::handle entity = AssertScriptEntity(entityTable); - auto& entityScript = entity->GetComponent(); + auto& entityScript = entity.get(); return std::visit([&](auto&& arg) { using T = std::decay_t; @@ -62,15 +59,16 @@ namespace bw elementMetatable["Enable"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); - entity->Enable(); + entt::handle entity = AssertScriptEntity(entityTable); + //entity->Enable(); + //TODO }); elementMetatable["GetDirection"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); - auto& nodeComponent = entity->GetComponent(); + auto& nodeComponent = entity.get(); Nz::Vector2f direction(nodeComponent.GetRotation(Nz::CoordSys::Global) * Nz::Vector2f::UnitX()); if (nodeComponent.GetScale().x < 0.f) @@ -81,59 +79,58 @@ namespace bw elementMetatable["GetPosition"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); - auto& nodeComponent = entity->GetComponent(); + auto& nodeComponent = entity.get(); return Nz::Vector2f(nodeComponent.GetPosition(Nz::CoordSys::Global)); }); elementMetatable["GetRotation"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); - auto& nodeComponent = entity->GetComponent(); + auto& nodeComponent = entity.get(); return Nz::DegreeAnglef(AngleFromQuaternion(nodeComponent.GetRotation(Nz::CoordSys::Global))); //GetComponent(); + auto& nodeComponent = entity.get(); Nz::Vector2f scale = Nz::Vector2f(nodeComponent.GetScale(Nz::CoordSys::Global)); return std::abs(scale.y); }); elementMetatable["IsEnabled"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); - return entity->IsEnabled(); + entt::handle entity = AssertScriptEntity(entityTable); + //return entity->IsEnabled(); }); elementMetatable["IsLookingRight"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); - auto& nodeComponent = entity->GetComponent(); + auto& nodeComponent = entity.get(); return nodeComponent.GetScale().x > 0.f; }); elementMetatable["IsValid"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = RetrieveScriptEntity(entityTable); - return entity.IsValid(); + entt::handle entity = RetrieveScriptEntity(entityTable); + return entity.valid(); }); elementMetatable["Kill"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); - if (entity->HasComponent()) - { - auto& entityHealth = entity->GetComponent(); - entityHealth.Damage(entityHealth.GetHealth(), entity); - } + entt::handle entity = AssertScriptEntity(entityTable); + + HealthComponent* entityHealth = entity.try_get(); + if (entityHealth) + entityHealth->Damage(entityHealth->GetHealth(), entity); else - entity->Kill(); + entity.destroy(); }); elementMetatable["On"] = LuaFunction([&](sol::this_state L, const sol::table& entityTable, const std::string_view& event, sol::main_protected_function callback) @@ -148,37 +145,38 @@ namespace bw elementMetatable["SetLifeTime"] = LuaFunction([](const sol::table& entityTable, float lifetime) { - entt::entity entity = AssertScriptEntity(entityTable); - entity->AddComponent(lifetime); + entt::handle entity = AssertScriptEntity(entityTable); + + //entity->AddComponent(lifetime); }); elementMetatable["SetScale"] = LuaFunction([&](const sol::table& entityTable, float scale) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); SetScale(entity, scale); }); elementMetatable["ToLocalPosition"] = LuaFunction([](const sol::table& entityTable, const Nz::Vector2f& globalPosition) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); - auto& nodeComponent = entity->GetComponent(); + auto& nodeComponent = entity.get(); return Nz::Vector2f(nodeComponent.ToLocalPosition(globalPosition)); }); elementMetatable["ToGlobalPosition"] = LuaFunction([](const sol::table& entityTable, const Nz::Vector2f& localPosition) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); - auto& nodeComponent = entity->GetComponent(); + auto& nodeComponent = entity.get(); return Nz::Vector2f(nodeComponent.ToGlobalPosition(localPosition)); }); elementMetatable["Trigger"] = LuaFunction([](const sol::table& entityTable, const std::string_view& event, sol::variadic_args parameters) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); - auto& entityScript = entity->GetComponent(); + auto& entityScript = entity.get(); const auto& element = entityScript.GetElement(); std::string eventName = std::string(event); @@ -210,9 +208,9 @@ namespace bw return eventData.index; }; - if (entt::entity entity = RetrieveScriptEntity(entityTable)) + if (entt::handle entity = RetrieveScriptEntity(entityTable)) { - auto& entityScript = entity->GetComponent(); + auto& entityScript = entity.get(); std::size_t eventIndex = RetrieveEventIndex(entityScript.GetElement()); std::size_t callbackId = entityScript.RegisterCallbackCustom(eventIndex, std::move(callback), async); @@ -248,13 +246,11 @@ namespace bw if (async && HasReturnValue(scriptingEvent)) TriggerLuaArgError(L, 2, "events returning a value cannot be async"); - if (entt::entity entity = RetrieveScriptEntity(entityTable)) + if (entt::handle entity = RetrieveScriptEntity(entityTable)) { - auto& entityScript = entity->GetComponent(); + auto& entityScript = entity.get(); std::size_t callbackId = entityScript.RegisterCallback(scriptingEvent, std::move(callback), async); - entity->Invalidate(); - return ElementEventConnection{ scriptingEvent, callbackId }; } else diff --git a/src/CoreLib/Scripting/SharedEntityLibrary.cpp b/src/CoreLib/Scripting/SharedEntityLibrary.cpp index 42e6eb3c..40c52aa5 100644 --- a/src/CoreLib/Scripting/SharedEntityLibrary.cpp +++ b/src/CoreLib/Scripting/SharedEntityLibrary.cpp @@ -4,12 +4,14 @@ #include #include +#include #include #include #include #include #include #include +#include #include #include #include @@ -160,11 +162,13 @@ namespace bw void SharedEntityLibrary::InitRigidBody(lua_State* /*L*/, entt::handle entity, float mass) { - auto& entityNode = entity.get(); - auto& entityPhys = entity.emplace(); - entityPhys.SetMass(mass); + auto& entityMatch = entity.get(); + auto& physics = entityMatch.GetMatch().GetLayer(entityMatch.GetLayerIndex()).GetPhysicsSystem(); + + auto& entityPhys = entity.emplace(physics.CreateRigidBody(mass)); - // Temp fix because Nazara + // Temp fix because of a Nazara bug + auto& entityNode = entity.get(); entityPhys.SetRotation(AngleFromQuaternion(entityNode.GetRotation(Nz::CoordSys::Global))); } @@ -181,20 +185,14 @@ namespace bw void SharedEntityLibrary::SetMass(lua_State* /*L*/, entt::handle entity, float mass, bool recomputeMomentOfInertia) { - Nz::RigidBody2DComponent* rigidBody = entity.try_get(); - if (!rigidBody) - return; - - rigidBody->SetMass(mass, recomputeMomentOfInertia); + if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + rigidBody->SetMass(mass, recomputeMomentOfInertia); } void SharedEntityLibrary::SetMomentOfInertia(lua_State* /*L*/, entt::handle entity, float momentOfInertia) { - Nz::RigidBody2DComponent* rigidBody = entity.try_get(); - if (!rigidBody) - return; - - rigidBody->SetMomentOfInertia(momentOfInertia); + if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + rigidBody->SetMomentOfInertia(momentOfInertia); } void SharedEntityLibrary::SetPosition(lua_State* L, entt::handle entity, const Nz::Vector2f& position) @@ -217,21 +215,21 @@ namespace bw void SharedEntityLibrary::UpdatePlayerJumpHeight(lua_State* L, entt::handle entity, float jumpHeight, float jumpHeightBoost) { - PlayerMovementComponent* playerMovementComponent = entity.try_get(); - if (!playerMovementComponent) + PlayerMovementComponent* playerMovement = entity.try_get(); + if (!playerMovement) TriggerLuaArgError(L, 1, "entity has no player movement"); - playerMovementComponent->UpdateJumpHeight(jumpHeight); - playerMovementComponent->UpdateJumpBoostHeight(jumpHeightBoost); + playerMovement->UpdateJumpHeight(jumpHeight); + playerMovement->UpdateJumpBoostHeight(jumpHeightBoost); } void SharedEntityLibrary::UpdatePlayerMovement(lua_State* L, entt::handle entity, float movementSpeed) { - PlayerMovementComponent* playerMovementComponent = entity.try_get(); - if (!playerMovementComponent) + PlayerMovementComponent* playerMovement = entity.try_get(); + if (!playerMovement) TriggerLuaArgError(L, 1, "entity has no player movement"); - playerMovementComponent->UpdateMovementSpeed(movementSpeed); + playerMovement->UpdateMovementSpeed(movementSpeed); } void SharedEntityLibrary::RegisterSharedLibrary(sol::table& elementMetatable) @@ -240,85 +238,78 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - if (entity->HasComponent()) - { - Ndk::PhysicsComponent2D& hitEntityPhys = entity.get(); - hitEntityPhys.AddForce(force); - } + if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + rigidBody->AddForce(force); }); elementMetatable["ApplyImpulse"] = LuaFunction([this](const sol::table& entityTable, const Nz::Vector2f& force) { entt::handle entity = AssertScriptEntity(entityTable); - if (entity->HasComponent()) - { - Ndk::PhysicsComponent2D& hitEntityPhys = entity.get(); - hitEntityPhys.AddImpulse(force); - } + if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + rigidBody->AddImpulse(force); }); elementMetatable["Damage"] = LuaFunction([](const sol::table& entityTable, Nz::UInt16 damage, std::optional attackerEntity) { entt::handle entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + + HealthComponent* entityHealth = entity.try_get(); + if (!entityHealth) return; - auto& entityHealth = entity.get(); - entityHealth.Damage(damage, (attackerEntity) ? RetrieveScriptEntity(*attackerEntity) : entt::null); + entityHealth->Damage(damage, (attackerEntity) ? RetrieveScriptEntity(*attackerEntity) : entt::handle{}); }); elementMetatable["ForceSleep"] = LuaFunction([](const sol::table& entityTable) { entt::handle entity = AssertScriptEntity(entityTable); - if (entity->HasComponent()) - { - auto& physComponent = entity.get(); - physComponent.ForceSleep(); - } + if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + rigidBody->ForceSleep(); }); elementMetatable["GetColliders"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) -> sol::object { entt::handle entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + + CollisionDataComponent* entityCollisionData = entity.try_get(); + if (!entityCollisionData) return sol::nil; sol::state_view state(L); - return ColliderToTable(state, entity.get().GetColliders()); + return ColliderToTable(state, entityCollisionData->GetColliders()); }); elementMetatable["GetInputController"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) { entt::handle entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + InputComponent* input = entity.try_get(); + if (!input) TriggerLuaArgError(L, 1, "entity has no inputs"); - return entity.get().GetController(); + return input->GetController(); }); elementMetatable["GetHealth"] = LuaFunction([](const sol::table& entityTable) -> Nz::UInt16 { entt::handle entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + + HealthComponent* entityHealth = entity.try_get(); + if (!entityHealth) return 0; - auto& entityHealth = entity.get(); - return entityHealth.GetHealth(); + return entityHealth->GetHealth(); }); elementMetatable["GetMass"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) -> sol::object { entt::handle entity = AssertScriptEntity(entityTable); - if (entity->HasComponent()) - { - auto& physComponent = entity.get(); - return sol::make_object(L, physComponent.GetMass()); - } + if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + return sol::make_object(L, rigidBody->GetMass()); else return sol::nil; }); @@ -327,11 +318,8 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - if (entity->HasComponent()) - { - auto& physComponent = entity.get(); - return sol::make_object(L, physComponent.GetMomentOfInertia()); - } + if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + return sol::make_object(L, rigidBody->GetMomentOfInertia()); else return sol::nil; }); @@ -340,27 +328,30 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + PlayerMovementComponent* playerMovement = entity.try_get(); + if (!playerMovement) TriggerLuaArgError(L, 1, "entity has no player movement"); - return entity.get().GetController(); + return playerMovement->GetController(); }); elementMetatable["GetPlayerMovementSpeed"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) { entt::handle entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + PlayerMovementComponent* playerMovement = entity.try_get(); + if (!playerMovement) TriggerLuaArgError(L, 1, "entity has no player movement"); - return entity.get().GetMovementSpeed(); + return playerMovement->GetMovementSpeed(); }); elementMetatable["GetPlayerJumpHeight"] = LuaFunction([](sol::this_state L, const sol::table& entityTable) { entt::handle entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + PlayerMovementComponent* playerMovement = entity.try_get(); + if (!playerMovement) TriggerLuaArgError(L, 1, "entity has no player movement"); auto& movementComponent = entity.get(); @@ -380,39 +371,42 @@ namespace bw elementMetatable["GetVelocity"] = LuaFunction([](const sol::table& entityTable) { entt::handle entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + + Nz::RigidBody2DComponent* physComponent = entity.try_get(); + if (!physComponent) return Nz::Vector2f::Zero(); - auto& physComponent = entity.get(); - return physComponent.GetVelocity(); + return physComponent->GetVelocity(); }); elementMetatable["Heal"] = LuaFunction([](const sol::table& entityTable, Nz::UInt16 value, std::optional healerEntity) { entt::handle entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + + HealthComponent* entityHealth = entity.try_get(); + if (!entityHealth) return; - auto& entityHealth = entity.get(); - entityHealth.Heal(value, (healerEntity) ? RetrieveScriptEntity(*healerEntity) : entt::null); + entityHealth->Heal(value, (healerEntity) ? RetrieveScriptEntity(*healerEntity) : entt::handle{}); }); elementMetatable["InitWeaponWielder"] = LuaFunction([](const sol::table& entityTable, const sol::table& wielderData) { entt::handle entity = AssertScriptEntity(entityTable); - auto& wielderComponent = entity.emplace(); + auto& wielderComponent = entity.emplace(entity); wielderComponent.SetWeaponOffset(wielderData["WeaponOffset"]); }); elementMetatable["IsFullHealth"] = LuaFunction([](const sol::table& entityTable) -> bool { entt::handle entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) - return false; - auto& entityHealth = entity.get(); - return entityHealth.GetHealth() >= entityHealth.GetMaxHealth(); + HealthComponent* entityHealth = entity.try_get(); + if (!entityHealth) + return true; + + return entityHealth->GetHealth() >= entityHealth->GetMaxHealth(); }); elementMetatable["InitRigidBody"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, float mass) @@ -426,17 +420,18 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + PlayerMovementComponent* entityMovement = entity.try_get(); + if (!entityMovement) TriggerLuaArgError(L, 1, "entity has no player movement"); - return entity.get().IsOnGround(); + return entityMovement->IsOnGround(); }); elementMetatable["IsSleeping"] = LuaFunction([](const sol::table& entityTable) { entt::handle entity = AssertScriptEntity(entityTable); - if (entity->HasComponent()) - return entity.get().IsSleeping(); + if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + return rigidBody->IsSleeping(); else return false; }); @@ -445,12 +440,11 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - if (entity->HasComponent()) + if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) { - Ndk::PhysicsComponent2D& hitEntityPhys = entity.get(); if (fn) { - hitEntityPhys.SetVelocityFunction([entity, fn = std::move(fn)](Nz::RigidBody2D& body2D, const Nz::Vector2f& gravity, float damping, float deltaTime) + rigidBody->SetVelocityFunction([entity, fn = std::move(fn)](Nz::RigidBody2D& body2D, const Nz::Vector2f& gravity, float damping, float deltaTime) { auto& entityScript = entity.get(); @@ -470,27 +464,29 @@ namespace bw }); } else - hitEntityPhys.SetVelocityFunction(nullptr); + rigidBody->SetVelocityFunction(nullptr); } }); elementMetatable["Remove"] = LuaFunction([](const sol::table& entityTable) { entt::handle entity = AssertScriptEntity(entityTable); - entity->Kill(); + + entity.destroy(); }); elementMetatable["SetAngularVelocity"] = LuaFunction([](const sol::table& entityTable, const Nz::DegreeAnglef& velocity) { entt::handle entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + + Nz::RigidBody2DComponent* physComponent = entity.try_get(); + if (!physComponent) return; - auto& physComponent = entity.get(); - physComponent.SetAngularVelocity(velocity); + physComponent->SetAngularVelocity(velocity); }); - elementMetatable["SetColliders"] = LuaFunction([](sol::this_state L, const sol::table& entityTable, const sol::table& colliderTable) + elementMetatable["SetColliders"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, const sol::table& colliderTable) { entt::handle entity = AssertScriptEntity(entityTable); @@ -531,7 +527,13 @@ namespace bw } } - entity.emplace(entityCollData.BuildCollider(entityNode.GetScale().y)); + std::shared_ptr collider = entityCollData.BuildCollider(entityNode.GetScale().y); + + Nz::RigidBody2DComponent* physComponent = entity.try_get(); + if (!physComponent) + InitRigidBody(L, entity, 0.f); + + physComponent->SetGeom(std::move(collider)); }); elementMetatable["SetDirection"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, const Nz::Vector2f& upVector) @@ -589,43 +591,48 @@ namespace bw elementMetatable["SetVelocity"] = LuaFunction([](const sol::table& entityTable, const Nz::Vector2f& velocity) { entt::handle entity = AssertScriptEntity(entityTable); - if (!entity || !entity->HasComponent()) + + Nz::RigidBody2DComponent* physComponent = entity.try_get(); + if (!physComponent) return; - auto& physComponent = entity.get(); - physComponent.SetVelocity(velocity); + physComponent->SetVelocity(velocity); }); elementMetatable["UpdateInputs"] = LuaFunction([](const sol::table& entityTable, const PlayerInputData& inputs) { entt::handle entity = AssertScriptEntity(entityTable); - if (!entity || !entity->HasComponent()) + + InputComponent* input = entity.try_get(); + if (!input) return; - auto& entityInputs = entity.get(); - entityInputs.UpdateInputs(inputs); + input->UpdateInputs(inputs); }); elementMetatable["UpdateInputController"] = LuaFunction([this](const sol::table& entityTable, std::shared_ptr controller) { entt::handle entity = AssertScriptEntity(entityTable); - if (!entity || !entity->HasComponent()) + + InputComponent* input = entity.try_get(); + if (!input) return; - auto& entityInputs = entity.get(); - entityInputs.UpdateController(std::move(controller)); + input->UpdateController(std::move(controller)); }); elementMetatable["UpdatePlayerMovementController"] = LuaFunction([](sol::this_state L, const sol::table& entityTable, sol::optional> controller) { entt::handle entity = AssertScriptEntity(entityTable); - if (!entity->HasComponent()) + + PlayerMovementComponent* playerMovement = entity.try_get(); + if (!playerMovement) TriggerLuaArgError(L, 1, "entity has no player movement"); if (controller) - return entity.get().UpdateController(std::move(*controller)); + return playerMovement->UpdateController(std::move(*controller)); else - return entity.get().UpdateController(nullptr); + return playerMovement->UpdateController(nullptr); }); elementMetatable["UpdatePlayerMovementSpeed"] = LuaFunction([&](sol::this_state L, const sol::table& entityTable, float newSpeed) diff --git a/src/CoreLib/Scripting/SharedEntityStore.cpp b/src/CoreLib/Scripting/SharedEntityStore.cpp index b5ebe380..47841a7c 100644 --- a/src/CoreLib/Scripting/SharedEntityStore.cpp +++ b/src/CoreLib/Scripting/SharedEntityStore.cpp @@ -22,10 +22,9 @@ namespace bw { if (InputComponent* entityInputs = entity.try_get()) { - entityInputs->OnInputUpdate.Connect([](InputComponent* input) + entityInputs->OnInputUpdate.Connect([entity](InputComponent* input) { - entt::entity entity = input->GetEntity(); - auto& entityScript = entity->GetComponent(); + auto& entityScript = entity.get(); entityScript.ExecuteCallback(input->GetInputs()); }); @@ -36,13 +35,12 @@ namespace bw { } - bool SharedEntityStore::InitializeEntity(const ScriptedEntity& entityClass, entt::entity entity) const + bool SharedEntityStore::InitializeEntity(const ScriptedEntity& entityClass, entt::handle entity) const { if (!ScriptStore::InitializeEntity(entityClass, entity)) return false; BindCallbacks(entityClass, entity); - return true; } } diff --git a/src/CoreLib/Scripting/SharedGamemode.cpp b/src/CoreLib/Scripting/SharedGamemode.cpp index 06d6f506..ec098d72 100644 --- a/src/CoreLib/Scripting/SharedGamemode.cpp +++ b/src/CoreLib/Scripting/SharedGamemode.cpp @@ -6,8 +6,6 @@ #include #include #include -#include -#include #include #include #include diff --git a/src/CoreLib/Scripting/SharedScriptingLibrary.cpp b/src/CoreLib/Scripting/SharedScriptingLibrary.cpp index 8dad59c6..d29b233e 100644 --- a/src/CoreLib/Scripting/SharedScriptingLibrary.cpp +++ b/src/CoreLib/Scripting/SharedScriptingLibrary.cpp @@ -2,6 +2,8 @@ // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE +#if 0 + #include #include #include @@ -158,11 +160,14 @@ namespace bw "ReadEntity", LuaFunction([&](IncomingNetworkPacket& incomingPacket) -> sol::object { Nz::Int64 entityId = incomingPacket.ReadCompressedInteger(); - entt::entity entity = m_match.RetrieveEntityByUniqueId(entityId); - if (entity && entity->HasComponent()) - return entity->GetComponent().GetTable(); - else - return sol::nil; + entt::handle entity = m_match.RetrieveEntityByUniqueId(entityId); + if (entity) + { + if (ScriptComponent* scriptComponent = entity.try_get()) + return scriptComponent->GetTable(); + } + + return sol::nil; }) ); @@ -180,7 +185,7 @@ namespace bw "WriteEntity", LuaFunction([&](OutgoingNetworkPacket& outgoingPacket, const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); outgoingPacket.WriteCompressedInteger(m_match.RetrieveUniqueIdByEntity(entity)); }) ); @@ -239,13 +244,13 @@ namespace bw sol::table result = state.create_table(); std::size_t index = 1; - auto entityFunc = [&](entt::entity entity) + auto entityFunc = [&](entt::handle entity) { - if (!entity->HasComponent()) + ScriptComponent* entityScript = entity.try_get(); + if (!entityScript) return; - auto& entityScript = entity->GetComponent(); - result[index++] = entityScript.GetTable(); + result[index++] = entityScript->GetTable(); }; if (layerIndexOpt) @@ -268,14 +273,14 @@ namespace bw sol::table result = state.create_table(); std::size_t index = 1; - auto entityFunc = [&](entt::entity entity) + auto entityFunc = [&](entt::handle entity) { - if (!entity->HasComponent()) + ScriptComponent* entityScript = entity.try_get(); + if (!entityScript) return; - auto& entityScript = entity->GetComponent(); - if (entityScript.GetElement()->fullName == entityClass) - result[index++] = entityScript.GetTable(); + if (entityScript->GetElement()->fullName == entityClass) + result[index++] = entityScript->GetTable(); }; if (layerIndexOpt) @@ -344,56 +349,57 @@ namespace bw { library["CreateDampenedSpringConstraint"] = LuaFunction([](sol::this_state L, const sol::table& firstEntityTable, const sol::table& secondEntityTable, const Nz::Vector2f& firstAnchor, const Nz::Vector2f& secondAnchor, float restLength, float stiffness, float damping) { - entt::entity firstEntity = AssertScriptEntity(firstEntityTable); - entt::entity secondEntity = AssertScriptEntity(secondEntityTable); + entt::handle firstEntity = AssertScriptEntity(firstEntityTable); + entt::handle secondEntity = AssertScriptEntity(secondEntityTable); if (firstEntity == secondEntity) TriggerLuaArgError(L, 1, "Cannot apply a constraint to the same entity"); - entt::entity constraintEntity = firstEntity->GetWorld()->CreateEntity(); - auto& constraintComponent = constraintEntity->AddComponent(); + entt::registry& registry = *firstEntity.registry(); + entt::entity constraintEntity = registry.create(); + auto& constraintComponent = registry.emplace(constraintEntity); return DampedSpringConstraint(constraintEntity, constraintComponent.CreateConstraint(firstEntity, secondEntity, firstAnchor, secondAnchor, restLength, stiffness, damping)); }); library["CreatePinConstraint"] = LuaFunction([](sol::this_state L, const sol::table& firstEntityTable, const sol::table& secondEntityTable, const Nz::Vector2f& firstAnchor, const Nz::Vector2f& secondAnchor) { - entt::entity firstEntity = AssertScriptEntity(firstEntityTable); - entt::entity secondEntity = AssertScriptEntity(secondEntityTable); + entt::handle firstEntity = AssertScriptEntity(firstEntityTable); + entt::handle secondEntity = AssertScriptEntity(secondEntityTable); if (firstEntity == secondEntity) TriggerLuaArgError(L, 1, "Cannot apply a constraint to the same entity"); - entt::entity constraintEntity = firstEntity->GetWorld()->CreateEntity(); - auto& constraintComponent = constraintEntity->AddComponent(); + entt::entity constraintEntity = firstEntity.registry()->create(); + auto& constraintComponent = constraintEntity->AddComponent(); return PinConstraint(constraintEntity, constraintComponent.CreateConstraint(firstEntity, secondEntity, firstAnchor, secondAnchor)); }); library["CreatePivotConstraint"] = LuaFunction([](sol::this_state L, const sol::table& firstEntityTable, const sol::table& secondEntityTable, const Nz::Vector2f& firstAnchor, const Nz::Vector2f& secondAnchor) { - entt::entity firstEntity = AssertScriptEntity(firstEntityTable); - entt::entity secondEntity = AssertScriptEntity(secondEntityTable); + entt::handle firstEntity = AssertScriptEntity(firstEntityTable); + entt::handle secondEntity = AssertScriptEntity(secondEntityTable); if (firstEntity == secondEntity) TriggerLuaArgError(L, 1, "Cannot apply a constraint to the same entity"); - entt::entity constraintEntity = firstEntity->GetWorld()->CreateEntity(); - auto& constraintComponent = constraintEntity->AddComponent(); + entt::entity constraintEntity = firstEntity.registry()->create(); + auto& constraintComponent = constraintEntity->AddComponent(); return PivotConstraint(constraintEntity, constraintComponent.CreateConstraint(firstEntity, secondEntity, firstAnchor, secondAnchor)); }); library["CreateRotaryLimitConstraint"] = LuaFunction([](sol::this_state L, const sol::table& firstEntityTable, const sol::table& secondEntityTable, const Nz::RadianAnglef& minAngle, const Nz::RadianAnglef& maxAngle) { - entt::entity firstEntity = AssertScriptEntity(firstEntityTable); - entt::entity secondEntity = AssertScriptEntity(secondEntityTable); + entt::handle firstEntity = AssertScriptEntity(firstEntityTable); + entt::handle secondEntity = AssertScriptEntity(secondEntityTable); if (firstEntity == secondEntity) TriggerLuaArgError(L, 1, "Cannot apply a constraint to the same entity"); - entt::entity constraintEntity = firstEntity->GetWorld()->CreateEntity(); - auto& constraintComponent = constraintEntity->AddComponent(); + entt::entity constraintEntity = firstEntity.registry()->create(); + auto& constraintComponent = constraintEntity->AddComponent(); return RotaryLimitConstraint(constraintEntity, constraintComponent.CreateConstraint(firstEntity, secondEntity, minAngle, maxAngle)); }); @@ -403,7 +409,7 @@ namespace bw if (layer >= m_match.GetLayerCount()) TriggerLuaArgError(L, 1, "invalid layer index"); - Ndk::World& world = m_match.GetLayer(layer).GetWorld(); + entt::registry& world = m_match.GetLayer(layer).GetWorld(); auto& physSystem = world.GetSystem(); Ndk::EntityList hitEntities; //< FIXME: RegionQuery hit multiples entities @@ -435,7 +441,7 @@ namespace bw if (layer >= m_match.GetLayerCount()) TriggerLuaArgError(L, 1, "invalid layer index"); - Ndk::World& world = m_match.GetLayer(layer).GetWorld(); + entt::registry& world = m_match.GetLayer(layer).GetWorld(); auto& physSystem = world.GetSystem(); Ndk::PhysicsSystem2D::RaycastHit hitInfo; @@ -462,7 +468,7 @@ namespace bw if (layer >= m_match.GetLayerCount()) TriggerLuaArgError(L, 1, "invalid layer index"); - Ndk::World& world = m_match.GetLayer(layer).GetWorld(); + entt::registry& world = m_match.GetLayer(layer).GetWorld(); auto& physSystem = world.GetSystem(); Ndk::EntityList hitEntities; //< FIXME: RegionQuery hit multiples entities @@ -517,3 +523,5 @@ namespace bw }); } } + +#endif diff --git a/src/CoreLib/Scripting/SharedWeaponLibrary.cpp b/src/CoreLib/Scripting/SharedWeaponLibrary.cpp index 0632862b..317f173d 100644 --- a/src/CoreLib/Scripting/SharedWeaponLibrary.cpp +++ b/src/CoreLib/Scripting/SharedWeaponLibrary.cpp @@ -9,8 +9,8 @@ #include #include #include -#include -#include +#include +#include #include namespace bw @@ -24,20 +24,20 @@ namespace bw { elementMetatable["GetOwnerEntity"] = LuaFunction([](const sol::table& weaponTable) -> sol::object { - entt::entity entity = AssertScriptEntity(weaponTable); + entt::handle entity = AssertScriptEntity(weaponTable); - entt::entity ownerEntity = entity->GetComponent().GetOwner(); + entt::handle ownerEntity = entity.get().GetOwner(); if (!ownerEntity) return sol::nil; - return ownerEntity->GetComponent().GetTable(); + return ownerEntity.get().GetTable(); }); elementMetatable["SetNextTriggerTime"] = LuaFunction([](const sol::table& weaponTable, Nz::UInt64 nextTriggerTime) { - entt::entity entity = AssertScriptEntity(weaponTable); + entt::handle entity = AssertScriptEntity(weaponTable); - entity->GetComponent().SetNextTriggerTime(nextTriggerTime); + entity.get().SetNextTriggerTime(nextTriggerTime); }); } } diff --git a/src/CoreLib/Scripting/SharedWeaponStore.cpp b/src/CoreLib/Scripting/SharedWeaponStore.cpp index 7f7c133d..aa98d9c8 100644 --- a/src/CoreLib/Scripting/SharedWeaponStore.cpp +++ b/src/CoreLib/Scripting/SharedWeaponStore.cpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include namespace bw @@ -58,35 +58,32 @@ namespace bw weapon.animationStartFunction = elementTable.get_or("OnAnimationStart", sol::main_protected_function{}); } - bool SharedWeaponStore::InitializeWeapon(const ScriptedWeapon& weaponClass, entt::entity entity, entt::entity parent) + bool SharedWeaponStore::InitializeWeapon(const ScriptedWeapon& weaponClass, entt::handle entity, entt::handle parent) { - entity->AddComponent(weaponClass.cooldown); + entity.emplace(weaponClass.cooldown); - entity->AddComponent(parent, weaponClass.attackMode); + entity.emplace(parent, weaponClass.attackMode); - auto& weaponNode = entity->AddComponent(); + auto& weaponNode = entity.emplace(); weaponNode.SetParent(parent); weaponNode.SetInheritRotation(false); weaponNode.SetInheritScale(false); - if (parent->HasComponent()) - { - auto& wielderComponent = parent->GetComponent(); - weaponNode.SetPosition(wielderComponent.GetWeaponOffset()); - } + if (WeaponWielderComponent* parentWeaponWielder = parent.try_get()) + weaponNode.SetPosition(parentWeaponWielder->GetWeaponOffset()); else - bwLog(GetLogger(), LogLevel::Warning, "Weapon owner (Entity #{0}) has not been initialized as a wielder", parent->GetId()); + bwLog(GetLogger(), LogLevel::Warning, "Weapon owner (Entity #) has not been initialized as a wielder"); if (weaponClass.animations) { - auto& anim = entity->AddComponent(weaponClass.animations); + auto& anim = entity.emplace(entity, weaponClass.animations); if (weaponClass.animationStartFunction) { anim.OnAnimationStart.Connect([this, callback = weaponClass.animationStartFunction](AnimationComponent* anim) { - entt::entity entity = anim->GetEntity(); - auto& scriptComponent = entity->GetComponent(); + entt::handle entity = anim->GetHandle(); + auto& scriptComponent = entity.get(); auto co = scriptComponent.GetContext()->CreateCoroutine(callback); diff --git a/src/CoreLib/SharedLayer.cpp b/src/CoreLib/SharedLayer.cpp index 663f8d38..a760d8fb 100644 --- a/src/CoreLib/SharedLayer.cpp +++ b/src/CoreLib/SharedLayer.cpp @@ -12,33 +12,36 @@ #include #include #include -#include -#include -#include +#include +#include +#include #include namespace bw { SharedLayer::SharedLayer(SharedMatch& match, LayerIndex layerIndex) : m_match(match), + m_systemGraph(m_registry), m_layerIndex(layerIndex) { - m_world.AddSystem(); - m_world.AddSystem(); - m_world.AddSystem(); + m_systemGraph.AddSystem(); + m_systemGraph.AddSystem(); + m_systemGraph.AddSystem(); - m_world.AddSystem(match); - m_world.AddSystem(); - m_world.AddSystem(); - m_world.AddSystem(match); - m_world.AddSystem(match); + m_systemGraph.AddSystem(match); + m_systemGraph.AddSystem(); + m_systemGraph.AddSystem(); + m_systemGraph.AddSystem(match); + m_systemGraph.AddSystem(match); - Ndk::PhysicsSystem2D& physics = m_world.GetSystem(); + Nz::PhysWorld2D& physics = m_systemGraph.GetSystem().GetPhysWorld(); physics.SetGravity(Nz::Vector2f(0.f, 9.81f * 192.f)); physics.SetMaxStepCount(1); physics.SetSleepTime(0.f); physics.SetStepSize(match.GetTickDuration()); + // EnTT FIXME +#if 0 Ndk::PhysicsSystem2D::Callback triggerCallbacks; triggerCallbacks.startCallback = [](Ndk::PhysicsSystem2D& /*world*/, Nz::Arbiter2D& /*arbiter*/, entt::entity bodyA, entt::entity bodyB, void* /*userdata*/) { @@ -108,12 +111,13 @@ namespace bw system.SetFixedUpdateRate(0.f); system.SetMaximumUpdateRate(0.f); }); +#endif } SharedLayer::~SharedLayer() = default; void SharedLayer::TickUpdate(float elapsedTime) { - m_world.Update(elapsedTime); + m_systemGraph.Update(elapsedTime); } } diff --git a/src/CoreLib/SharedMatch.cpp b/src/CoreLib/SharedMatch.cpp index 30e69fea..dad394d0 100644 --- a/src/CoreLib/SharedMatch.cpp +++ b/src/CoreLib/SharedMatch.cpp @@ -7,7 +7,6 @@ #include #include #include -#include #include namespace bw @@ -19,7 +18,7 @@ namespace bw SharedMatch::SharedMatch(BurgApp& app, LogSide side, std::string matchName, float tickDuration) : m_name(std::move(matchName)), - m_logger(app, *this, side, app.GetLogger(), sizeof(EntityLogContext)), + m_logger(app, *this, side, app.GetLogger()), m_scriptPacketHandler(m_logger), m_currentTick(0), m_currentTime(0), diff --git a/src/CoreLib/Systems/AnimationSystem.cpp b/src/CoreLib/Systems/AnimationSystem.cpp index 627c6730..6de77771 100644 --- a/src/CoreLib/Systems/AnimationSystem.cpp +++ b/src/CoreLib/Systems/AnimationSystem.cpp @@ -8,19 +8,15 @@ namespace bw { - AnimationSystem::AnimationSystem(SharedMatch& match) : - m_match(match) + void AnimationSystem::Update(float /*elapsedTime*/) { - } - - void AnimationSystem::OnUpdate(float /*elapsedTime*/) - { - /*Nz::UInt64 now = m_match.GetCurrentTime(); + Nz::UInt64 now = m_match.GetCurrentTime(); - for (entt::entity entity : GetEntities()) + auto view = m_registry.view(); + for (entt::entity entity : view) { - auto& animComponent = entity->GetComponent(); + auto& animComponent = view.get(entity); animComponent.Update(now); - }*/ + } } } diff --git a/src/CoreLib/Systems/InputSystem.cpp b/src/CoreLib/Systems/InputSystem.cpp index 877b2e14..e05c2574 100644 --- a/src/CoreLib/Systems/InputSystem.cpp +++ b/src/CoreLib/Systems/InputSystem.cpp @@ -7,25 +7,16 @@ namespace bw { - InputSystem::InputSystem() + void InputSystem::Update(float /*elapsedTime*/) { - Requires(); - SetMaximumUpdateRate(0); - SetUpdateOrder(-100); - } - - void InputSystem::OnUpdate(float /*elapsedTime*/) - { - for (entt::entity entity : GetEntities()) + auto view = m_registry.view(); + for (auto [entity, inputComponent] : view.each()) { - auto& inputComponent = entity->GetComponent(); if (const auto& controller = inputComponent.GetController()) { - if (auto inputOpt = controller->GenerateInputs(entity)) + if (auto inputOpt = controller->GenerateInputs(entt::handle(m_registry, entity))) inputComponent.UpdateInputs(*inputOpt); } } } - - Ndk::SystemIndex InputSystem::systemIndex; } diff --git a/src/CoreLib/Systems/NetworkSyncSystem.cpp b/src/CoreLib/Systems/NetworkSyncSystem.cpp index 1bbf4954..3fd2ff4c 100644 --- a/src/CoreLib/Systems/NetworkSyncSystem.cpp +++ b/src/CoreLib/Systems/NetworkSyncSystem.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include #include #include #include @@ -13,22 +12,27 @@ #include #include #include +#include namespace bw { - NetworkSyncSystem::NetworkSyncSystem(TerrainLayer& layer) : + NetworkSyncSystem::NetworkSyncSystem(entt::registry& registry, TerrainLayer& layer) : + m_registry(registry), m_layer(layer) { - Requires(); - SetMaximumUpdateRate(30.f); - SetUpdateOrder(100); //< Execute after every other system + m_freeNetworkIds.Resize(1024, true); + + m_observer.connect(m_registry, entt::collector.group()); + //Requires(); + //SetMaximumUpdateRate(30.f); } void NetworkSyncSystem::CreateEntities(const std::function& callback) const { m_creationEvents.clear(); - for (entt::entity entity : GetEntities()) + auto view = m_registry.view(); + for (entt::entity entity : view) { EntityCreation& creationEvent = m_creationEvents.emplace_back(); BuildEvent(creationEvent, entity); @@ -41,7 +45,8 @@ namespace bw { m_destructionEvents.clear(); - for (entt::entity entity : GetEntities()) + auto view = m_registry.view(); + for (entt::entity entity : view) { EntityDestruction& destructionEvent = m_destructionEvents.emplace_back(); BuildEvent(destructionEvent, entity); @@ -56,7 +61,7 @@ namespace bw for (entt::entity entity : m_physicsEntities) { - auto& entityPhys = entity->GetComponent(); + auto& entityPhys = m_registry.get(entity); if (entityPhys.IsSleeping()) continue; @@ -66,81 +71,82 @@ namespace bw callback(m_movementEvents.data(), m_movementEvents.size()); } - void NetworkSyncSystem::BuildEvent(EntityCreation& creationEvent, Ndk::Entity* entity) const + Nz::UInt32 NetworkSyncSystem::AllocateNetworkId() + { + std::size_t freeId = m_freeNetworkIds.FindFirst(); + if (freeId == m_freeNetworkIds.npos) + { + freeId = m_freeNetworkIds.GetSize(); + m_freeNetworkIds.Resize(m_freeNetworkIds.GetSize() * 2, true); + } + + m_freeNetworkIds.Set(freeId, false); + return Nz::SafeCast(freeId); + } + + void NetworkSyncSystem::BuildEvent(EntityCreation& creationEvent, entt::entity entity) const { - const NetworkSyncComponent& syncComponent = entity->GetComponent(); + const NetworkSyncComponent& syncComponent = m_registry.get(entity); - creationEvent.entityId = entity->GetId(); + creationEvent.entityId = syncComponent.GetNetworkId(); creationEvent.entityClass = syncComponent.GetEntityClass(); - auto& entityMatch = entity->GetComponent(); + auto& entityMatch = m_registry.get(entity); creationEvent.uniqueId = entityMatch.GetUniqueId(); - if (entt::entity parent = syncComponent.GetParent()) + if (entt::handle parent = syncComponent.GetParent()) { - assert(parent->GetWorld() == entity->GetWorld()); - creationEvent.parent = parent->GetId(); + assert(parent.registry() == &m_registry); + creationEvent.parent = parent.get().GetNetworkId(); } - if (entity->HasComponent()) + if (HealthComponent* healthComponent = m_registry.try_get(entity)) { - auto& entityHealth = entity->GetComponent(); - creationEvent.healthProperties.emplace(); - creationEvent.healthProperties->currentHealth = entityHealth.GetHealth(); - creationEvent.healthProperties->maxHealth = entityHealth.GetMaxHealth(); + creationEvent.healthProperties->currentHealth = healthComponent->GetHealth(); + creationEvent.healthProperties->maxHealth = healthComponent->GetMaxHealth(); } - if (entity->HasComponent()) - { - auto& entityInputs = entity->GetComponent(); - - creationEvent.inputs = entityInputs.GetInputs(); - } + if (InputComponent* entityInputs = m_registry.try_get(entity)) + creationEvent.inputs = entityInputs->GetInputs(); - if (entity->HasComponent()) - creationEvent.playerOwner = entity->GetComponent().GetOwner(); + if (OwnerComponent* entityOwner = m_registry.try_get(entity)) + creationEvent.playerOwner = entityOwner->GetOwner(); else creationEvent.playerOwner = nullptr; - auto& entityNode = entity->GetComponent(); + auto& entityNode = m_registry.get(entity); creationEvent.scale = entityNode.GetScale().y; //< x is affected by the "looking right" flag - if (entity->HasComponent()) + if (Nz::RigidBody2DComponent* entityPhys = m_registry.try_get(entity)) { - auto& entityPhys = entity->GetComponent(); - - creationEvent.position = entityPhys.GetPosition(); - creationEvent.rotation = entityPhys.GetRotation(); + creationEvent.position = entityPhys->GetPosition(); + creationEvent.rotation = entityPhys->GetRotation(); creationEvent.physicsProperties.emplace(); - creationEvent.physicsProperties->angularVelocity = entityPhys.GetAngularVelocity(); - creationEvent.physicsProperties->isSleeping = entityPhys.IsSleeping(); - creationEvent.physicsProperties->linearVelocity = entityPhys.GetVelocity(); - creationEvent.physicsProperties->mass = entityPhys.GetMass(); - creationEvent.physicsProperties->momentOfInertia = entityPhys.GetMomentOfInertia(); + creationEvent.physicsProperties->angularVelocity = entityPhys->GetAngularVelocity(); + creationEvent.physicsProperties->isSleeping = entityPhys->IsSleeping(); + creationEvent.physicsProperties->linearVelocity = entityPhys->GetVelocity(); + creationEvent.physicsProperties->mass = entityPhys->GetMass(); + creationEvent.physicsProperties->momentOfInertia = entityPhys->GetMomentOfInertia(); } else { - creationEvent.position = Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys_Local)); - creationEvent.rotation = Nz::DegreeAnglef(AngleFromQuaternion(entityNode.GetRotation(Nz::CoordSys_Local))); //< Erk + creationEvent.position = Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys::Local)); + creationEvent.rotation = Nz::DegreeAnglef(AngleFromQuaternion(entityNode.GetRotation(Nz::CoordSys::Local))); //< Eww } - if (entity->HasComponent()) + if (PlayerMovementComponent* entityPlayerMovement = m_registry.try_get(entity)) { - auto& entityPlayerMovement = entity->GetComponent(); - creationEvent.playerMovement.emplace(); - creationEvent.playerMovement->isFacingRight = entityPlayerMovement.IsFacingRight(); + creationEvent.playerMovement->isFacingRight = entityPlayerMovement->IsFacingRight(); } - if (entity->HasComponent()) + if (ScriptComponent* scriptComponent = m_registry.try_get(entity)) { - auto& scriptComponent = entity->GetComponent(); - - const auto& element = scriptComponent.GetElement(); + const auto& element = scriptComponent->GetElement(); - for (const auto& [key, value] : scriptComponent.GetProperties()) + for (const auto& [key, value] : scriptComponent->GetProperties()) { auto it = element->properties.find(key); assert(it != element->properties.end()); @@ -152,11 +158,13 @@ namespace bw auto RegisterDependentId = [&](EntityId entityId) { - entt::entity propertyEntity = m_layer.GetMatch().RetrieveEntityByUniqueId(entityId); + entt::handle propertyEntity = m_layer.GetMatch().RetrieveEntityByUniqueId(entityId); if (propertyEntity) { - auto& propertyEntityMatch = propertyEntity->GetComponent(); - creationEvent.dependentIds.emplace_back(propertyEntityMatch.GetLayerIndex(), propertyEntity->GetId()); + Nz::UInt32 networkId = propertyEntity.get().GetNetworkId(); + + auto& propertyEntityMatch = propertyEntity.get(); + creationEvent.dependentIds.emplace_back(propertyEntityMatch.GetLayerIndex(), networkId); } }; @@ -181,91 +189,98 @@ namespace bw } } - if (entity->HasComponent()) + if (WeaponWielderComponent* entityWeaponWielder = m_registry.try_get(entity)) { - auto& entityWeaponWielder = entity->GetComponent(); - - if (entt::entity activeWeapon = entityWeaponWielder.GetActiveWeapon()) - creationEvent.weapon = activeWeapon->GetId(); + if (entt::handle activeWeapon = entityWeaponWielder->GetActiveWeapon()) + { + Nz::UInt32 networkId = activeWeapon.get().GetNetworkId(); + creationEvent.weapon = networkId; + } } } - void NetworkSyncSystem::BuildEvent(EntityDeath& deathEvent, Ndk::Entity* entity) const + void NetworkSyncSystem::BuildEvent(EntityDeath& deathEvent, entt::entity entity) const { - deathEvent.entityId = entity->GetId(); + const NetworkSyncComponent& syncComponent = m_registry.get(entity); + deathEvent.entityId = syncComponent.GetNetworkId(); } - void NetworkSyncSystem::BuildEvent(EntityDestruction& deleteEvent, Ndk::Entity* entity) const + void NetworkSyncSystem::BuildEvent(EntityDestruction& deleteEvent, entt::entity entity) const { - deleteEvent.entityId = entity->GetId(); + const NetworkSyncComponent& syncComponent = m_registry.get(entity); + deleteEvent.entityId = syncComponent.GetNetworkId(); } - void NetworkSyncSystem::BuildEvent(EntityMovement& movementEvent, Ndk::Entity* entity) const + void NetworkSyncSystem::BuildEvent(EntityMovement& movementEvent, entt::entity entity) const { - movementEvent.entityId = entity->GetId(); + const NetworkSyncComponent& syncComponent = m_registry.get(entity); + movementEvent.entityId = syncComponent.GetNetworkId(); - if (entity->HasComponent()) + if (Nz::RigidBody2DComponent* entityPhys = m_registry.try_get(entity)) { //TODO: Handle parents? - auto& entityPhys = entity->GetComponent(); - movementEvent.position = entityPhys.GetPosition(); - movementEvent.rotation = entityPhys.GetRotation(); + movementEvent.position = entityPhys->GetPosition(); + movementEvent.rotation = entityPhys->GetRotation(); movementEvent.physicsProperties.emplace(); - movementEvent.physicsProperties->angularVelocity = entityPhys.GetAngularVelocity(); - movementEvent.physicsProperties->isSleeping = entityPhys.IsSleeping(); - movementEvent.physicsProperties->linearVelocity = entityPhys.GetVelocity(); - movementEvent.physicsProperties->mass = entityPhys.GetMass(); + movementEvent.physicsProperties->angularVelocity = entityPhys->GetAngularVelocity(); + movementEvent.physicsProperties->isSleeping = entityPhys->IsSleeping(); + movementEvent.physicsProperties->linearVelocity = entityPhys->GetVelocity(); + movementEvent.physicsProperties->mass = entityPhys->GetMass(); } else { - auto& entityNode = entity->GetComponent(); - movementEvent.position = Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys_Local)); - movementEvent.rotation = AngleFromQuaternion(entityNode.GetRotation(Nz::CoordSys_Local)); //< Erk + auto& entityNode = m_registry.get(entity); + movementEvent.position = Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys::Local)); + movementEvent.rotation = AngleFromQuaternion(entityNode.GetRotation(Nz::CoordSys::Local)); //< Ew } - if (entity->HasComponent()) + if (PlayerMovementComponent* entityPlayerMovement = m_registry.try_get(entity)) { - auto& entityPlayerMovement = entity->GetComponent(); - movementEvent.playerMovement.emplace(); - movementEvent.playerMovement->isFacingRight = entityPlayerMovement.IsFacingRight(); + movementEvent.playerMovement->isFacingRight = entityPlayerMovement->IsFacingRight(); } } - void NetworkSyncSystem::OnEntityAdded(Ndk::Entity* entity) + void NetworkSyncSystem::FreeNetworkId(Nz::UInt32 networkId) + { + assert(!m_freeNetworkIds.UnboundedTest(networkId)); + m_freeNetworkIds.Set(networkId, true); + } + + void NetworkSyncSystem::HandleNewEntity(entt::entity entity) { EntityCreation creationEvent; BuildEvent(creationEvent, entity); OnEntityCreated(this, creationEvent); - assert(m_entitySlots.find(entity->GetId()) == m_entitySlots.end()); - auto& slots = m_entitySlots.emplace(entity->GetId(), EntitySlots()).first.value(); + assert(m_entitySlots.find(entity) == m_entitySlots.end()); + auto& slots = m_entitySlots.emplace(entity, EntitySlots()).first.value(); - if (entity->HasComponent()) - m_physicsEntities.Insert(entity); + if (m_registry.try_get(entity)) + m_physicsEntities.insert(entity); else - m_staticEntities.Insert(entity); + m_staticEntities.insert(entity); - if (entity->HasComponent()) + Nz::UInt32 networkId = creationEvent.entityId; + + if (AnimationComponent* entityAnim = m_registry.try_get(entity)) { - slots.onAnimationStart.Connect(entity->GetComponent().OnAnimationStart, [&](AnimationComponent* anim) + slots.onAnimationStart.Connect(entityAnim->OnAnimationStart, [this, networkId](AnimationComponent* anim) { EntityPlayAnimation event; event.animId = anim->GetAnimId(); - event.entityId = anim->GetEntity()->GetId(); + event.entityId = networkId; event.startTime = anim->GetStartTime(); OnEntityPlayAnimation(this, event); }); } - if (entity->HasComponent()) + if (HealthComponent* entityHealth = m_registry.try_get(entity)) { - auto& entityHealth = entity->GetComponent(); - - slots.onDied.Connect(entityHealth.OnDied, [&](const HealthComponent* health, entt::entity /*attacker*/) + slots.onDied.Connect(entityHealth->OnDie, [this](const HealthComponent* health, entt::entity /*attacker*/) { EntityDeath deathEvent; BuildEvent(deathEvent, health->GetEntity()); @@ -273,63 +288,64 @@ namespace bw OnEntityDeath(this, deathEvent); }); - slots.onHealthChange.Connect(entityHealth.OnHealthChange, [&](HealthComponent* health, Nz::UInt16 /*newHealth*/, entt::entity /*dealer*/) + slots.onHealthChange.Connect(entityHealth->OnHealthChange, [this, networkId](HealthComponent* health, Nz::UInt16 /*newHealth*/, entt::entity /*dealer*/) { - m_healthUpdateEntities.Insert(health->GetEntity()); + m_healthUpdateEntities.insert(health->GetEntity()); }); } - if (entity->HasComponent()) + if (InputComponent* entityInput = m_registry.try_get(entity)) { - slots.onInputUpdate.Connect(entity->GetComponent().OnInputUpdate, [&](InputComponent* input) + slots.onInputUpdate.Connect(entityInput->OnInputUpdate, [this](InputComponent* input) { - m_inputUpdateEntities.Insert(input->GetEntity()); + m_inputUpdateEntities.insert(input->GetEntity()); }); } - if (entity->HasComponent()) + if (WeaponWielderComponent* entityWeaponWielder = m_registry.try_get(entity)) { - auto& entityWeaponWielder = entity->GetComponent(); - - slots.onNewWeaponSelection.Connect(entityWeaponWielder.OnNewWeaponSelection, [&](WeaponWielderComponent* wielder, std::size_t /*newWeaponIndex*/) + slots.onNewWeaponSelection.Connect(entityWeaponWielder->OnNewWeaponSelection, [this](WeaponWielderComponent* wielder, std::size_t /*newWeaponIndex*/) { - m_weaponUpdateEntities.Insert(wielder->GetEntity()); + m_weaponUpdateEntities.insert(wielder->GetEntity()); }); } } - void NetworkSyncSystem::OnEntityRemoved(Ndk::Entity* entity) + void NetworkSyncSystem::OnComponentRemoved(entt::entity entity) { EntityDestruction destructionEvent; BuildEvent(destructionEvent, entity); OnEntityDeleted(this, destructionEvent); - m_healthUpdateEntities.Remove(entity); - m_inputUpdateEntities.Remove(entity); - m_physicsEntities.Remove(entity); - m_physicsUpdateEntities.Remove(entity); - m_staticEntities.Remove(entity); - m_weaponUpdateEntities.Remove(entity); + m_healthUpdateEntities.erase(entity); + m_inputUpdateEntities.erase(entity); + m_physicsEntities.erase(entity); + m_physicsUpdateEntities.erase(entity); + m_staticEntities.erase(entity); + m_weaponUpdateEntities.erase(entity); - auto it = m_entitySlots.find(entity->GetId()); + auto it = m_entitySlots.find(entity); assert(it != m_entitySlots.end()); m_entitySlots.erase(it); } - void NetworkSyncSystem::OnUpdate(float /*elapsedTime*/) + void NetworkSyncSystem::Update(float /*elapsedTime*/) { if (!m_healthUpdateEntities.empty()) { m_healthEvents.clear(); - for (const auto& entity : m_healthUpdateEntities) + for (entt::entity entity : m_healthUpdateEntities) { + const auto& entityHealth = m_registry.get(entity); + const auto& entityNetwork = m_registry.get(entity); + EntityHealth& healthEvent = m_healthEvents.emplace_back(); - healthEvent.entityId = entity->GetId(); - healthEvent.currentHealth = entity->GetComponent().GetHealth(); + healthEvent.entityId = entityNetwork.GetNetworkId(); + healthEvent.currentHealth = entityHealth.GetHealth(); } - m_healthUpdateEntities.Clear(); + m_healthUpdateEntities.clear(); OnEntitiesHealthUpdate(this, m_healthEvents.data(), m_healthEvents.size()); } @@ -338,14 +354,17 @@ namespace bw { m_inputEvents.clear(); - for (const auto& entity : m_inputUpdateEntities) + for (entt::entity entity : m_inputUpdateEntities) { + const auto& entityInputs = m_registry.get(entity); + const auto& entityNetwork = m_registry.get(entity); + EntityInputs& inputEvent = m_inputEvents.emplace_back(); - inputEvent.entityId = entity->GetId(); - inputEvent.inputs = entity->GetComponent().GetInputs(); + inputEvent.entityId = entityNetwork.GetNetworkId(); + inputEvent.inputs = entityInputs.GetInputs(); } - m_inputUpdateEntities.Clear(); + m_inputUpdateEntities.clear(); OnEntitiesInputUpdate(this, m_inputEvents.data(), m_inputEvents.size()); } @@ -360,35 +379,36 @@ namespace bw OnEntityInvalidated(this, movementEvent); } - m_movedStaticEntities.Clear(); + m_movedStaticEntities.clear(); } if (!m_physicsUpdateEntities.empty()) { m_physicsEvent.clear(); - for (const auto& entity : m_physicsUpdateEntities) + for (entt::entity entity : m_physicsUpdateEntities) { + const auto& entityNetwork = m_registry.get(entity); + const auto& entityPhysics = m_registry.get(entity); + EntityPhysics& physicsEvent = m_physicsEvent.emplace_back(); - physicsEvent.entityId = entity->GetId(); + physicsEvent.entityId = entityNetwork.GetNetworkId(); - auto& entityPhysics = entity->GetComponent(); physicsEvent.isAsleep = entityPhysics.IsSleeping(); physicsEvent.mass = entityPhysics.GetMass(); physicsEvent.momentOfInertia = entityPhysics.GetMomentOfInertia(); - if (entity->HasComponent()) + if (PlayerMovementComponent* entityPlayerMovement = m_registry.try_get(entity)) { auto& playerMovementData = physicsEvent.playerMovement.emplace(); - auto& entityPlayerMovement = entity->GetComponent(); - playerMovementData.jumpHeight = entityPlayerMovement.GetJumpHeight(); - playerMovementData.jumpHeightBoost = entityPlayerMovement.GetJumpBoostHeight(); - playerMovementData.movementSpeed = entityPlayerMovement.GetMovementSpeed(); + playerMovementData.jumpHeight = entityPlayerMovement->GetJumpHeight(); + playerMovementData.jumpHeightBoost = entityPlayerMovement->GetJumpBoostHeight(); + playerMovementData.movementSpeed = entityPlayerMovement->GetMovementSpeed(); } } - m_physicsUpdateEntities.Clear(); + m_physicsUpdateEntities.clear(); OnEntitiesPhysicsUpdate(this, m_physicsEvent.data(), m_physicsEvent.size()); } @@ -397,16 +417,17 @@ namespace bw { m_scaleEvent.clear(); - for (const auto& entity : m_scaleUpdateEntities) + for (entt::entity entity : m_scaleUpdateEntities) { - auto& entityNode = entity->GetComponent(); + const auto& entityNetwork = m_registry.get(entity); + const auto& entityNode = m_registry.get(entity); EntityScale& scaleEvent = m_scaleEvent.emplace_back(); - scaleEvent.entityId = entity->GetId(); + scaleEvent.entityId = entityNetwork.GetNetworkId(); scaleEvent.newScale = entityNode.GetScale().y; } - m_scaleUpdateEntities.Clear(); + m_scaleUpdateEntities.clear(); OnEntitiesScaleUpdate(this, m_scaleEvent.data(), m_scaleEvent.size()); } @@ -415,24 +436,23 @@ namespace bw { m_weaponEvents.clear(); - for (const auto& entity : m_weaponUpdateEntities) + for (entt::entity entity : m_weaponUpdateEntities) { - auto& weaponWielder = entity->GetComponent(); + const auto& entityNetwork = m_registry.get(entity); + const auto& entityWeaponWielder = m_registry.get(entity); - std::size_t selectedWeapon = weaponWielder.GetSelectedWeapon(); + std::size_t selectedWeapon = entityWeaponWielder.GetSelectedWeapon(); EntityWeapon& weaponEvent = m_weaponEvents.emplace_back(); - weaponEvent.entityId = entity->GetId(); + weaponEvent.entityId = entityNetwork.GetNetworkId(); if (selectedWeapon != WeaponWielderComponent::NoWeapon) - weaponEvent.weaponId = weaponWielder.GetWeapon(selectedWeapon)->GetId(); + weaponEvent.weaponId = entityWeaponWielder.GetWeapon(selectedWeapon).get().GetNetworkId(); } - m_weaponUpdateEntities.Clear(); + m_weaponUpdateEntities.clear(); OnEntitiesWeaponUpdate(this, m_weaponEvents.data(), m_weaponEvents.size()); } } - - Ndk::SystemIndex NetworkSyncSystem::systemIndex; } diff --git a/src/CoreLib/Systems/PlayerMovementSystem.cpp b/src/CoreLib/Systems/PlayerMovementSystem.cpp index 7c5439d3..dc34b739 100644 --- a/src/CoreLib/Systems/PlayerMovementSystem.cpp +++ b/src/CoreLib/Systems/PlayerMovementSystem.cpp @@ -4,58 +4,62 @@ #include #include +#include +#include #include #include #include +#include namespace bw { - PlayerMovementSystem::PlayerMovementSystem(entt::registry& registry) + PlayerMovementSystem::PlayerMovementSystem(entt::registry& registry) : + m_controllerObserver(registry, entt::collector.group()), + m_registry(registry) { - //Requires(); - //SetUpdateOrder(50); //< Execute after physics but before rendering + m_inputDestroyConnection = registry.on_destroy().connect<&PlayerMovementSystem::OnInputDestroy>(this); + m_movementDestroyConnection = registry.on_destroy().connect<&PlayerMovementSystem::OnMovementDestroy>(this); + } + + PlayerMovementSystem::~PlayerMovementSystem() + { + m_inputDestroyConnection.release(); + m_movementDestroyConnection.release(); } - void PlayerMovementSystem::OnEntityAdded(Ndk::Entity* entity) + void PlayerMovementSystem::Update(float /*elapsedTime*/) { - /*Ndk::PhysicsComponent2D& entityPhys = entity->GetComponent(); - entityPhys.SetVelocityFunction([entity = entity->CreateHandle()](Nz::RigidBody2D& rigidBody, const Nz::Vector2f& gravity, float damping, float dt) + m_controllerObserver.each([&](entt::entity entity) { - auto& movementComponent = entity->GetComponent(); + assert(m_inputControlledEntities.find(entity) == m_inputControlledEntities.end()); - const auto& controller = movementComponent.GetController(); - if (controller) + auto& entityPhys = m_registry.get(entity); + entityPhys.SetVelocityFunction([handle = entt::handle(m_registry, entity)](Nz::RigidBody2D& rigidBody, const Nz::Vector2f& gravity, float damping, float dt) { - auto& inputComponent = entity->GetComponent(); - const auto& inputs = inputComponent.GetInputs(); - - controller->UpdateVelocity(inputs, movementComponent, rigidBody, gravity, damping, dt); - } - else - rigidBody.UpdateVelocity(gravity, damping, dt); - });*/ - } + auto& movementComponent = handle.get(); - void PlayerMovementSystem::OnEntityRemoved(Ndk::Entity* entity) - { - /*if (!entity->HasComponent()) - return; + const auto& controller = movementComponent.GetController(); + if (controller) + { + auto& inputComponent = handle.get(); + const auto& inputs = inputComponent.GetInputs(); - Ndk::PhysicsComponent2D& entityPhys = entity->GetComponent(); - if (!entityPhys.IsValid()) - return; + controller->UpdateVelocity(inputs, movementComponent, rigidBody, gravity, damping, dt); + } + else + rigidBody.UpdateVelocity(gravity, damping, dt); + }); - entityPhys.ResetVelocityFunction();*/ - } + m_inputControlledEntities.emplace(entity); + }); - void PlayerMovementSystem::OnUpdate(float /*elapsedTime*/) - { - /*for (entt::entity entity : GetEntities()) + auto view = m_registry.view(); + for (entt::entity entity : view) { - auto& inputComponent = entity->GetComponent(); - auto& playerMovement = entity->GetComponent(); - auto& nodeComponent = entity->GetComponent(); - auto& entityPhys = entity->GetComponent(); + auto& inputComponent = view.get(entity); + auto& playerMovement = view.get(entity); + auto& nodeComponent = view.get(entity); + auto& entityPhys = view.get(entity); const auto& inputs = inputComponent.GetInputs(); @@ -74,6 +78,30 @@ namespace bw if (playerMovement.UpdateFacingRightState(inputs.isLookingRight)) nodeComponent.Scale(-1.f, 1.f); - }*/ + } + } + + void PlayerMovementSystem::OnMovementDestroy(entt::registry& registry, entt::entity entity) + { + auto it = m_inputControlledEntities.find(entity); + if (it == m_inputControlledEntities.end()) + return; + + auto& entityPhys = registry.get(entity); + entityPhys.ResetVelocityFunction(); + + m_inputControlledEntities.erase(it); + } + + void PlayerMovementSystem::OnInputDestroy(entt::registry& registry, entt::entity entity) + { + auto it = m_inputControlledEntities.find(entity); + if (it == m_inputControlledEntities.end()) + return; + + auto& entityPhys = registry.get(entity); + entityPhys.ResetVelocityFunction(); + + m_inputControlledEntities.erase(it); } } diff --git a/src/CoreLib/Systems/TickCallbackSystem.cpp b/src/CoreLib/Systems/TickCallbackSystem.cpp index c8b9bd32..053da5b1 100644 --- a/src/CoreLib/Systems/TickCallbackSystem.cpp +++ b/src/CoreLib/Systems/TickCallbackSystem.cpp @@ -6,36 +6,44 @@ #include #include #include +#include namespace bw { - TickCallbackSystem::TickCallbackSystem(SharedMatch& match) : + TickCallbackSystem::TickCallbackSystem(entt::registry& registry, SharedMatch& match) : + m_registry(registry), + m_scriptObserver(registry, entt::collector.update()), m_match(match) { - Requires(); - SetMaximumUpdateRate(0); + m_scriptDestroyConnection = m_registry.on_destroy().connect<&TickCallbackSystem::OnScriptDestroy>(this); } - void TickCallbackSystem::OnEntityRemoved(Ndk::Entity* entity) + TickCallbackSystem::~TickCallbackSystem() { - m_tickableEntities.Remove(entity); + m_scriptDestroyConnection.release(); } - void TickCallbackSystem::OnEntityValidation(Ndk::Entity* entity, bool /*justAdded*/) + void TickCallbackSystem::OnScriptDestroy(entt::registry& registry, entt::entity entity) { - auto& scriptComponent = entity->GetComponent(); + assert(&m_registry == ®istry); - if (scriptComponent.HasCallbacks(ElementEvent::Tick)) - m_tickableEntities.Insert(entity); - else - m_tickableEntities.Remove(entity); + m_tickableEntities.erase(entity); } - void TickCallbackSystem::OnUpdate(float elapsedTime) + void TickCallbackSystem::Update(float elapsedTime) { + for (entt::entity entity : m_scriptObserver) + { + auto& scriptComponent = m_registry.get(entity); + if (scriptComponent.HasCallbacks(ElementEvent::Tick)) + m_tickableEntities.emplace(entity); + else + m_tickableEntities.erase(entity); + } + for (entt::entity entity : m_tickableEntities) { - auto& scriptComponent = entity->GetComponent(); + auto& scriptComponent = m_registry.get(entity); if (!scriptComponent.CanTriggerTick(elapsedTime)) // #include #include -#include +#include namespace bw { - WeaponSystem::WeaponSystem(SharedMatch& match) : - m_match(match) + void WeaponSystem::Update(float /*elapsedTime*/) { - Requires(); - SetMaximumUpdateRate(0); - } - - void WeaponSystem::OnUpdate(float /*elapsedTime*/) - { - for (entt::entity weapon : GetEntities()) + auto view = m_registry.view(); + for (entt::entity weapon : view) { - auto& weaponComponent = weapon->GetComponent(); + auto& weaponComponent = view.get(weapon); if (!weaponComponent.IsActive()) continue; - if (entt::entity owner = weaponComponent.GetOwner()) + if (entt::entity owner = weaponComponent.GetOwner(); owner != entt::null) { - InputComponent& ownerInputs = owner->GetComponent(); - Ndk::NodeComponent& ownerNode = owner->GetComponent(); - Ndk::NodeComponent& weaponNode = weapon->GetComponent(); + InputComponent& ownerInputs = m_registry.get(owner); + Nz::NodeComponent& ownerNode = view.get(owner); + Nz::NodeComponent& weaponNode = view.get(weapon); const auto& inputs = ownerInputs.GetInputs(); const auto& previousInputs = ownerInputs.GetPreviousInputs(); @@ -59,10 +53,10 @@ namespace bw if (isAttacking) { - auto& weaponCooldown = weapon->GetComponent(); + auto& weaponCooldown = view.get(weapon); if (weaponCooldown.Trigger(m_match.GetCurrentTime())) { - auto& weaponScript = weapon->GetComponent(); + auto& weaponScript = view.get(weapon); weaponScript.ExecuteCallback(weaponScript.GetTable()); weaponComponent.SetAttacking(true); @@ -70,7 +64,7 @@ namespace bw } else if (!inputs.isAttacking && weaponComponent.IsAttacking()) { - auto& weaponScript = weapon->GetComponent(); + auto& weaponScript = view.get(weapon); weaponScript.ExecuteCallback(weaponScript.GetTable()); weaponComponent.SetAttacking(false); @@ -79,5 +73,4 @@ namespace bw } } - Ndk::SystemIndex WeaponSystem::systemIndex; } diff --git a/src/CoreLib/Terrain.cpp b/src/CoreLib/Terrain.cpp index 5412d9e9..6b2528ff 100644 --- a/src/CoreLib/Terrain.cpp +++ b/src/CoreLib/Terrain.cpp @@ -12,26 +12,26 @@ namespace bw { m_layers.reserve(m_map.GetLayerCount()); for (LayerIndex layerIndex = 0; layerIndex < m_map.GetLayerCount(); ++layerIndex) - m_layers.emplace_back(match, LayerIndex(layerIndex), m_map.GetLayer(layerIndex)); + m_layers.emplace_back(std::make_unique(match, LayerIndex(layerIndex), m_map.GetLayer(layerIndex))); } void Terrain::Initialize() { - for (TerrainLayer& layer : m_layers) - layer.InitializeEntities(); + for (auto& layerPtr : m_layers) + layerPtr->InitializeEntities(); } void Terrain::Reset() { - for (TerrainLayer& layer : m_layers) - layer.ResetEntities(); + for (auto& layerPtr : m_layers) + layerPtr->ResetEntities(); Initialize(); } void Terrain::Update(float elapsedTime) { - for (TerrainLayer& layer : m_layers) - layer.TickUpdate(elapsedTime); + for (auto& layerPtr : m_layers) + layerPtr->TickUpdate(elapsedTime); } } diff --git a/src/CoreLib/TerrainLayer.cpp b/src/CoreLib/TerrainLayer.cpp index 6b382980..f0a7962e 100644 --- a/src/CoreLib/TerrainLayer.cpp +++ b/src/CoreLib/TerrainLayer.cpp @@ -11,8 +11,6 @@ #include #include #include -#include -#include namespace bw { @@ -20,8 +18,8 @@ namespace bw SharedLayer(match, layerIndex), m_mapLayer(layerData) { - Ndk::World& world = GetWorld(); - world.AddSystem(*this); + Nz::SystemGraph& systemGraph = GetSystemGraph(); + systemGraph.AddSystem(*this); ResetEntities(); } @@ -35,8 +33,8 @@ namespace bw { Match& match = GetMatch(); - Ndk::World& world = GetWorld(); - world.Clear(); + entt::registry& world = GetWorld(); + world.clear(); auto& entityStore = match.GetEntityStore(); for (const Map::Entity& entityData : m_mapLayer.entities) @@ -50,7 +48,7 @@ namespace bw try { - entt::entity entity = entityStore.CreateEntity(*this, entityTypeIndex, entityData.uniqueId, entityData.position, entityData.rotation, entityData.properties); + entt::handle entity = entityStore.CreateEntity(*this, entityTypeIndex, entityData.uniqueId, entityData.position, entityData.rotation, entityData.properties); if (entity) match.RegisterEntity(entityData.uniqueId, entity); } @@ -64,13 +62,11 @@ namespace bw void TerrainLayer::InitializeEntities() { auto& entityStore = GetMatch().GetEntityStore(); - for (entt::entity entity : GetWorld().GetEntities()) + entt::registry& registry = GetWorld(); + GetWorld().each([&](entt::entity entity) { - if (!entityStore.InitializeEntity(entity)) - entity->Kill(); - } - - Ndk::World& world = GetWorld(); - world.Refresh(); + if (!entityStore.InitializeEntity(entt::handle(registry, entity))) + registry.destroy(entity); + }); } } diff --git a/src/MapEditor/Enums.hpp b/src/MapEditor/Enums.hpp index b7043dbb..9b5a84d5 100644 --- a/src/MapEditor/Enums.hpp +++ b/src/MapEditor/Enums.hpp @@ -7,7 +7,7 @@ #ifndef BURGWAR_MAPEDITOR_ENUMS_HPP #define BURGWAR_MAPEDITOR_ENUMS_HPP -#include +#include namespace bw { diff --git a/src/MapEditor/Gizmos/EditorGizmo.cpp b/src/MapEditor/Gizmos/EditorGizmo.cpp index af462586..84209b37 100644 --- a/src/MapEditor/Gizmos/EditorGizmo.cpp +++ b/src/MapEditor/Gizmos/EditorGizmo.cpp @@ -8,11 +8,11 @@ #include #include #include -#include +#include namespace bw { - EditorGizmo::EditorGizmo(Ndk::World& renderWorld, std::vector entities) : + EditorGizmo::EditorGizmo(entt::registry& renderWorld, std::vector entities) : m_targetEntities(std::move(entities)) { m_selectionOverlayEntity = renderWorld.CreateEntity(); @@ -46,7 +46,7 @@ namespace bw Nz::Vector3f origin = globalAABB.GetCenter(); - auto& node = m_selectionOverlayEntity->GetComponent(); + auto& node = m_selectionOverlayentity.get(); node.SetPosition(origin); auto& gfx = m_selectionOverlayEntity->GetComponent(); diff --git a/src/MapEditor/Gizmos/EditorGizmo.hpp b/src/MapEditor/Gizmos/EditorGizmo.hpp index 802c5e96..febc7846 100644 --- a/src/MapEditor/Gizmos/EditorGizmo.hpp +++ b/src/MapEditor/Gizmos/EditorGizmo.hpp @@ -17,7 +17,7 @@ namespace bw class EditorGizmo { public: - EditorGizmo(Ndk::World& renderWorld, std::vector entities); + EditorGizmo(entt::registry& renderWorld, std::vector entities); virtual ~EditorGizmo(); inline entt::entity GetSelectionOverlayEntity() const; diff --git a/src/MapEditor/Gizmos/PositionGizmo.cpp b/src/MapEditor/Gizmos/PositionGizmo.cpp index fac5db3c..85cfd3a6 100644 --- a/src/MapEditor/Gizmos/PositionGizmo.cpp +++ b/src/MapEditor/Gizmos/PositionGizmo.cpp @@ -7,12 +7,12 @@ #include #include #include -#include +#include #include namespace bw { - PositionGizmo::PositionGizmo(Camera& camera, Ndk::World& renderWorld, std::vector entities, const Nz::Vector2f& positionAlignment) : + PositionGizmo::PositionGizmo(Camera& camera, entt::registry& renderWorld, std::vector entities, const Nz::Vector2f& positionAlignment) : EditorGizmo(renderWorld, std::move(entities)), m_camera(camera), m_hoveredAction(MovementType::None), @@ -168,7 +168,7 @@ namespace bw Nz::Vector2f newPosition = ComputeNewPosition(mouseMoved.x, mouseMoved.y); entt::entity selectionOverlayEntity = GetSelectionOverlayEntity(); - auto& node = selectionOverlayEntity->GetComponent(); + auto& node = selectionOverlayentity.get(); node.SetPosition(newPosition); const std::vector& targetEntities = GetTargetEntities(); diff --git a/src/MapEditor/Gizmos/PositionGizmo.hpp b/src/MapEditor/Gizmos/PositionGizmo.hpp index 7816add9..776acd61 100644 --- a/src/MapEditor/Gizmos/PositionGizmo.hpp +++ b/src/MapEditor/Gizmos/PositionGizmo.hpp @@ -21,7 +21,7 @@ namespace bw class PositionGizmo : public EditorGizmo { public: - PositionGizmo(Camera& camera, Ndk::World& renderWorld, std::vector entities, const Nz::Vector2f& positionAlignment); + PositionGizmo(Camera& camera, entt::registry& renderWorld, std::vector entities, const Nz::Vector2f& positionAlignment); ~PositionGizmo() = default; bool OnMouseButtonPressed(const Nz::WindowEvent::MouseButtonEvent& mouseButton) override; diff --git a/src/MapEditor/Logic/TileMapEditorMode.cpp b/src/MapEditor/Logic/TileMapEditorMode.cpp index bda075e5..4643fa03 100644 --- a/src/MapEditor/Logic/TileMapEditorMode.cpp +++ b/src/MapEditor/Logic/TileMapEditorMode.cpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include @@ -255,7 +255,7 @@ namespace bw { m_tileSelectionEntity->Enable(); - auto& node = m_tileSelectionEntity->GetComponent(); + auto& node = m_tileSelectionentity.get(); node.SetPosition(Nz::Vector2f(*tilePosition) * m_tilemapData.tileSize + m_tilemapData.origin); std::size_t selectionWidth = std::min(m_tilemapData.mapSize.x - tilePosition->x, m_selection.width); diff --git a/src/MapEditor/Scripting/EditorElementLibrary.cpp b/src/MapEditor/Scripting/EditorElementLibrary.cpp index fbefc713..3fc62ec6 100644 --- a/src/MapEditor/Scripting/EditorElementLibrary.cpp +++ b/src/MapEditor/Scripting/EditorElementLibrary.cpp @@ -19,16 +19,16 @@ namespace bw elementMetatable["GetLayerIndex"] = LuaFunction([](const sol::table& entityTable) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); - return entity->GetComponent().GetLayerIndex(); + return entity.get().GetLayerIndex(); }); elementMetatable["GetProperty"] = LuaFunction([](sol::this_state s, const sol::table& table, const std::string& propertyName) -> sol::object { - entt::entity entity = AssertScriptEntity(table); + entt::handle entity = AssertScriptEntity(table); - auto& entityScript = entity->GetComponent(); + auto& entityScript = entity.get(); auto propertyVal = entityScript.GetProperty(propertyName); if (propertyVal.has_value()) diff --git a/src/MapEditor/Scripting/EditorEntityLibrary.cpp b/src/MapEditor/Scripting/EditorEntityLibrary.cpp index 48a4a971..08078bbf 100644 --- a/src/MapEditor/Scripting/EditorEntityLibrary.cpp +++ b/src/MapEditor/Scripting/EditorEntityLibrary.cpp @@ -31,7 +31,7 @@ namespace bw elementMetatable["AddLayer"] = LuaFunction([&](sol::this_state L, const sol::table& entityTable, const sol::table& parameters) { - entt::entity entity = AssertScriptEntity(entityTable); + entt::handle entity = AssertScriptEntity(entityTable); MapCanvas& mapCanvas = *m_editorWindow.GetMapCanvas(); diff --git a/src/MapEditor/Scripting/EditorEntityStore.cpp b/src/MapEditor/Scripting/EditorEntityStore.cpp index 51eb6434..9c11ac8f 100644 --- a/src/MapEditor/Scripting/EditorEntityStore.cpp +++ b/src/MapEditor/Scripting/EditorEntityStore.cpp @@ -11,7 +11,7 @@ namespace bw { - std::optional EditorEntityStore::Instantiate(LayerIndex layerIndex, Ndk::World& world, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, entt::entity parent) const + std::optional EditorEntityStore::Instantiate(LayerIndex layerIndex, entt::registry& world, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, entt::entity parent) const { entt::entity entity = ClientEditorEntityStore::InstantiateEntity(world, entityIndex, position, rotation, scale, std::move(properties), parent); if (!entity) diff --git a/src/MapEditor/Scripting/EditorEntityStore.hpp b/src/MapEditor/Scripting/EditorEntityStore.hpp index d0a5357e..13e45bee 100644 --- a/src/MapEditor/Scripting/EditorEntityStore.hpp +++ b/src/MapEditor/Scripting/EditorEntityStore.hpp @@ -20,7 +20,7 @@ namespace bw inline EditorEntityStore(MapCanvas& mapCanvas, ClientAssetStore& assetStore, const Logger& logger, std::shared_ptr context); ~EditorEntityStore() = default; - std::optional Instantiate(LayerIndex layerIndex, Ndk::World& world, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, entt::entity parent = entt::null) const; + std::optional Instantiate(LayerIndex layerIndex, entt::registry& world, std::size_t entityIndex, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, entt::entity parent = entt::null) const; private: void BindCallbacks(const ScriptedEntity& entityClass, entt::entity entity) const override; diff --git a/src/MapEditor/Widgets/EditorWindow.cpp b/src/MapEditor/Widgets/EditorWindow.cpp index e00c18b8..f928a410 100644 --- a/src/MapEditor/Widgets/EditorWindow.cpp +++ b/src/MapEditor/Widgets/EditorWindow.cpp @@ -21,7 +21,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/MapEditor/Widgets/EntityInfoDialog.hpp b/src/MapEditor/Widgets/EntityInfoDialog.hpp index b4af0caf..b21b9ee5 100644 --- a/src/MapEditor/Widgets/EntityInfoDialog.hpp +++ b/src/MapEditor/Widgets/EntityInfoDialog.hpp @@ -7,7 +7,7 @@ #ifndef BURGWAR_MAPEDITOR_WIDGETS_ENTITYINFODIALOG_HPP #define BURGWAR_MAPEDITOR_WIDGETS_ENTITYINFODIALOG_HPP -#include +#include #include #include #include diff --git a/src/MapEditor/Widgets/MapCanvas.cpp b/src/MapEditor/Widgets/MapCanvas.cpp index c1c01d39..d53ae8a4 100644 --- a/src/MapEditor/Widgets/MapCanvas.cpp +++ b/src/MapEditor/Widgets/MapCanvas.cpp @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include #include #include @@ -35,7 +35,7 @@ namespace bw m_editor(editor), m_isPhysicsDebugDrawEnabled(false) { - Ndk::World& world = GetWorld(); + entt::registry& world = GetWorld(); world.AddSystem(); world.AddSystem(); @@ -568,7 +568,7 @@ namespace bw auto& gfxComponent = m_gridEntity->GetComponent(); gfxComponent.Clear(); - auto& nodeComponent = m_gridEntity->GetComponent(); + auto& nodeComponent = m_gridentity.get(); nodeComponent.SetPosition(camPos); auto AddGrid = [&](float lineWidth, float gridSize, Nz::Color color, int renderOrder) diff --git a/src/MapEditor/Widgets/MapCanvasLayer.cpp b/src/MapEditor/Widgets/MapCanvasLayer.cpp index cf93459a..a2ee76c4 100644 --- a/src/MapEditor/Widgets/MapCanvasLayer.cpp +++ b/src/MapEditor/Widgets/MapCanvasLayer.cpp @@ -6,7 +6,7 @@ #include #include #include -#include +#include namespace bw { diff --git a/src/MapEditor/Widgets/PlayWindow.cpp b/src/MapEditor/Widgets/PlayWindow.cpp index 46a1efed..1f33350a 100644 --- a/src/MapEditor/Widgets/PlayWindow.cpp +++ b/src/MapEditor/Widgets/PlayWindow.cpp @@ -9,7 +9,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/MapEditor/Widgets/PlayWindow.hpp b/src/MapEditor/Widgets/PlayWindow.hpp index a628b55b..469b57e9 100644 --- a/src/MapEditor/Widgets/PlayWindow.hpp +++ b/src/MapEditor/Widgets/PlayWindow.hpp @@ -30,7 +30,7 @@ namespace bw void resizeEvent(QResizeEvent* event) override; - Ndk::World m_world; + entt::registry m_world; Ndk::Canvas m_canvas; std::optional m_clientMatch; std::optional m_match; diff --git a/src/MapEditor/Widgets/ScrollCanvas.cpp b/src/MapEditor/Widgets/ScrollCanvas.cpp index b0f30a26..79671343 100644 --- a/src/MapEditor/Widgets/ScrollCanvas.cpp +++ b/src/MapEditor/Widgets/ScrollCanvas.cpp @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include #include @@ -63,12 +63,12 @@ namespace bw return m_canvas->GetCamera(); } - Ndk::World& ScrollCanvas::GetWorld() + entt::registry& ScrollCanvas::GetWorld() { return m_canvas->GetWorld(); } - const Ndk::World& ScrollCanvas::GetWorld() const + const entt::registry& ScrollCanvas::GetWorld() const { return m_canvas->GetWorld(); } diff --git a/src/MapEditor/Widgets/ScrollCanvas.hpp b/src/MapEditor/Widgets/ScrollCanvas.hpp index b85c4323..df4e0b6d 100644 --- a/src/MapEditor/Widgets/ScrollCanvas.hpp +++ b/src/MapEditor/Widgets/ScrollCanvas.hpp @@ -31,8 +31,8 @@ namespace bw Camera& GetCamera(); const Camera& GetCamera() const; - Ndk::World& GetWorld(); - const Ndk::World& GetWorld() const; + entt::registry& GetWorld(); + const entt::registry& GetWorld() const; inline WorldCanvas* GetWorldCanvas(); inline const WorldCanvas* GetWorldCanvas() const; diff --git a/src/MapEditor/Widgets/TileSelectionWidget.cpp b/src/MapEditor/Widgets/TileSelectionWidget.cpp index d8d9762e..c01f6f29 100644 --- a/src/MapEditor/Widgets/TileSelectionWidget.cpp +++ b/src/MapEditor/Widgets/TileSelectionWidget.cpp @@ -9,7 +9,7 @@ #include #include #include -#include +#include #include #include #include @@ -190,7 +190,7 @@ namespace bw Nz::Vector2f firstPosition = Nz::Vector2f(firstX, firstY) * m_tileSize; Nz::Vector2f lastPosition = Nz::Vector2f(lastX, lastY) * m_tileSize; - auto& selectedEntityNode = m_selectedEntity->GetComponent(); + auto& selectedEntityNode = m_selectedentity.get(); selectedEntityNode.SetPosition(firstPosition); m_selectedSprite->SetSize(lastPosition - firstPosition + m_tileSize); @@ -333,7 +333,7 @@ namespace bw Nz::Vector2f lastPosition = Nz::Vector2f(lastX, lastY) * m_tileSize; m_selectionEntity->Enable(); - auto& selectionEntityNode = m_selectionEntity->GetComponent(); + auto& selectionEntityNode = m_selectionentity.get(); selectionEntityNode.SetPosition(firstPosition); m_selectionSprite->SetSize(lastPosition - firstPosition + m_tileSize); }; @@ -350,7 +350,7 @@ namespace bw Nz::Vector2f firstPosition = Nz::Vector2f(selectionLastRect % currentGroup.mapSize.x, selectionLastRect / currentGroup.mapSize.x) * m_tileSize; m_selectionEntity->Enable(); - auto& selectionEntityNode = m_selectionEntity->GetComponent(); + auto& selectionEntityNode = m_selectionentity.get(); selectionEntityNode.SetPosition(firstPosition); m_selectionSprite->SetSize(m_tileSize); } diff --git a/src/MapEditor/Widgets/WorldCanvas.cpp b/src/MapEditor/Widgets/WorldCanvas.cpp index 7afff89b..c01b7179 100644 --- a/src/MapEditor/Widgets/WorldCanvas.cpp +++ b/src/MapEditor/Widgets/WorldCanvas.cpp @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/MapEditor/Widgets/WorldCanvas.hpp b/src/MapEditor/Widgets/WorldCanvas.hpp index edb48076..b8fcae24 100644 --- a/src/MapEditor/Widgets/WorldCanvas.hpp +++ b/src/MapEditor/Widgets/WorldCanvas.hpp @@ -28,8 +28,8 @@ namespace bw inline const CameraMovement& GetCameraController() const; inline Camera& GetCamera(); inline const Camera& GetCamera() const; - inline Ndk::World& GetWorld(); - inline const Ndk::World& GetWorld() const; + inline entt::registry& GetWorld(); + inline const entt::registry& GetWorld() const; void UpdateBackgroundColor(Nz::Color color); @@ -51,7 +51,7 @@ namespace bw private: std::optional m_cameraMovement; Nz::Color m_backgroundColor; - Ndk::World m_world; + entt::registry m_world; Camera m_camera; }; } diff --git a/src/MapEditor/Widgets/WorldCanvas.inl b/src/MapEditor/Widgets/WorldCanvas.inl index f34e8394..a7a9bd39 100644 --- a/src/MapEditor/Widgets/WorldCanvas.inl +++ b/src/MapEditor/Widgets/WorldCanvas.inl @@ -26,12 +26,12 @@ namespace bw return m_camera; } - inline Ndk::World& WorldCanvas::GetWorld() + inline entt::registry& WorldCanvas::GetWorld() { return m_world; } - inline const Ndk::World& WorldCanvas::GetWorld() const + inline const entt::registry& WorldCanvas::GetWorld() const { return m_world; } diff --git a/xmake-repo/packages/n/nazaraengine/xmake.lua b/xmake-repo/packages/n/nazaraengine/xmake.lua index 6a53b656..364c644a 100644 --- a/xmake-repo/packages/n/nazaraengine/xmake.lua +++ b/xmake-repo/packages/n/nazaraengine/xmake.lua @@ -8,6 +8,8 @@ package("nazaraengine") add_versions("2021.06.10", "4989fbe2d28aa37dc11d24bdcc395431932a2f11") add_versions("2021.04.01", "aef225d8784396035e1f92a029a685e654320e73") + add_deps("nzsl") + add_configs("audio", {description = "Includes the audio module", default = true, type = "boolean"}) add_configs("graphics", {description = "Includes the graphics module", default = true, type = "boolean"}) add_configs("network", {description = "Includes the network module", default = true, type = "boolean"}) diff --git a/xmake.lua b/xmake.lua index b111fbc0..134690ec 100644 --- a/xmake.lua +++ b/xmake.lua @@ -186,7 +186,7 @@ target("ClientLib") add_headerfiles("include/(ClientLib/**.hpp)", "include/(ClientLib/**.inl)") add_headerfiles("src/ClientLib/**.hpp", "src/ClientLib/**.inl") add_files("src/ClientLib/**.cpp") - add_packages("nzsl", "nazara", { public = true }) + add_packages("nazarautils", "nzsl", "nazara", { public = true }) target("Main") set_group("Common") From ac4b7018e016f0bddc3b17b27ad4472a478fdd80 Mon Sep 17 00:00:00 2001 From: SirLynix Date: Tue, 2 Aug 2022 08:45:09 +0200 Subject: [PATCH 07/17] WIP --- include/ClientLib/Camera.hpp | 7 +- include/ClientLib/Chatbox.hpp | 21 ++--- include/ClientLib/ClientAssetStore.hpp | 12 +-- include/ClientLib/ClientConsole.hpp | 2 +- include/ClientLib/ClientLayerEntity.hpp | 2 +- include/ClientLib/ClientLayerSound.hpp | 4 +- include/ClientLib/ClientMatch.hpp | 2 +- .../Components/SoundEmitterComponent.hpp | 2 +- include/ClientLib/Console.hpp | 7 +- include/ClientLib/Console.inl | 3 +- include/ClientLib/EscapeMenu.hpp | 4 +- include/ClientLib/LayerVisualEntity.hpp | 24 ++--- include/ClientLib/LayerVisualEntity.inl | 8 +- include/ClientLib/OptionWidget.hpp | 8 +- include/ClientLib/Scoreboard.hpp | 6 +- include/ClientLib/Scripting/ParticleGroup.hpp | 2 +- include/ClientLib/Scripting/Texture.hpp | 4 +- include/ClientLib/Scripting/Texture.inl | 2 +- include/ClientLib/SoundEntity.hpp | 4 +- include/ClientLib/Systems/SoundSystem.hpp | 2 +- include/ClientLib/VisualEntity.hpp | 22 ++--- include/CoreLib/AssetStore.inl | 2 +- include/CoreLib/EntityOwner.hpp | 2 +- include/CoreLib/Scripting/ScriptStore.inl | 15 ++- .../CoreLib/Scripting/ScriptingContext.hpp | 1 - src/Client/States/BackgroundState.cpp | 2 +- src/Client/States/BackgroundState.hpp | 2 +- .../States/Game/AuthenticationState.hpp | 2 +- src/Client/States/Game/CancelableState.hpp | 2 +- src/Client/States/Game/ConnectedState.hpp | 2 +- .../States/Game/ConnectionLostState.cpp | 2 +- src/Client/States/Game/ConnectionState.hpp | 2 +- .../States/Game/ResourceDownloadState.hpp | 2 +- src/Client/States/Game/StatusState.hpp | 2 +- src/Client/States/JoinServerState.cpp | 6 +- src/Client/States/MainMenuState.cpp | 6 +- src/Client/States/StartServerState.cpp | 6 +- src/ClientLib/Camera.cpp | 92 +++++++++++-------- src/ClientLib/Chatbox.cpp | 29 +++--- src/ClientLib/ClientAssetStore.cpp | 17 ++-- src/ClientLib/ClientConsole.cpp | 2 +- src/ClientLib/ClientEditorApp.cpp | 23 +---- src/ClientLib/ClientEditorApp.hpp | 3 +- src/ClientLib/ClientLayerSound.cpp | 2 +- .../Components/SoundEmitterComponent.cpp | 2 +- src/ClientLib/Console.cpp | 22 ++--- src/ClientLib/LayerVisualEntity.cpp | 14 +-- .../ClientEditorScriptingLibrary.cpp | 2 +- .../Scripting/ClientElementLibrary.cpp | 4 +- .../Scripting/ClientScriptingLibrary.cpp | 2 +- src/ClientLib/SoundEntity.cpp | 2 +- src/ClientLib/Systems/SoundSystem.cpp | 2 +- src/ClientLib/VisualEntity.cpp | 18 ++-- src/CoreLib/Match.cpp | 2 +- src/CoreLib/Player.cpp | 2 - src/CoreLib/Scripting/ScriptingContext.cpp | 24 +---- src/CoreLib/Scripting/ServerEntityLibrary.cpp | 5 + src/CoreLib/Scripting/SharedEntityLibrary.cpp | 5 + .../Scripting/SharedScriptingLibrary.cpp | 10 +- src/CoreLib/SharedLayer.cpp | 5 +- src/CoreLib/Systems/WeaponSystem.cpp | 2 +- src/MapEditor/Gizmos/EditorGizmo.cpp | 6 +- src/MapEditor/Gizmos/EditorGizmo.hpp | 4 +- src/MapEditor/Logic/EntityEditorMode.cpp | 4 +- src/MapEditor/Logic/TileMapEditorMode.hpp | 2 +- src/MapEditor/Widgets/TileSelectionWidget.hpp | 2 +- src/Server/ServerApp.cpp | 11 ++- src/Server/ServerApp.hpp | 6 +- src/Server/main.cpp | 5 +- xmake-repo/packages/n/nazaraengine/xmake.lua | 9 ++ xmake-requires.lock | 69 ++++++++------ xmake.lua | 4 +- 72 files changed, 320 insertions(+), 297 deletions(-) diff --git a/include/ClientLib/Camera.hpp b/include/ClientLib/Camera.hpp index 84d498f7..715bfd36 100644 --- a/include/ClientLib/Camera.hpp +++ b/include/ClientLib/Camera.hpp @@ -13,7 +13,7 @@ #include #include #include -#include +#include namespace bw { @@ -24,7 +24,7 @@ namespace bw class BURGWAR_CLIENTLIB_API Camera : public Nz::HandledObject { public: - Camera(entt::registry& world, Nz::RenderTarget* renderTarget, bool perspective); + Camera(entt::registry& registry, Nz::RenderTarget* renderTarget, bool perspective); Camera(const Camera&) = delete; Camera(Camera&&) = delete; ~Camera() = default; @@ -59,10 +59,11 @@ namespace bw private: void UpdateProjection(); void UpdateZoomFactor(); + void UpdateZoomFactor(const Nz::Vector2ui& newRenderTargetSize); NazaraSlot(Nz::RenderTarget, OnRenderTargetSizeChange, m_onTargetSizeChanged); - Ndk::EntityOwner m_cameraEntity; + EntityOwner m_cameraEntity; bool m_isPerspective; float m_projectedDepth; float m_invFovTan; diff --git a/include/ClientLib/Chatbox.hpp b/include/ClientLib/Chatbox.hpp index ba36aad4..3dbbeff9 100644 --- a/include/ClientLib/Chatbox.hpp +++ b/include/ClientLib/Chatbox.hpp @@ -10,12 +10,11 @@ #include #include #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include namespace bw @@ -37,7 +36,7 @@ namespace bw using Item = std::variant; - Chatbox(const Logger& logger, Nz::RenderTarget* rt, Ndk::Canvas* canvas); + Chatbox(const Logger& logger, Nz::RenderTarget* rt, Nz::Canvas* canvas); Chatbox(const Chatbox&) = delete; Chatbox(Chatbox&&) = delete; ~Chatbox(); @@ -60,15 +59,15 @@ namespace bw NazaraSignal(OnChatMessage, const std::string& /*message*/); private: - void OnRenderTargetSizeChange(const Nz::RenderTarget* renderTarget); + void OnRenderTargetSizeChange(const Nz::RenderTarget* renderTarget, const Nz::Vector2ui& newSize); void Refresh(); NazaraSlot(Nz::RenderTarget, OnRenderTargetSizeChange, m_onTargetChangeSizeSlot); std::vector> m_chatLines; - Ndk::ScrollAreaWidget* m_chatboxScrollArea; - Ndk::RichTextAreaWidget* m_chatBox; - Ndk::TextAreaWidget* m_chatEnteringBox; + Nz::RichTextAreaWidget* m_chatBox; + Nz::ScrollAreaWidget* m_chatboxScrollArea; + Nz::TextAreaWidget* m_chatEnteringBox; const Logger& m_logger; }; } diff --git a/include/ClientLib/ClientAssetStore.hpp b/include/ClientLib/ClientAssetStore.hpp index 56aa3009..0db5f1f1 100644 --- a/include/ClientLib/ClientAssetStore.hpp +++ b/include/ClientLib/ClientAssetStore.hpp @@ -23,14 +23,14 @@ namespace bw void Clear() override; - const Nz::ModelRef& GetModel(const std::string& modelPath) const; - const Nz::SoundBufferRef& GetSoundBuffer(const std::string& soundPath) const; - const Nz::TextureRef& GetTexture(const std::string& texturePath) const; + const std::shared_ptr& GetModel(const std::string& modelPath) const; + const std::shared_ptr& GetSoundBuffer(const std::string& soundPath) const; + const std::shared_ptr& GetTexture(const std::string& texturePath) const; private: - mutable tsl::hopscotch_map m_models; - mutable tsl::hopscotch_map m_soundBuffers; - mutable tsl::hopscotch_map m_textures; + mutable tsl::hopscotch_map> m_models; + mutable tsl::hopscotch_map> m_soundBuffers; + mutable tsl::hopscotch_map> m_textures; }; } diff --git a/include/ClientLib/ClientConsole.hpp b/include/ClientLib/ClientConsole.hpp index 2eba846a..9b8a5f00 100644 --- a/include/ClientLib/ClientConsole.hpp +++ b/include/ClientLib/ClientConsole.hpp @@ -20,7 +20,7 @@ namespace bw class BURGWAR_CLIENTLIB_API ClientConsole : public Console { public: - ClientConsole(const Logger& logger, Nz::RenderTarget* window, Ndk::Canvas* canvas, std::shared_ptr scriptingLibrary, const std::shared_ptr& scriptDir); + ClientConsole(const Logger& logger, Nz::RenderTarget* window, Nz::Canvas* canvas, std::shared_ptr scriptingLibrary, const std::shared_ptr& scriptDir); ClientConsole(const ClientConsole&) = delete; ClientConsole(ClientConsole&&) = delete; ~ClientConsole() = default; diff --git a/include/ClientLib/ClientLayerEntity.hpp b/include/ClientLib/ClientLayerEntity.hpp index b3468412..19fa3511 100644 --- a/include/ClientLib/ClientLayerEntity.hpp +++ b/include/ClientLib/ClientLayerEntity.hpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/ClientLib/ClientLayerSound.hpp b/include/ClientLib/ClientLayerSound.hpp index 7790bd88..bb74fb91 100644 --- a/include/ClientLib/ClientLayerSound.hpp +++ b/include/ClientLib/ClientLayerSound.hpp @@ -41,7 +41,7 @@ namespace bw LayerIndex GetLayerIndex() const; inline Nz::Vector2f GetPosition() const; - std::size_t PlaySound(const Nz::SoundBufferRef& soundBuffer, bool isLooping, bool isSpatialized); + std::size_t PlaySound(const std::shared_ptr& soundBuffer, bool isLooping, bool isSpatialized); void StopSound(std::size_t soundIndex); bool Update(float elapsedTime); @@ -60,7 +60,7 @@ namespace bw struct PlayingSound { - Nz::SoundBufferRef soundBuffer; + std::shared_ptr soundBuffer; float currentOffset = 0.f; float duration = 0.f; bool isLooping; diff --git a/include/ClientLib/ClientMatch.hpp b/include/ClientLib/ClientMatch.hpp index c2bd2105..0e806807 100644 --- a/include/ClientLib/ClientMatch.hpp +++ b/include/ClientLib/ClientMatch.hpp @@ -31,7 +31,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/ClientLib/Components/SoundEmitterComponent.hpp b/include/ClientLib/Components/SoundEmitterComponent.hpp index 882161e6..147b5191 100644 --- a/include/ClientLib/Components/SoundEmitterComponent.hpp +++ b/include/ClientLib/Components/SoundEmitterComponent.hpp @@ -26,7 +26,7 @@ namespace bw SoundEmitterComponent(SoundEmitterComponent&&) = default; ~SoundEmitterComponent() = default; - Nz::UInt32 PlaySound(const Nz::SoundBufferRef& soundBuffer, const Nz::Vector3f& soundPosition, bool attachedToEntity, bool isLooping, bool isSpatialized); + Nz::UInt32 PlaySound(const std::shared_ptr& soundBuffer, const Nz::Vector3f& soundPosition, bool attachedToEntity, bool isLooping, bool isSpatialized); void StopSound(Nz::UInt32 soundId); static Ndk::ComponentIndex componentIndex; diff --git a/include/ClientLib/Console.hpp b/include/ClientLib/Console.hpp index 1f5ec847..42618e99 100644 --- a/include/ClientLib/Console.hpp +++ b/include/ClientLib/Console.hpp @@ -10,8 +10,7 @@ #include #include #include -#include -#include +#include #include #include @@ -22,7 +21,7 @@ namespace bw public: using ExecuteCallback = std::function; - Console(Nz::RenderTarget* window, Ndk::Canvas* canvas); + Console(Nz::RenderTarget* window, Nz::Canvas* canvas); Console(const Console&) = delete; Console(Console&&) = delete; ~Console(); @@ -47,7 +46,7 @@ namespace bw NazaraSlot(Nz::RenderTarget, OnRenderTargetSizeChange, m_onTargetChangeSizeSlot); ExecuteCallback m_callback; - Ndk::Console* m_widget; + //Nz::Console* m_widget; }; } diff --git a/include/ClientLib/Console.inl b/include/ClientLib/Console.inl index 21c9cc3a..e3a4d288 100644 --- a/include/ClientLib/Console.inl +++ b/include/ClientLib/Console.inl @@ -13,6 +13,7 @@ namespace bw inline bool Console::IsVisible() const { - return m_widget->IsVisible(); + return false; + //return m_widget->IsVisible(); } } diff --git a/include/ClientLib/EscapeMenu.hpp b/include/ClientLib/EscapeMenu.hpp index 894f1662..06cb07df 100644 --- a/include/ClientLib/EscapeMenu.hpp +++ b/include/ClientLib/EscapeMenu.hpp @@ -12,8 +12,8 @@ #include #include #include -#include -#include +#include +#include namespace bw { diff --git a/include/ClientLib/LayerVisualEntity.hpp b/include/ClientLib/LayerVisualEntity.hpp index dd18d94b..c732b37a 100644 --- a/include/ClientLib/LayerVisualEntity.hpp +++ b/include/ClientLib/LayerVisualEntity.hpp @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include #include #include @@ -32,22 +32,22 @@ namespace bw friend VisualEntity; public: - inline LayerVisualEntity(entt::entity entity, LayerIndex layerIndex, EntityId uniqueId); + inline LayerVisualEntity(entt::handle entity, LayerIndex layerIndex, EntityId uniqueId); LayerVisualEntity(const LayerVisualEntity&) = delete; LayerVisualEntity(LayerVisualEntity&& entity) noexcept; virtual ~LayerVisualEntity(); - void AttachHoveringRenderable(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder, float hoveringHeight); - void AttachRenderable(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder); - void DetachHoveringRenderable(const Nz::InstancedRenderableRef& renderable); - void DetachRenderable(const Nz::InstancedRenderableRef& renderable); + void AttachHoveringRenderable(std::shared_ptr renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder, float hoveringHeight); + void AttachRenderable(std::shared_ptr renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder); + void DetachHoveringRenderable(const std::shared_ptr& renderable); + void DetachRenderable(const std::shared_ptr& renderable); inline void Disable(); void Enable(bool enable = true); template void ForEachRenderable(Func&& func) const; - inline entt::entity GetEntity() const; + inline entt::handle GetEntity() const; Nz::Boxf GetGlobalBounds() const; inline LayerIndex GetLayerIndex() const; Nz::Boxf GetLocalBounds() const; @@ -58,9 +58,9 @@ namespace bw void SyncVisuals(); - void UpdateHoveringRenderableHoveringHeight(const Nz::InstancedRenderableRef& renderable, float newHoveringHeight); - void UpdateHoveringRenderableMatrix(const Nz::InstancedRenderableRef& renderable, const Nz::Matrix4f& offsetMatrix); - void UpdateRenderableMatrix(const Nz::InstancedRenderableRef& renderable, const Nz::Matrix4f& offsetMatrix); + void UpdateHoveringRenderableHoveringHeight(const std::shared_ptr& renderable, float newHoveringHeight); + void UpdateHoveringRenderableMatrix(const std::shared_ptr& renderable, const Nz::Matrix4f& offsetMatrix); + void UpdateRenderableMatrix(const std::shared_ptr& renderable, const Nz::Matrix4f& offsetMatrix); void UpdateScale(float newScale); void UpdateState(const Nz::Vector2f& position, const Nz::RadianAnglef& rotation); void UpdateState(const Nz::Vector2f& position, const Nz::RadianAnglef& rotation, const Nz::Vector2f& linearVel, const Nz::RadianAnglef& angularVel); @@ -75,7 +75,7 @@ namespace bw struct RenderableData { - Nz::InstancedRenderableRef renderable; + std::shared_ptr renderable; Nz::Matrix4f offsetMatrix; int renderOrder; }; @@ -89,7 +89,7 @@ namespace bw std::vector m_attachedHoveringRenderables; std::vector m_attachedRenderables; std::vector m_visualEntities; - Ndk::EntityOwner m_entity; + EntityOwner m_entity; EntityId m_uniqueId; LayerIndex m_layerIndex; }; diff --git a/include/ClientLib/LayerVisualEntity.inl b/include/ClientLib/LayerVisualEntity.inl index 6865b279..e6d617ae 100644 --- a/include/ClientLib/LayerVisualEntity.inl +++ b/include/ClientLib/LayerVisualEntity.inl @@ -8,12 +8,12 @@ namespace bw { - inline LayerVisualEntity::LayerVisualEntity(entt::entity entity, LayerIndex layerIndex, EntityId uniqueId) : + inline LayerVisualEntity::LayerVisualEntity(entt::handle entity, LayerIndex layerIndex, EntityId uniqueId) : m_entity(entity), m_uniqueId(uniqueId), m_layerIndex(layerIndex) { - assert(m_entity); + assert(m_entity.GetEntity()); } inline void LayerVisualEntity::Disable() @@ -28,9 +28,9 @@ namespace bw func(std::as_const(renderableData.renderable), std::as_const(renderableData.offsetMatrix), std::as_const(renderableData.renderOrder)); } - inline entt::entity LayerVisualEntity::GetEntity() const + inline entt::handle LayerVisualEntity::GetEntity() const { - return m_entity; + return m_entity.GetEntity(); } inline LayerIndex LayerVisualEntity::GetLayerIndex() const diff --git a/include/ClientLib/OptionWidget.hpp b/include/ClientLib/OptionWidget.hpp index 99ae70dc..af02c3a2 100644 --- a/include/ClientLib/OptionWidget.hpp +++ b/include/ClientLib/OptionWidget.hpp @@ -10,10 +10,10 @@ #include #include #include -#include -#include -#include -#include +#include +#include +#include +#include #include namespace bw diff --git a/include/ClientLib/Scoreboard.hpp b/include/ClientLib/Scoreboard.hpp index 3478d374..c4bd155e 100644 --- a/include/ClientLib/Scoreboard.hpp +++ b/include/ClientLib/Scoreboard.hpp @@ -9,9 +9,9 @@ #include #include -#include -#include -#include +#include +#include +#include #include namespace bw diff --git a/include/ClientLib/Scripting/ParticleGroup.hpp b/include/ClientLib/Scripting/ParticleGroup.hpp index d5acf13c..fea3b160 100644 --- a/include/ClientLib/Scripting/ParticleGroup.hpp +++ b/include/ClientLib/Scripting/ParticleGroup.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include namespace bw { diff --git a/include/ClientLib/Scripting/Texture.hpp b/include/ClientLib/Scripting/Texture.hpp index 9696915b..ae91f26b 100644 --- a/include/ClientLib/Scripting/Texture.hpp +++ b/include/ClientLib/Scripting/Texture.hpp @@ -15,7 +15,7 @@ namespace bw class BURGWAR_CLIENTLIB_API Texture { public: - inline Texture(Nz::TextureRef texture); + inline Texture(std::shared_ptr texture); Texture(const Texture&) = default; Texture(Texture&&) = default; ~Texture() = default; @@ -26,7 +26,7 @@ namespace bw Texture& operator=(Texture&&) = default; private: - Nz::TextureRef m_texture; + std::shared_ptr m_texture; }; } diff --git a/include/ClientLib/Scripting/Texture.inl b/include/ClientLib/Scripting/Texture.inl index 82c7a763..202d9bae 100644 --- a/include/ClientLib/Scripting/Texture.inl +++ b/include/ClientLib/Scripting/Texture.inl @@ -6,7 +6,7 @@ namespace bw { - inline Texture::Texture(Nz::TextureRef texture) : + inline Texture::Texture(std::shared_ptr texture) : m_texture(std::move(texture)) { } diff --git a/include/ClientLib/SoundEntity.hpp b/include/ClientLib/SoundEntity.hpp index 28e4d5bb..331dd255 100644 --- a/include/ClientLib/SoundEntity.hpp +++ b/include/ClientLib/SoundEntity.hpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include namespace bw { @@ -31,7 +31,7 @@ namespace bw inline entt::entity GetEntity() const; - void PlaySound(std::size_t soundIndex, const Nz::SoundBufferRef& soundBuffer, bool isLooping, bool isSpatialized); + void PlaySound(std::size_t soundIndex, const std::shared_ptr& soundBuffer, bool isLooping, bool isSpatialized); void StopSound(std::size_t soundIndex); diff --git a/include/ClientLib/Systems/SoundSystem.hpp b/include/ClientLib/Systems/SoundSystem.hpp index dcfd9f12..98ac225c 100644 --- a/include/ClientLib/Systems/SoundSystem.hpp +++ b/include/ClientLib/Systems/SoundSystem.hpp @@ -31,7 +31,7 @@ namespace bw static constexpr Nz::UInt32 InvalidSoundId = 0; private: - Nz::UInt32 PlaySound(const Nz::SoundBufferRef& soundBuffer, const Nz::Vector3f& soundPosition, bool attachedToEntity, bool isLooping, bool isSpatialized); + Nz::UInt32 PlaySound(const std::shared_ptr& soundBuffer, const Nz::Vector3f& soundPosition, bool attachedToEntity, bool isLooping, bool isSpatialized); void StopSound(Nz::UInt32 soundId); void UpdateVolume(float newVolume); diff --git a/include/ClientLib/VisualEntity.hpp b/include/ClientLib/VisualEntity.hpp index 43e7eafc..0db4a2cc 100644 --- a/include/ClientLib/VisualEntity.hpp +++ b/include/ClientLib/VisualEntity.hpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include namespace bw @@ -39,25 +39,25 @@ namespace bw VisualEntity& operator=(VisualEntity&& entity) = delete; private: - void AttachHoveringRenderable(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder, float hoverOffset); - void AttachRenderable(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder); - void DetachHoveringRenderable(const Nz::InstancedRenderableRef& renderable); - void DetachRenderable(const Nz::InstancedRenderableRef& renderable); + void AttachHoveringRenderable(std::shared_ptr renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder, float hoverOffset); + void AttachRenderable(std::shared_ptr renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder); + void DetachHoveringRenderable(const std::shared_ptr& renderable); + void DetachRenderable(const std::shared_ptr& renderable); inline void Enable(bool enable); - void UpdateHoveringRenderableHoveringHeight(const Nz::InstancedRenderableRef& renderable, float newHoveringHeight); - void UpdateHoveringRenderableMatrix(const Nz::InstancedRenderableRef& renderable, const Nz::Matrix4f& offsetMatrix); - void UpdateHoveringRenderableRenderOrder(const Nz::InstancedRenderableRef& renderable, int renderOrder); + void UpdateHoveringRenderableHoveringHeight(const std::shared_ptr& renderable, float newHoveringHeight); + void UpdateHoveringRenderableMatrix(const std::shared_ptr& renderable, const Nz::Matrix4f& offsetMatrix); + void UpdateHoveringRenderableRenderOrder(const std::shared_ptr& renderable, int renderOrder); - void UpdateRenderableMatrix(const Nz::InstancedRenderableRef& renderable, const Nz::Matrix4f& offsetMatrix); - void UpdateRenderableRenderOrder(const Nz::InstancedRenderableRef& renderable, int renderOrder); + void UpdateRenderableMatrix(const std::shared_ptr& renderable, const Nz::Matrix4f& offsetMatrix); + void UpdateRenderableRenderOrder(const std::shared_ptr& renderable, int renderOrder); struct HoveringRenderable { float offset; Ndk::EntityOwner entity; - Nz::InstancedRenderableRef renderable; + std::shared_ptr renderable; }; std::vector m_hoveringRenderables; diff --git a/include/CoreLib/AssetStore.inl b/include/CoreLib/AssetStore.inl index 6a52cc70..0c3004d5 100644 --- a/include/CoreLib/AssetStore.inl +++ b/include/CoreLib/AssetStore.inl @@ -54,7 +54,7 @@ namespace bw bwLog(m_logger, LogLevel::Info, "Loading asset from {}", arg.filePath.generic_u8string()); return (resource = ResourceType::LoadFromFile(arg.filePath.generic_u8string(), params)) != nullptr; } - else if constexpr (std::is_same_v || std::is_same_v) + else if constexpr (std::is_base_of_v) { return false; } diff --git a/include/CoreLib/EntityOwner.hpp b/include/CoreLib/EntityOwner.hpp index 8354d964..c2ff133b 100644 --- a/include/CoreLib/EntityOwner.hpp +++ b/include/CoreLib/EntityOwner.hpp @@ -14,7 +14,7 @@ namespace bw class EntityOwner { public: - inline EntityOwner(entt::handle entity); + inline EntityOwner(entt::handle entity = entt::handle{}); EntityOwner(const EntityOwner&) = delete; inline EntityOwner(EntityOwner&& entityOwner) noexcept; inline ~EntityOwner(); diff --git a/include/CoreLib/Scripting/ScriptStore.inl b/include/CoreLib/Scripting/ScriptStore.inl index 102b6aeb..e32974c6 100644 --- a/include/CoreLib/Scripting/ScriptStore.inl +++ b/include/CoreLib/Scripting/ScriptStore.inl @@ -72,19 +72,16 @@ namespace bw { const auto& scriptDir = m_context->GetScriptDirectory(); - auto callback = [&](const Nz::VirtualDirectory::Entry& entry) + auto callback = [&](const Nz::VirtualDirectory::DirectoryEntry& directoryEntry) { - if (std::holds_alternative(entry)) + directoryEntry.directory->Foreach([&](std::string_view entryName, const Nz::VirtualDirectory::Entry& entry) { - const Nz::VirtualDirectory::DirectoryEntry& directoryEntry = std::get(entry); - directoryEntry.directory->Foreach([&](std::string_view entryName, const Nz::VirtualDirectory::Entry& entry) - { - LoadElement(std::holds_alternative(entry), directoryPath / entryName); - }); - } + bool isDirectory = std::holds_alternative(entry) || std::holds_alternative(entry); + LoadElement(isDirectory, directoryPath / entryName); + }); }; - scriptDir->GetEntry(directoryPath.generic_u8string(), callback); + scriptDir->GetDirectoryEntry(directoryPath.generic_u8string(), callback); } template diff --git a/include/CoreLib/Scripting/ScriptingContext.hpp b/include/CoreLib/Scripting/ScriptingContext.hpp index 16147d15..8303fa1e 100644 --- a/include/CoreLib/Scripting/ScriptingContext.hpp +++ b/include/CoreLib/Scripting/ScriptingContext.hpp @@ -74,7 +74,6 @@ namespace bw tl::expected LoadFile(std::filesystem::path path, const std::string_view& content); std::optional LoadFile(std::filesystem::path path, const std::string_view& content, Async); void LoadDirectory(std::filesystem::path path, const Nz::VirtualDirectory::DirectoryEntry& folder); - void LoadDirectory(std::filesystem::path path, const Nz::VirtualDirectory::PhysicalDirectoryEntry& folder); std::string ReadFile(const std::filesystem::path& path, const Nz::VirtualDirectory::PhysicalFileEntry& entry); std::filesystem::path m_currentFile; diff --git a/src/Client/States/BackgroundState.cpp b/src/Client/States/BackgroundState.cpp index 0398c322..bd02c869 100644 --- a/src/Client/States/BackgroundState.cpp +++ b/src/Client/States/BackgroundState.cpp @@ -20,7 +20,7 @@ namespace bw StateData& stateData = GetStateData(); //stateData.world->GetSystem().SetDefaultBackground(Nz::ColorBackground::New(Nz::Color(131, 180, 205))); - if (Nz::TextureRef backgroundTexture = Nz::TextureLibrary::Get("MenuBackground")) + if (std::shared_ptr backgroundTexture = Nz::TextureLibrary::Get("MenuBackground")) { m_backgroundSprite = Nz::Sprite::New(); m_backgroundSprite->SetTexture(backgroundTexture); diff --git a/src/Client/States/BackgroundState.hpp b/src/Client/States/BackgroundState.hpp index 9455b3b8..2451108e 100644 --- a/src/Client/States/BackgroundState.hpp +++ b/src/Client/States/BackgroundState.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include namespace bw { diff --git a/src/Client/States/Game/AuthenticationState.hpp b/src/Client/States/Game/AuthenticationState.hpp index 4f5c384d..41605945 100644 --- a/src/Client/States/Game/AuthenticationState.hpp +++ b/src/Client/States/Game/AuthenticationState.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include namespace bw diff --git a/src/Client/States/Game/CancelableState.hpp b/src/Client/States/Game/CancelableState.hpp index 4ec30b48..981c0474 100644 --- a/src/Client/States/Game/CancelableState.hpp +++ b/src/Client/States/Game/CancelableState.hpp @@ -8,7 +8,7 @@ #define BURGWAR_STATES_GAME_CANCELABLESTATE_HPP #include -#include +#include #include namespace bw diff --git a/src/Client/States/Game/ConnectedState.hpp b/src/Client/States/Game/ConnectedState.hpp index 18db1800..ee14e9cd 100644 --- a/src/Client/States/Game/ConnectedState.hpp +++ b/src/Client/States/Game/ConnectedState.hpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/Client/States/Game/ConnectionLostState.cpp b/src/Client/States/Game/ConnectionLostState.cpp index edcb174a..a8f3efa5 100644 --- a/src/Client/States/Game/ConnectionLostState.cpp +++ b/src/Client/States/Game/ConnectionLostState.cpp @@ -6,7 +6,7 @@ #include #include #include -#include +#include namespace bw { diff --git a/src/Client/States/Game/ConnectionState.hpp b/src/Client/States/Game/ConnectionState.hpp index 15c90975..ab76b017 100644 --- a/src/Client/States/Game/ConnectionState.hpp +++ b/src/Client/States/Game/ConnectionState.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/Client/States/Game/ResourceDownloadState.hpp b/src/Client/States/Game/ResourceDownloadState.hpp index 2d7b2dbe..6d375551 100644 --- a/src/Client/States/Game/ResourceDownloadState.hpp +++ b/src/Client/States/Game/ResourceDownloadState.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/Client/States/Game/StatusState.hpp b/src/Client/States/Game/StatusState.hpp index 2536c915..9fe4d446 100644 --- a/src/Client/States/Game/StatusState.hpp +++ b/src/Client/States/Game/StatusState.hpp @@ -8,7 +8,7 @@ #define BURGWAR_STATES_GAME_STATUSSTATE_HPP #include -#include +#include namespace bw { diff --git a/src/Client/States/JoinServerState.cpp b/src/Client/States/JoinServerState.cpp index 53657f35..0b3be294 100644 --- a/src/Client/States/JoinServerState.cpp +++ b/src/Client/States/JoinServerState.cpp @@ -13,9 +13,9 @@ #include #include #include -#include -#include -#include +#include +#include +#include #include #include diff --git a/src/Client/States/MainMenuState.cpp b/src/Client/States/MainMenuState.cpp index 55e6b8d1..8d211b41 100644 --- a/src/Client/States/MainMenuState.cpp +++ b/src/Client/States/MainMenuState.cpp @@ -17,9 +17,9 @@ #include #include #include -#include -#include -#include +#include +#include +#include #include #include diff --git a/src/Client/States/StartServerState.cpp b/src/Client/States/StartServerState.cpp index c5284b9d..74dadc3e 100644 --- a/src/Client/States/StartServerState.cpp +++ b/src/Client/States/StartServerState.cpp @@ -15,9 +15,9 @@ #include #include #include -#include -#include -#include +#include +#include +#include #include #include diff --git a/src/ClientLib/Camera.cpp b/src/ClientLib/Camera.cpp index c1c9b39d..ffe371a7 100644 --- a/src/ClientLib/Camera.cpp +++ b/src/ClientLib/Camera.cpp @@ -3,32 +3,31 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include -#include +#include #include namespace bw { - Camera::Camera(entt::registry& world, Nz::RenderTarget* renderTarget, bool perspective) : + Camera::Camera(entt::registry& registry, Nz::RenderTarget* renderTarget, bool perspective) : m_isPerspective(!perspective), // To enable it after m_zoomFactor(1.f) { constexpr float fov = 30.f; - m_cameraEntity = world.CreateEntity(); + m_cameraEntity = entt::handle(registry, registry.create()); - auto& camera = m_cameraEntity->AddComponent(); - camera.SetFOV(fov); - camera.SetTarget(renderTarget); - camera.SetZFar(20000.f); + auto& camera = m_cameraEntity->emplace(renderTarget, Nz::ProjectionType::Orthographic); + camera.UpdateFOV(fov); + camera.UpdateTarget(renderTarget); + camera.UpdateZFar(20000.f); - m_cameraEntity->AddComponent(); + m_cameraEntity->emplace(); m_invFovTan = 1.f / std::tan(Nz::DegreeToRadian(fov * 0.5f)); EnablePerspective(perspective); - m_onTargetSizeChanged.Connect(renderTarget->OnRenderTargetSizeChange, [this](const Nz::RenderTarget*) { UpdateZoomFactor(); }); + m_onTargetSizeChanged.Connect(renderTarget->OnRenderTargetSizeChange, [this](const Nz::RenderTarget*, const Nz::Vector2ui& newRenderTargetSize) { UpdateZoomFactor(newRenderTargetSize); }); } void Camera::EnablePerspective(bool enable) @@ -43,37 +42,39 @@ namespace bw float Camera::GetFOV() const { - auto& entityCamera = m_cameraEntity->GetComponent(); - return entityCamera.GetFOV(); + auto& entityCamera = m_cameraEntity->get(); + return entityCamera.GetFOV().ToDegrees(); } Nz::Vector2f Camera::GetPosition() const { - auto& entityNode = m_cameraentity.get(); + auto& entityNode = m_cameraEntity->get(); return Nz::Vector2f(entityNode.GetPosition()); } const Nz::Recti& Camera::GetViewport() const { - auto& entityCamera = m_cameraEntity->GetComponent(); + auto& entityCamera = m_cameraEntity->get(); return entityCamera.GetViewport(); } Nz::Vector2f Camera::Project(const Nz::Vector2f& worldPosition) const { - auto& entityCamera = m_cameraEntity->GetComponent(); - return Nz::Vector2f(entityCamera.Project(worldPosition)); + throw std::runtime_error("EnTT TODO"); + //auto& entityCamera = m_cameraEntity->get(); + //return Nz::Vector2f(entityCamera.Project(worldPosition)); } Nz::Vector3f Camera::Project(const Nz::Vector3f& worldPosition) const { - auto& entityCamera = m_cameraEntity->GetComponent(); - return entityCamera.Project(worldPosition); + throw std::runtime_error("EnTT TODO"); + //auto& entityCamera = m_cameraEntity->get(); + //return entityCamera.Project(worldPosition); } void Camera::MoveBy(const Nz::Vector2f& offset) { - auto& entityNode = m_cameraentity.get(); + auto& entityNode = m_cameraEntity->get(); MoveToPosition(Nz::Vector2f(entityNode.GetPosition()) + offset); } @@ -86,14 +87,14 @@ namespace bw OnCameraMove(this, position); - auto& entityNode = m_cameraentity.get(); + auto& entityNode = m_cameraEntity->get(); entityNode.SetPosition(position); } void Camera::SetFOV(float fov) { - auto& entityCamera = m_cameraEntity->GetComponent(); - entityCamera.SetFOV(fov); + auto& entityCamera = m_cameraEntity->get(); + entityCamera.UpdateFOV(fov); m_invFovTan = 1.f / std::tan(Nz::DegreeToRadian(fov * 0.5f)); @@ -112,33 +113,39 @@ namespace bw Nz::Vector2f Camera::Unproject(const Nz::Vector2f& screenPosition) const { - auto& entityCamera = m_cameraEntity->GetComponent(); + throw std::runtime_error("EnTT TODO"); - return Nz::Vector2f(entityCamera.Unproject(Nz::Vector3f(screenPosition.x, screenPosition.y, m_projectedDepth))); + //auto& entityCamera = m_cameraEntity->get(); + + //return Nz::Vector2f(entityCamera.Unproject(Nz::Vector3f(screenPosition.x, screenPosition.y, m_projectedDepth))); } Nz::Vector3f Camera::Unproject(const Nz::Vector3f& screenPosition) const { - auto& entityCamera = m_cameraEntity->GetComponent(); + throw std::runtime_error("EnTT TODO"); + + //auto& entityCamera = m_cameraEntity->get(); - return entityCamera.Unproject(screenPosition); + //return entityCamera.Unproject(screenPosition); } void Camera::UpdateProjection() { - auto& entityCamera = m_cameraEntity->GetComponent(); + auto& entityCamera = m_cameraEntity->get(); if (m_isPerspective) { - entityCamera.SetProjectionScale({ 1.f, -1.f, 1.f }); - entityCamera.SetProjectionType(Nz::ProjectionType_Perspective); + // EnTT TODO + //entityCamera.SetProjectionScale({ 1.f, -1.f, 1.f }); + entityCamera.UpdateProjectionType(Nz::ProjectionType::Perspective); } else { m_projectedDepth = 0.f; - entityCamera.SetProjectionScale(Nz::Vector3f::Unit()); - entityCamera.SetProjectionType(Nz::ProjectionType_Orthogonal); + // EnTT TODO + //entityCamera.SetProjectionScale(Nz::Vector3f::Unit()); + entityCamera.UpdateProjectionType(Nz::ProjectionType::Orthographic); } UpdateZoomFactor(); @@ -146,24 +153,31 @@ namespace bw void Camera::UpdateZoomFactor() { - auto& entityCamera = m_cameraEntity->GetComponent(); - auto& entityNode = m_cameraentity.get(); + auto& entityCamera = m_cameraEntity->get(); + return UpdateZoomFactor(entityCamera.GetRenderTarget().GetSize()); + } + + void Camera::UpdateZoomFactor(const Nz::Vector2ui& newRenderTargetSize) + { + auto& entityCamera = m_cameraEntity->get(); + auto& entityNode = m_cameraEntity->get(); - Nz::Vector2f viewportSize = Nz::Vector2f(entityCamera.GetTarget()->GetSize()) / m_zoomFactor; + Nz::Vector2f size = Nz::Vector2f(newRenderTargetSize) / m_zoomFactor; //viewportSize.x = std::round(viewportSize.x); //viewportSize.y = std::round(viewportSize.y); if (m_isPerspective) { Nz::Vector3f initialPosition; - initialPosition.x = viewportSize.x * 0.5f; - initialPosition.y = viewportSize.y * 0.5f; - initialPosition.z = viewportSize.y * 0.5f * m_invFovTan; + initialPosition.x = size.x * 0.5f; + initialPosition.y = size.y * 0.5f; + initialPosition.z = size.y * 0.5f * m_invFovTan; entityNode.SetInitialPosition(initialPosition); - m_projectedDepth = entityCamera.Project({ 0.f, 0.f, 0.f }).z; + throw std::runtime_error("EnTT TODO"); + //m_projectedDepth = entityCamera.Project({ 0.f, 0.f, 0.f }).z; } else - entityCamera.SetSize(viewportSize); + entityCamera.UpdateSize(size); } } diff --git a/src/ClientLib/Chatbox.cpp b/src/ClientLib/Chatbox.cpp index 5d173702..4abec867 100644 --- a/src/ClientLib/Chatbox.cpp +++ b/src/ClientLib/Chatbox.cpp @@ -6,45 +6,46 @@ #include #include #include -#include +#include namespace bw { static constexpr std::size_t maxChatLines = 100; - Chatbox::Chatbox(const Logger& logger, Nz::RenderTarget* rt, Ndk::Canvas* canvas) : + Chatbox::Chatbox(const Logger& logger, Nz::RenderTarget* rt, Nz::Canvas* canvas) : m_chatEnteringBox(nullptr), m_logger(logger) { - Nz::FontRef chatboxFont = Nz::FontLibrary::Get("BW_Chatbox"); - assert(chatboxFont); + //TODO + //Nz::FontRef chatboxFont = Nz::FontLibrary::Get("BW_Chatbox"); + //assert(chatboxFont); - m_chatBox = canvas->Add(); + m_chatBox = canvas->Add(); m_chatBox->EnableBackground(false); m_chatBox->EnableLineWrap(true); m_chatBox->SetBackgroundColor(Nz::Color(0, 0, 0, 50)); m_chatBox->SetCharacterSize(22); m_chatBox->SetTextColor(Nz::Color::White); - m_chatBox->SetTextFont(chatboxFont); + //m_chatBox->SetTextFont(chatboxFont); m_chatBox->SetTextOutlineColor(Nz::Color::Black); m_chatBox->SetTextOutlineThickness(1.f); m_chatBox->SetReadOnly(true); - m_chatboxScrollArea = canvas->Add(m_chatBox); + m_chatboxScrollArea = canvas->Add(m_chatBox); m_chatboxScrollArea->Resize({ 480.f, 0.f }); m_chatboxScrollArea->EnableScrollbar(false); - m_chatEnteringBox = canvas->Add(); + m_chatEnteringBox = canvas->Add(); m_chatEnteringBox->EnableBackground(true); m_chatEnteringBox->SetBackgroundColor(Nz::Color(255, 255, 255, 150)); m_chatEnteringBox->SetTextColor(Nz::Color::Black); - m_chatEnteringBox->SetTextFont(chatboxFont); + //m_chatEnteringBox->SetTextFont(chatboxFont); m_chatEnteringBox->Hide(); // Connect every slot m_onTargetChangeSizeSlot.Connect(rt->OnRenderTargetSizeChange, this, &Chatbox::OnRenderTargetSizeChange); - OnRenderTargetSizeChange(rt); + OnRenderTargetSizeChange(rt, rt->GetSize()); } Chatbox::~Chatbox() @@ -114,14 +115,14 @@ namespace bw void Chatbox::SendMessage() { - Nz::String text = m_chatEnteringBox->GetText(); - if (!text.IsEmpty()) + std::string text = m_chatEnteringBox->GetText(); + if (!text.empty()) OnChatMessage(text); } - void Chatbox::OnRenderTargetSizeChange(const Nz::RenderTarget* renderTarget) + void Chatbox::OnRenderTargetSizeChange(const Nz::RenderTarget* renderTarget, const Nz::Vector2ui& newSize) { - Nz::Vector2f size = Nz::Vector2f(renderTarget->GetSize()); + Nz::Vector2f size = Nz::Vector2f(newSize); m_chatEnteringBox->Resize({ size.x, 40.f }); m_chatEnteringBox->SetPosition({ 0.f, size.y - m_chatEnteringBox->GetHeight() - 5.f, 0.f }); diff --git a/src/ClientLib/ClientAssetStore.cpp b/src/ClientLib/ClientAssetStore.cpp index 53a0e08e..1db72035 100644 --- a/src/ClientLib/ClientAssetStore.cpp +++ b/src/ClientLib/ClientAssetStore.cpp @@ -3,6 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include +#include namespace bw { @@ -15,18 +16,21 @@ namespace bw m_textures.clear(); } - const Nz::ModelRef& ClientAssetStore::GetModel(const std::string& modelPath) const + const std::shared_ptr& ClientAssetStore::GetModel(const std::string& modelPath) const { - Nz::ModelParameters loaderParameters; + static std::shared_ptr dummy; + return dummy; + // TODO + /*Nz::ModelParameters loaderParameters; loaderParameters.material.shaderName = "Basic"; loaderParameters.mesh.animated = false; loaderParameters.mesh.center = true; loaderParameters.mesh.storage = Nz::DataStorage_Hardware; - return GetResource(modelPath, m_models, loaderParameters); + return GetResource(modelPath, m_models, loaderParameters);*/ } - const Nz::SoundBufferRef& ClientAssetStore::GetSoundBuffer(const std::string& soundPath) const + const std::shared_ptr& ClientAssetStore::GetSoundBuffer(const std::string& soundPath) const { Nz::SoundBufferParams loaderParameters; loaderParameters.forceMono = true; @@ -34,9 +38,10 @@ namespace bw return GetResource(soundPath, m_soundBuffers, loaderParameters); } - const Nz::TextureRef& ClientAssetStore::GetTexture(const std::string& texturePath) const + const std::shared_ptr& ClientAssetStore::GetTexture(const std::string& texturePath) const { - Nz::ImageParams loaderParameters; + Nz::TextureParams loaderParameters; + loaderParameters.renderDevice = Nz::Graphics::Instance()->GetRenderDevice(); return GetResource(texturePath, m_textures, loaderParameters); } diff --git a/src/ClientLib/ClientConsole.cpp b/src/ClientLib/ClientConsole.cpp index 76fd98cb..bf053bc8 100644 --- a/src/ClientLib/ClientConsole.cpp +++ b/src/ClientLib/ClientConsole.cpp @@ -6,7 +6,7 @@ namespace bw { - ClientConsole::ClientConsole(const Logger& logger, Nz::RenderTarget* window, Ndk::Canvas* canvas, std::shared_ptr scriptingLibrary, const std::shared_ptr& scriptDir) : + ClientConsole::ClientConsole(const Logger& logger, Nz::RenderTarget* window, Nz::Canvas* canvas, std::shared_ptr scriptingLibrary, const std::shared_ptr& scriptDir) : Console(window, canvas), m_environment(logger, std::move(scriptingLibrary), scriptDir) { diff --git a/src/ClientLib/ClientEditorApp.cpp b/src/ClientLib/ClientEditorApp.cpp index 50d6475c..e866bfde 100644 --- a/src/ClientLib/ClientEditorApp.cpp +++ b/src/ClientLib/ClientEditorApp.cpp @@ -27,7 +27,6 @@ namespace bw } ClientEditorApp::ClientEditorApp(int argc, char* argv[], LogSide side, const SharedAppConfig& configFile) : - ClientApplication(argc, argv), BurgApp(side, configFile), m_playerSettings(*this) { @@ -42,26 +41,14 @@ namespace bw { Nz::Audio::SetGlobalVolume(float(newValue)); }); - - Ndk::InitializeComponent("LayrEnt"); - Ndk::InitializeComponent("LclMatch"); - Ndk::InitializeComponent("LclOwner"); - Ndk::InitializeComponent("LclPly"); - Ndk::InitializeComponent("SndEmtr"); - Ndk::InitializeComponent("VsbLayrs"); - Ndk::InitializeComponent("Interp"); - Ndk::InitializeSystem(); - Ndk::InitializeSystem(); - Ndk::InitializeSystem(); - Ndk::InitializeSystem(); } ClientEditorApp::~ClientEditorApp() { - Nz::FontLibrary::Clear(); + /*Nz::FontLibrary::Clear(); Nz::MaterialLibrary::Clear(); Nz::SpriteLibrary::Clear(); - Nz::TextureLibrary::Clear(); + Nz::TextureLibrary::Clear();*/ } void ClientEditorApp::SavePlayerConfig() @@ -72,14 +59,14 @@ namespace bw void ClientEditorApp::Quit() { - ClientApplication::Quit(); + //ClientApplication::Quit(); } void ClientEditorApp::FillStores() { const std::string& gameResourceFolder = m_config.GetStringValue("Resources.AssetDirectory"); - Nz::MaterialRef spriteNoDepthMat = Nz::Material::New(); + /*Nz::MaterialRef spriteNoDepthMat = Nz::Material::New(); spriteNoDepthMat->EnableDepthBuffer(false); spriteNoDepthMat->EnableFaceCulling(false); @@ -117,6 +104,6 @@ namespace bw Nz::FontLibrary::Register("BW_Chatbox", barthowheel); Nz::FontLibrary::Register("BW_Names", grandstander); - Nz::FontLibrary::Register("BW_ScoreMenu", Nz::Font::GetDefault()); + Nz::FontLibrary::Register("BW_ScoreMenu", Nz::Font::GetDefault());*/ } } diff --git a/src/ClientLib/ClientEditorApp.hpp b/src/ClientLib/ClientEditorApp.hpp index 91b2ef57..6f53e0e4 100644 --- a/src/ClientLib/ClientEditorApp.hpp +++ b/src/ClientLib/ClientEditorApp.hpp @@ -9,13 +9,12 @@ #include #include -#include namespace bw { class SharedAppConfig; - class BURGWAR_CLIENTLIB_API ClientEditorApp : public Ndk::ClientApplication, public BurgApp + class BURGWAR_CLIENTLIB_API ClientEditorApp : public BurgApp { public: ClientEditorApp(int argc, char* argv[], LogSide side, const SharedAppConfig& configFile); diff --git a/src/ClientLib/ClientLayerSound.cpp b/src/ClientLib/ClientLayerSound.cpp index d1d1c1cf..0e3d9b60 100644 --- a/src/ClientLib/ClientLayerSound.cpp +++ b/src/ClientLib/ClientLayerSound.cpp @@ -23,7 +23,7 @@ namespace bw return m_layer.GetLayerIndex(); } - std::size_t ClientLayerSound::PlaySound(const Nz::SoundBufferRef& soundBuffer, bool isLooping, bool isSpatialized) + std::size_t ClientLayerSound::PlaySound(const std::shared_ptr& soundBuffer, bool isLooping, bool isSpatialized) { // Find first finished sound std::size_t soundIndex = 0; diff --git a/src/ClientLib/Components/SoundEmitterComponent.cpp b/src/ClientLib/Components/SoundEmitterComponent.cpp index 5bce2953..4cb18356 100644 --- a/src/ClientLib/Components/SoundEmitterComponent.cpp +++ b/src/ClientLib/Components/SoundEmitterComponent.cpp @@ -8,7 +8,7 @@ namespace bw { - Nz::UInt32 SoundEmitterComponent::PlaySound(const Nz::SoundBufferRef& soundBuffer, const Nz::Vector3f& soundPosition, bool attachedToEntity, bool isLooping, bool isSpatialized) + Nz::UInt32 SoundEmitterComponent::PlaySound(const std::shared_ptr& soundBuffer, const Nz::Vector3f& soundPosition, bool attachedToEntity, bool isLooping, bool isSpatialized) { entt::entity entity = GetEntity(); if (!entity) diff --git a/src/ClientLib/Console.cpp b/src/ClientLib/Console.cpp index 891c8951..863e3136 100644 --- a/src/ClientLib/Console.cpp +++ b/src/ClientLib/Console.cpp @@ -3,20 +3,20 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +//#include namespace bw { - Console::Console(Nz::RenderTarget* window, Ndk::Canvas* canvas) + Console::Console(Nz::RenderTarget* window, Nz::Canvas* canvas) { - m_widget = canvas->Add(); + /*m_widget = canvas->Add(); m_widget->Hide(); m_widget->OnCommand.Connect([this](Ndk::Console*, const Nz::String& command) { if (m_callback) m_callback(command); - }); + });*/ // Connect every slot m_onTargetChangeSizeSlot.Connect(window->OnRenderTargetSizeChange, this, &Console::OnRenderTargetSizeChange); @@ -26,17 +26,17 @@ namespace bw Console::~Console() { - m_widget->Destroy(); + //m_widget->Destroy(); } void Console::Clear() { - m_widget->Clear(); + //m_widget->Clear(); } void Console::Print(const std::string& str, Nz::Color color) { - m_widget->AddLine(str, color); + //m_widget->AddLine(str, color); } void Console::SetExecuteCallback(ExecuteCallback callback) @@ -48,13 +48,13 @@ namespace bw { if (IsVisible() != shouldShow) { - if (shouldShow) + /*if (shouldShow) { m_widget->Show(true); m_widget->SetFocus(); } else - m_widget->Hide(); + m_widget->Hide();*/ } } @@ -62,7 +62,7 @@ namespace bw { Nz::Vector2f size = Nz::Vector2f(renderTarget->GetSize()); - m_widget->Resize({ size.x, size.y / 3.f }); - m_widget->SetPosition(0.f, 0.f); + //m_widget->Resize({ size.x, size.y / 3.f }); + //m_widget->SetPosition(0.f, 0.f); } } diff --git a/src/ClientLib/LayerVisualEntity.cpp b/src/ClientLib/LayerVisualEntity.cpp index c4f2b60b..32a07cd7 100644 --- a/src/ClientLib/LayerVisualEntity.cpp +++ b/src/ClientLib/LayerVisualEntity.cpp @@ -39,7 +39,7 @@ namespace bw LayerVisualEntity::~LayerVisualEntity() = default; - void LayerVisualEntity::AttachHoveringRenderable(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder, float hoveringHeight) + void LayerVisualEntity::AttachHoveringRenderable(std::shared_ptr renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder, float hoveringHeight) { auto& renderableData = m_attachedHoveringRenderables.emplace_back(); renderableData.hoveringHeight = hoveringHeight; @@ -51,7 +51,7 @@ namespace bw visualEntity->AttachHoveringRenderable(renderableData.data.renderable, renderableData.data.offsetMatrix, renderableData.data.renderOrder, hoveringHeight); } - void LayerVisualEntity::AttachRenderable(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder) + void LayerVisualEntity::AttachRenderable(std::shared_ptr renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder) { auto& renderableData = m_attachedRenderables.emplace_back(); renderableData.offsetMatrix = offsetMatrix; @@ -62,7 +62,7 @@ namespace bw visualEntity->AttachRenderable(renderableData.renderable, renderableData.offsetMatrix, renderableData.renderOrder); } - void LayerVisualEntity::DetachHoveringRenderable(const Nz::InstancedRenderableRef& renderable) + void LayerVisualEntity::DetachHoveringRenderable(const std::shared_ptr& renderable) { for (auto it = m_attachedHoveringRenderables.begin(); it != m_attachedHoveringRenderables.end(); ++it) { @@ -78,7 +78,7 @@ namespace bw } } - void LayerVisualEntity::DetachRenderable(const Nz::InstancedRenderableRef& renderable) + void LayerVisualEntity::DetachRenderable(const std::shared_ptr& renderable) { auto it = std::find_if(m_attachedRenderables.begin(), m_attachedRenderables.end(), [&](const RenderableData& renderableData) { return renderableData.renderable == renderable; }); if (it != m_attachedRenderables.end()) @@ -170,7 +170,7 @@ namespace bw visualEntity->Update(position, rotation, scale); } - void LayerVisualEntity::UpdateHoveringRenderableHoveringHeight(const Nz::InstancedRenderableRef& renderable, float newHoveringHeight) + void LayerVisualEntity::UpdateHoveringRenderableHoveringHeight(const std::shared_ptr& renderable, float newHoveringHeight) { for (auto& hoveringRenderable : m_attachedHoveringRenderables) { @@ -185,7 +185,7 @@ namespace bw } } - void LayerVisualEntity::UpdateHoveringRenderableMatrix(const Nz::InstancedRenderableRef& renderable, const Nz::Matrix4f& offsetMatrix) + void LayerVisualEntity::UpdateHoveringRenderableMatrix(const std::shared_ptr& renderable, const Nz::Matrix4f& offsetMatrix) { for (auto& hoveringRenderable : m_attachedHoveringRenderables) { @@ -200,7 +200,7 @@ namespace bw } } - void LayerVisualEntity::UpdateRenderableMatrix(const Nz::InstancedRenderableRef& renderable, const Nz::Matrix4f& offsetMatrix) + void LayerVisualEntity::UpdateRenderableMatrix(const std::shared_ptr& renderable, const Nz::Matrix4f& offsetMatrix) { auto it = std::find_if(m_attachedRenderables.begin(), m_attachedRenderables.end(), [&](const RenderableData& renderableData) { return renderableData.renderable == renderable; }); if (it != m_attachedRenderables.end()) diff --git a/src/ClientLib/Scripting/ClientEditorScriptingLibrary.cpp b/src/ClientLib/Scripting/ClientEditorScriptingLibrary.cpp index 73fd2eac..22b9e61c 100644 --- a/src/ClientLib/Scripting/ClientEditorScriptingLibrary.cpp +++ b/src/ClientLib/Scripting/ClientEditorScriptingLibrary.cpp @@ -36,7 +36,7 @@ namespace bw { library["GetTexture"] = [this](const std::string& texturePath) -> std::optional { - const Nz::TextureRef& texture = m_assetStore.GetTexture(texturePath); + const std::shared_ptr& texture = m_assetStore.GetTexture(texturePath); if (texture) return Texture(texture); else diff --git a/src/ClientLib/Scripting/ClientElementLibrary.cpp b/src/ClientLib/Scripting/ClientElementLibrary.cpp index c8c0b65c..ce13c65b 100644 --- a/src/ClientLib/Scripting/ClientElementLibrary.cpp +++ b/src/ClientLib/Scripting/ClientElementLibrary.cpp @@ -42,7 +42,7 @@ namespace bw Nz::Vector3f rotation = parameters.get_or("Rotation", Nz::Vector3f::Zero()); //< TODO: Euler angles Nz::Vector3f scale = parameters.get_or("Scale", Nz::Vector3f::Unit()); - Nz::ModelRef model = m_assetStore.GetModel(modelPath); + std::shared_ptr model = m_assetStore.GetModel(modelPath); if (!model) return; @@ -301,7 +301,7 @@ namespace bw entt::handle entity = AssertScriptEntity(entityTable); auto& entityMatch = entity->GetComponent(); - const Nz::SoundBufferRef& soundBuffer = m_assetStore.GetSoundBuffer(soundPath); + const std::shared_ptr& soundBuffer = m_assetStore.GetSoundBuffer(soundPath); if (!soundBuffer) TriggerLuaArgError(L, 1, "failed to load " + soundPath); diff --git a/src/ClientLib/Scripting/ClientScriptingLibrary.cpp b/src/ClientLib/Scripting/ClientScriptingLibrary.cpp index 5b57469f..e18bb523 100644 --- a/src/ClientLib/Scripting/ClientScriptingLibrary.cpp +++ b/src/ClientLib/Scripting/ClientScriptingLibrary.cpp @@ -221,7 +221,7 @@ namespace bw if (layerIndex >= match.GetLayerCount()) TriggerLuaArgError(L, 1, "layer out of range (" + std::to_string(layerIndex) + " > " + std::to_string(match.GetLayerCount()) + ")"); - const Nz::SoundBufferRef& soundBuffer = match.GetAssetStore().GetSoundBuffer(soundPath); + const std::shared_ptr& soundBuffer = match.GetAssetStore().GetSoundBuffer(soundPath); if (!soundBuffer) TriggerLuaArgError(L, 1, "failed to load " + soundPath); diff --git a/src/ClientLib/SoundEntity.cpp b/src/ClientLib/SoundEntity.cpp index 423f8da4..be80dc45 100644 --- a/src/ClientLib/SoundEntity.cpp +++ b/src/ClientLib/SoundEntity.cpp @@ -42,7 +42,7 @@ namespace bw m_layerSound->UnregisterAudibleSound(this); } - void SoundEntity::PlaySound(std::size_t soundIndex, const Nz::SoundBufferRef& soundBuffer, bool isLooping, bool isSpatialized) + void SoundEntity::PlaySound(std::size_t soundIndex, const std::shared_ptr& soundBuffer, bool isLooping, bool isSpatialized) { if (soundIndex >= m_soundIds.size()) m_soundIds.resize(soundIndex + 1); diff --git a/src/ClientLib/Systems/SoundSystem.cpp b/src/ClientLib/Systems/SoundSystem.cpp index 6812c1f4..a364f84a 100644 --- a/src/ClientLib/Systems/SoundSystem.cpp +++ b/src/ClientLib/Systems/SoundSystem.cpp @@ -26,7 +26,7 @@ namespace bw }); } - Nz::UInt32 SoundSystem::PlaySound(const Nz::SoundBufferRef& soundBuffer, const Nz::Vector3f& soundPosition, bool attachedToEntity, bool isLooping, bool isSpatialized) + Nz::UInt32 SoundSystem::PlaySound(const std::shared_ptr& soundBuffer, const Nz::Vector3f& soundPosition, bool attachedToEntity, bool isLooping, bool isSpatialized) { Nz::UInt32 soundId = m_nextSoundId++; // Prevent sound id to be invalid sound id diff --git a/src/ClientLib/VisualEntity.cpp b/src/ClientLib/VisualEntity.cpp index d8caf8d6..31b99558 100644 --- a/src/ClientLib/VisualEntity.cpp +++ b/src/ClientLib/VisualEntity.cpp @@ -75,7 +75,7 @@ namespace bw } } - void VisualEntity::AttachHoveringRenderable(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder, float hoverOffset) + void VisualEntity::AttachHoveringRenderable(std::shared_ptr renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder, float hoverOffset) { auto& hoveringRenderable = m_hoveringRenderables.emplace_back(); hoveringRenderable.entity = m_entity->GetWorld()->CreateEntity(); @@ -87,12 +87,12 @@ namespace bw gfxComponent.Attach(hoveringRenderable.renderable, offsetMatrix, renderOrder); } - void VisualEntity::AttachRenderable(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder) + void VisualEntity::AttachRenderable(std::shared_ptr renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder) { m_entity->GetComponent().Attach(std::move(renderable), offsetMatrix, m_baseRenderOrder + renderOrder); } - void VisualEntity::DetachHoveringRenderable(const Nz::InstancedRenderableRef& renderable) + void VisualEntity::DetachHoveringRenderable(const std::shared_ptr& renderable) { for (auto it = m_hoveringRenderables.begin(); it != m_hoveringRenderables.end(); ++it) { @@ -106,12 +106,12 @@ namespace bw } } - void VisualEntity::DetachRenderable(const Nz::InstancedRenderableRef& renderable) + void VisualEntity::DetachRenderable(const std::shared_ptr& renderable) { m_entity->GetComponent().Detach(renderable); } - void VisualEntity::UpdateHoveringRenderableHoveringHeight(const Nz::InstancedRenderableRef& renderable, float newHoveringHeight) + void VisualEntity::UpdateHoveringRenderableHoveringHeight(const std::shared_ptr& renderable, float newHoveringHeight) { for (auto& hoveringRenderable : m_hoveringRenderables) { @@ -123,7 +123,7 @@ namespace bw } } - void VisualEntity::UpdateHoveringRenderableMatrix(const Nz::InstancedRenderableRef& renderable, const Nz::Matrix4f& offsetMatrix) + void VisualEntity::UpdateHoveringRenderableMatrix(const std::shared_ptr& renderable, const Nz::Matrix4f& offsetMatrix) { for (auto& hoveringRenderable : m_hoveringRenderables) { @@ -135,7 +135,7 @@ namespace bw } } - void VisualEntity::UpdateHoveringRenderableRenderOrder(const Nz::InstancedRenderableRef& renderable, int renderOrder) + void VisualEntity::UpdateHoveringRenderableRenderOrder(const std::shared_ptr& renderable, int renderOrder) { for (auto& hoveringRenderable : m_hoveringRenderables) { @@ -147,12 +147,12 @@ namespace bw } } - void VisualEntity::UpdateRenderableMatrix(const Nz::InstancedRenderableRef& renderable, const Nz::Matrix4f& offsetMatrix) + void VisualEntity::UpdateRenderableMatrix(const std::shared_ptr& renderable, const Nz::Matrix4f& offsetMatrix) { m_entity->GetComponent().UpdateLocalMatrix(renderable, offsetMatrix); } - void VisualEntity::UpdateRenderableRenderOrder(const Nz::InstancedRenderableRef& renderable, int renderOrder) + void VisualEntity::UpdateRenderableRenderOrder(const std::shared_ptr& renderable, int renderOrder) { m_entity->GetComponent().UpdateRenderOrder(renderable, m_baseRenderOrder + renderOrder); } diff --git a/src/CoreLib/Match.cpp b/src/CoreLib/Match.cpp index 43cfba77..ae001f0e 100644 --- a/src/CoreLib/Match.cpp +++ b/src/CoreLib/Match.cpp @@ -323,7 +323,7 @@ namespace bw Entity& entityData = m_entitiesByUniqueId.emplace(uniqueId, Entity{}).first.value(); entityData.entity = entity; - entityData.onDestruction.Connect(entity.get().OnDestruction, [this, uniqueId](DestructionWatcherComponent* watcher) + entityData.onDestruction.Connect(entity.get_or_emplace(entity).OnDestruction, [this, uniqueId](DestructionWatcherComponent* watcher) { // Don't trigger the Destroyed event when resetting map if (!m_isResetting) diff --git a/src/CoreLib/Player.cpp b/src/CoreLib/Player.cpp index 0cd16321..138bee43 100644 --- a/src/CoreLib/Player.cpp +++ b/src/CoreLib/Player.cpp @@ -24,8 +24,6 @@ #include #include #include -#include -#include #include namespace bw diff --git a/src/CoreLib/Scripting/ScriptingContext.cpp b/src/CoreLib/Scripting/ScriptingContext.cpp index efe59394..49b1e5ab 100644 --- a/src/CoreLib/Scripting/ScriptingContext.cpp +++ b/src/CoreLib/Scripting/ScriptingContext.cpp @@ -45,7 +45,7 @@ namespace bw if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) return LoadFile(file, arg); - else if constexpr (std::is_same_v || std::is_same_v) + else if constexpr (std::is_base_of_v) return tl::unexpected(file.generic_u8string() + " is a directory, expected a file"); else static_assert(AlwaysFalse::value, "non-exhaustive visitor"); @@ -80,7 +80,7 @@ namespace bw if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) return LoadFile(file, arg, Async{}); - else if constexpr (std::is_same_v || std::is_same_v) + else if constexpr (std::is_base_of_v) { bwLog(m_logger, LogLevel::Error, "{0} is a directory, expected a file", file.generic_u8string()); return {}; @@ -110,7 +110,7 @@ namespace bw if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) bwLog(m_logger, LogLevel::Error, "{0} is a file, expected a directory", folder.generic_u8string()); - else if constexpr (std::is_same_v || std::is_same_v) + else if constexpr (std::is_base_of_v) LoadDirectory(folder, arg); else static_assert(AlwaysFalse::value, "non-exhaustive visitor"); @@ -137,7 +137,7 @@ namespace bw if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) bwLog(m_logger, LogLevel::Error, "{0} is a file, expected a directory", folder.generic_u8string()); - else if constexpr (std::is_same_v || std::is_same_v) + else if constexpr (std::is_base_of_v) LoadDirectory(folder, arg); else static_assert(AlwaysFalse::value, "non-exhaustive visitor"); @@ -310,7 +310,7 @@ namespace bw if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) return LoadFile(entryPath, arg); - else if constexpr (std::is_same_v || std::is_same_v) + else if constexpr (std::is_base_of_v) { LoadDirectory(entryPath, arg); return sol::nil; @@ -325,20 +325,6 @@ namespace bw }); } - void ScriptingContext::LoadDirectory(std::filesystem::path path, const Nz::VirtualDirectory::PhysicalDirectoryEntry& folder) - { - for (const auto& entry : std::filesystem::recursive_directory_iterator(folder.filePath)) - { - if (!entry.is_regular_file()) - continue; - - Nz::VirtualDirectory::PhysicalFileEntry physicalEntry; - physicalEntry.filePath = entry.path(); - - LoadFile(physicalEntry.filePath.parent_path(), physicalEntry); - } - } - std::string ScriptingContext::ReadFile(const std::filesystem::path& path, const Nz::VirtualDirectory::PhysicalFileEntry& entry) { Nz::File file(entry.filePath.generic_u8string()); diff --git a/src/CoreLib/Scripting/ServerEntityLibrary.cpp b/src/CoreLib/Scripting/ServerEntityLibrary.cpp index 1f1c7a53..804cc1e1 100644 --- a/src/CoreLib/Scripting/ServerEntityLibrary.cpp +++ b/src/CoreLib/Scripting/ServerEntityLibrary.cpp @@ -41,8 +41,12 @@ namespace bw auto& entityMatch = entity.get(); + assert(entity.valid()); + std::size_t weaponIndex = weaponWielder->GiveWeapon(weaponClass, [&] (const std::string& weaponClass) -> entt::handle { + assert(entity.valid()); + Match& match = entityMatch.GetMatch(); Terrain& terrain = match.GetTerrain(); TerrainLayer& terrainLayer = terrain.GetLayer(entityMatch.GetLayerIndex()); @@ -57,6 +61,7 @@ namespace bw EntityId uniqueId = match.AllocateUniqueId(); + assert(entity.valid()); entt::handle weapon = weaponStore.InstantiateWeapon(terrainLayer, weaponEntityIndex, uniqueId, {}, entity); if (!weapon) return entt::handle{}; diff --git a/src/CoreLib/Scripting/SharedEntityLibrary.cpp b/src/CoreLib/Scripting/SharedEntityLibrary.cpp index 40c52aa5..7bedc119 100644 --- a/src/CoreLib/Scripting/SharedEntityLibrary.cpp +++ b/src/CoreLib/Scripting/SharedEntityLibrary.cpp @@ -162,6 +162,8 @@ namespace bw void SharedEntityLibrary::InitRigidBody(lua_State* /*L*/, entt::handle entity, float mass) { + entity.remove(); + auto& entityMatch = entity.get(); auto& physics = entityMatch.GetMatch().GetLayer(entityMatch.GetLayerIndex()).GetPhysicsSystem(); @@ -531,7 +533,10 @@ namespace bw Nz::RigidBody2DComponent* physComponent = entity.try_get(); if (!physComponent) + { InitRigidBody(L, entity, 0.f); + physComponent = &entity.get(); + } physComponent->SetGeom(std::move(collider)); }); diff --git a/src/CoreLib/Scripting/SharedScriptingLibrary.cpp b/src/CoreLib/Scripting/SharedScriptingLibrary.cpp index d29b233e..46aa5d89 100644 --- a/src/CoreLib/Scripting/SharedScriptingLibrary.cpp +++ b/src/CoreLib/Scripting/SharedScriptingLibrary.cpp @@ -2,8 +2,6 @@ // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE -#if 0 - #include #include #include @@ -20,8 +18,7 @@ #include #include #include -#include -#include +#include #include namespace bw @@ -347,6 +344,8 @@ namespace bw void SharedScriptingLibrary::RegisterPhysicsLibrary(ScriptingContext& /*context*/, sol::table& library) { + // EnTT TODO +#if 0 library["CreateDampenedSpringConstraint"] = LuaFunction([](sol::this_state L, const sol::table& firstEntityTable, const sol::table& secondEntityTable, const Nz::Vector2f& firstAnchor, const Nz::Vector2f& secondAnchor, float restLength, float stiffness, float damping) { entt::handle firstEntity = AssertScriptEntity(firstEntityTable); @@ -500,6 +499,7 @@ namespace bw physSystem.RaycastQuery(startPos, endPos, 1.f, 0, 0xFFFFFFFF, 0xFFFFFFFF, resultCallback); }); +#endif } void SharedScriptingLibrary::RegisterScriptLibrary(ScriptingContext& /*context*/, sol::table& /*library*/) @@ -523,5 +523,3 @@ namespace bw }); } } - -#endif diff --git a/src/CoreLib/SharedLayer.cpp b/src/CoreLib/SharedLayer.cpp index a760d8fb..9a563555 100644 --- a/src/CoreLib/SharedLayer.cpp +++ b/src/CoreLib/SharedLayer.cpp @@ -114,7 +114,10 @@ namespace bw #endif } - SharedLayer::~SharedLayer() = default; + SharedLayer::~SharedLayer() + { + m_registry.clear(); + } void SharedLayer::TickUpdate(float elapsedTime) { diff --git a/src/CoreLib/Systems/WeaponSystem.cpp b/src/CoreLib/Systems/WeaponSystem.cpp index 7fcd01de..5c030e56 100644 --- a/src/CoreLib/Systems/WeaponSystem.cpp +++ b/src/CoreLib/Systems/WeaponSystem.cpp @@ -24,7 +24,7 @@ namespace bw if (entt::entity owner = weaponComponent.GetOwner(); owner != entt::null) { InputComponent& ownerInputs = m_registry.get(owner); - Nz::NodeComponent& ownerNode = view.get(owner); + Nz::NodeComponent& ownerNode = m_registry.get(owner); Nz::NodeComponent& weaponNode = view.get(weapon); const auto& inputs = ownerInputs.GetInputs(); diff --git a/src/MapEditor/Gizmos/EditorGizmo.cpp b/src/MapEditor/Gizmos/EditorGizmo.cpp index 84209b37..db2ff1df 100644 --- a/src/MapEditor/Gizmos/EditorGizmo.cpp +++ b/src/MapEditor/Gizmos/EditorGizmo.cpp @@ -52,7 +52,7 @@ namespace bw auto& gfx = m_selectionOverlayEntity->GetComponent(); gfx.Clear(); - Nz::ModelRef aabbModel = GenerateBoxModel(); + std::shared_ptr aabbModel = GenerateBoxModel(); gfx.Attach(aabbModel, Nz::Matrix4f::Transform(globalAABB.GetPosition() - origin, Nz::Quaternionf::Identity(), globalAABB.GetLengths()), std::numeric_limits::max()); @@ -63,7 +63,7 @@ namespace bw } } - Nz::ModelRef EditorGizmo::GenerateBoxModel() + std::shared_ptr EditorGizmo::GenerateBoxModel() { std::array indices = { { @@ -117,7 +117,7 @@ namespace bw translucent->SetDiffuseColor(Nz::Color::Orange); translucent->EnableDepthBuffer(false); - Nz::ModelRef model = Nz::Model::New(); + std::shared_ptr model = Nz::Model::New(); model->SetMesh(mesh); model->SetMaterial(0, translucent); diff --git a/src/MapEditor/Gizmos/EditorGizmo.hpp b/src/MapEditor/Gizmos/EditorGizmo.hpp index febc7846..2f852348 100644 --- a/src/MapEditor/Gizmos/EditorGizmo.hpp +++ b/src/MapEditor/Gizmos/EditorGizmo.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include namespace bw { @@ -30,7 +30,7 @@ namespace bw void Refresh(); private: - static Nz::ModelRef GenerateBoxModel(); + static std::shared_ptr GenerateBoxModel(); Ndk::EntityOwner m_selectionOverlayEntity; std::vector m_targetEntities; diff --git a/src/MapEditor/Logic/EntityEditorMode.cpp b/src/MapEditor/Logic/EntityEditorMode.cpp index a59b8a7d..f8447b16 100644 --- a/src/MapEditor/Logic/EntityEditorMode.cpp +++ b/src/MapEditor/Logic/EntityEditorMode.cpp @@ -26,7 +26,7 @@ namespace bw auto& entityData = m_entities.emplace_back(); entityData.layerEntity = visualEntity.CreateHandle(); - visualEntity.ForEachRenderable([&](const Nz::InstancedRenderableRef& renderable, const Nz::Matrix4f& /*localMatrix*/, int /*renderOrder*/) + visualEntity.ForEachRenderable([&](const std::shared_ptr& renderable, const Nz::Matrix4f& /*localMatrix*/, int /*renderOrder*/) { auto& renderableData = entityData.renderables.emplace_back(); @@ -53,7 +53,7 @@ namespace bw continue; std::size_t i = 0; - entityData.layerEntity->ForEachRenderable([&](const Nz::InstancedRenderableRef& renderable, const Nz::Matrix4f& /*localMatrix*/, int /*renderOrder*/) + entityData.layerEntity->ForEachRenderable([&](const std::shared_ptr& renderable, const Nz::Matrix4f& /*localMatrix*/, int /*renderOrder*/) { auto& renderableData = entityData.renderables[i]; for (std::size_t j = 0; j < renderable->GetMaterialCount(); ++j) diff --git a/src/MapEditor/Logic/TileMapEditorMode.hpp b/src/MapEditor/Logic/TileMapEditorMode.hpp index 65ca8388..990a3413 100644 --- a/src/MapEditor/Logic/TileMapEditorMode.hpp +++ b/src/MapEditor/Logic/TileMapEditorMode.hpp @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include class QDockWidget; diff --git a/src/MapEditor/Widgets/TileSelectionWidget.hpp b/src/MapEditor/Widgets/TileSelectionWidget.hpp index 8a5c0a8b..61dd4a15 100644 --- a/src/MapEditor/Widgets/TileSelectionWidget.hpp +++ b/src/MapEditor/Widgets/TileSelectionWidget.hpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/Server/ServerApp.cpp b/src/Server/ServerApp.cpp index 0e5ae9ae..9e5f72c4 100644 --- a/src/Server/ServerApp.cpp +++ b/src/Server/ServerApp.cpp @@ -8,7 +8,6 @@ namespace bw { ServerApp::ServerApp(int argc, char* argv[]) : - Application(argc, argv), BurgApp(LogSide::Server, m_configFile), m_configFile(*this) { @@ -59,17 +58,19 @@ namespace bw int ServerApp::Run() { + m_running = true; + Nz::Clock updateClock; Nz::UInt64 tickDuration = static_cast(m_match->GetTickDuration() * 1'000'000); - while (Application::Run()) + while (m_running) { BurgApp::Update(); - if (!m_match->Update(GetUpdateTime())) + Nz::UInt64 elapsedTime = updateClock.Restart(); + if (!m_match->Update(elapsedTime / 1'000'000.f)) break; - Nz::UInt64 elapsedTime = updateClock.Restart(); if (tickDuration > elapsedTime) { // Since OS sleep is not that precise, let some time between the wakeup time and the tick @@ -89,6 +90,6 @@ namespace bw void ServerApp::Quit() { - Application::Quit(); + m_running = false; } } diff --git a/src/Server/ServerApp.hpp b/src/Server/ServerApp.hpp index 9168d18d..49c2032a 100644 --- a/src/Server/ServerApp.hpp +++ b/src/Server/ServerApp.hpp @@ -10,12 +10,11 @@ #include #include #include -#include #include namespace bw { - class ServerApp : public Ndk::Application, public BurgApp + class ServerApp : public BurgApp { public: ServerApp(int argc, char* argv[]); @@ -25,8 +24,9 @@ namespace bw void Quit() override; private: - ServerAppConfig m_configFile; std::unique_ptr m_match; + ServerAppConfig m_configFile; + bool m_running; }; } diff --git a/src/Server/main.cpp b/src/Server/main.cpp index 7b74be16..ec99cba7 100644 --- a/src/Server/main.cpp +++ b/src/Server/main.cpp @@ -2,14 +2,15 @@ // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE -#include +#include #include +#include #include #include
int BurgWarServer(int argc, char* argv[]) { - Nz::Initializer network; + Nz::Modules nazara; bw::ServerApp app(argc, argv); return app.Run(); diff --git a/xmake-repo/packages/n/nazaraengine/xmake.lua b/xmake-repo/packages/n/nazaraengine/xmake.lua index 364c644a..7d1b1da9 100644 --- a/xmake-repo/packages/n/nazaraengine/xmake.lua +++ b/xmake-repo/packages/n/nazaraengine/xmake.lua @@ -18,6 +18,7 @@ package("nazaraengine") add_configs("platform", {description = "Includes the platform module", default = true, type = "boolean"}) add_configs("renderer", {description = "Includes the renderer module", default = true, type = "boolean"}) add_configs("utility", {description = "Includes the utility module", default = true, type = "boolean"}) + add_configs("widget", {description = "Includes the widget module", default = true, type = "boolean"}) add_configs("plugin-assimp", {description = "Includes the assimp plugin", default = false, type = "boolean"}) if is_plat("linux") then @@ -56,6 +57,10 @@ package("nazaraengine") return package:config("utility") or has_platform(package) end + local function has_widget(package) + return package:config("widget") + end + local function has_assimp_plugin(package) return package:config("plugin-assimp") end @@ -103,6 +108,10 @@ package("nazaraengine") table.insert(links, prefix .. "Physics3D" .. suffix) end + if has_widget(package) then + table.insert(links, prefix .. "Widget" .. suffix) + end + if has_graphics(package) then table.insert(links, prefix .. "Graphics" .. suffix) end diff --git a/xmake-requires.lock b/xmake-requires.lock index 3a8a1988..9a56ffc0 100644 --- a/xmake-requires.lock +++ b/xmake-requires.lock @@ -109,7 +109,7 @@ ["cmake#31fecfc4"] = { repo = { branch = "master", - commit = "84816643e18c08dc36896a8362c1f2eab945364c", + commit = "acc779215567170eae5fa81054df9a14fbc74346", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "3.22.1" @@ -118,7 +118,7 @@ branch = "master", repo = { branch = "master", - commit = "52f61c7e552ca64212ebc7d819faa6692943a52b", + commit = "98cc5e3d8c1c8074d067a4e63e0d7f94146a579a", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "master" @@ -126,39 +126,47 @@ ["cxxopts#31fecfc4"] = { repo = { branch = "master", - commit = "52f61c7e552ca64212ebc7d819faa6692943a52b", + commit = "f881bf0478fb7210197d5079522041997ab94f34", url = "https://github.com/xmake-io/xmake-repo.git" }, - version = "v2.2.0" + version = "v3.0.0" }, ["efsw#31fecfc4"] = { repo = { branch = "master", - commit = "a866090956c8d7375e71feafa27455697fb938b6", + commit = "f881bf0478fb7210197d5079522041997ab94f34", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "1.1.0" }, - ["entt#31fecfc4"] = { + ["entt 3.10.1#31fecfc4"] = { repo = { branch = "master", - commit = "c62703f4efa4275cab3009a5f41b76ebe3791a92", + commit = "f881bf0478fb7210197d5079522041997ab94f34", url = "https://github.com/xmake-io/xmake-repo.git" }, - version = "v3.9.0" + version = "v3.10.1" }, - ["fmt#7572102e"] = { + ["fmt#31fecfc4"] = { repo = { branch = "master", - commit = "4023b478acb08700c7ddd302d12101f19a4190f6", + commit = "f881bf0478fb7210197d5079522041997ab94f34", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "8.1.1" }, + ["fmt#7572102e"] = { + repo = { + branch = "master", + commit = "acc779215567170eae5fa81054df9a14fbc74346", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "9.0.0" + }, ["frozen#31fecfc4"] = { repo = { branch = "master", - commit = "a73dc9a151cd3d46e8edb8153b800659115726d3", + commit = "f881bf0478fb7210197d5079522041997ab94f34", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "1.1.1" @@ -166,7 +174,7 @@ ["hopscotch-map#31fecfc4"] = { repo = { branch = "master", - commit = "52f61c7e552ca64212ebc7d819faa6692943a52b", + commit = "98cc5e3d8c1c8074d067a4e63e0d7f94146a579a", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v2.3.0" @@ -174,10 +182,10 @@ ["libcurl#31fecfc4"] = { repo = { branch = "master", - commit = "4023b478acb08700c7ddd302d12101f19a4190f6", + commit = "acc779215567170eae5fa81054df9a14fbc74346", url = "https://github.com/xmake-io/xmake-repo.git" }, - version = "7.82.0" + version = "7.84.0" }, ["nazaraengine#31fecfc4"] = { repo = { @@ -185,7 +193,7 @@ }, version = "2021.08.28" }, - ["nazaraengine~server#df983b2f"] = { + ["nazaraengine~server#047efbe9"] = { repo = { url = "xmake-repo" }, @@ -193,37 +201,44 @@ }, ["nazarautils#31fecfc4"] = { repo = { - commit = "15982f784152309b48de0111fb3d2e076583b999", + commit = "5d2ec45e5605b9d8c9667c485986abbcfe914fce", url = "https://github.com/NazaraEngine/xmake-repo" }, - version = "2022.05.26" + version = "2022.06.14" }, ["nazarautils#c806eb3e"] = { repo = { - commit = "15982f784152309b48de0111fb3d2e076583b999", + commit = "5d2ec45e5605b9d8c9667c485986abbcfe914fce", url = "https://github.com/NazaraEngine/xmake-repo" }, - version = "2022.05.26" + version = "2022.06.14" }, ["nlohmann_json#31fecfc4"] = { repo = { branch = "master", - commit = "4023b478acb08700c7ddd302d12101f19a4190f6", + commit = "f881bf0478fb7210197d5079522041997ab94f34", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v3.10.5" }, + ["nzsl#31fecfc4"] = { + repo = { + commit = "3ac930f44899384afafd429551e83e89f8e541a9", + url = "https://github.com/NazaraEngine/xmake-repo" + }, + version = "2022.07.02" + }, ["nzsl#c806eb3e"] = { repo = { - commit = "94c34c4a3a02a0a5de61c0a88a63774c67b83a45", + commit = "3ac930f44899384afafd429551e83e89f8e541a9", url = "https://github.com/NazaraEngine/xmake-repo" }, - version = "2022.06.05" + version = "2022.07.27" }, ["ordered_map#31fecfc4"] = { repo = { branch = "master", - commit = "42bf1fa0b15d271c477bfc17315d0a778a256edd", + commit = "f881bf0478fb7210197d5079522041997ab94f34", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v1.0.0" @@ -231,7 +246,7 @@ ["sol2 v3.2.1#72267bd5"] = { repo = { branch = "master", - commit = "52f61c7e552ca64212ebc7d819faa6692943a52b", + commit = "98cc5e3d8c1c8074d067a4e63e0d7f94146a579a", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v3.2.1" @@ -240,7 +255,7 @@ branch = "master", repo = { branch = "master", - commit = "52f61c7e552ca64212ebc7d819faa6692943a52b", + commit = "98cc5e3d8c1c8074d067a4e63e0d7f94146a579a", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "master" @@ -248,7 +263,7 @@ ["tl_expected#31fecfc4"] = { repo = { branch = "master", - commit = "52f61c7e552ca64212ebc7d819faa6692943a52b", + commit = "98cc5e3d8c1c8074d067a4e63e0d7f94146a579a", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v1.0.0" @@ -256,7 +271,7 @@ ["tl_function_ref#31fecfc4"] = { repo = { branch = "master", - commit = "52f61c7e552ca64212ebc7d819faa6692943a52b", + commit = "98cc5e3d8c1c8074d067a4e63e0d7f94146a579a", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v1.0.0" diff --git a/xmake.lua b/xmake.lua index 134690ec..71d9f980 100644 --- a/xmake.lua +++ b/xmake.lua @@ -12,11 +12,11 @@ set_version("0.2.0") add_repositories("nazara-engine-repo https://github.com/NazaraEngine/xmake-repo") add_requires("nazarautils", "nzsl", { debug = is_mode("debug") }) -add_requires("cxxopts", "concurrentqueue", "entt", "hopscotch-map", "nlohmann_json", "tl_expected", "tl_function_ref") +add_requires("cxxopts", "concurrentqueue", "entt 3.10.1", "hopscotch-map", "nlohmann_json", "tl_expected", "tl_function_ref") add_requires("fmt", { configs = { header_only = false, pic = true } }) add_requires("libcurl", { optional = true }) add_requires("nazaraengine", { alias = "nazara" }) -add_requires("nazaraengine~server", { alias = "nazaraserver", configs = { audio = false, graphics = false, platform = false, renderer = false } }) +add_requires("nazaraengine~server", { alias = "nazaraserver", configs = { audio = false, graphics = false, platform = false, renderer = false, widget = false } }) add_requires("sol2 v3.2.1", { verify = false, configs = { includes_lua = false } }) if is_plat("windows") then From ef163248976a76ee5cbb4ed7cbca7055b46550b5 Mon Sep 17 00:00:00 2001 From: SirLynix Date: Tue, 22 Nov 2022 20:04:42 +0100 Subject: [PATCH 08/17] WIP --- include/ClientLib/ClientEditorLayer.hpp | 2 +- include/ClientLib/ClientLayer.hpp | 5 +- include/ClientLib/ClientLayerEntity.hpp | 8 +- include/ClientLib/ClientMatch.hpp | 44 +-- include/ClientLib/ClientMatch.inl | 6 +- .../Components/ClientMatchComponent.hpp | 8 +- .../Components/ClientMatchComponent.inl | 4 +- .../Components/ClientOwnerComponent.hpp | 5 +- .../LocalPlayerControlledComponent.hpp | 5 +- .../Components/SoundEmitterComponent.hpp | 5 +- .../Components/VisibleLayerComponent.hpp | 6 +- .../ClientLib/Components/VisualComponent.hpp | 5 +- .../VisualInterpolationComponent.hpp | 5 +- include/ClientLib/EscapeMenu.hpp | 13 +- include/ClientLib/InputPoller.hpp | 1 - include/ClientLib/LayerVisualEntity.inl | 4 +- include/ClientLib/OptionWidget.hpp | 14 +- include/ClientLib/Scoreboard.hpp | 12 +- .../Scripting/ClientEditorEntityStore.hpp | 4 +- .../Scripting/ClientElementLibrary.hpp | 2 +- .../Scripting/ClientEntityLibrary.hpp | 2 +- include/ClientLib/Scripting/ParticleGroup.hpp | 2 +- .../ClientLib/Scripting/ParticleRegistry.hpp | 8 +- include/ClientLib/Scripting/Sprite.hpp | 5 +- include/ClientLib/Scripting/Sprite.inl | 2 +- include/ClientLib/Scripting/Text.hpp | 4 +- include/ClientLib/Scripting/Text.inl | 2 +- include/ClientLib/SoundEntity.hpp | 4 +- include/ClientLib/SoundEntity.inl | 2 +- .../ClientLib/Systems/FrameCallbackSystem.hpp | 21 +- .../Systems/PostFrameCallbackSystem.hpp | 19 +- include/ClientLib/Systems/SoundSystem.hpp | 20 +- .../Systems/VisualInterpolationSystem.hpp | 12 +- include/ClientLib/VisualEntity.hpp | 6 +- include/ClientLib/VisualEntity.inl | 7 +- .../CoreLib/Systems/TickCallbackSystem.hpp | 4 +- include/CoreLib/TerrainLayer.hpp | 2 +- src/Client/ClientApp.cpp | 2 +- src/Client/States/AbstractState.hpp | 2 +- src/Client/States/BackgroundState.hpp | 4 +- src/Client/States/Game/CancelableState.cpp | 4 +- src/Client/States/Game/CancelableState.hpp | 2 +- src/Client/States/Game/ConnectedState.cpp | 8 +- src/Client/States/Game/ConnectedState.hpp | 10 +- .../States/Game/ConnectionLostState.cpp | 2 +- src/Client/States/Game/StatusState.cpp | 2 +- src/Client/States/Game/StatusState.hpp | 2 +- src/Client/States/JoinServerState.cpp | 12 +- src/Client/States/JoinServerState.hpp | 8 +- src/Client/States/MainMenuState.cpp | 16 +- src/Client/States/MainMenuState.hpp | 8 +- src/Client/States/ServerListState.cpp | 16 +- src/Client/States/ServerListState.hpp | 10 +- src/Client/States/StartServerState.cpp | 22 +- src/Client/States/StartServerState.hpp | 8 +- src/Client/States/StateData.hpp | 8 +- src/ClientLib/ClientEditorApp.cpp | 9 +- src/ClientLib/ClientEditorLayer.cpp | 16 +- src/ClientLib/ClientLayer.cpp | 85 ++---- src/ClientLib/ClientLayerEntity.cpp | 55 ++-- src/ClientLib/ClientMatch.cpp | 119 ++++---- .../Components/ClientMatchComponent.cpp | 6 +- src/ClientLib/EscapeMenu.cpp | 24 +- src/ClientLib/LayerVisualEntity.cpp | 47 ++-- src/ClientLib/OptionWidget.cpp | 20 +- src/ClientLib/Scoreboard.cpp | 31 ++- .../Scripting/ClientEditorEntityStore.cpp | 20 +- .../Scripting/ClientElementLibrary.cpp | 72 +++-- .../Scripting/ClientEntityLibrary.cpp | 28 +- src/ClientLib/Scripting/ClientEntityStore.cpp | 6 +- .../Scripting/ClientWeaponLibrary.cpp | 2 +- src/ClientLib/Scripting/ClientWeaponStore.cpp | 2 +- src/ClientLib/Scripting/ParticleRegistry.cpp | 4 + src/ClientLib/Systems/FrameCallbackSystem.cpp | 34 +-- .../Systems/PostFrameCallbackSystem.cpp | 36 +-- src/ClientLib/Systems/SoundSystem.cpp | 135 +++++---- .../Systems/VisualInterpolationSystem.cpp | 32 +-- src/CoreLib/Player.cpp | 2 +- src/CoreLib/Systems/TickCallbackSystem.cpp | 5 - src/CoreLib/Utility/CrashHandlerWin32.cpp | 6 +- src/MapEditor/Gizmos/EditorGizmo.hpp | 2 +- src/MapEditor/Gizmos/PositionGizmo.hpp | 4 +- src/MapEditor/Logic/TileMapEditorMode.hpp | 6 +- src/MapEditor/Widgets/MapCanvas.cpp | 2 +- src/MapEditor/Widgets/MapCanvas.hpp | 4 +- src/MapEditor/Widgets/PlayWindow.hpp | 2 +- src/MapEditor/Widgets/TileSelectionWidget.hpp | 10 +- xmake-repo/packages/n/nazaraengine/xmake.lua | 256 +++++++++--------- xmake-requires.lock | 216 ++++++++++++--- xmake.lua | 14 +- 90 files changed, 900 insertions(+), 838 deletions(-) diff --git a/include/ClientLib/ClientEditorLayer.hpp b/include/ClientLib/ClientEditorLayer.hpp index 0488724c..9e343a83 100644 --- a/include/ClientLib/ClientEditorLayer.hpp +++ b/include/ClientLib/ClientEditorLayer.hpp @@ -20,7 +20,7 @@ namespace bw public: ClientEditorLayer(SharedMatch& match, LayerIndex layerIndex); ClientEditorLayer(const ClientEditorLayer&) = delete; - ClientEditorLayer(ClientEditorLayer&&) noexcept = default; + ClientEditorLayer(ClientEditorLayer&&) = delete; ~ClientEditorLayer() = default; virtual void FrameUpdate(float elapsedTime); diff --git a/include/ClientLib/ClientLayer.hpp b/include/ClientLib/ClientLayer.hpp index 42ce8280..171ba1b4 100644 --- a/include/ClientLib/ClientLayer.hpp +++ b/include/ClientLib/ClientLayer.hpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -30,7 +31,7 @@ namespace bw public: ClientLayer(ClientMatch& match, LayerIndex layerIndex, const Nz::Color& backgroundColor); ClientLayer(const ClientLayer&) = delete; - ClientLayer(ClientLayer&&) noexcept; + ClientLayer(ClientLayer&&) = delete; ~ClientLayer(); inline void Disable(); @@ -91,7 +92,7 @@ namespace bw ClientLayerEntity layerEntity; - NazaraSlot(Ndk::Entity, OnEntityDestruction, onDestruction); + NazaraSlot(DestructionWatcherComponent, OnDestruction, onDestruction); }; struct SoundData diff --git a/include/ClientLib/ClientLayerEntity.hpp b/include/ClientLib/ClientLayerEntity.hpp index 19fa3511..0f010961 100644 --- a/include/ClientLib/ClientLayerEntity.hpp +++ b/include/ClientLib/ClientLayerEntity.hpp @@ -31,7 +31,7 @@ namespace bw class BURGWAR_CLIENTLIB_API ClientLayerEntity final : public LayerVisualEntity { public: - ClientLayerEntity(ClientLayer& layer, entt::entity entity, Nz::UInt32 serverEntityId, EntityId uniqueId); + ClientLayerEntity(ClientLayer& layer, entt::handle entity, Nz::UInt32 serverEntityId, EntityId uniqueId); ClientLayerEntity(const ClientLayerEntity&) = delete; ClientLayerEntity(ClientLayerEntity&& entity) noexcept = default; ~ClientLayerEntity(); @@ -72,7 +72,7 @@ namespace bw struct DebugEntityIdData { - Nz::TextSpriteRef entityIdSprite; + std::shared_ptr entityIdSprite; }; struct HealthData @@ -80,8 +80,8 @@ namespace bw float spriteWidth; Nz::UInt16 currentHealth; Nz::UInt16 maxHealth; - Nz::SpriteRef healthSprite; - Nz::SpriteRef lostHealthSprite; + std::shared_ptr healthSprite; + std::shared_ptr lostHealthSprite; }; std::unique_ptr m_ghostEntity; diff --git a/include/ClientLib/ClientMatch.hpp b/include/ClientLib/ClientMatch.hpp index 0e806807..8fc8e5ea 100644 --- a/include/ClientLib/ClientMatch.hpp +++ b/include/ClientLib/ClientMatch.hpp @@ -26,12 +26,12 @@ #include #include #include -#include #include #include #include -#include +#include #include +#include #include #include #include @@ -54,7 +54,7 @@ namespace bw friend ClientSession; public: - ClientMatch(ClientEditorApp& burgApp, Nz::RenderWindow* window, Nz::RenderTarget* renderTarget, Ndk::Canvas* canvas, ClientSession& session, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData); + ClientMatch(ClientEditorApp& burgApp, Nz::RenderWindow* window, Nz::RenderTarget* renderTarget, Nz::Canvas* canvas, ClientSession& session, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData); ClientMatch(const ClientMatch&) = delete; ClientMatch(ClientMatch&&) = delete; ~ClientMatch(); @@ -65,7 +65,7 @@ namespace bw Nz::UInt64 EstimateServerTick() const; - void ForEachEntity(std::function func) override; + void ForEachEntity(tl::function_ref func) override; template void ForEachPlayer(F&& func); inline Nz::UInt16 GetActiveLayer(); @@ -85,8 +85,8 @@ namespace bw inline std::size_t GetLocalPlayerCount() const; inline const PlayerInputData& GetLocalPlayerInputs(std::size_t localPlayerIndex) const; const NetworkStringStore& GetNetworkStringStore() const override; - inline ParticleRegistry& GetParticleRegistry(); - inline const ParticleRegistry& GetParticleRegistry() const; + //inline ParticleRegistry& GetParticleRegistry(); + //inline const ParticleRegistry& GetParticleRegistry() const; inline ClientPlayer* GetPlayerByIndex(Nz::UInt16 playerIndex); inline entt::registry& GetRenderWorld(); std::shared_ptr GetSharedGamemode() const override; @@ -101,9 +101,9 @@ namespace bw inline void Quit(); void RegisterEntity(EntityId uniqueId, ClientLayerEntityHandle entity); - - entt::entity RetrieveEntityByUniqueId(EntityId uniqueId) const override; - EntityId RetrieveUniqueIdByEntity(entt::entity entity) const override; + + entt::handle RetrieveEntityByUniqueId(EntityId uniqueId) const override; + EntityId RetrieveUniqueIdByEntity(entt::handle entity) const override; void UnregisterEntity(EntityId uniqueId); @@ -141,7 +141,7 @@ namespace bw void BindEscapeMenu(); void BindPackets(); - void BindSignals(ClientEditorApp& burgApp, Nz::RenderWindow* window, Ndk::Canvas* canvas); + void BindSignals(ClientEditorApp& burgApp, Nz::RenderWindow* window, Nz::Canvas* canvas); void HandleChatMessage(const Packets::ChatMessage& packet); void HandleConsoleAnswer(const Packets::ConsoleAnswer& packet); void HandleEntityCreated(ClientLayer* layer, ClientLayerEntity& entity); @@ -245,6 +245,17 @@ namespace bw std::vector layers; }; + struct RenderWorld + { + RenderWorld() : + systemGraph(registry) + { + } + + entt::registry registry; + Nz::SystemGraph systemGraph; + }; + struct TickPrediction { Nz::UInt16 serverTick; @@ -260,8 +271,8 @@ namespace bw NazaraSlot(Nz::RenderTarget, OnRenderTargetSizeChange, m_onRenderTargetSizeChange); NazaraSlot(Nz::EventHandler, OnGainedFocus, m_onGainedFocus); NazaraSlot(Nz::EventHandler, OnLostFocus, m_onLostFocus); - NazaraSlot(Ndk::Canvas, OnUnhandledKeyPressed, m_onUnhandledKeyPressed); - NazaraSlot(Ndk::Canvas, OnUnhandledKeyReleased, m_onUnhandledKeyReleased); + NazaraSlot(Nz::Canvas, OnUnhandledKeyPressed, m_onUnhandledKeyPressed); + NazaraSlot(Nz::Canvas, OnUnhandledKeyReleased, m_onUnhandledKeyReleased); NazaraSlot(ClientLayer, OnEntityCreated, m_onEntityCreated); NazaraSlot(ClientLayer, OnEntityDelete, m_onEntityDelete); @@ -274,7 +285,7 @@ namespace bw std::optional m_remoteConsole; std::optional m_debug; std::optional m_localConsole; - std::optional m_particleRegistry; + //std::optional m_particleRegistry; std::shared_ptr m_gamemode; std::shared_ptr m_scriptingContext; std::string m_gamemodeName; @@ -284,10 +295,9 @@ namespace bw std::vector m_predictedInputs; std::vector m_tickedPackets; std::vector m_tickPredictions; - Ndk::Canvas* m_canvas; - Ndk::EntityHandle m_currentLayer; - entt::registry m_renderWorld; - Nz::ColorBackgroundRef m_colorBackground; + Nz::Canvas* m_canvas; + entt::handle m_currentLayer; + RenderWorld m_renderWorld; EntityId m_freeClientId; Nz::RenderTarget* m_renderTarget; Nz::RenderWindow* m_window; diff --git a/include/ClientLib/ClientMatch.inl b/include/ClientLib/ClientMatch.inl index 868d4f5b..2dcea56c 100644 --- a/include/ClientLib/ClientMatch.inl +++ b/include/ClientLib/ClientMatch.inl @@ -91,7 +91,7 @@ namespace bw assert(localPlayerIndex < m_localPlayers.size()); return m_localPlayers[localPlayerIndex].lastInputData; } - + /* inline ParticleRegistry& ClientMatch::GetParticleRegistry() { assert(m_particleRegistry); @@ -103,7 +103,7 @@ namespace bw assert(m_particleRegistry); return *m_particleRegistry; } - + */ inline ClientPlayer* ClientMatch::GetPlayerByIndex(Nz::UInt16 playerIndex) { if (playerIndex >= m_matchPlayers.size() || !m_matchPlayers[playerIndex].has_value()) @@ -114,7 +114,7 @@ namespace bw inline entt::registry& ClientMatch::GetRenderWorld() { - return m_renderWorld; + return m_renderWorld.registry; } inline void ClientMatch::Quit() diff --git a/include/ClientLib/Components/ClientMatchComponent.hpp b/include/ClientLib/Components/ClientMatchComponent.hpp index cc367306..f6568773 100644 --- a/include/ClientLib/Components/ClientMatchComponent.hpp +++ b/include/ClientLib/Components/ClientMatchComponent.hpp @@ -10,14 +10,14 @@ #include #include #include -#include +#include namespace bw { class ClientLayer; class ClientMatch; - class BURGWAR_CLIENTLIB_API ClientMatchComponent : public Ndk::Component + class BURGWAR_CLIENTLIB_API ClientMatchComponent { public: inline ClientMatchComponent(ClientMatch& clientMatch, LayerIndex layerIndex, EntityId uniqueId); @@ -29,11 +29,9 @@ namespace bw inline ClientMatch& GetClientMatch() const; inline EntityId GetUniqueId() const; - static Ndk::ComponentIndex componentIndex; - private: + Nz::MovablePtr m_clientMatch; EntityId m_uniqueId; - ClientMatch& m_clientMatch; LayerIndex m_layerIndex; }; } diff --git a/include/ClientLib/Components/ClientMatchComponent.inl b/include/ClientLib/Components/ClientMatchComponent.inl index 793ce369..5f6c8d37 100644 --- a/include/ClientLib/Components/ClientMatchComponent.inl +++ b/include/ClientLib/Components/ClientMatchComponent.inl @@ -7,8 +7,8 @@ namespace bw { inline ClientMatchComponent::ClientMatchComponent(ClientMatch& clientMatch, LayerIndex layerIndex, EntityId uniqueId) : + m_clientMatch(&clientMatch), m_uniqueId(uniqueId), - m_clientMatch(clientMatch), m_layerIndex(layerIndex) { } @@ -20,7 +20,7 @@ namespace bw inline ClientMatch& ClientMatchComponent::GetClientMatch() const { - return m_clientMatch; + return *m_clientMatch; } inline EntityId ClientMatchComponent::GetUniqueId() const diff --git a/include/ClientLib/Components/ClientOwnerComponent.hpp b/include/ClientLib/Components/ClientOwnerComponent.hpp index 5c9ea586..2ef229dd 100644 --- a/include/ClientLib/Components/ClientOwnerComponent.hpp +++ b/include/ClientLib/Components/ClientOwnerComponent.hpp @@ -9,12 +9,11 @@ #include #include -#include #include namespace bw { - class BURGWAR_CLIENTLIB_API ClientOwnerComponent : public Ndk::Component + class BURGWAR_CLIENTLIB_API ClientOwnerComponent { public: ClientOwnerComponent(ClientPlayerHandle owner); @@ -22,8 +21,6 @@ namespace bw inline ClientPlayer* GetOwner() const; - static Ndk::ComponentIndex componentIndex; - private: ClientPlayerHandle m_owner; }; diff --git a/include/ClientLib/Components/LocalPlayerControlledComponent.hpp b/include/ClientLib/Components/LocalPlayerControlledComponent.hpp index d2a80f8b..14a56b54 100644 --- a/include/ClientLib/Components/LocalPlayerControlledComponent.hpp +++ b/include/ClientLib/Components/LocalPlayerControlledComponent.hpp @@ -9,14 +9,13 @@ #include #include -#include #include namespace bw { class ClientMatch; - class BURGWAR_CLIENTLIB_API LocalPlayerControlledComponent : public Ndk::Component + class BURGWAR_CLIENTLIB_API LocalPlayerControlledComponent { public: inline LocalPlayerControlledComponent(ClientMatch& clientMatch, Nz::UInt8 localPlayerIndex); @@ -25,8 +24,6 @@ namespace bw inline ClientMatch& GetClientMatch() const; inline Nz::UInt8 GetLocalPlayerIndex() const; - static Ndk::ComponentIndex componentIndex; - private: ClientMatch& m_clientMatch; Nz::UInt8 m_localPlayerIndex; diff --git a/include/ClientLib/Components/SoundEmitterComponent.hpp b/include/ClientLib/Components/SoundEmitterComponent.hpp index 147b5191..4b003620 100644 --- a/include/ClientLib/Components/SoundEmitterComponent.hpp +++ b/include/ClientLib/Components/SoundEmitterComponent.hpp @@ -10,13 +10,12 @@ #include #include #include -#include #include #include namespace bw { - class BURGWAR_CLIENTLIB_API SoundEmitterComponent : public Ndk::Component + class BURGWAR_CLIENTLIB_API SoundEmitterComponent { friend class SoundSystem; @@ -29,8 +28,6 @@ namespace bw Nz::UInt32 PlaySound(const std::shared_ptr& soundBuffer, const Nz::Vector3f& soundPosition, bool attachedToEntity, bool isLooping, bool isSpatialized); void StopSound(Nz::UInt32 soundId); - static Ndk::ComponentIndex componentIndex; - SoundEmitterComponent& operator=(const SoundEmitterComponent&) = delete; SoundEmitterComponent& operator=(SoundEmitterComponent&&) = default; diff --git a/include/ClientLib/Components/VisibleLayerComponent.hpp b/include/ClientLib/Components/VisibleLayerComponent.hpp index 2ba91039..332f3ba1 100644 --- a/include/ClientLib/Components/VisibleLayerComponent.hpp +++ b/include/ClientLib/Components/VisibleLayerComponent.hpp @@ -14,17 +14,17 @@ #include #include #include -#include #include namespace bw { class ClientLayerEntity; - class BURGWAR_CLIENTLIB_API VisibleLayerComponent : public Ndk::Component + class BURGWAR_CLIENTLIB_API VisibleLayerComponent { public: inline VisibleLayerComponent(entt::registry& renderWorld); + VisibleLayerComponent(VisibleLayerComponent&&) noexcept = default; ~VisibleLayerComponent() = default; void Clear(); @@ -32,8 +32,6 @@ namespace bw void RegisterLocalLayer(ClientLayer& localLayer, int renderOrder, const Nz::Vector2f& scale, const Nz::Vector2f& parallaxFactor); void RegisterVisibleLayer(Camera& camera, VisualLayer& visualLayer, int renderOrder, const Nz::Vector2f& scale, const Nz::Vector2f& parallaxFactor); - static Ndk::ComponentIndex componentIndex; - private: struct VisibleLayer; diff --git a/include/ClientLib/Components/VisualComponent.hpp b/include/ClientLib/Components/VisualComponent.hpp index f1e17aac..1a5008a7 100644 --- a/include/ClientLib/Components/VisualComponent.hpp +++ b/include/ClientLib/Components/VisualComponent.hpp @@ -9,11 +9,10 @@ #include #include -#include namespace bw { - class BURGWAR_CLIENTLIB_API VisualComponent : public Ndk::Component + class BURGWAR_CLIENTLIB_API VisualComponent { public: inline VisualComponent(LayerVisualEntityHandle visualEntity); @@ -21,8 +20,6 @@ namespace bw inline const LayerVisualEntityHandle& GetLayerVisual() const; - static Ndk::ComponentIndex componentIndex; - private: LayerVisualEntityHandle m_visualEntity; }; diff --git a/include/ClientLib/Components/VisualInterpolationComponent.hpp b/include/ClientLib/Components/VisualInterpolationComponent.hpp index bc2e261b..1dc66e5e 100644 --- a/include/ClientLib/Components/VisualInterpolationComponent.hpp +++ b/include/ClientLib/Components/VisualInterpolationComponent.hpp @@ -10,11 +10,10 @@ #include #include #include -#include namespace bw { - class BURGWAR_CLIENTLIB_API VisualInterpolationComponent : public Ndk::Component + class BURGWAR_CLIENTLIB_API VisualInterpolationComponent { friend class VisualInterpolationSystem; @@ -22,8 +21,6 @@ namespace bw inline VisualInterpolationComponent(); ~VisualInterpolationComponent() = default; - static Ndk::ComponentIndex componentIndex; - private: inline const Nz::Vector2f& GetLastPosition(); inline const Nz::RadianAnglef& GetLastRotation(); diff --git a/include/ClientLib/EscapeMenu.hpp b/include/ClientLib/EscapeMenu.hpp index 06cb07df..eaac1ef0 100644 --- a/include/ClientLib/EscapeMenu.hpp +++ b/include/ClientLib/EscapeMenu.hpp @@ -10,10 +10,9 @@ #include #include #include -#include -#include #include #include +#include namespace bw { @@ -23,7 +22,7 @@ namespace bw class BURGWAR_CLIENTLIB_API EscapeMenu { public: - EscapeMenu(ClientEditorApp& clientEditorApp, Ndk::Canvas* canvas); + EscapeMenu(ClientEditorApp& clientEditorApp, Nz::Canvas* canvas); EscapeMenu(const EscapeMenu&) = delete; EscapeMenu(EscapeMenu&&) = delete; ~EscapeMenu(); @@ -46,10 +45,10 @@ namespace bw void Layout(); - Ndk::ButtonWidget* m_closeMenuButton; - Ndk::ButtonWidget* m_leaveMatchButton; - Ndk::ButtonWidget* m_optionsButton; - Ndk::ButtonWidget* m_quitAppButton; + Nz::ButtonWidget* m_closeMenuButton; + Nz::ButtonWidget* m_leaveMatchButton; + Nz::ButtonWidget* m_optionsButton; + Nz::ButtonWidget* m_quitAppButton; Nz::BaseWidget* m_backgroundWidget; ClientEditorApp& m_app; OptionWidget* m_optionWidget; diff --git a/include/ClientLib/InputPoller.hpp b/include/ClientLib/InputPoller.hpp index aa4d153b..88548c15 100644 --- a/include/ClientLib/InputPoller.hpp +++ b/include/ClientLib/InputPoller.hpp @@ -11,7 +11,6 @@ #include #include #include -#include namespace bw { diff --git a/include/ClientLib/LayerVisualEntity.inl b/include/ClientLib/LayerVisualEntity.inl index e6d617ae..595536ea 100644 --- a/include/ClientLib/LayerVisualEntity.inl +++ b/include/ClientLib/LayerVisualEntity.inl @@ -45,6 +45,8 @@ namespace bw inline bool LayerVisualEntity::IsEnabled() const { - return m_entity->IsEnabled(); + return true; + // TODO + //return m_entity->IsEnabled(); } } diff --git a/include/ClientLib/OptionWidget.hpp b/include/ClientLib/OptionWidget.hpp index af02c3a2..1a99c983 100644 --- a/include/ClientLib/OptionWidget.hpp +++ b/include/ClientLib/OptionWidget.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include @@ -61,7 +61,7 @@ namespace bw struct Option { std::string keyName; - Ndk::LabelWidget* label; + Nz::LabelWidget* label; }; struct BoolOption : Option @@ -97,18 +97,18 @@ namespace bw struct Section { - Ndk::ButtonWidget* button; + Nz::ButtonWidget* button; std::vector options; - NazaraSlot(Ndk::ButtonWidget, OnButtonTrigger, onTriggerSlot); + NazaraSlot(Nz::ButtonWidget, OnButtonTrigger, onTriggerSlot); }; std::unordered_map m_sections; std::unordered_map m_updatedValues; Section* m_activeSection; - Ndk::ButtonWidget* m_applyButton; - Ndk::ButtonWidget* m_backButton; - Ndk::ButtonWidget* m_resetButton; + Nz::ButtonWidget* m_applyButton; + Nz::ButtonWidget* m_backButton; + Nz::ButtonWidget* m_resetButton; ConfigFile& m_playerConfig; bool m_ignoreWidgetUpdate; }; diff --git a/include/ClientLib/Scoreboard.hpp b/include/ClientLib/Scoreboard.hpp index c4bd155e..0698c0aa 100644 --- a/include/ClientLib/Scoreboard.hpp +++ b/include/ClientLib/Scoreboard.hpp @@ -34,7 +34,7 @@ namespace bw void RegisterPlayer(std::size_t playerIndex, std::size_t teamId, std::vector values, std::optional color = {}, bool isLocalPlayer = false); - Nz::String ToString() const; + std::string ToString() const; void UnregisterPlayer(std::size_t playerIndex); @@ -54,7 +54,7 @@ namespace bw struct ColumnData { std::string value; - Ndk::LabelWidget* label; + Nz::LabelWidget* label; }; Nz::BaseWidget* background; @@ -66,7 +66,7 @@ namespace bw struct ColumnData { std::string name; - Ndk::LabelWidget* widget; + Nz::LabelWidget* widget; }; struct TeamData @@ -74,8 +74,8 @@ namespace bw std::string name; Nz::Color color; Nz::BaseWidget* background; - Ndk::ImageWidget* line; - Ndk::LabelWidget* widget; + Nz::ImageWidget* line; + Nz::LabelWidget* widget; }; std::vector m_columns; @@ -84,7 +84,7 @@ namespace bw Nz::BaseWidget* m_backgroundWidget; Nz::BaseWidget* m_columnBackgroundWidget; Nz::BaseWidget* m_contentWidget; - Ndk::ScrollAreaWidget* m_scrollArea; + Nz::ScrollAreaWidget* m_scrollArea; const Logger& m_logger; }; } diff --git a/include/ClientLib/Scripting/ClientEditorEntityStore.hpp b/include/ClientLib/Scripting/ClientEditorEntityStore.hpp index 814400c6..785840dc 100644 --- a/include/ClientLib/Scripting/ClientEditorEntityStore.hpp +++ b/include/ClientLib/Scripting/ClientEditorEntityStore.hpp @@ -25,8 +25,8 @@ namespace bw ClientEditorEntityStore(ClientEditorEntityStore&&) = delete; ~ClientEditorEntityStore() = default; - bool InitializeEntity(entt::entity entity) const; - virtual entt::entity InstantiateEntity(entt::registry& registry, std::size_t entityIndex, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, entt::entity parentEntity = entt::null) const; + bool InitializeEntity(entt::handle entity) const; + virtual entt::handle InstantiateEntity(entt::registry& registry, std::size_t entityIndex, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, entt::handle parentEntity = {}) const; protected: void InitializeElementTable(sol::main_table& elementTable) override; diff --git a/include/ClientLib/Scripting/ClientElementLibrary.hpp b/include/ClientLib/Scripting/ClientElementLibrary.hpp index 80792cf8..3f6062c4 100644 --- a/include/ClientLib/Scripting/ClientElementLibrary.hpp +++ b/include/ClientLib/Scripting/ClientElementLibrary.hpp @@ -24,7 +24,7 @@ namespace bw protected: virtual void RegisterClientLibrary(sol::table& elementTable); - void SetScale(entt::entity entity, float newScale) override; + void SetScale(entt::handle entity, float newScale) override; private: ClientAssetStore& m_assetStore; diff --git a/include/ClientLib/Scripting/ClientEntityLibrary.hpp b/include/ClientLib/Scripting/ClientEntityLibrary.hpp index caed6701..63300314 100644 --- a/include/ClientLib/Scripting/ClientEntityLibrary.hpp +++ b/include/ClientLib/Scripting/ClientEntityLibrary.hpp @@ -24,7 +24,7 @@ namespace bw void RegisterLibrary(sol::table& elementMetatable) override; protected: - void InitRigidBody(lua_State* L, entt::entity entity, float mass) override; + void InitRigidBody(lua_State* L, entt::handle entity, float mass) override; private: void RegisterClientLibrary(sol::table& elementMetatable); diff --git a/include/ClientLib/Scripting/ParticleGroup.hpp b/include/ClientLib/Scripting/ParticleGroup.hpp index fea3b160..c26d7e0f 100644 --- a/include/ClientLib/Scripting/ParticleGroup.hpp +++ b/include/ClientLib/Scripting/ParticleGroup.hpp @@ -38,7 +38,7 @@ namespace bw ParticleGroup& operator=(ParticleGroup&&) noexcept = default; private: - Ndk::EntityOwner m_entity; + EntityOwner m_entity; const ParticleRegistry& m_registry; }; } diff --git a/include/ClientLib/Scripting/ParticleRegistry.hpp b/include/ClientLib/Scripting/ParticleRegistry.hpp index b051e0b9..42c6f51b 100644 --- a/include/ClientLib/Scripting/ParticleRegistry.hpp +++ b/include/ClientLib/Scripting/ParticleRegistry.hpp @@ -7,11 +7,9 @@ #ifndef BURGWAR_CLIENTLIB_SCRIPTING_PARTICLEREGISTRY_HPP #define BURGWAR_CLIENTLIB_SCRIPTING_PARTICLEREGISTRY_HPP +#if 0 + #include -#include -#include -#include -#include #include #include #include @@ -56,3 +54,5 @@ namespace bw #include #endif + +#endif diff --git a/include/ClientLib/Scripting/Sprite.hpp b/include/ClientLib/Scripting/Sprite.hpp index ac2aad75..e5a3a9bd 100644 --- a/include/ClientLib/Scripting/Sprite.hpp +++ b/include/ClientLib/Scripting/Sprite.hpp @@ -12,7 +12,6 @@ #include #include #include -#include #include namespace bw @@ -20,7 +19,7 @@ namespace bw class BURGWAR_CLIENTLIB_API Sprite { public: - inline Sprite(LayerVisualEntityHandle visualEntity, Nz::SpriteRef sprite, const Nz::Matrix4f& transformMatrix, int renderOrder); + inline Sprite(LayerVisualEntityHandle visualEntity, std::shared_ptr sprite, const Nz::Matrix4f& transformMatrix, int renderOrder); Sprite(const Sprite&) = delete; Sprite(Sprite&&) noexcept = default; ~Sprite() = default; @@ -49,7 +48,7 @@ namespace bw LayerVisualEntityHandle m_visualEntity; Nz::Matrix4f m_transformMatrix; - Nz::SpriteRef m_sprite; + std::shared_ptr m_sprite; int m_renderOrder; bool m_isVisible; }; diff --git a/include/ClientLib/Scripting/Sprite.inl b/include/ClientLib/Scripting/Sprite.inl index e12c8cc9..1028029e 100644 --- a/include/ClientLib/Scripting/Sprite.inl +++ b/include/ClientLib/Scripting/Sprite.inl @@ -6,7 +6,7 @@ namespace bw { - inline Sprite::Sprite(LayerVisualEntityHandle visualEntity, Nz::SpriteRef sprite, const Nz::Matrix4f& transformMatrix, int renderOrder) : + inline Sprite::Sprite(LayerVisualEntityHandle visualEntity, std::shared_ptr sprite, const Nz::Matrix4f& transformMatrix, int renderOrder) : m_visualEntity(std::move(visualEntity)), m_transformMatrix(transformMatrix), m_sprite(std::move(sprite)), diff --git a/include/ClientLib/Scripting/Text.hpp b/include/ClientLib/Scripting/Text.hpp index 9bd034a4..51b33f5d 100644 --- a/include/ClientLib/Scripting/Text.hpp +++ b/include/ClientLib/Scripting/Text.hpp @@ -20,7 +20,7 @@ namespace bw class Text { public: - inline Text(LayerVisualEntityHandle visualEntity, Nz::SimpleTextDrawer drawer, Nz::TextSpriteRef textSprite, const Nz::Matrix4f& transformMatrix, int renderOrder, bool isHovering); + inline Text(LayerVisualEntityHandle visualEntity, Nz::SimpleTextDrawer drawer, std::shared_ptr textSprite, const Nz::Matrix4f& transformMatrix, int renderOrder, bool isHovering); Text(const Text&) = delete; Text(Text&&) = default; ~Text() = default; @@ -50,7 +50,7 @@ namespace bw LayerVisualEntityHandle m_visualEntity; Nz::Matrix4f m_transformMatrix; Nz::SimpleTextDrawer m_drawer; - Nz::TextSpriteRef m_textSprite; + std::shared_ptr m_textSprite; bool m_isHovering; bool m_isVisible; float m_hoveringHeight; diff --git a/include/ClientLib/Scripting/Text.inl b/include/ClientLib/Scripting/Text.inl index dd4856a5..a2c44c71 100644 --- a/include/ClientLib/Scripting/Text.inl +++ b/include/ClientLib/Scripting/Text.inl @@ -6,7 +6,7 @@ namespace bw { - inline Text::Text(LayerVisualEntityHandle visualEntity, Nz::SimpleTextDrawer drawer, Nz::TextSpriteRef textSprite, const Nz::Matrix4f& transformMatrix, int renderOrder, bool isHovering) : + inline Text::Text(LayerVisualEntityHandle visualEntity, Nz::SimpleTextDrawer drawer, std::shared_ptr textSprite, const Nz::Matrix4f& transformMatrix, int renderOrder, bool isHovering) : m_visualEntity(std::move(visualEntity)), m_transformMatrix(transformMatrix), m_drawer(std::move(drawer)), diff --git a/include/ClientLib/SoundEntity.hpp b/include/ClientLib/SoundEntity.hpp index 331dd255..6f1ced23 100644 --- a/include/ClientLib/SoundEntity.hpp +++ b/include/ClientLib/SoundEntity.hpp @@ -29,7 +29,7 @@ namespace bw SoundEntity(SoundEntity&& entity) noexcept; ~SoundEntity(); - inline entt::entity GetEntity() const; + inline entt::handle GetEntity() const; void PlaySound(std::size_t soundIndex, const std::shared_ptr& soundBuffer, bool isLooping, bool isSpatialized); @@ -42,7 +42,7 @@ namespace bw private: std::vector m_soundIds; - Ndk::EntityOwner m_entity; + EntityOwner m_entity; ClientLayerSoundHandle m_layerSound; float m_depth; }; diff --git a/include/ClientLib/SoundEntity.inl b/include/ClientLib/SoundEntity.inl index 98c1ce39..7305e197 100644 --- a/include/ClientLib/SoundEntity.inl +++ b/include/ClientLib/SoundEntity.inl @@ -6,7 +6,7 @@ namespace bw { - inline entt::entity SoundEntity::GetEntity() const + inline entt::handle SoundEntity::GetEntity() const { return m_entity; } diff --git a/include/ClientLib/Systems/FrameCallbackSystem.hpp b/include/ClientLib/Systems/FrameCallbackSystem.hpp index c002b78d..2f8f4cb3 100644 --- a/include/ClientLib/Systems/FrameCallbackSystem.hpp +++ b/include/ClientLib/Systems/FrameCallbackSystem.hpp @@ -8,28 +8,27 @@ #define BURGWAR_CLIENTLIB_SYSTEMS_FRAMECALLBACKSYSTEM_HPP #include -#include -#include +#include #include namespace bw { - class ClientMatch; - - class BURGWAR_CLIENTLIB_API FrameCallbackSystem : public Ndk::System + class BURGWAR_CLIENTLIB_API FrameCallbackSystem { public: - FrameCallbackSystem(); + static constexpr Nz::Int64 ExecutionOrder = 100; + + FrameCallbackSystem(entt::registry& registry); ~FrameCallbackSystem() = default; - static Ndk::SystemIndex systemIndex; + void Update(float elapsedTime); private: - void OnEntityRemoved(Ndk::Entity* entity) override; - void OnEntityValidation(Ndk::Entity* entity, bool justAdded) override; - void OnUpdate(float elapsedTime) override; + void OnScriptDestroy(entt::registry& registry, entt::entity entity); - Ndk::EntityList m_frameUpdateEntities; + std::unordered_set m_frameUpdateEntities; + entt::scoped_connection m_scriptDestroyConnection; + entt::registry& m_registry; }; } diff --git a/include/ClientLib/Systems/PostFrameCallbackSystem.hpp b/include/ClientLib/Systems/PostFrameCallbackSystem.hpp index 225fa8af..2f194ea2 100644 --- a/include/ClientLib/Systems/PostFrameCallbackSystem.hpp +++ b/include/ClientLib/Systems/PostFrameCallbackSystem.hpp @@ -8,26 +8,27 @@ #define BURGWAR_CLIENTLIB_SYSTEMS_POSTFRAMECALLBACKSYSTEM_HPP #include -#include -#include +#include #include namespace bw { - class BURGWAR_CLIENTLIB_API PostFrameCallbackSystem : public Ndk::System + class BURGWAR_CLIENTLIB_API PostFrameCallbackSystem { public: - PostFrameCallbackSystem(); + static constexpr Nz::Int64 ExecutionOrder = 150; + + PostFrameCallbackSystem(entt::registry& registry); ~PostFrameCallbackSystem() = default; - static Ndk::SystemIndex systemIndex; + void Update(float elapsedTime); private: - void OnEntityRemoved(Ndk::Entity* entity) override; - void OnEntityValidation(Ndk::Entity* entity, bool justAdded) override; - void OnUpdate(float elapsedTime) override; + void OnScriptDestroy(entt::registry& registry, entt::entity entity); - Ndk::EntityList m_frameUpdateEntities; + std::unordered_set m_frameUpdateEntities; + entt::scoped_connection m_scriptDestroyConnection; + entt::registry& m_registry; }; } diff --git a/include/ClientLib/Systems/SoundSystem.hpp b/include/ClientLib/Systems/SoundSystem.hpp index 98ac225c..2334bc88 100644 --- a/include/ClientLib/Systems/SoundSystem.hpp +++ b/include/ClientLib/Systems/SoundSystem.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include @@ -18,27 +18,25 @@ namespace bw { class ConfigFile; - class BURGWAR_CLIENTLIB_API SoundSystem : public Ndk::System + class BURGWAR_CLIENTLIB_API SoundSystem { friend class SoundEmitterComponent; public: - SoundSystem(ConfigFile& playerSettings); + SoundSystem(entt::registry& registry, ConfigFile& playerSettings); ~SoundSystem() = default; - static Ndk::SystemIndex systemIndex; + void Update(float elapsedTime); static constexpr Nz::UInt32 InvalidSoundId = 0; private: + void OnSoundDestroy(entt::registry& registry, entt::entity entity); + Nz::UInt32 PlaySound(const std::shared_ptr& soundBuffer, const Nz::Vector3f& soundPosition, bool attachedToEntity, bool isLooping, bool isSpatialized); void StopSound(Nz::UInt32 soundId); void UpdateVolume(float newVolume); - void OnEntityRemoved(Ndk::Entity* entity) override; - void OnEntityValidation(Ndk::Entity* entity, bool justAdded) override; - void OnUpdate(float elapsedTime) override; - struct SoundData { Nz::Sound sound; @@ -47,12 +45,16 @@ namespace bw }; std::size_t m_maxSoundInPool; + std::unordered_set m_movableEntities; std::vector m_soundPool; tsl::hopscotch_map m_playingSounds; + entt::observer m_observer; + entt::scoped_connection m_nodeDestroyConnection; + entt::scoped_connection m_soundEmitterDestroyConnection; + entt::registry& m_registry; typename Nz::Signal::ConnectionGuard m_effectVolumeUpdateSlot; Nz::Vector3f m_soundOffset; Nz::UInt32 m_nextSoundId; - Ndk::EntityList m_movableEntities; float m_volume; }; } diff --git a/include/ClientLib/Systems/VisualInterpolationSystem.hpp b/include/ClientLib/Systems/VisualInterpolationSystem.hpp index fd35ab78..69b8f953 100644 --- a/include/ClientLib/Systems/VisualInterpolationSystem.hpp +++ b/include/ClientLib/Systems/VisualInterpolationSystem.hpp @@ -8,21 +8,21 @@ #define BURGWAR_CLIENTLIB_SYSTEMS_VISUALINTERPOLATIONSYSTEM_HPP #include -#include +#include namespace bw { - class BURGWAR_CLIENTLIB_API VisualInterpolationSystem : public Ndk::System + class BURGWAR_CLIENTLIB_API VisualInterpolationSystem { public: - VisualInterpolationSystem(); + VisualInterpolationSystem(entt::registry& registry); ~VisualInterpolationSystem() = default; - static Ndk::SystemIndex systemIndex; + void Update(float elapsedTime); private: - void OnEntityAdded(Ndk::Entity* entity) override; - void OnUpdate(float elapsedTime) override; + entt::observer m_observer; + entt::registry& m_registry; }; } diff --git a/include/ClientLib/VisualEntity.hpp b/include/ClientLib/VisualEntity.hpp index 0db4a2cc..f68e4ea5 100644 --- a/include/ClientLib/VisualEntity.hpp +++ b/include/ClientLib/VisualEntity.hpp @@ -31,7 +31,7 @@ namespace bw VisualEntity(VisualEntity&& entity) noexcept; ~VisualEntity(); - inline entt::entity GetEntity() const; + inline entt::handle GetEntity() const; void Update(const Nz::Vector2f& position, const Nz::Quaternionf& rotation, const Nz::Vector2f& scale); @@ -56,12 +56,12 @@ namespace bw struct HoveringRenderable { float offset; - Ndk::EntityOwner entity; + EntityOwner entity; std::shared_ptr renderable; }; std::vector m_hoveringRenderables; - Ndk::EntityOwner m_entity; + EntityOwner m_entity; LayerVisualEntityHandle m_visualEntity; int m_baseRenderOrder; }; diff --git a/include/ClientLib/VisualEntity.inl b/include/ClientLib/VisualEntity.inl index ead0e6ad..0858600e 100644 --- a/include/ClientLib/VisualEntity.inl +++ b/include/ClientLib/VisualEntity.inl @@ -6,15 +6,16 @@ namespace bw { - inline entt::entity VisualEntity::GetEntity() const + inline entt::handle VisualEntity::GetEntity() const { return m_entity; } inline void VisualEntity::Enable(bool enable) { - m_entity->Enable(enable); + // TODO + /*m_entity->Enable(enable); for (auto& hoveringRenderable : m_hoveringRenderables) - hoveringRenderable.entity->Enable(enable); + hoveringRenderable.entity->Enable(enable);*/ } } diff --git a/include/CoreLib/Systems/TickCallbackSystem.hpp b/include/CoreLib/Systems/TickCallbackSystem.hpp index d06cf29b..8c233fad 100644 --- a/include/CoreLib/Systems/TickCallbackSystem.hpp +++ b/include/CoreLib/Systems/TickCallbackSystem.hpp @@ -20,7 +20,7 @@ namespace bw { public: TickCallbackSystem(entt::registry& registry, SharedMatch& match); - ~TickCallbackSystem(); + ~TickCallbackSystem() = default; void Update(float elapsedTime); @@ -28,8 +28,8 @@ namespace bw void OnScriptDestroy(entt::registry& registry, entt::entity entity); std::unordered_set m_tickableEntities; - entt::connection m_scriptDestroyConnection; entt::observer m_scriptObserver; + entt::scoped_connection m_scriptDestroyConnection; entt::registry& m_registry; SharedMatch& m_match; }; diff --git a/include/CoreLib/TerrainLayer.hpp b/include/CoreLib/TerrainLayer.hpp index 70026527..b7e4a2c1 100644 --- a/include/CoreLib/TerrainLayer.hpp +++ b/include/CoreLib/TerrainLayer.hpp @@ -24,7 +24,7 @@ namespace bw public: TerrainLayer(Match& match, LayerIndex layerIndex, const Map::Layer& layerData); TerrainLayer(const TerrainLayer&) = delete; - TerrainLayer(TerrainLayer&&) noexcept = default; + TerrainLayer(TerrainLayer&&) = delete; ~TerrainLayer() = default; Match& GetMatch(); diff --git a/src/Client/ClientApp.cpp b/src/Client/ClientApp.cpp index 2fa2f4a1..543824ac 100644 --- a/src/Client/ClientApp.cpp +++ b/src/Client/ClientApp.cpp @@ -85,7 +85,7 @@ namespace bw if (m_config.GetBoolValue("Debug.ShowVersion")) { - Ndk::LabelWidget* versionLabel = m_stateData->canvas->Add(); + Nz::LabelWidget* versionLabel = m_stateData->canvas->Add(); versionLabel->UpdateText(Nz::SimpleTextDrawer::Draw(std::to_string(GameMajorVersion) + "." + std::to_string(GameMinorVersion) + "." + std::to_string(GamePatchVersion), 14)); versionLabel->Resize(versionLabel->GetPreferredSize()); diff --git a/src/Client/States/AbstractState.hpp b/src/Client/States/AbstractState.hpp index 8f872d21..46f7ed92 100644 --- a/src/Client/States/AbstractState.hpp +++ b/src/Client/States/AbstractState.hpp @@ -50,7 +50,7 @@ namespace bw std::shared_ptr m_stateData; std::vector> m_cleanupFunctions; std::vector m_widgets; - std::vector m_entities; + std::vector m_entities; bool m_isVisible; }; } diff --git a/src/Client/States/BackgroundState.hpp b/src/Client/States/BackgroundState.hpp index 2451108e..2488f311 100644 --- a/src/Client/States/BackgroundState.hpp +++ b/src/Client/States/BackgroundState.hpp @@ -26,8 +26,8 @@ namespace bw void LayoutWidgets() override; - Ndk::EntityOwner m_spriteEntity; - Nz::SpriteRef m_backgroundSprite; + EntityOwner m_spriteEntity; + std::shared_ptr m_backgroundSprite; }; } diff --git a/src/Client/States/Game/CancelableState.cpp b/src/Client/States/Game/CancelableState.cpp index 06e52c49..78bc5419 100644 --- a/src/Client/States/Game/CancelableState.cpp +++ b/src/Client/States/Game/CancelableState.cpp @@ -13,11 +13,11 @@ namespace bw StatusState(std::move(stateData)), m_originalState(std::move(originalState)) { - m_cancelButton = CreateWidget(); + m_cancelButton = CreateWidget(); m_cancelButton->UpdateText(Nz::SimpleTextDrawer::Draw("Cancel", 24)); m_cancelButton->Resize(m_cancelButton->GetPreferredSize()); - m_cancelButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) + m_cancelButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { Cancel(); }); diff --git a/src/Client/States/Game/CancelableState.hpp b/src/Client/States/Game/CancelableState.hpp index 981c0474..c7a44f32 100644 --- a/src/Client/States/Game/CancelableState.hpp +++ b/src/Client/States/Game/CancelableState.hpp @@ -35,7 +35,7 @@ namespace bw std::function m_nextStateCallback; std::shared_ptr m_originalState; - Ndk::ButtonWidget* m_cancelButton; + Nz::ButtonWidget* m_cancelButton; float m_nextStateDelay; }; } diff --git a/src/Client/States/Game/ConnectedState.cpp b/src/Client/States/Game/ConnectedState.cpp index 9dc1704f..88748aca 100644 --- a/src/Client/States/Game/ConnectedState.cpp +++ b/src/Client/States/Game/ConnectedState.cpp @@ -59,7 +59,7 @@ namespace bw cursor += m_connectionLostSprite->GetSize().y; } - for (Ndk::LabelWidget* label : { m_pingLabel, m_downloadSpeedLabel, m_uploadSpeedLabel }) + for (Nz::LabelWidget* label : { m_pingLabel, m_downloadSpeedLabel, m_uploadSpeedLabel }) { if (label) { @@ -172,7 +172,7 @@ namespace bw } if (m_connectionInfoFlags & InfoFlags::DownloadSpeed) - m_downloadSpeedLabel = CreateWidget(); + m_downloadSpeedLabel = CreateWidget(); else if (m_downloadSpeedLabel) { DestroyWidget(m_downloadSpeedLabel); @@ -180,7 +180,7 @@ namespace bw } if (m_connectionInfoFlags & InfoFlags::Ping) - m_pingLabel = CreateWidget(); + m_pingLabel = CreateWidget(); else if (m_pingLabel) { DestroyWidget(m_pingLabel); @@ -188,7 +188,7 @@ namespace bw } if (m_connectionInfoFlags & InfoFlags::UploadSpeed) - m_uploadSpeedLabel = CreateWidget(); + m_uploadSpeedLabel = CreateWidget(); else if (m_uploadSpeedLabel) { DestroyWidget(m_uploadSpeedLabel); diff --git a/src/Client/States/Game/ConnectedState.hpp b/src/Client/States/Game/ConnectedState.hpp index ee14e9cd..394dd2e7 100644 --- a/src/Client/States/Game/ConnectedState.hpp +++ b/src/Client/States/Game/ConnectedState.hpp @@ -47,12 +47,12 @@ namespace bw std::optional m_lastSessionInfo; std::shared_ptr m_firstState; std::shared_ptr m_clientSession; - Ndk::EntityOwner m_connectionLostEntity; - Ndk::LabelWidget* m_downloadSpeedLabel; - Ndk::LabelWidget* m_pingLabel; - Ndk::LabelWidget* m_uploadSpeedLabel; + EntityOwner m_connectionLostEntity; + Nz::LabelWidget* m_downloadSpeedLabel; + Nz::LabelWidget* m_pingLabel; + Nz::LabelWidget* m_uploadSpeedLabel; Nz::Clock m_lastSessionClock; - Nz::SpriteRef m_connectionLostSprite; + std::shared_ptr m_connectionLostSprite; Nz::UInt8 m_connectionInfoFlags; Nz::UInt32 m_queryId; AverageValues m_downloadSpeed; diff --git a/src/Client/States/Game/ConnectionLostState.cpp b/src/Client/States/Game/ConnectionLostState.cpp index a8f3efa5..d31575e6 100644 --- a/src/Client/States/Game/ConnectionLostState.cpp +++ b/src/Client/States/Game/ConnectionLostState.cpp @@ -14,7 +14,7 @@ namespace bw AbstractState(std::move(stateData)), m_timer(5.f) { - Ndk::LabelWidget* labelWidget = CreateWidget(); + Nz::LabelWidget* labelWidget = CreateWidget(); labelWidget->UpdateText(Nz::SimpleTextDrawer::Draw("Connection lost.", 36, Nz::TextStyle_Regular, Nz::Color::Red)); labelWidget->Center(); } diff --git a/src/Client/States/Game/StatusState.cpp b/src/Client/States/Game/StatusState.cpp index 25793bdb..4593a0b6 100644 --- a/src/Client/States/Game/StatusState.cpp +++ b/src/Client/States/Game/StatusState.cpp @@ -12,7 +12,7 @@ namespace bw StatusState::StatusState(std::shared_ptr stateData) : AbstractState(std::move(stateData)) { - m_statusLabel = CreateWidget(); + m_statusLabel = CreateWidget(); } void StatusState::Enter(Ndk::StateMachine& fsm) diff --git a/src/Client/States/Game/StatusState.hpp b/src/Client/States/Game/StatusState.hpp index 9fe4d446..ab957c97 100644 --- a/src/Client/States/Game/StatusState.hpp +++ b/src/Client/States/Game/StatusState.hpp @@ -24,7 +24,7 @@ namespace bw void UpdateStatus(const std::string& status, const Nz::Color& color); private: - Ndk::LabelWidget* m_statusLabel; + Nz::LabelWidget* m_statusLabel; }; } diff --git a/src/Client/States/JoinServerState.cpp b/src/Client/States/JoinServerState.cpp index 0b3be294..d7c37542 100644 --- a/src/Client/States/JoinServerState.cpp +++ b/src/Client/States/JoinServerState.cpp @@ -25,10 +25,10 @@ namespace bw AbstractState(std::move(stateData)), m_previousState(std::move(previousState)) { - m_statusLabel = CreateWidget(); + m_statusLabel = CreateWidget(); m_statusLabel->Hide(); - m_serverLabel = CreateWidget(); + m_serverLabel = CreateWidget(); m_serverLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Server: ", 24)); m_serverAddressLayout = CreateWidget(Ndk::BoxLayoutOrientation_Horizontal); @@ -55,20 +55,20 @@ namespace bw }); - m_connectionButton = CreateWidget(); + m_connectionButton = CreateWidget(); m_connectionButton->UpdateText(Nz::SimpleTextDrawer::Draw("Connect to server", 24)); m_connectionButton->Resize(m_connectionButton->GetPreferredSize()); - m_connectionButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) + m_connectionButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { OnConnectionPressed(); }); - m_backButton = CreateWidget(); + m_backButton = CreateWidget(); m_backButton->UpdateText(Nz::SimpleTextDrawer::Draw("Back", 24)); m_backButton->Resize(m_backButton->GetPreferredSize()); - m_backButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) + m_backButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { OnBackPressed(); }); diff --git a/src/Client/States/JoinServerState.hpp b/src/Client/States/JoinServerState.hpp index 4615ff0e..4458c979 100644 --- a/src/Client/States/JoinServerState.hpp +++ b/src/Client/States/JoinServerState.hpp @@ -37,10 +37,10 @@ namespace bw std::shared_ptr m_nextGameState; std::shared_ptr m_nextState; Ndk::BoxLayout* m_serverAddressLayout; - Ndk::ButtonWidget* m_backButton; - Ndk::ButtonWidget* m_connectionButton; - Ndk::LabelWidget* m_serverLabel; - Ndk::LabelWidget* m_statusLabel; + Nz::ButtonWidget* m_backButton; + Nz::ButtonWidget* m_connectionButton; + Nz::LabelWidget* m_serverLabel; + Nz::LabelWidget* m_statusLabel; Ndk::TextAreaWidget* m_serverAddressArea; Ndk::TextAreaWidget* m_serverPortArea; }; diff --git a/src/Client/States/MainMenuState.cpp b/src/Client/States/MainMenuState.cpp index 8d211b41..7f1085fd 100644 --- a/src/Client/States/MainMenuState.cpp +++ b/src/Client/States/MainMenuState.cpp @@ -28,38 +28,38 @@ namespace bw MainMenuState::MainMenuState(std::shared_ptr stateData) : AbstractState(std::move(stateData)) { - m_startServerButton = CreateWidget(); + m_startServerButton = CreateWidget(); m_startServerButton->UpdateText(Nz::SimpleTextDrawer::Draw("Start server...", 24)); m_startServerButton->Resize(m_startServerButton->GetPreferredSize()); - m_startServerButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) + m_startServerButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { OnStartServerPressed(); }); - m_joinServerButton = CreateWidget(); + m_joinServerButton = CreateWidget(); m_joinServerButton->UpdateText(Nz::SimpleTextDrawer::Draw("Join server...", 24)); m_joinServerButton->Resize(m_joinServerButton->GetPreferredSize()); - m_joinServerButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) + m_joinServerButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { OnJoinServerPressed(); }); - m_optionButton = CreateWidget(); + m_optionButton = CreateWidget(); m_optionButton->UpdateText(Nz::SimpleTextDrawer::Draw("Option", 24)); m_optionButton->Resize(m_optionButton->GetPreferredSize()); - m_optionButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) + m_optionButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { OnOptionPressed(); }); - m_quitButton = CreateWidget(); + m_quitButton = CreateWidget(); m_quitButton->UpdateText(Nz::SimpleTextDrawer::Draw("Quit", 24)); m_quitButton->Resize(m_quitButton->GetPreferredSize()); - m_quitButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) + m_quitButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { OnQuitPressed(); }); diff --git a/src/Client/States/MainMenuState.hpp b/src/Client/States/MainMenuState.hpp index 806a04fb..6a896750 100644 --- a/src/Client/States/MainMenuState.hpp +++ b/src/Client/States/MainMenuState.hpp @@ -32,10 +32,10 @@ namespace bw std::shared_ptr m_nextState; Ndk::BoxLayout* m_serverAddressLayout; - Ndk::ButtonWidget* m_joinServerButton; - Ndk::ButtonWidget* m_optionButton; - Ndk::ButtonWidget* m_quitButton; - Ndk::ButtonWidget* m_startServerButton; + Nz::ButtonWidget* m_joinServerButton; + Nz::ButtonWidget* m_optionButton; + Nz::ButtonWidget* m_quitButton; + Nz::ButtonWidget* m_startServerButton; }; } diff --git a/src/Client/States/ServerListState.cpp b/src/Client/States/ServerListState.cpp index 6dce178d..43f6ce35 100644 --- a/src/Client/States/ServerListState.cpp +++ b/src/Client/States/ServerListState.cpp @@ -32,25 +32,25 @@ namespace bw m_serverListWidget = GetStateData().canvas->Add(); - m_serverListScrollbar = CreateWidget(m_serverListWidget); + m_serverListScrollbar = CreateWidget(m_serverListWidget); m_serverListScrollbar->EnableBackground(true); m_serverListScrollbar->SetBackgroundColor(Nz::Color(0, 0, 0, 80)); m_serverListScrollbar->EnableScrollbar(true); - m_backButton = CreateWidget(); + m_backButton = CreateWidget(); m_backButton->UpdateText(Nz::SimpleTextDrawer::Draw("Back", 24)); m_backButton->Resize(m_backButton->GetPreferredSize()); - m_backButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) + m_backButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { OnBackPressed(); }); - m_directConnectButton = CreateWidget(); + m_directConnectButton = CreateWidget(); m_directConnectButton->UpdateText(Nz::SimpleTextDrawer::Draw("Direct connection...", 24)); m_directConnectButton->Resize(m_directConnectButton->GetPreferredSize()); - m_directConnectButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) + m_directConnectButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { OnDirectConnectionPressed(); }); @@ -347,15 +347,15 @@ namespace bw bwLog(stateData.app->GetLogger(), LogLevel::Debug, "server {0} appeared (from {1})", uuid, masterServer); // New server - serverData.connectButton = m_serverListWidget->Add(); + serverData.connectButton = m_serverListWidget->Add(); serverData.connectButton->UpdateText(Nz::SimpleTextDrawer::Draw("Connect", 24)); serverData.connectButton->Resize(serverData.connectButton->GetPreferredSize()); - serverData.connectButton->OnButtonTrigger.Connect([this, masterServer, uuid](const Ndk::ButtonWidget* /*button*/) + serverData.connectButton->OnButtonTrigger.Connect([this, masterServer, uuid](const Nz::ButtonWidget* /*button*/) { OnServerConnectionPressed(masterServer, uuid); }); - serverData.infoLabel = m_serverListWidget->Add(); + serverData.infoLabel = m_serverListWidget->Add(); } Nz::RichTextDrawer infoDrawer; diff --git a/src/Client/States/ServerListState.hpp b/src/Client/States/ServerListState.hpp index 5738c05d..34161d6f 100644 --- a/src/Client/States/ServerListState.hpp +++ b/src/Client/States/ServerListState.hpp @@ -41,8 +41,8 @@ namespace bw struct ServerData { - Ndk::ButtonWidget* connectButton; - Ndk::LabelWidget* infoLabel; + Nz::ButtonWidget* connectButton; + Nz::LabelWidget* infoLabel; std::string serverName; }; @@ -54,9 +54,9 @@ namespace bw }; Nz::BaseWidget* m_serverListWidget; - Ndk::ButtonWidget* m_backButton; - Ndk::ButtonWidget* m_directConnectButton; - Ndk::ScrollAreaWidget* m_serverListScrollbar; + Nz::ButtonWidget* m_backButton; + Nz::ButtonWidget* m_directConnectButton; + Nz::ScrollAreaWidget* m_serverListScrollbar; std::shared_ptr m_previousState; std::shared_ptr m_nextGameState; std::shared_ptr m_nextState; diff --git a/src/Client/States/StartServerState.cpp b/src/Client/States/StartServerState.cpp index 74dadc3e..ca4b1e12 100644 --- a/src/Client/States/StartServerState.cpp +++ b/src/Client/States/StartServerState.cpp @@ -27,7 +27,7 @@ namespace bw AbstractState(std::move(stateData)), m_previousState(std::move(previousState)) { - m_statusLabel = CreateWidget(); + m_statusLabel = CreateWidget(); m_statusLabel->Hide(); m_background = CreateWidget(); @@ -37,13 +37,13 @@ namespace bw m_serverConfigLayout = m_background->Add(Ndk::BoxLayoutOrientation_Vertical); m_serverConfigLayout->SetPosition(10.f, 10.f); - m_title = m_serverConfigLayout->Add(); + m_title = m_serverConfigLayout->Add(); m_title->UpdateText(Nz::SimpleTextDrawer::Draw("Server configuration", 36)); m_title->CenterHorizontal(); Ndk::BoxLayout* gamemodeLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); - Ndk::LabelWidget* gamemodeLabel = gamemodeLayout->Add(); + Nz::LabelWidget* gamemodeLabel = gamemodeLayout->Add(); gamemodeLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Gamemode: ", 24)); m_gamemodeArea = gamemodeLayout->Add(); @@ -54,7 +54,7 @@ namespace bw Ndk::BoxLayout* mapLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); - Ndk::LabelWidget* mapLabel = mapLayout->Add(); + Nz::LabelWidget* mapLabel = mapLayout->Add(); mapLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Map: ", 24)); m_mapArea = mapLayout->Add(); @@ -65,7 +65,7 @@ namespace bw Ndk::BoxLayout* portLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); - Ndk::LabelWidget* portLabel = portLayout->Add(); + Nz::LabelWidget* portLabel = portLayout->Add(); portLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Port: ", 24)); m_portArea = portLayout->Add(); @@ -86,7 +86,7 @@ namespace bw m_nameLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); - Ndk::LabelWidget* nameLabel = m_nameLayout->Add(); + Nz::LabelWidget* nameLabel = m_nameLayout->Add(); nameLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Name: ", 24)); m_nameArea = m_nameLayout->Add(); @@ -97,7 +97,7 @@ namespace bw m_descriptionLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); - Ndk::LabelWidget* descLabel = m_descriptionLayout->Add(); + Nz::LabelWidget* descLabel = m_descriptionLayout->Add(); descLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Description: ", 24)); m_descriptionArea = m_descriptionLayout->Add(); @@ -108,18 +108,18 @@ namespace bw Ndk::BoxLayout* buttonLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); - m_backButton = buttonLayout->Add(); + m_backButton = buttonLayout->Add(); m_backButton->UpdateText(Nz::SimpleTextDrawer::Draw("Back", 24)); - m_backButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) + m_backButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { OnBackPressed(); }); - m_startServerButton = buttonLayout->Add(); + m_startServerButton = buttonLayout->Add(); m_startServerButton->UpdateText(Nz::SimpleTextDrawer::Draw("Start server", 24)); - m_startServerButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) + m_startServerButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { OnStartServerPressed(); }); diff --git a/src/Client/States/StartServerState.hpp b/src/Client/States/StartServerState.hpp index 8c5916d0..4c7782fd 100644 --- a/src/Client/States/StartServerState.hpp +++ b/src/Client/States/StartServerState.hpp @@ -39,11 +39,11 @@ namespace bw Ndk::BoxLayout* m_nameLayout; Ndk::BoxLayout* m_serverConfigLayout; Nz::BaseWidget* m_background; - Ndk::ButtonWidget* m_backButton; - Ndk::ButtonWidget* m_startServerButton; + Nz::ButtonWidget* m_backButton; + Nz::ButtonWidget* m_startServerButton; Ndk::CheckboxWidget* m_listServerCheckbox; - Ndk::LabelWidget* m_title; - Ndk::LabelWidget* m_statusLabel; + Nz::LabelWidget* m_title; + Nz::LabelWidget* m_statusLabel; Ndk::TextAreaWidget* m_descriptionArea; Ndk::TextAreaWidget* m_gamemodeArea; Ndk::TextAreaWidget* m_mapArea; diff --git a/src/Client/States/StateData.hpp b/src/Client/States/StateData.hpp index 95bab9d6..64297607 100644 --- a/src/Client/States/StateData.hpp +++ b/src/Client/States/StateData.hpp @@ -8,8 +8,8 @@ #define BURGWAR_STATES_STATEDATA_HPP #include -#include -#include +#include +#include #include namespace bw @@ -18,9 +18,9 @@ namespace bw struct StateData { - std::optional canvas; + std::optional canvas; ClientApp* app; - entt::registryHandle world; + entt::registry* world; Nz::RenderWindow* window; }; } diff --git a/src/ClientLib/ClientEditorApp.cpp b/src/ClientLib/ClientEditorApp.cpp index e866bfde..85d9d02d 100644 --- a/src/ClientLib/ClientEditorApp.cpp +++ b/src/ClientLib/ClientEditorApp.cpp @@ -36,10 +36,13 @@ namespace bw m_playerSettings.SaveToFile(PlayerSettingsFile); } - Nz::Audio::SetGlobalVolume(m_playerSettings.GetIntegerValue("Sound.GlobalVolume")); + const auto& defaultDevice = Nz::Audio::Instance()->GetDefaultDevice(); + + defaultDevice->SetGlobalVolume(m_playerSettings.GetIntegerValue("Sound.GlobalVolume")); m_playerSettings.GetIntegerUpdateSignal("Sound.GlobalVolume").Connect([](long long newValue) { - Nz::Audio::SetGlobalVolume(float(newValue)); + const auto& defaultDevice = Nz::Audio::Instance()->GetDefaultDevice(); + defaultDevice->SetGlobalVolume(float(newValue)); }); } @@ -77,7 +80,7 @@ namespace bw //FIXME: Should be part of ClientLib too Nz::Color trailColor(242, 255, 168); - Nz::SpriteRef trailSprite = Nz::Sprite::New(); + std::shared_ptr trailSprite = Nz::Sprite::New(); trailSprite->SetMaterial(Nz::Material::New("Translucent2D")); trailSprite->SetCornerColor(Nz::RectCorner_LeftBottom, trailColor * Nz::Color(128, 128, 128, 0)); trailSprite->SetCornerColor(Nz::RectCorner_LeftTop, trailColor * Nz::Color(128, 128, 128, 0)); diff --git a/src/ClientLib/ClientEditorLayer.cpp b/src/ClientLib/ClientEditorLayer.cpp index 3a1ac814..5723cd25 100644 --- a/src/ClientLib/ClientEditorLayer.cpp +++ b/src/ClientLib/ClientEditorLayer.cpp @@ -6,20 +6,20 @@ #include #include #include -#include +#include namespace bw { ClientEditorLayer::ClientEditorLayer(SharedMatch& match, LayerIndex layerIndex) : SharedLayer(match, layerIndex) { - entt::registry& world = GetWorld(); - world.AddSystem(); - world.AddSystem(); - world.AddSystem(); + auto& systemGraph = GetSystemGraph(); + systemGraph.AddSystem(); + systemGraph.AddSystem(); + systemGraph.AddSystem(); } - - void ClientEditorLayer::FrameUpdate(float elapsedTime) + + /*void ClientEditorLayer::FrameUpdate(float elapsedTime) { entt::registry& world = GetWorld(); world.ForEachSystem([](Ndk::BaseSystem& system) @@ -72,5 +72,5 @@ namespace bw world.GetSystem().Enable(false); SharedLayer::TickUpdate(elapsedTime); - } + }*/ } diff --git a/src/ClientLib/ClientLayer.cpp b/src/ClientLib/ClientLayer.cpp index 920e3fc7..a74a411e 100644 --- a/src/ClientLib/ClientLayer.cpp +++ b/src/ClientLib/ClientLayer.cpp @@ -3,6 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include +#include #include #include #include @@ -13,9 +14,9 @@ #include #include #include +#include +#include #include -#include -#include namespace bw { @@ -25,10 +26,10 @@ namespace bw m_isEnabled(false), m_isPredictionEnabled(false) { - entt::registry& world = GetWorld(); - world.AddSystem(); - world.AddSystem(); - world.AddSystem(); + Nz::SystemGraph& systemGraph = GetSystemGraph(); + systemGraph.AddSystem(); + systemGraph.AddSystem(); + systemGraph.AddSystem(); OnEntityCreated.Connect([this](ClientLayer* layer, ClientLayerEntity& layerEntity) { @@ -41,34 +42,6 @@ namespace bw }); } - ClientLayer::ClientLayer(ClientLayer&& layer) noexcept : - ClientEditorLayer(std::move(layer)), - m_entities(std::move(layer.m_entities)), - m_serverEntityIds(std::move(layer.m_serverEntityIds)), - m_backgroundColor(layer.m_backgroundColor), - m_isEnabled(layer.m_isEnabled), - m_isPredictionEnabled(layer.m_isPredictionEnabled) - { - for (auto it = m_entities.begin(); it != m_entities.end(); ++it) - { - EntityData& entity = it.value(); - entity.onDestruction.Connect(entity.layerEntity.GetEntity()->OnEntityDestruction, [this, uniqueId = entity.layerEntity.GetUniqueId()](Ndk::Entity*) - { - HandleEntityDestruction(uniqueId); - }); - } - - OnEntityCreated.Connect([this](ClientLayer* layer, ClientLayerEntity& layerEntity) - { - OnEntityVisualCreated(layer, layerEntity); - }); - - OnEntityDelete.Connect([this](ClientLayer* layer, ClientLayerEntity& layerEntity) - { - OnEntityVisualDelete(layer, layerEntity); - }); - } - ClientLayer::~ClientLayer() { Enable(false); @@ -89,9 +62,6 @@ namespace bw m_sounds.clear(); m_freeSoundIds.Clear(); - // Since we are disabled, refresh won't be called until we are enabled, refresh the world now to kill entities - GetWorld().Clear(); - assert(m_entities.empty()); assert(m_serverEntityIds.empty()); } @@ -139,7 +109,7 @@ namespace bw ClientLayerEntity& ClientLayer::RegisterEntity(ClientLayerEntity layerEntity) { assert(layerEntity.GetEntity()); - assert(layerEntity.GetEntity()->GetWorld() == &GetWorld()); + assert(layerEntity.GetEntity().registry() == &GetWorld()); EntityId uniqueId = layerEntity.GetUniqueId(); @@ -154,7 +124,8 @@ namespace bw auto it = m_entities.emplace(uniqueId, std::move(layerEntity)).first; EntityData& entity = it.value(); - entity.onDestruction.Connect(entity.layerEntity.GetEntity()->OnEntityDestruction, [this, uniqueId](Ndk::Entity*) + entt::handle handle = entity.layerEntity.GetEntity(); + entity.onDestruction.Connect(handle.get_or_emplace(handle).OnDestruction, [this, uniqueId](DestructionWatcherComponent*) { HandleEntityDestruction(uniqueId); }); @@ -245,7 +216,7 @@ namespace bw // Entity if (std::size_t elementIndex = entityStore.GetElementIndex(entityClass); elementIndex != ClientEntityStore::InvalidIndex) { - auto entity = entityStore.InstantiateEntity(*this, elementIndex, entityId, uniqueId, entityData.position, entityData.rotation, scale, properties, (parent) ? parent->GetEntity() : entt::null); + auto entity = entityStore.InstantiateEntity(*this, elementIndex, entityId, uniqueId, entityData.position, entityData.rotation, scale, properties, (parent) ? parent->GetEntity() : entt::handle{}); if (!entity) { bwLog(GetMatch().GetLogger(), LogLevel::Error, "Failed to instantiate entity {0} of type {1}", uniqueId, entityClass); @@ -304,7 +275,7 @@ namespace bw if (entityData.ownerPlayerIndex) { if (ClientPlayer* player = GetClientMatch().GetPlayerByIndex(*entityData.ownerPlayerIndex)) - layerEntity->GetEntity()->AddComponent(player->CreateHandle()); + layerEntity->GetEntity().emplace(player->CreateHandle()); } if (entityData.health) @@ -314,16 +285,15 @@ namespace bw { auto& physProperties = *entityData.physicsProperties; - if (layerEntity->GetEntity()->HasComponent()) + if (Nz::RigidBody2DComponent* entityPhys = layerEntity->GetEntity().try_get()) { - auto& entityPhys = layerEntity->GetEntity()->GetComponent(); - entityPhys.SetMass(physProperties.mass, false); - entityPhys.SetMomentOfInertia(physProperties.momentOfInertia); - entityPhys.SetAngularVelocity(physProperties.angularVelocity); - entityPhys.SetVelocity(physProperties.linearVelocity); + entityPhys->SetMass(physProperties.mass, false); + entityPhys->SetMomentOfInertia(physProperties.momentOfInertia); + entityPhys->SetAngularVelocity(physProperties.angularVelocity); + entityPhys->SetVelocity(physProperties.linearVelocity); if (physProperties.isAsleep) - entityPhys.ForceSleep(); + entityPhys->ForceSleep(); } else bwLog(GetMatch().GetLogger(), LogLevel::Warning, "Entity {0} has physical properties but is not physical client-side"); @@ -350,10 +320,10 @@ namespace bw OnEntityDelete(this, entity.layerEntity); // Don't trigger the Destroyed event on disabling layers - if (IsEnabled() && entity.layerEntity.GetEntity()->HasComponent()) + if (IsEnabled()) { - auto& scriptComponent = entity.layerEntity.GetEntity()->GetComponent(); - scriptComponent.ExecuteCallback(); + if (ScriptComponent* scriptComponent = entity.layerEntity.GetEntity().try_get()) + scriptComponent->ExecuteCallback(); } // `it` and `entity` are no longer valid here (as a new entity could have been created by the destroyed callback) @@ -485,9 +455,9 @@ namespace bw ClientLayerEntity& localEntity = *entityOpt; if (localEntity.IsPhysical()) { - entt::entity entity = localEntity.GetEntity(); + entt::handle entity = localEntity.GetEntity(); - auto& entityPhys = entity->GetComponent(); + auto& entityPhys = entity.get(); entityPhys.SetMass(packet.mass, false); entityPhys.SetMomentOfInertia(packet.momentOfInertia); @@ -498,12 +468,11 @@ namespace bw { auto& packetPlayerMovement = packet.playerMovement.value(); - if (entity->HasComponent()) + if (PlayerMovementComponent* entityPlayerMovement = entity.try_get()) { - auto& entityPlayerMovement = entity->GetComponent(); - entityPlayerMovement.UpdateJumpBoostHeight(packetPlayerMovement.jumpHeightBoost); - entityPlayerMovement.UpdateJumpHeight(packetPlayerMovement.jumpHeight); - entityPlayerMovement.UpdateMovementSpeed(packetPlayerMovement.movementSpeed); + entityPlayerMovement->UpdateJumpBoostHeight(packetPlayerMovement.jumpHeightBoost); + entityPlayerMovement->UpdateJumpHeight(packetPlayerMovement.jumpHeight); + entityPlayerMovement->UpdateMovementSpeed(packetPlayerMovement.movementSpeed); } } } diff --git a/src/ClientLib/ClientLayerEntity.cpp b/src/ClientLib/ClientLayerEntity.cpp index f27bf866..0311e76f 100644 --- a/src/ClientLib/ClientLayerEntity.cpp +++ b/src/ClientLib/ClientLayerEntity.cpp @@ -14,11 +14,11 @@ #include #include #include -#include +#include namespace bw { - ClientLayerEntity::ClientLayerEntity(ClientLayer& layer, entt::entity entity, Nz::UInt32 serverEntityId, EntityId uniqueId) : + ClientLayerEntity::ClientLayerEntity(ClientLayer& layer, entt::handle entity, Nz::UInt32 serverEntityId, EntityId uniqueId) : LayerVisualEntity(entity, layer.GetLayerIndex(), uniqueId), m_serverEntityId(serverEntityId), m_layer(layer) @@ -39,7 +39,7 @@ namespace bw { assert(IsPhysical()); - auto& entityPhys = GetEntity()->GetComponent(); + auto& entityPhys = GetEntity().get(); return entityPhys.GetAngularVelocity(); } @@ -47,12 +47,12 @@ namespace bw { if (!m_ghostEntity) { - entt::entity ghostEntity = GetEntity()->GetWorld()->CreateEntity(); - ghostEntity->AddComponent(); + /*entt::entity ghostEntity = GetEntity()->GetWorld()->CreateEntity(); + ghostEntity->AddComponent(); m_ghostEntity = std::make_unique(m_layer, ghostEntity, ClientsideId, m_layer.GetClientMatch().AllocateClientUniqueId()); - /*for (auto& renderable : m_attachedRenderables) + for (auto& renderable : m_attachedRenderables) { if (std::unique_ptr clonedRenderable = renderable.renderable->Clone()) { @@ -86,7 +86,7 @@ namespace bw { assert(IsPhysical()); - auto& entityPhys = GetEntity()->GetComponent(); + auto& entityPhys = GetEntity().get(); return entityPhys.GetVelocity(); } @@ -94,7 +94,7 @@ namespace bw { assert(IsPhysical()); - auto& entityPhys = GetEntity()->GetComponent(); + auto& entityPhys = GetEntity().get(); return entityPhys.GetPosition(); } @@ -102,19 +102,19 @@ namespace bw { assert(IsPhysical()); - auto& entityPhys = GetEntity()->GetComponent(); + auto& entityPhys = GetEntity().get(); return entityPhys.GetRotation(); } Nz::Vector2f ClientLayerEntity::GetPosition() const { - auto& entityNode = GetEntity()->GetComponent(); + auto& entityNode = GetEntity().get(); return Nz::Vector2f(entityNode.GetPosition()); //< FIXME } Nz::RadianAnglef ClientLayerEntity::GetRotation() const { - auto& entityNode = GetEntity()->GetComponent(); + auto& entityNode = GetEntity().get(); return AngleFromQuaternion(entityNode.GetRotation()); //< FIXME } @@ -125,13 +125,13 @@ namespace bw healthData.maxHealth = maxHealth; healthData.spriteWidth = GetLocalBounds().width * 0.85f; - Nz::SpriteRef lostHealthBar = Nz::Sprite::New(); + /*std::shared_ptr lostHealthBar = Nz::Sprite::New(); lostHealthBar->SetMaterial(Nz::MaterialLibrary::Get("SpriteNoDepth")); lostHealthBar->SetSize(healthData.spriteWidth, 10); lostHealthBar->SetColor(Nz::Color::Red); lostHealthBar->SetOrigin(Nz::Vector2f(healthData.spriteWidth / 2.f, lostHealthBar->GetSize().y)); - Nz::SpriteRef healthBar = Nz::Sprite::New(); + std::shared_ptr healthBar = Nz::Sprite::New(); healthBar->SetMaterial(Nz::MaterialLibrary::Get("SpriteNoDepth")); healthBar->SetSize(healthData.spriteWidth * healthData.currentHealth / healthData.maxHealth, 10); healthBar->SetColor(Nz::Color::Green); @@ -139,30 +139,30 @@ namespace bw healthData.lostHealthSprite = lostHealthBar; healthData.healthSprite = healthBar; - + */ if (currentHealth != maxHealth) ShowHealthBar(); } bool ClientLayerEntity::IsFacingRight() const { - auto& entityNode = GetEntity()->GetComponent(); + auto& entityNode = GetEntity().get(); return entityNode.GetScale().x > 0.f; } void ClientLayerEntity::UpdateAnimation(Nz::UInt8 animationId) { - auto& animComponent = GetEntity()->GetComponent(); + auto& animComponent = GetEntity().get(); animComponent.Play(animationId, m_layer.GetMatch().GetCurrentTime()); } void ClientLayerEntity::UpdatePlayerMovement(bool isFacingRight) { - auto& playerMovementComponent = GetEntity()->GetComponent(); + auto& playerMovementComponent = GetEntity().get(); if (playerMovementComponent.UpdateFacingRightState(isFacingRight)) { - auto& entityNode = GetEntity()->GetComponent(); + auto& entityNode = GetEntity().get(); entityNode.Scale(-1.f, 1.f); } } @@ -176,34 +176,33 @@ namespace bw return; m_health->currentHealth = newHealth; - m_health->healthSprite->SetSize(m_health->spriteWidth * m_health->currentHealth / m_health->maxHealth, 10); + m_health->healthSprite->SetSize(Nz::Vector2f(m_health->spriteWidth * m_health->currentHealth / m_health->maxHealth, 10)); if (m_health->currentHealth == m_health->maxHealth) HideHealthBar(); else ShowHealthBar(); - if (GetEntity()->HasComponent()) + if (ScriptComponent* scriptComponent = GetEntity().try_get()) { - auto& scriptComponent = GetEntity()->GetComponent(); - scriptComponent.ExecuteCallback(oldHealth, newHealth); + scriptComponent->ExecuteCallback(oldHealth, newHealth); if (newHealth == 0) { - scriptComponent.ExecuteCallback(); - scriptComponent.ExecuteCallback(); + scriptComponent->ExecuteCallback(); + scriptComponent->ExecuteCallback(); } } } void ClientLayerEntity::UpdateInputs(const PlayerInputData& inputData) { - GetEntity()->GetComponent().UpdateInputs(inputData); + GetEntity().get().UpdateInputs(inputData); } void ClientLayerEntity::UpdateParent(const ClientLayerEntity* newParent) { - auto& entityNode = GetEntity()->GetComponent(); + auto& entityNode = GetEntity().get(); if (newParent) entityNode.SetParent(newParent->GetEntity(), true); else @@ -214,7 +213,7 @@ namespace bw { if (m_weaponEntity) { - auto& entityWeapon = m_weaponEntity->GetEntity()->GetComponent(); + auto& entityWeapon = m_weaponEntity->GetEntity().get(); entityWeapon.SetActive(false); m_weaponEntity->Disable(); @@ -223,7 +222,7 @@ namespace bw m_weaponEntity = entity; if (m_weaponEntity) { - auto& entityWeapon = m_weaponEntity->GetEntity()->GetComponent(); + auto& entityWeapon = m_weaponEntity->GetEntity().get(); entityWeapon.SetActive(true); m_weaponEntity->Enable(); diff --git a/src/ClientLib/ClientMatch.cpp b/src/ClientLib/ClientMatch.cpp index 982bdedd..4f77d9e1 100644 --- a/src/ClientLib/ClientMatch.cpp +++ b/src/ClientLib/ClientMatch.cpp @@ -32,22 +32,20 @@ #include #include #include -#include -#include #include +#include #include #include #include #include #include -#include -#include +#include #include #include namespace bw { - ClientMatch::ClientMatch(ClientEditorApp& burgApp, Nz::RenderWindow* window, Nz::RenderTarget* renderTarget, Ndk::Canvas* canvas, ClientSession& session, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData) : + ClientMatch::ClientMatch(ClientEditorApp& burgApp, Nz::RenderWindow* window, Nz::RenderTarget* renderTarget, Nz::Canvas* canvas, ClientSession& session, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData) : SharedMatch(burgApp, LogSide::Client, "local", matchData.tickDuration), m_gamemodeName(matchData.gamemode), m_canvas(canvas), @@ -96,25 +94,16 @@ namespace bw auto& playerSettings = burgApp.GetPlayerSettings(); - m_renderWorld.AddSystem(); - m_renderWorld.AddSystem(); - m_renderWorld.AddSystem(); - m_renderWorld.AddSystem(); - m_renderWorld.AddSystem(*this); - m_renderWorld.AddSystem(playerSettings); - - m_colorBackground = Nz::ColorBackground::New(Nz::Color::Black); - - Ndk::RenderSystem& renderSystem = m_renderWorld.GetSystem(); - renderSystem.SetGlobalUp(Nz::Vector3f::Down()); - renderSystem.SetDefaultBackground(m_colorBackground); + m_renderWorld.systemGraph.AddSystem(); + m_renderWorld.systemGraph.AddSystem(*this); + m_renderWorld.systemGraph.AddSystem(playerSettings); m_camera.emplace(m_renderWorld, renderTarget, true); m_camera->SetZoomFactor(0.8f); - m_currentLayer = m_renderWorld.CreateEntity(); - m_currentLayer->AddComponent(); - m_currentLayer->AddComponent(m_renderWorld); + m_currentLayer = entt::handle(m_renderWorld.registry, m_renderWorld.registry.create()); + m_currentLayer.emplace(); + //m_currentLayer.emplace(m_renderWorld); InitializeRemoteConsole(); @@ -198,7 +187,7 @@ namespace bw m_gamemode.reset(); } - void ClientMatch::ForEachEntity(std::function func) + void ClientMatch::ForEachEntity(tl::function_ref func) { for (auto& layer : m_layers) { @@ -268,11 +257,11 @@ namespace bw { localhost.SetPort(static_cast(42000 + i)); - if (m_debug->socket.Bind(localhost) == Nz::SocketState_Bound) + if (m_debug->socket.Bind(localhost) == Nz::SocketState::Bound) break; } - if (m_debug->socket.GetState() == Nz::SocketState_Bound) + if (m_debug->socket.GetState() == Nz::SocketState::Bound) { bwLog(GetLogger(), LogLevel::Info, "Debug socket bound to port {0}", m_debug->socket.GetBoundPort()); } @@ -294,7 +283,7 @@ namespace bw if (!m_assetStore) { m_assetStore.emplace(GetLogger(), std::move(assetDir)); - m_particleRegistry.emplace(m_assetStore.value()); + //m_particleRegistry.emplace(m_assetStore.value()); } else { @@ -453,9 +442,9 @@ namespace bw m_localPlayers[localIndex].inputPoller = std::move(inputPoller); }); - ForEachEntity([this](entt::entity entity) + ForEachEntity([this](entt::handle entity) { - if (entity->HasComponent()) + if (ScriptComponent* scriptComponent = entity.try_get()) { // Warning: ugly (FIXME) m_entityStore->UpdateEntityElement(entity); @@ -480,21 +469,25 @@ namespace bw m_entitiesByUniqueId.emplace(uniqueId, std::move(entity)); } - entt::entity ClientMatch::RetrieveEntityByUniqueId(EntityId uniqueId) const + entt::handle ClientMatch::RetrieveEntityByUniqueId(EntityId uniqueId) const { auto it = m_entitiesByUniqueId.find(uniqueId); if (it == m_entitiesByUniqueId.end()) - return entt::null; + return {}; return it.value()->GetEntity(); } - EntityId ClientMatch::RetrieveUniqueIdByEntity(entt::entity entity) const + EntityId ClientMatch::RetrieveUniqueIdByEntity(entt::handle entity) const { - if (!entity || !entity->HasComponent()) + if (!entity) return InvalidEntityId; - return entity->GetComponent().GetUniqueId(); + ClientMatchComponent* matchComponent = entity.try_get(); + if (!matchComponent) + return InvalidEntityId; + + return matchComponent->GetUniqueId(); } void ClientMatch::UnregisterEntity(EntityId uniqueId) @@ -617,7 +610,7 @@ namespace bw layerPtr->SyncVisuals(); } - m_renderWorld.Update(elapsedTime); + m_renderWorld.systemGraph.Update(elapsedTime); if (m_gamemode) m_gamemode->ExecuteCallback(elapsedTime); @@ -797,7 +790,7 @@ namespace bw }); } - void ClientMatch::BindSignals(ClientEditorApp& burgApp, Nz::RenderWindow* window, Ndk::Canvas* canvas) + void ClientMatch::BindSignals(ClientEditorApp& burgApp, Nz::RenderWindow* window, Nz::Canvas* canvas) { m_chatBox.OnChatMessage.Connect([this](const std::string& message) { @@ -895,7 +888,7 @@ namespace bw }; }); - m_onRenderTargetSizeChange.Connect(window->OnRenderTargetSizeChange, [this](const Nz::RenderTarget* renderTarget) + m_onRenderTargetSizeChange.Connect(window->GetRenderTarget()->OnRenderTargetSizeChange, [this](const Nz::RenderTarget* renderTarget) { Nz::Vector2f size = Nz::Vector2f(renderTarget->GetSize()); @@ -1128,8 +1121,8 @@ namespace bw if (localPlayer.controlledEntity) { auto& controlledEntity = localPlayer.controlledEntity; - controlledEntity->GetEntity()->RemoveComponent(); - controlledEntity->GetEntity()->RemoveComponent(); + //controlledEntity->GetEntity().remove(); + controlledEntity->GetEntity().remove(); m_layers[controlledEntity->GetLayerIndex()]->EnablePrediction(false); } @@ -1140,8 +1133,8 @@ namespace bw ClientLayerEntity& layerEntity = layerEntityOpt.value(); localPlayer.controlledEntity = layerEntity.CreateHandle(); - localPlayer.controlledEntity->GetEntity()->AddComponent(); - localPlayer.controlledEntity->GetEntity()->AddComponent(*this, packet.localIndex); + //localPlayer.controlledEntity->GetEntity().emplace(); + localPlayer.controlledEntity->GetEntity().emplace(*this, packet.localIndex); HandlePlayerControlEntity(localPlayer.playerIndex, layerEntity.GetUniqueId()); } @@ -1486,17 +1479,17 @@ namespace bw auto& controllerData = m_localPlayers[i]; if (controllerData.controlledEntity) { - auto& controlledEntity = controllerData.controlledEntity->GetEntity(); + entt::handle controlledEntity = controllerData.controlledEntity->GetEntity(); - InputComponent& entityInputs = controlledEntity->GetComponent(); + InputComponent& entityInputs = controlledEntity.get(); const auto& playerInputData = input.inputs[i]; entityInputs.UpdateInputs(playerInputData.input); entityInputs.UpdatePreviousInputs(playerInputData.previousInput); if (playerInputData.movement) { - auto& playerMovement = controlledEntity->GetComponent(); - auto& playerPhysics = controlledEntity->GetComponent(); + auto& playerMovement = controlledEntity.get(); + auto& playerPhysics = controlledEntity.get(); playerMovement.UpdateGroundState(playerInputData.movement->isOnGround); playerMovement.UpdateJumpTime(playerInputData.movement->jumpTime); playerMovement.UpdateWasJumpingState(playerInputData.movement->wasJumping); @@ -1505,13 +1498,9 @@ namespace bw playerPhysics.SetSurfaceVelocity(0, playerInputData.movement->surfaceVelocity); } - for (auto&& weaponData : playerInputData.weapons) - { - if (!weaponData.entity) - continue; - - weaponData.entity->GetComponent().SetAttacking(weaponData.isAttacking); - } + // WTF? + //for (auto&& weaponData : playerInputData.weapons) + // weaponData.entity->GetComponent().SetAttacking(weaponData.isAttacking); } } @@ -1594,8 +1583,8 @@ namespace bw auto& layer = m_layers[m_activeLayerIndex]; - m_colorBackground->SetColor(layer->GetBackgroundColor()); - auto& visibleLayer = m_currentLayer->GetComponent(); + //m_colorBackground->SetColor(layer->GetBackgroundColor()); + auto& visibleLayer = m_currentLayer.get(); visibleLayer.Clear(); visibleLayer.RegisterLocalLayer(*layer, 0, Nz::Vector2f::Unit(), Nz::Vector2f::Unit()); } @@ -1619,9 +1608,9 @@ namespace bw ClientLayerEntity& layerEntity = entityOpt.value(); - assert(layerEntity.GetEntity()->HasComponent()); + assert(layerEntity.GetEntity().try_get()); - auto& scriptComponent = layerEntity.GetEntity()->GetComponent(); + auto& scriptComponent = layerEntity.GetEntity().get(); const ScriptedWeapon& weaponData = static_cast(*scriptComponent.GetElement()); auto& weapon = playerData.weapons.emplace_back(); @@ -1738,30 +1727,28 @@ namespace bw if (controllerData.controlledEntity) { - auto& entity = controllerData.controlledEntity->GetEntity(); - if (entity->HasComponent()) + auto entity = controllerData.controlledEntity->GetEntity(); + if (PlayerMovementComponent* playerMovement = entity.try_get()) { - auto& playerMovement = entity->GetComponent(); - auto& playerPhysics = entity->GetComponent(); + auto& playerPhysics = entity.get(); auto& movementData = playerData.movement.emplace(); - movementData.isOnGround = playerMovement.IsOnGround(); - movementData.jumpTime = playerMovement.GetJumpTime(); - movementData.wasJumping = playerMovement.WasJumping(); + movementData.isOnGround = playerMovement->IsOnGround(); + movementData.jumpTime = playerMovement->GetJumpTime(); + movementData.wasJumping = playerMovement->WasJumping(); movementData.friction = playerPhysics.GetFriction(0); movementData.surfaceVelocity = playerPhysics.GetSurfaceVelocity(0); } - if (entity->HasComponent()) + if (InputComponent* inputComponent = entity.try_get()) { - auto& entityInputs = entity->GetComponent(); - playerData.input = entityInputs.GetInputs(); - playerData.previousInput = entityInputs.GetPreviousInputs(); + playerData.input = inputComponent->GetInputs(); + playerData.previousInput = inputComponent->GetPreviousInputs(); } } - for (auto&& weapon : controllerData.weapons) + /*for (auto&& weapon : controllerData.weapons) { if (!weapon.entity || !weapon.entity->HasComponent()) continue; @@ -1769,7 +1756,7 @@ namespace bw auto& weaponData = playerData.weapons.emplace_back(); weaponData.entity = weapon.entity; weaponData.isAttacking = weapon.entity->GetComponent().IsAttacking(); - } + }*/ } for (auto& layer : m_layers) diff --git a/src/ClientLib/Components/ClientMatchComponent.cpp b/src/ClientLib/Components/ClientMatchComponent.cpp index 4950be48..5b2234f8 100644 --- a/src/ClientLib/Components/ClientMatchComponent.cpp +++ b/src/ClientLib/Components/ClientMatchComponent.cpp @@ -9,13 +9,11 @@ namespace bw { ClientLayer& ClientMatchComponent::GetLayer() { - return m_clientMatch.GetLayer(m_layerIndex); + return m_clientMatch->GetLayer(m_layerIndex); } const ClientLayer& ClientMatchComponent::GetLayer() const { - return m_clientMatch.GetLayer(m_layerIndex); + return m_clientMatch->GetLayer(m_layerIndex); } - - Ndk::ComponentIndex ClientMatchComponent::componentIndex; } diff --git a/src/ClientLib/EscapeMenu.cpp b/src/ClientLib/EscapeMenu.cpp index b80eb4e2..4bf1447c 100644 --- a/src/ClientLib/EscapeMenu.cpp +++ b/src/ClientLib/EscapeMenu.cpp @@ -9,38 +9,38 @@ namespace bw { - EscapeMenu::EscapeMenu(ClientEditorApp& clientEditorApp, Ndk::Canvas* canvas) : + EscapeMenu::EscapeMenu(ClientEditorApp& clientEditorApp, Nz::Canvas* canvas) : m_app(clientEditorApp) { m_backgroundWidget = canvas->Add(); m_backgroundWidget->EnableBackground(true); m_backgroundWidget->SetBackgroundColor(Nz::Color(0, 0, 0, 160)); - m_closeMenuButton = m_backgroundWidget->Add(); + m_closeMenuButton = m_backgroundWidget->Add(); m_closeMenuButton->UpdateText(Nz::SimpleTextDrawer::Draw("Close", 30)); m_closeMenuButton->Resize(m_closeMenuButton->GetPreferredSize()); - m_closeMenuButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) { + m_closeMenuButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { Hide(); }); - m_optionsButton = m_backgroundWidget->Add(); + m_optionsButton = m_backgroundWidget->Add(); m_optionsButton->UpdateText(Nz::SimpleTextDrawer::Draw("Options", 30)); m_optionsButton->Resize(m_optionsButton->GetPreferredSize()); - m_optionsButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) { + m_optionsButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { OnOptionButtonPressed(); }); - m_leaveMatchButton = m_backgroundWidget->Add(); + m_leaveMatchButton = m_backgroundWidget->Add(); m_leaveMatchButton->UpdateText(Nz::SimpleTextDrawer::Draw("Leave match", 30)); m_leaveMatchButton->Resize(m_leaveMatchButton->GetPreferredSize()); - m_leaveMatchButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) { + m_leaveMatchButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { OnLeaveMatch(this); }); - m_quitAppButton = m_backgroundWidget->Add(); + m_quitAppButton = m_backgroundWidget->Add(); m_quitAppButton->UpdateText(Nz::SimpleTextDrawer::Draw("Exit application", 30)); m_quitAppButton->Resize(m_quitAppButton->GetPreferredSize()); - m_quitAppButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) { + m_quitAppButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { OnQuitApp(this); }); @@ -108,11 +108,11 @@ namespace bw constexpr float padding = 20.f; constexpr float buttonPadding = 10.f; - std::array buttons = { m_closeMenuButton, m_optionsButton, m_leaveMatchButton, m_quitAppButton }; + std::array buttons = { m_closeMenuButton, m_optionsButton, m_leaveMatchButton, m_quitAppButton }; float maxWidth = 0.f; float height = 0.f; - for (Ndk::ButtonWidget* button : buttons) + for (Nz::ButtonWidget* button : buttons) { maxWidth = std::max(maxWidth, button->GetWidth()); height += button->GetHeight(); @@ -123,7 +123,7 @@ namespace bw m_backgroundWidget->Resize({ maxWidth, height }); float cursor = padding; - for (Ndk::ButtonWidget* button : buttons) + for (Nz::ButtonWidget* button : buttons) { button->SetPosition(0.f, cursor); button->CenterHorizontal(); diff --git a/src/ClientLib/LayerVisualEntity.cpp b/src/ClientLib/LayerVisualEntity.cpp index 32a07cd7..4ac55fd1 100644 --- a/src/ClientLib/LayerVisualEntity.cpp +++ b/src/ClientLib/LayerVisualEntity.cpp @@ -11,6 +11,8 @@ #include #include #include +#include +#include #include namespace bw @@ -95,15 +97,16 @@ namespace bw if (IsEnabled() == enable) return; - m_entity->Enable(enable); + // TODO + //m_entity->Enable(enable); for (VisualEntity* visualEntity : m_visualEntities) visualEntity->Enable(enable); } Nz::Boxf LayerVisualEntity::GetGlobalBounds() const { - auto& entityNode = m_entity.get(); - Nz::Matrix4f worldMatrix = Nz::Matrix4f::ConcatenateAffine(s_coordinateMatrix, entityNode.GetTransformMatrix()); + auto& entityNode = m_entity->get(); + Nz::Matrix4f worldMatrix = Nz::Matrix4f::ConcatenateTransform(s_coordinateMatrix, entityNode.GetTransformMatrix()); Nz::Vector3f globalPos = worldMatrix.GetTranslation(); @@ -112,10 +115,10 @@ namespace bw Nz::Boxf aabb(globalPos.x, globalPos.y, globalPos.z, 0.f, 0.f, 0.f); for (const RenderableData& r : m_attachedRenderables) { - Nz::BoundingVolumef boundingVolume = r.renderable->GetBoundingVolume(); + Nz::BoundingVolumef boundingVolume = r.renderable->GetAABB(); if (boundingVolume.IsFinite()) { - boundingVolume.Update(Nz::Matrix4f::ConcatenateAffine(worldMatrix, r.offsetMatrix)); + boundingVolume.Update(Nz::Matrix4f::ConcatenateTransform(worldMatrix, r.offsetMatrix)); if (first) aabb.Set(boundingVolume.aabb); @@ -136,10 +139,10 @@ namespace bw Nz::Boxf aabb(-1.f, -1.f, -1.f); for (const RenderableData& r : m_attachedRenderables) { - Nz::BoundingVolumef boundingVolume = r.renderable->GetBoundingVolume(); + Nz::BoundingVolumef boundingVolume = r.renderable->GetAABB(); if (boundingVolume.IsFinite()) { - boundingVolume.Update(Nz::Matrix4f::ConcatenateAffine(s_coordinateMatrix, r.offsetMatrix)); + boundingVolume.Update(Nz::Matrix4f::ConcatenateTransform(s_coordinateMatrix, r.offsetMatrix)); if (first) aabb.Set(boundingVolume.aabb); @@ -155,12 +158,12 @@ namespace bw bool LayerVisualEntity::IsPhysical() const { - return m_entity->HasComponent(); //< TODO: Cache this? + return m_entity->try_get() != nullptr; //< TODO: Cache this? } void LayerVisualEntity::SyncVisuals() { - auto& entityNode = m_entity.get(); + auto& entityNode = m_entity->get(); Nz::Vector2f position = Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys::Global)); Nz::Vector2f scale = Nz::Vector2f(entityNode.GetScale(Nz::CoordSys::Global)); @@ -215,25 +218,21 @@ namespace bw void LayerVisualEntity::UpdateScale(float newScale) { - if (m_entity->HasComponent()) - { - auto& scriptComponent = m_entity->GetComponent(); - scriptComponent.ExecuteCallback(newScale); - } + if (ScriptComponent* scriptComponent = m_entity->try_get()) + scriptComponent->ExecuteCallback(newScale); - auto& node = m_entity.get(); + auto& node = m_entity->get(); Nz::Vector2f scale = Nz::Vector2f(node.GetScale()); scale.x = std::copysign(newScale, scale.x); scale.y = std::copysign(newScale, scale.y); node.SetScale(scale, Nz::CoordSys::Local); - if (m_entity->HasComponent()) + if (CollisionDataComponent* entityCollData = m_entity->try_get()) { - auto& entityCollData = m_entity->GetComponent(); - auto& entityCollider = m_entity->GetComponent(); + auto& entityCollider = m_entity->get(); - entityCollider.SetGeom(entityCollData.BuildCollider(newScale), false, false); + entityCollider.SetGeom(entityCollData->BuildCollider(newScale), false, false); } } @@ -241,13 +240,13 @@ namespace bw { if (IsPhysical()) { - auto& entityPhys = m_entity->GetComponent(); + auto& entityPhys = m_entity->get(); entityPhys.SetPosition(position); entityPhys.SetRotation(rotation); } else { - auto& entityNode = m_entity.get(); + auto& entityNode = m_entity->get(); entityNode.SetPosition(position); entityNode.SetRotation(rotation); } @@ -257,7 +256,7 @@ namespace bw { if (IsPhysical()) { - auto& entityPhys = m_entity->GetComponent(); + auto& entityPhys = m_entity->get(); entityPhys.SetAngularVelocity(angularVel); entityPhys.SetPosition(position); entityPhys.SetRotation(rotation); @@ -265,7 +264,7 @@ namespace bw } else { - auto& entityNode = m_entity.get(); + auto& entityNode = m_entity->get(); entityNode.SetPosition(position); entityNode.SetRotation(rotation); } @@ -286,7 +285,7 @@ namespace bw visualEntity->Enable(IsEnabled()); - auto& entityNode = m_entity.get(); + auto& entityNode = m_entity->get(); Nz::Vector2f position = Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys::Global)); Nz::Vector2f scale = Nz::Vector2f(entityNode.GetScale(Nz::CoordSys::Global)); Nz::Quaternionf rotation = entityNode.GetRotation(Nz::CoordSys::Global); diff --git a/src/ClientLib/OptionWidget.cpp b/src/ClientLib/OptionWidget.cpp index 049ae1f5..020ce4fc 100644 --- a/src/ClientLib/OptionWidget.cpp +++ b/src/ClientLib/OptionWidget.cpp @@ -35,26 +35,26 @@ namespace bw LoadConfigValues(); - m_applyButton = Add(); + m_applyButton = Add(); m_applyButton->UpdateText(Nz::SimpleTextDrawer::Draw("Apply", 24)); m_applyButton->Resize(m_applyButton->GetPreferredSize()); - m_applyButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) + m_applyButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { OnApply(); }); - m_backButton = Add(); + m_backButton = Add(); m_backButton->UpdateText(Nz::SimpleTextDrawer::Draw("Back", 24)); m_backButton->Resize(m_backButton->GetPreferredSize()); - m_backButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) + m_backButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { OnBack(); }); - m_resetButton = Add(); + m_resetButton = Add(); m_resetButton->UpdateText(Nz::SimpleTextDrawer::Draw("Reset", 24)); m_resetButton->Resize(m_resetButton->GetPreferredSize()); - m_resetButton->OnButtonTrigger.Connect([this](const Ndk::ButtonWidget*) + m_resetButton->OnButtonTrigger.Connect([this](const Nz::ButtonWidget*) { OnReset(); }); @@ -73,12 +73,12 @@ namespace bw auto it = m_sections.emplace(std::move(sectionName), Section{}).first; Section& section = it->second; - section.button = Add(); + section.button = Add(); section.button->UpdateText(Nz::SimpleTextDrawer::Draw(it->first, 36)); section.button->Resize(section.button->GetPreferredSize()); section.button->SetPosition(0.f, cursor); - section.onTriggerSlot.Connect(section.button->OnButtonTrigger, [this, sectionName = it->first](const Ndk::ButtonWidget*) + section.onTriggerSlot.Connect(section.button->OnButtonTrigger, [this, sectionName = it->first](const Nz::ButtonWidget*) { UpdateSection(sectionName); }); @@ -220,7 +220,7 @@ namespace bw { option.keyName = std::move(keyName); - option.label = Add(); + option.label = Add(); option.label->UpdateText(Nz::SimpleTextDrawer::Draw(std::string(label), 24)); //< FIXME: Nazara-next option.label->Resize(option.label->GetPreferredSize()); } @@ -247,7 +247,7 @@ namespace bw } float cursor = size.x; - for (Ndk::ButtonWidget* button : { m_applyButton, m_resetButton, m_backButton }) + for (Nz::ButtonWidget* button : { m_applyButton, m_resetButton, m_backButton }) { button->SetPosition(cursor - button->GetWidth(), size.y - button->GetHeight()); cursor -= button->GetWidth() + 10.f; diff --git a/src/ClientLib/Scoreboard.cpp b/src/ClientLib/Scoreboard.cpp index 7e9a072e..8405f4e4 100644 --- a/src/ClientLib/Scoreboard.cpp +++ b/src/ClientLib/Scoreboard.cpp @@ -7,7 +7,7 @@ #include #include #include -#include +#include namespace bw { @@ -25,7 +25,7 @@ namespace bw m_contentWidget = Add(); - m_scrollArea = Add(m_contentWidget); + m_scrollArea = Add(m_contentWidget); m_scrollArea->EnableScrollbar(true); } @@ -36,14 +36,15 @@ namespace bw std::size_t Scoreboard::AddColumn(std::string name) { - Nz::FontRef scoreMenuFont = Nz::FontLibrary::Get("BW_ScoreMenu"); + std::shared_ptr scoreMenuFont = Nz::Font::GetDefault(); + //Nz::FontRef scoreMenuFont = Nz::FontLibrary::Get("BW_ScoreMenu"); assert(scoreMenuFont); std::size_t columnIndex = m_columns.size(); auto& columnData = m_columns.emplace_back(); columnData.name = std::move(name); - columnData.widget = Add(); + columnData.widget = Add(); columnData.widget->UpdateText(Nz::SimpleTextDrawer::Draw(scoreMenuFont, columnData.name, 24, 0)); columnData.widget->Resize(columnData.widget->GetPreferredSize()); @@ -54,7 +55,8 @@ namespace bw std::size_t Scoreboard::AddTeam(std::string name, Nz::Color color) { - Nz::FontRef scoreMenuFont = Nz::FontLibrary::Get("BW_ScoreMenu"); + std::shared_ptr scoreMenuFont = Nz::Font::GetDefault(); + //Nz::FontRef scoreMenuFont = Nz::FontLibrary::Get("BW_ScoreMenu"); assert(scoreMenuFont); std::size_t teamIndex = m_teams.size(); @@ -65,10 +67,10 @@ namespace bw teamData.background = m_contentWidget->Add(); - teamData.line = m_contentWidget->Add(); + teamData.line = m_contentWidget->Add(); teamData.line->SetColor(teamData.color); - teamData.widget = m_contentWidget->Add(); + teamData.widget = m_contentWidget->Add(); teamData.widget->UpdateText(Nz::SimpleTextDrawer::Draw(scoreMenuFont, teamData.name, 24, 0, teamData.color)); teamData.widget->Resize(teamData.widget->GetPreferredSize()); @@ -97,14 +99,15 @@ namespace bw else if (teamId < m_teams.size()) playerColor = m_teams[teamId].color; - Nz::FontRef scoreMenuFont = Nz::FontLibrary::Get("BW_ScoreMenu"); + std::shared_ptr scoreMenuFont = Nz::Font::GetDefault(); + //Nz::FontRef scoreMenuFont = Nz::FontLibrary::Get("BW_ScoreMenu"); assert(scoreMenuFont); for (std::string& value : values) { auto& columnData = playerData.values.emplace_back(); columnData.value = std::move(value); - columnData.label = m_contentWidget->Add(); + columnData.label = m_contentWidget->Add(); columnData.label->UpdateText(Nz::SimpleTextDrawer::Draw(scoreMenuFont, columnData.value, 18, 0, playerColor)); columnData.label->Resize(columnData.label->GetPreferredSize()); } @@ -112,7 +115,7 @@ namespace bw Layout(); } - Nz::String Scoreboard::ToString() const + std::string Scoreboard::ToString() const { return "Scoreboard"; } @@ -148,8 +151,8 @@ namespace bw if (teamId < m_teams.size()) teamColor = m_teams[teamId].color; - Nz::FontRef scoreMenuFont = Nz::FontLibrary::Get("BW_ScoreMenu"); - assert(scoreMenuFont); + std::shared_ptr scoreMenuFont = Nz::Font::GetDefault(); + //Nz::FontRef scoreMenuFont = Nz::FontLibrary::Get("BW_ScoreMenu"); for (auto& playerColumn : playerData->values) { @@ -176,8 +179,8 @@ namespace bw else if (playerData.teamId < m_teams.size()) playerColor = m_teams[playerData.teamId].color; - Nz::FontRef scoreMenuFont = Nz::FontLibrary::Get("BW_ScoreMenu"); - assert(scoreMenuFont); + std::shared_ptr scoreMenuFont = Nz::Font::GetDefault(); + //Nz::FontRef scoreMenuFont = Nz::FontLibrary::Get("BW_ScoreMenu"); auto& columnData = playerData.values[valueIndex]; columnData.value = std::move(value); diff --git a/src/ClientLib/Scripting/ClientEditorEntityStore.cpp b/src/ClientLib/Scripting/ClientEditorEntityStore.cpp index cb8f5933..9278cb48 100644 --- a/src/ClientLib/Scripting/ClientEditorEntityStore.cpp +++ b/src/ClientLib/Scripting/ClientEditorEntityStore.cpp @@ -9,34 +9,34 @@ #include #include #include -#include +#include +#include #include -#include namespace bw { - bool ClientEditorEntityStore::InitializeEntity(entt::entity entity) const + bool ClientEditorEntityStore::InitializeEntity(entt::handle entity) const { - auto& scriptComponent = entity->GetComponent(); + auto& scriptComponent = entity.get(); if (!InitializeEntity(static_cast(*scriptComponent.GetElement()), entity)) { - entity->Kill(); + entity.destroy(); return false; } return true; } - entt::entity ClientEditorEntityStore::InstantiateEntity(entt::registry& world, std::size_t entityIndex, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, entt::entity parentEntity) const + entt::handle ClientEditorEntityStore::InstantiateEntity(entt::registry& world, std::size_t entityIndex, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, PropertyValueMap properties, entt::handle parentEntity) const { const auto& entityClass = GetElement(entityIndex); bool hasInputs = entityClass->elementTable.get_or("HasInputs", false); bool playerControlled = entityClass->elementTable.get_or("PlayerControlled", false); - entt::entity entity = CreateEntity(world, entityClass, std::move(properties)); + entt::handle entity = CreateEntity(world, entityClass, std::move(properties)); - auto& nodeComponent = entity->AddComponent(); + auto& nodeComponent = entity.emplace(); nodeComponent.SetPosition(position); nodeComponent.SetRotation(rotation); nodeComponent.SetScale(scale); @@ -45,10 +45,10 @@ namespace bw nodeComponent.SetParent(parentEntity); if (playerControlled) - entity->AddComponent(); + entity.emplace(); if (hasInputs) - entity->AddComponent(std::make_shared()); + entity.emplace(std::make_shared()); return entity; } diff --git a/src/ClientLib/Scripting/ClientElementLibrary.cpp b/src/ClientLib/Scripting/ClientElementLibrary.cpp index ce13c65b..339fee04 100644 --- a/src/ClientLib/Scripting/ClientElementLibrary.cpp +++ b/src/ClientLib/Scripting/ClientElementLibrary.cpp @@ -14,11 +14,9 @@ #include #include #include -#include -#include +#include +#include #include -#include -#include #include namespace bw @@ -48,7 +46,7 @@ namespace bw Nz::Matrix4 transformMatrix = Nz::Matrix4f::Transform(offset, Nz::EulerAnglesf(rotation.x, rotation.y, rotation.z), scale); - auto& visualComponent = entity->GetComponent(); + auto& visualComponent = entity.get(); visualComponent.GetLayerVisual()->AttachRenderable(model, transformMatrix, renderOrder); }); @@ -59,7 +57,7 @@ namespace bw return; entt::handle entity = AssertScriptEntity(entityTable); - entt::registry* world = entity->GetWorld(); + /*entt::registry* world = entity->GetWorld(); assert(world); Ndk::EntityList hitEntities; //< FIXME: RegionQuery hit multiples entities @@ -73,10 +71,10 @@ namespace bw if (hitEntity->HasComponent()) { - Ndk::PhysicsComponent2D& hitEntityPhys = hitEntity->GetComponent(); + Ndk::PhysicsComponent2D& hitEntityPhys = hitEntity.get(); hitEntityPhys.AddImpulse(Nz::Vector2f::Normalize(hitEntityPhys.GetMassCenter(Nz::CoordSys::Global) - origin) * pushbackForce); } - }); + });*/ }; elementTable["AddSprite"] = LuaFunction([this](const sol::table& entityTable, const sol::table& parameters) @@ -101,7 +99,7 @@ namespace bw color = Nz::Color::White; //TODO: Don't create a material everytime - Nz::MaterialRef mat = Nz::Material::New("Translucent2D"); + /*Nz::MaterialRef mat = Nz::Material::New("Translucent2D"); if (!texturePath.empty()) mat->SetDiffuseMap(m_assetStore.GetTexture(texturePath)); @@ -110,9 +108,8 @@ namespace bw if (repeatTexture) sampler.SetWrapMode(Nz::SamplerWrap_Repeat); - Nz::SpriteRef sprite = Nz::Sprite::New(); + std::shared_ptr sprite = std::make_shared(); sprite->SetColor(color); - sprite->SetMaterial(mat); sprite->SetTextureCoords(textureCoords); if (std::optional cornerColorTable = parameters.get_or>("CornerColor", std::nullopt); cornerColorTable) @@ -127,19 +124,19 @@ namespace bw { { "TopLeft", - Nz::RectCorner_LeftTop + Nz::RectCorner::LeftTop }, { "TopRight", - Nz::RectCorner_RightTop + Nz::RectCorner::RightTop }, { "BottomLeft", - Nz::RectCorner_LeftBottom + Nz::RectCorner::LeftBottom }, { "BottomRight", - Nz::RectCorner_RightBottom + Nz::RectCorner::RightBottom } } }; @@ -156,12 +153,12 @@ namespace bw sprite->SetSize(size * scale); sprite->SetOrigin(sprite->GetSize() * origin); - auto& visualComponent = entity->GetComponent(); + auto& visualComponent = entity.get(); Sprite scriptSprite(visualComponent.GetLayerVisual(), sprite, transformMatrix, renderOrder); scriptSprite.Show(); - return scriptSprite; + return scriptSprite;*/ }); elementTable["AddText"] = LuaFunction([this](const sol::table& entityTable, const sol::table& parameters) @@ -191,13 +188,13 @@ namespace bw else outlineColor = Nz::Color::Black; - Nz::FontRef font; + /*Nz::FontRef font; if (!fontName.empty()) { font = Nz::FontLibrary::Get(fontName); if (!font) bwLog(GetLogger(), LogLevel::Warning, "unknown font \"{}\"", fontName); - } + }*/ Nz::SimpleTextDrawer drawer; drawer.SetColor(color); @@ -205,13 +202,13 @@ namespace bw drawer.SetOutlineThickness(outlineThickness); drawer.SetText(text); - if (font) - drawer.SetFont(font); + //if (font) + // drawer.SetFont(font); - Nz::TextSpriteRef textSprite = Nz::TextSprite::New(); + std::shared_ptr textSprite = Nz::TextSprite::New(); textSprite->Update(drawer); - auto& visualComponent = entity->GetComponent(); + auto& visualComponent = entity.get(); Text scriptText(visualComponent.GetLayerVisual(), std::move(drawer), std::move(textSprite), transformMatrix, renderOrder, isHovering); scriptText.Show(); @@ -227,7 +224,7 @@ namespace bw elementTable["GetGlobalBounds"] = LuaFunction([](const sol::table& entityTable) { entt::handle entity = AssertScriptEntity(entityTable); - auto& visualComponent = entity->GetComponent(); + auto& visualComponent = entity.get(); const auto& layerVisualHandle = visualComponent.GetLayerVisual(); if (!layerVisualHandle) @@ -246,13 +243,13 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - return entity->GetComponent().GetLayerIndex(); + return entity.get().GetLayerIndex(); }); elementTable["GetLocalBounds"] = LuaFunction([](const sol::table& entityTable) { entt::handle entity = AssertScriptEntity(entityTable); - auto& visualComponent = entity->GetComponent(); + auto& visualComponent = entity.get(); const auto& layerVisualHandle = visualComponent.GetLayerVisual(); if (!layerVisualHandle) @@ -266,17 +263,17 @@ namespace bw { entt::handle entity = AssertScriptEntity(table); - if (!entity->HasComponent()) + if (ClientOwnerComponent* clientOwner = entity.try_get()) + return sol::make_object(s, clientOwner->GetOwner()->CreateHandle()); + else return sol::nil; - - return sol::make_object(s, entity->GetComponent().GetOwner()->CreateHandle()); }); elementTable["GetProperty"] = LuaFunction([](sol::this_state s, const sol::table& table, const std::string& propertyName) -> sol::object { entt::handle entity = AssertScriptEntity(table); - auto& entityScript = entity->GetComponent(); + auto& entityScript = entity.get(); auto propertyVal = entityScript.GetProperty(propertyName); if (propertyVal.has_value()) @@ -285,8 +282,8 @@ namespace bw const PropertyValue& property = propertyVal.value(); ClientMatch* match; - if (entity->HasComponent()) - match = &entity->GetComponent().GetClientMatch(); + if (ClientMatchComponent* matchComponent = entity.try_get()) + match = &matchComponent->GetClientMatch(); else match = nullptr; @@ -299,7 +296,7 @@ namespace bw elementTable["PlaySound"] = LuaFunction([this](sol::this_state L, const sol::table& entityTable, const std::string& soundPath, bool isAttachedToEntity, bool isLooping, bool isSpatialized) { entt::handle entity = AssertScriptEntity(entityTable); - auto& entityMatch = entity->GetComponent(); + auto& entityMatch = entity.get(); const std::shared_ptr& soundBuffer = m_assetStore.GetSoundBuffer(soundPath); if (!soundBuffer) @@ -322,15 +319,14 @@ namespace bw }); } - void ClientElementLibrary::SetScale(entt::entity entity, float newScale) + void ClientElementLibrary::SetScale(entt::handle entity, float newScale) { - auto& visualComponent = entity->GetComponent(); + auto& visualComponent = entity.get(); visualComponent.GetLayerVisual()->UpdateScale(newScale); - if (entity->HasComponent()) + if (WeaponWielderComponent* wielderComponent = entity.try_get()) { - auto& wielderComponent = entity->GetComponent(); - for (entt::entity weapon : wielderComponent.GetWeapons()) + for (const EntityOwner& weapon : wielderComponent->GetWeapons()) SetScale(weapon, newScale); } } diff --git a/src/ClientLib/Scripting/ClientEntityLibrary.cpp b/src/ClientLib/Scripting/ClientEntityLibrary.cpp index 01103441..f2b23232 100644 --- a/src/ClientLib/Scripting/ClientEntityLibrary.cpp +++ b/src/ClientLib/Scripting/ClientEntityLibrary.cpp @@ -18,11 +18,11 @@ #include #include #include -#include +//#include +#include #include -#include +#include #include -#include namespace bw { @@ -33,12 +33,12 @@ namespace bw RegisterClientLibrary(elementMetatable); } - void ClientEntityLibrary::InitRigidBody(lua_State* L, entt::entity entity, float mass) + void ClientEntityLibrary::InitRigidBody(lua_State* L, entt::handle entity, float mass) { SharedEntityLibrary::InitRigidBody(L, entity, mass); - entity->GetComponent().EnableNodeSynchronization(false); - entity->AddComponent(); + //entity.get().EnableNodeSynchronization(false); + entity.emplace(); } void ClientEntityLibrary::RegisterClientLibrary(sol::table& elementMetatable) @@ -47,7 +47,7 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - auto& clientMatch = entity->GetComponent().GetClientMatch(); + auto& clientMatch = entity.get().GetClientMatch(); LayerIndex layerIndex = parameters["LayerIndex"]; if (layerIndex >= clientMatch.GetLayerCount()) @@ -57,10 +57,7 @@ namespace bw Nz::Vector2f parallaxFactor = parameters.get_or("ParallaxFactor", Nz::Vector2f::Unit()); Nz::Vector2f scale = parameters.get_or("Scale", Nz::Vector2f::Unit()); - if (!entity->HasComponent()) - entity->AddComponent(clientMatch.GetRenderWorld()); - - auto& visibleLayer = entity->GetComponent(); + auto& visibleLayer = entity.get_or_emplace(clientMatch.GetRenderWorld()); visibleLayer.RegisterLocalLayer(clientMatch.GetLayer(layerIndex), renderOrder, scale, parallaxFactor); }); @@ -80,7 +77,7 @@ namespace bw if (materials.empty()) return {}; - Nz::TileMapRef tileMap = Nz::TileMap::New(mapSize, cellSize, materials.size()); + /*Nz::TileMapRef tileMap = Nz::TileMap::New(mapSize, cellSize, materials.size()); for (auto&& [materialPath, matIndex] : materials) { Nz::MaterialRef material = Nz::Material::New(); //< FIXME @@ -132,15 +129,16 @@ namespace bw Tilemap scriptTilemap(visualComponent.GetLayerVisual(), std::move(tileMap), transformMatrix, renderOrder); scriptTilemap.Show(); - return scriptTilemap; + return scriptTilemap;*/ + return {}; }); elementMetatable["ClearLayers"] = LuaFunction([](const sol::table& entityTable) { entt::handle entity = AssertScriptEntity(entityTable); - if (entity->HasComponent()) - entity->GetComponent().Clear(); + if (VisibleLayerComponent* visibleLayer = entity.try_get()) + visibleLayer->Clear(); }); } } diff --git a/src/ClientLib/Scripting/ClientEntityStore.cpp b/src/ClientLib/Scripting/ClientEntityStore.cpp index 3ee987f3..e9d36679 100644 --- a/src/ClientLib/Scripting/ClientEntityStore.cpp +++ b/src/ClientLib/Scripting/ClientEntityStore.cpp @@ -12,13 +12,13 @@ namespace bw { std::optional ClientEntityStore::InstantiateEntity(ClientLayer& layer, std::size_t elementIndex, Nz::UInt32 serverId, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, const PropertyValueMap& properties, entt::entity parentEntity) const { - entt::entity entity = ClientEditorEntityStore::InstantiateEntity(layer.GetWorld(), elementIndex, position, rotation, scale, properties, parentEntity); + entt::handle entity = ClientEditorEntityStore::InstantiateEntity(layer.GetWorld(), elementIndex, position, rotation, scale, properties, parentEntity); if (!entity) return std::nullopt; ClientLayerEntity layerEntity(layer, entity, serverId, uniqueId); - entity->AddComponent(layerEntity.CreateHandle()); - entity->AddComponent(layer.GetClientMatch(), layer.GetLayerIndex(), uniqueId); + entity.emplace(layerEntity.CreateHandle()); + entity.emplace(layer.GetClientMatch(), layer.GetLayerIndex(), uniqueId); if (!InitializeEntity(entity)) return std::nullopt; diff --git a/src/ClientLib/Scripting/ClientWeaponLibrary.cpp b/src/ClientLib/Scripting/ClientWeaponLibrary.cpp index 50c1d991..eba31a45 100644 --- a/src/ClientLib/Scripting/ClientWeaponLibrary.cpp +++ b/src/ClientLib/Scripting/ClientWeaponLibrary.cpp @@ -55,7 +55,7 @@ namespace bw const float trailSpeed = 500.f; - const Nz::SpriteRef& trailSprite = Nz::SpriteLibrary::Get("Trail"); + const std::shared_ptr& trailSprite = Nz::SpriteLibrary::Get("Trail"); if (!trailSprite) return; diff --git a/src/ClientLib/Scripting/ClientWeaponStore.cpp b/src/ClientLib/Scripting/ClientWeaponStore.cpp index d1fc08e6..5ac5d822 100644 --- a/src/ClientLib/Scripting/ClientWeaponStore.cpp +++ b/src/ClientLib/Scripting/ClientWeaponStore.cpp @@ -27,7 +27,7 @@ namespace bw auto& sampler = mat->GetDiffuseSampler(); sampler.SetFilterMode(Nz::SamplerFilter_Bilinear); - Nz::SpriteRef sprite = Nz::Sprite::New(); + std::shared_ptr sprite = Nz::Sprite::New(); sprite->SetMaterial(mat); sprite->SetSize(sprite->GetSize() * weaponClass->scale); Nz::Vector2f burgerSize = sprite->GetSize(); diff --git a/src/ClientLib/Scripting/ParticleRegistry.cpp b/src/ClientLib/Scripting/ParticleRegistry.cpp index 59b23280..c63fac0e 100644 --- a/src/ClientLib/Scripting/ParticleRegistry.cpp +++ b/src/ClientLib/Scripting/ParticleRegistry.cpp @@ -2,6 +2,8 @@ // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE +#if 0 + #include #include #include @@ -409,3 +411,5 @@ namespace bw return factory(parameters); } } + +#endif diff --git a/src/ClientLib/Systems/FrameCallbackSystem.cpp b/src/ClientLib/Systems/FrameCallbackSystem.cpp index fb93b3c0..97eb0f1a 100644 --- a/src/ClientLib/Systems/FrameCallbackSystem.cpp +++ b/src/ClientLib/Systems/FrameCallbackSystem.cpp @@ -3,43 +3,31 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include #include #include namespace bw { - FrameCallbackSystem::FrameCallbackSystem() + FrameCallbackSystem::FrameCallbackSystem(entt::registry& registry) : + m_registry(registry) { - Requires(); - SetMaximumUpdateRate(0); - SetUpdateOrder(100); + m_scriptDestroyConnection = m_registry.on_destroy().connect<&FrameCallbackSystem::OnScriptDestroy>(this); } - void FrameCallbackSystem::OnEntityRemoved(Ndk::Entity* entity) - { - m_frameUpdateEntities.Remove(entity); - } - - void FrameCallbackSystem::OnEntityValidation(Ndk::Entity* entity, bool /*justAdded*/) - { - auto& scriptComponent = entity->GetComponent(); - - if (scriptComponent.HasCallbacks(ElementEvent::Frame)) - m_frameUpdateEntities.Insert(entity); - else - m_frameUpdateEntities.Remove(entity); - } - - void FrameCallbackSystem::OnUpdate(float /*elapsedTime*/) + void FrameCallbackSystem::Update(float /*elapsedTime*/) { for (entt::entity entity : m_frameUpdateEntities) { - auto& scriptComponent = entity->GetComponent(); + auto& scriptComponent = m_registry.get(entity); scriptComponent.ExecuteCallback(); } } - Ndk::SystemIndex FrameCallbackSystem::systemIndex; + void FrameCallbackSystem::OnScriptDestroy(entt::registry& registry, entt::entity entity) + { + assert(&m_registry == ®istry); + + m_frameUpdateEntities.erase(entity); + } } diff --git a/src/ClientLib/Systems/PostFrameCallbackSystem.cpp b/src/ClientLib/Systems/PostFrameCallbackSystem.cpp index 3fd648bd..128b2d2d 100644 --- a/src/ClientLib/Systems/PostFrameCallbackSystem.cpp +++ b/src/ClientLib/Systems/PostFrameCallbackSystem.cpp @@ -3,43 +3,31 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include #include #include namespace bw { - PostFrameCallbackSystem::PostFrameCallbackSystem() + PostFrameCallbackSystem::PostFrameCallbackSystem(entt::registry& registry) : + m_registry(registry) { - Requires(); - SetMaximumUpdateRate(0); - SetUpdateOrder(100); + m_scriptDestroyConnection = m_registry.on_destroy().connect<&PostFrameCallbackSystem::OnScriptDestroy>(this); } - void PostFrameCallbackSystem::OnEntityRemoved(Ndk::Entity* entity) - { - m_frameUpdateEntities.Remove(entity); - } - - void PostFrameCallbackSystem::OnEntityValidation(Ndk::Entity* entity, bool /*justAdded*/) - { - auto& scriptComponent = entity->GetComponent(); - - if (scriptComponent.HasCallbacks(ElementEvent::PostFrame)) - m_frameUpdateEntities.Insert(entity); - else - m_frameUpdateEntities.Remove(entity); - } - - void PostFrameCallbackSystem::OnUpdate(float /*elapsedTime*/) + void PostFrameCallbackSystem::Update(float /*elapsedTime*/) { for (entt::entity entity : m_frameUpdateEntities) { - auto& scriptComponent = entity->GetComponent(); + auto& scriptComponent = m_registry.get(entity); - scriptComponent.ExecuteCallback(); + scriptComponent.ExecuteCallback(); } } - Ndk::SystemIndex PostFrameCallbackSystem::systemIndex; + void PostFrameCallbackSystem::OnScriptDestroy(entt::registry& registry, entt::entity entity) + { + assert(&m_registry == ®istry); + + m_frameUpdateEntities.erase(entity); + } } diff --git a/src/ClientLib/Systems/SoundSystem.cpp b/src/ClientLib/Systems/SoundSystem.cpp index a364f84a..e6c4d671 100644 --- a/src/ClientLib/Systems/SoundSystem.cpp +++ b/src/ClientLib/Systems/SoundSystem.cpp @@ -12,18 +12,80 @@ namespace bw { - SoundSystem::SoundSystem(ConfigFile& playerSettings) : + SoundSystem::SoundSystem(entt::registry& registry, ConfigFile& playerSettings) : m_maxSoundInPool(32), + m_registry(registry), m_soundOffset(0.f, 0.f, 50.f), m_nextSoundId(1) { - Requires(); - m_volume = float(playerSettings.GetIntegerValue("Sound.EffectVolume")); m_effectVolumeUpdateSlot.Connect(playerSettings.GetIntegerUpdateSignal("Sound.EffectVolume"), [this](long long newValue) { UpdateVolume(float(newValue)); }); + + m_observer.connect(m_registry, entt::collector.group()); + + m_nodeDestroyConnection = m_registry.on_destroy().connect<&SoundSystem::OnSoundDestroy>(this); + m_soundEmitterDestroyConnection = m_registry.on_destroy().connect<&SoundSystem::OnSoundDestroy>(this); + } + + void SoundSystem::Update(float elapsedTime) + { + float invElapsedTime = 1.f / elapsedTime; + + m_observer.each([&](entt::entity entity) + { + if (m_registry.try_get(entity) && m_registry.try_get()) + m_movableEntities.insert(entity); + }); + + for (auto& soundEntry : m_soundPool) + { + if (!soundEntry.sound.IsPlaying()) + m_playingSounds.erase(soundEntry.playingSoundId); + } + + for (entt::entity movableEntity : m_movableEntities) + { + auto& nodeComponent = m_registry.get(movableEntity); + auto& soundEmitterComponent = m_registry.get(movableEntity); + + Nz::Vector3f entityPos = nodeComponent.GetPosition(); + Nz::Vector3f lastEntityPos = soundEmitterComponent.GetLastPosition(); + soundEmitterComponent.UpdateLastPosition(entityPos); + + Nz::Vector3f velocity = (entityPos - lastEntityPos) * invElapsedTime; + + auto& ownedSound = soundEmitterComponent.GetSounds(); + for (auto ownedSoundIt = ownedSound.begin(); ownedSoundIt != ownedSound.end();) + { + Nz::UInt32 soundId = *ownedSoundIt; + + auto it = m_playingSounds.find(soundId); + if (it == m_playingSounds.end()) + { + ownedSoundIt = ownedSound.erase(ownedSoundIt); + continue; + } + + auto& soundEntry = m_soundPool[it->second]; + if (soundEntry.attachedToEntity) + { + soundEntry.sound.SetPosition(entityPos + m_soundOffset); + soundEntry.sound.SetVelocity(velocity); + } + + ++ownedSoundIt; + } + } + } + + void SoundSystem::OnSoundDestroy(entt::registry& registry, entt::entity entity) + { + assert(&m_registry == ®istry); + + m_movableEntities.erase(entity); } Nz::UInt32 SoundSystem::PlaySound(const std::shared_ptr& soundBuffer, const Nz::Vector3f& soundPosition, bool attachedToEntity, bool isLooping, bool isSpatialized) @@ -101,71 +163,4 @@ namespace bw for (SoundData& soundData : m_soundPool) soundData.sound.SetVolume(newVolume); } - - void SoundSystem::OnEntityRemoved(Ndk::Entity* entity) - { - m_movableEntities.Remove(entity); - } - - void SoundSystem::OnEntityValidation(Ndk::Entity* entity, bool /*justAdded*/) - { - if (entity->HasComponent()) - { - m_movableEntities.Insert(entity); - - auto& nodeComponent = entity.get(); - auto& soundEmitterComponent = entity->GetComponent(); - - soundEmitterComponent.UpdateLastPosition(nodeComponent.GetPosition()); - } - else - m_movableEntities.Remove(entity); - } - - void SoundSystem::OnUpdate(float elapsedTime) - { - float invElapsedTime = 1.f / elapsedTime; - - for (auto& soundEntry : m_soundPool) - { - if (!soundEntry.sound.IsPlaying()) - m_playingSounds.erase(soundEntry.playingSoundId); - } - - for (entt::entity movableEntity : m_movableEntities) - { - auto& nodeComponent = movableentity.get(); - auto& soundEmitterComponent = movableEntity->GetComponent(); - - Nz::Vector3f entityPos = nodeComponent.GetPosition(); - Nz::Vector3f lastEntityPos = soundEmitterComponent.GetLastPosition(); - soundEmitterComponent.UpdateLastPosition(entityPos); - - Nz::Vector3f velocity = (entityPos - lastEntityPos) * invElapsedTime; - - auto& ownedSound = soundEmitterComponent.GetSounds(); - for (auto ownedSoundIt = ownedSound.begin(); ownedSoundIt != ownedSound.end();) - { - Nz::UInt32 soundId = *ownedSoundIt; - - auto it = m_playingSounds.find(soundId); - if (it == m_playingSounds.end()) - { - ownedSoundIt = ownedSound.erase(ownedSoundIt); - continue; - } - - auto& soundEntry = m_soundPool[it->second]; - if (soundEntry.attachedToEntity) - { - soundEntry.sound.SetPosition(entityPos + m_soundOffset); - soundEntry.sound.SetVelocity(velocity); - } - - ++ownedSoundIt; - } - } - } - - Ndk::SystemIndex SoundSystem::systemIndex; } diff --git a/src/ClientLib/Systems/VisualInterpolationSystem.cpp b/src/ClientLib/Systems/VisualInterpolationSystem.cpp index 314673c9..6e28600d 100644 --- a/src/ClientLib/Systems/VisualInterpolationSystem.cpp +++ b/src/ClientLib/Systems/VisualInterpolationSystem.cpp @@ -6,35 +6,37 @@ #include #include #include +#include #include -#include #include namespace bw { - VisualInterpolationSystem::VisualInterpolationSystem() + VisualInterpolationSystem::VisualInterpolationSystem(entt::registry& registry) : + m_registry(registry) { - Requires(); + m_observer.connect(m_registry, entt::collector.group()); } - void VisualInterpolationSystem::OnEntityAdded(Ndk::Entity* entity) + void VisualInterpolationSystem::Update(float elapsedTime) { - auto& entityNode = entity.get(); - auto& entityLerp = entity->GetComponent(); + m_observer.each([&](entt::entity entity) + { + auto& entityNode = m_registry.get(entity); + auto& entityLerp = m_registry.get(entity); - entityLerp.UpdateLastStates(Nz::Vector2f(entityNode.GetPosition()), AngleFromQuaternion(entityNode.GetRotation())); - } + entityLerp.UpdateLastStates(Nz::Vector2f(entityNode.GetPosition()), AngleFromQuaternion(entityNode.GetRotation())); + }); - void VisualInterpolationSystem::OnUpdate(float elapsedTime) - { float C = 10.f; float factor = 1.f - std::exp(-elapsedTime * C); - for (entt::entity entity : GetEntities()) + auto view = m_registry.view(); + for (entt::entity entity : view) { - auto& entityLerp = entity->GetComponent(); - auto& entityNode = entity.get(); - auto& entityPhysics = entity->GetComponent(); + auto& entityLerp = m_registry.get(entity); + auto& entityNode = m_registry.get(entity); + auto& entityPhysics = m_registry.get(entity); // x = x + (target-x) * (1-Exp(-deltaTime*C)) Nz::RadianAnglef sourceRot = entityLerp.GetLastRotation(); @@ -51,6 +53,4 @@ namespace bw entityLerp.UpdateLastStates(position, rotation); } } - - Ndk::SystemIndex VisualInterpolationSystem::systemIndex; } diff --git a/src/CoreLib/Player.cpp b/src/CoreLib/Player.cpp index 138bee43..320a1ab0 100644 --- a/src/CoreLib/Player.cpp +++ b/src/CoreLib/Player.cpp @@ -116,7 +116,7 @@ namespace bw { auto& weaponWielder = m_playerEntity->GetComponent(); - weaponWielder.OverrideEntities([&](Ndk::EntityOwner& weaponEntity) + weaponWielder.OverrideEntities([&](EntityOwner& weaponEntity) { EntityId weaponUniqueId = m_match.AllocateUniqueId(); diff --git a/src/CoreLib/Systems/TickCallbackSystem.cpp b/src/CoreLib/Systems/TickCallbackSystem.cpp index 053da5b1..08f6993c 100644 --- a/src/CoreLib/Systems/TickCallbackSystem.cpp +++ b/src/CoreLib/Systems/TickCallbackSystem.cpp @@ -18,11 +18,6 @@ namespace bw m_scriptDestroyConnection = m_registry.on_destroy().connect<&TickCallbackSystem::OnScriptDestroy>(this); } - TickCallbackSystem::~TickCallbackSystem() - { - m_scriptDestroyConnection.release(); - } - void TickCallbackSystem::OnScriptDestroy(entt::registry& registry, entt::entity entity) { assert(&m_registry == ®istry); diff --git a/src/CoreLib/Utility/CrashHandlerWin32.cpp b/src/CoreLib/Utility/CrashHandlerWin32.cpp index e30cd8f7..ae439aa7 100644 --- a/src/CoreLib/Utility/CrashHandlerWin32.cpp +++ b/src/CoreLib/Utility/CrashHandlerWin32.cpp @@ -3,6 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include +#include #include #ifdef NAZARA_PLATFORM_WINDOWS @@ -173,7 +174,10 @@ namespace bw ss << "Game version: " << GameMajorVersion << "." << GameMinorVersion << "." << GamePatchVersion << " (" << GameVersion << ")" << "\n"; ss << "Build info: " << GetBuildInfo() << "\n"; - ss << "CPU: " << Nz::HardwareInfo::GetProcessorBrandString() << "\n"; + const Nz::HardwareInfo& hardwareInfo = Nz::Core::Instance()->GetHardwareInfo(); + ss << "CPU: " << hardwareInfo.GetCpuBrandString() << " - " << hardwareInfo.GetCpuVendorName() << "\n"; + ss << "Thread count: " << hardwareInfo.GetCpuThreadCount() << "\n"; + ss << "Memory: " << hardwareInfo.GetSystemTotalMemory() << "\n"; ss << "\n"; diff --git a/src/MapEditor/Gizmos/EditorGizmo.hpp b/src/MapEditor/Gizmos/EditorGizmo.hpp index 2f852348..dc59b1b4 100644 --- a/src/MapEditor/Gizmos/EditorGizmo.hpp +++ b/src/MapEditor/Gizmos/EditorGizmo.hpp @@ -32,7 +32,7 @@ namespace bw private: static std::shared_ptr GenerateBoxModel(); - Ndk::EntityOwner m_selectionOverlayEntity; + EntityOwner m_selectionOverlayEntity; std::vector m_targetEntities; }; } diff --git a/src/MapEditor/Gizmos/PositionGizmo.hpp b/src/MapEditor/Gizmos/PositionGizmo.hpp index 776acd61..9b993fba 100644 --- a/src/MapEditor/Gizmos/PositionGizmo.hpp +++ b/src/MapEditor/Gizmos/PositionGizmo.hpp @@ -45,13 +45,13 @@ namespace bw }; std::array m_spriteDefaultColors; - std::array m_sprites; + std::array, 3> m_sprites; std::array m_allowedMovements; std::vector m_entitiesOffsets; Camera& m_camera; MovementType m_hoveredAction; MovementType m_movementType; - Ndk::EntityOwner m_arrowEntity; + EntityOwner m_arrowEntity; Nz::Vector2f m_movementStartPos; Nz::Vector2f m_originalPosition; Nz::Vector2f m_positionAlignment; diff --git a/src/MapEditor/Logic/TileMapEditorMode.hpp b/src/MapEditor/Logic/TileMapEditorMode.hpp index 990a3413..8563b9a9 100644 --- a/src/MapEditor/Logic/TileMapEditorMode.hpp +++ b/src/MapEditor/Logic/TileMapEditorMode.hpp @@ -73,10 +73,10 @@ namespace bw SelectedTiles m_selection; std::vector m_tilesetGroups; std::vector m_tiles; - Ndk::EntityOwner m_tileSelectionEntity; - Ndk::EntityOwner m_tilemapEntity; + EntityOwner m_tileSelectionEntity; + EntityOwner m_tilemapEntity; Nz::CursorRef m_eraserCursor; - Nz::SpriteRef m_hoveringTileSprite; + std::shared_ptr m_hoveringTileSprite; Nz::TileMapRef m_tileMap; EditionMode m_editionMode; TileMapData m_tilemapData; diff --git a/src/MapEditor/Widgets/MapCanvas.cpp b/src/MapEditor/Widgets/MapCanvas.cpp index d53ae8a4..a636c773 100644 --- a/src/MapEditor/Widgets/MapCanvas.cpp +++ b/src/MapEditor/Widgets/MapCanvas.cpp @@ -584,7 +584,7 @@ namespace bw auto AddLine = [&](const Nz::Vector2f& origin, const Nz::Vector2f& size) { - Nz::SpriteRef lineSprite = Nz::Sprite::New(); + std::shared_ptr lineSprite = Nz::Sprite::New(); lineSprite->SetColor(color); lineSprite->SetSize(size); diff --git a/src/MapEditor/Widgets/MapCanvas.hpp b/src/MapEditor/Widgets/MapCanvas.hpp index 3f176970..9c13e75f 100644 --- a/src/MapEditor/Widgets/MapCanvas.hpp +++ b/src/MapEditor/Widgets/MapCanvas.hpp @@ -119,8 +119,8 @@ namespace bw std::vector m_layers; std::unique_ptr m_entityGizmo; EditorWindow& m_editor; - Ndk::EntityOwner m_currentLayerEntity; - Ndk::EntityOwner m_gridEntity; + EntityOwner m_currentLayerEntity; + EntityOwner m_gridEntity; bool m_isPhysicsDebugDrawEnabled; }; } diff --git a/src/MapEditor/Widgets/PlayWindow.hpp b/src/MapEditor/Widgets/PlayWindow.hpp index 469b57e9..33f1a2a8 100644 --- a/src/MapEditor/Widgets/PlayWindow.hpp +++ b/src/MapEditor/Widgets/PlayWindow.hpp @@ -31,7 +31,7 @@ namespace bw void resizeEvent(QResizeEvent* event) override; entt::registry m_world; - Ndk::Canvas m_canvas; + Nz::Canvas m_canvas; std::optional m_clientMatch; std::optional m_match; std::shared_ptr m_session; diff --git a/src/MapEditor/Widgets/TileSelectionWidget.hpp b/src/MapEditor/Widgets/TileSelectionWidget.hpp index 61dd4a15..166fdb70 100644 --- a/src/MapEditor/Widgets/TileSelectionWidget.hpp +++ b/src/MapEditor/Widgets/TileSelectionWidget.hpp @@ -67,7 +67,7 @@ namespace bw struct GroupData { - Ndk::EntityOwner tilemap; + EntityOwner tilemap; Nz::Vector2i contentSize; Nz::Vector2ui mapSize; std::vector materialFirstRectIndices; @@ -81,11 +81,11 @@ namespace bw std::size_t m_lastSelectedTile; std::optional m_currentSelectionFirstRect; std::vector m_groups; - Ndk::EntityOwner m_selectedEntity; - Ndk::EntityOwner m_selectionEntity; + EntityOwner m_selectedEntity; + EntityOwner m_selectionEntity; Nz::Bitset m_activeTiles; - Nz::SpriteRef m_selectedSprite; - Nz::SpriteRef m_selectionSprite; + std::shared_ptr m_selectedSprite; + std::shared_ptr m_selectionSprite; Nz::Vector2f m_tileSize; ScrollCanvas* m_tileSelectionCanvas; }; diff --git a/xmake-repo/packages/n/nazaraengine/xmake.lua b/xmake-repo/packages/n/nazaraengine/xmake.lua index 7d1b1da9..77774f4c 100644 --- a/xmake-repo/packages/n/nazaraengine/xmake.lua +++ b/xmake-repo/packages/n/nazaraengine/xmake.lua @@ -1,145 +1,153 @@ package("nazaraengine") - set_homepage("https://github.com/DigitalPulseSoftware/NazaraEngine") - set_description("A fast, complete, cross-platform and object-oriented engine which can help you in your daily developper life") - - set_urls("https://github.com/DigitalPulseSoftware/NazaraEngine.git") - - add_versions("2021.08.28", "8d7e99456ce5e76993cd2037a017018f982e2206") - add_versions("2021.06.10", "4989fbe2d28aa37dc11d24bdcc395431932a2f11") - add_versions("2021.04.01", "aef225d8784396035e1f92a029a685e654320e73") - - add_deps("nzsl") - - add_configs("audio", {description = "Includes the audio module", default = true, type = "boolean"}) - add_configs("graphics", {description = "Includes the graphics module", default = true, type = "boolean"}) - add_configs("network", {description = "Includes the network module", default = true, type = "boolean"}) - add_configs("physics2d", {description = "Includes the 2D physics module", default = true, type = "boolean"}) - add_configs("physics3d", {description = "Includes the 3D physics module", default = true, type = "boolean"}) - add_configs("platform", {description = "Includes the platform module", default = true, type = "boolean"}) - add_configs("renderer", {description = "Includes the renderer module", default = true, type = "boolean"}) - add_configs("utility", {description = "Includes the utility module", default = true, type = "boolean"}) - add_configs("widget", {description = "Includes the widget module", default = true, type = "boolean"}) - add_configs("plugin-assimp", {description = "Includes the assimp plugin", default = false, type = "boolean"}) - - if is_plat("linux") then - add_syslinks("pthread") - end - - local function has_audio(package) - return not package:config("server") and (package:config("audio")) - end - - local function has_graphics(package) - return not package:config("server") and (package:config("graphics")) - end - - local function has_network(package) - return package:config("network") - end - - local function has_renderer(package) - return not package:config("server") and (package:config("renderer") or has_graphics(package)) - end - - local function has_platform(package) - return not package:config("server") and (package:config("platform") or has_renderer(package)) - end - - local function has_physics2d(package) - return package:config("physics2d") - end - - local function has_physics3d(package) - return package:config("physics3d") - end - - local function has_utility(package) - return package:config("utility") or has_platform(package) - end - - local function has_widget(package) - return package:config("widget") - end + set_homepage("https://github.com/NazaraEngine/NazaraEngine") + set_description("Nazara Engine is a cross-platform framework aimed at (but not limited to) real-time applications requiring audio, 2D and 3D rendering, network and more (such as video games).") + set_license("MIT") + set_policy("package.librarydeps.strict_compatibility", true) + + set_urls("https://github.com/NazaraEngine/NazaraEngine.git") + + add_versions("2022.11.05", "45d4195527d6f2a79d3230a08bf1269cf254f9b9") + + add_deps("nazarautils") + add_deps("chipmunk2d", "dr_wav", "efsw", "fmt", "frozen", "kiwisolver", "libflac", "libsdl", "minimp3", "ordered_map", "stb", { private = true }) + add_deps("libvorbis", { private = true, configs = { with_vorbisenc = false } }) + add_deps("openal-soft", { private = true, configs = { shared = true }}) + + -- static compilation is not supported for now + add_configs("shared", {description = "Build shared library.", default = true, type = "boolean", readonly = true}) + + -- all modules have their own config + add_configs("plugin_assimp", {description = "Includes the assimp plugin", default = false, type = "boolean"}) + add_configs("plugin_ffmpeg", {description = "Includes the ffmpeg plugin", default = false, type = "boolean"}) + add_configs("entt", {description = "Includes EnTT to use components and systems", default = true, type = "boolean"}) + add_configs("with_symbols", {description = "Enable debug symbols in release", default = false, type = "boolean"}) + + local components = { + { + name = "Audio", + deps = { "core" } + }, + { + name = "Core", + custom = function (package, component) + if package:is_plat("linux") then + component:add("syslinks", "pthread", "dl") + end + end + }, + { + name = "Graphics", + deps = { "renderer" } + }, + { + name = "Network", + deps = { "core" } + }, + { + name = "Physics2D", + deps = { "core" } + }, + { + name = "Physics3D", + deps = { "core" } + }, + { + name = "Platform", + deps = { "utility" } + }, + { + name = "Renderer", + deps = { "platform", "utility" }, + custom = function (package, component) + if package:is_plat("windows", "mingw") then + component:add("syslinks", "gdi32", "user32", "advapi32") + end + end + }, + { + name = "Utility", + deps = { "core" } + }, + { + name = "Widgets", + deps = { "graphics" } + }, + } + + for _, comp in ipairs(components) do + local componentName = comp.name:lower() + add_configs(componentName, { description = "Includes the " .. comp.name .. " module", default = true, type = "boolean" }) + + on_component(componentName, function (package, component) + local prefix = "Nazara" + local suffix = package:config("shared") and "" or "-s" + if package:debug() then + suffix = suffix .. "-d" + end - local function has_assimp_plugin(package) - return package:config("plugin-assimp") + component:add("deps", table.unwrap(comp.deps)) + component:add("links", prefix .. comp.name .. suffix) + if comp.custom then + comp.custom(package, component) + end + end) end - on_load("windows", "linux", "macosx", "mingw", function (package) - local nazaradir = os.getenv("NAZARA_ENGINE_PATH") or "C:/Projets/Perso/NazaraNext/NazaraEngine" - if not os.isdir(nazaradir) then - raise("missing NAZARA_ENGINE_PATH") - end - package:set("installdir", nazaradir) - end) - - on_fetch(function (package) - local defines = {} - local includedirs = package:installdir("include") - local links = {} - local libprefix = package:debug() and "debug" or "releasedbg" - local linkdirs = package:installdir("bin/" .. package:plat() .. "_" .. package:arch() .. "_" .. libprefix) - local syslinks = {} - - local prefix = "Nazara" - local suffix = package:config("shared") and "" or "-s" - - if package:debug() then - suffix = suffix .. "-d" + on_load(function (package) + for _, comp in ipairs(components) do + local componentName = comp.name:lower() + if package:config(componentName) then + package:add("components", componentName) + end end if not package:config("shared") then - table.insert(defines, "NAZARA_STATIC") + package:add("defines", "NAZARA_STATIC") end - if has_audio(package) then - table.insert(links, prefix .. "Audio" .. suffix) + package:add("deps", "nzsl", { debug = package:debug(), configs = { with_symbols = package:config("with_symbols") or package:debug(), shared = true } }) + package:add("deps", "freetype", { private = true, configs = { bzip2 = true, png = true, woff2 = true, zlib = true, debug = package:debug() } }) + package:add("deps", "newtondynamics3", { private = true, debug = is_plat("windows") and package:debug() }) + if package:config("entt") then + package:add("deps", "entt 3.10.1") end - - if has_network(package) then - table.insert(links, prefix .. "Network" .. suffix) + if package:config("plugin_assimp") then + package:add("deps", "assimp v5.2.3", { private = true }) end - - if has_physics2d(package) then - table.insert(links, prefix .. "Physics2D" .. suffix) + if package:config("plugin_ffmpeg") then + package:add("deps", "ffmpeg", { private = true, configs = { shared = true }}) end + end) - if has_physics3d(package) then - table.insert(links, prefix .. "Physics3D" .. suffix) - end + on_install("windows", "mingw", "linux", "macosx", function (package) + local configs = {} + configs.assimp = package:config("plugin_assimp") + configs.ffmpeg = package:config("plugin_ffmpeg") + configs.examples = false + configs.override_runtime = false - if has_widget(package) then - table.insert(links, prefix .. "Widget" .. suffix) + if not package:config("shared") then + configs.embed_rendererbackends = true end - if has_graphics(package) then - table.insert(links, prefix .. "Graphics" .. suffix) + if package:is_debug() then + configs.mode = "debug" + elseif package:config("with_symbols") then + configs.mode = "releasedbg" + else + configs.mode = "release" end + import("package.tools.xmake").install(package, configs) + end) - if has_renderer(package) then - table.insert(links, prefix .. "Renderer" .. suffix) - if package:is_plat("windows", "mingw") then - table.insert(syslinks, "gdi32") - table.insert(syslinks, "user32") - table.insert(syslinks, "advapi32") + on_test(function (package) + for _, comp in ipairs(components) do + if package:config(comp.name:lower()) then + assert(package:check_cxxsnippets({test = [[ + void test() { + Nz::Modules nazara; + } + ]]}, {configs = {languages = "c++17"}, includes = "Nazara/" .. comp.name .. ".hpp"})) end end - - if has_platform(package) then - table.insert(links, prefix .. "Platform" .. suffix) - end - - if has_utility(package) then - table.insert(links, prefix .. "Utility" .. suffix) - end - - table.insert(links, prefix .. "Core" .. suffix) - - return { - defines = defines, - includedirs = includedirs, - links = links, - linkdirs = linkdirs, - syslinks = syslinks - } end) diff --git a/xmake-requires.lock b/xmake-requires.lock index 9a56ffc0..8fff1a38 100644 --- a/xmake-requires.lock +++ b/xmake-requires.lock @@ -106,19 +106,43 @@ } }, ["windows|x64"] = { + ["brotli#31fecfc4"] = { + repo = { + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "1.0.9" + }, + ["bzip2#31fecfc4"] = { + repo = { + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "1.0.8" + }, + ["chipmunk2d#31fecfc4"] = { + repo = { + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "7.0.3" + }, ["cmake#31fecfc4"] = { repo = { branch = "master", - commit = "acc779215567170eae5fa81054df9a14fbc74346", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", url = "https://github.com/xmake-io/xmake-repo.git" }, - version = "3.22.1" + version = "3.24.2" }, ["concurrentqueue#31fecfc4"] = { branch = "master", repo = { branch = "master", - commit = "98cc5e3d8c1c8074d067a4e63e0d7f94146a579a", + commit = "f881bf0478fb7210197d5079522041997ab94f34", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "master" @@ -126,15 +150,23 @@ ["cxxopts#31fecfc4"] = { repo = { branch = "master", - commit = "f881bf0478fb7210197d5079522041997ab94f34", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v3.0.0" }, + ["dr_wav#31fecfc4"] = { + repo = { + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "0.12.19" + }, ["efsw#31fecfc4"] = { repo = { branch = "master", - commit = "f881bf0478fb7210197d5079522041997ab94f34", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "1.1.0" @@ -142,7 +174,7 @@ ["entt 3.10.1#31fecfc4"] = { repo = { branch = "master", - commit = "f881bf0478fb7210197d5079522041997ab94f34", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v3.10.1" @@ -150,23 +182,31 @@ ["fmt#31fecfc4"] = { repo = { branch = "master", - commit = "f881bf0478fb7210197d5079522041997ab94f34", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", url = "https://github.com/xmake-io/xmake-repo.git" }, - version = "8.1.1" + version = "9.1.0" }, ["fmt#7572102e"] = { repo = { branch = "master", - commit = "acc779215567170eae5fa81054df9a14fbc74346", + commit = "8bbde2f876ebb123723243fdb1db7321503df67b", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "9.1.0" + }, + ["freetype#feb50816"] = { + repo = { + branch = "master", + commit = "71a1727013cbaf7a193154a5d2d24f0c6c568140", url = "https://github.com/xmake-io/xmake-repo.git" }, - version = "9.0.0" + version = "2.12.1" }, ["frozen#31fecfc4"] = { repo = { branch = "master", - commit = "f881bf0478fb7210197d5079522041997ab94f34", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "1.1.1" @@ -174,79 +214,163 @@ ["hopscotch-map#31fecfc4"] = { repo = { branch = "master", - commit = "98cc5e3d8c1c8074d067a4e63e0d7f94146a579a", + commit = "f881bf0478fb7210197d5079522041997ab94f34", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v2.3.0" }, + ["kiwisolver#31fecfc4"] = { + repo = { + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "1.4.4" + }, ["libcurl#31fecfc4"] = { repo = { branch = "master", - commit = "acc779215567170eae5fa81054df9a14fbc74346", + commit = "8bbde2f876ebb123723243fdb1db7321503df67b", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "7.84.0" }, - ["nazaraengine#31fecfc4"] = { + ["libflac#31fecfc4"] = { repo = { - url = "xmake-repo" + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" }, - version = "2021.08.28" + version = "1.3.3" + }, + ["libogg#31fecfc4"] = { + repo = { + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "v1.3.4" + }, + ["libpng#31fecfc4"] = { + repo = { + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "v1.6.37" + }, + ["libsdl#31fecfc4"] = { + repo = { + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "2.24.2" + }, + ["libvorbis#3c9faad2"] = { + repo = { + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "1.3.7" + }, + ["meson#31fecfc4"] = { + repo = { + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "0.62.1" + }, + ["minimp3#31fecfc4"] = { + repo = { + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "2021.05.29" }, - ["nazaraengine~server#047efbe9"] = { + ["nazaraengine#6e0ce8a6"] = { repo = { url = "xmake-repo" }, - version = "2021.08.28" + version = "2022.11.05" }, ["nazarautils#31fecfc4"] = { repo = { - commit = "5d2ec45e5605b9d8c9667c485986abbcfe914fce", + commit = "5727e994c2b90e34bc01773e1d35f147640b818e", url = "https://github.com/NazaraEngine/xmake-repo" }, - version = "2022.06.14" + version = "2022.11.19" }, - ["nazarautils#c806eb3e"] = { + ["newtondynamics3#c806eb3e"] = { repo = { - commit = "5d2ec45e5605b9d8c9667c485986abbcfe914fce", - url = "https://github.com/NazaraEngine/xmake-repo" + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" }, - version = "2022.06.14" + version = "v3.14d" + }, + ["ninja#31fecfc4"] = { + repo = { + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "1.11.0" }, ["nlohmann_json#31fecfc4"] = { repo = { branch = "master", - commit = "f881bf0478fb7210197d5079522041997ab94f34", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", url = "https://github.com/xmake-io/xmake-repo.git" }, - version = "v3.10.5" + version = "v3.11.2" }, - ["nzsl#31fecfc4"] = { + ["nzsl#97361567"] = { repo = { - commit = "3ac930f44899384afafd429551e83e89f8e541a9", + commit = "5727e994c2b90e34bc01773e1d35f147640b818e", url = "https://github.com/NazaraEngine/xmake-repo" }, - version = "2022.07.02" + version = "2022.11.19" }, - ["nzsl#c806eb3e"] = { + ["openal-soft#67114504"] = { repo = { - commit = "3ac930f44899384afafd429551e83e89f8e541a9", - url = "https://github.com/NazaraEngine/xmake-repo" + branch = "master", + commit = "d52551c039b87921184893a4097eb1572455b683", + url = "https://github.com/xmake-io/xmake-repo.git" }, - version = "2022.07.27" + version = "1.22.2" }, ["ordered_map#31fecfc4"] = { repo = { branch = "master", - commit = "f881bf0478fb7210197d5079522041997ab94f34", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v1.0.0" }, + ["pkgconf#31fecfc4"] = { + repo = { + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "1.9.3" + }, + ["python 3.x#31fecfc4"] = { + repo = { + branch = "master", + commit = "71a1727013cbaf7a193154a5d2d24f0c6c568140", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "3.10.6" + }, ["sol2 v3.2.1#72267bd5"] = { repo = { branch = "master", - commit = "98cc5e3d8c1c8074d067a4e63e0d7f94146a579a", + commit = "f881bf0478fb7210197d5079522041997ab94f34", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v3.2.1" @@ -255,15 +379,23 @@ branch = "master", repo = { branch = "master", - commit = "98cc5e3d8c1c8074d067a4e63e0d7f94146a579a", + commit = "f881bf0478fb7210197d5079522041997ab94f34", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "master" }, + ["stb#31fecfc4"] = { + repo = { + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "2021.09.10" + }, ["tl_expected#31fecfc4"] = { repo = { branch = "master", - commit = "98cc5e3d8c1c8074d067a4e63e0d7f94146a579a", + commit = "f881bf0478fb7210197d5079522041997ab94f34", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v1.0.0" @@ -271,10 +403,18 @@ ["tl_function_ref#31fecfc4"] = { repo = { branch = "master", - commit = "98cc5e3d8c1c8074d067a4e63e0d7f94146a579a", + commit = "f881bf0478fb7210197d5079522041997ab94f34", url = "https://github.com/xmake-io/xmake-repo.git" }, version = "v1.0.0" + }, + ["zlib#31fecfc4"] = { + repo = { + branch = "master", + commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "v1.2.12" } } } \ No newline at end of file diff --git a/xmake.lua b/xmake.lua index 71d9f980..a8f7b337 100644 --- a/xmake.lua +++ b/xmake.lua @@ -10,13 +10,11 @@ set_project("BurgWar") set_version("0.2.0") add_repositories("nazara-engine-repo https://github.com/NazaraEngine/xmake-repo") -add_requires("nazarautils", "nzsl", { debug = is_mode("debug") }) add_requires("cxxopts", "concurrentqueue", "entt 3.10.1", "hopscotch-map", "nlohmann_json", "tl_expected", "tl_function_ref") add_requires("fmt", { configs = { header_only = false, pic = true } }) add_requires("libcurl", { optional = true }) -add_requires("nazaraengine", { alias = "nazara" }) -add_requires("nazaraengine~server", { alias = "nazaraserver", configs = { audio = false, graphics = false, platform = false, renderer = false, widget = false } }) +add_requires("nazaraengine", { configs = { debug = is_mode("debug", "asan"), shared = true } }) add_requires("sol2 v3.2.1", { verify = false, configs = { includes_lua = false } }) if is_plat("windows") then @@ -24,7 +22,7 @@ if is_plat("windows") then end add_requireconfs("fmt", "stackwalker", { debug = is_mode("debug", "asan") }) -add_requireconfs("libcurl", "nazaraengine", "nazaraengine~server", { configs = { debug = is_mode("debug", "asan"), shared = true } }) +add_requireconfs("libcurl") set_allowedmodes("asan", "debug", "releasedbg") set_allowedplats("windows", "mingw", "linux", "macosx") @@ -108,8 +106,7 @@ target("CoreLib") add_headerfiles("src/CoreLib/**.hpp", "src/CoreLib/**.inl") add_files("src/CoreLib/**.cpp") add_packages("concurrentqueue", "entt", "fmt", "hopscotch-map", "nlohmann_json", "sol2", "tl_expected", "tl_function_ref", { public = true }) - add_packages("nazaraserver") - add_packages("nazarautils", { public = true }) + add_packages("nazaraengine", { components = { "core", "network", "physics2d", "utility" }, public = true }) add_packages("libcurl", { public = true, links = {} }) if is_plat("windows") then @@ -186,7 +183,7 @@ target("ClientLib") add_headerfiles("include/(ClientLib/**.hpp)", "include/(ClientLib/**.inl)") add_headerfiles("src/ClientLib/**.hpp", "src/ClientLib/**.inl") add_files("src/ClientLib/**.cpp") - add_packages("nazarautils", "nzsl", "nazara", { public = true }) + add_packages("nazaraengine", { components = { "graphics", "platform", "renderer", "widgets" }, public = true }) target("Main") set_group("Common") @@ -199,7 +196,6 @@ target("Main") add_headerfiles("include/(Main/**.hpp)", "include/(Main/**.inl)") add_headerfiles("src/Main/**.hpp", "src/Main/**.inl") add_files("src/Main/**.cpp") - add_packages("nazaraserver") target("BurgWar") set_group("Executable") @@ -210,7 +206,6 @@ target("BurgWar") add_deps("Main", "ClientLib", "CoreLib") add_headerfiles("src/Client/**.hpp", "src/Client/**.inl") add_files("src/Client/**.cpp") - add_packages("nazara") if is_plat("windows", "mingw") then add_files("src/Client/resources.rc") @@ -231,7 +226,6 @@ target("BurgWarServer") add_deps("Main", "CoreLib") add_headerfiles("src/Server/**.hpp", "src/Server/**.inl") add_files("src/Server/**.cpp") - add_packages("nazaraserver") after_install(function (target) os.vcp("serverconfig.lua", path.join(target:installdir(), "bin")) From ca7ed724f2bc76f0b0f92bffcefc18d7bde758fd Mon Sep 17 00:00:00 2001 From: SirLynix Date: Fri, 24 Mar 2023 18:02:45 +0100 Subject: [PATCH 09/17] Update for last Nazara version --- include/ClientLib/Chatbox.hpp | 2 +- include/ClientLib/ClientEditorLayer.hpp | 12 +- include/ClientLib/ClientLayer.hpp | 6 +- include/ClientLib/ClientLayerSound.hpp | 2 +- include/ClientLib/ClientMatch.hpp | 2 +- include/ClientLib/ClientSession.hpp | 12 +- include/ClientLib/ClientSession.inl | 8 +- .../Components/ClientMatchComponent.hpp | 2 +- include/ClientLib/Console.hpp | 2 +- include/ClientLib/DownloadManager.hpp | 2 +- include/ClientLib/EscapeMenu.hpp | 2 +- include/ClientLib/Export.hpp | 2 +- include/ClientLib/HttpDownloadManager.hpp | 2 +- include/ClientLib/InputPoller.hpp | 2 +- include/ClientLib/LocalSessionManager.hpp | 2 +- include/ClientLib/OptionWidget.hpp | 2 +- include/ClientLib/PacketDownloadManager.hpp | 2 +- include/ClientLib/PlayerConfig.hpp | 4 +- include/ClientLib/Scripting/Music.hpp | 2 +- .../ClientLib/Systems/FrameCallbackSystem.hpp | 2 +- .../Systems/PostFrameCallbackSystem.hpp | 2 +- include/ClientLib/Systems/SoundSystem.hpp | 4 +- .../Systems/VisualInterpolationSystem.hpp | 2 +- include/ClientLib/VisualLayer.hpp | 2 +- include/CoreLib/AnimationManager.hpp | 4 +- include/CoreLib/AnimationManager.inl | 2 +- include/CoreLib/AnimationStore.hpp | 4 +- include/CoreLib/AssetStore.inl | 16 +- .../{BurgApp.hpp => BurgAppComponent.hpp} | 26 ++- .../{BurgApp.inl => BurgAppComponent.inl} | 17 +- .../CoreLib/Components/AnimationComponent.hpp | 15 +- .../CoreLib/Components/AnimationComponent.inl | 4 +- include/CoreLib/Components/BaseComponent.hpp | 2 +- .../CoreLib/Components/CooldownComponent.hpp | 11 +- .../CoreLib/Components/CooldownComponent.inl | 8 +- .../DestructionWatcherComponent.hpp | 2 +- .../CoreLib/Components/HealthComponent.hpp | 2 +- include/CoreLib/Components/InputComponent.hpp | 2 +- include/CoreLib/Components/MatchComponent.hpp | 2 +- .../Components/NetworkSyncComponent.hpp | 4 +- .../CoreLib/Components/ScriptComponent.hpp | 7 +- .../CoreLib/Components/ScriptComponent.inl | 6 +- .../Components/WeaponWielderComponent.hpp | 2 +- include/CoreLib/ConfigFile.hpp | 10 +- include/CoreLib/ConfigFile.inl | 2 +- include/CoreLib/EntityId.hpp | 2 +- include/CoreLib/Export.hpp | 2 +- include/CoreLib/LayerIndex.hpp | 2 +- include/CoreLib/LogSystem/LogContextPtr.hpp | 2 +- include/CoreLib/LogSystem/Logger.hpp | 12 +- include/CoreLib/LogSystem/Logger.inl | 4 +- include/CoreLib/LogSystem/MatchLogger.hpp | 4 +- include/CoreLib/LogSystem/MatchLogger.inl | 4 +- include/CoreLib/Map.hpp | 2 +- include/CoreLib/MasterServerEntry.hpp | 5 +- include/CoreLib/Match.hpp | 18 +-- include/CoreLib/Match.inl | 2 +- include/CoreLib/MatchClientSession.hpp | 7 +- include/CoreLib/MatchClientVisibility.hpp | 6 +- include/CoreLib/MatchSessions.hpp | 2 +- include/CoreLib/NetworkSessionManager.hpp | 2 +- include/CoreLib/Player.hpp | 2 +- include/CoreLib/PropertyValues.hpp | 2 +- include/CoreLib/Protocol/Packets.hpp | 2 +- include/CoreLib/Scripting/ElementEvents.hpp | 2 +- include/CoreLib/Scripting/ScriptStore.inl | 4 +- include/CoreLib/Scripting/ScriptedElement.hpp | 2 +- include/CoreLib/Scripting/ScriptedEntity.hpp | 2 +- .../CoreLib/Scripting/ScriptingContext.hpp | 12 +- .../CoreLib/Scripting/ScriptingContext.inl | 2 +- .../CoreLib/Scripting/ServerWeaponStore.hpp | 2 +- include/CoreLib/SessionBridge.hpp | 2 +- include/CoreLib/SessionManager.hpp | 2 +- include/CoreLib/SharedAppConfig.hpp | 4 +- include/CoreLib/SharedLayer.hpp | 8 +- include/CoreLib/SharedLayer.inl | 2 +- include/CoreLib/SharedMatch.hpp | 18 +-- include/CoreLib/SharedMatch.inl | 4 +- include/CoreLib/Systems/AnimationSystem.hpp | 3 +- include/CoreLib/Systems/InputSystem.hpp | 3 +- include/CoreLib/Systems/NetworkSyncSystem.hpp | 6 +- .../CoreLib/Systems/PlayerMovementSystem.hpp | 3 +- .../CoreLib/Systems/TickCallbackSystem.hpp | 3 +- include/CoreLib/Systems/WeaponSystem.hpp | 3 +- include/CoreLib/Terrain.hpp | 2 +- include/CoreLib/TerrainLayer.hpp | 2 +- include/CoreLib/TimerManager.hpp | 8 +- include/CoreLib/TimerManager.inl | 4 +- include/CoreLib/Utility/CircularBuffer.inl | 2 +- include/CoreLib/WebRequest.hpp | 2 +- include/CoreLib/WebRequestResult.hpp | 2 +- include/CoreLib/WebService.hpp | 4 +- src/Client/ClientApp.cpp | 2 +- src/Client/States/AbstractState.hpp | 2 +- src/Client/States/BackgroundState.cpp | 2 +- src/Client/States/BackgroundState.hpp | 2 +- .../States/Game/AuthenticationState.cpp | 4 +- src/Client/States/Game/CancelableState.cpp | 2 +- src/Client/States/Game/CancelableState.hpp | 2 +- src/Client/States/Game/ConnectedState.cpp | 2 +- src/Client/States/Game/ConnectedState.hpp | 2 +- .../States/Game/ConnectionLostState.cpp | 4 +- .../States/Game/ConnectionLostState.hpp | 2 +- src/Client/States/Game/ConnectionState.cpp | 4 +- src/Client/States/Game/ConnectionState.hpp | 2 +- src/Client/States/Game/GameState.cpp | 2 +- src/Client/States/Game/GameState.hpp | 2 +- .../States/Game/ResourceDownloadState.cpp | 2 +- .../States/Game/ResourceDownloadState.hpp | 2 +- src/Client/States/Game/ServerState.cpp | 2 +- src/Client/States/Game/ServerState.hpp | 2 +- src/Client/States/JoinServerState.cpp | 12 +- src/Client/States/JoinServerState.hpp | 2 +- src/Client/States/MainMenuState.cpp | 2 +- src/Client/States/MainMenuState.hpp | 2 +- src/Client/States/OptionState.hpp | 2 +- src/Client/States/ServerListState.cpp | 4 +- src/Client/States/ServerListState.hpp | 4 +- src/Client/States/StartServerState.cpp | 28 ++-- src/Client/States/StartServerState.hpp | 2 +- src/ClientLib/Chatbox.cpp | 4 +- src/ClientLib/ClientEditorApp.cpp | 2 +- src/ClientLib/ClientEditorApp.hpp | 4 +- src/ClientLib/ClientEditorLayer.cpp | 8 +- src/ClientLib/ClientLayer.cpp | 2 +- src/ClientLib/ClientLayerEntity.cpp | 2 +- src/ClientLib/ClientLayerSound.cpp | 2 +- src/ClientLib/ClientMatch.cpp | 2 +- src/ClientLib/ClientSession.cpp | 2 +- src/ClientLib/LocalSessionBridge.cpp | 8 +- src/ClientLib/OptionWidget.cpp | 6 +- src/ClientLib/PlayerConfig.cpp | 2 +- src/ClientLib/Scoreboard.cpp | 2 +- .../Scripting/ClientElementLibrary.cpp | 2 +- src/ClientLib/Scripting/ParticleRegistry.cpp | 8 +- src/ClientLib/Systems/SoundSystem.cpp | 2 +- .../Systems/VisualInterpolationSystem.cpp | 2 +- .../{BurgApp.cpp => BurgAppComponent.cpp} | 31 ++-- src/CoreLib/Components/AnimationComponent.cpp | 6 +- src/CoreLib/Components/ScriptComponent.cpp | 2 +- src/CoreLib/ConfigFile.cpp | 2 +- src/CoreLib/LogSystem/Logger.cpp | 6 +- src/CoreLib/LogSystem/StdSink.cpp | 4 +- src/CoreLib/Map.cpp | 4 +- src/CoreLib/MasterServerEntry.cpp | 12 +- src/CoreLib/Match.cpp | 35 ++-- src/CoreLib/MatchClientSession.cpp | 12 +- src/CoreLib/MatchClientVisibility.cpp | 4 +- src/CoreLib/NetworkReactor.cpp | 4 +- src/CoreLib/Player.cpp | 7 +- src/CoreLib/Scripting/ScriptingContext.cpp | 48 ++---- src/CoreLib/Scripting/ServerWeaponStore.cpp | 2 +- src/CoreLib/Scripting/SharedEntityLibrary.cpp | 2 +- .../Scripting/SharedScriptingLibrary.cpp | 6 +- src/CoreLib/Scripting/SharedWeaponLibrary.cpp | 2 +- src/CoreLib/Scripting/SharedWeaponStore.cpp | 6 +- src/CoreLib/ScriptingEnvironment.cpp | 6 +- src/CoreLib/SharedAppConfig.cpp | 2 +- src/CoreLib/SharedLayer.cpp | 6 +- src/CoreLib/SharedMatch.cpp | 32 ++-- src/CoreLib/Systems/AnimationSystem.cpp | 4 +- src/CoreLib/Systems/InputSystem.cpp | 2 +- src/CoreLib/Systems/NetworkSyncSystem.cpp | 4 +- src/CoreLib/Systems/PlayerMovementSystem.cpp | 2 +- src/CoreLib/Systems/TickCallbackSystem.cpp | 2 +- src/CoreLib/Systems/WeaponSystem.cpp | 2 +- src/CoreLib/Terrain.cpp | 2 +- src/CoreLib/TerrainLayer.cpp | 2 +- src/CoreLib/Utility/CrashHandler.cpp | 2 +- src/CoreLib/Utility/CrashHandlerWin32.cpp | 2 +- src/MapEditor/Enums.hpp | 2 +- src/MapEditor/Gizmos/PositionGizmo.hpp | 2 +- src/MapEditor/Logic/SelectionEditorMode.hpp | 2 +- src/MapEditor/Logic/TileMapEditorMode.cpp | 2 +- src/MapEditor/Widgets/EditorWindow.cpp | 6 +- src/MapEditor/Widgets/EditorWindow.hpp | 2 +- src/MapEditor/Widgets/EntityInfoDialog.hpp | 2 +- src/MapEditor/Widgets/MapCanvas.cpp | 2 +- src/MapEditor/Widgets/MapCanvas.hpp | 2 +- src/MapEditor/Widgets/NazaraCanvas.hpp | 2 +- src/MapEditor/Widgets/PlayWindow.cpp | 2 +- src/MapEditor/Widgets/PlayWindow.hpp | 2 +- src/MapEditor/Widgets/TileSelectionWidget.hpp | 2 +- src/MapEditor/Widgets/WorldCanvas.cpp | 4 +- src/MapEditor/Widgets/WorldCanvas.hpp | 2 +- .../{ServerApp.cpp => ServerAppComponent.cpp} | 52 +++--- .../{ServerApp.hpp => ServerAppComponent.hpp} | 14 +- .../{ServerApp.inl => ServerAppComponent.inl} | 2 +- src/Server/ServerAppConfig.cpp | 4 +- src/Server/ServerAppConfig.hpp | 4 +- src/Server/main.cpp | 8 +- xmake-repo/packages/n/nazaraengine/xmake.lua | 153 ------------------ xmake.lua | 3 - 193 files changed, 461 insertions(+), 667 deletions(-) rename include/CoreLib/{BurgApp.hpp => BurgAppComponent.hpp} (66%) rename include/CoreLib/{BurgApp.inl => BurgAppComponent.inl} (54%) rename src/CoreLib/{BurgApp.cpp => BurgAppComponent.cpp} (85%) rename src/Server/{ServerApp.cpp => ServerAppComponent.cpp} (67%) rename src/Server/{ServerApp.hpp => ServerAppComponent.hpp} (62%) rename src/Server/{ServerApp.inl => ServerAppComponent.inl} (79%) delete mode 100644 xmake-repo/packages/n/nazaraengine/xmake.lua diff --git a/include/ClientLib/Chatbox.hpp b/include/ClientLib/Chatbox.hpp index 3dbbeff9..8cb616da 100644 --- a/include/ClientLib/Chatbox.hpp +++ b/include/ClientLib/Chatbox.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CLIENTLIB_CHATBOX_HPP #include -#include +#include #include #include #include diff --git a/include/ClientLib/ClientEditorLayer.hpp b/include/ClientLib/ClientEditorLayer.hpp index 9e343a83..a8cfd8cd 100644 --- a/include/ClientLib/ClientEditorLayer.hpp +++ b/include/ClientLib/ClientEditorLayer.hpp @@ -10,8 +10,8 @@ #include #include #include -#include -#include +#include +#include namespace bw { @@ -23,11 +23,11 @@ namespace bw ClientEditorLayer(ClientEditorLayer&&) = delete; ~ClientEditorLayer() = default; - virtual void FrameUpdate(float elapsedTime); - virtual void PreFrameUpdate(float elapsedTime); - virtual void PostFrameUpdate(float elapsedTime); + virtual void FrameUpdate(Nz::Time elapsedTime); + virtual void PreFrameUpdate(Nz::Time elapsedTime); + virtual void PostFrameUpdate(Nz::Time elapsedTime); - void TickUpdate(float elapsedTime) override; + void TickUpdate(Nz::Time elapsedTime) override; ClientEditorLayer& operator=(const ClientEditorLayer&) = delete; ClientEditorLayer& operator=(ClientEditorLayer&&) = delete; diff --git a/include/ClientLib/ClientLayer.hpp b/include/ClientLib/ClientLayer.hpp index 171ba1b4..41ff7972 100644 --- a/include/ClientLib/ClientLayer.hpp +++ b/include/ClientLib/ClientLayer.hpp @@ -7,8 +7,8 @@ #ifndef BURGWAR_CLIENTLIB_CLIENTLAYER_HPP #define BURGWAR_CLIENTLIB_CLIENTLAYER_HPP -#include -#include +#include +#include #include #include #include @@ -51,7 +51,7 @@ namespace bw bool IsEnabled() const override; inline bool IsPredictionEnabled() const; - void PostFrameUpdate(float elapsedTime) override; + void PostFrameUpdate(Nz::Time elapsedTime) override; ClientLayerEntity& RegisterEntity(ClientLayerEntity layerEntity); ClientLayerSound& RegisterSound(ClientLayerSound layerEntity); diff --git a/include/ClientLib/ClientLayerSound.hpp b/include/ClientLib/ClientLayerSound.hpp index bb74fb91..f883a54e 100644 --- a/include/ClientLib/ClientLayerSound.hpp +++ b/include/ClientLib/ClientLayerSound.hpp @@ -44,7 +44,7 @@ namespace bw std::size_t PlaySound(const std::shared_ptr& soundBuffer, bool isLooping, bool isSpatialized); void StopSound(std::size_t soundIndex); - bool Update(float elapsedTime); + bool Update(Nz::Time elapsedTime); inline void UpdatePosition(const Nz::Vector2f& position); diff --git a/include/ClientLib/ClientMatch.hpp b/include/ClientLib/ClientMatch.hpp index 8fc8e5ea..47a23b34 100644 --- a/include/ClientLib/ClientMatch.hpp +++ b/include/ClientLib/ClientMatch.hpp @@ -107,7 +107,7 @@ namespace bw void UnregisterEntity(EntityId uniqueId); - bool Update(float elapsedTime); + bool Update(Nz::Time elapsedTime); ClientMatch& operator=(const ClientMatch&) = delete; ClientMatch& operator=(ClientMatch&&) = delete; diff --git a/include/ClientLib/ClientSession.hpp b/include/ClientLib/ClientSession.hpp index 874235d3..b52c5ad2 100644 --- a/include/ClientLib/ClientSession.hpp +++ b/include/ClientLib/ClientSession.hpp @@ -11,21 +11,21 @@ #include #include #include -#include +#include #include #include #include namespace bw { - class BurgApp; + class BurgAppComponent; class BURGWAR_CLIENTLIB_API ClientSession { friend class ClientCommandStore; public: - inline ClientSession(BurgApp& app); + inline ClientSession(BurgAppComponent& app); ClientSession(const ClientSession&) = delete; ClientSession(ClientSession&&) = delete; virtual ~ClientSession(); @@ -33,8 +33,8 @@ namespace bw bool Connect(std::shared_ptr sessionBridge); void Disconnect(); - inline BurgApp& GetApp(); - inline const BurgApp& GetApp() const; + inline BurgAppComponent& GetApp(); + inline const BurgAppComponent& GetApp() const; inline const NetworkStringStore& GetNetworkStringStore() const; inline bool IsConnected() const; @@ -95,7 +95,7 @@ namespace bw NazaraSlot(SessionBridge, OnIncomingPacket, m_onIncomingPacketSlot); std::shared_ptr m_bridge; - BurgApp& m_application; + BurgAppComponent& m_application; ClientCommandStore m_commandStore; NetworkStringStore m_stringStore; }; diff --git a/include/ClientLib/ClientSession.inl b/include/ClientLib/ClientSession.inl index d002edd3..18ee9e7d 100644 --- a/include/ClientLib/ClientSession.inl +++ b/include/ClientLib/ClientSession.inl @@ -3,23 +3,23 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include #include namespace bw { - inline ClientSession::ClientSession(BurgApp& application) : + inline ClientSession::ClientSession(BurgAppComponent& application) : m_application(application), m_commandStore(m_application.GetLogger()) { } - inline BurgApp& ClientSession::GetApp() + inline BurgAppComponent& ClientSession::GetApp() { return m_application; } - inline const BurgApp& ClientSession::GetApp() const + inline const BurgAppComponent& ClientSession::GetApp() const { return m_application; } diff --git a/include/ClientLib/Components/ClientMatchComponent.hpp b/include/ClientLib/Components/ClientMatchComponent.hpp index f6568773..dcfcfb01 100644 --- a/include/ClientLib/Components/ClientMatchComponent.hpp +++ b/include/ClientLib/Components/ClientMatchComponent.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include namespace bw { diff --git a/include/ClientLib/Console.hpp b/include/ClientLib/Console.hpp index 42618e99..a48ffc4c 100644 --- a/include/ClientLib/Console.hpp +++ b/include/ClientLib/Console.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CLIENTLIB_CONSOLE_HPP #include -#include +#include #include #include #include diff --git a/include/ClientLib/DownloadManager.hpp b/include/ClientLib/DownloadManager.hpp index 4eb882b6..bee71051 100644 --- a/include/ClientLib/DownloadManager.hpp +++ b/include/ClientLib/DownloadManager.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include diff --git a/include/ClientLib/EscapeMenu.hpp b/include/ClientLib/EscapeMenu.hpp index eaac1ef0..b37c805b 100644 --- a/include/ClientLib/EscapeMenu.hpp +++ b/include/ClientLib/EscapeMenu.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CLIENTLIB_ESCAPEMENU_HPP #include -#include +#include #include #include #include diff --git a/include/ClientLib/Export.hpp b/include/ClientLib/Export.hpp index 68866af8..6015a13d 100644 --- a/include/ClientLib/Export.hpp +++ b/include/ClientLib/Export.hpp @@ -7,7 +7,7 @@ #ifndef BURGWAR_CLIENTLIB_EXPORT_HPP #define BURGWAR_CLIENTLIB_EXPORT_HPP -#include +#include #ifdef BURGWAR_CLIENTLIB_STATIC #define BURGWAR_CLIENTLIB_API diff --git a/include/ClientLib/HttpDownloadManager.hpp b/include/ClientLib/HttpDownloadManager.hpp index 33f14558..0ececb05 100644 --- a/include/ClientLib/HttpDownloadManager.hpp +++ b/include/ClientLib/HttpDownloadManager.hpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include diff --git a/include/ClientLib/InputPoller.hpp b/include/ClientLib/InputPoller.hpp index 88548c15..66091839 100644 --- a/include/ClientLib/InputPoller.hpp +++ b/include/ClientLib/InputPoller.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include namespace bw { diff --git a/include/ClientLib/LocalSessionManager.hpp b/include/ClientLib/LocalSessionManager.hpp index 8596f42f..7b5403a6 100644 --- a/include/ClientLib/LocalSessionManager.hpp +++ b/include/ClientLib/LocalSessionManager.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include diff --git a/include/ClientLib/OptionWidget.hpp b/include/ClientLib/OptionWidget.hpp index 1a99c983..a59222c3 100644 --- a/include/ClientLib/OptionWidget.hpp +++ b/include/ClientLib/OptionWidget.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CLIENTLIB_OPTIONMENU_HPP #include -#include +#include #include #include #include diff --git a/include/ClientLib/PacketDownloadManager.hpp b/include/ClientLib/PacketDownloadManager.hpp index 81409d6d..30f0dc2f 100644 --- a/include/ClientLib/PacketDownloadManager.hpp +++ b/include/ClientLib/PacketDownloadManager.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/ClientLib/PlayerConfig.hpp b/include/ClientLib/PlayerConfig.hpp index 94476ec7..6208e4ac 100644 --- a/include/ClientLib/PlayerConfig.hpp +++ b/include/ClientLib/PlayerConfig.hpp @@ -12,12 +12,12 @@ namespace bw { - class BurgApp; + class BurgAppComponent; class BURGWAR_CLIENTLIB_API PlayerConfig : public ConfigFile { public: - PlayerConfig(BurgApp& app); + PlayerConfig(BurgAppComponent& app); ~PlayerConfig() = default; }; } diff --git a/include/ClientLib/Scripting/Music.hpp b/include/ClientLib/Scripting/Music.hpp index 0dfe8c0a..ee438324 100644 --- a/include/ClientLib/Scripting/Music.hpp +++ b/include/ClientLib/Scripting/Music.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include namespace bw { diff --git a/include/ClientLib/Systems/FrameCallbackSystem.hpp b/include/ClientLib/Systems/FrameCallbackSystem.hpp index 2f8f4cb3..0520b9d5 100644 --- a/include/ClientLib/Systems/FrameCallbackSystem.hpp +++ b/include/ClientLib/Systems/FrameCallbackSystem.hpp @@ -21,7 +21,7 @@ namespace bw FrameCallbackSystem(entt::registry& registry); ~FrameCallbackSystem() = default; - void Update(float elapsedTime); + void Update(Nz::Time elapsedTime); private: void OnScriptDestroy(entt::registry& registry, entt::entity entity); diff --git a/include/ClientLib/Systems/PostFrameCallbackSystem.hpp b/include/ClientLib/Systems/PostFrameCallbackSystem.hpp index 2f194ea2..a0136531 100644 --- a/include/ClientLib/Systems/PostFrameCallbackSystem.hpp +++ b/include/ClientLib/Systems/PostFrameCallbackSystem.hpp @@ -21,7 +21,7 @@ namespace bw PostFrameCallbackSystem(entt::registry& registry); ~PostFrameCallbackSystem() = default; - void Update(float elapsedTime); + void Update(Nz::Time elapsedTime); private: void OnScriptDestroy(entt::registry& registry, entt::entity entity); diff --git a/include/ClientLib/Systems/SoundSystem.hpp b/include/ClientLib/Systems/SoundSystem.hpp index 2334bc88..9ed242e3 100644 --- a/include/ClientLib/Systems/SoundSystem.hpp +++ b/include/ClientLib/Systems/SoundSystem.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include @@ -26,7 +26,7 @@ namespace bw SoundSystem(entt::registry& registry, ConfigFile& playerSettings); ~SoundSystem() = default; - void Update(float elapsedTime); + void Update(Nz::Time elapsedTime); static constexpr Nz::UInt32 InvalidSoundId = 0; diff --git a/include/ClientLib/Systems/VisualInterpolationSystem.hpp b/include/ClientLib/Systems/VisualInterpolationSystem.hpp index 69b8f953..c5df718a 100644 --- a/include/ClientLib/Systems/VisualInterpolationSystem.hpp +++ b/include/ClientLib/Systems/VisualInterpolationSystem.hpp @@ -18,7 +18,7 @@ namespace bw VisualInterpolationSystem(entt::registry& registry); ~VisualInterpolationSystem() = default; - void Update(float elapsedTime); + void Update(Nz::Time elapsedTime); private: entt::observer m_observer; diff --git a/include/ClientLib/VisualLayer.hpp b/include/ClientLib/VisualLayer.hpp index 9a1b4c6c..06a7eb24 100644 --- a/include/ClientLib/VisualLayer.hpp +++ b/include/ClientLib/VisualLayer.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CLIENTLIB_VISUALLAYER_HPP #include -#include +#include namespace bw { diff --git a/include/CoreLib/AnimationManager.hpp b/include/CoreLib/AnimationManager.hpp index 57769b69..19287188 100644 --- a/include/CoreLib/AnimationManager.hpp +++ b/include/CoreLib/AnimationManager.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CORELIB_ANIMATIONMANAGER_HPP #include -#include +#include #include #include @@ -25,7 +25,7 @@ namespace bw inline void PushAnimation(float duration, UpdateCallback update, FinishCallback finish); - inline void Update(float elapsedTime); + inline void Update(Nz::Time elapsedTime); private: struct Animation diff --git a/include/CoreLib/AnimationManager.inl b/include/CoreLib/AnimationManager.inl index 121c0c01..49c8fda3 100644 --- a/include/CoreLib/AnimationManager.inl +++ b/include/CoreLib/AnimationManager.inl @@ -20,7 +20,7 @@ namespace bw anim.updateCallback = std::move(update); } - inline void AnimationManager::Update(float elapsedTime) + inline void AnimationManager::Update(Nz::Time elapsedTime) { std::move(m_newAnimations.begin(), m_newAnimations.end(), std::back_inserter(m_playingAnimations)); m_newAnimations.clear(); diff --git a/include/CoreLib/AnimationStore.hpp b/include/CoreLib/AnimationStore.hpp index e744124f..18f060d3 100644 --- a/include/CoreLib/AnimationStore.hpp +++ b/include/CoreLib/AnimationStore.hpp @@ -8,8 +8,8 @@ #define BURGWAR_CORELIB_ANIMATIONSTORE_HPP #include +#include #include -#include #include #include @@ -31,7 +31,7 @@ namespace bw struct AnimationData { std::string animationName; - std::chrono::milliseconds duration; + Nz::Time duration; }; static constexpr std::size_t InvalidId = std::numeric_limits::max(); diff --git a/include/CoreLib/AssetStore.inl b/include/CoreLib/AssetStore.inl index 0c3004d5..6625bf9b 100644 --- a/include/CoreLib/AssetStore.inl +++ b/include/CoreLib/AssetStore.inl @@ -39,20 +39,10 @@ namespace bw { using T = std::decay_t; - if constexpr (std::is_same_v) + if constexpr (std::is_same_v) { - bwLog(m_logger, LogLevel::Info, "Loading asset from memory"); - return (resource = ResourceType::LoadFromMemory(arg.data, arg.size, params)) != nullptr; - } - else if constexpr (std::is_same_v) - { - bwLog(m_logger, LogLevel::Info, "Loading asset from memory"); - return (resource = ResourceType::LoadFromMemory(arg.data.data(), arg.data.size(), params)) != nullptr; - } - else if constexpr (std::is_same_v) - { - bwLog(m_logger, LogLevel::Info, "Loading asset from {}", arg.filePath.generic_u8string()); - return (resource = ResourceType::LoadFromFile(arg.filePath.generic_u8string(), params)) != nullptr; + bwLog(m_logger, LogLevel::Info, "Loading asset from {}", arg.stream->GetPath().generic_u8string()); + return (resource = ResourceType::LoadFromStream(*arg.stream, params)) != nullptr; } else if constexpr (std::is_base_of_v) { diff --git a/include/CoreLib/BurgApp.hpp b/include/CoreLib/BurgAppComponent.hpp similarity index 66% rename from include/CoreLib/BurgApp.hpp rename to include/CoreLib/BurgAppComponent.hpp index 5f7be4c2..084cbf25 100644 --- a/include/CoreLib/BurgApp.hpp +++ b/include/CoreLib/BurgAppComponent.hpp @@ -11,7 +11,8 @@ #include #include #include -#include +#include +#include #include #include #include @@ -21,20 +22,20 @@ namespace bw class ConfigFile; class Mod; - class BURGWAR_CORELIB_API BurgApp + class BURGWAR_CORELIB_API BurgAppComponent : public Nz::ApplicationComponent { public: - BurgApp(LogSide side, const ConfigFile& config); - ~BurgApp(); + BurgAppComponent(Nz::ApplicationBase& app, LogSide side, const ConfigFile& config); + ~BurgAppComponent(); - inline Nz::UInt64 GetAppTime() const; + inline Nz::Time GetAppTime() const; inline const ConfigFile& GetConfig() const; inline Logger& GetLogger(); - inline Nz::UInt64 GetLogTime() const; + inline Nz::Time GetLogTime() const; inline const tsl::hopscotch_map>& GetMods() const; inline WebService& GetWebService(); - void Update(); + void Update(Nz::Time elapsedTime) override; private: static void HandleInterruptSignal(const char* signalName); @@ -43,22 +44,19 @@ namespace bw Logger m_logger; - static BurgApp* s_application; + static BurgAppComponent* s_application; protected: void LoadMods(); - virtual void Quit() = 0; - const ConfigFile& m_config; std::optional m_webService; tsl::hopscotch_map> m_mods; - Nz::UInt64 m_appTime; - Nz::UInt64 m_lastTime; - Nz::UInt64 m_startTime; + Nz::Time m_appTime; + Nz::Time m_startTime; }; } -#include +#include #endif diff --git a/include/CoreLib/BurgApp.inl b/include/CoreLib/BurgAppComponent.inl similarity index 54% rename from include/CoreLib/BurgApp.inl rename to include/CoreLib/BurgAppComponent.inl index 311d292a..a6b49d5d 100644 --- a/include/CoreLib/BurgApp.inl +++ b/include/CoreLib/BurgAppComponent.inl @@ -2,40 +2,39 @@ // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE -#include +#include #include -#include #include #include namespace bw { - inline Nz::UInt64 BurgApp::GetAppTime() const + inline Nz::Time BurgAppComponent::GetAppTime() const { return m_appTime; } - inline const ConfigFile& BurgApp::GetConfig() const + inline const ConfigFile& BurgAppComponent::GetConfig() const { return m_config; } - inline auto BurgApp::GetLogger() -> Logger& + inline auto BurgAppComponent::GetLogger() -> Logger& { return m_logger; } - inline Nz::UInt64 BurgApp::GetLogTime() const + inline Nz::Time BurgAppComponent::GetLogTime() const { - return Nz::GetElapsedMicroseconds() - m_startTime; + return Nz::GetElapsedNanoseconds() - m_startTime; } - inline const tsl::hopscotch_map>& BurgApp::GetMods() const + inline const tsl::hopscotch_map>& BurgAppComponent::GetMods() const { return m_mods; } - inline WebService& BurgApp::GetWebService() + inline WebService& BurgAppComponent::GetWebService() { assert(m_webService); return *m_webService; diff --git a/include/CoreLib/Components/AnimationComponent.hpp b/include/CoreLib/Components/AnimationComponent.hpp index 8fd6d753..eec8ca01 100644 --- a/include/CoreLib/Components/AnimationComponent.hpp +++ b/include/CoreLib/Components/AnimationComponent.hpp @@ -9,7 +9,8 @@ #include #include -#include +#include +#include #include #include @@ -28,23 +29,23 @@ namespace bw inline std::size_t GetAnimId() const; inline const std::shared_ptr& GetAnimationStore() const; - inline Nz::UInt64 GetEndTime() const; - inline Nz::UInt64 GetStartTime() const; + inline Nz::Time GetEndTime() const; + inline Nz::Time GetStartTime() const; inline bool IsPlaying() const; - void Play(std::size_t animId, Nz::UInt64 animStartTime); + void Play(std::size_t animId, Nz::Time animStartTime); NazaraSignal(OnAnimationEnd, AnimationComponent* /*emitter*/); NazaraSignal(OnAnimationStart, AnimationComponent* /*emitter*/); private: - void Update(Nz::UInt64 now); + void Update(Nz::Time now); struct ActiveAnimation { std::size_t animId; - Nz::UInt64 endTime; - Nz::UInt64 startTime; + Nz::Time endTime; + Nz::Time startTime; }; std::optional m_playingAnimation; diff --git a/include/CoreLib/Components/AnimationComponent.inl b/include/CoreLib/Components/AnimationComponent.inl index a4787878..42a4eef6 100644 --- a/include/CoreLib/Components/AnimationComponent.inl +++ b/include/CoreLib/Components/AnimationComponent.inl @@ -31,13 +31,13 @@ namespace bw return m_animationStore; } - inline Nz::UInt64 AnimationComponent::GetEndTime() const + inline Nz::Time AnimationComponent::GetEndTime() const { assert(IsPlaying()); return m_playingAnimation->endTime; } - inline Nz::UInt64 AnimationComponent::GetStartTime() const + inline Nz::Time AnimationComponent::GetStartTime() const { assert(IsPlaying()); return m_playingAnimation->startTime; diff --git a/include/CoreLib/Components/BaseComponent.hpp b/include/CoreLib/Components/BaseComponent.hpp index 2e065147..8f4aae5c 100644 --- a/include/CoreLib/Components/BaseComponent.hpp +++ b/include/CoreLib/Components/BaseComponent.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CORELIB_COMPONENTS_BASECOMPONENT_HPP #include -#include +#include #include namespace bw diff --git a/include/CoreLib/Components/CooldownComponent.hpp b/include/CoreLib/Components/CooldownComponent.hpp index f722ffe8..80e88470 100644 --- a/include/CoreLib/Components/CooldownComponent.hpp +++ b/include/CoreLib/Components/CooldownComponent.hpp @@ -8,23 +8,24 @@ #define BURGWAR_CORELIB_COMPONENTS_COOLDOWNCOMPONENT_HPP #include +#include namespace bw { class BURGWAR_CORELIB_API CooldownComponent { public: - inline CooldownComponent(Nz::UInt32 cooldown); + inline CooldownComponent(Nz::Time cooldown); CooldownComponent(const CooldownComponent&) = default; ~CooldownComponent() = default; - inline void SetNextTriggerTime(Nz::UInt64 time); + inline void SetNextTriggerTime(Nz::Time time); - inline bool Trigger(Nz::UInt64 currentTime); + inline bool Trigger(Nz::Time currentTime); private: - Nz::UInt32 m_cooldown; - Nz::UInt64 m_nextTriggerTime; + Nz::Time m_cooldown; + Nz::Time m_nextTriggerTime; }; } diff --git a/include/CoreLib/Components/CooldownComponent.inl b/include/CoreLib/Components/CooldownComponent.inl index 348fb0ad..e5e0c7ee 100644 --- a/include/CoreLib/Components/CooldownComponent.inl +++ b/include/CoreLib/Components/CooldownComponent.inl @@ -6,18 +6,18 @@ namespace bw { - inline CooldownComponent::CooldownComponent(Nz::UInt32 cooldown) : + inline CooldownComponent::CooldownComponent(Nz::Time cooldown) : m_cooldown(cooldown), - m_nextTriggerTime(0) + m_nextTriggerTime(Nz::Time::Zero()) { } - inline void CooldownComponent::SetNextTriggerTime(Nz::UInt64 time) + inline void CooldownComponent::SetNextTriggerTime(Nz::Time time) { m_nextTriggerTime = time; } - inline bool CooldownComponent::Trigger(Nz::UInt64 currentTime) + inline bool CooldownComponent::Trigger(Nz::Time currentTime) { if (currentTime < m_nextTriggerTime) return false; diff --git a/include/CoreLib/Components/DestructionWatcherComponent.hpp b/include/CoreLib/Components/DestructionWatcherComponent.hpp index 12470f42..47df8b11 100644 --- a/include/CoreLib/Components/DestructionWatcherComponent.hpp +++ b/include/CoreLib/Components/DestructionWatcherComponent.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include namespace bw { diff --git a/include/CoreLib/Components/HealthComponent.hpp b/include/CoreLib/Components/HealthComponent.hpp index cda226ad..e464d043 100644 --- a/include/CoreLib/Components/HealthComponent.hpp +++ b/include/CoreLib/Components/HealthComponent.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include namespace bw { diff --git a/include/CoreLib/Components/InputComponent.hpp b/include/CoreLib/Components/InputComponent.hpp index 1ac99ddb..7b413842 100644 --- a/include/CoreLib/Components/InputComponent.hpp +++ b/include/CoreLib/Components/InputComponent.hpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include diff --git a/include/CoreLib/Components/MatchComponent.hpp b/include/CoreLib/Components/MatchComponent.hpp index 36b400df..a1718c36 100644 --- a/include/CoreLib/Components/MatchComponent.hpp +++ b/include/CoreLib/Components/MatchComponent.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include namespace bw { diff --git a/include/CoreLib/Components/NetworkSyncComponent.hpp b/include/CoreLib/Components/NetworkSyncComponent.hpp index c8f5915a..3af31028 100644 --- a/include/CoreLib/Components/NetworkSyncComponent.hpp +++ b/include/CoreLib/Components/NetworkSyncComponent.hpp @@ -8,8 +8,8 @@ #define BURGWAR_CORELIB_COMPONENTS_NETWORKSYNCCOMPONENT_HPP #include -#include -#include +#include +#include #include #include diff --git a/include/CoreLib/Components/ScriptComponent.hpp b/include/CoreLib/Components/ScriptComponent.hpp index e11a9e1f..3953d925 100644 --- a/include/CoreLib/Components/ScriptComponent.hpp +++ b/include/CoreLib/Components/ScriptComponent.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -52,7 +53,7 @@ namespace bw inline std::size_t RegisterCallback(ElementEvent event, sol::main_protected_function callback, bool async); inline std::size_t RegisterCallbackCustom(std::size_t eventIndex, sol::main_protected_function callback, bool async); - inline void SetNextTick(float seconds); + inline void SetNextTick(Nz::Time seconds); inline bool UnregisterCallback(ElementEvent event, std::size_t callbackId); inline bool UnregisterCallbackCustom(std::size_t eventIndex, std::size_t callbackId); @@ -66,7 +67,7 @@ namespace bw static constexpr auto in_place_delete = true; private: - inline bool CanTriggerTick(float elapsedTime); + inline bool CanTriggerTick(Nz::Time elapsedTime); std::array, ElementEventCount> m_eventCallbacks; std::vector> m_customEventCallbacks; @@ -76,7 +77,7 @@ namespace bw std::size_t m_nextCallbackId; sol::table m_entityTable; PropertyValueMap m_properties; - float m_timeBeforeTick; + Nz::Time m_timeBeforeTick; }; } diff --git a/include/CoreLib/Components/ScriptComponent.inl b/include/CoreLib/Components/ScriptComponent.inl index e3b5dc15..6cbedf58 100644 --- a/include/CoreLib/Components/ScriptComponent.inl +++ b/include/CoreLib/Components/ScriptComponent.inl @@ -231,7 +231,7 @@ namespace bw return callbackData.callbackId; } - inline void ScriptComponent::SetNextTick(float seconds) + inline void ScriptComponent::SetNextTick(Nz::Time seconds) { m_timeBeforeTick = seconds; } @@ -276,9 +276,9 @@ namespace bw m_element = std::move(element); } - inline bool ScriptComponent::CanTriggerTick(float elapsedTime) + inline bool ScriptComponent::CanTriggerTick(Nz::Time elapsedTime) { m_timeBeforeTick -= elapsedTime; - return m_timeBeforeTick < 0.f; + return m_timeBeforeTick < Nz::Time::Zero(); } } diff --git a/include/CoreLib/Components/WeaponWielderComponent.hpp b/include/CoreLib/Components/WeaponWielderComponent.hpp index b9ccc3e2..fb4c6d38 100644 --- a/include/CoreLib/Components/WeaponWielderComponent.hpp +++ b/include/CoreLib/Components/WeaponWielderComponent.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/CoreLib/ConfigFile.hpp b/include/CoreLib/ConfigFile.hpp index ca7214ca..fb2634d6 100644 --- a/include/CoreLib/ConfigFile.hpp +++ b/include/CoreLib/ConfigFile.hpp @@ -8,8 +8,8 @@ #define BURGWAR_CORELIB_CONFIGFILE_HPP #include -#include -#include +#include +#include #include #include #include @@ -21,12 +21,12 @@ namespace bw { - class BurgApp; + class BurgAppComponent; class BURGWAR_CORELIB_API ConfigFile { public: - ConfigFile(BurgApp& app); + ConfigFile(BurgAppComponent& app); ConfigFile(const ConfigFile&) = delete; ConfigFile(ConfigFile&&) noexcept = default; ~ConfigFile() = default; @@ -130,7 +130,7 @@ namespace bw std::vector m_options; std::unordered_map m_optionByName; - BurgApp& m_app; + BurgAppComponent& m_app; ConfigSection m_globalSection; }; } diff --git a/include/CoreLib/ConfigFile.inl b/include/CoreLib/ConfigFile.inl index d7a29d2f..d7b1dbbe 100644 --- a/include/CoreLib/ConfigFile.inl +++ b/include/CoreLib/ConfigFile.inl @@ -9,7 +9,7 @@ namespace bw { - inline ConfigFile::ConfigFile(BurgApp& app) : + inline ConfigFile::ConfigFile(BurgAppComponent& app) : m_app(app) { } diff --git a/include/CoreLib/EntityId.hpp b/include/CoreLib/EntityId.hpp index d4147045..e9ceaba6 100644 --- a/include/CoreLib/EntityId.hpp +++ b/include/CoreLib/EntityId.hpp @@ -7,7 +7,7 @@ #ifndef BURGWAR_CORELIB_ENTITYID_HPP #define BURGWAR_CORELIB_ENTITYID_HPP -#include +#include namespace bw { diff --git a/include/CoreLib/Export.hpp b/include/CoreLib/Export.hpp index 6eeab16c..cc843338 100644 --- a/include/CoreLib/Export.hpp +++ b/include/CoreLib/Export.hpp @@ -7,7 +7,7 @@ #ifndef BURGWAR_CORELIB_EXPORT_HPP #define BURGWAR_CORELIB_EXPORT_HPP -#include +#include #ifdef BURGWAR_CORELIB_STATIC #define BURGWAR_CORELIB_API diff --git a/include/CoreLib/LayerIndex.hpp b/include/CoreLib/LayerIndex.hpp index 88d81586..61245d14 100644 --- a/include/CoreLib/LayerIndex.hpp +++ b/include/CoreLib/LayerIndex.hpp @@ -7,7 +7,7 @@ #ifndef BURGWAR_CORELIB_LAYERINDEX_HPP #define BURGWAR_CORELIB_LAYERINDEX_HPP -#include +#include #include namespace bw diff --git a/include/CoreLib/LogSystem/LogContextPtr.hpp b/include/CoreLib/LogSystem/LogContextPtr.hpp index 49081847..b0d9213f 100644 --- a/include/CoreLib/LogSystem/LogContextPtr.hpp +++ b/include/CoreLib/LogSystem/LogContextPtr.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include namespace bw { diff --git a/include/CoreLib/LogSystem/Logger.hpp b/include/CoreLib/LogSystem/Logger.hpp index 7a0b374c..c191e2c5 100644 --- a/include/CoreLib/LogSystem/Logger.hpp +++ b/include/CoreLib/LogSystem/Logger.hpp @@ -12,8 +12,8 @@ #include #include #include -#include -#include +#include +#include #include #include #include @@ -29,7 +29,7 @@ while (false) namespace bw { - class BurgApp; + class BurgAppComponent; class LogSink; class BURGWAR_CORELIB_API Logger : public AbstractLogger @@ -38,8 +38,8 @@ namespace bw friend class LoggerProxy; public: - inline Logger(BurgApp& app, LogSide logSide); - inline Logger(BurgApp& app, LogSide logSide, const AbstractLogger& logParent); + inline Logger(BurgAppComponent& app, LogSide logSide); + inline Logger(BurgAppComponent& app, LogSide logSide, const AbstractLogger& logParent); Logger(const Logger&) = delete; Logger(Logger&&) noexcept = default; ~Logger() = default; @@ -71,7 +71,7 @@ namespace bw private: void FreeContext(LogContext* context) const; - BurgApp& m_app; + BurgAppComponent& m_app; LogLevel m_minimumLogLevel; Nz::MovablePtr m_logParent; std::vector> m_sinks; diff --git a/include/CoreLib/LogSystem/Logger.inl b/include/CoreLib/LogSystem/Logger.inl index c271b3b3..7c81891b 100644 --- a/include/CoreLib/LogSystem/Logger.inl +++ b/include/CoreLib/LogSystem/Logger.inl @@ -7,7 +7,7 @@ namespace bw { - inline Logger::Logger(BurgApp& app, LogSide logSide) : + inline Logger::Logger(BurgAppComponent& app, LogSide logSide) : AbstractLogger(logSide), m_app(app), m_minimumLogLevel(LogLevel::Debug), @@ -15,7 +15,7 @@ namespace bw { } - inline Logger::Logger(BurgApp& app, LogSide logSide, const AbstractLogger& logParent) : + inline Logger::Logger(BurgAppComponent& app, LogSide logSide, const AbstractLogger& logParent) : Logger(app, logSide) { m_logParent = &logParent; diff --git a/include/CoreLib/LogSystem/MatchLogger.hpp b/include/CoreLib/LogSystem/MatchLogger.hpp index b8bd1111..00116765 100644 --- a/include/CoreLib/LogSystem/MatchLogger.hpp +++ b/include/CoreLib/LogSystem/MatchLogger.hpp @@ -16,8 +16,8 @@ namespace bw class BURGWAR_CORELIB_API MatchLogger : public Logger { public: - inline MatchLogger(BurgApp& app, SharedMatch& sharedMatch, LogSide logSide); - inline MatchLogger(BurgApp& app, SharedMatch& sharedMatch, LogSide logSide, const AbstractLogger& logParent); + inline MatchLogger(BurgAppComponent& app, SharedMatch& sharedMatch, LogSide logSide); + inline MatchLogger(BurgAppComponent& app, SharedMatch& sharedMatch, LogSide logSide, const AbstractLogger& logParent); MatchLogger(const MatchLogger&) = delete; MatchLogger(MatchLogger&&) noexcept = default; ~MatchLogger() = default; diff --git a/include/CoreLib/LogSystem/MatchLogger.inl b/include/CoreLib/LogSystem/MatchLogger.inl index 6f84f16e..6e612eff 100644 --- a/include/CoreLib/LogSystem/MatchLogger.inl +++ b/include/CoreLib/LogSystem/MatchLogger.inl @@ -6,13 +6,13 @@ namespace bw { - inline MatchLogger::MatchLogger(BurgApp& app, SharedMatch& sharedMatch, LogSide logSide) : + inline MatchLogger::MatchLogger(BurgAppComponent& app, SharedMatch& sharedMatch, LogSide logSide) : Logger(app, logSide), m_sharedMatch(sharedMatch) { } - inline MatchLogger::MatchLogger(BurgApp& app, SharedMatch& sharedMatch, LogSide logSide, const AbstractLogger& logParent) : + inline MatchLogger::MatchLogger(BurgAppComponent& app, SharedMatch& sharedMatch, LogSide logSide, const AbstractLogger& logParent) : Logger(app, logSide, logParent), m_sharedMatch(sharedMatch) { diff --git a/include/CoreLib/Map.hpp b/include/CoreLib/Map.hpp index 1e65ec1a..aec01114 100644 --- a/include/CoreLib/Map.hpp +++ b/include/CoreLib/Map.hpp @@ -123,7 +123,7 @@ namespace bw struct Layer { - Nz::Color backgroundColor = Nz::Color::Black; + Nz::Color backgroundColor = Nz::Color::Black(); Nz::Vector2f positionAlignment = Nz::Vector2f::Unit(); std::string name = "unnamed layer"; std::vector entities; diff --git a/include/CoreLib/MasterServerEntry.hpp b/include/CoreLib/MasterServerEntry.hpp index 34009bc0..fe1d402b 100644 --- a/include/CoreLib/MasterServerEntry.hpp +++ b/include/CoreLib/MasterServerEntry.hpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -27,7 +28,7 @@ namespace bw MasterServerEntry(MasterServerEntry&&) = delete; ~MasterServerEntry() = default; - void Update(float elapsedTime); + void Update(Nz::Time elapsedTime); MasterServerEntry& operator=(const MasterServerEntry&) = delete; MasterServerEntry& operator=(MasterServerEntry&&) = delete; @@ -44,7 +45,7 @@ namespace bw std::string m_updateToken; Match& m_match; WebService m_webService; - float m_timeBeforeRefresh; + Nz::Time m_timeBeforeRefresh; }; } diff --git a/include/CoreLib/Match.hpp b/include/CoreLib/Match.hpp index 138c13c2..3e69d990 100644 --- a/include/CoreLib/Match.hpp +++ b/include/CoreLib/Match.hpp @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include #include #include @@ -34,7 +34,7 @@ namespace bw { - class BurgApp; + class BurgAppComponent; class Mod; class ServerGamemode; class ServerScriptingLibrary; @@ -58,7 +58,7 @@ namespace bw struct MatchSettings; struct ModSettings; - Match(BurgApp& app, MatchSettings matchSettings, GamemodeSettings gamemodeSettings, ModSettings modSettings); + Match(BurgAppComponent& app, MatchSettings matchSettings, GamemodeSettings gamemodeSettings, ModSettings modSettings); Match(const Match&) = delete; Match(Match&&) = delete; ~Match(); @@ -77,7 +77,7 @@ namespace bw void ForEachEntity(tl::function_ref func) override; template void ForEachPlayer(F&& func, bool onlyReady = true); - inline BurgApp& GetApp(); + inline BurgAppComponent& GetApp(); inline const std::shared_ptr& GetAssetDirectory() const; inline AssetStore& GetAssetStore(); bool GetClientAsset(const std::string& filePath, const ClientAsset** clientScriptData); @@ -122,7 +122,7 @@ namespace bw entt::handle RetrieveEntityByUniqueId(EntityId uniqueId) const override; EntityId RetrieveUniqueIdByEntity(entt::handle entity) const override; - bool Update(float elapsedTime); + bool Update(Nz::Time elapsedTime); inline void Quit(); @@ -147,11 +147,11 @@ namespace bw std::size_t maxPlayerCount; std::string name; std::string description; + Nz::Time tickDuration; Nz::UInt16 port = 0; Map map; bool sleepWhenEmpty = true; bool registerToMasterServer = true; - float tickDuration; }; struct ModSettings @@ -182,7 +182,7 @@ namespace bw Debug() = default; Nz::UdpSocket socket; - Nz::UInt64 lastBroadcastTime = 0; + Nz::Time lastBroadcastTime = Nz::Time::Zero(); }; struct Entity @@ -213,8 +213,8 @@ namespace bw tsl::hopscotch_map m_entitiesByUniqueId; Nz::Bitset<> m_freePlayerId; EntityId m_nextUniqueId; - Nz::UInt64 m_lastPingUpdate; - BurgApp& m_app; + Nz::Time m_lastPingUpdate; + BurgAppComponent& m_app; GamemodeSettings m_gamemodeSettings; Map m_map; MatchSessions m_sessions; diff --git a/include/CoreLib/Match.inl b/include/CoreLib/Match.inl index 35e120af..b0a7ee83 100644 --- a/include/CoreLib/Match.inl +++ b/include/CoreLib/Match.inl @@ -37,7 +37,7 @@ namespace bw } } - inline BurgApp& Match::GetApp() + inline BurgAppComponent& Match::GetApp() { return m_app; } diff --git a/include/CoreLib/MatchClientSession.hpp b/include/CoreLib/MatchClientSession.hpp index e798e98f..72a3dfef 100644 --- a/include/CoreLib/MatchClientSession.hpp +++ b/include/CoreLib/MatchClientSession.hpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -51,11 +52,11 @@ namespace bw void HandleIncomingPacket(Nz::NetPacket& packet); - void OnTick(float elapsedTime); + void OnTick(Nz::Time elapsedTime); template void SendPacket(const T& packet); - void Update(float elapsedTime); + void Update(Nz::Time elapsedTime); MatchClientSession& operator=(const MatchClientSession&) = delete; MatchClientSession& operator=(MatchClientSession&&) = delete; @@ -95,9 +96,9 @@ namespace bw std::unique_ptr m_visibility; //std::vector m_pendingAssetRequest; std::vector m_players; + Nz::Time m_peerInfoUpdateCounter; Nz::UInt16 m_lastInputTick; Nz::UInt32 m_ping; - float m_peerInfoUpdateCounter; }; } diff --git a/include/CoreLib/MatchClientVisibility.hpp b/include/CoreLib/MatchClientVisibility.hpp index 6930affb..e52a1c8a 100644 --- a/include/CoreLib/MatchClientVisibility.hpp +++ b/include/CoreLib/MatchClientVisibility.hpp @@ -14,9 +14,9 @@ #include #include #include -#include -#include -#include +#include +#include +#include #include #include #include diff --git a/include/CoreLib/MatchSessions.hpp b/include/CoreLib/MatchSessions.hpp index 64b7eb4e..0c4d548c 100644 --- a/include/CoreLib/MatchSessions.hpp +++ b/include/CoreLib/MatchSessions.hpp @@ -13,7 +13,7 @@ #include #include #include -#include +#include #include #include diff --git a/include/CoreLib/NetworkSessionManager.hpp b/include/CoreLib/NetworkSessionManager.hpp index 4c5f91ee..0d3194af 100644 --- a/include/CoreLib/NetworkSessionManager.hpp +++ b/include/CoreLib/NetworkSessionManager.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include namespace bw diff --git a/include/CoreLib/Player.hpp b/include/CoreLib/Player.hpp index c2f7e99b..791b85a7 100644 --- a/include/CoreLib/Player.hpp +++ b/include/CoreLib/Player.hpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/CoreLib/PropertyValues.hpp b/include/CoreLib/PropertyValues.hpp index 9737d5b3..dcfbd94b 100644 --- a/include/CoreLib/PropertyValues.hpp +++ b/include/CoreLib/PropertyValues.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/CoreLib/Protocol/Packets.hpp b/include/CoreLib/Protocol/Packets.hpp index f9cb7b77..943facf9 100644 --- a/include/CoreLib/Protocol/Packets.hpp +++ b/include/CoreLib/Protocol/Packets.hpp @@ -13,7 +13,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/CoreLib/Scripting/ElementEvents.hpp b/include/CoreLib/Scripting/ElementEvents.hpp index 1c029ef0..70fdd121 100644 --- a/include/CoreLib/Scripting/ElementEvents.hpp +++ b/include/CoreLib/Scripting/ElementEvents.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include diff --git a/include/CoreLib/Scripting/ScriptStore.inl b/include/CoreLib/Scripting/ScriptStore.inl index e32974c6..ee0ec118 100644 --- a/include/CoreLib/Scripting/ScriptStore.inl +++ b/include/CoreLib/Scripting/ScriptStore.inl @@ -7,7 +7,7 @@ #include #include #include -#include +#include #include #include #include @@ -76,7 +76,7 @@ namespace bw { directoryEntry.directory->Foreach([&](std::string_view entryName, const Nz::VirtualDirectory::Entry& entry) { - bool isDirectory = std::holds_alternative(entry) || std::holds_alternative(entry); + bool isDirectory = std::holds_alternative(entry); LoadElement(isDirectory, directoryPath / entryName); }); }; diff --git a/include/CoreLib/Scripting/ScriptedElement.hpp b/include/CoreLib/Scripting/ScriptedElement.hpp index 10ebc738..3ddb1dfc 100644 --- a/include/CoreLib/Scripting/ScriptedElement.hpp +++ b/include/CoreLib/Scripting/ScriptedElement.hpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/CoreLib/Scripting/ScriptedEntity.hpp b/include/CoreLib/Scripting/ScriptedEntity.hpp index 2515d04a..2e36de84 100644 --- a/include/CoreLib/Scripting/ScriptedEntity.hpp +++ b/include/CoreLib/Scripting/ScriptedEntity.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CORELIB_SCRIPTING_SCRIPTEDENTITY_HPP #include -#include +#include namespace bw { diff --git a/include/CoreLib/Scripting/ScriptingContext.hpp b/include/CoreLib/Scripting/ScriptingContext.hpp index 8303fa1e..060a2979 100644 --- a/include/CoreLib/Scripting/ScriptingContext.hpp +++ b/include/CoreLib/Scripting/ScriptingContext.hpp @@ -46,7 +46,7 @@ namespace bw bool LoadDirectoryOpt(const std::filesystem::path& folder); void LoadLibrary(std::shared_ptr library); - inline void Print(const std::string& str, const Nz::Color& color = Nz::Color::White); + inline void Print(const std::string& str, const Nz::Color& color = Nz::Color::White()); void ReloadLibraries(); @@ -65,16 +65,12 @@ namespace bw private: sol::thread& CreateThread(); - tl::expected LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::DataPointerEntry& entry); - std::optional LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::DataPointerEntry& entry, Async); - tl::expected LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::FileContentEntry& entry); - std::optional LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::FileContentEntry& entry, Async); - tl::expected LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::PhysicalFileEntry& entry); - std::optional LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::PhysicalFileEntry& entry, Async); + tl::expected LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::FileEntry& entry); + std::optional LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::FileEntry& entry, Async); tl::expected LoadFile(std::filesystem::path path, const std::string_view& content); std::optional LoadFile(std::filesystem::path path, const std::string_view& content, Async); void LoadDirectory(std::filesystem::path path, const Nz::VirtualDirectory::DirectoryEntry& folder); - std::string ReadFile(const std::filesystem::path& path, const Nz::VirtualDirectory::PhysicalFileEntry& entry); + std::string ReadFile(const std::filesystem::path& path, const Nz::VirtualDirectory::FileEntry& entry); std::filesystem::path m_currentFile; std::filesystem::path m_currentFolder; diff --git a/include/CoreLib/Scripting/ScriptingContext.inl b/include/CoreLib/Scripting/ScriptingContext.inl index 9f199f43..9de4afd9 100644 --- a/include/CoreLib/Scripting/ScriptingContext.inl +++ b/include/CoreLib/Scripting/ScriptingContext.inl @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/CoreLib/Scripting/ServerWeaponStore.hpp b/include/CoreLib/Scripting/ServerWeaponStore.hpp index 3e6b5ada..f0b5134d 100644 --- a/include/CoreLib/Scripting/ServerWeaponStore.hpp +++ b/include/CoreLib/Scripting/ServerWeaponStore.hpp @@ -12,7 +12,7 @@ namespace bw { - class BurgApp; + class BurgAppComponent; class TerrainLayer; class BURGWAR_CORELIB_API ServerWeaponStore : public SharedWeaponStore diff --git a/include/CoreLib/SessionBridge.hpp b/include/CoreLib/SessionBridge.hpp index 39de418b..f3f41c52 100644 --- a/include/CoreLib/SessionBridge.hpp +++ b/include/CoreLib/SessionBridge.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include namespace bw { diff --git a/include/CoreLib/SessionManager.hpp b/include/CoreLib/SessionManager.hpp index 0e1ce20e..9ece4545 100644 --- a/include/CoreLib/SessionManager.hpp +++ b/include/CoreLib/SessionManager.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include namespace bw diff --git a/include/CoreLib/SharedAppConfig.hpp b/include/CoreLib/SharedAppConfig.hpp index 98b7cd9e..9e7058b8 100644 --- a/include/CoreLib/SharedAppConfig.hpp +++ b/include/CoreLib/SharedAppConfig.hpp @@ -12,12 +12,12 @@ namespace bw { - class BurgApp; + class BurgAppComponent; class BURGWAR_CORELIB_API SharedAppConfig : public ConfigFile { public: - SharedAppConfig(BurgApp& app); + SharedAppConfig(BurgAppComponent& app); ~SharedAppConfig() = default; }; } diff --git a/include/CoreLib/SharedLayer.hpp b/include/CoreLib/SharedLayer.hpp index 5db58e3d..fefd8585 100644 --- a/include/CoreLib/SharedLayer.hpp +++ b/include/CoreLib/SharedLayer.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include @@ -33,18 +33,18 @@ namespace bw inline entt::registry& GetWorld(); inline const entt::registry& GetWorld() const; - virtual void TickUpdate(float elapsedTime); + virtual void TickUpdate(Nz::Time elapsedTime); SharedLayer& operator=(const SharedLayer&) = delete; SharedLayer& operator=(SharedLayer&&) = delete; protected: - inline Nz::SystemGraph& GetSystemGraph(); + inline Nz::EnttSystemGraph& GetSystemGraph(); private: SharedMatch& m_match; entt::registry m_registry; - Nz::SystemGraph m_systemGraph; + Nz::EnttSystemGraph m_systemGraph; LayerIndex m_layerIndex; }; } diff --git a/include/CoreLib/SharedLayer.inl b/include/CoreLib/SharedLayer.inl index 7ba889dc..381b00bb 100644 --- a/include/CoreLib/SharedLayer.inl +++ b/include/CoreLib/SharedLayer.inl @@ -41,7 +41,7 @@ namespace bw return m_registry; } - inline Nz::SystemGraph& SharedLayer::GetSystemGraph() + inline Nz::EnttSystemGraph& SharedLayer::GetSystemGraph() { return m_systemGraph; } diff --git a/include/CoreLib/SharedMatch.hpp b/include/CoreLib/SharedMatch.hpp index 7099c2fb..17547d6a 100644 --- a/include/CoreLib/SharedMatch.hpp +++ b/include/CoreLib/SharedMatch.hpp @@ -18,7 +18,7 @@ namespace bw { - class BurgApp; + class BurgAppComponent; class ScriptingContext; class SharedEntityStore; class SharedLayer; @@ -28,7 +28,7 @@ namespace bw class BURGWAR_CORELIB_API SharedMatch { public: - SharedMatch(BurgApp& app, LogSide side, std::string matchName, float tickDuration); + SharedMatch(BurgAppComponent& app, LogSide side, std::string matchName, Nz::Time tickDuration); SharedMatch(const SharedMatch&) = delete; SharedMatch(SharedMatch&&) = delete; virtual ~SharedMatch(); @@ -36,7 +36,7 @@ namespace bw virtual void ForEachEntity(tl::function_ref func) = 0; inline Nz::UInt64 GetCurrentTick() const; - inline Nz::UInt64 GetCurrentTime() const; + inline Nz::Time GetCurrentTime() const; virtual SharedEntityStore& GetEntityStore() = 0; virtual const SharedEntityStore& GetEntityStore() const = 0; inline MatchLogger& GetLogger(); @@ -50,7 +50,7 @@ namespace bw inline ScriptHandlerRegistry& GetScriptPacketHandlerRegistry(); inline const ScriptHandlerRegistry& GetScriptPacketHandlerRegistry() const; virtual std::shared_ptr GetSharedGamemode() const = 0; - inline float GetTickDuration() const; + inline Nz::Time GetTickDuration() const; inline TimerManager& GetTimerManager(); virtual SharedWeaponStore& GetWeaponStore() = 0; virtual const SharedWeaponStore& GetWeaponStore() const = 0; @@ -58,7 +58,7 @@ namespace bw virtual entt::handle RetrieveEntityByUniqueId(EntityId uniqueId) const = 0; virtual EntityId RetrieveUniqueIdByEntity(entt::handle entity) const = 0; - void Update(float elapsedTime); + void Update(Nz::Time elapsedTime); SharedMatch& operator=(const SharedMatch&) = delete; SharedMatch& operator=(SharedMatch&&) = delete; @@ -71,12 +71,10 @@ namespace bw MatchLogger m_logger; ScriptHandlerRegistry m_scriptPacketHandler; TimerManager m_timerManager; + Nz::Time m_currentTime; + Nz::Time m_tickTimer; + Nz::Time m_tickDuration; Nz::UInt64 m_currentTick; - Nz::UInt64 m_currentTime; - float m_floatingTime; - float m_maxTickTimer; - float m_tickDuration; - float m_tickTimer; }; } diff --git a/include/CoreLib/SharedMatch.inl b/include/CoreLib/SharedMatch.inl index 84cdfdd2..364ea2eb 100644 --- a/include/CoreLib/SharedMatch.inl +++ b/include/CoreLib/SharedMatch.inl @@ -12,7 +12,7 @@ namespace bw return m_currentTick; } - inline Nz::UInt64 SharedMatch::GetCurrentTime() const + inline Nz::Time SharedMatch::GetCurrentTime() const { return m_currentTime; } @@ -47,7 +47,7 @@ namespace bw return m_scriptPacketHandler; } - inline float SharedMatch::GetTickDuration() const + inline Nz::Time SharedMatch::GetTickDuration() const { return m_tickDuration; } diff --git a/include/CoreLib/Systems/AnimationSystem.hpp b/include/CoreLib/Systems/AnimationSystem.hpp index e1f4dc69..75df8c5b 100644 --- a/include/CoreLib/Systems/AnimationSystem.hpp +++ b/include/CoreLib/Systems/AnimationSystem.hpp @@ -8,6 +8,7 @@ #define BURGWAR_CLIENTLIB_SYSTEMS_ANIMATIONSYSTEM_HPP #include +#include #include #include @@ -21,7 +22,7 @@ namespace bw inline AnimationSystem(entt::registry& registry, SharedMatch& match); ~AnimationSystem() = default; - void Update(float elapsedTime); + void Update(Nz::Time elapsedTime); private: entt::registry& m_registry; diff --git a/include/CoreLib/Systems/InputSystem.hpp b/include/CoreLib/Systems/InputSystem.hpp index 6581d559..48e0271b 100644 --- a/include/CoreLib/Systems/InputSystem.hpp +++ b/include/CoreLib/Systems/InputSystem.hpp @@ -8,6 +8,7 @@ #define BURGWAR_CORELIB_SYSTEMS_INPUTSYSTEM_HPP #include +#include #include #include @@ -21,7 +22,7 @@ namespace bw inline InputSystem(entt::registry& registry); ~InputSystem() = default; - void Update(float elapsedTime); + void Update(Nz::Time elapsedTime); private: entt::registry& m_registry; diff --git a/include/CoreLib/Systems/NetworkSyncSystem.hpp b/include/CoreLib/Systems/NetworkSyncSystem.hpp index 2cbca772..cdace3dd 100644 --- a/include/CoreLib/Systems/NetworkSyncSystem.hpp +++ b/include/CoreLib/Systems/NetworkSyncSystem.hpp @@ -15,8 +15,8 @@ #include #include #include -#include -#include +#include +#include #include #include #include @@ -59,7 +59,7 @@ namespace bw inline void NotifyPhysicsUpdate(entt::entity entity); inline void NotifyScaleUpdate(entt::entity entity); - void Update(float elapsedTime); + void Update(Nz::Time elapsedTime); NetworkSyncSystem& operator=(const NetworkSyncSystem&) = delete; diff --git a/include/CoreLib/Systems/PlayerMovementSystem.hpp b/include/CoreLib/Systems/PlayerMovementSystem.hpp index d8505d12..e281937b 100644 --- a/include/CoreLib/Systems/PlayerMovementSystem.hpp +++ b/include/CoreLib/Systems/PlayerMovementSystem.hpp @@ -8,6 +8,7 @@ #define BURGWAR_CLIENTLIB_SYSTEMS_PLAYERMOVEMENT_HPP #include +#include #include #include #include @@ -22,7 +23,7 @@ namespace bw PlayerMovementSystem(entt::registry& registry); ~PlayerMovementSystem(); - void Update(float elapsedTime); + void Update(Nz::Time elapsedTime); private: void OnMovementDestroy(entt::registry& registry, entt::entity entity); diff --git a/include/CoreLib/Systems/TickCallbackSystem.hpp b/include/CoreLib/Systems/TickCallbackSystem.hpp index 8c233fad..c0114cdc 100644 --- a/include/CoreLib/Systems/TickCallbackSystem.hpp +++ b/include/CoreLib/Systems/TickCallbackSystem.hpp @@ -8,6 +8,7 @@ #define BURGWAR_CORELIB_SYSTEMS_TICKCALLBACKSYSTEM_HPP #include +#include #include #include #include @@ -22,7 +23,7 @@ namespace bw TickCallbackSystem(entt::registry& registry, SharedMatch& match); ~TickCallbackSystem() = default; - void Update(float elapsedTime); + void Update(Nz::Time elapsedTime); private: void OnScriptDestroy(entt::registry& registry, entt::entity entity); diff --git a/include/CoreLib/Systems/WeaponSystem.hpp b/include/CoreLib/Systems/WeaponSystem.hpp index 75c8d80e..cf8c791c 100644 --- a/include/CoreLib/Systems/WeaponSystem.hpp +++ b/include/CoreLib/Systems/WeaponSystem.hpp @@ -8,6 +8,7 @@ #define BURGWAR_CORELIB_SYSTEMS_WEAPONSYSTEM_HPP #include +#include #include #include @@ -21,7 +22,7 @@ namespace bw inline WeaponSystem(entt::registry& registry, SharedMatch& match); ~WeaponSystem() = default; - void Update(float elapsedTime); + void Update(Nz::Time elapsedTime); private: entt::registry& m_registry; diff --git a/include/CoreLib/Terrain.hpp b/include/CoreLib/Terrain.hpp index 859a8a2f..18f9582a 100644 --- a/include/CoreLib/Terrain.hpp +++ b/include/CoreLib/Terrain.hpp @@ -32,7 +32,7 @@ namespace bw void Reset(); - void Update(float elapsedTime); + void Update(Nz::Time elapsedTime); Terrain& operator=(const Terrain&) = delete; diff --git a/include/CoreLib/TerrainLayer.hpp b/include/CoreLib/TerrainLayer.hpp index b7e4a2c1..59dbf2f6 100644 --- a/include/CoreLib/TerrainLayer.hpp +++ b/include/CoreLib/TerrainLayer.hpp @@ -14,7 +14,7 @@ namespace bw { - class BurgApp; + class BurgAppComponent; class Match; class BURGWAR_CORELIB_API TerrainLayer : public SharedLayer diff --git a/include/CoreLib/TimerManager.hpp b/include/CoreLib/TimerManager.hpp index b7a07f2e..755bb0c4 100644 --- a/include/CoreLib/TimerManager.hpp +++ b/include/CoreLib/TimerManager.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CORELIB_TIMERMANAGER_HPP #include -#include +#include #include #include @@ -26,15 +26,15 @@ namespace bw inline void Clear(); - inline void PushCallback(Nz::UInt64 expirationTime, Callback finish); + inline void PushCallback(Nz::Time expirationTime, Callback finish); - inline void Update(Nz::UInt64 now); + inline void Update(Nz::Time now); private: struct Timer { Callback callback; - Nz::UInt64 expirationTime; + Nz::Time expirationTime; }; std::vector m_pendingTimers; diff --git a/include/CoreLib/TimerManager.inl b/include/CoreLib/TimerManager.inl index 5eef683c..bfd98144 100644 --- a/include/CoreLib/TimerManager.inl +++ b/include/CoreLib/TimerManager.inl @@ -11,7 +11,7 @@ namespace bw m_pendingTimers.clear(); } - inline void TimerManager::PushCallback(Nz::UInt64 expirationTime, Callback callback) + inline void TimerManager::PushCallback(Nz::Time expirationTime, Callback callback) { Timer& timer = m_pendingTimers.emplace_back(); timer.callback = std::move(callback); @@ -20,7 +20,7 @@ namespace bw //TODO: Insertion sort } - inline void TimerManager::Update(Nz::UInt64 now) + inline void TimerManager::Update(Nz::Time now) { // Use index instead of iterator because callback may push new timers for (std::size_t i = 0; i < m_pendingTimers.size();) diff --git a/include/CoreLib/Utility/CircularBuffer.inl b/include/CoreLib/Utility/CircularBuffer.inl index 9086919a..db99ff56 100644 --- a/include/CoreLib/Utility/CircularBuffer.inl +++ b/include/CoreLib/Utility/CircularBuffer.inl @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include #include namespace bw diff --git a/include/CoreLib/WebRequest.hpp b/include/CoreLib/WebRequest.hpp index c1fabbf8..ede8fccf 100644 --- a/include/CoreLib/WebRequest.hpp +++ b/include/CoreLib/WebRequest.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include diff --git a/include/CoreLib/WebRequestResult.hpp b/include/CoreLib/WebRequestResult.hpp index 54529a62..87c0c583 100644 --- a/include/CoreLib/WebRequestResult.hpp +++ b/include/CoreLib/WebRequestResult.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CORELIB_WEBREQUESTRESULT_HPP #include -#include +#include #include #include #include diff --git a/include/CoreLib/WebService.hpp b/include/CoreLib/WebService.hpp index 987acf18..ad2ee996 100644 --- a/include/CoreLib/WebService.hpp +++ b/include/CoreLib/WebService.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include using CURLM = void; @@ -21,7 +21,7 @@ namespace bw class BURGWAR_CORELIB_API WebService { - friend class BurgApp; + friend class BurgAppComponent; friend class WebRequest; friend class WebRequestResult; diff --git a/src/Client/ClientApp.cpp b/src/Client/ClientApp.cpp index 543824ac..0242d164 100644 --- a/src/Client/ClientApp.cpp +++ b/src/Client/ClientApp.cpp @@ -120,7 +120,7 @@ namespace bw { m_mainWindow->Display(); - BurgApp::Update(); + BurgAppComponent::Update(); m_networkReactors.Update(); diff --git a/src/Client/States/AbstractState.hpp b/src/Client/States/AbstractState.hpp index 46f7ed92..5e4cce59 100644 --- a/src/Client/States/AbstractState.hpp +++ b/src/Client/States/AbstractState.hpp @@ -34,7 +34,7 @@ namespace bw void Enter(Ndk::StateMachine& fsm) override; void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; virtual void LayoutWidgets(); diff --git a/src/Client/States/BackgroundState.cpp b/src/Client/States/BackgroundState.cpp index bd02c869..0c15b791 100644 --- a/src/Client/States/BackgroundState.cpp +++ b/src/Client/States/BackgroundState.cpp @@ -43,7 +43,7 @@ namespace bw */ } - bool BackgroundState::Update(Ndk::StateMachine& fsm, float elapsedTime) + bool BackgroundState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; diff --git a/src/Client/States/BackgroundState.hpp b/src/Client/States/BackgroundState.hpp index 2488f311..3e90faeb 100644 --- a/src/Client/States/BackgroundState.hpp +++ b/src/Client/States/BackgroundState.hpp @@ -22,7 +22,7 @@ namespace bw private: void Enter(Ndk::StateMachine& fsm) override; void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; void LayoutWidgets() override; diff --git a/src/Client/States/Game/AuthenticationState.cpp b/src/Client/States/Game/AuthenticationState.cpp index 12f5dc0f..ae859662 100644 --- a/src/Client/States/Game/AuthenticationState.cpp +++ b/src/Client/States/Game/AuthenticationState.cpp @@ -15,7 +15,7 @@ namespace bw { m_onAuthFailedSlot.Connect(m_clientSession->OnAuthFailure, [this](ClientSession*, const Packets::AuthFailure& /*data*/) { - UpdateStatus("Failed to authenticate", Nz::Color::Red); + UpdateStatus("Failed to authenticate", Nz::Color::Red()); Cancel(3.f); }); @@ -29,7 +29,7 @@ namespace bw { if (!m_authSuccessPacket) { - UpdateStatus("Protocol error", Nz::Color::Red); + UpdateStatus("Protocol error", Nz::Color::Red()); Cancel(3.f); return; } diff --git a/src/Client/States/Game/CancelableState.cpp b/src/Client/States/Game/CancelableState.cpp index 78bc5419..22ca5597 100644 --- a/src/Client/States/Game/CancelableState.cpp +++ b/src/Client/States/Game/CancelableState.cpp @@ -54,7 +54,7 @@ namespace bw m_cancelButton->SetPosition(canvasSize.x / 2.f - m_cancelButton->GetWidth() / 2.f, canvasSize.y - 10.f - m_cancelButton->GetHeight()); } - bool CancelableState::Update(Ndk::StateMachine& fsm, float elapsedTime) + bool CancelableState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) { if (!StatusState::Update(fsm, elapsedTime)) return false; diff --git a/src/Client/States/Game/CancelableState.hpp b/src/Client/States/Game/CancelableState.hpp index c7a44f32..50f429c8 100644 --- a/src/Client/States/Game/CancelableState.hpp +++ b/src/Client/States/Game/CancelableState.hpp @@ -19,7 +19,7 @@ namespace bw CancelableState(std::shared_ptr stateData, std::shared_ptr originalState); ~CancelableState() = default; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; protected: void Cancel(float delay = 0.f); diff --git a/src/Client/States/Game/ConnectedState.cpp b/src/Client/States/Game/ConnectedState.cpp index 88748aca..985a77dd 100644 --- a/src/Client/States/Game/ConnectedState.cpp +++ b/src/Client/States/Game/ConnectedState.cpp @@ -245,7 +245,7 @@ namespace bw LayoutWidgets(); } - bool ConnectedState::Update(Ndk::StateMachine& fsm, float elapsedTime) + bool ConnectedState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; diff --git a/src/Client/States/Game/ConnectedState.hpp b/src/Client/States/Game/ConnectedState.hpp index 394dd2e7..e08734de 100644 --- a/src/Client/States/Game/ConnectedState.hpp +++ b/src/Client/States/Game/ConnectedState.hpp @@ -42,7 +42,7 @@ namespace bw void PollSessionInfo(); void RefreshFlags(); void UpdateSessionInfo(); - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; std::optional m_lastSessionInfo; std::shared_ptr m_firstState; diff --git a/src/Client/States/Game/ConnectionLostState.cpp b/src/Client/States/Game/ConnectionLostState.cpp index d31575e6..ff892262 100644 --- a/src/Client/States/Game/ConnectionLostState.cpp +++ b/src/Client/States/Game/ConnectionLostState.cpp @@ -15,11 +15,11 @@ namespace bw m_timer(5.f) { Nz::LabelWidget* labelWidget = CreateWidget(); - labelWidget->UpdateText(Nz::SimpleTextDrawer::Draw("Connection lost.", 36, Nz::TextStyle_Regular, Nz::Color::Red)); + labelWidget->UpdateText(Nz::SimpleTextDrawer::Draw("Connection lost.", 36, Nz::TextStyle_Regular, Nz::Color::Red())); labelWidget->Center(); } - bool ConnectionLostState::Update(Ndk::StateMachine& fsm, float elapsedTime) + bool ConnectionLostState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; diff --git a/src/Client/States/Game/ConnectionLostState.hpp b/src/Client/States/Game/ConnectionLostState.hpp index 504476e1..96a911da 100644 --- a/src/Client/States/Game/ConnectionLostState.hpp +++ b/src/Client/States/Game/ConnectionLostState.hpp @@ -18,7 +18,7 @@ namespace bw ~ConnectionLostState() = default; private: - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; float m_timer; }; diff --git a/src/Client/States/Game/ConnectionState.cpp b/src/Client/States/Game/ConnectionState.cpp index 74c6880e..491ac21c 100644 --- a/src/Client/States/Game/ConnectionState.cpp +++ b/src/Client/States/Game/ConnectionState.cpp @@ -71,7 +71,7 @@ namespace bw { bwLog(GetStateData().app->GetLogger(), LogLevel::Error, "no more addresses available, connection failed"); - UpdateStatus("Failed to connect to server", Nz::Color::Red); + UpdateStatus("Failed to connect to server", Nz::Color::Red()); Cancel(3.f); return; } @@ -149,7 +149,7 @@ namespace bw m_timeBeforeGivingUp = 3.f; //< Should be instant } - bool ConnectionState::Update(Ndk::StateMachine& fsm, float elapsedTime) + bool ConnectionState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) { if (!CancelableState::Update(fsm, elapsedTime)) return false; diff --git a/src/Client/States/Game/ConnectionState.hpp b/src/Client/States/Game/ConnectionState.hpp index ab76b017..b149cc46 100644 --- a/src/Client/States/Game/ConnectionState.hpp +++ b/src/Client/States/Game/ConnectionState.hpp @@ -44,7 +44,7 @@ namespace bw void ProcessNextAddress(const ServerName& name); void ProcessNextAddress(const Nz::IpAddress& address); void ProcessNextAddress(LocalSessionManager* sessionManager); - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; struct ResolvingData { diff --git a/src/Client/States/Game/GameState.cpp b/src/Client/States/Game/GameState.cpp index 63aa32fc..ea1137ef 100644 --- a/src/Client/States/Game/GameState.cpp +++ b/src/Client/States/Game/GameState.cpp @@ -32,7 +32,7 @@ namespace bw m_clientSession->Disconnect(); } - bool GameState::Update(Ndk::StateMachine& fsm, float elapsedTime) + bool GameState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; diff --git a/src/Client/States/Game/GameState.hpp b/src/Client/States/Game/GameState.hpp index f0df6183..0347c3e0 100644 --- a/src/Client/States/Game/GameState.hpp +++ b/src/Client/States/Game/GameState.hpp @@ -26,7 +26,7 @@ namespace bw private: void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; std::shared_ptr m_nextState; std::shared_ptr m_clientSession; diff --git a/src/Client/States/Game/ResourceDownloadState.cpp b/src/Client/States/Game/ResourceDownloadState.cpp index 6bb3c7be..4febd5f9 100644 --- a/src/Client/States/Game/ResourceDownloadState.cpp +++ b/src/Client/States/Game/ResourceDownloadState.cpp @@ -139,7 +139,7 @@ namespace bw } } - bool ResourceDownloadState::Update(Ndk::StateMachine& fsm, float elapsedTime) + bool ResourceDownloadState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) { if (!CancelableState::Update(fsm, elapsedTime)) return false; diff --git a/src/Client/States/Game/ResourceDownloadState.hpp b/src/Client/States/Game/ResourceDownloadState.hpp index 6d375551..2b555e1d 100644 --- a/src/Client/States/Game/ResourceDownloadState.hpp +++ b/src/Client/States/Game/ResourceDownloadState.hpp @@ -41,7 +41,7 @@ namespace bw void OnCancelled() override; void RegisterFiles(const std::vector& files, const std::shared_ptr& resourceDir, const std::shared_ptr& targetDir, const std::string& cacheDir, FileMap& fileMap, bool keepInMemory); - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; using CancelableState::UpdateStatus; void UpdateStatus(); diff --git a/src/Client/States/Game/ServerState.cpp b/src/Client/States/Game/ServerState.cpp index 03599ffc..9f7f0082 100644 --- a/src/Client/States/Game/ServerState.cpp +++ b/src/Client/States/Game/ServerState.cpp @@ -32,7 +32,7 @@ namespace bw fsm.PushState(std::make_shared(GetStateDataPtr(), m_localSessionManager, m_originalState)); } - bool ServerState::Update(Ndk::StateMachine& fsm, float elapsedTime) + bool ServerState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; diff --git a/src/Client/States/Game/ServerState.hpp b/src/Client/States/Game/ServerState.hpp index f184f8ae..2f7b2e9a 100644 --- a/src/Client/States/Game/ServerState.hpp +++ b/src/Client/States/Game/ServerState.hpp @@ -28,7 +28,7 @@ namespace bw private: void Enter(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; std::optional m_match; std::shared_ptr m_originalState; diff --git a/src/Client/States/JoinServerState.cpp b/src/Client/States/JoinServerState.cpp index d7c37542..51210a58 100644 --- a/src/Client/States/JoinServerState.cpp +++ b/src/Client/States/JoinServerState.cpp @@ -38,14 +38,14 @@ namespace bw m_serverAddressArea->SetBackgroundColor(Nz::Color::White); m_serverAddressArea->Resize({ 400.f, 36.f }); m_serverAddressArea->SetMaximumWidth(400.f); - m_serverAddressArea->SetTextColor(Nz::Color::Black); + m_serverAddressArea->SetTextColor(Nz::Color::Black()); m_serverPortArea = m_serverAddressLayout->Add(); m_serverPortArea->EnableBackground(true); m_serverPortArea->SetBackgroundColor(Nz::Color::White); m_serverPortArea->Resize({ 50.f, 36.f }); m_serverPortArea->SetMaximumWidth(100.f); - m_serverPortArea->SetTextColor(Nz::Color::Black); + m_serverPortArea->SetTextColor(Nz::Color::Black()); m_serverPortArea->SetCharacterFilter([](Nz::UInt32 character) { if (character < U'0' || character > U'9') @@ -86,7 +86,7 @@ namespace bw AbstractState::Leave(fsm); } - bool JoinServerState::Update(Ndk::StateMachine& fsm, float elapsedTime) + bool JoinServerState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; @@ -109,21 +109,21 @@ namespace bw std::string serverHostname = m_serverAddressArea->GetText(); if (serverHostname.empty()) { - UpdateStatus("Error: blank server address", Nz::Color::Red); + UpdateStatus("Error: blank server address", Nz::Color::Red()); return; } Nz::String serverPort = m_serverPortArea->GetText(); if (serverPort.IsEmpty()) { - UpdateStatus("Error: blank server port", Nz::Color::Red); + UpdateStatus("Error: blank server port", Nz::Color::Red()); return; } long long rawPort; if (!serverPort.ToInteger(&rawPort) || rawPort <= 0 || rawPort > 0xFFFF) { - UpdateStatus("Error: " + serverPort + " is not a valid port", Nz::Color::Red); + UpdateStatus("Error: " + serverPort + " is not a valid port", Nz::Color::Red()); return; } diff --git a/src/Client/States/JoinServerState.hpp b/src/Client/States/JoinServerState.hpp index 4458c979..b3a13f10 100644 --- a/src/Client/States/JoinServerState.hpp +++ b/src/Client/States/JoinServerState.hpp @@ -24,7 +24,7 @@ namespace bw private: void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; void LayoutWidgets() override; diff --git a/src/Client/States/MainMenuState.cpp b/src/Client/States/MainMenuState.cpp index 7f1085fd..e2291f02 100644 --- a/src/Client/States/MainMenuState.cpp +++ b/src/Client/States/MainMenuState.cpp @@ -65,7 +65,7 @@ namespace bw }); } - bool MainMenuState::Update(Ndk::StateMachine& fsm, float elapsedTime) + bool MainMenuState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; diff --git a/src/Client/States/MainMenuState.hpp b/src/Client/States/MainMenuState.hpp index 6a896750..07c257a7 100644 --- a/src/Client/States/MainMenuState.hpp +++ b/src/Client/States/MainMenuState.hpp @@ -21,7 +21,7 @@ namespace bw ~MainMenuState() = default; private: - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; void LayoutWidgets() override; diff --git a/src/Client/States/OptionState.hpp b/src/Client/States/OptionState.hpp index 222fee10..1ae8ea76 100644 --- a/src/Client/States/OptionState.hpp +++ b/src/Client/States/OptionState.hpp @@ -24,7 +24,7 @@ namespace bw private: void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; void LayoutWidgets() override; diff --git a/src/Client/States/ServerListState.cpp b/src/Client/States/ServerListState.cpp index 43f6ce35..e465fbc2 100644 --- a/src/Client/States/ServerListState.cpp +++ b/src/Client/States/ServerListState.cpp @@ -86,7 +86,7 @@ namespace bw m_serverListWidget->Hide(); } - bool ServerListState::Update(Ndk::StateMachine& fsm, float elapsedTime) + bool ServerListState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; @@ -247,7 +247,7 @@ namespace bw m_webService->AddRequest(std::move(request)); } - void ServerListState::RefreshServers(float elapsedTime) + void ServerListState::RefreshServers(Nz::Time elapsedTime) { for (auto it = m_masterServers.begin(); it != m_masterServers.end(); ++it) { diff --git a/src/Client/States/ServerListState.hpp b/src/Client/States/ServerListState.hpp index 34161d6f..3f510810 100644 --- a/src/Client/States/ServerListState.hpp +++ b/src/Client/States/ServerListState.hpp @@ -28,7 +28,7 @@ namespace bw private: void Enter(Ndk::StateMachine& fsm) override; void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; void LayoutWidgets() override; @@ -36,7 +36,7 @@ namespace bw void OnDirectConnectionPressed(); void OnServerConnectionPressed(const std::string& masterServer, const std::string& uuid); - void RefreshServers(float elapsedTime); + void RefreshServers(Nz::Time elapsedTime); void UpdateServerList(const std::string& masterServer, const nlohmann::json& serverListDoc); struct ServerData diff --git a/src/Client/States/StartServerState.cpp b/src/Client/States/StartServerState.cpp index ca4b1e12..cd29f045 100644 --- a/src/Client/States/StartServerState.cpp +++ b/src/Client/States/StartServerState.cpp @@ -49,7 +49,7 @@ namespace bw m_gamemodeArea = gamemodeLayout->Add(); m_gamemodeArea->EnableBackground(true); m_gamemodeArea->SetBackgroundColor(Nz::Color::White); - m_gamemodeArea->SetTextColor(Nz::Color::Black); + m_gamemodeArea->SetTextColor(Nz::Color::Black()); m_gamemodeArea->SetMaximumHeight(m_gamemodeArea->GetMinimumHeight()); Ndk::BoxLayout* mapLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); @@ -60,7 +60,7 @@ namespace bw m_mapArea = mapLayout->Add(); m_mapArea->EnableBackground(true); m_mapArea->SetBackgroundColor(Nz::Color::White); - m_mapArea->SetTextColor(Nz::Color::Black); + m_mapArea->SetTextColor(Nz::Color::Black()); m_mapArea->SetMaximumHeight(m_mapArea->GetMinimumHeight()); Ndk::BoxLayout* portLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); @@ -71,7 +71,7 @@ namespace bw m_portArea = portLayout->Add(); m_portArea->EnableBackground(true); m_portArea->SetBackgroundColor(Nz::Color::White); - m_portArea->SetTextColor(Nz::Color::Black); + m_portArea->SetTextColor(Nz::Color::Black()); m_portArea->SetMaximumHeight(m_mapArea->GetMinimumHeight()); m_portArea->SetCharacterFilter([](Nz::UInt32 character) { @@ -92,7 +92,7 @@ namespace bw m_nameArea = m_nameLayout->Add(); m_nameArea->EnableBackground(true); m_nameArea->SetBackgroundColor(Nz::Color::White); - m_nameArea->SetTextColor(Nz::Color::Black); + m_nameArea->SetTextColor(Nz::Color::Black()); m_nameArea->SetMaximumHeight(m_mapArea->GetMinimumHeight()); m_descriptionLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); @@ -103,7 +103,7 @@ namespace bw m_descriptionArea = m_descriptionLayout->Add(); m_descriptionArea->EnableBackground(true); m_descriptionArea->SetBackgroundColor(Nz::Color::White); - m_descriptionArea->SetTextColor(Nz::Color::Black); + m_descriptionArea->SetTextColor(Nz::Color::Black()); m_descriptionArea->SetMaximumHeight(m_mapArea->GetMinimumHeight()); Ndk::BoxLayout* buttonLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); @@ -139,7 +139,7 @@ namespace bw m_portArea->SetText(std::to_string(playerConfig.GetIntegerValue("StartServer.Port"))); } - bool StartServerState::Update(Ndk::StateMachine& fsm, float elapsedTime) + bool StartServerState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; @@ -164,28 +164,28 @@ namespace bw std::string gamemode = m_gamemodeArea->GetText(); if (gamemode.empty()) { - UpdateStatus("Error: blank gamemode", Nz::Color::Red); + UpdateStatus("Error: blank gamemode", Nz::Color::Red()); return; } std::string map = m_mapArea->GetText(); if (map.empty()) { - UpdateStatus("Error: blank map", Nz::Color::Red); + UpdateStatus("Error: blank map", Nz::Color::Red()); return; } Nz::String serverPort = m_portArea->GetText(); if (serverPort.IsEmpty()) { - UpdateStatus("Error: blank server port", Nz::Color::Red); + UpdateStatus("Error: blank server port", Nz::Color::Red()); return; } long long rawPort; if (!serverPort.ToInteger(&rawPort) || rawPort < 0 || rawPort > 0xFFFF) { - UpdateStatus("Error: " + serverPort + " is not a valid port", Nz::Color::Red); + UpdateStatus("Error: " + serverPort + " is not a valid port", Nz::Color::Red()); return; } @@ -199,20 +199,20 @@ namespace bw serverName = m_nameArea->GetText(); if (serverName.empty()) { - UpdateStatus("Error: blank server name", Nz::Color::Red); + UpdateStatus("Error: blank server name", Nz::Color::Red()); return; } if (serverName.size() > 32) { - UpdateStatus("Error: server name is too long", Nz::Color::Red); + UpdateStatus("Error: server name is too long", Nz::Color::Red()); return; } serverDesc = m_descriptionArea->GetText(); if (serverDesc.size() > 1024) { - UpdateStatus("Error: server description is too long", Nz::Color::Red); + UpdateStatus("Error: server description is too long", Nz::Color::Red()); return; } @@ -263,7 +263,7 @@ namespace bw } catch (const std::exception& e) { - UpdateStatus("Failed to start server: " + std::string(e.what()), Nz::Color::Red); + UpdateStatus("Failed to start server: " + std::string(e.what()), Nz::Color::Red()); } } diff --git a/src/Client/States/StartServerState.hpp b/src/Client/States/StartServerState.hpp index 4c7782fd..afe17243 100644 --- a/src/Client/States/StartServerState.hpp +++ b/src/Client/States/StartServerState.hpp @@ -23,7 +23,7 @@ namespace bw private: void Enter(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; void LayoutWidgets() override; diff --git a/src/ClientLib/Chatbox.cpp b/src/ClientLib/Chatbox.cpp index 4abec867..77ad98e7 100644 --- a/src/ClientLib/Chatbox.cpp +++ b/src/ClientLib/Chatbox.cpp @@ -27,7 +27,7 @@ namespace bw m_chatBox->SetCharacterSize(22); m_chatBox->SetTextColor(Nz::Color::White); //m_chatBox->SetTextFont(chatboxFont); - m_chatBox->SetTextOutlineColor(Nz::Color::Black); + m_chatBox->SetTextOutlineColor(Nz::Color::Black()); m_chatBox->SetTextOutlineThickness(1.f); m_chatBox->SetReadOnly(true); @@ -38,7 +38,7 @@ namespace bw m_chatEnteringBox = canvas->Add(); m_chatEnteringBox->EnableBackground(true); m_chatEnteringBox->SetBackgroundColor(Nz::Color(255, 255, 255, 150)); - m_chatEnteringBox->SetTextColor(Nz::Color::Black); + m_chatEnteringBox->SetTextColor(Nz::Color::Black()); //m_chatEnteringBox->SetTextFont(chatboxFont); m_chatEnteringBox->Hide(); diff --git a/src/ClientLib/ClientEditorApp.cpp b/src/ClientLib/ClientEditorApp.cpp index 85d9d02d..8478947f 100644 --- a/src/ClientLib/ClientEditorApp.cpp +++ b/src/ClientLib/ClientEditorApp.cpp @@ -27,7 +27,7 @@ namespace bw } ClientEditorApp::ClientEditorApp(int argc, char* argv[], LogSide side, const SharedAppConfig& configFile) : - BurgApp(side, configFile), + BurgAppComponent(side, configFile), m_playerSettings(*this) { if (!m_playerSettings.LoadFromFile(PlayerSettingsFile)) diff --git a/src/ClientLib/ClientEditorApp.hpp b/src/ClientLib/ClientEditorApp.hpp index 6f53e0e4..b3505d3a 100644 --- a/src/ClientLib/ClientEditorApp.hpp +++ b/src/ClientLib/ClientEditorApp.hpp @@ -7,14 +7,14 @@ #ifndef BURGWAR_CLIENTLIB_CLIENTEDITORAPP_HPP #define BURGWAR_CLIENTLIB_CLIENTEDITORAPP_HPP -#include +#include #include namespace bw { class SharedAppConfig; - class BURGWAR_CLIENTLIB_API ClientEditorApp : public BurgApp + class BURGWAR_CLIENTLIB_API ClientEditorApp : public BurgAppComponent { public: ClientEditorApp(int argc, char* argv[], LogSide side, const SharedAppConfig& configFile); diff --git a/src/ClientLib/ClientEditorLayer.cpp b/src/ClientLib/ClientEditorLayer.cpp index 5723cd25..e027e617 100644 --- a/src/ClientLib/ClientEditorLayer.cpp +++ b/src/ClientLib/ClientEditorLayer.cpp @@ -19,7 +19,7 @@ namespace bw systemGraph.AddSystem(); } - /*void ClientEditorLayer::FrameUpdate(float elapsedTime) + /*void ClientEditorLayer::FrameUpdate(Nz::Time elapsedTime) { entt::registry& world = GetWorld(); world.ForEachSystem([](Ndk::BaseSystem& system) @@ -33,7 +33,7 @@ namespace bw world.Update(elapsedTime); } - void ClientEditorLayer::PreFrameUpdate(float elapsedTime) + void ClientEditorLayer::PreFrameUpdate(Nz::Time elapsedTime) { entt::registry& world = GetWorld(); world.ForEachSystem([](Ndk::BaseSystem& system) @@ -46,7 +46,7 @@ namespace bw world.Update(elapsedTime); } - void ClientEditorLayer::PostFrameUpdate(float elapsedTime) + void ClientEditorLayer::PostFrameUpdate(Nz::Time elapsedTime) { entt::registry& world = GetWorld(); world.ForEachSystem([](Ndk::BaseSystem& system) @@ -59,7 +59,7 @@ namespace bw world.Update(elapsedTime); } - void ClientEditorLayer::TickUpdate(float elapsedTime) + void ClientEditorLayer::TickUpdate(Nz::Time elapsedTime) { entt::registry& world = GetWorld(); world.ForEachSystem([](Ndk::BaseSystem& system) diff --git a/src/ClientLib/ClientLayer.cpp b/src/ClientLib/ClientLayer.cpp index a74a411e..d2dc1221 100644 --- a/src/ClientLib/ClientLayer.cpp +++ b/src/ClientLib/ClientLayer.cpp @@ -85,7 +85,7 @@ namespace bw return m_isEnabled; } - void ClientLayer::PostFrameUpdate(float elapsedTime) + void ClientLayer::PostFrameUpdate(Nz::Time elapsedTime) { ClientEditorLayer::PostFrameUpdate(elapsedTime); diff --git a/src/ClientLib/ClientLayerEntity.cpp b/src/ClientLib/ClientLayerEntity.cpp index 0311e76f..d2fae808 100644 --- a/src/ClientLib/ClientLayerEntity.cpp +++ b/src/ClientLib/ClientLayerEntity.cpp @@ -128,7 +128,7 @@ namespace bw /*std::shared_ptr lostHealthBar = Nz::Sprite::New(); lostHealthBar->SetMaterial(Nz::MaterialLibrary::Get("SpriteNoDepth")); lostHealthBar->SetSize(healthData.spriteWidth, 10); - lostHealthBar->SetColor(Nz::Color::Red); + lostHealthBar->SetColor(Nz::Color::Red()); lostHealthBar->SetOrigin(Nz::Vector2f(healthData.spriteWidth / 2.f, lostHealthBar->GetSize().y)); std::shared_ptr healthBar = Nz::Sprite::New(); diff --git a/src/ClientLib/ClientLayerSound.cpp b/src/ClientLib/ClientLayerSound.cpp index 0e3d9b60..35674fab 100644 --- a/src/ClientLib/ClientLayerSound.cpp +++ b/src/ClientLib/ClientLayerSound.cpp @@ -58,7 +58,7 @@ namespace bw soundEntity->StopSound(soundIndex); } - bool ClientLayerSound::Update(float elapsedTime) + bool ClientLayerSound::Update(Nz::Time elapsedTime) { bool hasActiveSounds = false; for (auto it = m_playingSounds.begin(); it != m_playingSounds.end(); ++it) diff --git a/src/ClientLib/ClientMatch.cpp b/src/ClientLib/ClientMatch.cpp index 4f77d9e1..40e18feb 100644 --- a/src/ClientLib/ClientMatch.cpp +++ b/src/ClientLib/ClientMatch.cpp @@ -497,7 +497,7 @@ namespace bw m_entitiesByUniqueId.erase(it); } - bool ClientMatch::Update(float elapsedTime) + bool ClientMatch::Update(Nz::Time elapsedTime) { if (m_isLeavingMatch) return false; diff --git a/src/ClientLib/ClientSession.cpp b/src/ClientLib/ClientSession.cpp index 1d805fd6..fbe570d3 100644 --- a/src/ClientLib/ClientSession.cpp +++ b/src/ClientLib/ClientSession.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include #include #include #include diff --git a/src/ClientLib/LocalSessionBridge.cpp b/src/ClientLib/LocalSessionBridge.cpp index a62ca00f..ea3215e2 100644 --- a/src/ClientLib/LocalSessionBridge.cpp +++ b/src/ClientLib/LocalSessionBridge.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include #include #include @@ -15,7 +15,7 @@ namespace bw m_sessionManager(sessionManager), m_isServer(isServer) { - BurgApp& app = m_sessionManager.GetOwner()->GetMatch().GetApp(); + BurgAppComponent& app = m_sessionManager.GetOwner()->GetMatch().GetApp(); m_lastReceiveTime = app.GetAppTime(); m_sessionInfo.ping = 0; @@ -42,7 +42,7 @@ namespace bw void LocalSessionBridge::HandleIncomingPacket(Nz::NetPacket& packet) { - BurgApp& app = m_sessionManager.GetOwner()->GetMatch().GetApp(); + BurgAppComponent& app = m_sessionManager.GetOwner()->GetMatch().GetApp(); m_lastReceiveTime = app.GetAppTime(); m_sessionInfo.totalByteReceived += packet.GetDataSize(); @@ -53,7 +53,7 @@ namespace bw void LocalSessionBridge::QueryInfo(std::function callback) const { - BurgApp& app = m_sessionManager.GetOwner()->GetMatch().GetApp(); + BurgAppComponent& app = m_sessionManager.GetOwner()->GetMatch().GetApp(); m_sessionInfo.timeSinceLastReceive = static_cast(app.GetAppTime() - m_lastReceiveTime); diff --git a/src/ClientLib/OptionWidget.cpp b/src/ClientLib/OptionWidget.cpp index 020ce4fc..3e2b0b88 100644 --- a/src/ClientLib/OptionWidget.cpp +++ b/src/ClientLib/OptionWidget.cpp @@ -109,7 +109,7 @@ namespace bw option.optionWidget = Add(); option.optionWidget->Resize({ 50.f, option.optionWidget->GetPreferredHeight() }); - option.optionWidget->SetTextColor(Nz::Color::Black); + option.optionWidget->SetTextColor(Nz::Color::Black()); option.optionWidget->SetCharacterFilter([](char32_t character) { @@ -143,7 +143,7 @@ namespace bw option.optionWidget = Add(); option.optionWidget->Resize({ 50.f, option.optionWidget->GetPreferredHeight() }); - option.optionWidget->SetTextColor(Nz::Color::Black); + option.optionWidget->SetTextColor(Nz::Color::Black()); option.optionWidget->SetCharacterFilter([](char32_t character) { @@ -177,7 +177,7 @@ namespace bw option.optionWidget = Add(); option.optionWidget->Resize({ 200.f, option.optionWidget->GetPreferredHeight() }); - option.optionWidget->SetTextColor(Nz::Color::Black); + option.optionWidget->SetTextColor(Nz::Color::Black()); option.onTextChangedSlot.Connect(option.optionWidget->OnTextChanged, [this, keyName = option.keyName, textArea = option.optionWidget](const Ndk::AbstractTextAreaWidget* /*textArea*/, const Nz::String& text) { diff --git a/src/ClientLib/PlayerConfig.cpp b/src/ClientLib/PlayerConfig.cpp index 532c0df7..d8090de0 100644 --- a/src/ClientLib/PlayerConfig.cpp +++ b/src/ClientLib/PlayerConfig.cpp @@ -6,7 +6,7 @@ namespace bw { - PlayerConfig::PlayerConfig(BurgApp& app) : + PlayerConfig::PlayerConfig(BurgAppComponent& app) : ConfigFile(app) { RegisterStringOption("JoinServer.Address", "localhost"); diff --git a/src/ClientLib/Scoreboard.cpp b/src/ClientLib/Scoreboard.cpp index 8405f4e4..9eea32e7 100644 --- a/src/ClientLib/Scoreboard.cpp +++ b/src/ClientLib/Scoreboard.cpp @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/ClientLib/Scripting/ClientElementLibrary.cpp b/src/ClientLib/Scripting/ClientElementLibrary.cpp index 339fee04..b965c931 100644 --- a/src/ClientLib/Scripting/ClientElementLibrary.cpp +++ b/src/ClientLib/Scripting/ClientElementLibrary.cpp @@ -186,7 +186,7 @@ namespace bw if (std::optional colorParameter = parameters.get_or>("OutlineColor", std::nullopt); colorParameter) outlineColor = colorParameter.value(); else - outlineColor = Nz::Color::Black; + outlineColor = Nz::Color::Black(); /*Nz::FontRef font; if (!fontName.empty()) diff --git a/src/ClientLib/Scripting/ParticleRegistry.cpp b/src/ClientLib/Scripting/ParticleRegistry.cpp index c63fac0e..42049b81 100644 --- a/src/ClientLib/Scripting/ParticleRegistry.cpp +++ b/src/ClientLib/Scripting/ParticleRegistry.cpp @@ -76,7 +76,7 @@ namespace bw RegisterController("life", [](const sol::table& /*parameters*/) -> Nz::ParticleControllerRef { return Nz::ParticleFunctionController::New( - [](Nz::ParticleGroup& group, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) + [](Nz::ParticleGroup& group, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::Time elapsedTime) { auto lifePtr = mapper.GetComponentPtr(Nz::ParticleComponent_Life); @@ -97,7 +97,7 @@ namespace bw Nz::Vector2f growth = parameters["size"]; return Nz::ParticleFunctionController::New( - [=](Nz::ParticleGroup& /*group*/, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) + [=](Nz::ParticleGroup& /*group*/, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::Time elapsedTime) { auto sizePtr = mapper.GetComponentPtr(Nz::ParticleComponent_Size); @@ -114,7 +114,7 @@ namespace bw if (Nz::NumberEquals(damping, 1.f)) { return Nz::ParticleFunctionController::New( - [=](Nz::ParticleGroup& /*group*/, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) + [=](Nz::ParticleGroup& /*group*/, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::Time elapsedTime) { auto posPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Position); auto velPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Velocity); @@ -127,7 +127,7 @@ namespace bw else { return Nz::ParticleFunctionController::New( - [=](Nz::ParticleGroup& /*group*/, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) + [=](Nz::ParticleGroup& /*group*/, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::Time elapsedTime) { auto posPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Position); auto velPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Velocity); diff --git a/src/ClientLib/Systems/SoundSystem.cpp b/src/ClientLib/Systems/SoundSystem.cpp index e6c4d671..80be1eb6 100644 --- a/src/ClientLib/Systems/SoundSystem.cpp +++ b/src/ClientLib/Systems/SoundSystem.cpp @@ -30,7 +30,7 @@ namespace bw m_soundEmitterDestroyConnection = m_registry.on_destroy().connect<&SoundSystem::OnSoundDestroy>(this); } - void SoundSystem::Update(float elapsedTime) + void SoundSystem::Update(Nz::Time elapsedTime) { float invElapsedTime = 1.f / elapsedTime; diff --git a/src/ClientLib/Systems/VisualInterpolationSystem.cpp b/src/ClientLib/Systems/VisualInterpolationSystem.cpp index 6e28600d..2cac207f 100644 --- a/src/ClientLib/Systems/VisualInterpolationSystem.cpp +++ b/src/ClientLib/Systems/VisualInterpolationSystem.cpp @@ -18,7 +18,7 @@ namespace bw m_observer.connect(m_registry, entt::collector.group()); } - void VisualInterpolationSystem::Update(float elapsedTime) + void VisualInterpolationSystem::Update(Nz::Time elapsedTime) { m_observer.each([&](entt::entity entity) { diff --git a/src/CoreLib/BurgApp.cpp b/src/CoreLib/BurgAppComponent.cpp similarity index 85% rename from src/CoreLib/BurgApp.cpp rename to src/CoreLib/BurgAppComponent.cpp index db57aaf9..17f071a6 100644 --- a/src/CoreLib/BurgApp.cpp +++ b/src/CoreLib/BurgAppComponent.cpp @@ -2,7 +2,8 @@ // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE -#include +#include +#include #include #include #include @@ -26,7 +27,6 @@ #include #include #include -#include #include #include @@ -48,12 +48,12 @@ namespace bw { - BurgApp::BurgApp(LogSide side, const ConfigFile& config) : + BurgAppComponent::BurgAppComponent(Nz::ApplicationBase& app, LogSide side, const ConfigFile& config) : + ApplicationComponent(app), m_logger(*this, side), m_config(config), - m_appTime(0), - m_lastTime(Nz::GetElapsedMicroseconds()), - m_startTime(m_lastTime) + m_appTime(Nz::Time::Zero()), + m_startTime(Nz::GetElapsedNanoseconds()) { assert(!s_application); s_application = this; @@ -73,7 +73,7 @@ namespace bw bwLog(GetLogger(), LogLevel::Error, "failed to initialize web services ({0}), some functionalities will not work", error); } - BurgApp::~BurgApp() + BurgAppComponent::~BurgAppComponent() { m_webService.reset(); WebService::Uninitialize(); @@ -82,26 +82,23 @@ namespace bw s_application = nullptr; } - void BurgApp::Update() + void BurgAppComponent::Update(Nz::Time elapsedTime) { - Nz::UInt64 now = Nz::GetElapsedMicroseconds(); - Nz::UInt64 elapsedTime = now - m_lastTime; - m_appTime += elapsedTime / 1000; - m_lastTime = now; + m_appTime += elapsedTime; if (m_webService) m_webService->Poll(); } - void BurgApp::HandleInterruptSignal(const char* signalName) + void BurgAppComponent::HandleInterruptSignal(const char* signalName) { assert(s_application); bwLog(s_application->GetLogger(), LogLevel::Info, "received interruption signal {0}, exiting...", signalName); - s_application->Quit(); + s_application->GetApp().Quit(); } - void BurgApp::InstallInterruptHandlers() + void BurgAppComponent::InstallInterruptHandlers() { bool succeeded = false; @@ -144,7 +141,7 @@ namespace bw bwLog(GetLogger(), LogLevel::Error, "failed to install interruption signal handlers"); } - void BurgApp::LoadMods() + void BurgAppComponent::LoadMods() { const std::string& modDir = m_config.GetStringValue("Resources.ModDirectory"); if (modDir.empty()) @@ -158,5 +155,5 @@ namespace bw } } - BurgApp* BurgApp::s_application = nullptr; + BurgAppComponent* BurgAppComponent::s_application = nullptr; } diff --git a/src/CoreLib/Components/AnimationComponent.cpp b/src/CoreLib/Components/AnimationComponent.cpp index 3d0c56fd..27f91c69 100644 --- a/src/CoreLib/Components/AnimationComponent.cpp +++ b/src/CoreLib/Components/AnimationComponent.cpp @@ -7,19 +7,19 @@ namespace bw { - void AnimationComponent::Play(std::size_t animId, Nz::UInt64 animStartTime) + void AnimationComponent::Play(std::size_t animId, Nz::Time animStartTime) { const auto& animData = m_animationStore->GetAnimation(animId); auto& playingAnim = m_playingAnimation.emplace(); playingAnim.animId = animId; - playingAnim.endTime = animStartTime + animData.duration.count(); + playingAnim.endTime = animStartTime + animData.duration; playingAnim.startTime = animStartTime; OnAnimationStart(this); } - void AnimationComponent::Update(Nz::UInt64 now) + void AnimationComponent::Update(Nz::Time now) { if (!IsPlaying()) return; diff --git a/src/CoreLib/Components/ScriptComponent.cpp b/src/CoreLib/Components/ScriptComponent.cpp index c4460b3f..fa023441 100644 --- a/src/CoreLib/Components/ScriptComponent.cpp +++ b/src/CoreLib/Components/ScriptComponent.cpp @@ -14,7 +14,7 @@ namespace bw m_nextCallbackId(m_element->nextCallbackId), m_entityTable(std::move(entityTable)), m_properties(std::move(properties)), - m_timeBeforeTick(0.f) + m_timeBeforeTick(Nz::Time::Zero()) { m_logger = std::make_unique(entt::null, logger); } diff --git a/src/CoreLib/ConfigFile.cpp b/src/CoreLib/ConfigFile.cpp index 707c2788..bd861906 100644 --- a/src/CoreLib/ConfigFile.cpp +++ b/src/CoreLib/ConfigFile.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include #include #include #include diff --git a/src/CoreLib/LogSystem/Logger.cpp b/src/CoreLib/LogSystem/Logger.cpp index b6303f50..306fca73 100644 --- a/src/CoreLib/LogSystem/Logger.cpp +++ b/src/CoreLib/LogSystem/Logger.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include #include #include #include @@ -44,7 +44,7 @@ namespace bw void Logger::InitializeContext(LogContext& context) const { - context.elapsedTime = m_app.GetLogTime() / 1'000'000.f; + context.elapsedTime = m_app.GetLogTime().AsSeconds(); context.side = GetSide(); } @@ -66,7 +66,7 @@ namespace bw #else // libstdc++ doesn't support std::to_chars for floating-point values :( - auto TimePart = [](float elapsedTime) -> std::string + auto TimePart = [](Nz::Time elapsedTime) -> std::string { std::stringstream ss; ss.setf(std::ios::fixed, std::ios::floatfield); diff --git a/src/CoreLib/LogSystem/StdSink.cpp b/src/CoreLib/LogSystem/StdSink.cpp index 1ed4cc2b..e32404d6 100644 --- a/src/CoreLib/LogSystem/StdSink.cpp +++ b/src/CoreLib/LogSystem/StdSink.cpp @@ -4,8 +4,8 @@ #include #include -#include -#include +#include +#include #include #include #include diff --git a/src/CoreLib/Map.cpp b/src/CoreLib/Map.cpp index 7219fba8..50d7de6a 100644 --- a/src/CoreLib/Map.cpp +++ b/src/CoreLib/Map.cpp @@ -6,7 +6,7 @@ #include #include #include -#include +#include #include #include #include @@ -356,7 +356,7 @@ namespace bw for (auto&& entry : mapJson["layers"]) { Layer& layer = layers.emplace_back(); - layer.backgroundColor = entry.value("backgroundColor", Nz::Color::Black); + layer.backgroundColor = entry.value("backgroundColor", Nz::Color::Black()); layer.name = entry.value("name", ""); for (auto&& entityInfo : entry["entities"]) diff --git a/src/CoreLib/MasterServerEntry.cpp b/src/CoreLib/MasterServerEntry.cpp index ebb28616..e129348e 100644 --- a/src/CoreLib/MasterServerEntry.cpp +++ b/src/CoreLib/MasterServerEntry.cpp @@ -24,12 +24,12 @@ namespace bw { } - void MasterServerEntry::Update(float elapsedTime) + void MasterServerEntry::Update(Nz::Time elapsedTime) { m_webService.Poll(); m_timeBeforeRefresh -= elapsedTime; - if (m_timeBeforeRefresh >= 0.f) + if (m_timeBeforeRefresh >= Nz::Time::Zero()) return; if (!m_updateToken.empty()) @@ -134,7 +134,7 @@ namespace bw bwLog(m_match.GetLogger(), LogLevel::Info, (refresh) ? "successfully refreshed server to {0}" : "successfully registered server to {0}", m_masterServerURL); m_updateToken = std::move(updateToken); - m_timeBeforeRefresh = 30.f; + m_timeBeforeRefresh = Nz::Time::Seconds(30.f); break; } @@ -144,7 +144,7 @@ namespace bw { bwLog(m_match.GetLogger(), LogLevel::Warning, "master server {0} rejected token, retrying to register server...", m_masterServerURL); m_updateToken.clear(); - m_timeBeforeRefresh = 1.f; + m_timeBeforeRefresh = Nz::Time::Seconds(1.f); break; } else @@ -172,7 +172,7 @@ namespace bw request->SetJSonContent(serverData.dump()); m_webService.AddRequest(std::move(request)); - m_timeBeforeRefresh = 15.f; + m_timeBeforeRefresh = Nz::Time::Seconds(15.f); } void MasterServerEntry::Register() @@ -187,6 +187,6 @@ namespace bw request->SetJSonContent(BuildServerInfo().dump()); m_webService.AddRequest(std::move(request)); - m_timeBeforeRefresh = 15.f; + m_timeBeforeRefresh = Nz::Time::Seconds(15.f); } } diff --git a/src/CoreLib/Match.cpp b/src/CoreLib/Match.cpp index ae001f0e..97c77360 100644 --- a/src/CoreLib/Match.cpp +++ b/src/CoreLib/Match.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include #include #include #include @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -31,11 +32,11 @@ namespace bw { - Match::Match(BurgApp& app, MatchSettings matchSettings, GamemodeSettings gamemodeSettings, ModSettings modSettings) : + Match::Match(BurgAppComponent& app, MatchSettings matchSettings, GamemodeSettings gamemodeSettings, ModSettings modSettings) : SharedMatch(app, LogSide::Server, matchSettings.name, matchSettings.tickDuration), m_maxPlayerCount(matchSettings.maxPlayerCount), m_nextUniqueId(matchSettings.map.GetFreeUniqueId()), - m_lastPingUpdate(0), + m_lastPingUpdate(Nz::Time::Zero()), m_app(app), m_gamemodeSettings(std::move(gamemodeSettings)), m_map(std::move(matchSettings.map)), @@ -278,10 +279,12 @@ namespace bw bool found = m_assetDirectory->GetEntry(assetPath, [&](const Nz::VirtualDirectory::Entry& entry) { - if (!std::holds_alternative(entry)) + if (!std::holds_alternative(entry)) throw std::runtime_error(assetPath + " is not a file"); - const std::filesystem::path& filepath = std::get(entry).filePath; + std::filesystem::path filepath = std::get(entry).stream->GetPath(); + if (filepath.empty()) + throw std::runtime_error(assetPath + " is not a file"); Nz::UInt64 assetSize = std::filesystem::file_size(filepath); Nz::ByteArray assetHash = Nz::File::ComputeHash(Nz::HashType::SHA1, filepath.generic_u8string()); @@ -353,11 +356,11 @@ namespace bw { const std::string& assetDirectory = m_app.GetConfig().GetStringValue("Resources.AssetDirectory"); - m_assetDirectory = std::make_shared(assetDirectory); + m_assetDirectory = std::make_shared(std::make_shared(assetDirectory)); for (const auto& modPtr : m_enabledMods) { for (const auto& [assetPath, physicalPath] : modPtr->GetAssets()) - m_assetDirectory->StoreFile(assetPath, physicalPath); + m_assetDirectory->StoreFile(assetPath, std::make_shared(physicalPath, Nz::OpenMode::ReadOnly | Nz::OpenMode::Defer)); } if (!m_assetStore) @@ -425,15 +428,15 @@ namespace bw const std::string& scriptFolder = m_app.GetConfig().GetStringValue("Resources.ScriptDirectory"); - m_scriptDirectory = std::make_shared(scriptFolder); + m_scriptDirectory = std::make_shared(std::make_shared(scriptFolder)); for (const auto& modPtr : m_enabledMods) { for (const auto& [scriptPath, physicalPath] : modPtr->GetScripts()) - m_scriptDirectory->StoreFile(scriptPath, physicalPath); + m_scriptDirectory->StoreFile(scriptPath, std::make_shared(physicalPath, Nz::OpenMode::ReadOnly | Nz::OpenMode::Defer)); } for (const auto& mapScript : m_map.GetScripts()) - m_scriptDirectory->StoreFile(mapScript.filepath, mapScript.content); + m_scriptDirectory->StoreFile(mapScript.filepath, mapScript.content.data(), mapScript.content.size()); if (!m_scriptingContext) { @@ -638,7 +641,7 @@ namespace bw return matchComponent->GetUniqueId(); } - bool Match::Update(float elapsedTime) + bool Match::Update(Nz::Time elapsedTime) { m_sessions.Poll(); @@ -652,15 +655,15 @@ namespace bw SharedMatch::Update(elapsedTime); - Nz::UInt64 appTime = m_app.GetAppTime(); - if (appTime - m_lastPingUpdate > 1000) + Nz::Time appTime = m_app.GetAppTime(); + if (appTime - m_lastPingUpdate > Nz::Time::Second()) { SendPingUpdate(); m_lastPingUpdate = appTime; } - if (m_debug && appTime - m_debug->lastBroadcastTime > 1000 / 60) + if (m_debug && appTime - m_debug->lastBroadcastTime > Nz::Time::TickDuration(60)) { m_debug->lastBroadcastTime = m_app.GetAppTime(); @@ -736,7 +739,7 @@ namespace bw const Map& mapData = m_terrain->GetMap(); m_matchData.gamemode = m_gamemodeSettings.name; - m_matchData.tickDuration = GetTickDuration(); + m_matchData.tickDuration = GetTickDuration().AsSeconds(); m_matchData.layers.clear(); m_matchData.layers.reserve(mapData.GetLayerCount()); @@ -830,7 +833,7 @@ namespace bw void Match::OnTick(bool lastTick) { - float elapsedTime = GetTickDuration(); + Nz::Time elapsedTime = GetTickDuration(); m_sessions.ForEachSession([&](MatchClientSession& session) { diff --git a/src/CoreLib/MatchClientSession.cpp b/src/CoreLib/MatchClientSession.cpp index 167abf92..deed9128 100644 --- a/src/CoreLib/MatchClientSession.cpp +++ b/src/CoreLib/MatchClientSession.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include #include #include #include @@ -30,7 +30,7 @@ namespace bw m_commandStore(commandStore), m_bridge(std::move(bridge)), m_ping(0), - m_peerInfoUpdateCounter(0.f) + m_peerInfoUpdateCounter(Nz::Time::Zero()) { m_visibility = std::make_unique(match, *this); m_bridge->OnIncomingPacket.Connect([this](Nz::NetPacket& packet) @@ -57,7 +57,7 @@ namespace bw m_commandStore.UnserializePacket(*this, packet); } - void MatchClientSession::OnTick(float /*elapsedTime*/) + void MatchClientSession::OnTick(Nz::Time /*elapsedTime*/) { if (!m_queuedInputs.IsEmpty()) { @@ -77,14 +77,14 @@ namespace bw bwLog(m_match.GetLogger(), LogLevel::Warning, "Player session #{} has no input for this tick", m_sessionId);*/ } - void MatchClientSession::Update(float elapsedTime) + void MatchClientSession::Update(Nz::Time elapsedTime) { m_visibility->Update(); m_peerInfoUpdateCounter += elapsedTime; - if (m_peerInfoUpdateCounter >= 1.f) + if (m_peerInfoUpdateCounter >= Nz::Time::Second()) { - m_peerInfoUpdateCounter = 0.f; + m_peerInfoUpdateCounter = Nz::Time::Zero(); m_bridge->QueryInfo([clientSession = CreateHandle()](const SessionBridge::SessionInfo& info) { diff --git a/src/CoreLib/MatchClientVisibility.cpp b/src/CoreLib/MatchClientVisibility.cpp index d59c5b04..707ba6cf 100644 --- a/src/CoreLib/MatchClientVisibility.cpp +++ b/src/CoreLib/MatchClientVisibility.cpp @@ -6,8 +6,8 @@ #include #include #include -#include -#include +#include +#include #include #include #include diff --git a/src/CoreLib/NetworkReactor.cpp b/src/CoreLib/NetworkReactor.cpp index 6578a060..e3f93a3d 100644 --- a/src/CoreLib/NetworkReactor.cpp +++ b/src/CoreLib/NetworkReactor.cpp @@ -161,8 +161,8 @@ namespace bw } // Use a timeout to prevent hanging on silent peers - Nz::Clock c; - while (c.GetMilliseconds() < 1000) + Nz::MillisecondClock c; + while (c.GetElapsedTime() < Nz::Time::Milliseconds(1000)) { Nz::ENetEvent event; if (m_host.Service(&event, 1) > 0) diff --git a/src/CoreLib/Player.cpp b/src/CoreLib/Player.cpp index 320a1ab0..f2aaed6e 100644 --- a/src/CoreLib/Player.cpp +++ b/src/CoreLib/Player.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include #include #include #include @@ -23,7 +23,8 @@ #include #include #include -#include +#include +#include #include namespace bw @@ -57,7 +58,7 @@ namespace bw { const std::string& scriptFolder = m_match.GetApp().GetConfig().GetStringValue("Resources.ScriptDirectory"); - m_scriptingEnvironment.emplace(m_match.GetLogger(), m_match.GetScriptingLibrary(), std::make_shared(scriptFolder)); + m_scriptingEnvironment.emplace(m_match.GetLogger(), m_match.GetScriptingLibrary(), std::make_shared(std::make_shared(scriptFolder))); m_scriptingEnvironment->SetOutputCallback([ply = CreateHandle()](const std::string& text, Nz::Color color) { if (!ply) diff --git a/src/CoreLib/Scripting/ScriptingContext.cpp b/src/CoreLib/Scripting/ScriptingContext.cpp index 49b1e5ab..6e55ac74 100644 --- a/src/CoreLib/Scripting/ScriptingContext.cpp +++ b/src/CoreLib/Scripting/ScriptingContext.cpp @@ -6,7 +6,7 @@ #include #include #include -#include +#include #include #include @@ -43,7 +43,7 @@ namespace bw { using T = std::decay_t; - if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) + if constexpr (std::is_same_v) return LoadFile(file, arg); else if constexpr (std::is_base_of_v) return tl::unexpected(file.generic_u8string() + " is a directory, expected a file"); @@ -78,7 +78,7 @@ namespace bw { using T = std::decay_t; - if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) + if constexpr (std::is_same_v) return LoadFile(file, arg, Async{}); else if constexpr (std::is_base_of_v) { @@ -108,7 +108,7 @@ namespace bw { using T = std::decay_t; - if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) + if constexpr (std::is_same_v) bwLog(m_logger, LogLevel::Error, "{0} is a file, expected a directory", folder.generic_u8string()); else if constexpr (std::is_base_of_v) LoadDirectory(folder, arg); @@ -135,7 +135,7 @@ namespace bw { using T = std::decay_t; - if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) + if constexpr (std::is_same_v) bwLog(m_logger, LogLevel::Error, "{0} is a file, expected a directory", folder.generic_u8string()); else if constexpr (std::is_base_of_v) LoadDirectory(folder, arg); @@ -218,27 +218,7 @@ namespace bw return (!m_availableThreads.empty()) ? PopThread() : AllocateThread(); } - tl::expected ScriptingContext::LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::DataPointerEntry& entry) - { - return LoadFile(std::move(path), std::string_view(reinterpret_cast(entry.data), entry.size)); - } - - auto ScriptingContext::LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::DataPointerEntry& entry, Async) -> std::optional - { - return LoadFile(std::move(path), std::string_view(reinterpret_cast(entry.data), entry.size), Async{}); - } - - tl::expected ScriptingContext::LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::FileContentEntry& entry) - { - return LoadFile(std::move(path), std::string_view(reinterpret_cast(entry.data.data()), entry.data.size())); - } - - auto ScriptingContext::LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::FileContentEntry& entry, Async) -> std::optional - { - return LoadFile(std::move(path), std::string_view(reinterpret_cast(entry.data.data()), entry.data.size()), Async{}); - } - - tl::expected ScriptingContext::LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::PhysicalFileEntry& entry) + tl::expected ScriptingContext::LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::FileEntry& entry) { std::string fileContent = ReadFile(path, entry); if (fileContent.empty()) @@ -247,7 +227,7 @@ namespace bw return LoadFile(std::move(path), std::string_view(fileContent)); } - auto ScriptingContext::LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::PhysicalFileEntry& entry, Async) -> std::optional + auto ScriptingContext::LoadFile(std::filesystem::path path, const Nz::VirtualDirectory::FileEntry& entry, Async) -> std::optional { std::string fileContent = ReadFile(path, entry); if (fileContent.empty()) @@ -308,7 +288,7 @@ namespace bw { using T = std::decay_t; - if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) + if constexpr (std::is_same_v) return LoadFile(entryPath, arg); else if constexpr (std::is_base_of_v) { @@ -325,17 +305,17 @@ namespace bw }); } - std::string ScriptingContext::ReadFile(const std::filesystem::path& path, const Nz::VirtualDirectory::PhysicalFileEntry& entry) + std::string ScriptingContext::ReadFile(const std::filesystem::path& path, const Nz::VirtualDirectory::FileEntry& entry) { - Nz::File file(entry.filePath.generic_u8string()); - if (!file.Open(Nz::OpenMode::ReadOnly)) + Nz::UInt64 fileSize = entry.stream->GetSize(); + if (fileSize == 0) { - bwLog(m_logger, LogLevel::Error, "Failed to load {0}: failed to open file", path.generic_u8string()); + bwLog(m_logger, LogLevel::Error, "Failed to load {0}: unhandled streaming", path.generic_u8string()); return {}; } - std::string content(file.GetSize(), '\0'); - if (file.Read(content.data(), content.size()) != content.size()) + std::string content(fileSize, '\0'); + if (entry.stream->Read(&content[0], fileSize) != fileSize) { bwLog(m_logger, LogLevel::Error, "Failed to load {0}: failed to read file", path.generic_u8string()); return {}; diff --git a/src/CoreLib/Scripting/ServerWeaponStore.cpp b/src/CoreLib/Scripting/ServerWeaponStore.cpp index b7dd2ee1..b749573b 100644 --- a/src/CoreLib/Scripting/ServerWeaponStore.cpp +++ b/src/CoreLib/Scripting/ServerWeaponStore.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include #include #include #include diff --git a/src/CoreLib/Scripting/SharedEntityLibrary.cpp b/src/CoreLib/Scripting/SharedEntityLibrary.cpp index 7bedc119..eb88a671 100644 --- a/src/CoreLib/Scripting/SharedEntityLibrary.cpp +++ b/src/CoreLib/Scripting/SharedEntityLibrary.cpp @@ -17,7 +17,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/CoreLib/Scripting/SharedScriptingLibrary.cpp b/src/CoreLib/Scripting/SharedScriptingLibrary.cpp index 46aa5d89..fe7918f5 100644 --- a/src/CoreLib/Scripting/SharedScriptingLibrary.cpp +++ b/src/CoreLib/Scripting/SharedScriptingLibrary.cpp @@ -71,7 +71,7 @@ namespace bw "GetLastForce", LuaFunction([&](Constraint& constraint) { float lastImpulse = constraint.GetLastImpulse(); - return lastImpulse / m_match.GetTickDuration(); + return lastImpulse / m_match.GetTickDuration().AsSeconds(); }), "GetLastImpulse", LuaFunction(&Constraint::GetLastImpulse), "GetMaxForce", LuaFunction(&Constraint::GetMaxForce), @@ -311,7 +311,7 @@ namespace bw library["GetSeconds"] = LuaFunction([this]() { - return m_match.GetCurrentTime() / 1000.f; + return m_match.GetCurrentTime().AsSeconds(); }); library["GetTickDuration"] = LuaFunction([&]() @@ -511,7 +511,7 @@ namespace bw { library["Create"] = LuaFunction([&](Nz::UInt64 time, sol::main_protected_function callback) { - m_match.GetTimerManager().PushCallback(m_match.GetCurrentTime() + time, [this, callback = std::move(callback)]() + m_match.GetTimerManager().PushCallback(m_match.GetCurrentTime() + Nz::Time::Milliseconds(time), [this, callback = std::move(callback)]() { auto result = callback(); if (!result.valid()) diff --git a/src/CoreLib/Scripting/SharedWeaponLibrary.cpp b/src/CoreLib/Scripting/SharedWeaponLibrary.cpp index 317f173d..54e8887a 100644 --- a/src/CoreLib/Scripting/SharedWeaponLibrary.cpp +++ b/src/CoreLib/Scripting/SharedWeaponLibrary.cpp @@ -37,7 +37,7 @@ namespace bw { entt::handle entity = AssertScriptEntity(weaponTable); - entity.get().SetNextTriggerTime(nextTriggerTime); + entity.get().SetNextTriggerTime(Nz::Time::Milliseconds(nextTriggerTime)); }); } } diff --git a/src/CoreLib/Scripting/SharedWeaponStore.cpp b/src/CoreLib/Scripting/SharedWeaponStore.cpp index aa98d9c8..932a4f17 100644 --- a/src/CoreLib/Scripting/SharedWeaponStore.cpp +++ b/src/CoreLib/Scripting/SharedWeaponStore.cpp @@ -9,7 +9,7 @@ #include #include #include -#include +#include #include #include #include @@ -49,7 +49,7 @@ namespace bw auto& anim = animData.emplace_back(); anim.animationName = animTable[1]; - anim.duration = static_cast(static_cast(double(animTable[2]) * 1000.0)); + anim.duration = Nz::Time::Seconds(static_cast(animTable[2])); } weapon.animations = std::make_shared(std::move(animData)); @@ -60,7 +60,7 @@ namespace bw bool SharedWeaponStore::InitializeWeapon(const ScriptedWeapon& weaponClass, entt::handle entity, entt::handle parent) { - entity.emplace(weaponClass.cooldown); + entity.emplace(Nz::Time::Milliseconds(weaponClass.cooldown)); entity.emplace(parent, weaponClass.attackMode); diff --git a/src/CoreLib/ScriptingEnvironment.cpp b/src/CoreLib/ScriptingEnvironment.cpp index 771ad458..06d7ba1d 100644 --- a/src/CoreLib/ScriptingEnvironment.cpp +++ b/src/CoreLib/ScriptingEnvironment.cpp @@ -39,7 +39,7 @@ namespace bw { sol::error err = result; if (m_outputCallback) - m_outputCallback(err.what(), Nz::Color::Red); + m_outputCallback(err.what(), Nz::Color::Red()); return false; } @@ -48,7 +48,7 @@ namespace bw { sol::error err = loadResult; if (m_outputCallback) - m_outputCallback(err.what(), Nz::Color::Red); + m_outputCallback(err.what(), Nz::Color::Red()); return false; } @@ -58,7 +58,7 @@ namespace bw catch (const std::exception& e) { if (m_outputCallback) - m_outputCallback("PANIC: " + std::string(e.what()), Nz::Color::Red); + m_outputCallback("PANIC: " + std::string(e.what()), Nz::Color::Red()); return false; } diff --git a/src/CoreLib/SharedAppConfig.cpp b/src/CoreLib/SharedAppConfig.cpp index fb581884..b9d3c61a 100644 --- a/src/CoreLib/SharedAppConfig.cpp +++ b/src/CoreLib/SharedAppConfig.cpp @@ -6,7 +6,7 @@ namespace bw { - SharedAppConfig::SharedAppConfig(BurgApp& app) : + SharedAppConfig::SharedAppConfig(BurgAppComponent& app) : ConfigFile(app) { RegisterStringOption("Resources.AssetDirectory"); diff --git a/src/CoreLib/SharedLayer.cpp b/src/CoreLib/SharedLayer.cpp index 9a563555..ee9be9c2 100644 --- a/src/CoreLib/SharedLayer.cpp +++ b/src/CoreLib/SharedLayer.cpp @@ -26,7 +26,7 @@ namespace bw { m_systemGraph.AddSystem(); m_systemGraph.AddSystem(); - m_systemGraph.AddSystem(); + //m_systemGraph.AddSystem(); m_systemGraph.AddSystem(match); m_systemGraph.AddSystem(); @@ -37,7 +37,7 @@ namespace bw Nz::PhysWorld2D& physics = m_systemGraph.GetSystem().GetPhysWorld(); physics.SetGravity(Nz::Vector2f(0.f, 9.81f * 192.f)); physics.SetMaxStepCount(1); - physics.SetSleepTime(0.f); + physics.SetSleepTime(Nz::Time::Zero()); physics.SetStepSize(match.GetTickDuration()); // EnTT FIXME @@ -119,7 +119,7 @@ namespace bw m_registry.clear(); } - void SharedLayer::TickUpdate(float elapsedTime) + void SharedLayer::TickUpdate(Nz::Time elapsedTime) { m_systemGraph.Update(elapsedTime); } diff --git a/src/CoreLib/SharedMatch.cpp b/src/CoreLib/SharedMatch.cpp index dad394d0..681ad644 100644 --- a/src/CoreLib/SharedMatch.cpp +++ b/src/CoreLib/SharedMatch.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include #include #include #include @@ -16,46 +16,38 @@ namespace bw unsigned int MaxDelayedTick = 10; } - SharedMatch::SharedMatch(BurgApp& app, LogSide side, std::string matchName, float tickDuration) : + SharedMatch::SharedMatch(BurgAppComponent& app, LogSide side, std::string matchName, Nz::Time tickDuration) : m_name(std::move(matchName)), m_logger(app, *this, side, app.GetLogger()), m_scriptPacketHandler(m_logger), - m_currentTick(0), - m_currentTime(0), - m_floatingTime(0.f), - m_maxTickTimer(MaxDelayedTick * tickDuration), + m_currentTime(Nz::Time::Zero()), + m_tickTimer(Nz::Time::Zero()), m_tickDuration(tickDuration), - m_tickTimer(0.f) + m_currentTick(0) { m_logger.SetMinimumLogLevel(LogLevel::Debug); } SharedMatch::~SharedMatch() = default; - void SharedMatch::Update(float elapsedTime) + void SharedMatch::Update(Nz::Time elapsedTime) { m_tickTimer += elapsedTime; - if (m_tickTimer > m_maxTickTimer) + std::size_t tickCount = static_cast(m_tickTimer / m_tickDuration); + if (tickCount > MaxDelayedTick) { - float lostTicks = (m_tickTimer - m_maxTickTimer) / m_tickDuration; - bwLog(m_logger, LogLevel::Warning, "Update is too slow, {} ticks have been discarded to preserve realtime", lostTicks); - - m_tickTimer = m_maxTickTimer; + bwLog(m_logger, LogLevel::Warning, "Update is too slow, {} ticks have been discarded to preserve realtime", tickCount - MaxDelayedTick); + tickCount = MaxDelayedTick; } - while (m_tickTimer >= m_tickDuration) + for (std::size_t i = 0; i < tickCount; ++i) { m_tickTimer -= m_tickDuration; + m_currentTime += m_tickDuration; m_timerManager.Update(m_currentTime); OnTick(m_tickTimer < m_tickDuration); - - m_currentTick++; - m_floatingTime += m_tickDuration * 1000.f; - Nz::UInt64 elapsedTimeMs = static_cast(m_floatingTime); - m_currentTime += elapsedTimeMs; - m_floatingTime -= elapsedTimeMs; } } } diff --git a/src/CoreLib/Systems/AnimationSystem.cpp b/src/CoreLib/Systems/AnimationSystem.cpp index 6de77771..b3804a1c 100644 --- a/src/CoreLib/Systems/AnimationSystem.cpp +++ b/src/CoreLib/Systems/AnimationSystem.cpp @@ -8,9 +8,9 @@ namespace bw { - void AnimationSystem::Update(float /*elapsedTime*/) + void AnimationSystem::Update(Nz::Time /*elapsedTime*/) { - Nz::UInt64 now = m_match.GetCurrentTime(); + Nz::Time now = m_match.GetCurrentTime(); auto view = m_registry.view(); for (entt::entity entity : view) diff --git a/src/CoreLib/Systems/InputSystem.cpp b/src/CoreLib/Systems/InputSystem.cpp index e05c2574..fd96ba91 100644 --- a/src/CoreLib/Systems/InputSystem.cpp +++ b/src/CoreLib/Systems/InputSystem.cpp @@ -7,7 +7,7 @@ namespace bw { - void InputSystem::Update(float /*elapsedTime*/) + void InputSystem::Update(Nz::Time /*elapsedTime*/) { auto view = m_registry.view(); for (auto [entity, inputComponent] : view.each()) diff --git a/src/CoreLib/Systems/NetworkSyncSystem.cpp b/src/CoreLib/Systems/NetworkSyncSystem.cpp index 3fd2ff4c..2437a096 100644 --- a/src/CoreLib/Systems/NetworkSyncSystem.cpp +++ b/src/CoreLib/Systems/NetworkSyncSystem.cpp @@ -272,7 +272,7 @@ namespace bw EntityPlayAnimation event; event.animId = anim->GetAnimId(); event.entityId = networkId; - event.startTime = anim->GetStartTime(); + event.startTime = anim->GetStartTime().AsMicroseconds(); OnEntityPlayAnimation(this, event); }); @@ -330,7 +330,7 @@ namespace bw m_entitySlots.erase(it); } - void NetworkSyncSystem::Update(float /*elapsedTime*/) + void NetworkSyncSystem::Update(Nz::Time /*elapsedTime*/) { if (!m_healthUpdateEntities.empty()) { diff --git a/src/CoreLib/Systems/PlayerMovementSystem.cpp b/src/CoreLib/Systems/PlayerMovementSystem.cpp index dc34b739..224a9e89 100644 --- a/src/CoreLib/Systems/PlayerMovementSystem.cpp +++ b/src/CoreLib/Systems/PlayerMovementSystem.cpp @@ -27,7 +27,7 @@ namespace bw m_movementDestroyConnection.release(); } - void PlayerMovementSystem::Update(float /*elapsedTime*/) + void PlayerMovementSystem::Update(Nz::Time /*elapsedTime*/) { m_controllerObserver.each([&](entt::entity entity) { diff --git a/src/CoreLib/Systems/TickCallbackSystem.cpp b/src/CoreLib/Systems/TickCallbackSystem.cpp index 08f6993c..5f7ec2b3 100644 --- a/src/CoreLib/Systems/TickCallbackSystem.cpp +++ b/src/CoreLib/Systems/TickCallbackSystem.cpp @@ -25,7 +25,7 @@ namespace bw m_tickableEntities.erase(entity); } - void TickCallbackSystem::Update(float elapsedTime) + void TickCallbackSystem::Update(Nz::Time elapsedTime) { for (entt::entity entity : m_scriptObserver) { diff --git a/src/CoreLib/Systems/WeaponSystem.cpp b/src/CoreLib/Systems/WeaponSystem.cpp index 5c030e56..0f91be30 100644 --- a/src/CoreLib/Systems/WeaponSystem.cpp +++ b/src/CoreLib/Systems/WeaponSystem.cpp @@ -12,7 +12,7 @@ namespace bw { - void WeaponSystem::Update(float /*elapsedTime*/) + void WeaponSystem::Update(Nz::Time /*elapsedTime*/) { auto view = m_registry.view(); for (entt::entity weapon : view) diff --git a/src/CoreLib/Terrain.cpp b/src/CoreLib/Terrain.cpp index 6b2528ff..f974bedd 100644 --- a/src/CoreLib/Terrain.cpp +++ b/src/CoreLib/Terrain.cpp @@ -29,7 +29,7 @@ namespace bw Initialize(); } - void Terrain::Update(float elapsedTime) + void Terrain::Update(Nz::Time elapsedTime) { for (auto& layerPtr : m_layers) layerPtr->TickUpdate(elapsedTime); diff --git a/src/CoreLib/TerrainLayer.cpp b/src/CoreLib/TerrainLayer.cpp index f0a7962e..f0056aef 100644 --- a/src/CoreLib/TerrainLayer.cpp +++ b/src/CoreLib/TerrainLayer.cpp @@ -18,7 +18,7 @@ namespace bw SharedLayer(match, layerIndex), m_mapLayer(layerData) { - Nz::SystemGraph& systemGraph = GetSystemGraph(); + Nz::EnttSystemGraph& systemGraph = GetSystemGraph(); systemGraph.AddSystem(*this); ResetEntities(); diff --git a/src/CoreLib/Utility/CrashHandler.cpp b/src/CoreLib/Utility/CrashHandler.cpp index bcaa9a5a..2f03fb56 100644 --- a/src/CoreLib/Utility/CrashHandler.cpp +++ b/src/CoreLib/Utility/CrashHandler.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include #ifdef NAZARA_PLATFORM_WINDOWS #include diff --git a/src/CoreLib/Utility/CrashHandlerWin32.cpp b/src/CoreLib/Utility/CrashHandlerWin32.cpp index ae439aa7..7d466c87 100644 --- a/src/CoreLib/Utility/CrashHandlerWin32.cpp +++ b/src/CoreLib/Utility/CrashHandlerWin32.cpp @@ -2,7 +2,7 @@ // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE -#include +#include #include #include diff --git a/src/MapEditor/Enums.hpp b/src/MapEditor/Enums.hpp index 9b5a84d5..f2969e67 100644 --- a/src/MapEditor/Enums.hpp +++ b/src/MapEditor/Enums.hpp @@ -7,7 +7,7 @@ #ifndef BURGWAR_MAPEDITOR_ENUMS_HPP #define BURGWAR_MAPEDITOR_ENUMS_HPP -#include +#include namespace bw { diff --git a/src/MapEditor/Gizmos/PositionGizmo.hpp b/src/MapEditor/Gizmos/PositionGizmo.hpp index 9b993fba..74215eff 100644 --- a/src/MapEditor/Gizmos/PositionGizmo.hpp +++ b/src/MapEditor/Gizmos/PositionGizmo.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/MapEditor/Logic/SelectionEditorMode.hpp b/src/MapEditor/Logic/SelectionEditorMode.hpp index 6a83fe8e..2fd2fb57 100644 --- a/src/MapEditor/Logic/SelectionEditorMode.hpp +++ b/src/MapEditor/Logic/SelectionEditorMode.hpp @@ -8,7 +8,7 @@ #define BURGWAR_MAPEDITOR_SCRIPTING_SELECTION_EDITOR_MODE_HPP #include -#include +#include namespace bw { diff --git a/src/MapEditor/Logic/TileMapEditorMode.cpp b/src/MapEditor/Logic/TileMapEditorMode.cpp index 4643fa03..047e60db 100644 --- a/src/MapEditor/Logic/TileMapEditorMode.cpp +++ b/src/MapEditor/Logic/TileMapEditorMode.cpp @@ -99,7 +99,7 @@ namespace bw if (m_eraserCursor) canvas->SetCursor(m_eraserCursor); - m_hoveringTileSprite->SetColor(Nz::Color::Red); + m_hoveringTileSprite->SetColor(Nz::Color::Red()); } else { diff --git a/src/MapEditor/Widgets/EditorWindow.cpp b/src/MapEditor/Widgets/EditorWindow.cpp index f928a410..03c17c74 100644 --- a/src/MapEditor/Widgets/EditorWindow.cpp +++ b/src/MapEditor/Widgets/EditorWindow.cpp @@ -593,7 +593,7 @@ namespace bw m_undoStack.clear(); - m_canvas->UpdateBackgroundColor(Nz::Color::Black); + m_canvas->UpdateBackgroundColor(Nz::Color::Black()); if (hasWorkingMap) RebuildCanvas(); @@ -985,7 +985,7 @@ namespace bw m_canvas->UpdateBackgroundColor(m_workingMap.GetLayer(*m_currentLayer).backgroundColor); } else - m_canvas->UpdateBackgroundColor(Nz::Color::Black); + m_canvas->UpdateBackgroundColor(Nz::Color::Black()); QSettings().setValue(settings_showBackgroundColor, checked); }); @@ -1423,7 +1423,7 @@ namespace bw m_currentLayer.reset(); m_entityIndices.clear(); m_canvas->UpdateActiveLayer({}); - m_canvas->UpdateBackgroundColor(Nz::Color::Black); + m_canvas->UpdateBackgroundColor(Nz::Color::Black()); m_entityList.listWidget->clear(); diff --git a/src/MapEditor/Widgets/EditorWindow.hpp b/src/MapEditor/Widgets/EditorWindow.hpp index 5b877e6d..dcc8d4bd 100644 --- a/src/MapEditor/Widgets/EditorWindow.hpp +++ b/src/MapEditor/Widgets/EditorWindow.hpp @@ -8,7 +8,7 @@ #define BURGWAR_MAPEDITOR_WIDGETS_EDITORWINDOW_HPP #include -#include +#include #include #include #include diff --git a/src/MapEditor/Widgets/EntityInfoDialog.hpp b/src/MapEditor/Widgets/EntityInfoDialog.hpp index b21b9ee5..cfc69a4e 100644 --- a/src/MapEditor/Widgets/EntityInfoDialog.hpp +++ b/src/MapEditor/Widgets/EntityInfoDialog.hpp @@ -7,7 +7,7 @@ #ifndef BURGWAR_MAPEDITOR_WIDGETS_ENTITYINFODIALOG_HPP #define BURGWAR_MAPEDITOR_WIDGETS_ENTITYINFODIALOG_HPP -#include +#include #include #include #include diff --git a/src/MapEditor/Widgets/MapCanvas.cpp b/src/MapEditor/Widgets/MapCanvas.cpp index a636c773..79f72f4d 100644 --- a/src/MapEditor/Widgets/MapCanvas.cpp +++ b/src/MapEditor/Widgets/MapCanvas.cpp @@ -497,7 +497,7 @@ namespace bw layer.TickUpdate(GetTickDuration()); } - void MapCanvas::OnUpdate(float elapsedTime) + void MapCanvas::OnUpdate(Nz::Time elapsedTime) { Update(elapsedTime); diff --git a/src/MapEditor/Widgets/MapCanvas.hpp b/src/MapEditor/Widgets/MapCanvas.hpp index 9c13e75f..4ae6a071 100644 --- a/src/MapEditor/Widgets/MapCanvas.hpp +++ b/src/MapEditor/Widgets/MapCanvas.hpp @@ -96,7 +96,7 @@ namespace bw void OnMouseLeft() override; void OnMouseMoved(const Nz::WindowEvent::MouseMoveEvent& mouseMoved) override; void OnTick(bool /*lastTick*/) override; - void OnUpdate(float elapsedTime) override; + void OnUpdate(Nz::Time elapsedTime) override; inline void UnregisterEntity(EntityId uniqueId); void UpdateGrid(); diff --git a/src/MapEditor/Widgets/NazaraCanvas.hpp b/src/MapEditor/Widgets/NazaraCanvas.hpp index cd57af32..2e4f3f05 100644 --- a/src/MapEditor/Widgets/NazaraCanvas.hpp +++ b/src/MapEditor/Widgets/NazaraCanvas.hpp @@ -27,7 +27,7 @@ namespace bw protected: virtual void OnHide(); virtual void OnShow(); - virtual void OnUpdate(float elapsedTime); + virtual void OnUpdate(Nz::Time elapsedTime); void closeEvent(QCloseEvent *event) override; void hideEvent(QHideEvent *event) override; diff --git a/src/MapEditor/Widgets/PlayWindow.cpp b/src/MapEditor/Widgets/PlayWindow.cpp index 1f33350a..e49c2dbc 100644 --- a/src/MapEditor/Widgets/PlayWindow.cpp +++ b/src/MapEditor/Widgets/PlayWindow.cpp @@ -86,7 +86,7 @@ namespace bw m_session->SendPacket(authPacket); } - void PlayWindow::OnUpdate(float elapsedTime) + void PlayWindow::OnUpdate(Nz::Time elapsedTime) { NazaraCanvas::OnUpdate(elapsedTime); diff --git a/src/MapEditor/Widgets/PlayWindow.hpp b/src/MapEditor/Widgets/PlayWindow.hpp index 33f1a2a8..0eec6c04 100644 --- a/src/MapEditor/Widgets/PlayWindow.hpp +++ b/src/MapEditor/Widgets/PlayWindow.hpp @@ -26,7 +26,7 @@ namespace bw ~PlayWindow() = default; private: - void OnUpdate(float elapsedTime) override; + void OnUpdate(Nz::Time elapsedTime) override; void resizeEvent(QResizeEvent* event) override; diff --git a/src/MapEditor/Widgets/TileSelectionWidget.hpp b/src/MapEditor/Widgets/TileSelectionWidget.hpp index 166fdb70..c35afe06 100644 --- a/src/MapEditor/Widgets/TileSelectionWidget.hpp +++ b/src/MapEditor/Widgets/TileSelectionWidget.hpp @@ -7,7 +7,7 @@ #ifndef BURGWAR_MAPEDITOR_WIDGETS_TILESELECTIONWIDGET_HPP #define BURGWAR_MAPEDITOR_WIDGETS_TILESELECTIONWIDGET_HPP -#include +#include #include #include #include diff --git a/src/MapEditor/Widgets/WorldCanvas.cpp b/src/MapEditor/Widgets/WorldCanvas.cpp index c01b7179..6473085e 100644 --- a/src/MapEditor/Widgets/WorldCanvas.cpp +++ b/src/MapEditor/Widgets/WorldCanvas.cpp @@ -13,7 +13,7 @@ namespace bw { WorldCanvas::WorldCanvas(QWidget* parent) : NazaraCanvas(parent), - m_backgroundColor(Nz::Color::Black), + m_backgroundColor(Nz::Color::Black()), m_camera(m_world, this, true) { Ndk::RenderSystem& renderSystem = m_world.AddSystem(); @@ -86,7 +86,7 @@ namespace bw m_world.GetSystem().SetDefaultBackground(Nz::ColorBackground::New(color)); } - void WorldCanvas::OnUpdate(float elapsedTime) + void WorldCanvas::OnUpdate(Nz::Time elapsedTime) { SetActive(true); m_world.Update(elapsedTime); diff --git a/src/MapEditor/Widgets/WorldCanvas.hpp b/src/MapEditor/Widgets/WorldCanvas.hpp index b8fcae24..b0452bd1 100644 --- a/src/MapEditor/Widgets/WorldCanvas.hpp +++ b/src/MapEditor/Widgets/WorldCanvas.hpp @@ -46,7 +46,7 @@ namespace bw virtual void OnMouseMoved(const Nz::WindowEvent::MouseMoveEvent& mouseMoved); virtual void OnMouseWheelMoved(const Nz::WindowEvent::MouseWheelEvent& mouseWheel); - void OnUpdate(float elapsedTime) override; + void OnUpdate(Nz::Time elapsedTime) override; private: std::optional m_cameraMovement; diff --git a/src/Server/ServerApp.cpp b/src/Server/ServerAppComponent.cpp similarity index 67% rename from src/Server/ServerApp.cpp rename to src/Server/ServerAppComponent.cpp index 9e5f72c4..b8b350ef 100644 --- a/src/Server/ServerApp.cpp +++ b/src/Server/ServerAppComponent.cpp @@ -2,13 +2,13 @@ // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE -#include -#include +#include +#include namespace bw { - ServerApp::ServerApp(int argc, char* argv[]) : - BurgApp(LogSide::Server, m_configFile), + ServerAppComponent::ServerAppComponent(Nz::ApplicationBase& app) : + BurgAppComponent(app, LogSide::Server, m_configFile), m_configFile(*this) { if (!m_configFile.LoadFromFile("serverconfig.lua")) @@ -34,7 +34,7 @@ namespace bw matchSettings.maxPlayerCount = maxPlayerCount; matchSettings.name = serverName; matchSettings.port = serverPort; - matchSettings.tickDuration = 1.f / tickRate; + matchSettings.tickDuration = Nz::Time::Seconds(1.f / tickRate); // Load map if (!EndsWith(mapPath, ".bmap")) @@ -56,40 +56,28 @@ namespace bw m_match = std::make_unique(*this, std::move(matchSettings), std::move(gamemodeSettings), std::move(modSettings)); } - int ServerApp::Run() + void ServerAppComponent::Update(Nz::Time elapsedTime) { - m_running = true; + BurgAppComponent::Update(elapsedTime); - Nz::Clock updateClock; - Nz::UInt64 tickDuration = static_cast(m_match->GetTickDuration() * 1'000'000); - - while (m_running) + if (!m_match->Update(elapsedTime)) { - BurgApp::Update(); + GetApp().Quit(); + return; + } - Nz::UInt64 elapsedTime = updateClock.Restart(); - if (!m_match->Update(elapsedTime / 1'000'000.f)) - break; + Nz::Time tickDuration = m_match->GetTickDuration(); + if (elapsedTime < tickDuration) + { + // Since OS sleep is not that precise, let some time between the wakeup time and the tick + constexpr Nz::Time wakeUpTime = Nz::Time::Milliseconds(3); - if (tickDuration > elapsedTime) + Nz::Time remainingTime = tickDuration - elapsedTime; + if (remainingTime > wakeUpTime) { - // Since OS sleep is not that precise, let some time between the wakeup time and the tick - constexpr Nz::UInt64 wakeUpTime = 3'000; - - Nz::UInt64 remainingTime = tickDuration - elapsedTime; - if (remainingTime > wakeUpTime) - { - Nz::UInt64 sleepTime = remainingTime - wakeUpTime; - std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime / 1'000)); - } + Nz::Time sleepTime = remainingTime - wakeUpTime; + std::this_thread::sleep_for(sleepTime.AsDuration()); } } - - return 0; - } - - void ServerApp::Quit() - { - m_running = false; } } diff --git a/src/Server/ServerApp.hpp b/src/Server/ServerAppComponent.hpp similarity index 62% rename from src/Server/ServerApp.hpp rename to src/Server/ServerAppComponent.hpp index 49c2032a..d46e9be0 100644 --- a/src/Server/ServerApp.hpp +++ b/src/Server/ServerAppComponent.hpp @@ -7,29 +7,27 @@ #ifndef BURGWAR_SERVERAPP_HPP #define BURGWAR_SERVERAPP_HPP -#include +#include #include #include #include namespace bw { - class ServerApp : public BurgApp + class ServerAppComponent : public BurgAppComponent { public: - ServerApp(int argc, char* argv[]); - ~ServerApp() = default; + ServerAppComponent(Nz::ApplicationBase& app); + ~ServerAppComponent() = default; - int Run(); - void Quit() override; + void Update(Nz::Time elapsedTime) override; private: std::unique_ptr m_match; ServerAppConfig m_configFile; - bool m_running; }; } -#include +#include #endif diff --git a/src/Server/ServerApp.inl b/src/Server/ServerAppComponent.inl similarity index 79% rename from src/Server/ServerApp.inl rename to src/Server/ServerAppComponent.inl index 2b535f31..cea9fa4f 100644 --- a/src/Server/ServerApp.inl +++ b/src/Server/ServerAppComponent.inl @@ -2,4 +2,4 @@ // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE -#include +#include diff --git a/src/Server/ServerAppConfig.cpp b/src/Server/ServerAppConfig.cpp index f9d4c3ec..68d0fad3 100644 --- a/src/Server/ServerAppConfig.cpp +++ b/src/Server/ServerAppConfig.cpp @@ -3,11 +3,11 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include namespace bw { - ServerAppConfig::ServerAppConfig(ServerApp& app) : + ServerAppConfig::ServerAppConfig(ServerAppComponent& app) : SharedAppConfig(app) { RegisterStringOption("ServerSettings.Gamemode"); diff --git a/src/Server/ServerAppConfig.hpp b/src/Server/ServerAppConfig.hpp index 7685fb02..42cdea63 100644 --- a/src/Server/ServerAppConfig.hpp +++ b/src/Server/ServerAppConfig.hpp @@ -11,12 +11,12 @@ namespace bw { - class ServerApp; + class ServerAppComponent; class ServerAppConfig : public SharedAppConfig { public: - ServerAppConfig(ServerApp& app); + ServerAppConfig(ServerAppComponent& app); ~ServerAppConfig() = default; }; } diff --git a/src/Server/main.cpp b/src/Server/main.cpp index ec99cba7..7f3fe5fa 100644 --- a/src/Server/main.cpp +++ b/src/Server/main.cpp @@ -2,16 +2,16 @@ // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE -#include +#include #include #include -#include +#include #include
int BurgWarServer(int argc, char* argv[]) { - Nz::Modules nazara; - bw::ServerApp app(argc, argv); + Nz::Application app(argc, argv); + app.AddComponent(); return app.Run(); } diff --git a/xmake-repo/packages/n/nazaraengine/xmake.lua b/xmake-repo/packages/n/nazaraengine/xmake.lua deleted file mode 100644 index 77774f4c..00000000 --- a/xmake-repo/packages/n/nazaraengine/xmake.lua +++ /dev/null @@ -1,153 +0,0 @@ -package("nazaraengine") - set_homepage("https://github.com/NazaraEngine/NazaraEngine") - set_description("Nazara Engine is a cross-platform framework aimed at (but not limited to) real-time applications requiring audio, 2D and 3D rendering, network and more (such as video games).") - set_license("MIT") - set_policy("package.librarydeps.strict_compatibility", true) - - set_urls("https://github.com/NazaraEngine/NazaraEngine.git") - - add_versions("2022.11.05", "45d4195527d6f2a79d3230a08bf1269cf254f9b9") - - add_deps("nazarautils") - add_deps("chipmunk2d", "dr_wav", "efsw", "fmt", "frozen", "kiwisolver", "libflac", "libsdl", "minimp3", "ordered_map", "stb", { private = true }) - add_deps("libvorbis", { private = true, configs = { with_vorbisenc = false } }) - add_deps("openal-soft", { private = true, configs = { shared = true }}) - - -- static compilation is not supported for now - add_configs("shared", {description = "Build shared library.", default = true, type = "boolean", readonly = true}) - - -- all modules have their own config - add_configs("plugin_assimp", {description = "Includes the assimp plugin", default = false, type = "boolean"}) - add_configs("plugin_ffmpeg", {description = "Includes the ffmpeg plugin", default = false, type = "boolean"}) - add_configs("entt", {description = "Includes EnTT to use components and systems", default = true, type = "boolean"}) - add_configs("with_symbols", {description = "Enable debug symbols in release", default = false, type = "boolean"}) - - local components = { - { - name = "Audio", - deps = { "core" } - }, - { - name = "Core", - custom = function (package, component) - if package:is_plat("linux") then - component:add("syslinks", "pthread", "dl") - end - end - }, - { - name = "Graphics", - deps = { "renderer" } - }, - { - name = "Network", - deps = { "core" } - }, - { - name = "Physics2D", - deps = { "core" } - }, - { - name = "Physics3D", - deps = { "core" } - }, - { - name = "Platform", - deps = { "utility" } - }, - { - name = "Renderer", - deps = { "platform", "utility" }, - custom = function (package, component) - if package:is_plat("windows", "mingw") then - component:add("syslinks", "gdi32", "user32", "advapi32") - end - end - }, - { - name = "Utility", - deps = { "core" } - }, - { - name = "Widgets", - deps = { "graphics" } - }, - } - - for _, comp in ipairs(components) do - local componentName = comp.name:lower() - add_configs(componentName, { description = "Includes the " .. comp.name .. " module", default = true, type = "boolean" }) - - on_component(componentName, function (package, component) - local prefix = "Nazara" - local suffix = package:config("shared") and "" or "-s" - if package:debug() then - suffix = suffix .. "-d" - end - - component:add("deps", table.unwrap(comp.deps)) - component:add("links", prefix .. comp.name .. suffix) - if comp.custom then - comp.custom(package, component) - end - end) - end - - on_load(function (package) - for _, comp in ipairs(components) do - local componentName = comp.name:lower() - if package:config(componentName) then - package:add("components", componentName) - end - end - - if not package:config("shared") then - package:add("defines", "NAZARA_STATIC") - end - - package:add("deps", "nzsl", { debug = package:debug(), configs = { with_symbols = package:config("with_symbols") or package:debug(), shared = true } }) - package:add("deps", "freetype", { private = true, configs = { bzip2 = true, png = true, woff2 = true, zlib = true, debug = package:debug() } }) - package:add("deps", "newtondynamics3", { private = true, debug = is_plat("windows") and package:debug() }) - if package:config("entt") then - package:add("deps", "entt 3.10.1") - end - if package:config("plugin_assimp") then - package:add("deps", "assimp v5.2.3", { private = true }) - end - if package:config("plugin_ffmpeg") then - package:add("deps", "ffmpeg", { private = true, configs = { shared = true }}) - end - end) - - on_install("windows", "mingw", "linux", "macosx", function (package) - local configs = {} - configs.assimp = package:config("plugin_assimp") - configs.ffmpeg = package:config("plugin_ffmpeg") - configs.examples = false - configs.override_runtime = false - - if not package:config("shared") then - configs.embed_rendererbackends = true - end - - if package:is_debug() then - configs.mode = "debug" - elseif package:config("with_symbols") then - configs.mode = "releasedbg" - else - configs.mode = "release" - end - import("package.tools.xmake").install(package, configs) - end) - - on_test(function (package) - for _, comp in ipairs(components) do - if package:config(comp.name:lower()) then - assert(package:check_cxxsnippets({test = [[ - void test() { - Nz::Modules nazara; - } - ]]}, {configs = {languages = "c++17"}, includes = "Nazara/" .. comp.name .. ".hpp"})) - end - end - end) diff --git a/xmake.lua b/xmake.lua index a8f7b337..d8d8ce36 100644 --- a/xmake.lua +++ b/xmake.lua @@ -4,7 +4,6 @@ set_xmakever("2.5.6") option("build_mapeditor", { default = true, showmenu = true, description = "Should the map editor be compiled as part of the project? (requires Qt)" }) set_policy("package.requires_lock", true) -add_repositories("burgwar-repo xmake-repo") set_project("BurgWar") set_version("0.2.0") @@ -221,8 +220,6 @@ target("BurgWarServer") set_kind("binary") add_rules("install_symbolfile", "install_metadata") - add_defines("NDK_SERVER") - add_deps("Main", "CoreLib") add_headerfiles("src/Server/**.hpp", "src/Server/**.inl") add_files("src/Server/**.cpp") From 179653f3e8e7b5beac8fb7d2bda7951bc67f8d22 Mon Sep 17 00:00:00 2001 From: SirLynix Date: Sat, 25 Mar 2023 18:50:02 +0100 Subject: [PATCH 10/17] Some progress on ClientLib port --- include/ClientLib/ClientLayerSound.hpp | 6 +-- include/ClientLib/ClientMatch.hpp | 20 +++++----- include/ClientLib/ClientMatch.inl | 2 +- .../Components/VisibleLayerComponent.hpp | 5 ++- .../Components/VisibleLayerComponent.inl | 3 +- include/ClientLib/Console.hpp | 2 +- include/ClientLib/EscapeMenu.hpp | 6 +-- include/ClientLib/KeyboardAndMousePoller.hpp | 4 +- include/ClientLib/LocalSessionBridge.hpp | 2 +- include/ClientLib/OptionWidget.hpp | 16 ++++---- .../ClientLib/Scripting/ClientEntityStore.hpp | 2 +- include/ClientLib/Scripting/Music.hpp | 10 ++--- include/ClientLib/Scripting/Music.inl | 8 ++-- include/ClientLib/Scripting/Text.hpp | 2 +- include/ClientLib/Scripting/Text.inl | 2 +- include/ClientLib/Scripting/Tilemap.hpp | 6 +-- include/ClientLib/Scripting/Tilemap.inl | 2 +- include/CoreLib/AnimationManager.hpp | 7 ++-- include/CoreLib/AnimationManager.inl | 6 +-- include/CoreLib/NetworkReactor.hpp | 3 +- include/CoreLib/SessionBridge.hpp | 3 +- src/Client/ClientApp.cpp | 8 ++-- src/Client/ClientApp.hpp | 4 +- .../States/Game/AuthenticationState.cpp | 4 +- src/Client/States/Game/ConnectedState.cpp | 2 +- src/Client/States/Game/ConnectionState.cpp | 8 ++-- .../States/Game/ResourceDownloadState.cpp | 4 +- src/Client/States/JoinServerState.cpp | 10 ++--- src/Client/States/JoinServerState.hpp | 6 +-- src/Client/States/ServerListState.cpp | 6 +-- src/Client/States/StartServerState.cpp | 28 +++++++------- src/Client/States/StartServerState.hpp | 14 +++---- src/ClientLib/Chatbox.cpp | 4 +- ...orApp.cpp => ClientEditorAppComponent.cpp} | 17 +++------ ...orApp.hpp => ClientEditorAppComponent.hpp} | 10 ++--- ...orApp.inl => ClientEditorAppComponent.inl} | 6 +-- src/ClientLib/ClientLayer.cpp | 2 +- src/ClientLib/ClientLayerSound.cpp | 6 +-- src/ClientLib/ClientMatch.cpp | 36 +++++++++--------- .../Components/ClientOwnerComponent.cpp | 11 ------ .../LocalPlayerControlledComponent.cpp | 10 ----- .../Components/SoundEmitterComponent.cpp | 11 ++---- .../Components/VisibleLayerComponent.cpp | 4 +- src/ClientLib/Components/VisualComponent.cpp | 10 ----- .../VisualInterpolationComponent.cpp | 10 ----- src/ClientLib/Console.cpp | 4 +- src/ClientLib/EscapeMenu.cpp | 4 +- src/ClientLib/KeyboardAndMousePoller.cpp | 19 +++++----- src/ClientLib/LayerVisualEntity.cpp | 4 +- src/ClientLib/LocalPlayerInputController.cpp | 2 +- src/ClientLib/LocalSessionBridge.cpp | 2 +- src/ClientLib/OptionWidget.cpp | 38 ++++++++++--------- src/ClientLib/Scoreboard.cpp | 10 ++--- .../Scripting/ClientEditorEntityStore.cpp | 2 +- .../Scripting/ClientElementLibrary.cpp | 6 +-- .../Scripting/ClientEntityLibrary.cpp | 4 +- src/ClientLib/Scripting/ClientEntityStore.cpp | 2 +- .../Scripting/ClientScriptingLibrary.cpp | 4 +- src/ClientLib/Scripting/Music.cpp | 4 +- src/CoreLib/NetworkReactor.cpp | 2 +- .../Scripting/SharedElementLibrary.cpp | 6 +-- src/MapEditor/Logic/TileMapEditorMode.cpp | 2 +- src/MapEditor/Logic/TileMapEditorMode.hpp | 2 +- src/MapEditor/Widgets/EditorWindow.cpp | 2 +- src/MapEditor/Widgets/EditorWindow.hpp | 4 +- src/MapEditor/Widgets/PlayWindow.cpp | 4 +- src/MapEditor/Widgets/PlayWindow.hpp | 4 +- src/MapEditor/Widgets/TileSelectionWidget.cpp | 10 ++--- src/MapEditor/Widgets/WorldCanvas.cpp | 18 ++++----- xmake.lua | 2 +- 70 files changed, 232 insertions(+), 277 deletions(-) rename src/ClientLib/{ClientEditorApp.cpp => ClientEditorAppComponent.cpp} (90%) rename src/ClientLib/{ClientEditorApp.hpp => ClientEditorAppComponent.hpp} (68%) rename src/ClientLib/{ClientEditorApp.inl => ClientEditorAppComponent.inl} (56%) delete mode 100644 src/ClientLib/Components/ClientOwnerComponent.cpp delete mode 100644 src/ClientLib/Components/LocalPlayerControlledComponent.cpp delete mode 100644 src/ClientLib/Components/VisualComponent.cpp delete mode 100644 src/ClientLib/Components/VisualInterpolationComponent.cpp diff --git a/include/ClientLib/ClientLayerSound.hpp b/include/ClientLib/ClientLayerSound.hpp index f883a54e..bd093432 100644 --- a/include/ClientLib/ClientLayerSound.hpp +++ b/include/ClientLib/ClientLayerSound.hpp @@ -36,7 +36,7 @@ namespace bw inline ClientLayerSound(ClientLayerSound&& entity) noexcept; ~ClientLayerSound() = default; - float GetSoundDuration(std::size_t soundIndex) const; + Nz::Time GetSoundDuration(std::size_t soundIndex) const; LayerIndex GetLayerIndex() const; inline Nz::Vector2f GetPosition() const; @@ -61,8 +61,8 @@ namespace bw struct PlayingSound { std::shared_ptr soundBuffer; - float currentOffset = 0.f; - float duration = 0.f; + Nz::Time currentOffset = Nz::Time::Zero(); + Nz::Time duration = Nz::Time::Zero(); bool isLooping; bool isSpatialized; }; diff --git a/include/ClientLib/ClientMatch.hpp b/include/ClientLib/ClientMatch.hpp index 47a23b34..ba73b365 100644 --- a/include/ClientLib/ClientMatch.hpp +++ b/include/ClientLib/ClientMatch.hpp @@ -27,7 +27,7 @@ #include #include #include -#include +#include #include #include #include @@ -41,7 +41,7 @@ namespace bw { - class ClientEditorApp; + class ClientEditorAppComponent; class Camera; class ClientGamemode; class ClientSession; @@ -54,7 +54,7 @@ namespace bw friend ClientSession; public: - ClientMatch(ClientEditorApp& burgApp, Nz::RenderWindow* window, Nz::RenderTarget* renderTarget, Nz::Canvas* canvas, ClientSession& session, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData); + ClientMatch(ClientEditorAppComponent& burgApp, Nz::Window* window, Nz::RenderTarget* renderTarget, Nz::Canvas* canvas, ClientSession& session, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData); ClientMatch(const ClientMatch&) = delete; ClientMatch(ClientMatch&&) = delete; ~ClientMatch(); @@ -71,7 +71,7 @@ namespace bw inline Nz::UInt16 GetActiveLayer(); inline AnimationManager& GetAnimationManager(); inline ClientAssetStore& GetAssetStore(); - inline ClientEditorApp& GetApplication(); + inline ClientEditorAppComponent& GetApplication(); inline Camera& GetCamera(); inline const Camera& GetCamera() const; inline ClientSession& GetClientSession(); @@ -141,7 +141,7 @@ namespace bw void BindEscapeMenu(); void BindPackets(); - void BindSignals(ClientEditorApp& burgApp, Nz::RenderWindow* window, Nz::Canvas* canvas); + void BindSignals(ClientEditorAppComponent& burgApp, Nz::Window* window, Nz::Canvas* canvas); void HandleChatMessage(const Packets::ChatMessage& packet); void HandleConsoleAnswer(const Packets::ConsoleAnswer& packet); void HandleEntityCreated(ClientLayer* layer, ClientLayerEntity& entity); @@ -253,7 +253,7 @@ namespace bw } entt::registry registry; - Nz::SystemGraph systemGraph; + Nz::EnttSystemGraph systemGraph; }; struct TickPrediction @@ -269,8 +269,8 @@ namespace bw }; NazaraSlot(Nz::RenderTarget, OnRenderTargetSizeChange, m_onRenderTargetSizeChange); - NazaraSlot(Nz::EventHandler, OnGainedFocus, m_onGainedFocus); - NazaraSlot(Nz::EventHandler, OnLostFocus, m_onLostFocus); + NazaraSlot(Nz::WindowEventHandler, OnGainedFocus, m_onGainedFocus); + NazaraSlot(Nz::WindowEventHandler, OnLostFocus, m_onLostFocus); NazaraSlot(Nz::Canvas, OnUnhandledKeyPressed, m_onUnhandledKeyPressed); NazaraSlot(Nz::Canvas, OnUnhandledKeyReleased, m_onUnhandledKeyReleased); NazaraSlot(ClientLayer, OnEntityCreated, m_onEntityCreated); @@ -300,7 +300,7 @@ namespace bw RenderWorld m_renderWorld; EntityId m_freeClientId; Nz::RenderTarget* m_renderTarget; - Nz::RenderWindow* m_window; + Nz::Window* m_window; Nz::UInt16 m_activeLayerIndex; tsl::hopscotch_map m_entitiesByUniqueId; tsl::hopscotch_map m_playerEntitiesByUniqueId; @@ -308,7 +308,7 @@ namespace bw AnimationManager m_animationManager; AverageValues m_averageTickError; Chatbox m_chatBox; - ClientEditorApp& m_application; + ClientEditorAppComponent& m_application; ClientSession& m_session; EscapeMenu m_escapeMenu; PropertyValueMap m_gamemodeProperties; diff --git a/include/ClientLib/ClientMatch.inl b/include/ClientLib/ClientMatch.inl index 2dcea56c..64dfc92d 100644 --- a/include/ClientLib/ClientMatch.inl +++ b/include/ClientLib/ClientMatch.inl @@ -45,7 +45,7 @@ namespace bw return *m_assetStore; } - inline ClientEditorApp& ClientMatch::GetApplication() + inline ClientEditorAppComponent& ClientMatch::GetApplication() { return m_application; } diff --git a/include/ClientLib/Components/VisibleLayerComponent.hpp b/include/ClientLib/Components/VisibleLayerComponent.hpp index 332f3ba1..202b86f6 100644 --- a/include/ClientLib/Components/VisibleLayerComponent.hpp +++ b/include/ClientLib/Components/VisibleLayerComponent.hpp @@ -7,6 +7,7 @@ #ifndef BURGWAR_CLIENTLIB_COMPONENTS_VISIBLELAYERCOMPONENT_HPP #define BURGWAR_CLIENTLIB_COMPONENTS_VISIBLELAYERCOMPONENT_HPP +#include #include #include #include @@ -20,10 +21,10 @@ namespace bw { class ClientLayerEntity; - class BURGWAR_CLIENTLIB_API VisibleLayerComponent + class BURGWAR_CLIENTLIB_API VisibleLayerComponent : public BaseComponent { public: - inline VisibleLayerComponent(entt::registry& renderWorld); + inline VisibleLayerComponent(entt::registry& renderWorld, entt::handle entity); VisibleLayerComponent(VisibleLayerComponent&&) noexcept = default; ~VisibleLayerComponent() = default; diff --git a/include/ClientLib/Components/VisibleLayerComponent.inl b/include/ClientLib/Components/VisibleLayerComponent.inl index 110a6ecf..f9517608 100644 --- a/include/ClientLib/Components/VisibleLayerComponent.inl +++ b/include/ClientLib/Components/VisibleLayerComponent.inl @@ -6,7 +6,8 @@ namespace bw { - inline VisibleLayerComponent::VisibleLayerComponent(entt::registry& renderWorld) : + inline VisibleLayerComponent::VisibleLayerComponent(entt::registry& renderWorld, entt::handle entity) : + BaseComponent(entity), m_renderWorld(renderWorld) { } diff --git a/include/ClientLib/Console.hpp b/include/ClientLib/Console.hpp index a48ffc4c..d6718dd4 100644 --- a/include/ClientLib/Console.hpp +++ b/include/ClientLib/Console.hpp @@ -32,7 +32,7 @@ namespace bw inline bool IsVisible() const; - void Print(const std::string& str, Nz::Color color = Nz::Color::White); + void Print(const std::string& str, Nz::Color color = Nz::Color::White()); void SetExecuteCallback(ExecuteCallback callback); void Show(bool shouldShow); diff --git a/include/ClientLib/EscapeMenu.hpp b/include/ClientLib/EscapeMenu.hpp index b37c805b..0b461028 100644 --- a/include/ClientLib/EscapeMenu.hpp +++ b/include/ClientLib/EscapeMenu.hpp @@ -16,13 +16,13 @@ namespace bw { - class ClientEditorApp; + class ClientEditorAppComponent; class OptionWidget; class BURGWAR_CLIENTLIB_API EscapeMenu { public: - EscapeMenu(ClientEditorApp& clientEditorApp, Nz::Canvas* canvas); + EscapeMenu(ClientEditorAppComponent& clientEditorApp, Nz::Canvas* canvas); EscapeMenu(const EscapeMenu&) = delete; EscapeMenu(EscapeMenu&&) = delete; ~EscapeMenu(); @@ -50,7 +50,7 @@ namespace bw Nz::ButtonWidget* m_optionsButton; Nz::ButtonWidget* m_quitAppButton; Nz::BaseWidget* m_backgroundWidget; - ClientEditorApp& m_app; + ClientEditorAppComponent& m_app; OptionWidget* m_optionWidget; }; } diff --git a/include/ClientLib/KeyboardAndMousePoller.hpp b/include/ClientLib/KeyboardAndMousePoller.hpp index 814a45da..108c0ffa 100644 --- a/include/ClientLib/KeyboardAndMousePoller.hpp +++ b/include/ClientLib/KeyboardAndMousePoller.hpp @@ -22,8 +22,8 @@ namespace bw PlayerInputData Poll(ClientMatch& clientMatch, const ClientLayerEntityHandle& controlledEntity) override; private: - NazaraSlot(Nz::EventHandler, OnKeyPressed, m_onKeyPressedSlot); - NazaraSlot(Nz::EventHandler, OnMouseWheelMoved, m_onMouseWheelMovedSlot); + NazaraSlot(Nz::WindowEventHandler, OnKeyPressed, m_onKeyPressedSlot); + NazaraSlot(Nz::WindowEventHandler, OnMouseWheelMoved, m_onMouseWheelMovedSlot); Nz::Window& m_window; Nz::UInt8 m_localPlayerIndex; diff --git a/include/ClientLib/LocalSessionBridge.hpp b/include/ClientLib/LocalSessionBridge.hpp index 13e77941..9ba23139 100644 --- a/include/ClientLib/LocalSessionBridge.hpp +++ b/include/ClientLib/LocalSessionBridge.hpp @@ -32,7 +32,7 @@ namespace bw private: std::size_t m_peerId; - Nz::UInt64 m_lastReceiveTime; + Nz::Time m_lastReceiveTime; mutable SessionInfo m_sessionInfo; LocalSessionManager& m_sessionManager; bool m_isServer; diff --git a/include/ClientLib/OptionWidget.hpp b/include/ClientLib/OptionWidget.hpp index a59222c3..b4153782 100644 --- a/include/ClientLib/OptionWidget.hpp +++ b/include/ClientLib/OptionWidget.hpp @@ -66,30 +66,30 @@ namespace bw struct BoolOption : Option { - Ndk::CheckboxWidget* optionWidget; + Nz::CheckboxWidget* optionWidget; - NazaraSlot(Ndk::CheckboxWidget, OnStateChanged, onStateChangeSlot); + NazaraSlot(Nz::CheckboxWidget, OnCheckboxStateUpdate, onStateChangeSlot); }; struct FloatOption : Option { - Ndk::TextAreaWidget* optionWidget; + Nz::TextAreaWidget* optionWidget; - NazaraSlot(Ndk::TextAreaWidget, OnTextChanged, onTextChangedSlot); + NazaraSlot(Nz::TextAreaWidget, OnTextChanged, onTextChangedSlot); }; struct IntegerOption : Option { - Ndk::TextAreaWidget* optionWidget; + Nz::TextAreaWidget* optionWidget; - NazaraSlot(Ndk::TextAreaWidget, OnTextChanged, onTextChangedSlot); + NazaraSlot(Nz::TextAreaWidget, OnTextChanged, onTextChangedSlot); }; struct StringOption : Option { - Ndk::TextAreaWidget* optionWidget; + Nz::TextAreaWidget* optionWidget; - NazaraSlot(Ndk::TextAreaWidget, OnTextChanged, onTextChangedSlot); + NazaraSlot(Nz::TextAreaWidget, OnTextChanged, onTextChangedSlot); }; using OptionType = std::variant; diff --git a/include/ClientLib/Scripting/ClientEntityStore.hpp b/include/ClientLib/Scripting/ClientEntityStore.hpp index 1d2c1d1d..33448153 100644 --- a/include/ClientLib/Scripting/ClientEntityStore.hpp +++ b/include/ClientLib/Scripting/ClientEntityStore.hpp @@ -27,7 +27,7 @@ namespace bw ClientEntityStore(ClientEntityStore&&) = delete; ~ClientEntityStore() = default; - std::optional InstantiateEntity(ClientLayer& layer, std::size_t elementIndex, Nz::UInt32 serverId, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, const PropertyValueMap& properties, entt::entity parentEntity = entt::null) const; + std::optional InstantiateEntity(ClientLayer& layer, std::size_t elementIndex, Nz::UInt32 serverId, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, const PropertyValueMap& properties, entt::handle parentEntity = entt::handle{}) const; }; } diff --git a/include/ClientLib/Scripting/Music.hpp b/include/ClientLib/Scripting/Music.hpp index ee438324..57789585 100644 --- a/include/ClientLib/Scripting/Music.hpp +++ b/include/ClientLib/Scripting/Music.hpp @@ -13,20 +13,20 @@ namespace bw { - class ClientEditorApp; + class ClientEditorAppComponent; class BURGWAR_CLIENTLIB_API Music { public: - Music(ClientEditorApp& app, Nz::Music music); + Music(ClientEditorAppComponent& app, Nz::Music music); Music(const Music&) = delete; Music(Music&&) noexcept = default; ~Music() = default; inline void EnableLooping(bool loop); - inline Nz::UInt32 GetDuration() const; - inline Nz::UInt32 GetPlayingOffset() const; + inline Nz::Time GetDuration() const; + inline Nz::Time GetPlayingOffset() const; inline Nz::UInt64 GetSampleCount() const; inline Nz::UInt32 GetSampleRate() const; @@ -36,7 +36,7 @@ namespace bw inline void Pause(); inline void Play(); - inline void SetPlayingOffset(Nz::UInt32 offset); + inline void SetPlayingOffset(Nz::Time offset); inline void Stop(); diff --git a/include/ClientLib/Scripting/Music.inl b/include/ClientLib/Scripting/Music.inl index 47c66668..893deb2c 100644 --- a/include/ClientLib/Scripting/Music.inl +++ b/include/ClientLib/Scripting/Music.inl @@ -11,12 +11,12 @@ namespace bw m_music.EnableLooping(loop); } - inline Nz::UInt32 Music::GetDuration() const + inline Nz::Time Music::GetDuration() const { return m_music.GetDuration(); } - inline Nz::UInt32 Music::GetPlayingOffset() const + inline Nz::Time Music::GetPlayingOffset() const { return m_music.GetPlayingOffset(); } @@ -38,7 +38,7 @@ namespace bw inline bool Music::IsPlaying() const { - return m_music.GetStatus() == Nz::SoundStatus_Playing; + return m_music.GetStatus() == Nz::SoundStatus::Playing; } inline void Music::Pause() @@ -51,7 +51,7 @@ namespace bw m_music.Play(); } - inline void Music::SetPlayingOffset(Nz::UInt32 offset) + inline void Music::SetPlayingOffset(Nz::Time offset) { m_music.SetPlayingOffset(offset); } diff --git a/include/ClientLib/Scripting/Text.hpp b/include/ClientLib/Scripting/Text.hpp index 51b33f5d..4cdfff14 100644 --- a/include/ClientLib/Scripting/Text.hpp +++ b/include/ClientLib/Scripting/Text.hpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include namespace bw diff --git a/include/ClientLib/Scripting/Text.inl b/include/ClientLib/Scripting/Text.inl index a2c44c71..0840a36e 100644 --- a/include/ClientLib/Scripting/Text.inl +++ b/include/ClientLib/Scripting/Text.inl @@ -20,7 +20,7 @@ namespace bw inline Nz::Vector2f Text::GetSize() const { - Nz::Boxf box = m_textSprite->GetBoundingVolume().obb.localBox; + Nz::Boxf box = m_textSprite->GetAABB(); return { box.width, box.height }; } diff --git a/include/ClientLib/Scripting/Tilemap.hpp b/include/ClientLib/Scripting/Tilemap.hpp index 6023dfc1..f35d20f1 100644 --- a/include/ClientLib/Scripting/Tilemap.hpp +++ b/include/ClientLib/Scripting/Tilemap.hpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include namespace bw @@ -20,7 +20,7 @@ namespace bw class BURGWAR_CLIENTLIB_API Tilemap { public: - inline Tilemap(LayerVisualEntityHandle visualEntity, Nz::TileMapRef tilemap, const Nz::Matrix4f& transformMatrix, int renderOrder); + inline Tilemap(LayerVisualEntityHandle visualEntity, std::shared_ptr tilemap, const Nz::Matrix4f& transformMatrix, int renderOrder); Tilemap(const Tilemap&) = delete; Tilemap(Tilemap&&) noexcept = default; ~Tilemap() = default; @@ -47,7 +47,7 @@ namespace bw LayerVisualEntityHandle m_visualEntity; Nz::Matrix4f m_transformMatrix; - Nz::TileMapRef m_tilemap; + std::shared_ptr m_tilemap; int m_renderOrder; bool m_isVisible; }; diff --git a/include/ClientLib/Scripting/Tilemap.inl b/include/ClientLib/Scripting/Tilemap.inl index fc3c829c..d217573a 100644 --- a/include/ClientLib/Scripting/Tilemap.inl +++ b/include/ClientLib/Scripting/Tilemap.inl @@ -6,7 +6,7 @@ namespace bw { - inline Tilemap::Tilemap(LayerVisualEntityHandle visualEntity, Nz::TileMapRef tilemap, const Nz::Matrix4f& transformMatrix, int renderOrder) : + inline Tilemap::Tilemap(LayerVisualEntityHandle visualEntity, std::shared_ptr tilemap, const Nz::Matrix4f& transformMatrix, int renderOrder) : m_visualEntity(std::move(visualEntity)), m_transformMatrix(transformMatrix), m_tilemap(std::move(tilemap)), diff --git a/include/CoreLib/AnimationManager.hpp b/include/CoreLib/AnimationManager.hpp index 19287188..bc3a57d6 100644 --- a/include/CoreLib/AnimationManager.hpp +++ b/include/CoreLib/AnimationManager.hpp @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -23,7 +24,7 @@ namespace bw AnimationManager() = default; ~AnimationManager() = default; - inline void PushAnimation(float duration, UpdateCallback update, FinishCallback finish); + inline void PushAnimation(Nz::Time duration, UpdateCallback update, FinishCallback finish); inline void Update(Nz::Time elapsedTime); @@ -32,8 +33,8 @@ namespace bw { std::function finishCallback; std::function updateCallback; - float duration; - float elapsedtime; + Nz::Time duration; + Nz::Time elapsedtime; }; std::vector m_newAnimations; diff --git a/include/CoreLib/AnimationManager.inl b/include/CoreLib/AnimationManager.inl index 49c8fda3..a705feb5 100644 --- a/include/CoreLib/AnimationManager.inl +++ b/include/CoreLib/AnimationManager.inl @@ -8,14 +8,14 @@ namespace bw { - inline void AnimationManager::PushAnimation(float duration, UpdateCallback update, FinishCallback finish) + inline void AnimationManager::PushAnimation(Nz::Time duration, UpdateCallback update, FinishCallback finish) { if (!update(0.f)) return; Animation& anim = m_newAnimations.emplace_back(); anim.duration = duration; - anim.elapsedtime = 0.f; + anim.elapsedtime = Nz::Time::Zero(); anim.finishCallback = std::move(finish); anim.updateCallback = std::move(update); } @@ -41,7 +41,7 @@ namespace bw isRunning = false; } else - isRunning = anim.updateCallback(anim.elapsedtime / anim.duration); + isRunning = anim.updateCallback((anim.elapsedtime / anim.duration).AsSeconds()); if (isRunning) ++i; diff --git a/include/CoreLib/NetworkReactor.hpp b/include/CoreLib/NetworkReactor.hpp index 19c9aa02..5bdbb458 100644 --- a/include/CoreLib/NetworkReactor.hpp +++ b/include/CoreLib/NetworkReactor.hpp @@ -8,6 +8,7 @@ #define BURGWAR_CORELIB_NETWORK_REACTOR_HPP #include +#include #include #include #include @@ -53,8 +54,8 @@ namespace bw struct PeerInfo { + Nz::Time timeSinceLastReceive; Nz::UInt32 ping; - Nz::UInt32 timeSinceLastReceive; Nz::UInt32 totalPacketLost; Nz::UInt32 totalPacketReceived; Nz::UInt32 totalPacketSent; diff --git a/include/CoreLib/SessionBridge.hpp b/include/CoreLib/SessionBridge.hpp index f3f41c52..6f20f8ac 100644 --- a/include/CoreLib/SessionBridge.hpp +++ b/include/CoreLib/SessionBridge.hpp @@ -10,6 +10,7 @@ #include #include #include +#include namespace bw { @@ -44,8 +45,8 @@ namespace bw struct SessionInfo { + Nz::Time timeSinceLastReceive; Nz::UInt32 ping; - Nz::UInt32 timeSinceLastReceive; Nz::UInt32 totalPacketReceived; Nz::UInt32 totalPacketLost; Nz::UInt32 totalPacketSent; diff --git a/src/Client/ClientApp.cpp b/src/Client/ClientApp.cpp index 0242d164..1424ea14 100644 --- a/src/Client/ClientApp.cpp +++ b/src/Client/ClientApp.cpp @@ -18,7 +18,7 @@ namespace bw { ClientApp::ClientApp(int argc, char* argv[]) : - ClientEditorApp(argc, argv, LogSide::Client, m_configFile), + ClientEditorAppComponent(argc, argv, LogSide::Client, m_configFile), m_stateMachine(nullptr), m_configFile(*this), m_networkReactors(GetLogger()) @@ -74,7 +74,7 @@ namespace bw camera2D->AddComponent(); - Nz::EventHandler& eventHandler = m_mainWindow->GetEventHandler(); + Nz::WindowEventHandler& eventHandler = m_mainWindow->GetEventHandler(); m_stateData = std::make_shared(); m_stateData->app = this; @@ -91,13 +91,13 @@ namespace bw versionLabel->SetPosition(m_stateData->canvas->GetWidth() - versionLabel->GetWidth(), m_stateData->canvas->GetHeight() - versionLabel->GetHeight()); - eventHandler.OnResized.Connect([=](const Nz::EventHandler*, const Nz::WindowEvent::SizeEvent& sizeEvent) + eventHandler.OnResized.Connect([=](const Nz::WindowEventHandler*, const Nz::WindowEvent::SizeEvent& sizeEvent) { versionLabel->SetPosition(sizeEvent.width - versionLabel->GetWidth(), sizeEvent.height - versionLabel->GetHeight()); }); } - eventHandler.OnResized.Connect([&](const Nz::EventHandler*, const Nz::WindowEvent::SizeEvent& sizeEvent) + eventHandler.OnResized.Connect([&](const Nz::WindowEventHandler*, const Nz::WindowEvent::SizeEvent& sizeEvent) { m_stateData->canvas->Resize(Nz::Vector2f(Nz::Vector2ui(sizeEvent.width, sizeEvent.height))); }); diff --git a/src/Client/ClientApp.hpp b/src/Client/ClientApp.hpp index 63d5c552..9a271389 100644 --- a/src/Client/ClientApp.hpp +++ b/src/Client/ClientApp.hpp @@ -7,7 +7,7 @@ #ifndef BURGWAR_CLIENTAPP_HPP #define BURGWAR_CLIENTAPP_HPP -#include +#include #include #include #include @@ -19,7 +19,7 @@ namespace bw { struct StateData; - class ClientApp : public ClientEditorApp + class ClientApp : public ClientEditorAppComponent { public: ClientApp(int argc, char* argv[]); diff --git a/src/Client/States/Game/AuthenticationState.cpp b/src/Client/States/Game/AuthenticationState.cpp index ae859662..ae2a6ec2 100644 --- a/src/Client/States/Game/AuthenticationState.cpp +++ b/src/Client/States/Game/AuthenticationState.cpp @@ -21,7 +21,7 @@ namespace bw m_onAuthSucceededSlot.Connect(m_clientSession->OnAuthSuccess, [this](ClientSession*, const Packets::AuthSuccess& data) { - UpdateStatus("Authentication succeeded, waiting for match data...", Nz::Color::White); + UpdateStatus("Authentication succeeded, waiting for match data...", Nz::Color::White()); m_authSuccessPacket = data; }); @@ -34,7 +34,7 @@ namespace bw return; } - UpdateStatus("Received match data", Nz::Color::White); + UpdateStatus("Received match data", Nz::Color::White()); SwitchToState(std::make_shared(GetStateDataPtr(), m_clientSession, m_authSuccessPacket.value(), data, GetOriginalState()), 0.5f); }); diff --git a/src/Client/States/Game/ConnectedState.cpp b/src/Client/States/Game/ConnectedState.cpp index 985a77dd..75053b1c 100644 --- a/src/Client/States/Game/ConnectedState.cpp +++ b/src/Client/States/Game/ConnectedState.cpp @@ -212,7 +212,7 @@ namespace bw if (m_pingLabel) { - drawer.SetText(Nz::String::Number(sessionInfo.ping) + "ms"); + drawer.SetText(std::to_string(sessionInfo.ping) + "ms"); m_pingLabel->UpdateText(drawer); m_pingLabel->Resize(m_pingLabel->GetPreferredSize()); diff --git a/src/Client/States/Game/ConnectionState.cpp b/src/Client/States/Game/ConnectionState.cpp index 491ac21c..b2af8952 100644 --- a/src/Client/States/Game/ConnectionState.cpp +++ b/src/Client/States/Game/ConnectionState.cpp @@ -31,7 +31,7 @@ namespace bw m_clientSession = std::make_shared(*app); m_clientSessionConnectedSlot.Connect(m_clientSession->OnConnected, [this] (ClientSession*) { - UpdateStatus("Connected, authenticating...", Nz::Color::White); + UpdateStatus("Connected, authenticating...", Nz::Color::White()); auto authState = std::make_shared(GetStateDataPtr(), m_clientSession, GetOriginalState()); SwitchToState(std::make_shared(GetStateDataPtr(), m_clientSession, std::move(authState)), 0.5f); @@ -100,7 +100,7 @@ namespace bw bwLog(GetStateData().app->GetLogger(), LogLevel::Debug, "resolving {0}:{1}...", m_resolvingData->serverName.hostname, name.port); Nz::ResolveError resolveError; - std::vector serverAddresses = Nz::IpAddress::ResolveHostname(Nz::NetProtocol::Any, m_resolvingData->serverName.hostname, Nz::String::Number(name.port), &resolveError); + std::vector serverAddresses = Nz::IpAddress::ResolveHostname(Nz::NetProtocol::Any, m_resolvingData->serverName.hostname, std::to_string(name.port), &resolveError); if (serverAddresses.empty()) { m_resolvingData->result = tl::unexpected(Nz::ErrorToString(resolveError)); @@ -120,7 +120,7 @@ namespace bw m_resolvingData->hasResult = true; }); - UpdateStatus("Resolving " + name.hostname + "...", Nz::Color::White); + UpdateStatus("Resolving " + name.hostname + "...", Nz::Color::White()); } void ConnectionState::ProcessNextAddress(const Nz::IpAddress& address) @@ -136,7 +136,7 @@ namespace bw m_clientSession->Connect(std::move(sessionBridge)); m_timeBeforeGivingUp = 10.f; - UpdateStatus("Connecting to " + address.ToString() + "...", Nz::Color::White); + UpdateStatus("Connecting to " + address.ToString() + "...", Nz::Color::White()); } else HandleConnectionFailure(); diff --git a/src/Client/States/Game/ResourceDownloadState.cpp b/src/Client/States/Game/ResourceDownloadState.cpp index 4febd5f9..ec869808 100644 --- a/src/Client/States/Game/ResourceDownloadState.cpp +++ b/src/Client/States/Game/ResourceDownloadState.cpp @@ -156,7 +156,7 @@ namespace bw if (hasFinished && !IsSwitching()) { bwLog(GetStateData().app->GetLogger(), LogLevel::Info, "Creating match..."); - UpdateStatus("Entering match...", Nz::Color::White); + UpdateStatus("Entering match...", Nz::Color::White()); SwitchToState(std::make_shared(GetStateDataPtr(), m_clientSession, m_authSuccess, m_matchData, std::move(m_targetAssetDirectory), std::move(m_targetScriptDirectory)), 0.5f); } @@ -336,6 +336,6 @@ namespace bw WriteData("assets", m_assetData); WriteData("scripts", m_scriptData); - UpdateStatus(status.str(), Nz::Color::White); + UpdateStatus(status.str(), Nz::Color::White()); } } diff --git a/src/Client/States/JoinServerState.cpp b/src/Client/States/JoinServerState.cpp index 51210a58..594998d1 100644 --- a/src/Client/States/JoinServerState.cpp +++ b/src/Client/States/JoinServerState.cpp @@ -33,16 +33,16 @@ namespace bw m_serverAddressLayout = CreateWidget(Ndk::BoxLayoutOrientation_Horizontal); - m_serverAddressArea = m_serverAddressLayout->Add(); + m_serverAddressArea = m_serverAddressLayout->Add(); m_serverAddressArea->EnableBackground(true); - m_serverAddressArea->SetBackgroundColor(Nz::Color::White); + m_serverAddressArea->SetBackgroundColor(Nz::Color::White()); m_serverAddressArea->Resize({ 400.f, 36.f }); m_serverAddressArea->SetMaximumWidth(400.f); m_serverAddressArea->SetTextColor(Nz::Color::Black()); - m_serverPortArea = m_serverAddressLayout->Add(); + m_serverPortArea = m_serverAddressLayout->Add(); m_serverPortArea->EnableBackground(true); - m_serverPortArea->SetBackgroundColor(Nz::Color::White); + m_serverPortArea->SetBackgroundColor(Nz::Color::White()); m_serverPortArea->Resize({ 50.f, 36.f }); m_serverPortArea->SetMaximumWidth(100.f); m_serverPortArea->SetTextColor(Nz::Color::Black()); @@ -113,7 +113,7 @@ namespace bw return; } - Nz::String serverPort = m_serverPortArea->GetText(); + std::string serverPort = m_serverPortArea->GetText(); if (serverPort.IsEmpty()) { UpdateStatus("Error: blank server port", Nz::Color::Red()); diff --git a/src/Client/States/JoinServerState.hpp b/src/Client/States/JoinServerState.hpp index b3a13f10..0e348ce7 100644 --- a/src/Client/States/JoinServerState.hpp +++ b/src/Client/States/JoinServerState.hpp @@ -31,7 +31,7 @@ namespace bw void OnBackPressed(); void OnConnectionPressed(); - void UpdateStatus(const std::string& status, const Nz::Color& color = Nz::Color::White); + void UpdateStatus(const std::string& status, const Nz::Color& color = Nz::Color::White()); std::shared_ptr m_previousState; std::shared_ptr m_nextGameState; @@ -41,8 +41,8 @@ namespace bw Nz::ButtonWidget* m_connectionButton; Nz::LabelWidget* m_serverLabel; Nz::LabelWidget* m_statusLabel; - Ndk::TextAreaWidget* m_serverAddressArea; - Ndk::TextAreaWidget* m_serverPortArea; + Nz::TextAreaWidget* m_serverAddressArea; + Nz::TextAreaWidget* m_serverPortArea; }; } diff --git a/src/Client/States/ServerListState.cpp b/src/Client/States/ServerListState.cpp index e465fbc2..01c501bf 100644 --- a/src/Client/States/ServerListState.cpp +++ b/src/Client/States/ServerListState.cpp @@ -363,7 +363,7 @@ namespace bw infoDrawer.AppendText(name + '\n'); infoDrawer.SetDefaultCharacterSize(18); - infoDrawer.SetDefaultColor(Nz::Color::White); + infoDrawer.SetDefaultColor(Nz::Color::White()); if (!desc.empty()) infoDrawer.AppendText(desc + '\n'); @@ -372,13 +372,13 @@ namespace bw infoDrawer.SetDefaultColor(Nz::Color(220, 220, 220)); infoDrawer.AppendText("Gamemode: "); - infoDrawer.SetDefaultColor(Nz::Color::White); + infoDrawer.SetDefaultColor(Nz::Color::White()); infoDrawer.AppendText(gamemode); infoDrawer.SetDefaultColor(Nz::Color(220, 220, 220)); infoDrawer.AppendText(" Map: "); - infoDrawer.SetDefaultColor(Nz::Color::White); + infoDrawer.SetDefaultColor(Nz::Color::White()); infoDrawer.AppendText(map); infoDrawer.AppendText("\n"); diff --git a/src/Client/States/StartServerState.cpp b/src/Client/States/StartServerState.cpp index cd29f045..919cb1fa 100644 --- a/src/Client/States/StartServerState.cpp +++ b/src/Client/States/StartServerState.cpp @@ -46,9 +46,9 @@ namespace bw Nz::LabelWidget* gamemodeLabel = gamemodeLayout->Add(); gamemodeLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Gamemode: ", 24)); - m_gamemodeArea = gamemodeLayout->Add(); + m_gamemodeArea = gamemodeLayout->Add(); m_gamemodeArea->EnableBackground(true); - m_gamemodeArea->SetBackgroundColor(Nz::Color::White); + m_gamemodeArea->SetBackgroundColor(Nz::Color::White()); m_gamemodeArea->SetTextColor(Nz::Color::Black()); m_gamemodeArea->SetMaximumHeight(m_gamemodeArea->GetMinimumHeight()); @@ -57,9 +57,9 @@ namespace bw Nz::LabelWidget* mapLabel = mapLayout->Add(); mapLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Map: ", 24)); - m_mapArea = mapLayout->Add(); + m_mapArea = mapLayout->Add(); m_mapArea->EnableBackground(true); - m_mapArea->SetBackgroundColor(Nz::Color::White); + m_mapArea->SetBackgroundColor(Nz::Color::White()); m_mapArea->SetTextColor(Nz::Color::Black()); m_mapArea->SetMaximumHeight(m_mapArea->GetMinimumHeight()); @@ -68,9 +68,9 @@ namespace bw Nz::LabelWidget* portLabel = portLayout->Add(); portLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Port: ", 24)); - m_portArea = portLayout->Add(); + m_portArea = portLayout->Add(); m_portArea->EnableBackground(true); - m_portArea->SetBackgroundColor(Nz::Color::White); + m_portArea->SetBackgroundColor(Nz::Color::White()); m_portArea->SetTextColor(Nz::Color::Black()); m_portArea->SetMaximumHeight(m_mapArea->GetMinimumHeight()); m_portArea->SetCharacterFilter([](Nz::UInt32 character) @@ -81,7 +81,7 @@ namespace bw return true; }); - m_listServerCheckbox = m_serverConfigLayout->Add(); + m_listServerCheckbox = m_serverConfigLayout->Add(); m_listServerCheckbox->UpdateText(Nz::SimpleTextDrawer::Draw("Register the server online", 24)); m_nameLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); @@ -89,9 +89,9 @@ namespace bw Nz::LabelWidget* nameLabel = m_nameLayout->Add(); nameLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Name: ", 24)); - m_nameArea = m_nameLayout->Add(); + m_nameArea = m_nameLayout->Add(); m_nameArea->EnableBackground(true); - m_nameArea->SetBackgroundColor(Nz::Color::White); + m_nameArea->SetBackgroundColor(Nz::Color::White()); m_nameArea->SetTextColor(Nz::Color::Black()); m_nameArea->SetMaximumHeight(m_mapArea->GetMinimumHeight()); @@ -100,9 +100,9 @@ namespace bw Nz::LabelWidget* descLabel = m_descriptionLayout->Add(); descLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Description: ", 24)); - m_descriptionArea = m_descriptionLayout->Add(); + m_descriptionArea = m_descriptionLayout->Add(); m_descriptionArea->EnableBackground(true); - m_descriptionArea->SetBackgroundColor(Nz::Color::White); + m_descriptionArea->SetBackgroundColor(Nz::Color::White()); m_descriptionArea->SetTextColor(Nz::Color::Black()); m_descriptionArea->SetMaximumHeight(m_mapArea->GetMinimumHeight()); @@ -133,7 +133,7 @@ namespace bw m_descriptionArea->SetText(playerConfig.GetStringValue("StartServer.Description")); m_gamemodeArea->SetText(playerConfig.GetStringValue("StartServer.Gamemode")); - m_listServerCheckbox->SetState((playerConfig.GetBoolValue("StartServer.ListServer")) ? Ndk::CheckboxState_Checked : Ndk::CheckboxState_Unchecked); + m_listServerCheckbox->SetState((playerConfig.GetBoolValue("StartServer.ListServer")) ? Nz::CheckboxState::Checked : Nz::CheckboxState::Unchecked); m_mapArea->SetText(playerConfig.GetStringValue("StartServer.Map")); m_nameArea->SetText(playerConfig.GetStringValue("StartServer.Name")); m_portArea->SetText(std::to_string(playerConfig.GetIntegerValue("StartServer.Port"))); @@ -175,7 +175,7 @@ namespace bw return; } - Nz::String serverPort = m_portArea->GetText(); + std::string serverPort = m_portArea->GetText(); if (serverPort.IsEmpty()) { UpdateStatus("Error: blank server port", Nz::Color::Red()); @@ -191,7 +191,7 @@ namespace bw ConfigFile& playerConfig = app->GetPlayerSettings(); - bool listServer = (m_listServerCheckbox->GetState() == Ndk::CheckboxState_Checked); + bool listServer = (m_listServerCheckbox->GetState() == Nz::CheckboxState::Checked); std::string serverName; std::string serverDesc; if (listServer) diff --git a/src/Client/States/StartServerState.hpp b/src/Client/States/StartServerState.hpp index afe17243..b56acd1f 100644 --- a/src/Client/States/StartServerState.hpp +++ b/src/Client/States/StartServerState.hpp @@ -30,7 +30,7 @@ namespace bw void OnBackPressed(); void OnStartServerPressed(); - void UpdateStatus(const std::string& status, const Nz::Color& color = Nz::Color::White); + void UpdateStatus(const std::string& status, const Nz::Color& color = Nz::Color::White()); std::shared_ptr m_previousState; std::shared_ptr m_nextGameState; @@ -41,14 +41,14 @@ namespace bw Nz::BaseWidget* m_background; Nz::ButtonWidget* m_backButton; Nz::ButtonWidget* m_startServerButton; - Ndk::CheckboxWidget* m_listServerCheckbox; + Nz::CheckboxWidget* m_listServerCheckbox; Nz::LabelWidget* m_title; Nz::LabelWidget* m_statusLabel; - Ndk::TextAreaWidget* m_descriptionArea; - Ndk::TextAreaWidget* m_gamemodeArea; - Ndk::TextAreaWidget* m_mapArea; - Ndk::TextAreaWidget* m_nameArea; - Ndk::TextAreaWidget* m_portArea; + Nz::TextAreaWidget* m_descriptionArea; + Nz::TextAreaWidget* m_gamemodeArea; + Nz::TextAreaWidget* m_mapArea; + Nz::TextAreaWidget* m_nameArea; + Nz::TextAreaWidget* m_portArea; }; } diff --git a/src/ClientLib/Chatbox.cpp b/src/ClientLib/Chatbox.cpp index 77ad98e7..e8aa7e5f 100644 --- a/src/ClientLib/Chatbox.cpp +++ b/src/ClientLib/Chatbox.cpp @@ -25,7 +25,7 @@ namespace bw m_chatBox->EnableLineWrap(true); m_chatBox->SetBackgroundColor(Nz::Color(0, 0, 0, 50)); m_chatBox->SetCharacterSize(22); - m_chatBox->SetTextColor(Nz::Color::White); + m_chatBox->SetTextColor(Nz::Color::White()); //m_chatBox->SetTextFont(chatboxFont); m_chatBox->SetTextOutlineColor(Nz::Color::Black()); m_chatBox->SetTextOutlineThickness(1.f); @@ -156,7 +156,7 @@ namespace bw }, lineItem); } - m_chatBox->SetTextColor(Nz::Color::White); + m_chatBox->SetTextColor(Nz::Color::White()); m_chatBox->AppendText("\n"); } diff --git a/src/ClientLib/ClientEditorApp.cpp b/src/ClientLib/ClientEditorAppComponent.cpp similarity index 90% rename from src/ClientLib/ClientEditorApp.cpp rename to src/ClientLib/ClientEditorAppComponent.cpp index 8478947f..6b340f65 100644 --- a/src/ClientLib/ClientEditorApp.cpp +++ b/src/ClientLib/ClientEditorAppComponent.cpp @@ -2,7 +2,7 @@ // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE -#include +#include #include #include #include @@ -26,8 +26,8 @@ namespace bw static constexpr const char* PlayerSettingsFile = "playerconfig.lua"; } - ClientEditorApp::ClientEditorApp(int argc, char* argv[], LogSide side, const SharedAppConfig& configFile) : - BurgAppComponent(side, configFile), + ClientEditorAppComponent::ClientEditorAppComponent(Nz::ApplicationBase& app, int argc, char* argv[], LogSide side, const SharedAppConfig& configFile) : + BurgAppComponent(app, side, configFile), m_playerSettings(*this) { if (!m_playerSettings.LoadFromFile(PlayerSettingsFile)) @@ -46,7 +46,7 @@ namespace bw }); } - ClientEditorApp::~ClientEditorApp() + ClientEditorAppComponent::~ClientEditorAppComponent() { /*Nz::FontLibrary::Clear(); Nz::MaterialLibrary::Clear(); @@ -54,18 +54,13 @@ namespace bw Nz::TextureLibrary::Clear();*/ } - void ClientEditorApp::SavePlayerConfig() + void ClientEditorAppComponent::SavePlayerConfig() { if (!m_playerSettings.SaveToFile(PlayerSettingsFile)) bwLog(GetLogger(), LogLevel::Warning, "Failed to save player config"); } - void ClientEditorApp::Quit() - { - //ClientApplication::Quit(); - } - - void ClientEditorApp::FillStores() + void ClientEditorAppComponent::FillStores() { const std::string& gameResourceFolder = m_config.GetStringValue("Resources.AssetDirectory"); diff --git a/src/ClientLib/ClientEditorApp.hpp b/src/ClientLib/ClientEditorAppComponent.hpp similarity index 68% rename from src/ClientLib/ClientEditorApp.hpp rename to src/ClientLib/ClientEditorAppComponent.hpp index b3505d3a..b8bb9547 100644 --- a/src/ClientLib/ClientEditorApp.hpp +++ b/src/ClientLib/ClientEditorAppComponent.hpp @@ -14,19 +14,17 @@ namespace bw { class SharedAppConfig; - class BURGWAR_CLIENTLIB_API ClientEditorApp : public BurgAppComponent + class BURGWAR_CLIENTLIB_API ClientEditorAppComponent : public BurgAppComponent { public: - ClientEditorApp(int argc, char* argv[], LogSide side, const SharedAppConfig& configFile); - ~ClientEditorApp(); + ClientEditorAppComponent(Nz::ApplicationBase& app, int argc, char* argv[], LogSide side, const SharedAppConfig& configFile); + ~ClientEditorAppComponent(); inline ConfigFile& GetPlayerSettings(); inline const ConfigFile& GetPlayerSettings() const; void SavePlayerConfig(); - void Quit() override; - protected: void FillStores(); @@ -35,6 +33,6 @@ namespace bw }; } -#include +#include #endif diff --git a/src/ClientLib/ClientEditorApp.inl b/src/ClientLib/ClientEditorAppComponent.inl similarity index 56% rename from src/ClientLib/ClientEditorApp.inl rename to src/ClientLib/ClientEditorAppComponent.inl index a1b51eac..8f50fd56 100644 --- a/src/ClientLib/ClientEditorApp.inl +++ b/src/ClientLib/ClientEditorAppComponent.inl @@ -2,16 +2,16 @@ // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE -#include +#include namespace bw { - inline ConfigFile& ClientEditorApp::GetPlayerSettings() + inline ConfigFile& ClientEditorAppComponent::GetPlayerSettings() { return m_playerSettings; } - inline const ConfigFile& ClientEditorApp::GetPlayerSettings() const + inline const ConfigFile& ClientEditorAppComponent::GetPlayerSettings() const { return m_playerSettings; } diff --git a/src/ClientLib/ClientLayer.cpp b/src/ClientLib/ClientLayer.cpp index d2dc1221..76e612e8 100644 --- a/src/ClientLib/ClientLayer.cpp +++ b/src/ClientLib/ClientLayer.cpp @@ -26,7 +26,7 @@ namespace bw m_isEnabled(false), m_isPredictionEnabled(false) { - Nz::SystemGraph& systemGraph = GetSystemGraph(); + Nz::EnttSystemGraph& systemGraph = GetSystemGraph(); systemGraph.AddSystem(); systemGraph.AddSystem(); systemGraph.AddSystem(); diff --git a/src/ClientLib/ClientLayerSound.cpp b/src/ClientLib/ClientLayerSound.cpp index 35674fab..06cd6773 100644 --- a/src/ClientLib/ClientLayerSound.cpp +++ b/src/ClientLib/ClientLayerSound.cpp @@ -8,12 +8,12 @@ namespace bw { - float ClientLayerSound::GetSoundDuration(std::size_t soundIndex) const + Nz::Time ClientLayerSound::GetSoundDuration(std::size_t soundIndex) const { assert(soundIndex < m_playingSounds.size()); auto& playingSoundOpt = m_playingSounds[soundIndex]; if (!playingSoundOpt) - return -1.f; + return Nz::Time::Zero(); return playingSoundOpt->duration; } @@ -37,7 +37,7 @@ namespace bw m_playingSounds.emplace_back(); auto& playingSound = m_playingSounds[soundIndex].emplace(); - playingSound.duration = soundBuffer->GetDuration() / 1000.f; + playingSound.duration = soundBuffer->GetDuration(); playingSound.isLooping = isLooping; playingSound.isSpatialized = isSpatialized; playingSound.soundBuffer = soundBuffer; diff --git a/src/ClientLib/ClientMatch.cpp b/src/ClientLib/ClientMatch.cpp index 40e18feb..f19eece8 100644 --- a/src/ClientLib/ClientMatch.cpp +++ b/src/ClientLib/ClientMatch.cpp @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include #include #include @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -45,8 +46,8 @@ namespace bw { - ClientMatch::ClientMatch(ClientEditorApp& burgApp, Nz::RenderWindow* window, Nz::RenderTarget* renderTarget, Nz::Canvas* canvas, ClientSession& session, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData) : - SharedMatch(burgApp, LogSide::Client, "local", matchData.tickDuration), + ClientMatch::ClientMatch(ClientEditorAppComponent& burgApp, Nz::Window* window, Nz::RenderTarget* renderTarget, Nz::Canvas* canvas, ClientSession& session, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData) : + SharedMatch(burgApp, LogSide::Client, "local", Nz::Time::Seconds(matchData.tickDuration)), m_gamemodeName(matchData.gamemode), m_canvas(canvas), m_freeClientId(-1), @@ -98,12 +99,12 @@ namespace bw m_renderWorld.systemGraph.AddSystem(*this); m_renderWorld.systemGraph.AddSystem(playerSettings); - m_camera.emplace(m_renderWorld, renderTarget, true); + m_camera.emplace(m_renderWorld.registry, renderTarget, true); m_camera->SetZoomFactor(0.8f); m_currentLayer = entt::handle(m_renderWorld.registry, m_renderWorld.registry.create()); m_currentLayer.emplace(); - //m_currentLayer.emplace(m_renderWorld); + m_currentLayer.emplace(m_renderWorld.registry, m_currentLayer); InitializeRemoteConsole(); @@ -356,7 +357,7 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - m_animationManager.PushAnimation(duration, [=](float ratio) + m_animationManager.PushAnimation(Nz::Time::Seconds(duration), [=](float ratio) { if (!entity) return false; @@ -382,7 +383,7 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - m_animationManager.PushAnimation(duration, [=](float ratio) + m_animationManager.PushAnimation(Nz::Time::Seconds(duration), [=](float ratio) { if (!entity) return false; @@ -657,7 +658,7 @@ namespace bw m_escapeMenu.OnQuitApp.Connect([this](EscapeMenu*) { - m_application.Quit(); + m_application.GetApp().Quit(); }); } @@ -790,7 +791,7 @@ namespace bw }); } - void ClientMatch::BindSignals(ClientEditorApp& burgApp, Nz::RenderWindow* window, Nz::Canvas* canvas) + void ClientMatch::BindSignals(ClientEditorAppComponent& burgApp, Nz::Window* window, Nz::Canvas* canvas) { m_chatBox.OnChatMessage.Connect([this](const std::string& message) { @@ -801,17 +802,17 @@ namespace bw m_session.SendPacket(chatPacket); }); - m_onGainedFocus.Connect(window->GetEventHandler().OnGainedFocus, [this](const Nz::EventHandler* /*eventHandler*/) + m_onGainedFocus.Connect(window->GetEventHandler().OnGainedFocus, [this](const Nz::WindowEventHandler* /*eventHandler*/) { m_hasFocus = true; }); - m_onLostFocus.Connect(window->GetEventHandler().OnLostFocus, [this](const Nz::EventHandler* /*eventHandler*/) + m_onLostFocus.Connect(window->GetEventHandler().OnLostFocus, [this](const Nz::WindowEventHandler* /*eventHandler*/) { m_hasFocus = false; }); - m_onUnhandledKeyPressed.Connect(canvas->OnUnhandledKeyPressed, [this](const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& event) + m_onUnhandledKeyPressed.Connect(canvas->OnUnhandledKeyPressed, [this](const Nz::WindowEventHandler*, const Nz::WindowEvent::KeyEvent& event) { switch (event.virtualKey) { @@ -873,7 +874,7 @@ namespace bw } }); - m_onUnhandledKeyReleased.Connect(canvas->OnUnhandledKeyReleased, [this](const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& event) + m_onUnhandledKeyReleased.Connect(canvas->OnUnhandledKeyReleased, [this](const Nz::WindowEventHandler*, const Nz::WindowEvent::KeyEvent& event) { switch (event.virtualKey) { @@ -888,6 +889,7 @@ namespace bw }; }); + /* TODO m_onRenderTargetSizeChange.Connect(window->GetRenderTarget()->OnRenderTargetSizeChange, [this](const Nz::RenderTarget* renderTarget) { Nz::Vector2f size = Nz::Vector2f(renderTarget->GetSize()); @@ -897,7 +899,7 @@ namespace bw m_scoreboard->Resize({ size.x * 0.75f, size.y * 0.75f }); m_scoreboard->Center(); } - }); + });*/ m_nicknameUpdateSlot.Connect(burgApp.GetPlayerSettings().GetStringUpdateSignal("Player.Name"), [this](const std::string& newValue) { @@ -936,9 +938,9 @@ namespace bw playerName = ""; m_chatBox.PrintMessage({ - Chatbox::ColorItem { Nz::Color::Yellow }, + Chatbox::ColorItem { Nz::Color::Yellow() }, Chatbox::TextItem { std::move(playerName) }, - Chatbox::ColorItem { Nz::Color::White }, + Chatbox::ColorItem { Nz::Color::White() }, Chatbox::TextItem { ": " }, Chatbox::TextItem { packet.content } }); @@ -1705,7 +1707,7 @@ namespace bw if (lastTick) { // Remember predicted ticks for improving over time - if (m_tickPredictions.size() >= static_cast(std::ceil(2 / GetTickDuration()))) //< Remember at most 2s of inputs + if (m_tickPredictions.size() >= static_cast(std::ceil(2 / GetTickDuration().AsSeconds()))) //< Remember at most 2s of inputs m_tickPredictions.erase(m_tickPredictions.begin()); auto& prediction = m_tickPredictions.emplace_back(); diff --git a/src/ClientLib/Components/ClientOwnerComponent.cpp b/src/ClientLib/Components/ClientOwnerComponent.cpp deleted file mode 100644 index f93870d7..00000000 --- a/src/ClientLib/Components/ClientOwnerComponent.cpp +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - Ndk::ComponentIndex ClientOwnerComponent::componentIndex; -} - diff --git a/src/ClientLib/Components/LocalPlayerControlledComponent.cpp b/src/ClientLib/Components/LocalPlayerControlledComponent.cpp deleted file mode 100644 index 73323f93..00000000 --- a/src/ClientLib/Components/LocalPlayerControlledComponent.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - Ndk::ComponentIndex LocalPlayerControlledComponent::componentIndex; -} diff --git a/src/ClientLib/Components/SoundEmitterComponent.cpp b/src/ClientLib/Components/SoundEmitterComponent.cpp index 4cb18356..09c59e5f 100644 --- a/src/ClientLib/Components/SoundEmitterComponent.cpp +++ b/src/ClientLib/Components/SoundEmitterComponent.cpp @@ -3,14 +3,13 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include #include namespace bw { Nz::UInt32 SoundEmitterComponent::PlaySound(const std::shared_ptr& soundBuffer, const Nz::Vector3f& soundPosition, bool attachedToEntity, bool isLooping, bool isSpatialized) { - entt::entity entity = GetEntity(); + /*entt::entity entity = GetEntity(); if (!entity) return SoundSystem::InvalidSoundId; @@ -20,13 +19,13 @@ namespace bw m_sounds.insert(soundId); return soundId; } - else + else*/ return SoundSystem::InvalidSoundId; } void SoundEmitterComponent::StopSound(Nz::UInt32 soundId) { - auto it = m_sounds.find(soundId); + /*auto it = m_sounds.find(soundId); if (it == m_sounds.end()) return; //< Sound can have been removed by the sound system @@ -37,8 +36,6 @@ namespace bw soundSystem.StopSound(soundId); } - m_sounds.erase(it); + m_sounds.erase(it);*/ } - - Ndk::ComponentIndex SoundEmitterComponent::componentIndex; } diff --git a/src/ClientLib/Components/VisibleLayerComponent.cpp b/src/ClientLib/Components/VisibleLayerComponent.cpp index b2c58e30..c29ece1f 100644 --- a/src/ClientLib/Components/VisibleLayerComponent.cpp +++ b/src/ClientLib/Components/VisibleLayerComponent.cpp @@ -69,7 +69,7 @@ namespace bw { assert(visibleLayer); - auto& nodeComponent = m_entity.get(); + auto& nodeComponent = GetHandle().get(); visibleLayer->baseNode.SetParent(nodeComponent); visibleLayer->baseNode.SetScale(scale); @@ -122,6 +122,4 @@ namespace bw m_visibleLayers.emplace_back(std::move(visibleLayer)); } - - Ndk::ComponentIndex VisibleLayerComponent::componentIndex; } diff --git a/src/ClientLib/Components/VisualComponent.cpp b/src/ClientLib/Components/VisualComponent.cpp deleted file mode 100644 index 41c0bd50..00000000 --- a/src/ClientLib/Components/VisualComponent.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - Ndk::ComponentIndex VisualComponent::componentIndex; -} diff --git a/src/ClientLib/Components/VisualInterpolationComponent.cpp b/src/ClientLib/Components/VisualInterpolationComponent.cpp deleted file mode 100644 index e2ba03a1..00000000 --- a/src/ClientLib/Components/VisualInterpolationComponent.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - Ndk::ComponentIndex VisualInterpolationComponent::componentIndex; -} diff --git a/src/ClientLib/Console.cpp b/src/ClientLib/Console.cpp index 863e3136..82ce205f 100644 --- a/src/ClientLib/Console.cpp +++ b/src/ClientLib/Console.cpp @@ -12,14 +12,14 @@ namespace bw /*m_widget = canvas->Add(); m_widget->Hide(); - m_widget->OnCommand.Connect([this](Ndk::Console*, const Nz::String& command) + m_widget->OnCommand.Connect([this](Ndk::Console*, const std::string& command) { if (m_callback) m_callback(command); });*/ // Connect every slot - m_onTargetChangeSizeSlot.Connect(window->OnRenderTargetSizeChange, this, &Console::OnRenderTargetSizeChange); + //m_onTargetChangeSizeSlot.Connect(window->OnRenderTargetSizeChange, this, &Console::OnRenderTargetSizeChange); OnRenderTargetSizeChange(window); } diff --git a/src/ClientLib/EscapeMenu.cpp b/src/ClientLib/EscapeMenu.cpp index 4bf1447c..24832550 100644 --- a/src/ClientLib/EscapeMenu.cpp +++ b/src/ClientLib/EscapeMenu.cpp @@ -3,13 +3,13 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include #include #include namespace bw { - EscapeMenu::EscapeMenu(ClientEditorApp& clientEditorApp, Nz::Canvas* canvas) : + EscapeMenu::EscapeMenu(ClientEditorAppComponent& clientEditorApp, Nz::Canvas* canvas) : m_app(clientEditorApp) { m_backgroundWidget = canvas->Add(); diff --git a/src/ClientLib/KeyboardAndMousePoller.cpp b/src/ClientLib/KeyboardAndMousePoller.cpp index 3683c047..cbb94833 100644 --- a/src/ClientLib/KeyboardAndMousePoller.cpp +++ b/src/ClientLib/KeyboardAndMousePoller.cpp @@ -9,7 +9,7 @@ #include #include #include -#include +#include namespace bw { @@ -17,8 +17,8 @@ namespace bw m_window(window), m_localPlayerIndex(localPlayerIndex) { - Nz::EventHandler& eventHandler = m_window.GetEventHandler(); - m_onKeyPressedSlot.Connect(eventHandler.OnKeyPressed, [this](const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& event) + Nz::WindowEventHandler& eventHandler = m_window.GetEventHandler(); + m_onKeyPressedSlot.Connect(eventHandler.OnKeyPressed, [this](const Nz::WindowEventHandler*, const Nz::WindowEvent::KeyEvent& event) { switch (event.virtualKey) { @@ -49,7 +49,7 @@ namespace bw } }); - m_onMouseWheelMovedSlot.Connect(eventHandler.OnMouseWheelMoved, [this](const Nz::EventHandler*, const Nz::WindowEvent::MouseWheelEvent& event) + m_onMouseWheelMovedSlot.Connect(eventHandler.OnMouseWheelMoved, [this](const Nz::WindowEventHandler*, const Nz::WindowEvent::MouseWheelEvent& event) { OnSwitchWeapon(this, event.delta > 0.f); }); @@ -92,20 +92,19 @@ namespace bw Nz::Vector2f originPosition = controlledEntity->GetPosition(); float lookSwitch = originPosition.x; - if (entity->HasComponent()) + if (WeaponWielderComponent* wielder = entity.try_get()) { - auto& wielderComponent = entity->GetComponent(); - Nz::Vector2f weaponOffset = wielderComponent.GetWeaponOffset(); + Nz::Vector2f weaponOffset = wielder->GetWeaponOffset(); if (!controlledEntity->IsFacingRight()) weaponOffset.x = -weaponOffset.x; originPosition += weaponOffset; } - else if (entity->HasComponent()) + else if (Nz::GraphicsComponent* gfxComponent = entity.try_get()) { - originPosition = Nz::Vector2f(entity->GetComponent().GetAABB().GetCenter()); - lookSwitch = originPosition.x; + //originPosition = Nz::Vector2f(gfxComponent->GetAABB().GetCenter()); + //lookSwitch = originPosition.x; } Nz::Vector2f mousePosition = Nz::Vector2f(Nz::Mouse::GetPosition(m_window)); diff --git a/src/ClientLib/LayerVisualEntity.cpp b/src/ClientLib/LayerVisualEntity.cpp index 4ac55fd1..8b1bf5e8 100644 --- a/src/ClientLib/LayerVisualEntity.cpp +++ b/src/ClientLib/LayerVisualEntity.cpp @@ -121,7 +121,7 @@ namespace bw boundingVolume.Update(Nz::Matrix4f::ConcatenateTransform(worldMatrix, r.offsetMatrix)); if (first) - aabb.Set(boundingVolume.aabb); + aabb = boundingVolume.aabb; else aabb.ExtendTo(boundingVolume.aabb); @@ -145,7 +145,7 @@ namespace bw boundingVolume.Update(Nz::Matrix4f::ConcatenateTransform(s_coordinateMatrix, r.offsetMatrix)); if (first) - aabb.Set(boundingVolume.aabb); + aabb = boundingVolume.aabb; else aabb.ExtendTo(boundingVolume.aabb); diff --git a/src/ClientLib/LocalPlayerInputController.cpp b/src/ClientLib/LocalPlayerInputController.cpp index 240a56c2..f3ea28a8 100644 --- a/src/ClientLib/LocalPlayerInputController.cpp +++ b/src/ClientLib/LocalPlayerInputController.cpp @@ -12,7 +12,7 @@ namespace bw std::optional LocalPlayerInputController::GenerateInputs(entt::handle entity) const { assert(entity); - LocalPlayerControlledComponent* controlledComponent = registry.try_get(entity); + LocalPlayerControlledComponent* controlledComponent = entity.try_get(); if (!controlledComponent) return std::nullopt; //< Don't override inputs (for non-local player controlled entities) diff --git a/src/ClientLib/LocalSessionBridge.cpp b/src/ClientLib/LocalSessionBridge.cpp index ea3215e2..7ac82868 100644 --- a/src/ClientLib/LocalSessionBridge.cpp +++ b/src/ClientLib/LocalSessionBridge.cpp @@ -55,7 +55,7 @@ namespace bw { BurgAppComponent& app = m_sessionManager.GetOwner()->GetMatch().GetApp(); - m_sessionInfo.timeSinceLastReceive = static_cast(app.GetAppTime() - m_lastReceiveTime); + m_sessionInfo.timeSinceLastReceive = app.GetAppTime() - m_lastReceiveTime; callback(m_sessionInfo); } diff --git a/src/ClientLib/OptionWidget.cpp b/src/ClientLib/OptionWidget.cpp index 3e2b0b88..eaca533a 100644 --- a/src/ClientLib/OptionWidget.cpp +++ b/src/ClientLib/OptionWidget.cpp @@ -91,12 +91,12 @@ namespace bw BoolOption option; InitOption(option, std::move(keyName), label); - option.optionWidget = Add(); + option.optionWidget = Add(); option.optionWidget->Resize(option.optionWidget->GetPreferredSize()); - option.onStateChangeSlot.Connect(option.optionWidget->OnStateChanged, [this, keyName = option.keyName](const Ndk::CheckboxWidget* checkbox) + option.onStateChangeSlot.Connect(option.optionWidget->OnCheckboxStateUpdate, [this, keyName = option.keyName](const Nz::CheckboxWidget* checkbox, Nz::CheckboxState newState) { - m_updatedValues[keyName] = checkbox->GetState() == Ndk::CheckboxState_Checked; + m_updatedValues[keyName] = newState == Nz::CheckboxState::Checked; }); m_activeSection->options.emplace_back(std::move(option)); @@ -107,7 +107,7 @@ namespace bw FloatOption option; InitOption(option, std::move(keyName), label); - option.optionWidget = Add(); + option.optionWidget = Add(); option.optionWidget->Resize({ 50.f, option.optionWidget->GetPreferredHeight() }); option.optionWidget->SetTextColor(Nz::Color::Black()); @@ -116,19 +116,20 @@ namespace bw return (character >= U'0' && character <= U'9') || (character == U'.') || (character == U'-'); }); - option.onTextChangedSlot.Connect(option.optionWidget->OnTextChanged, [this, keyName = option.keyName, textArea = option.optionWidget](const Ndk::AbstractTextAreaWidget* /*textArea*/, const Nz::String& text) + option.onTextChangedSlot.Connect(option.optionWidget->OnTextChanged, [this, keyName = option.keyName, textArea = option.optionWidget](const Nz::AbstractTextAreaWidget* /*textArea*/, const std::string& text) { if (m_ignoreWidgetUpdate) return; - double value; - if (text.ToDouble(&value)) + char* end; + double value = std::strtod(text.c_str(), &end); + if (end != text.c_str()) m_updatedValues[keyName] = value; else { // Revert to config value m_ignoreWidgetUpdate = true; - textArea->SetText(Nz::String::Number(m_playerConfig.GetFloatValue(keyName))); + textArea->SetText(std::to_string(m_playerConfig.GetFloatValue(keyName))); m_ignoreWidgetUpdate = false; } }); @@ -141,7 +142,7 @@ namespace bw IntegerOption option; InitOption(option, std::move(keyName), label); - option.optionWidget = Add(); + option.optionWidget = Add(); option.optionWidget->Resize({ 50.f, option.optionWidget->GetPreferredHeight() }); option.optionWidget->SetTextColor(Nz::Color::Black()); @@ -150,19 +151,20 @@ namespace bw return (character >= U'0' && character <= U'9') || (character == U'-'); }); - option.onTextChangedSlot.Connect(option.optionWidget->OnTextChanged, [this, keyName = option.keyName, textArea = option.optionWidget](const Ndk::AbstractTextAreaWidget* /*textArea*/, const Nz::String& text) + option.onTextChangedSlot.Connect(option.optionWidget->OnTextChanged, [this, keyName = option.keyName, textArea = option.optionWidget](const Nz::AbstractTextAreaWidget* /*textArea*/, const std::string& text) { if (m_ignoreWidgetUpdate) return; - long long value; - if (text.ToInteger(&value)) + char* end; + long long value = std::strtoll(text.c_str(), &end, 10); + if (end != text.c_str()) m_updatedValues[keyName] = value; else { // Revert to config value m_ignoreWidgetUpdate = true; - textArea->SetText(Nz::String::Number(m_playerConfig.GetIntegerValue(keyName))); + textArea->SetText(std::to_string(m_playerConfig.GetIntegerValue(keyName))); m_ignoreWidgetUpdate = false; } }); @@ -175,11 +177,11 @@ namespace bw StringOption option; InitOption(option, std::move(keyName), label); - option.optionWidget = Add(); + option.optionWidget = Add(); option.optionWidget->Resize({ 200.f, option.optionWidget->GetPreferredHeight() }); option.optionWidget->SetTextColor(Nz::Color::Black()); - option.onTextChangedSlot.Connect(option.optionWidget->OnTextChanged, [this, keyName = option.keyName, textArea = option.optionWidget](const Ndk::AbstractTextAreaWidget* /*textArea*/, const Nz::String& text) + option.onTextChangedSlot.Connect(option.optionWidget->OnTextChanged, [this, keyName = option.keyName, textArea = option.optionWidget](const Nz::AbstractTextAreaWidget* /*textArea*/, const std::string& text) { if (m_ignoreWidgetUpdate) return; @@ -337,11 +339,11 @@ namespace bw using T = std::decay_t; if constexpr (std::is_same_v) - arg.optionWidget->SetState((m_playerConfig.GetBoolValue(arg.keyName)) ? Ndk::CheckboxState_Checked : Ndk::CheckboxState_Unchecked); + arg.optionWidget->SetState((m_playerConfig.GetBoolValue(arg.keyName)) ? Nz::CheckboxState::Checked : Nz::CheckboxState::Unchecked); else if constexpr (std::is_same_v) - arg.optionWidget->SetText(Nz::String::Number(m_playerConfig.GetFloatValue(arg.keyName))); + arg.optionWidget->SetText(std::to_string(m_playerConfig.GetFloatValue(arg.keyName))); else if constexpr (std::is_same_v) - arg.optionWidget->SetText(Nz::String::Number(m_playerConfig.GetIntegerValue(arg.keyName))); + arg.optionWidget->SetText(std::to_string(m_playerConfig.GetIntegerValue(arg.keyName))); else if constexpr (std::is_same_v) arg.optionWidget->SetText(m_playerConfig.GetStringValue(arg.keyName)); else diff --git a/src/ClientLib/Scoreboard.cpp b/src/ClientLib/Scoreboard.cpp index 9eea32e7..774c43c3 100644 --- a/src/ClientLib/Scoreboard.cpp +++ b/src/ClientLib/Scoreboard.cpp @@ -67,8 +67,8 @@ namespace bw teamData.background = m_contentWidget->Add(); - teamData.line = m_contentWidget->Add(); - teamData.line->SetColor(teamData.color); + //teamData.line = m_contentWidget->Add(); + //teamData.line->SetColor(teamData.color); teamData.widget = m_contentWidget->Add(); teamData.widget->UpdateText(Nz::SimpleTextDrawer::Draw(scoreMenuFont, teamData.name, 24, 0, teamData.color)); @@ -93,7 +93,7 @@ namespace bw playerData.color = color; playerData.teamId = teamId; - Nz::Color playerColor = Nz::Color::White; + Nz::Color playerColor = Nz::Color::White(); if (playerData.color) playerColor = *playerData.color; else if (teamId < m_teams.size()) @@ -147,7 +147,7 @@ namespace bw { playerData->teamId = teamId; - Nz::Color teamColor = Nz::Color::White; + Nz::Color teamColor = Nz::Color::White(); if (teamId < m_teams.size()) teamColor = m_teams[teamId].color; @@ -173,7 +173,7 @@ namespace bw if (valueIndex >= playerData.values.size()) return; - Nz::Color playerColor = Nz::Color::White; + Nz::Color playerColor = Nz::Color::White(); if (playerData.color) playerColor = *playerData.color; else if (playerData.teamId < m_teams.size()) diff --git a/src/ClientLib/Scripting/ClientEditorEntityStore.cpp b/src/ClientLib/Scripting/ClientEditorEntityStore.cpp index 9278cb48..76c96b82 100644 --- a/src/ClientLib/Scripting/ClientEditorEntityStore.cpp +++ b/src/ClientLib/Scripting/ClientEditorEntityStore.cpp @@ -48,7 +48,7 @@ namespace bw entity.emplace(); if (hasInputs) - entity.emplace(std::make_shared()); + entity.emplace(entity, std::make_shared()); return entity; } diff --git a/src/ClientLib/Scripting/ClientElementLibrary.cpp b/src/ClientLib/Scripting/ClientElementLibrary.cpp index b965c931..248db381 100644 --- a/src/ClientLib/Scripting/ClientElementLibrary.cpp +++ b/src/ClientLib/Scripting/ClientElementLibrary.cpp @@ -96,7 +96,7 @@ namespace bw if (std::optional colorParameter = parameters.get_or>("Color", std::nullopt); colorParameter) color = colorParameter.value(); else - color = Nz::Color::White; + color = Nz::Color::White(); //TODO: Don't create a material everytime /*Nz::MaterialRef mat = Nz::Material::New("Translucent2D"); @@ -178,7 +178,7 @@ namespace bw if (std::optional colorParameter = parameters.get_or>("Color", std::nullopt); colorParameter) color = colorParameter.value(); else - color = Nz::Color::White; + color = Nz::Color::White(); float outlineThickness = parameters.get_or("OutlineThickness", 0.f); @@ -205,7 +205,7 @@ namespace bw //if (font) // drawer.SetFont(font); - std::shared_ptr textSprite = Nz::TextSprite::New(); + std::shared_ptr textSprite = std::make_shared(); textSprite->Update(drawer); auto& visualComponent = entity.get(); diff --git a/src/ClientLib/Scripting/ClientEntityLibrary.cpp b/src/ClientLib/Scripting/ClientEntityLibrary.cpp index f2b23232..69897bfb 100644 --- a/src/ClientLib/Scripting/ClientEntityLibrary.cpp +++ b/src/ClientLib/Scripting/ClientEntityLibrary.cpp @@ -57,7 +57,7 @@ namespace bw Nz::Vector2f parallaxFactor = parameters.get_or("ParallaxFactor", Nz::Vector2f::Unit()); Nz::Vector2f scale = parameters.get_or("Scale", Nz::Vector2f::Unit()); - auto& visibleLayer = entity.get_or_emplace(clientMatch.GetRenderWorld()); + auto& visibleLayer = entity.get_or_emplace(clientMatch.GetRenderWorld(), entity); visibleLayer.RegisterLocalLayer(clientMatch.GetLayer(layerIndex), renderOrder, scale, parallaxFactor); }); @@ -77,7 +77,7 @@ namespace bw if (materials.empty()) return {}; - /*Nz::TileMapRef tileMap = Nz::TileMap::New(mapSize, cellSize, materials.size()); + /*std::shared_ptr tileMap = Nz::TileMap::New(mapSize, cellSize, materials.size()); for (auto&& [materialPath, matIndex] : materials) { Nz::MaterialRef material = Nz::Material::New(); //< FIXME diff --git a/src/ClientLib/Scripting/ClientEntityStore.cpp b/src/ClientLib/Scripting/ClientEntityStore.cpp index e9d36679..344bb03f 100644 --- a/src/ClientLib/Scripting/ClientEntityStore.cpp +++ b/src/ClientLib/Scripting/ClientEntityStore.cpp @@ -10,7 +10,7 @@ namespace bw { - std::optional ClientEntityStore::InstantiateEntity(ClientLayer& layer, std::size_t elementIndex, Nz::UInt32 serverId, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, const PropertyValueMap& properties, entt::entity parentEntity) const + std::optional ClientEntityStore::InstantiateEntity(ClientLayer& layer, std::size_t elementIndex, Nz::UInt32 serverId, EntityId uniqueId, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, float scale, const PropertyValueMap& properties, entt::handle parentEntity) const { entt::handle entity = ClientEditorEntityStore::InstantiateEntity(layer.GetWorld(), elementIndex, position, rotation, scale, properties, parentEntity); if (!entity) diff --git a/src/ClientLib/Scripting/ClientScriptingLibrary.cpp b/src/ClientLib/Scripting/ClientScriptingLibrary.cpp index e18bb523..9ad8bf6d 100644 --- a/src/ClientLib/Scripting/ClientScriptingLibrary.cpp +++ b/src/ClientLib/Scripting/ClientScriptingLibrary.cpp @@ -15,8 +15,8 @@ #include #include #include -#include -#include +//#include +//#include namespace bw { diff --git a/src/ClientLib/Scripting/Music.cpp b/src/ClientLib/Scripting/Music.cpp index 98d06b71..eb50c3e6 100644 --- a/src/ClientLib/Scripting/Music.cpp +++ b/src/ClientLib/Scripting/Music.cpp @@ -3,13 +3,13 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include #include #include namespace bw { - Music::Music(ClientEditorApp& app, Nz::Music music) : + Music::Music(ClientEditorAppComponent& app, Nz::Music music) : m_music(std::move(music)) { auto& playerSettings = app.GetPlayerSettings(); diff --git a/src/CoreLib/NetworkReactor.cpp b/src/CoreLib/NetworkReactor.cpp index e3f93a3d..490f1004 100644 --- a/src/CoreLib/NetworkReactor.cpp +++ b/src/CoreLib/NetworkReactor.cpp @@ -329,7 +329,7 @@ namespace bw auto& peerInfo = newEvent.data.emplace(); peerInfo.callback = std::move(arg.callback); - peerInfo.peerInfo.timeSinceLastReceive = m_host.GetServiceTime() - peer->GetLastReceiveTime(); + peerInfo.peerInfo.timeSinceLastReceive = Nz::Time::Milliseconds(m_host.GetServiceTime() - peer->GetLastReceiveTime()); peerInfo.peerInfo.ping = peer->GetRoundTripTime(); peerInfo.peerInfo.totalByteReceived = peer->GetTotalByteReceived(); peerInfo.peerInfo.totalByteSent = peer->GetTotalByteSent(); diff --git a/src/CoreLib/Scripting/SharedElementLibrary.cpp b/src/CoreLib/Scripting/SharedElementLibrary.cpp index 25930895..090bd072 100644 --- a/src/CoreLib/Scripting/SharedElementLibrary.cpp +++ b/src/CoreLib/Scripting/SharedElementLibrary.cpp @@ -9,8 +9,8 @@ #include #include #include -//#include -#include +#include +#include #include namespace bw @@ -147,7 +147,7 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - //entity->AddComponent(lifetime); + entity.emplace(Nz::Time::Seconds(lifetime)); }); elementMetatable["SetScale"] = LuaFunction([&](const sol::table& entityTable, float scale) diff --git a/src/MapEditor/Logic/TileMapEditorMode.cpp b/src/MapEditor/Logic/TileMapEditorMode.cpp index 047e60db..d6bf2798 100644 --- a/src/MapEditor/Logic/TileMapEditorMode.cpp +++ b/src/MapEditor/Logic/TileMapEditorMode.cpp @@ -104,7 +104,7 @@ namespace bw else { canvas->SetCursor(Nz::SystemCursor_Default); - m_hoveringTileSprite->SetColor(Nz::Color::White); + m_hoveringTileSprite->SetColor(Nz::Color::White()); } } diff --git a/src/MapEditor/Logic/TileMapEditorMode.hpp b/src/MapEditor/Logic/TileMapEditorMode.hpp index 8563b9a9..3bad78c7 100644 --- a/src/MapEditor/Logic/TileMapEditorMode.hpp +++ b/src/MapEditor/Logic/TileMapEditorMode.hpp @@ -77,7 +77,7 @@ namespace bw EntityOwner m_tilemapEntity; Nz::CursorRef m_eraserCursor; std::shared_ptr m_hoveringTileSprite; - Nz::TileMapRef m_tileMap; + std::shared_ptr m_tileMap; EditionMode m_editionMode; TileMapData m_tilemapData; QDockWidget* m_tileEditorWidget; diff --git a/src/MapEditor/Widgets/EditorWindow.cpp b/src/MapEditor/Widgets/EditorWindow.cpp index 03c17c74..f3841789 100644 --- a/src/MapEditor/Widgets/EditorWindow.cpp +++ b/src/MapEditor/Widgets/EditorWindow.cpp @@ -53,7 +53,7 @@ namespace bw } EditorWindow::EditorWindow(int argc, char* argv[]) : - ClientEditorApp(argc, argv, LogSide::Editor, m_configFile), + ClientEditorAppComponent(argc, argv, LogSide::Editor, m_configFile), m_entityInfoDialog(nullptr), m_canvas(nullptr), m_playWindow(nullptr), diff --git a/src/MapEditor/Widgets/EditorWindow.hpp b/src/MapEditor/Widgets/EditorWindow.hpp index dcc8d4bd..a3654382 100644 --- a/src/MapEditor/Widgets/EditorWindow.hpp +++ b/src/MapEditor/Widgets/EditorWindow.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include #include @@ -37,7 +37,7 @@ namespace bw class ScriptingContext; class VirtualDirectory; - class EditorWindow : public ClientEditorApp, public QMainWindow + class EditorWindow : public ClientEditorAppComponent, public QMainWindow { public: EditorWindow(int argc, char* argv[]); diff --git a/src/MapEditor/Widgets/PlayWindow.cpp b/src/MapEditor/Widgets/PlayWindow.cpp index e49c2dbc..ae4e24ff 100644 --- a/src/MapEditor/Widgets/PlayWindow.cpp +++ b/src/MapEditor/Widgets/PlayWindow.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include #include #include #include @@ -15,7 +15,7 @@ namespace bw { - PlayWindow::PlayWindow(ClientEditorApp& app, Map map, float tickRate, QWidget* parent) : + PlayWindow::PlayWindow(ClientEditorAppComponent& app, Map map, float tickRate, QWidget* parent) : NazaraCanvas(parent), m_canvas(m_world.CreateHandle(), GetEventHandler(), GetCursorController().CreateHandle()) { diff --git a/src/MapEditor/Widgets/PlayWindow.hpp b/src/MapEditor/Widgets/PlayWindow.hpp index 0eec6c04..990b54c4 100644 --- a/src/MapEditor/Widgets/PlayWindow.hpp +++ b/src/MapEditor/Widgets/PlayWindow.hpp @@ -15,14 +15,14 @@ namespace bw { - class ClientEditorApp; + class ClientEditorAppComponent; class Map; class VirtualDirectory; class PlayWindow : public NazaraCanvas { public: - PlayWindow(ClientEditorApp& app, Map map, float tickRate, QWidget* parent = nullptr); + PlayWindow(ClientEditorAppComponent& app, Map map, float tickRate, QWidget* parent = nullptr); ~PlayWindow() = default; private: diff --git a/src/MapEditor/Widgets/TileSelectionWidget.cpp b/src/MapEditor/Widgets/TileSelectionWidget.cpp index c01f6f29..3c8d4c89 100644 --- a/src/MapEditor/Widgets/TileSelectionWidget.cpp +++ b/src/MapEditor/Widgets/TileSelectionWidget.cpp @@ -32,18 +32,18 @@ namespace bw m_tileSelectionCanvas = new ScrollCanvas; WorldCanvas* worldCanvas = m_tileSelectionCanvas->GetWorldCanvas(); - Nz::EventHandler& eventHandler = worldCanvas->GetEventHandler(); - eventHandler.OnMouseButtonPressed.Connect([this](const Nz::EventHandler*, const Nz::WindowEvent::MouseButtonEvent& mouseEvent) + Nz::WindowEventHandler& eventHandler = worldCanvas->GetEventHandler(); + eventHandler.OnMouseButtonPressed.Connect([this](const Nz::WindowEventHandler*, const Nz::WindowEvent::MouseButtonEvent& mouseEvent) { OnMouseButtonPressed(mouseEvent); }); - eventHandler.OnMouseButtonReleased.Connect([this](const Nz::EventHandler*, const Nz::WindowEvent::MouseButtonEvent& mouseEvent) + eventHandler.OnMouseButtonReleased.Connect([this](const Nz::WindowEventHandler*, const Nz::WindowEvent::MouseButtonEvent& mouseEvent) { OnMouseButtonReleased(mouseEvent); }); - eventHandler.OnMouseMoved.Connect([this](const Nz::EventHandler*, const Nz::WindowEvent::MouseMoveEvent& mouseEvent) + eventHandler.OnMouseMoved.Connect([this](const Nz::WindowEventHandler*, const Nz::WindowEvent::MouseMoveEvent& mouseEvent) { OnMouseMoved(mouseEvent); }); @@ -63,7 +63,7 @@ namespace bw } //unsigned int tileMapSide = static_cast(std::ceil(std::sqrt(tileData.size() + 1))); - Nz::TileMapRef tileMap = Nz::TileMap::New(mapSize, m_tileSize, tilesetGroup.materials.size()); + std::shared_ptr tileMap = Nz::TileMap::New(mapSize, m_tileSize, tilesetGroup.materials.size()); Nz::Vector2ui tileCursor = Nz::Vector2ui::Zero(); diff --git a/src/MapEditor/Widgets/WorldCanvas.cpp b/src/MapEditor/Widgets/WorldCanvas.cpp index 6473085e..217fc44a 100644 --- a/src/MapEditor/Widgets/WorldCanvas.cpp +++ b/src/MapEditor/Widgets/WorldCanvas.cpp @@ -19,44 +19,44 @@ namespace bw Ndk::RenderSystem& renderSystem = m_world.AddSystem(); renderSystem.SetGlobalUp(Nz::Vector3f::Down()); - Nz::EventHandler& eventHandler = GetEventHandler(); + Nz::WindowEventHandler& eventHandler = GetEventHandler(); - eventHandler.OnKeyPressed.Connect([this](const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& keyEvent) + eventHandler.OnKeyPressed.Connect([this](const Nz::WindowEventHandler*, const Nz::WindowEvent::KeyEvent& keyEvent) { OnKeyPressed(keyEvent); }); - eventHandler.OnKeyReleased.Connect([this](const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& keyEvent) + eventHandler.OnKeyReleased.Connect([this](const Nz::WindowEventHandler*, const Nz::WindowEvent::KeyEvent& keyEvent) { OnKeyReleased(keyEvent); }); - eventHandler.OnMouseButtonPressed.Connect([this](const Nz::EventHandler*, const Nz::WindowEvent::MouseButtonEvent& mouseButton) + eventHandler.OnMouseButtonPressed.Connect([this](const Nz::WindowEventHandler*, const Nz::WindowEvent::MouseButtonEvent& mouseButton) { OnMouseButtonPressed(mouseButton); }); - eventHandler.OnMouseButtonReleased.Connect([this](const Nz::EventHandler*, const Nz::WindowEvent::MouseButtonEvent& mouseButton) + eventHandler.OnMouseButtonReleased.Connect([this](const Nz::WindowEventHandler*, const Nz::WindowEvent::MouseButtonEvent& mouseButton) { OnMouseButtonReleased(mouseButton); }); - eventHandler.OnMouseEntered.Connect([this](const Nz::EventHandler*) + eventHandler.OnMouseEntered.Connect([this](const Nz::WindowEventHandler*) { OnMouseEntered(); }); - eventHandler.OnMouseLeft.Connect([this](const Nz::EventHandler*) + eventHandler.OnMouseLeft.Connect([this](const Nz::WindowEventHandler*) { OnMouseLeft(); }); - eventHandler.OnMouseMoved.Connect([this](const Nz::EventHandler*, const Nz::WindowEvent::MouseMoveEvent& mouseMoved) + eventHandler.OnMouseMoved.Connect([this](const Nz::WindowEventHandler*, const Nz::WindowEvent::MouseMoveEvent& mouseMoved) { OnMouseMoved(mouseMoved); }); - eventHandler.OnMouseWheelMoved.Connect([this](const Nz::EventHandler*, const Nz::WindowEvent::MouseWheelEvent& mouseWheel) + eventHandler.OnMouseWheelMoved.Connect([this](const Nz::WindowEventHandler*, const Nz::WindowEvent::MouseWheelEvent& mouseWheel) { OnMouseWheelMoved(mouseWheel); }); diff --git a/xmake.lua b/xmake.lua index d8d8ce36..3298e78f 100644 --- a/xmake.lua +++ b/xmake.lua @@ -10,7 +10,7 @@ set_version("0.2.0") add_repositories("nazara-engine-repo https://github.com/NazaraEngine/xmake-repo") -add_requires("cxxopts", "concurrentqueue", "entt 3.10.1", "hopscotch-map", "nlohmann_json", "tl_expected", "tl_function_ref") +add_requires("cxxopts", "concurrentqueue", "entt 3.11.1", "hopscotch-map", "nlohmann_json", "tl_expected", "tl_function_ref") add_requires("fmt", { configs = { header_only = false, pic = true } }) add_requires("libcurl", { optional = true }) add_requires("nazaraengine", { configs = { debug = is_mode("debug", "asan"), shared = true } }) From 2938938e8e8d92716ad6ed0625d2ae5e9d16b7bc Mon Sep 17 00:00:00 2001 From: SirLynix Date: Tue, 18 Jul 2023 18:13:28 +0200 Subject: [PATCH 11/17] WIP --- include/ClientLib/Camera.hpp | 7 +- include/ClientLib/ClientEditorLayer.hpp | 12 +- include/ClientLib/ClientMatch.hpp | 18 +- include/ClientLib/ClientMatch.inl | 4 +- .../Components/VisibleLayerComponent.hpp | 9 +- .../Components/VisibleLayerComponent.inl | 2 +- include/ClientLib/HttpDownloadManager.hpp | 6 +- .../ClientLib/Scripting/ClientWeaponStore.hpp | 2 +- include/ClientLib/Scripting/Music.hpp | 12 +- include/ClientLib/Scripting/Music.inl | 22 +- include/ClientLib/Scripting/ParticleGroup.hpp | 2 +- include/ClientLib/Scripting/Sound.hpp | 2 +- .../ClientLib/Systems/FrameCallbackSystem.hpp | 1 + .../Systems/PostFrameCallbackSystem.hpp | 1 + .../Systems/VisualInterpolationSystem.hpp | 1 + include/ClientLib/VisualEntity.hpp | 16 +- include/ClientLib/VisualEntity.inl | 10 +- .../CoreLib/BasicPlayerMovementController.hpp | 4 +- include/CoreLib/BurgAppComponent.hpp | 12 +- include/CoreLib/BurgAppComponent.inl | 7 +- .../Components/CollisionDataComponent.hpp | 6 +- .../Components/ConstraintComponent2D.hpp | 6 +- .../Components/ConstraintComponent2D.inl | 12 +- include/CoreLib/EntityOwner.hpp | 7 +- include/CoreLib/EntityOwner.inl | 13 +- include/CoreLib/MasterServerEntry.hpp | 8 +- .../NoclipPlayerMovementController.hpp | 2 +- include/CoreLib/PlayerMovementController.hpp | 8 +- .../CoreLib/Protocol/CompressedInteger.hpp | 4 + include/CoreLib/Scripting/Constraint.hpp | 16 +- include/CoreLib/Scripting/Constraint.inl | 8 +- .../CoreLib/Scripting/ServerEntityLibrary.hpp | 1 + .../CoreLib/Scripting/SharedEntityLibrary.hpp | 2 +- include/CoreLib/SharedLayer.hpp | 4 +- include/CoreLib/SharedLayer.inl | 4 +- include/CoreLib/WebRequest.hpp | 72 --- include/CoreLib/WebRequest.inl | 45 -- include/CoreLib/WebRequestResult.hpp | 54 --- include/CoreLib/WebRequestResult.inl | 49 -- include/CoreLib/WebService.hpp | 60 --- include/CoreLib/WebService.inl | 24 - .../{ClientApp.cpp => ClientAppComponent.cpp} | 74 +-- .../{ClientApp.hpp => ClientAppComponent.hpp} | 22 +- .../{ClientApp.inl => ClientAppComponent.inl} | 4 +- src/Client/ClientAppConfig.cpp | 4 +- src/Client/ClientAppConfig.hpp | 4 +- src/Client/States/AbstractState.cpp | 16 +- src/Client/States/AbstractState.hpp | 14 +- src/Client/States/AbstractState.inl | 8 +- src/Client/States/BackgroundState.cpp | 37 +- src/Client/States/BackgroundState.hpp | 6 +- .../States/Game/AuthenticationState.cpp | 12 +- .../States/Game/AuthenticationState.hpp | 2 +- src/Client/States/Game/CancelableState.cpp | 16 +- src/Client/States/Game/CancelableState.hpp | 13 +- src/Client/States/Game/ConnectedState.cpp | 60 +-- src/Client/States/Game/ConnectedState.hpp | 12 +- .../States/Game/ConnectionLostState.cpp | 8 +- .../States/Game/ConnectionLostState.hpp | 4 +- src/Client/States/Game/ConnectionState.cpp | 38 +- src/Client/States/Game/ConnectionState.hpp | 4 +- src/Client/States/Game/GameState.cpp | 10 +- src/Client/States/Game/GameState.hpp | 10 +- .../States/Game/ResourceDownloadState.cpp | 126 ++---- .../States/Game/ResourceDownloadState.hpp | 3 +- src/Client/States/Game/ServerState.cpp | 8 +- src/Client/States/Game/ServerState.hpp | 4 +- src/Client/States/Game/StatusState.cpp | 10 +- src/Client/States/Game/StatusState.hpp | 4 +- src/Client/States/JoinServerState.cpp | 27 +- src/Client/States/JoinServerState.hpp | 9 +- src/Client/States/MainMenuState.cpp | 10 +- src/Client/States/MainMenuState.hpp | 7 +- src/Client/States/OptionState.cpp | 10 +- src/Client/States/OptionState.hpp | 6 +- src/Client/States/ServerListState.cpp | 78 ++-- src/Client/States/ServerListState.hpp | 15 +- src/Client/States/StartServerState.cpp | 48 +- src/Client/States/StartServerState.hpp | 14 +- src/Client/States/StateData.hpp | 19 +- src/Client/main.cpp | 26 +- src/ClientLib/Camera.cpp | 33 +- src/ClientLib/ClientEditorAppComponent.cpp | 2 +- src/ClientLib/ClientEditorLayer.cpp | 61 +-- src/ClientLib/ClientLayer.cpp | 6 +- src/ClientLib/ClientLayerEntity.cpp | 16 +- src/ClientLib/ClientMatch.cpp | 40 +- src/ClientLib/EscapeMenu.cpp | 4 +- src/ClientLib/HttpDownloadManager.cpp | 14 +- src/ClientLib/LayerVisualEntity.cpp | 10 +- .../Scripting/ClientEditorEntityStore.cpp | 2 +- .../Scripting/ClientElementLibrary.cpp | 22 +- .../Scripting/ClientEntityLibrary.cpp | 44 +- .../Scripting/ClientScriptingLibrary.cpp | 65 ++- .../Scripting/ClientWeaponLibrary.cpp | 17 +- src/ClientLib/Scripting/ClientWeaponStore.cpp | 24 +- src/ClientLib/Scripting/Music.cpp | 40 +- src/ClientLib/Scripting/ParticleGroup.cpp | 28 +- src/ClientLib/Scripting/Sound.cpp | 2 +- src/ClientLib/Scripting/Sprite.cpp | 16 +- src/ClientLib/Scripting/Text.cpp | 3 +- src/ClientLib/SoundEntity.cpp | 17 +- src/ClientLib/Systems/FrameCallbackSystem.cpp | 2 +- .../Systems/PostFrameCallbackSystem.cpp | 2 +- src/ClientLib/Systems/SoundSystem.cpp | 6 +- .../Systems/VisualInterpolationSystem.cpp | 9 +- src/ClientLib/VisualEntity.cpp | 73 ++- src/CoreLib/BasicPlayerMovementController.cpp | 8 +- src/CoreLib/BurgAppComponent.cpp | 68 +-- .../Components/CollisionDataComponent.cpp | 18 +- src/CoreLib/MasterServerEntry.cpp | 28 +- src/CoreLib/Match.cpp | 8 +- .../NoclipPlayerMovementController.cpp | 6 +- src/CoreLib/Player.cpp | 6 +- src/CoreLib/PlayerMovementController.cpp | 2 +- .../Scripting/AbstractScriptingLibrary.cpp | 2 +- src/CoreLib/Scripting/Constraint.cpp | 18 +- src/CoreLib/Scripting/ScriptingContext.cpp | 2 + .../Scripting/ServerElementLibrary.cpp | 6 +- src/CoreLib/Scripting/ServerEntityLibrary.cpp | 16 + src/CoreLib/Scripting/ServerEntityStore.cpp | 2 +- src/CoreLib/Scripting/SharedEntityLibrary.cpp | 58 +-- .../Scripting/SharedScriptingLibrary.cpp | 4 +- src/CoreLib/SharedLayer.cpp | 6 +- src/CoreLib/SharedMatch.cpp | 2 + src/CoreLib/Systems/NetworkSyncSystem.cpp | 10 +- src/CoreLib/Systems/PlayerMovementSystem.cpp | 20 +- src/CoreLib/TerrainLayer.cpp | 2 +- src/CoreLib/WebRequest.cpp | 151 ------- src/CoreLib/WebRequestResult.cpp | 46 -- src/CoreLib/WebService.cpp | 166 ------- src/MapEditor/Components/CanvasComponent.cpp | 10 - src/MapEditor/Components/CanvasComponent.hpp | 5 +- src/MapEditor/Gizmos/CameraMovement.cpp | 5 +- src/MapEditor/Gizmos/CameraMovement.hpp | 3 +- src/MapEditor/Gizmos/EditorGizmo.cpp | 55 +-- src/MapEditor/Gizmos/EditorGizmo.hpp | 4 +- src/MapEditor/Gizmos/EditorGizmo.inl | 2 +- src/MapEditor/Gizmos/PositionGizmo.cpp | 40 +- src/MapEditor/Logic/EditorMode.hpp | 2 +- src/MapEditor/Widgets/EditorWindow.cpp | 6 +- src/MapEditor/Widgets/EditorWindow.hpp | 1 - src/MapEditor/Widgets/EditorWindowPrefabs.hpp | 1 - src/MapEditor/Widgets/EntityInfoDialog.hpp | 4 +- src/MapEditor/Widgets/MapCanvas.cpp | 24 +- src/MapEditor/Widgets/MapCanvas.hpp | 7 +- src/MapEditor/Widgets/NazaraCanvas.cpp | 78 ++-- src/MapEditor/Widgets/NazaraCanvas.hpp | 7 +- src/MapEditor/Widgets/ScrollCanvas.hpp | 1 - src/MapEditor/Widgets/WorldCanvas.cpp | 6 +- src/MapEditor/Widgets/WorldCanvas.hpp | 3 +- src/MapTool/main.cpp | 2 +- src/Server/ServerAppComponent.cpp | 6 + src/Server/main.cpp | 5 + xmake-requires.lock | 420 ------------------ xmake.lua | 14 +- 156 files changed, 1115 insertions(+), 2166 deletions(-) delete mode 100644 include/CoreLib/WebRequest.hpp delete mode 100644 include/CoreLib/WebRequest.inl delete mode 100644 include/CoreLib/WebRequestResult.hpp delete mode 100644 include/CoreLib/WebRequestResult.inl delete mode 100644 include/CoreLib/WebService.hpp delete mode 100644 include/CoreLib/WebService.inl rename src/Client/{ClientApp.cpp => ClientAppComponent.cpp} (57%) rename src/Client/{ClientApp.hpp => ClientAppComponent.hpp} (56%) rename src/Client/{ClientApp.inl => ClientAppComponent.inl} (65%) delete mode 100644 src/CoreLib/WebRequest.cpp delete mode 100644 src/CoreLib/WebRequestResult.cpp delete mode 100644 src/CoreLib/WebService.cpp delete mode 100644 src/MapEditor/Components/CanvasComponent.cpp delete mode 100644 xmake-requires.lock diff --git a/include/ClientLib/Camera.hpp b/include/ClientLib/Camera.hpp index 715bfd36..412f57e6 100644 --- a/include/ClientLib/Camera.hpp +++ b/include/ClientLib/Camera.hpp @@ -15,6 +15,11 @@ #include #include +namespace Nz +{ + class EnttWorld; +} + namespace bw { class Camera; @@ -24,7 +29,7 @@ namespace bw class BURGWAR_CLIENTLIB_API Camera : public Nz::HandledObject { public: - Camera(entt::registry& registry, Nz::RenderTarget* renderTarget, bool perspective); + Camera(Nz::EnttWorld& world, Nz::RenderTarget* renderTarget, bool perspective); Camera(const Camera&) = delete; Camera(Camera&&) = delete; ~Camera() = default; diff --git a/include/ClientLib/ClientEditorLayer.hpp b/include/ClientLib/ClientEditorLayer.hpp index a8cfd8cd..a0485ec6 100644 --- a/include/ClientLib/ClientEditorLayer.hpp +++ b/include/ClientLib/ClientEditorLayer.hpp @@ -13,6 +13,11 @@ #include #include +namespace Nz +{ + class EnttSystemGraph; +} + namespace bw { class BURGWAR_CLIENTLIB_API ClientEditorLayer : public SharedLayer, public VisualLayer @@ -27,10 +32,13 @@ namespace bw virtual void PreFrameUpdate(Nz::Time elapsedTime); virtual void PostFrameUpdate(Nz::Time elapsedTime); - void TickUpdate(Nz::Time elapsedTime) override; - ClientEditorLayer& operator=(const ClientEditorLayer&) = delete; ClientEditorLayer& operator=(ClientEditorLayer&&) = delete; + + private: + Nz::EnttSystemGraph m_frameSystemGraph; + Nz::EnttSystemGraph m_preFrameSystemGraph; + Nz::EnttSystemGraph m_postFrameSystemGraph; }; } diff --git a/include/ClientLib/ClientMatch.hpp b/include/ClientLib/ClientMatch.hpp index ba73b365..a5cb8c3d 100644 --- a/include/ClientLib/ClientMatch.hpp +++ b/include/ClientLib/ClientMatch.hpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -54,7 +55,7 @@ namespace bw friend ClientSession; public: - ClientMatch(ClientEditorAppComponent& burgApp, Nz::Window* window, Nz::RenderTarget* renderTarget, Nz::Canvas* canvas, ClientSession& session, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData); + ClientMatch(ClientEditorAppComponent& burgApp, Nz::Window* window, Nz::RenderTarget* renderTarget, Nz::Canvas* canvas, Nz::EnttWorld& renderWorld, ClientSession& session, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData); ClientMatch(const ClientMatch&) = delete; ClientMatch(ClientMatch&&) = delete; ~ClientMatch(); @@ -88,7 +89,7 @@ namespace bw //inline ParticleRegistry& GetParticleRegistry(); //inline const ParticleRegistry& GetParticleRegistry() const; inline ClientPlayer* GetPlayerByIndex(Nz::UInt16 playerIndex); - inline entt::registry& GetRenderWorld(); + inline Nz::EnttWorld& GetRenderWorld(); std::shared_ptr GetSharedGamemode() const override; ClientWeaponStore& GetWeaponStore() override; const ClientWeaponStore& GetWeaponStore() const override; @@ -245,17 +246,6 @@ namespace bw std::vector layers; }; - struct RenderWorld - { - RenderWorld() : - systemGraph(registry) - { - } - - entt::registry registry; - Nz::EnttSystemGraph systemGraph; - }; - struct TickPrediction { Nz::UInt16 serverTick; @@ -297,8 +287,8 @@ namespace bw std::vector m_tickPredictions; Nz::Canvas* m_canvas; entt::handle m_currentLayer; - RenderWorld m_renderWorld; EntityId m_freeClientId; + Nz::EnttWorld& m_renderWorld; Nz::RenderTarget* m_renderTarget; Nz::Window* m_window; Nz::UInt16 m_activeLayerIndex; diff --git a/include/ClientLib/ClientMatch.inl b/include/ClientLib/ClientMatch.inl index 64dfc92d..6c856b3c 100644 --- a/include/ClientLib/ClientMatch.inl +++ b/include/ClientLib/ClientMatch.inl @@ -112,9 +112,9 @@ namespace bw return &m_matchPlayers[playerIndex].value(); } - inline entt::registry& ClientMatch::GetRenderWorld() + inline Nz::EnttWorld& ClientMatch::GetRenderWorld() { - return m_renderWorld.registry; + return m_renderWorld; } inline void ClientMatch::Quit() diff --git a/include/ClientLib/Components/VisibleLayerComponent.hpp b/include/ClientLib/Components/VisibleLayerComponent.hpp index 202b86f6..68da3b14 100644 --- a/include/ClientLib/Components/VisibleLayerComponent.hpp +++ b/include/ClientLib/Components/VisibleLayerComponent.hpp @@ -17,6 +17,11 @@ #include #include +namespace Nz +{ + class EnttWorld; +} + namespace bw { class ClientLayerEntity; @@ -24,7 +29,7 @@ namespace bw class BURGWAR_CLIENTLIB_API VisibleLayerComponent : public BaseComponent { public: - inline VisibleLayerComponent(entt::registry& renderWorld, entt::handle entity); + inline VisibleLayerComponent(Nz::EnttWorld& renderWorld, entt::handle entity); VisibleLayerComponent(VisibleLayerComponent&&) noexcept = default; ~VisibleLayerComponent() = default; @@ -67,7 +72,7 @@ namespace bw //FIXME (shared_ptr => unique_ptr) std::vector> m_visibleLayers; - entt::registry& m_renderWorld; + Nz::EnttWorld& m_renderWorld; }; } diff --git a/include/ClientLib/Components/VisibleLayerComponent.inl b/include/ClientLib/Components/VisibleLayerComponent.inl index f9517608..f3ff990e 100644 --- a/include/ClientLib/Components/VisibleLayerComponent.inl +++ b/include/ClientLib/Components/VisibleLayerComponent.inl @@ -6,7 +6,7 @@ namespace bw { - inline VisibleLayerComponent::VisibleLayerComponent(entt::registry& renderWorld, entt::handle entity) : + inline VisibleLayerComponent::VisibleLayerComponent(Nz::EnttWorld& renderWorld, entt::handle entity) : BaseComponent(entity), m_renderWorld(renderWorld) { diff --git a/include/ClientLib/HttpDownloadManager.hpp b/include/ClientLib/HttpDownloadManager.hpp index 0ececb05..6d771627 100644 --- a/include/ClientLib/HttpDownloadManager.hpp +++ b/include/ClientLib/HttpDownloadManager.hpp @@ -7,7 +7,7 @@ #ifndef BURGWAR_CLIENTLIB_HTTPDOWNLOADMANAGER_HPP #define BURGWAR_CLIENTLIB_HTTPDOWNLOADMANAGER_HPP -#include +#include #include #include #include @@ -23,7 +23,7 @@ namespace bw class BURGWAR_CLIENTLIB_API HttpDownloadManager : public DownloadManager { public: - HttpDownloadManager(const Logger& logger, std::vector baseDownloadUrls, std::size_t maxSimultanousDownload = 2); + HttpDownloadManager(Nz::WebService& webService, const Logger& logger, std::vector baseDownloadUrls, std::size_t maxSimultanousDownload = 2); HttpDownloadManager(const HttpDownloadManager&) = delete; HttpDownloadManager(HttpDownloadManager&&) = delete; ~HttpDownloadManager() = default; @@ -65,8 +65,8 @@ namespace bw std::vector m_downloadList; std::vector m_requests; Nz::ByteArray m_byteArray; + Nz::WebService& m_webService; const Logger& m_logger; - WebService m_webService; }; } diff --git a/include/ClientLib/Scripting/ClientWeaponStore.hpp b/include/ClientLib/Scripting/ClientWeaponStore.hpp index 3252f688..6f790786 100644 --- a/include/ClientLib/Scripting/ClientWeaponStore.hpp +++ b/include/ClientLib/Scripting/ClientWeaponStore.hpp @@ -22,7 +22,7 @@ namespace bw inline ClientWeaponStore(ClientAssetStore& assetStore, const Logger& logger, std::shared_ptr context); ~ClientWeaponStore() = default; - std::optional InstantiateWeapon(ClientLayer& layer, std::size_t elementIndex, Nz::UInt32 serverId, EntityId uniqueId, const PropertyValueMap& properties, entt::entity parent); + std::optional InstantiateWeapon(ClientLayer& layer, std::size_t elementIndex, Nz::UInt32 serverId, EntityId uniqueId, const PropertyValueMap& properties, entt::handle parent); private: void InitializeElementTable(sol::main_table& elementTable) override; diff --git a/include/ClientLib/Scripting/Music.hpp b/include/ClientLib/Scripting/Music.hpp index 57789585..f32ef35a 100644 --- a/include/ClientLib/Scripting/Music.hpp +++ b/include/ClientLib/Scripting/Music.hpp @@ -18,9 +18,9 @@ namespace bw class BURGWAR_CLIENTLIB_API Music { public: - Music(ClientEditorAppComponent& app, Nz::Music music); + Music(ClientEditorAppComponent& app, std::unique_ptr music); Music(const Music&) = delete; - Music(Music&&) noexcept = default; + Music(Music&& music) noexcept; ~Music() = default; inline void EnableLooping(bool loop); @@ -41,12 +41,16 @@ namespace bw inline void Stop(); Music& operator=(const Music&) = delete; - Music& operator=(Music&&) noexcept = default; + Music& operator=(Music&& music) noexcept; private: + void ConnectSignals(); + void DisconnectSignals(); + typename Nz::Signal::ConnectionGuard m_musicVolumeUpdateSlot; - Nz::Music m_music; + std::unique_ptr m_music; + ClientEditorAppComponent& m_app; }; } diff --git a/include/ClientLib/Scripting/Music.inl b/include/ClientLib/Scripting/Music.inl index 893deb2c..26dd5b91 100644 --- a/include/ClientLib/Scripting/Music.inl +++ b/include/ClientLib/Scripting/Music.inl @@ -8,56 +8,56 @@ namespace bw { inline void Music::EnableLooping(bool loop) { - m_music.EnableLooping(loop); + m_music->EnableLooping(loop); } inline Nz::Time Music::GetDuration() const { - return m_music.GetDuration(); + return m_music->GetDuration(); } inline Nz::Time Music::GetPlayingOffset() const { - return m_music.GetPlayingOffset(); + return m_music->GetPlayingOffset(); } inline Nz::UInt64 Music::GetSampleCount() const { - return m_music.GetSampleCount(); + return m_music->GetSampleCount(); } inline Nz::UInt32 Music::GetSampleRate() const { - return m_music.GetSampleRate(); + return m_music->GetSampleRate(); } inline bool Music::IsLooping() const { - return m_music.IsLooping(); + return m_music->IsLooping(); } inline bool Music::IsPlaying() const { - return m_music.GetStatus() == Nz::SoundStatus::Playing; + return m_music->GetStatus() == Nz::SoundStatus::Playing; } inline void Music::Pause() { - m_music.Pause(); + m_music->Pause(); } inline void Music::Play() { - m_music.Play(); + m_music->Play(); } inline void Music::SetPlayingOffset(Nz::Time offset) { - m_music.SetPlayingOffset(offset); + m_music->SeekToPlayingOffset(offset); } inline void Music::Stop() { - m_music.Stop(); + m_music->Stop(); } } diff --git a/include/ClientLib/Scripting/ParticleGroup.hpp b/include/ClientLib/Scripting/ParticleGroup.hpp index c26d7e0f..735dfb22 100644 --- a/include/ClientLib/Scripting/ParticleGroup.hpp +++ b/include/ClientLib/Scripting/ParticleGroup.hpp @@ -18,7 +18,7 @@ namespace bw class BURGWAR_CLIENTLIB_API ParticleGroup { public: - ParticleGroup(const ParticleRegistry& particleRegistry, entt::entity particleGroup); + ParticleGroup(const ParticleRegistry& particleRegistry, entt::handle particleGroup); ParticleGroup(const ParticleGroup&) = delete; ParticleGroup(ParticleGroup&&) noexcept = default; ~ParticleGroup() = default; diff --git a/include/ClientLib/Scripting/Sound.hpp b/include/ClientLib/Scripting/Sound.hpp index be6df55b..34d4869f 100644 --- a/include/ClientLib/Scripting/Sound.hpp +++ b/include/ClientLib/Scripting/Sound.hpp @@ -20,7 +20,7 @@ namespace bw Sound(Sound&&) noexcept = default; ~Sound() = default; - float GetDuration() const; + Nz::Time GetDuration() const; void Stop(); diff --git a/include/ClientLib/Systems/FrameCallbackSystem.hpp b/include/ClientLib/Systems/FrameCallbackSystem.hpp index 0520b9d5..d5972ad8 100644 --- a/include/ClientLib/Systems/FrameCallbackSystem.hpp +++ b/include/ClientLib/Systems/FrameCallbackSystem.hpp @@ -8,6 +8,7 @@ #define BURGWAR_CLIENTLIB_SYSTEMS_FRAMECALLBACKSYSTEM_HPP #include +#include #include #include diff --git a/include/ClientLib/Systems/PostFrameCallbackSystem.hpp b/include/ClientLib/Systems/PostFrameCallbackSystem.hpp index a0136531..616a17a1 100644 --- a/include/ClientLib/Systems/PostFrameCallbackSystem.hpp +++ b/include/ClientLib/Systems/PostFrameCallbackSystem.hpp @@ -8,6 +8,7 @@ #define BURGWAR_CLIENTLIB_SYSTEMS_POSTFRAMECALLBACKSYSTEM_HPP #include +#include #include #include diff --git a/include/ClientLib/Systems/VisualInterpolationSystem.hpp b/include/ClientLib/Systems/VisualInterpolationSystem.hpp index c5df718a..bfbe77f3 100644 --- a/include/ClientLib/Systems/VisualInterpolationSystem.hpp +++ b/include/ClientLib/Systems/VisualInterpolationSystem.hpp @@ -8,6 +8,7 @@ #define BURGWAR_CLIENTLIB_SYSTEMS_VISUALINTERPOLATIONSYSTEM_HPP #include +#include #include namespace bw diff --git a/include/ClientLib/VisualEntity.hpp b/include/ClientLib/VisualEntity.hpp index f68e4ea5..916865c4 100644 --- a/include/ClientLib/VisualEntity.hpp +++ b/include/ClientLib/VisualEntity.hpp @@ -14,6 +14,11 @@ #include #include +namespace Nz +{ + class EnttWorld; +}; + namespace bw { class LayerVisualEntity; @@ -25,8 +30,8 @@ namespace bw friend LayerVisualEntity; public: - VisualEntity(entt::registry& renderWorld, LayerVisualEntityHandle visualEntityHandle, int baseRenderOrder = 0); - VisualEntity(entt::registry& renderWorld, LayerVisualEntityHandle visualEntityHandle, const Nz::Node& parentNode, int baseRenderOrder = 0); + VisualEntity(Nz::EnttWorld& renderWorld, LayerVisualEntityHandle visualEntityHandle, int baseRenderOrder = 0); + VisualEntity(Nz::EnttWorld& renderWorld, LayerVisualEntityHandle visualEntityHandle, const Nz::Node& parentNode, int baseRenderOrder = 0); VisualEntity(const VisualEntity&) = delete; VisualEntity(VisualEntity&& entity) noexcept; ~VisualEntity(); @@ -60,7 +65,14 @@ namespace bw std::shared_ptr renderable; }; + struct Renderable + { + EntityOwner entity; + std::shared_ptr renderable; + }; + std::vector m_hoveringRenderables; + std::vector m_renderables; EntityOwner m_entity; LayerVisualEntityHandle m_visualEntity; int m_baseRenderOrder; diff --git a/include/ClientLib/VisualEntity.inl b/include/ClientLib/VisualEntity.inl index 0858600e..33f46dbd 100644 --- a/include/ClientLib/VisualEntity.inl +++ b/include/ClientLib/VisualEntity.inl @@ -3,6 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include +#include namespace bw { @@ -13,9 +14,14 @@ namespace bw inline void VisualEntity::Enable(bool enable) { + if (enable) + m_entity->remove(); + else + m_entity->emplace_or_replace(); // TODO - /*m_entity->Enable(enable); + /* for (auto& hoveringRenderable : m_hoveringRenderables) - hoveringRenderable.entity->Enable(enable);*/ + hoveringRenderable.entity->Enable(enable); + */ } } diff --git a/include/CoreLib/BasicPlayerMovementController.hpp b/include/CoreLib/BasicPlayerMovementController.hpp index 367804eb..4a37429b 100644 --- a/include/CoreLib/BasicPlayerMovementController.hpp +++ b/include/CoreLib/BasicPlayerMovementController.hpp @@ -18,9 +18,9 @@ namespace bw BasicPlayerMovementController() = default; ~BasicPlayerMovementController() = default; - bool PreSolveCollision(PlayerMovementComponent& playerMovement, entt::entity collisionBody, Nz::Arbiter2D& arbiter) const override; + bool PreSolveCollision(PlayerMovementComponent& playerMovement, entt::entity collisionBody, Nz::ChipmunkArbiter2D& arbiter) const override; - void UpdateVelocity(const PlayerInputData& inputs, PlayerMovementComponent& playerMovement, Nz::RigidBody2D& rigidBody, const Nz::Vector2f& gravity, float damping, float dt) const override; + void UpdateVelocity(const PlayerInputData& inputs, PlayerMovementComponent& playerMovement, Nz::ChipmunkRigidBody2D& rigidBody, const Nz::Vector2f& gravity, float damping, float dt) const override; }; } diff --git a/include/CoreLib/BurgAppComponent.hpp b/include/CoreLib/BurgAppComponent.hpp index 084cbf25..a1ae566d 100644 --- a/include/CoreLib/BurgAppComponent.hpp +++ b/include/CoreLib/BurgAppComponent.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CORELIB_BURGAPP_HPP #include -#include +#include #include #include #include @@ -33,15 +33,13 @@ namespace bw inline Logger& GetLogger(); inline Nz::Time GetLogTime() const; inline const tsl::hopscotch_map>& GetMods() const; - inline WebService& GetWebService(); + inline Nz::WebService& GetWebService(); + + inline bool HasWebService() const; void Update(Nz::Time elapsedTime) override; private: - static void HandleInterruptSignal(const char* signalName); - - void InstallInterruptHandlers(); - Logger m_logger; static BurgAppComponent* s_application; @@ -50,7 +48,7 @@ namespace bw void LoadMods(); const ConfigFile& m_config; - std::optional m_webService; + std::unique_ptr m_webService; tsl::hopscotch_map> m_mods; Nz::Time m_appTime; Nz::Time m_startTime; diff --git a/include/CoreLib/BurgAppComponent.inl b/include/CoreLib/BurgAppComponent.inl index a6b49d5d..1d488499 100644 --- a/include/CoreLib/BurgAppComponent.inl +++ b/include/CoreLib/BurgAppComponent.inl @@ -34,9 +34,14 @@ namespace bw return m_mods; } - inline WebService& BurgAppComponent::GetWebService() + inline Nz::WebService& BurgAppComponent::GetWebService() { assert(m_webService); return *m_webService; } + + inline bool BurgAppComponent::HasWebService() const + { + return m_webService != nullptr; + } } diff --git a/include/CoreLib/Components/CollisionDataComponent.hpp b/include/CoreLib/Components/CollisionDataComponent.hpp index 4554cc96..2af02883 100644 --- a/include/CoreLib/Components/CollisionDataComponent.hpp +++ b/include/CoreLib/Components/CollisionDataComponent.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include namespace bw @@ -26,7 +26,7 @@ namespace bw inline void AddCollider(Collider collider); - std::shared_ptr BuildCollider(float scale = 1.f) const; + std::shared_ptr BuildCollider(float scale = 1.f) const; inline const std::vector& GetColliders() const; @@ -34,7 +34,7 @@ namespace bw CollisionDataComponent& operator=(CollisionDataComponent&&) = default; private: - static std::shared_ptr ToCollider(const Collider& collider, float scale); + static std::shared_ptr ToCollider(const Collider& collider, float scale); std::vector m_colliders; }; diff --git a/include/CoreLib/Components/ConstraintComponent2D.hpp b/include/CoreLib/Components/ConstraintComponent2D.hpp index f3174b47..3480b1e2 100644 --- a/include/CoreLib/Components/ConstraintComponent2D.hpp +++ b/include/CoreLib/Components/ConstraintComponent2D.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include @@ -25,7 +25,7 @@ namespace bw ConstraintComponent2D(ConstraintComponent2D&& joint) noexcept = default; template T* CreateConstraint(entt::registry& registry, entt::entity first, entt::entity second, Args&&... args); - bool RemoveConstraint(Nz::Constraint2D* constraint); + bool RemoveConstraint(Nz::ChipmunkConstraint2D* constraint); ConstraintComponent2D& operator=(const ConstraintComponent2D& joint) = delete; ConstraintComponent2D& operator=(ConstraintComponent2D&& joint) noexcept = default; @@ -34,7 +34,7 @@ namespace bw private: struct ConstraintData { - std::unique_ptr constraint; + std::unique_ptr constraint; NazaraSlot(DestructionWatcherComponent, OnDestruction, onBodyADestruction); NazaraSlot(DestructionWatcherComponent, OnDestruction, onBodyBDestruction); diff --git a/include/CoreLib/Components/ConstraintComponent2D.inl b/include/CoreLib/Components/ConstraintComponent2D.inl index 365fdf87..0ad642d5 100644 --- a/include/CoreLib/Components/ConstraintComponent2D.inl +++ b/include/CoreLib/Components/ConstraintComponent2D.inl @@ -4,25 +4,25 @@ #include #include -#include +#include namespace bw { template T* ConstraintComponent2D::CreateConstraint(entt::registry& registry, entt::entity first, entt::entity second, Args&& ...args) { - auto FetchBody = [&](entt::entity entity) -> Nz::RigidBody2D* + auto FetchBody = [&](entt::entity entity) -> Nz::ChipmunkRigidBody2D* { - if (Nz::RigidBody2DComponent* physBodyA = registry.try_get(entity)) + if (Nz::ChipmunkRigidBody2DComponent* physBodyA = registry.try_get(entity)) return physBodyA; return nullptr; }; - Nz::RigidBody2D* firstBody = FetchBody(first); + Nz::ChipmunkRigidBody2D* firstBody = FetchBody(first); NazaraAssert(firstBody, "First entity has no CollisionComponent2D nor PhysicsComponent2D component"); - Nz::RigidBody2D* secondBody = FetchBody(second); + Nz::ChipmunkRigidBody2D* secondBody = FetchBody(second); NazaraAssert(secondBody, "Second entity has no CollisionComponent2D nor PhysicsComponent2D component"); auto& constraintData = m_constraints.emplace_back(); @@ -47,7 +47,7 @@ namespace bw return static_cast(constraintData.constraint.get()); } - inline bool ConstraintComponent2D::RemoveConstraint(Nz::Constraint2D* constraintPtr) + inline bool ConstraintComponent2D::RemoveConstraint(Nz::ChipmunkConstraint2D* constraintPtr) { auto it = std::find_if(m_constraints.begin(), m_constraints.end(), [constraintPtr](const ConstraintData& constraintData) { return constraintData.constraint.get() == constraintPtr; }); if (it != m_constraints.end()) diff --git a/include/CoreLib/EntityOwner.hpp b/include/CoreLib/EntityOwner.hpp index c2ff133b..1abb8715 100644 --- a/include/CoreLib/EntityOwner.hpp +++ b/include/CoreLib/EntityOwner.hpp @@ -21,9 +21,10 @@ namespace bw inline entt::handle GetEntity() const; - operator entt::handle() const; - entt::handle* operator->(); - const entt::handle* operator->() const; + inline explicit operator bool() const; + inline operator entt::handle() const; + inline entt::handle* operator->(); + inline const entt::handle* operator->() const; EntityOwner& operator=(const EntityOwner&) = delete; inline EntityOwner& operator=(EntityOwner&& entityOwner) noexcept; diff --git a/include/CoreLib/EntityOwner.inl b/include/CoreLib/EntityOwner.inl index 4f3f0d92..be9a1e2e 100644 --- a/include/CoreLib/EntityOwner.inl +++ b/include/CoreLib/EntityOwner.inl @@ -14,11 +14,12 @@ namespace bw inline EntityOwner::EntityOwner(EntityOwner&& entityOwner) noexcept : m_entity(entityOwner.m_entity) { + entityOwner.m_entity = {}; } inline EntityOwner::~EntityOwner() { - if (m_entity.valid()) + if (m_entity) m_entity.destroy(); } @@ -26,7 +27,12 @@ namespace bw { return m_entity; } - + + inline EntityOwner::operator bool() const + { + return bool(m_entity); + } + inline EntityOwner::operator entt::handle() const { return m_entity; @@ -44,8 +50,7 @@ namespace bw inline EntityOwner& EntityOwner::operator=(EntityOwner&& entityOwner) noexcept { - m_entity = entityOwner.m_entity; - + std::swap(m_entity, entityOwner.m_entity); return *this; } } diff --git a/include/CoreLib/MasterServerEntry.hpp b/include/CoreLib/MasterServerEntry.hpp index fe1d402b..e6e0e8e2 100644 --- a/include/CoreLib/MasterServerEntry.hpp +++ b/include/CoreLib/MasterServerEntry.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CORELIB_MASTERSERVERENTRY_HPP #include -#include +#include #include #include #include @@ -23,7 +23,7 @@ namespace bw class BURGWAR_CORELIB_API MasterServerEntry { public: - MasterServerEntry(Match& match, std::string masterServerURL); + MasterServerEntry(Nz::WebService& webService, Match& match, std::string masterServerURL); MasterServerEntry(const MasterServerEntry&) = delete; MasterServerEntry(MasterServerEntry&&) = delete; ~MasterServerEntry() = default; @@ -35,7 +35,7 @@ namespace bw private: nlohmann::json BuildServerInfo() const; - void HandleResponse(WebRequestResult&& result, bool refresh); + void HandleResponse(Nz::WebRequestResult&& result, bool refresh); void Refresh(); void Register(); @@ -43,8 +43,8 @@ namespace bw std::string m_masterServerURL; std::string m_requestBody; std::string m_updateToken; + Nz::WebService& m_webService; Match& m_match; - WebService m_webService; Nz::Time m_timeBeforeRefresh; }; } diff --git a/include/CoreLib/NoclipPlayerMovementController.hpp b/include/CoreLib/NoclipPlayerMovementController.hpp index 6b9afd34..96bb0231 100644 --- a/include/CoreLib/NoclipPlayerMovementController.hpp +++ b/include/CoreLib/NoclipPlayerMovementController.hpp @@ -18,7 +18,7 @@ namespace bw NoclipPlayerMovementController() = default; ~NoclipPlayerMovementController() = default; - void UpdateVelocity(const PlayerInputData& inputs, PlayerMovementComponent& playerMovement, Nz::RigidBody2D& rigidBody, const Nz::Vector2f& gravity, float damping, float dt) const override; + void UpdateVelocity(const PlayerInputData& inputs, PlayerMovementComponent& playerMovement, Nz::ChipmunkRigidBody2D& rigidBody, const Nz::Vector2f& gravity, float damping, float dt) const override; }; } diff --git a/include/CoreLib/PlayerMovementController.hpp b/include/CoreLib/PlayerMovementController.hpp index 030d556d..34e1945d 100644 --- a/include/CoreLib/PlayerMovementController.hpp +++ b/include/CoreLib/PlayerMovementController.hpp @@ -13,8 +13,8 @@ namespace Nz { - class Arbiter2D; - class RigidBody2D; + class ChipmunkArbiter2D; + class ChipmunkRigidBody2D; } namespace bw @@ -28,9 +28,9 @@ namespace bw PlayerMovementController() = default; virtual ~PlayerMovementController(); - virtual bool PreSolveCollision(PlayerMovementComponent& playerMovement, entt::entity collisionBody, Nz::Arbiter2D& arbiter) const; + virtual bool PreSolveCollision(PlayerMovementComponent& playerMovement, entt::entity collisionBody, Nz::ChipmunkArbiter2D& arbiter) const; - virtual void UpdateVelocity(const PlayerInputData& inputs, PlayerMovementComponent& playerMovement, Nz::RigidBody2D& rigidBody, const Nz::Vector2f& gravity, float damping, float dt) const = 0; + virtual void UpdateVelocity(const PlayerInputData& inputs, PlayerMovementComponent& playerMovement, Nz::ChipmunkRigidBody2D& rigidBody, const Nz::Vector2f& gravity, float damping, float dt) const = 0; }; } diff --git a/include/CoreLib/Protocol/CompressedInteger.hpp b/include/CoreLib/Protocol/CompressedInteger.hpp index 0d094a35..b9fac1bf 100644 --- a/include/CoreLib/Protocol/CompressedInteger.hpp +++ b/include/CoreLib/Protocol/CompressedInteger.hpp @@ -8,6 +8,7 @@ #define BURGWAR_CORELIB_NETWORK_COMPRESSEDINTEGER_HPP #include +#include #include namespace bw @@ -57,6 +58,9 @@ namespace bw }; } +template struct fmt::formatter> : formatter {}; +template struct fmt::formatter> : formatter {}; + namespace Nz { template bool Serialize(SerializationContext& context, bw::CompressedSigned value, TypeTag>); diff --git a/include/CoreLib/Scripting/Constraint.hpp b/include/CoreLib/Scripting/Constraint.hpp index 437d914f..977d372e 100644 --- a/include/CoreLib/Scripting/Constraint.hpp +++ b/include/CoreLib/Scripting/Constraint.hpp @@ -8,7 +8,7 @@ #define BURGWAR_CORELIB_SCRIPTING_CONSTRAINT_HPP #include -#include +#include #include namespace bw @@ -16,7 +16,7 @@ namespace bw class BURGWAR_CORELIB_API Constraint { public: - Constraint(entt::handle entity, Nz::Constraint2DHandle constraint); + Constraint(entt::handle entity, Nz::ChipmunkConstraint2DHandle constraint); Constraint(const Constraint&) = delete; Constraint(Constraint&& constraint) noexcept; virtual ~Constraint(); @@ -45,16 +45,16 @@ namespace bw void KillEntity(); private: - NazaraSlot(Nz::HandledObject, OnHandledObjectDestruction, m_onDestruction); + NazaraSlot(Nz::HandledObject, OnHandledObjectDestruction, m_onDestruction); entt::handle m_entity; - Nz::Constraint2DHandle m_constraint; + Nz::ChipmunkConstraint2DHandle m_constraint; }; class BURGWAR_CORELIB_API DampedSpringConstraint : public Constraint { public: - inline DampedSpringConstraint(entt::handle entity, Nz::DampedSpringConstraint2D* constraint); + inline DampedSpringConstraint(entt::handle entity, Nz::ChipmunkDampedSpringConstraint2D* constraint); DampedSpringConstraint(DampedSpringConstraint&&) noexcept = default; ~DampedSpringConstraint() = default; @@ -65,7 +65,7 @@ namespace bw class BURGWAR_CORELIB_API PinConstraint : public Constraint { public: - inline PinConstraint(entt::handle entity, Nz::PinConstraint2D* constraint); + inline PinConstraint(entt::handle entity, Nz::ChipmunkPinConstraint2D* constraint); PinConstraint(PinConstraint&&) noexcept = default; ~PinConstraint() = default; @@ -80,7 +80,7 @@ namespace bw class BURGWAR_CORELIB_API PivotConstraint : public Constraint { public: - inline PivotConstraint(entt::handle entity, Nz::PivotConstraint2D* constraint); + inline PivotConstraint(entt::handle entity, Nz::ChipmunkPivotConstraint2D* constraint); PivotConstraint(PivotConstraint&&) noexcept = default; ~PivotConstraint() = default; @@ -91,7 +91,7 @@ namespace bw class BURGWAR_CORELIB_API RotaryLimitConstraint : public Constraint { public: - inline RotaryLimitConstraint(entt::handle entity, Nz::RotaryLimitConstraint2D* constraint); + inline RotaryLimitConstraint(entt::handle entity, Nz::ChipmunkRotaryLimitConstraint2D* constraint); RotaryLimitConstraint(RotaryLimitConstraint&&) noexcept = default; ~RotaryLimitConstraint() = default; diff --git a/include/CoreLib/Scripting/Constraint.inl b/include/CoreLib/Scripting/Constraint.inl index 247da371..ebdf0235 100644 --- a/include/CoreLib/Scripting/Constraint.inl +++ b/include/CoreLib/Scripting/Constraint.inl @@ -26,22 +26,22 @@ namespace bw return static_cast(m_constraint.GetObject()); } - inline DampedSpringConstraint::DampedSpringConstraint(entt::handle entity, Nz::DampedSpringConstraint2D* constraint) : + inline DampedSpringConstraint::DampedSpringConstraint(entt::handle entity, Nz::ChipmunkDampedSpringConstraint2D* constraint) : Constraint(entity, constraint->CreateHandle()) { } - inline PinConstraint::PinConstraint(entt::handle entity, Nz::PinConstraint2D* constraint) : + inline PinConstraint::PinConstraint(entt::handle entity, Nz::ChipmunkPinConstraint2D* constraint) : Constraint(entity, constraint->CreateHandle()) { } - inline PivotConstraint::PivotConstraint(entt::handle entity, Nz::PivotConstraint2D* constraint) : + inline PivotConstraint::PivotConstraint(entt::handle entity, Nz::ChipmunkPivotConstraint2D* constraint) : Constraint(entity, constraint->CreateHandle()) { } - inline RotaryLimitConstraint::RotaryLimitConstraint(entt::handle entity, Nz::RotaryLimitConstraint2D* constraint) : + inline RotaryLimitConstraint::RotaryLimitConstraint(entt::handle entity, Nz::ChipmunkRotaryLimitConstraint2D* constraint) : Constraint(entity, constraint->CreateHandle()) { } diff --git a/include/CoreLib/Scripting/ServerEntityLibrary.hpp b/include/CoreLib/Scripting/ServerEntityLibrary.hpp index 291eecb5..d678ec48 100644 --- a/include/CoreLib/Scripting/ServerEntityLibrary.hpp +++ b/include/CoreLib/Scripting/ServerEntityLibrary.hpp @@ -23,6 +23,7 @@ namespace bw private: void RegisterServerLibrary(sol::table& elementMetatable); + void InitRigidBody(lua_State* L, entt::handle entity, float mass) override; void SetDirection(lua_State* L, entt::handle entity, const Nz::Vector2f& upVector) override; void SetMass(lua_State* L, entt::handle entity, float mass, bool recomputeMomentOfInertia) override; void SetMomentOfInertia(lua_State* L, entt::handle entity, float momentOfInertia) override; diff --git a/include/CoreLib/Scripting/SharedEntityLibrary.hpp b/include/CoreLib/Scripting/SharedEntityLibrary.hpp index 726f23ce..f77bd8d2 100644 --- a/include/CoreLib/Scripting/SharedEntityLibrary.hpp +++ b/include/CoreLib/Scripting/SharedEntityLibrary.hpp @@ -23,7 +23,7 @@ namespace bw void RegisterLibrary(sol::table& elementMetatable) override; protected: - virtual void InitRigidBody(lua_State* L, entt::handle entity, float mass); + virtual void InitRigidBody(lua_State* L, entt::handle entity, float mass) = 0; virtual void SetDirection(lua_State* L, entt::handle entity, const Nz::Vector2f& upVector); virtual void SetMass(lua_State* L, entt::handle entity, float mass, bool recomputeMomentOfInertia); virtual void SetMomentOfInertia(lua_State* L, entt::handle entity, float momentOfInertia); diff --git a/include/CoreLib/SharedLayer.hpp b/include/CoreLib/SharedLayer.hpp index fefd8585..a63d0f75 100644 --- a/include/CoreLib/SharedLayer.hpp +++ b/include/CoreLib/SharedLayer.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include namespace bw @@ -29,7 +29,7 @@ namespace bw inline LayerIndex GetLayerIndex() const; inline SharedMatch& GetMatch(); - inline Nz::Physics2DSystem& GetPhysicsSystem(); + inline Nz::ChipmunkPhysics2DSystem& GetPhysicsSystem(); inline entt::registry& GetWorld(); inline const entt::registry& GetWorld() const; diff --git a/include/CoreLib/SharedLayer.inl b/include/CoreLib/SharedLayer.inl index 381b00bb..d3f754ec 100644 --- a/include/CoreLib/SharedLayer.inl +++ b/include/CoreLib/SharedLayer.inl @@ -26,9 +26,9 @@ namespace bw return m_match; } - inline Nz::Physics2DSystem& SharedLayer::GetPhysicsSystem() + inline Nz::ChipmunkPhysics2DSystem& SharedLayer::GetPhysicsSystem() { - return m_systemGraph.GetSystem(); + return m_systemGraph.GetSystem(); } inline entt::registry& SharedLayer::GetWorld() diff --git a/include/CoreLib/WebRequest.hpp b/include/CoreLib/WebRequest.hpp deleted file mode 100644 index ede8fccf..00000000 --- a/include/CoreLib/WebRequest.hpp +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#pragma once - -#ifndef BURGWAR_CORELIB_WEBREQUEST_HPP -#define BURGWAR_CORELIB_WEBREQUEST_HPP - -#include -#include -#include -#include -#include -#include -#include - -struct curl_slist; - -namespace bw -{ - class BURGWAR_CORELIB_API WebRequest - { - friend class WebService; - - public: - using DataCallback = std::function; - using ResultCallback = std::function; - - WebRequest(); - WebRequest(const WebRequest&) = delete; - WebRequest(WebRequest&&) = default; - ~WebRequest(); - - void ForceProtocol(Nz::NetProtocol protocol); - - inline void SetDataCallback(DataCallback callback); - inline void SetHeader(std::string header, std::string value); - void SetJSonContent(const std::string_view& encodedJSon); - void SetMaximumFileSize(Nz::UInt64 maxFileSize); - inline void SetResultCallback(ResultCallback callback); - void SetServiceName(const std::string_view& serviceName); - void SetURL(const std::string& url); - - void SetupGet(); - void SetupPost(); - - WebRequest& operator=(const WebRequest&) = delete; - WebRequest& operator=(WebRequest&&) = default; - - static std::unique_ptr Get(const std::string& url, ResultCallback callback = nullptr); - static std::unique_ptr Post(const std::string& url, ResultCallback callback = nullptr); - - private: - inline bool OnBodyResponse(const char* data, std::size_t length); - CURL* Prepare(); - inline void TriggerCallback(); - inline void TriggerCallback(std::string errorMessage); - - Nz::MovablePtr m_curlHandle; - Nz::MovablePtr m_headerList; - std::string m_responseBody; - tsl::hopscotch_map m_headers; - DataCallback m_dataCallback; - ResultCallback m_resultCallback; - bool m_isUserAgentSet; - }; -} - -#include - -#endif diff --git a/include/CoreLib/WebRequest.inl b/include/CoreLib/WebRequest.inl deleted file mode 100644 index 34fccf47..00000000 --- a/include/CoreLib/WebRequest.inl +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - inline void WebRequest::SetDataCallback(DataCallback callback) - { - m_dataCallback = std::move(callback); - } - - inline void WebRequest::SetResultCallback(ResultCallback callback) - { - m_resultCallback = std::move(callback); - } - - inline void WebRequest::SetHeader(std::string header, std::string value) - { - m_headers.insert_or_assign(std::move(header), std::move(value)); - } - - inline bool WebRequest::OnBodyResponse(const char* data, std::size_t length) - { - if (!m_dataCallback) - { - m_responseBody.append(data, length); - return true; - } - - return m_dataCallback(data, length); - } - - inline void WebRequest::TriggerCallback() - { - m_resultCallback(WebRequestResult(m_curlHandle.Get(), std::move(m_responseBody))); - m_responseBody.clear(); - } - - inline void WebRequest::TriggerCallback(std::string errorMessage) - { - m_resultCallback(WebRequestResult(std::move(errorMessage))); - } -} diff --git a/include/CoreLib/WebRequestResult.hpp b/include/CoreLib/WebRequestResult.hpp deleted file mode 100644 index 87c0c583..00000000 --- a/include/CoreLib/WebRequestResult.hpp +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#pragma once - -#ifndef BURGWAR_CORELIB_WEBREQUESTRESULT_HPP -#define BURGWAR_CORELIB_WEBREQUESTRESULT_HPP - -#include -#include -#include -#include -#include - -using CURL = void; - -namespace bw -{ - class BURGWAR_CORELIB_API WebRequestResult - { - friend class WebRequest; - - public: - WebRequestResult(const WebRequestResult&) = delete; - WebRequestResult(WebRequestResult&&) = delete; - ~WebRequestResult() = default; - - inline std::string& GetBody(); - inline const std::string& GetBody() const; - Nz::UInt64 GetDownloadedSize() const; - Nz::UInt64 GetDownloadSpeed() const; - inline const std::string& GetErrorMessage() const; - long GetReponseCode() const; - - inline bool HasSucceeded() const; - - inline explicit operator bool() const; - - WebRequestResult& operator=(const WebRequestResult&) = delete; - WebRequestResult& operator=(WebRequestResult&&) = delete; - - private: - inline WebRequestResult(CURL* curl, std::string body); - inline WebRequestResult(std::string errMessage); - - CURL* m_curlHandle; - std::string m_bodyOrErr; - }; -} - -#include - -#endif diff --git a/include/CoreLib/WebRequestResult.inl b/include/CoreLib/WebRequestResult.inl deleted file mode 100644 index c82ad2ff..00000000 --- a/include/CoreLib/WebRequestResult.inl +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - inline WebRequestResult::WebRequestResult(CURL* curl, std::string body) : - m_curlHandle(curl), - m_bodyOrErr(std::move(body)) - { - } - - inline WebRequestResult::WebRequestResult(std::string errMessage) : - m_curlHandle(nullptr), - m_bodyOrErr(std::move(errMessage)) - { - } - - inline std::string& WebRequestResult::GetBody() - { - assert(HasSucceeded()); - return m_bodyOrErr; - } - - inline const std::string& WebRequestResult::GetBody() const - { - assert(HasSucceeded()); - return m_bodyOrErr; - } - - inline const std::string& WebRequestResult::GetErrorMessage() const - { - assert(!HasSucceeded()); - return m_bodyOrErr; - } - - inline bool WebRequestResult::HasSucceeded() const - { - return m_curlHandle != nullptr; - } - - inline WebRequestResult::operator bool() const - { - return HasSucceeded(); - } - -} diff --git a/include/CoreLib/WebService.hpp b/include/CoreLib/WebService.hpp deleted file mode 100644 index ad2ee996..00000000 --- a/include/CoreLib/WebService.hpp +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#pragma once - -#ifndef BURGWAR_CORELIB_WEBREQUESTDISPATCHER_HPP -#define BURGWAR_CORELIB_WEBREQUESTDISPATCHER_HPP - -#include -#include -#include -#include - -using CURLM = void; - -namespace bw -{ - class Logger; - struct CurlLibrary; - - class BURGWAR_CORELIB_API WebService - { - friend class BurgAppComponent; - friend class WebRequest; - friend class WebRequestResult; - - public: - WebService(const Logger& logger); - WebService(const WebService&) = delete; - WebService(WebService&&) = default; - ~WebService(); - - void AddRequest(std::unique_ptr&& request); - - void Poll(); - - WebService& operator=(const WebService&) = delete; - WebService& operator=(WebService&&) = default; - - static inline const std::string& GetUserAgent(); - static inline bool IsInitialized(); - - private: - static inline const CurlLibrary& GetLibcurl(); - static bool Initialize(std::string* error); - static void Uninitialize(); - - const Logger& m_logger; - Nz::MovablePtr m_curlMulti; - tsl::hopscotch_map> m_activeRequests; - - static std::string s_userAgent; - static std::unique_ptr s_curlLibrary; - }; -} - -#include - -#endif diff --git a/include/CoreLib/WebService.inl b/include/CoreLib/WebService.inl deleted file mode 100644 index 05df635a..00000000 --- a/include/CoreLib/WebService.inl +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - inline const std::string& WebService::GetUserAgent() - { - return s_userAgent; - } - - inline bool WebService::IsInitialized() - { - return s_curlLibrary.get(); - } - - inline auto WebService::GetLibcurl() -> const CurlLibrary& - { - assert(IsInitialized()); - return *s_curlLibrary; - } -} diff --git a/src/Client/ClientApp.cpp b/src/Client/ClientAppComponent.cpp similarity index 57% rename from src/Client/ClientApp.cpp rename to src/Client/ClientAppComponent.cpp index 1424ea14..48ac1b36 100644 --- a/src/Client/ClientApp.cpp +++ b/src/Client/ClientAppComponent.cpp @@ -2,9 +2,15 @@ // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include @@ -17,8 +23,8 @@ namespace bw { - ClientApp::ClientApp(int argc, char* argv[]) : - ClientEditorAppComponent(argc, argv, LogSide::Client, m_configFile), + ClientAppComponent::ClientAppComponent(Nz::ApplicationBase& app, int argc, char* argv[]) : + ClientEditorAppComponent(app, argc, argv, LogSide::Client, m_configFile), m_stateMachine(nullptr), m_configFile(*this), m_networkReactors(GetLogger()) @@ -26,6 +32,13 @@ namespace bw if (!m_configFile.LoadFromFile("clientconfig.lua")) throw std::runtime_error("failed to load config file"); + Nz::AppFilesystemComponent& appFilesystem = app.GetComponent(); + appFilesystem.Mount("assetCache", Nz::Utf8Path(m_configFile.GetStringValue("Resources.AssetCacheDirectory"))); + appFilesystem.Mount("assets", Nz::Utf8Path(m_configFile.GetStringValue("Resources.AssetDirectory"))); + appFilesystem.Mount("mods", Nz::Utf8Path(m_configFile.GetStringValue("Resources.ModDirectory"))); + appFilesystem.Mount("scriptCache", Nz::Utf8Path(m_configFile.GetStringValue("Resources.ScriptCacheDirectory"))); + appFilesystem.Mount("scripts", Nz::Utf8Path(m_configFile.GetStringValue("Resources.ScriptDirectory"))); + LoadMods(); FillStores(); @@ -55,32 +68,34 @@ namespace bw else chosenVideoMode = Nz::VideoMode(width, height); - m_mainWindow = &AddWindow(chosenVideoMode, "Burg'war", (fullscreen) ? Nz::WindowStyle_Fullscreen : Nz::WindowStyle_Default, Nz::RenderTargetParameters(aaLevel)); + auto& windowingComponent = app.GetComponent(); + m_mainWindow = &windowingComponent.CreateWindow(chosenVideoMode, "Burg'war", (fullscreen) ? Nz::WindowStyle::Fullscreen : Nz::WindowStyle_Default); - m_mainWindow->EnableVerticalSync(vsync); - m_mainWindow->SetFramerateLimit(fpsLimit); + auto& ecsComponent = app.GetComponent(); - entt::registry& world = AddWorld(); + Nz::EnttWorld& world = ecsComponent.AddWorld(); - Ndk::RenderSystem& renderSystem = world.AddSystem(); - renderSystem.SetDefaultBackground(nullptr); - renderSystem.SetGlobalUp(Nz::Vector3f::Down()); + Nz::RenderSystem& renderSystem = world.AddSystem(); + Nz::WindowSwapchain& swapchain = renderSystem.CreateSwapchain(*m_mainWindow); - entt::entity camera2D = world.CreateEntity(); + entt::handle camera2D = world.CreateEntity(); - auto& cameraComponent2D = camera2D->AddComponent(); - cameraComponent2D.SetProjectionType(Nz::ProjectionType_Orthogonal); - cameraComponent2D.SetTarget(m_mainWindow); + auto& cameraComponent2D = camera2D.emplace(&swapchain, Nz::ProjectionType::Orthographic); + cameraComponent2D.UpdateClearColor(Nz::Color(1.f, 1.f, 1.f, 0.f)); + cameraComponent2D.UpdateRenderOrder(1); + cameraComponent2D.UpdateRenderMask(1); - camera2D->AddComponent(); + camera2D.emplace(); Nz::WindowEventHandler& eventHandler = m_mainWindow->GetEventHandler(); m_stateData = std::make_shared(); - m_stateData->app = this; + m_stateData->app = &app; + m_stateData->appComponent = this; + m_stateData->swapchain = &swapchain; m_stateData->window = m_mainWindow; m_stateData->world = &world; - m_stateData->canvas.emplace(world.CreateHandle(), eventHandler, m_mainWindow->GetCursorController().CreateHandle()); + m_stateData->canvas.emplace(world.GetRegistry(), eventHandler, m_mainWindow->GetCursorController().CreateHandle(), 0xFFFFFFFF); m_stateData->canvas->Resize(Nz::Vector2f(m_mainWindow->GetSize())); if (m_config.GetBoolValue("Debug.ShowVersion")) @@ -106,28 +121,21 @@ namespace bw m_stateMachine.PushState(std::make_shared(m_stateData)); } - ClientApp::~ClientApp() + ClientAppComponent::~ClientAppComponent() { m_stateMachine.ResetState(nullptr); - m_stateMachine.Update(0.f); + m_stateMachine.Update(Nz::Time::Zero()); m_networkReactors.ClearReactors(); } - int ClientApp::Run() + void ClientAppComponent::Update(Nz::Time elapsedTime) { - while (ClientApplication::Run()) - { - m_mainWindow->Display(); - - BurgAppComponent::Update(); + ClientEditorAppComponent::Update(elapsedTime); - m_networkReactors.Update(); - - if (!m_stateMachine.Update(GetUpdateTime())) - break; - } + m_networkReactors.Update(); - return 0; + if (!m_stateMachine.Update(elapsedTime)) + GetApp().Quit(); } } diff --git a/src/Client/ClientApp.hpp b/src/Client/ClientAppComponent.hpp similarity index 56% rename from src/Client/ClientApp.hpp rename to src/Client/ClientAppComponent.hpp index 9a271389..31e5ed30 100644 --- a/src/Client/ClientApp.hpp +++ b/src/Client/ClientAppComponent.hpp @@ -10,34 +10,36 @@ #include #include #include -#include -#include -#include +#include +#include +#include +#include +#include #include namespace bw { struct StateData; - class ClientApp : public ClientEditorAppComponent + class ClientAppComponent : public ClientEditorAppComponent { public: - ClientApp(int argc, char* argv[]); - ~ClientApp(); + ClientAppComponent(Nz::ApplicationBase& app, int argc, char* argv[]); + ~ClientAppComponent(); inline NetworkReactorManager& GetReactorManager(); - int Run(); + void Update(Nz::Time elapsedTime) override; private: std::shared_ptr m_stateData; - Ndk::StateMachine m_stateMachine; - Nz::RenderWindow* m_mainWindow; + Nz::StateMachine m_stateMachine; + Nz::Window* m_mainWindow; ClientAppConfig m_configFile; NetworkReactorManager m_networkReactors; }; } -#include +#include #endif diff --git a/src/Client/ClientApp.inl b/src/Client/ClientAppComponent.inl similarity index 65% rename from src/Client/ClientApp.inl rename to src/Client/ClientAppComponent.inl index ac0c6a21..f6753aad 100644 --- a/src/Client/ClientApp.inl +++ b/src/Client/ClientAppComponent.inl @@ -2,11 +2,11 @@ // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE -#include +#include namespace bw { - inline NetworkReactorManager& ClientApp::GetReactorManager() + inline NetworkReactorManager& ClientAppComponent::GetReactorManager() { return m_networkReactors; } diff --git a/src/Client/ClientAppConfig.cpp b/src/Client/ClientAppConfig.cpp index e17ca3f8..11e72b75 100644 --- a/src/Client/ClientAppConfig.cpp +++ b/src/Client/ClientAppConfig.cpp @@ -3,11 +3,11 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include namespace bw { - ClientAppConfig::ClientAppConfig(ClientApp& app) : + ClientAppConfig::ClientAppConfig(ClientAppComponent& app) : SharedAppConfig(app) { RegisterStringOption("Debug.ShowConnectionData"); diff --git a/src/Client/ClientAppConfig.hpp b/src/Client/ClientAppConfig.hpp index 4dcf50b5..864133ba 100644 --- a/src/Client/ClientAppConfig.hpp +++ b/src/Client/ClientAppConfig.hpp @@ -11,12 +11,12 @@ namespace bw { - class ClientApp; + class ClientAppComponent; class ClientAppConfig : public SharedAppConfig { public: - ClientAppConfig(ClientApp& app); + ClientAppConfig(ClientAppComponent& app); ~ClientAppConfig() = default; }; } diff --git a/src/Client/States/AbstractState.cpp b/src/Client/States/AbstractState.cpp index fcd45ed9..0f4680a8 100644 --- a/src/Client/States/AbstractState.cpp +++ b/src/Client/States/AbstractState.cpp @@ -10,7 +10,7 @@ namespace bw m_stateData(std::move(stateData)), m_isVisible(false) { - m_onTargetChangeSizeSlot.Connect(m_stateData->window->OnRenderTargetSizeChange, [this](const Nz::RenderTarget*) + m_onTargetChangeSizeSlot.Connect(m_stateData->swapchain->OnRenderTargetSizeChange, [this](const Nz::RenderTarget*, const Nz::Vector2ui& /*newSize*/) { if (m_isVisible) LayoutWidgets(); @@ -26,7 +26,7 @@ namespace bw entry.widget->Destroy(); } - void AbstractState::Enter(Ndk::StateMachine& /*fsm*/) + void AbstractState::Enter(Nz::StateMachine& /*fsm*/) { m_isVisible = true; @@ -38,10 +38,10 @@ namespace bw for (auto it = m_entities.begin(); it != m_entities.end();) { - entt::entity entity = *it; + entt::handle entity = *it; if (entity) { - entity->Enable(); + entity.erase(); ++it; } else @@ -51,7 +51,7 @@ namespace bw LayoutWidgets(); } - void AbstractState::Leave(Ndk::StateMachine& /*fsm*/) + void AbstractState::Leave(Nz::StateMachine& /*fsm*/) { m_isVisible = false; @@ -63,10 +63,10 @@ namespace bw for (auto it = m_entities.begin(); it != m_entities.end();) { - entt::entity entity = *it; + entt::handle entity = *it; if (entity) { - entity->Disable(); + entity.emplace(); ++it; } else @@ -74,7 +74,7 @@ namespace bw } } - bool AbstractState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) + bool AbstractState::Update(Nz::StateMachine& /*fsm*/, Nz::Time /*elapsedTime*/) { return true; } diff --git a/src/Client/States/AbstractState.hpp b/src/Client/States/AbstractState.hpp index 5e4cce59..d411e754 100644 --- a/src/Client/States/AbstractState.hpp +++ b/src/Client/States/AbstractState.hpp @@ -9,14 +9,16 @@ #include #include -#include +#include +#include +#include #include #include #include namespace bw { - class AbstractState : public Ndk::State, public std::enable_shared_from_this + class AbstractState : public Nz::State, public std::enable_shared_from_this { public: AbstractState(std::shared_ptr stateData); @@ -24,7 +26,7 @@ namespace bw protected: template void ConnectSignal(T& signal, Args&&... args); - inline entt::entity CreateEntity(); + inline entt::handle CreateEntity(); template T* CreateWidget(Args&&... args); inline void DestroyWidget(Nz::BaseWidget* widget); @@ -32,9 +34,9 @@ namespace bw inline const StateData& GetStateData() const; inline const std::shared_ptr& GetStateDataPtr(); - void Enter(Ndk::StateMachine& fsm) override; - void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; + void Enter(Nz::StateMachine& fsm) override; + void Leave(Nz::StateMachine& fsm) override; + bool Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) override; virtual void LayoutWidgets(); diff --git a/src/Client/States/AbstractState.inl b/src/Client/States/AbstractState.inl index 8fe16623..09c6291a 100644 --- a/src/Client/States/AbstractState.inl +++ b/src/Client/States/AbstractState.inl @@ -27,10 +27,12 @@ namespace bw return widget; } - inline entt::entity AbstractState::CreateEntity() + inline entt::handle AbstractState::CreateEntity() { - entt::entity entity = m_stateData->world->CreateEntity(); - entity->Enable(m_isVisible); + entt::handle entity = m_stateData->world->CreateEntity(); + if (!m_isVisible) + entity.emplace(); + m_entities.emplace_back(entity); return entity; diff --git a/src/Client/States/BackgroundState.cpp b/src/Client/States/BackgroundState.cpp index 0c15b791..94f19d5d 100644 --- a/src/Client/States/BackgroundState.cpp +++ b/src/Client/States/BackgroundState.cpp @@ -3,47 +3,46 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include -#include -#include +#include +#include +#include +#include #include -#include -#include #include namespace bw { - void BackgroundState::Enter(Ndk::StateMachine& fsm) + void BackgroundState::Enter(Nz::StateMachine& fsm) { AbstractState::Enter(fsm); StateData& stateData = GetStateData(); - //stateData.world->GetSystem().SetDefaultBackground(Nz::ColorBackground::New(Nz::Color(131, 180, 205))); - if (std::shared_ptr backgroundTexture = Nz::TextureLibrary::Get("MenuBackground")) + auto& appfs = stateData.app->GetComponent(); + + if (std::shared_ptr backgroundTexture = appfs.Load("assets/background.png")) { - m_backgroundSprite = Nz::Sprite::New(); - m_backgroundSprite->SetTexture(backgroundTexture); + std::shared_ptr mat = Nz::Graphics::Instance()->GetDefaultMaterials().basicNoDepth->Clone(); + mat->SetTextureProperty("BaseColorMap", std::move(backgroundTexture)); + + m_backgroundSprite = std::make_shared(std::move(mat)); m_spriteEntity = stateData.world->CreateEntity(); - m_spriteEntity->AddComponent().Attach(m_backgroundSprite, -100); - m_spriteEntity->AddComponent(); + m_spriteEntity->emplace().AttachRenderable(m_backgroundSprite, 1); + m_spriteEntity->emplace(); } LayoutWidgets(); } - void BackgroundState::Leave(Ndk::StateMachine& fsm) + void BackgroundState::Leave(Nz::StateMachine& fsm) { AbstractState::Leave(fsm); - /* - StateData& stateData = GetStateData(); - stateData.world->GetSystem().SetDefaultBackground(nullptr); - */ + m_spriteEntity = {}; } - bool BackgroundState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) + bool BackgroundState::Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; @@ -67,7 +66,7 @@ namespace bw m_backgroundSprite->SetSize(newSize); - m_spriteentity.get().SetPosition(canvasSize / 2.f - newSize / 2.f); + m_spriteEntity->get().SetPosition(canvasSize / 2.f - newSize / 2.f); } } } diff --git a/src/Client/States/BackgroundState.hpp b/src/Client/States/BackgroundState.hpp index 3e90faeb..ed6c5c49 100644 --- a/src/Client/States/BackgroundState.hpp +++ b/src/Client/States/BackgroundState.hpp @@ -20,9 +20,9 @@ namespace bw ~BackgroundState() = default; private: - void Enter(Ndk::StateMachine& fsm) override; - void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; + void Enter(Nz::StateMachine& fsm) override; + void Leave(Nz::StateMachine& fsm) override; + bool Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) override; void LayoutWidgets() override; diff --git a/src/Client/States/Game/AuthenticationState.cpp b/src/Client/States/Game/AuthenticationState.cpp index ae2a6ec2..cb30646b 100644 --- a/src/Client/States/Game/AuthenticationState.cpp +++ b/src/Client/States/Game/AuthenticationState.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include #include #include @@ -16,7 +16,7 @@ namespace bw m_onAuthFailedSlot.Connect(m_clientSession->OnAuthFailure, [this](ClientSession*, const Packets::AuthFailure& /*data*/) { UpdateStatus("Failed to authenticate", Nz::Color::Red()); - Cancel(3.f); + Cancel(Nz::Time::Seconds(3)); }); m_onAuthSucceededSlot.Connect(m_clientSession->OnAuthSuccess, [this](ClientSession*, const Packets::AuthSuccess& data) @@ -30,21 +30,21 @@ namespace bw if (!m_authSuccessPacket) { UpdateStatus("Protocol error", Nz::Color::Red()); - Cancel(3.f); + Cancel(Nz::Time::Seconds(3)); return; } UpdateStatus("Received match data", Nz::Color::White()); - SwitchToState(std::make_shared(GetStateDataPtr(), m_clientSession, m_authSuccessPacket.value(), data, GetOriginalState()), 0.5f); + SwitchToState(std::make_shared(GetStateDataPtr(), m_clientSession, m_authSuccessPacket.value(), data, GetOriginalState()), Nz::Time::Seconds(0.5f)); }); } - void AuthenticationState::Enter(Ndk::StateMachine& fsm) + void AuthenticationState::Enter(Nz::StateMachine& fsm) { StatusState::Enter(fsm); - ConfigFile& playerConfig = GetStateData().app->GetPlayerSettings(); + ConfigFile& playerConfig = GetStateData().appComponent->GetPlayerSettings(); Packets::Auth authPacket; authPacket.players.emplace_back().nickname = playerConfig.GetStringValue("Player.Name"); diff --git a/src/Client/States/Game/AuthenticationState.hpp b/src/Client/States/Game/AuthenticationState.hpp index 41605945..71ddc151 100644 --- a/src/Client/States/Game/AuthenticationState.hpp +++ b/src/Client/States/Game/AuthenticationState.hpp @@ -22,7 +22,7 @@ namespace bw ~AuthenticationState() = default; private: - void Enter(Ndk::StateMachine& fsm) override; + void Enter(Nz::StateMachine& fsm) override; void OnCancelled() override; std::optional m_authSuccessPacket; diff --git a/src/Client/States/Game/CancelableState.cpp b/src/Client/States/Game/CancelableState.cpp index 22ca5597..ec624adb 100644 --- a/src/Client/States/Game/CancelableState.cpp +++ b/src/Client/States/Game/CancelableState.cpp @@ -5,7 +5,7 @@ #include #include #include -#include +#include namespace bw { @@ -23,9 +23,9 @@ namespace bw }); } - void CancelableState::Cancel(float delay) + void CancelableState::Cancel(Nz::Time delay) { - UpdateState([this](Ndk::StateMachine& fsm) + UpdateState([this](Nz::StateMachine& fsm) { fsm.ResetState(std::make_shared(GetStateDataPtr())); fsm.PushState(std::move(m_originalState)); @@ -34,15 +34,15 @@ namespace bw OnCancelled(); } - void CancelableState::SwitchToState(std::shared_ptr state, float delay) + void CancelableState::SwitchToState(std::shared_ptr state, Nz::Time delay) { - UpdateState([this, state = std::move(state)](Ndk::StateMachine& fsm) mutable + UpdateState([this, state = std::move(state)](Nz::StateMachine& fsm) mutable { fsm.ChangeState(std::move(state)); }, delay); } - void CancelableState::UpdateState(std::function stateUpdate, float delay) + void CancelableState::UpdateState(std::function stateUpdate, Nz::Time delay) { m_nextStateCallback = std::move(stateUpdate); m_nextStateDelay = delay; @@ -54,14 +54,14 @@ namespace bw m_cancelButton->SetPosition(canvasSize.x / 2.f - m_cancelButton->GetWidth() / 2.f, canvasSize.y - 10.f - m_cancelButton->GetHeight()); } - bool CancelableState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) + bool CancelableState::Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) { if (!StatusState::Update(fsm, elapsedTime)) return false; if (m_nextStateCallback) { - if ((m_nextStateDelay -= elapsedTime) < 0.f) + if ((m_nextStateDelay -= elapsedTime) < Nz::Time::Zero()) { m_nextStateCallback(fsm); return true; diff --git a/src/Client/States/Game/CancelableState.hpp b/src/Client/States/Game/CancelableState.hpp index 50f429c8..741aada9 100644 --- a/src/Client/States/Game/CancelableState.hpp +++ b/src/Client/States/Game/CancelableState.hpp @@ -8,6 +8,7 @@ #define BURGWAR_STATES_GAME_CANCELABLESTATE_HPP #include +#include #include #include @@ -19,24 +20,24 @@ namespace bw CancelableState(std::shared_ptr stateData, std::shared_ptr originalState); ~CancelableState() = default; - bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; + bool Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) override; protected: - void Cancel(float delay = 0.f); + void Cancel(Nz::Time delay = Nz::Time::Zero()); inline const std::shared_ptr& GetOriginalState(); inline bool IsSwitching() const; - void SwitchToState(std::shared_ptr state, float delay = 0.f); - void UpdateState(std::function stateUpdate, float delay = 0.f); + void SwitchToState(std::shared_ptr state, Nz::Time delay = Nz::Time::Zero()); + void UpdateState(std::function stateUpdate, Nz::Time delay = Nz::Time::Zero()); virtual void OnCancelled() = 0; private: void LayoutWidgets() override; - std::function m_nextStateCallback; + std::function m_nextStateCallback; std::shared_ptr m_originalState; Nz::ButtonWidget* m_cancelButton; - float m_nextStateDelay; + Nz::Time m_nextStateDelay; }; } diff --git a/src/Client/States/Game/ConnectedState.cpp b/src/Client/States/Game/ConnectedState.cpp index 75053b1c..49518e9f 100644 --- a/src/Client/States/Game/ConnectedState.cpp +++ b/src/Client/States/Game/ConnectedState.cpp @@ -5,18 +5,20 @@ #include #include #include -#include +#include #include #include +#include +#include +#include #include -#include #include namespace bw { - constexpr float PeerInfoPollTime = 0.1f; //< 0.1s - constexpr float UpdateInfoRefreshTime = 1.0f; //< 1s - constexpr Nz::UInt32 TimeoutThreshold = 3'000; //< 3s + constexpr Nz::Time PeerInfoPollTime = Nz::Time::Seconds(0.1f); + constexpr Nz::Time UpdateInfoRefreshTime = Nz::Time::Seconds(1.0f); + constexpr Nz::Time TimeoutThreshold = Nz::Time::Seconds(3); ConnectedState::ConnectedState(std::shared_ptr stateData, std::shared_ptr clientSession, std::shared_ptr firstState) : AbstractState(std::move(stateData)), @@ -30,13 +32,13 @@ namespace bw m_downloadSpeed(10), m_uploadSpeed(10), m_connectionLost(false), - m_connectionLostCounter(0.f), - m_queryInfoTimer(0.f) + m_connectionLostCounter(Nz::Time::Zero()), + m_queryInfoTimer(Nz::Time::Zero()) { RefreshFlags(); } - void ConnectedState::Enter(Ndk::StateMachine& fsm) + void ConnectedState::Enter(Nz::StateMachine& fsm) { AbstractState::Enter(fsm); @@ -53,7 +55,7 @@ namespace bw float cursor = 0.f; if (m_connectionLostEntity) { - auto& entityNode = m_connectionLostentity.get(); + auto& entityNode = m_connectionLostEntity->get(); entityNode.SetPosition(windowSize.x - m_connectionLostSprite->GetSize().x - 10.f, cursor); cursor += m_connectionLostSprite->GetSize().y; @@ -75,29 +77,29 @@ namespace bw { if (!m_connectionLostSprite) { - const std::string& assetsFolder = GetStateData().app->GetConfig().GetStringValue("Resources.AssetDirectory"); + auto& appfs = GetStateData().app->GetComponent(); - Nz::MaterialRef connectionLostMat = Nz::Material::New("Translucent2D"); - connectionLostMat->SetDiffuseMap(assetsFolder + "/connection.png"); + std::shared_ptr connectionLostMat = Nz::Graphics::Instance()->GetDefaultMaterials().basicTransparent->Clone(); + connectionLostMat->SetTextureProperty("BaseColorMap", appfs.Load("assets/connection.png")); - m_connectionLostSprite = Nz::Sprite::New(); - m_connectionLostSprite->SetMaterial(std::move(connectionLostMat)); + m_connectionLostSprite = std::make_shared(std::move(connectionLostMat)); + m_connectionLostSprite->UpdateRenderLayer(1000000); } - m_connectionLostCounter = 0.f; + m_connectionLostCounter = Nz::Time::Zero(); m_connectionLostSprite->SetColor(Nz::Color(255, 0, 0, 0)); m_connectionLostEntity = CreateEntity(); - m_connectionLostEntity->AddComponent().Attach(m_connectionLostSprite, 1000000); - m_connectionLostEntity->AddComponent(); + m_connectionLostEntity->emplace(m_connectionLostSprite); + m_connectionLostEntity->emplace(); LayoutWidgets(); } void ConnectedState::OnConnectionRetrieved() { - m_connectionLostCounter = 0.f; - m_connectionLostSprite->SetColor(Nz::Color::Green); + m_connectionLostCounter = Nz::Time::Zero(); + m_connectionLostSprite->SetColor(Nz::Color::Green()); } void ConnectedState::PollSessionInfo() @@ -111,7 +113,7 @@ namespace bw { const SessionBridge::SessionInfo& lastSessionInfo = *m_lastSessionInfo; - double elapsedTime = double(m_lastSessionClock.Restart()) / 1'000'000; + double elapsedTime = m_lastSessionClock.Restart().AsSeconds(); m_downloadSpeed.InsertValue((sessionInfo.totalByteReceived - lastSessionInfo.totalByteReceived) / elapsedTime); m_uploadSpeed.InsertValue((sessionInfo.totalByteSent - lastSessionInfo.totalByteSent) / elapsedTime); @@ -147,7 +149,7 @@ namespace bw { StateData& stateData = GetStateData(); - const std::string& enabledConnectionData = stateData.app->GetConfig().GetStringValue("Debug.ShowConnectionData"); + const std::string& enabledConnectionData = stateData.appComponent->GetConfig().GetStringValue("Debug.ShowConnectionData"); SplitStringAny(enabledConnectionData, "+| ", [&](std::string_view option) { if (option == "ping") @@ -159,7 +161,7 @@ namespace bw else if (option == "usage") m_connectionInfoFlags |= InfoFlags::DataUsage; else - bwLog(stateData.app->GetLogger(), LogLevel::Warning, "unknown connection data option \"{0}\"", option); + bwLog(stateData.appComponent->GetLogger(), LogLevel::Warning, "unknown connection data option \"{0}\"", option); return true; }); @@ -167,7 +169,7 @@ namespace bw if ((m_connectionInfoFlags & InfoFlags::DataUsage) && ((m_connectionInfoFlags & (InfoFlags::DownloadSpeed | InfoFlags::UploadSpeed)) == 0)) { - bwLog(stateData.app->GetLogger(), LogLevel::Warning, "usage connection data option must be used with download and/or upload"); + bwLog(stateData.appComponent->GetLogger(), LogLevel::Warning, "usage connection data option must be used with download and/or upload"); m_connectionInfoFlags &= ~InfoFlags::DataUsage; } @@ -245,7 +247,7 @@ namespace bw LayoutWidgets(); } - bool ConnectedState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) + bool ConnectedState::Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; @@ -258,7 +260,7 @@ namespace bw } m_queryInfoTimer -= elapsedTime; - if (m_queryInfoTimer < 0.f) + if (m_queryInfoTimer < Nz::Time::Zero()) { PollSessionInfo(); @@ -268,7 +270,7 @@ namespace bw if (m_connectionInfoFlags != 0) { m_updateInfoTimer -= elapsedTime; - if (m_updateInfoTimer < 0.f) + if (m_updateInfoTimer < Nz::Time::Zero()) { UpdateSessionInfo(); @@ -281,16 +283,16 @@ namespace bw m_connectionLostCounter += elapsedTime; if (m_connectionLost) { - Nz::UInt8 alpha = Nz::UInt8(std::abs(std::sin(m_connectionLostCounter) * 255.f)); + Nz::UInt8 alpha = Nz::UInt8(std::abs(std::sin(m_connectionLostCounter.AsSeconds()) * 255.f)); m_connectionLostSprite->SetColor(Nz::Color(255, 0, 0, alpha)); } else { - Nz::UInt8 alpha = Nz::UInt8(std::max(std::cos(m_connectionLostCounter) * 255.f, 0.f)); + Nz::UInt8 alpha = Nz::UInt8(std::max(std::cos(m_connectionLostCounter.AsSeconds()) * 255.f, 0.f)); if (alpha > 0) m_connectionLostSprite->SetColor(Nz::Color(0, 255, 0, alpha)); else - m_connectionLostEntity.Reset(); + m_connectionLostEntity = EntityOwner{}; } } diff --git a/src/Client/States/Game/ConnectedState.hpp b/src/Client/States/Game/ConnectedState.hpp index e08734de..c0744229 100644 --- a/src/Client/States/Game/ConnectedState.hpp +++ b/src/Client/States/Game/ConnectedState.hpp @@ -35,14 +35,14 @@ namespace bw UploadSpeed = 1 << 3 }; - void Enter(Ndk::StateMachine& fsm) override; + void Enter(Nz::StateMachine& fsm) override; void LayoutWidgets() override; void OnConnectionLost(); void OnConnectionRetrieved(); void PollSessionInfo(); void RefreshFlags(); void UpdateSessionInfo(); - bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; + bool Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) override; std::optional m_lastSessionInfo; std::shared_ptr m_firstState; @@ -51,16 +51,16 @@ namespace bw Nz::LabelWidget* m_downloadSpeedLabel; Nz::LabelWidget* m_pingLabel; Nz::LabelWidget* m_uploadSpeedLabel; - Nz::Clock m_lastSessionClock; + Nz::MillisecondClock m_lastSessionClock; std::shared_ptr m_connectionLostSprite; + Nz::Time m_connectionLostCounter; + Nz::Time m_queryInfoTimer; + Nz::Time m_updateInfoTimer; Nz::UInt8 m_connectionInfoFlags; Nz::UInt32 m_queryId; AverageValues m_downloadSpeed; AverageValues m_uploadSpeed; bool m_connectionLost; - float m_connectionLostCounter; - float m_queryInfoTimer; - float m_updateInfoTimer; }; } diff --git a/src/Client/States/Game/ConnectionLostState.cpp b/src/Client/States/Game/ConnectionLostState.cpp index ff892262..44da3033 100644 --- a/src/Client/States/Game/ConnectionLostState.cpp +++ b/src/Client/States/Game/ConnectionLostState.cpp @@ -4,27 +4,27 @@ #include #include +#include #include -#include #include namespace bw { ConnectionLostState::ConnectionLostState(std::shared_ptr stateData) : AbstractState(std::move(stateData)), - m_timer(5.f) + m_timer(Nz::Time::Seconds(5)) { Nz::LabelWidget* labelWidget = CreateWidget(); labelWidget->UpdateText(Nz::SimpleTextDrawer::Draw("Connection lost.", 36, Nz::TextStyle_Regular, Nz::Color::Red())); labelWidget->Center(); } - bool ConnectionLostState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) + bool ConnectionLostState::Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; - if ((m_timer -= elapsedTime) < 0.f) + if ((m_timer -= elapsedTime) < Nz::Time::Zero()) fsm.ChangeState(std::make_shared(GetStateDataPtr())); return true; diff --git a/src/Client/States/Game/ConnectionLostState.hpp b/src/Client/States/Game/ConnectionLostState.hpp index 96a911da..f76437f4 100644 --- a/src/Client/States/Game/ConnectionLostState.hpp +++ b/src/Client/States/Game/ConnectionLostState.hpp @@ -18,9 +18,9 @@ namespace bw ~ConnectionLostState() = default; private: - bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; + bool Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) override; - float m_timer; + Nz::Time m_timer; }; } diff --git a/src/Client/States/Game/ConnectionState.cpp b/src/Client/States/Game/ConnectionState.cpp index b2af8952..af6dba4a 100644 --- a/src/Client/States/Game/ConnectionState.cpp +++ b/src/Client/States/Game/ConnectionState.cpp @@ -6,7 +6,7 @@ #include #include #include -#include +#include #include #include #include @@ -24,9 +24,9 @@ namespace bw CancelableState(stateData, std::move(previousState)), m_currentAddressIndex(0), m_addresses(std::move(remoteAddresses)), - m_timeBeforeGivingUp(0.f) + m_timeBeforeGivingUp(Nz::Time::Zero()) { - ClientApp* app = GetStateData().app; + ClientAppComponent* app = GetStateData().appComponent; m_clientSession = std::make_shared(*app); m_clientSessionConnectedSlot.Connect(m_clientSession->OnConnected, [this] (ClientSession*) @@ -34,7 +34,7 @@ namespace bw UpdateStatus("Connected, authenticating...", Nz::Color::White()); auto authState = std::make_shared(GetStateDataPtr(), m_clientSession, GetOriginalState()); - SwitchToState(std::make_shared(GetStateDataPtr(), m_clientSession, std::move(authState)), 0.5f); + SwitchToState(std::make_shared(GetStateDataPtr(), m_clientSession, std::move(authState)), Nz::Time::Seconds(0.5)); }); m_clientSessionDisconnectedSlot.Connect(m_clientSession->OnDisconnected, [this](ClientSession*) @@ -53,7 +53,7 @@ namespace bw void ConnectionState::HandleConnectionFailure() { - bwLog(GetStateData().app->GetLogger(), LogLevel::Error, "connection to address #{0}/{1} failed", m_currentAddressIndex + 1, m_addresses.size()); + bwLog(GetStateData().appComponent->GetLogger(), LogLevel::Error, "connection to address #{0}/{1} failed", m_currentAddressIndex + 1, m_addresses.size()); m_currentAddressIndex++; ProcessNextAddress(); @@ -69,10 +69,10 @@ namespace bw { if (m_currentAddressIndex >= m_addresses.size()) { - bwLog(GetStateData().app->GetLogger(), LogLevel::Error, "no more addresses available, connection failed"); + bwLog(GetStateData().appComponent->GetLogger(), LogLevel::Error, "no more addresses available, connection failed"); UpdateStatus("Failed to connect to server", Nz::Color::Red()); - Cancel(3.f); + Cancel(Nz::Time::Seconds(3)); return; } @@ -97,14 +97,14 @@ namespace bw resolve.serverName = name; resolve.thread = std::thread([=] { - bwLog(GetStateData().app->GetLogger(), LogLevel::Debug, "resolving {0}:{1}...", m_resolvingData->serverName.hostname, name.port); + bwLog(GetStateData().appComponent->GetLogger(), LogLevel::Debug, "resolving {0}:{1}...", m_resolvingData->serverName.hostname, name.port); Nz::ResolveError resolveError; std::vector serverAddresses = Nz::IpAddress::ResolveHostname(Nz::NetProtocol::Any, m_resolvingData->serverName.hostname, std::to_string(name.port), &resolveError); if (serverAddresses.empty()) { m_resolvingData->result = tl::unexpected(Nz::ErrorToString(resolveError)); - bwLog(GetStateData().app->GetLogger(), LogLevel::Debug, "resolution of {0}:{1} failed: {2}", m_resolvingData->serverName.hostname, name.port, m_resolvingData->result.error()); + bwLog(GetStateData().appComponent->GetLogger(), LogLevel::Debug, "resolution of {0}:{1} failed: {2}", m_resolvingData->serverName.hostname, name.port, m_resolvingData->result.error()); } else { @@ -113,7 +113,7 @@ namespace bw for (const auto& hostnameInfo : serverAddresses) addresses.push_back(hostnameInfo.address); - bwLog(GetStateData().app->GetLogger(), LogLevel::Debug, "resolution of {0}:{1} succeeded ({2} address(es) found)", m_resolvingData->serverName.hostname, name.port, addresses.size()); + bwLog(GetStateData().appComponent->GetLogger(), LogLevel::Debug, "resolution of {0}:{1} succeeded ({2} address(es) found)", m_resolvingData->serverName.hostname, name.port, addresses.size()); m_resolvingData->result = std::move(addresses); } @@ -125,16 +125,16 @@ namespace bw void ConnectionState::ProcessNextAddress(const Nz::IpAddress& address) { - ClientApp* app = GetStateData().app; + ClientAppComponent* app = GetStateData().appComponent; auto& networkManager = app->GetReactorManager(); - bwLog(GetStateData().app->GetLogger(), LogLevel::Debug, "connecting to {0}...", address.ToString()); + bwLog(GetStateData().appComponent->GetLogger(), LogLevel::Debug, "connecting to {0}...", address.ToString()); auto sessionBridge = networkManager.ConnectToServer(address, 0); if (sessionBridge) { m_clientSession->Connect(std::move(sessionBridge)); - m_timeBeforeGivingUp = 10.f; + m_timeBeforeGivingUp = Nz::Time::Seconds(10.f); UpdateStatus("Connecting to " + address.ToString() + "...", Nz::Color::White()); } @@ -144,12 +144,12 @@ namespace bw void ConnectionState::ProcessNextAddress(LocalSessionManager* sessionManager) { - bwLog(GetStateData().app->GetLogger(), LogLevel::Debug, "connecting using local session..."); + bwLog(GetStateData().appComponent->GetLogger(), LogLevel::Debug, "connecting using local session..."); m_clientSession->Connect(sessionManager->CreateSession()); - m_timeBeforeGivingUp = 3.f; //< Should be instant + m_timeBeforeGivingUp = Nz::Time::Seconds(3.f); //< Should be instant } - bool ConnectionState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) + bool ConnectionState::Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) { if (!CancelableState::Update(fsm, elapsedTime)) return false; @@ -168,15 +168,15 @@ namespace bw m_addresses.emplace(m_addresses.begin() + m_currentAddressIndex, *resultIt); } else - bwLog(GetStateData().app->GetLogger(), LogLevel::Error, "hostname resolution of {0} failed: {1}", m_resolvingData->serverName.hostname, m_resolvingData->result.error()); + bwLog(GetStateData().appComponent->GetLogger(), LogLevel::Error, "hostname resolution of {0} failed: {1}", m_resolvingData->serverName.hostname, m_resolvingData->result.error()); m_resolvingData.reset(); ProcessNextAddress(); } } - else if (m_timeBeforeGivingUp > 0.f) + else if (m_timeBeforeGivingUp > Nz::Time::Second()) { - if ((m_timeBeforeGivingUp -= elapsedTime) < 0.f) + if ((m_timeBeforeGivingUp -= elapsedTime) < Nz::Time::Second()) m_clientSession->Disconnect(); } diff --git a/src/Client/States/Game/ConnectionState.hpp b/src/Client/States/Game/ConnectionState.hpp index b149cc46..cdfc405b 100644 --- a/src/Client/States/Game/ConnectionState.hpp +++ b/src/Client/States/Game/ConnectionState.hpp @@ -44,7 +44,7 @@ namespace bw void ProcessNextAddress(const ServerName& name); void ProcessNextAddress(const Nz::IpAddress& address); void ProcessNextAddress(LocalSessionManager* sessionManager); - bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; + bool Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) override; struct ResolvingData { @@ -58,7 +58,7 @@ namespace bw std::shared_ptr m_clientSession; std::size_t m_currentAddressIndex; AddressList m_addresses; - float m_timeBeforeGivingUp; + Nz::Time m_timeBeforeGivingUp; NazaraSlot(ClientSession, OnConnected, m_clientSessionConnectedSlot); NazaraSlot(ClientSession, OnDisconnected, m_clientSessionDisconnectedSlot); diff --git a/src/Client/States/Game/GameState.cpp b/src/Client/States/Game/GameState.cpp index ea1137ef..1854bae7 100644 --- a/src/Client/States/Game/GameState.cpp +++ b/src/Client/States/Game/GameState.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include #include #include @@ -16,23 +16,23 @@ namespace bw { StateData& stateData = GetStateData(); - m_match = std::make_shared(*stateData.app, stateData.window, stateData.window, &stateData.canvas.value(), *m_clientSession, authSuccess, matchData); + m_match = std::make_shared(*stateData.appComponent, stateData.window, stateData.swapchain, &stateData.canvas.value(), *stateData.world, *m_clientSession, authSuccess, matchData); m_match->LoadAssets(std::move(assetDirectory)); m_match->LoadScripts(std::move(scriptDirectory)); - if (stateData.app->GetConfig().GetBoolValue("Debug.ShowServerGhosts")) + if (stateData.appComponent->GetConfig().GetBoolValue("Debug.ShowServerGhosts")) m_match->InitDebugGhosts(); m_clientSession->SendPacket(Packets::Ready{}); } - void GameState::Leave(Ndk::StateMachine& /*fsm*/) + void GameState::Leave(Nz::StateMachine& /*fsm*/) { if (m_clientSession) m_clientSession->Disconnect(); } - bool GameState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) + bool GameState::Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; diff --git a/src/Client/States/Game/GameState.hpp b/src/Client/States/Game/GameState.hpp index 0347c3e0..729feac7 100644 --- a/src/Client/States/Game/GameState.hpp +++ b/src/Client/States/Game/GameState.hpp @@ -11,10 +11,14 @@ #include #include +namespace Nz +{ + class VirtualDirectory; +} + namespace bw { class ClientMatch; - class VirtualDirectory; class GameState final : public AbstractState { @@ -25,8 +29,8 @@ namespace bw inline const std::shared_ptr& GetMatch(); private: - void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; + void Leave(Nz::StateMachine& fsm) override; + bool Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) override; std::shared_ptr m_nextState; std::shared_ptr m_clientSession; diff --git a/src/Client/States/Game/ResourceDownloadState.cpp b/src/Client/States/Game/ResourceDownloadState.cpp index ec869808..49be53ef 100644 --- a/src/Client/States/Game/ResourceDownloadState.cpp +++ b/src/Client/States/Game/ResourceDownloadState.cpp @@ -6,8 +6,9 @@ #include #include #include -#include +#include #include +#include #include #include @@ -19,31 +20,31 @@ namespace bw m_authSuccess(std::move(authSuccess)), m_matchData(std::move(matchData)) { - ClientApp* app = GetStateData().app; + ClientAppComponent* app = GetStateData().appComponent; const ConfigFile& config = app->GetConfig(); + auto& appfs = GetStateData().app->GetComponent(); + bwLog(app->GetLogger(), LogLevel::Info, "Downloading resources..."); - m_targetAssetDirectory = std::make_shared(); - m_targetScriptDirectory = std::make_shared(); + m_targetAssetDirectory = std::make_shared(); + m_targetScriptDirectory = std::make_shared(); m_downloadManagers.emplace_back(std::make_unique(m_clientSession)); // Register scripts before adding HTTP download manager (since we won't get theses files from fast download) - auto scriptDir = std::make_shared(config.GetStringValue("Resources.ScriptDirectory")); - RegisterFiles(m_matchData.scripts, scriptDir, m_targetScriptDirectory, config.GetStringValue("Resources.ScriptCacheDirectory"), m_scriptData, true); + RegisterFiles(m_matchData.scripts, appfs.GetDirectory("scripts"), m_targetScriptDirectory, config.GetStringValue("Resources.ScriptCacheDirectory"), m_scriptData, true); if (!m_matchData.fastDownloadUrls.empty()) { - if (WebService::IsInitialized()) - m_downloadManagers.emplace(m_downloadManagers.begin(), std::make_unique(app->GetLogger(), std::move(m_matchData.fastDownloadUrls), 2)); + if (app->HasWebService()) + m_downloadManagers.emplace(m_downloadManagers.begin(), std::make_unique(app->GetWebService(), app->GetLogger(), std::move(m_matchData.fastDownloadUrls), 2)); else bwLog(app->GetLogger(), LogLevel::Warning, "web services are not initialized, fast download will be disabled"); } // Register assets files - auto assetDir = std::make_shared(config.GetStringValue("Resources.AssetDirectory")); - RegisterFiles(m_matchData.assets, assetDir, m_targetAssetDirectory, config.GetStringValue("Resources.AssetCacheDirectory"), m_assetData, false); + RegisterFiles(m_matchData.assets, appfs.GetDirectory("assets"), m_targetAssetDirectory, config.GetStringValue("Resources.AssetCacheDirectory"), m_assetData, false); for (auto& downloadManagerPtr : m_downloadManagers) { @@ -59,7 +60,7 @@ namespace bw downloadManagerPtr->OnDownloadStarted.Connect([this](DownloadManager* downloadManager, std::size_t fileIndex, const std::string& downloadPath) { const auto& fileEntry = downloadManager->GetEntry(fileIndex); - bwLog(GetStateData().app->GetLogger(), LogLevel::Info, "Downloading {}... ({})", downloadPath, ByteToString(fileEntry.expectedSize)); + bwLog(GetStateData().appComponent->GetLogger(), LogLevel::Info, "Downloading {}... ({})", downloadPath, ByteToString(fileEntry.expectedSize)); }); downloadManagerPtr->OnDownloadFinished.Connect([this](DownloadManager* downloadManager, std::size_t fileIndex, const std::filesystem::path& realPath, Nz::UInt64 downloadSpeed) @@ -71,11 +72,13 @@ namespace bw auto& downloadData = GetDownloadData(fileEntry.downloadPath, &isAsset); downloadData.downloadedSize = downloadData.totalSize; - bwLog(GetStateData().app->GetLogger(), LogLevel::Info, "Downloaded {} ({})", fileEntry.downloadPath, ByteToString(downloadSpeed, true)); + bwLog(GetStateData().appComponent->GetLogger(), LogLevel::Info, "Downloaded {} ({})", fileEntry.downloadPath, ByteToString(downloadSpeed, true)); + + std::shared_ptr file = std::make_shared(realPath, Nz::OpenMode::ReadOnly | Nz::OpenMode::Defer); if (isAsset) - m_targetAssetDirectory->StoreFile(fileEntry.downloadPath, realPath); + m_targetAssetDirectory->StoreFile(fileEntry.downloadPath, std::move(file)); else - m_targetScriptDirectory->StoreFile(fileEntry.downloadPath, realPath); + m_targetScriptDirectory->StoreFile(fileEntry.downloadPath, std::move(file)); UpdateStatus(); }); @@ -89,11 +92,11 @@ namespace bw auto& downloadData = GetDownloadData(fileEntry.downloadPath, &isAsset); downloadData.downloadedSize = downloadData.totalSize; - bwLog(GetStateData().app->GetLogger(), LogLevel::Info, "Downloaded {} ({})", fileEntry.downloadPath, ByteToString(downloadSpeed, true)); + bwLog(GetStateData().appComponent->GetLogger(), LogLevel::Info, "Downloaded {} ({})", fileEntry.downloadPath, ByteToString(downloadSpeed, true)); if (isAsset) - m_targetAssetDirectory->StoreFile(fileEntry.downloadPath, content); + m_targetAssetDirectory->StoreFile(fileEntry.downloadPath, Nz::ByteArray(content)); else - m_targetScriptDirectory->StoreFile(fileEntry.downloadPath, content); + m_targetScriptDirectory->StoreFile(fileEntry.downloadPath, Nz::ByteArray(content)); UpdateStatus(); }); @@ -118,7 +121,7 @@ namespace bw break; } - bwLog(GetStateData().app->GetLogger(), LogLevel::Error, "File download failed ({}): {}", fileEntry.downloadPath, errorReason); + bwLog(GetStateData().appComponent->GetLogger(), LogLevel::Error, "File download failed ({}): {}", fileEntry.downloadPath, errorReason); // Reset file data and try to download it with another download manager auto& fileData = GetDownloadData(fileEntry.downloadPath); @@ -132,14 +135,14 @@ namespace bw if (it == m_downloadManagers.end()) return; - bwLog(GetStateData().app->GetLogger(), LogLevel::Info, "Retrying with another download manager..."); + bwLog(GetStateData().appComponent->GetLogger(), LogLevel::Info, "Retrying with another download manager..."); const auto& nextDownloadManager = *it; nextDownloadManager->RegisterFile(fileEntry.downloadPath, fileEntry.expectedChecksum, fileEntry.expectedSize, fileEntry.outputPath, fileEntry.keepInMemory); }); } } - bool ResourceDownloadState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) + bool ResourceDownloadState::Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) { if (!CancelableState::Update(fsm, elapsedTime)) return false; @@ -155,10 +158,10 @@ namespace bw if (hasFinished && !IsSwitching()) { - bwLog(GetStateData().app->GetLogger(), LogLevel::Info, "Creating match..."); + bwLog(GetStateData().appComponent->GetLogger(), LogLevel::Info, "Creating match..."); UpdateStatus("Entering match...", Nz::Color::White()); - SwitchToState(std::make_shared(GetStateDataPtr(), m_clientSession, m_authSuccess, m_matchData, std::move(m_targetAssetDirectory), std::move(m_targetScriptDirectory)), 0.5f); + SwitchToState(std::make_shared(GetStateDataPtr(), m_clientSession, m_authSuccess, m_matchData, std::move(m_targetAssetDirectory), std::move(m_targetScriptDirectory)), Nz::Time::Seconds(0.5f)); } return true; @@ -203,83 +206,52 @@ namespace bw expectedChecksum.Assign(resource.sha1Checksum.begin(), resource.sha1Checksum.end()); // Try to find file in resource directory - VirtualDirectory::Entry entry; - if (resourceDir->GetEntry(resource.path, &entry)) + bool isFilePresent = resourceDir->GetEntry(resource.path, [&](const Nz::VirtualDirectory::Entry& entry) { - bool isFilePresent = std::visit([&](auto&& arg) + return std::visit([&](auto&& arg) { using T = std::decay_t; - if constexpr (std::is_same_v) - { - std::size_t fileSize = arg.size(); - if (fileSize != resource.size) - return false; - - auto hash = Nz::AbstractHash::Get(Nz::HashType::SHA1); - hash->Begin(); - hash->Append(arg.data(), arg.size()); - - if (expectedChecksum != hash->End()) - return false; - - targetDir->StoreFile(resource.path, arg); - return true; - } - else if constexpr (std::is_same_v) + if constexpr (std::is_same_v) + return false; + else if constexpr (std::is_same_v) { - if (keepInMemory) + Nz::Stream& stream = *arg.stream; + if (stream.IsMemoryMapped()) { - Nz::ByteArray fileChecksum; - std::vector content; - - Nz::File file(arg.generic_u8string()); - if (!file.Open(Nz::OpenMode::ReadOnly)) - return false; - - content.resize(file.GetSize()); - if (file.Read(content.data(), content.size()) != content.size()) + std::size_t fileSize = stream.GetSize(); + if (fileSize != resource.size) return false; - auto fileHash = Nz::AbstractHash::Get(Nz::HashType::SHA1); - fileHash->Begin(); - fileHash->Append(content.data(), content.size()); + auto hash = Nz::AbstractHash::Get(Nz::HashType::SHA1); + hash->Begin(); + hash->Append(static_cast(stream.GetMappedPointer()), fileSize); - if (expectedChecksum != fileHash->End()) + if (expectedChecksum != hash->End()) return false; - - targetDir->StoreFile(resource.path, content); - return true; } else { - std::size_t fileSize = std::filesystem::file_size(arg); - if (fileSize != resource.size) + std::size_t fileSize = stream.GetSize(); + if (fileSize != 0 && fileSize != resource.size) return false; - if (expectedChecksum != Nz::File::ComputeHash(Nz::HashType::SHA1, arg.generic_u8string())) + if (expectedChecksum != Nz::File::ComputeHash(Nz::HashType::SHA1, stream.GetPath())) return false; - - targetDir->StoreFile(resource.path, arg); - return true; } - } - else if constexpr (std::is_same_v) - { - return false; - } - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); + targetDir->StoreFile(resource.path, arg.stream); + return true; + } }, entry); + }); - if (isFilePresent) - continue; - } + if (isFilePresent) + continue; // Try to find file in cache std::string hexChecksum = expectedChecksum.ToHex(); - std::filesystem::path cachePath = cacheDir / std::filesystem::u8path(resource.path); + std::filesystem::path cachePath = cacheDir / Nz::Utf8Path(resource.path); cachePath.replace_extension(hexChecksum + cachePath.extension().generic_u8string()); if (std::filesystem::is_regular_file(cachePath)) @@ -289,7 +261,7 @@ namespace bw { if (expectedChecksum == Nz::File::ComputeHash(Nz::HashType::SHA1, cachePath.generic_u8string())) { - targetDir->StoreFile(resource.path, cachePath); + targetDir->StoreFile(resource.path, std::make_unique(cachePath, Nz::OpenMode::ReadOnly | Nz::OpenMode::Defer)); continue; } } diff --git a/src/Client/States/Game/ResourceDownloadState.hpp b/src/Client/States/Game/ResourceDownloadState.hpp index 2b555e1d..b9805a10 100644 --- a/src/Client/States/Game/ResourceDownloadState.hpp +++ b/src/Client/States/Game/ResourceDownloadState.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -41,7 +42,7 @@ namespace bw void OnCancelled() override; void RegisterFiles(const std::vector& files, const std::shared_ptr& resourceDir, const std::shared_ptr& targetDir, const std::string& cacheDir, FileMap& fileMap, bool keepInMemory); - bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; + bool Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) override; using CancelableState::UpdateStatus; void UpdateStatus(); diff --git a/src/Client/States/Game/ServerState.cpp b/src/Client/States/Game/ServerState.cpp index 9f7f0082..035a0147 100644 --- a/src/Client/States/Game/ServerState.cpp +++ b/src/Client/States/Game/ServerState.cpp @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include #include @@ -15,7 +15,7 @@ namespace bw AbstractState(std::move(stateDataPtr)), m_originalState(std::move(originalState)) { - ClientApp& app = *GetStateData().app; + ClientAppComponent& app = *GetStateData().appComponent; const ConfigFile& config = app.GetConfig(); m_match.emplace(app, std::move(matchSettings), std::move(gamemodeSettings), std::move(modSettings)); @@ -27,12 +27,12 @@ namespace bw m_match->InitDebugGhosts(); } - void ServerState::Enter(Ndk::StateMachine& fsm) + void ServerState::Enter(Nz::StateMachine& fsm) { fsm.PushState(std::make_shared(GetStateDataPtr(), m_localSessionManager, m_originalState)); } - bool ServerState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) + bool ServerState::Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; diff --git a/src/Client/States/Game/ServerState.hpp b/src/Client/States/Game/ServerState.hpp index 2f7b2e9a..ef4725a3 100644 --- a/src/Client/States/Game/ServerState.hpp +++ b/src/Client/States/Game/ServerState.hpp @@ -27,8 +27,8 @@ namespace bw inline const Match& GetMatch() const; private: - void Enter(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; + void Enter(Nz::StateMachine& fsm) override; + bool Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) override; std::optional m_match; std::shared_ptr m_originalState; diff --git a/src/Client/States/Game/StatusState.cpp b/src/Client/States/Game/StatusState.cpp index 4593a0b6..a7147c9b 100644 --- a/src/Client/States/Game/StatusState.cpp +++ b/src/Client/States/Game/StatusState.cpp @@ -3,9 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include #include -#include namespace bw { @@ -15,22 +13,22 @@ namespace bw m_statusLabel = CreateWidget(); } - void StatusState::Enter(Ndk::StateMachine& fsm) + void StatusState::Enter(Nz::StateMachine& fsm) { AbstractState::Enter(fsm); StateData& stateData = GetStateData(); - stateData.world->GetSystem().SetDefaultBackground(Nz::ColorBackground::New(Nz::Color(100, 185, 191))); + //stateData.world->GetSystem().SetDefaultBackground(Nz::ColorBackground::New(Nz::Color(100, 185, 191))); } - void StatusState::Leave(Ndk::StateMachine& fsm) + void StatusState::Leave(Nz::StateMachine& fsm) { AbstractState::Leave(fsm); StateData& stateData = GetStateData(); - stateData.world->GetSystem().SetDefaultBackground(nullptr); + //stateData.world->GetSystem().SetDefaultBackground(nullptr); } void StatusState::UpdateStatus(const std::string& status, const Nz::Color& color) diff --git a/src/Client/States/Game/StatusState.hpp b/src/Client/States/Game/StatusState.hpp index ab957c97..b785d81e 100644 --- a/src/Client/States/Game/StatusState.hpp +++ b/src/Client/States/Game/StatusState.hpp @@ -19,8 +19,8 @@ namespace bw ~StatusState() = default; protected: - void Enter(Ndk::StateMachine& fsm) override; - void Leave(Ndk::StateMachine& fsm) override; + void Enter(Nz::StateMachine& fsm) override; + void Leave(Nz::StateMachine& fsm) override; void UpdateStatus(const std::string& status, const Nz::Color& color); private: diff --git a/src/Client/States/JoinServerState.cpp b/src/Client/States/JoinServerState.cpp index 594998d1..c46ba92c 100644 --- a/src/Client/States/JoinServerState.cpp +++ b/src/Client/States/JoinServerState.cpp @@ -4,18 +4,15 @@ #include #include -#include +#include #include #include #include -#include #include #include #include -#include -#include -#include -#include +#include +#include #include #include @@ -31,7 +28,7 @@ namespace bw m_serverLabel = CreateWidget(); m_serverLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Server: ", 24)); - m_serverAddressLayout = CreateWidget(Ndk::BoxLayoutOrientation_Horizontal); + m_serverAddressLayout = CreateWidget(Nz::BoxLayoutOrientation::LeftToRight); m_serverAddressArea = m_serverAddressLayout->Add(); m_serverAddressArea->EnableBackground(true); @@ -73,20 +70,20 @@ namespace bw OnBackPressed(); }); - const ConfigFile& playerConfig = GetStateData().app->GetPlayerSettings(); + const ConfigFile& playerConfig = GetStateData().appComponent->GetPlayerSettings(); m_serverAddressArea->SetText(playerConfig.GetStringValue("JoinServer.Address")); m_serverPortArea->SetText(std::to_string(playerConfig.GetIntegerValue("JoinServer.Port"))); } - void JoinServerState::Leave(Ndk::StateMachine& fsm) + void JoinServerState::Leave(Nz::StateMachine& fsm) { m_statusLabel->Hide(); AbstractState::Leave(fsm); } - bool JoinServerState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) + bool JoinServerState::Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; @@ -114,24 +111,24 @@ namespace bw } std::string serverPort = m_serverPortArea->GetText(); - if (serverPort.IsEmpty()) + if (serverPort.empty()) { UpdateStatus("Error: blank server port", Nz::Color::Red()); return; } - long long rawPort; - if (!serverPort.ToInteger(&rawPort) || rawPort <= 0 || rawPort > 0xFFFF) + long long rawPort = std::stoi(serverPort); + if (rawPort <= 0 || rawPort > 0xFFFF) { UpdateStatus("Error: " + serverPort + " is not a valid port", Nz::Color::Red()); return; } - ConfigFile& playerConfig = GetStateData().app->GetPlayerSettings(); + ConfigFile& playerConfig = GetStateData().appComponent->GetPlayerSettings(); playerConfig.SetStringValue("JoinServer.Address", serverHostname); playerConfig.SetIntegerValue("JoinServer.Port", rawPort); - GetStateData().app->SavePlayerConfig(); + GetStateData().appComponent->SavePlayerConfig(); ConnectionState::ServerName address; address.hostname = serverHostname; diff --git a/src/Client/States/JoinServerState.hpp b/src/Client/States/JoinServerState.hpp index 0e348ce7..ec8323dc 100644 --- a/src/Client/States/JoinServerState.hpp +++ b/src/Client/States/JoinServerState.hpp @@ -9,8 +9,7 @@ #include #include -#include -#include +#include #include #include @@ -23,8 +22,8 @@ namespace bw ~JoinServerState() = default; private: - void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; + void Leave(Nz::StateMachine& fsm) override; + bool Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) override; void LayoutWidgets() override; @@ -36,7 +35,7 @@ namespace bw std::shared_ptr m_previousState; std::shared_ptr m_nextGameState; std::shared_ptr m_nextState; - Ndk::BoxLayout* m_serverAddressLayout; + Nz::BoxLayout* m_serverAddressLayout; Nz::ButtonWidget* m_backButton; Nz::ButtonWidget* m_connectionButton; Nz::LabelWidget* m_serverLabel; diff --git a/src/Client/States/MainMenuState.cpp b/src/Client/States/MainMenuState.cpp index e2291f02..4221abac 100644 --- a/src/Client/States/MainMenuState.cpp +++ b/src/Client/States/MainMenuState.cpp @@ -4,19 +4,17 @@ #include #include -#include +#include #include #include #include #include #include -#include #include #include #include #include #include -#include #include #include #include @@ -65,7 +63,7 @@ namespace bw }); } - bool MainMenuState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) + bool MainMenuState::Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; @@ -121,14 +119,14 @@ namespace bw } Nz::Vector2f cursor = center; - cursor.y -= totalSize / 2.f; + cursor.y += totalSize / 2.f; for (Nz::BaseWidget* widget : widgets) { widget->Resize({ maxWidth, widget->GetHeight() }); widget->SetPosition({ 0.f, cursor.y, 0.f }); widget->CenterHorizontal(); - cursor.y += widget->GetSize().y + padding; + cursor.y -= widget->GetSize().y + padding; } } } diff --git a/src/Client/States/MainMenuState.hpp b/src/Client/States/MainMenuState.hpp index 07c257a7..9ab95403 100644 --- a/src/Client/States/MainMenuState.hpp +++ b/src/Client/States/MainMenuState.hpp @@ -8,8 +8,7 @@ #define BURGWAR_STATES_MAINMENUSTATE_HPP #include -#include -#include +#include #include namespace bw @@ -21,7 +20,7 @@ namespace bw ~MainMenuState() = default; private: - bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; + bool Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) override; void LayoutWidgets() override; @@ -31,7 +30,7 @@ namespace bw void OnQuitPressed(); std::shared_ptr m_nextState; - Ndk::BoxLayout* m_serverAddressLayout; + Nz::BoxLayout* m_serverAddressLayout; Nz::ButtonWidget* m_joinServerButton; Nz::ButtonWidget* m_optionButton; Nz::ButtonWidget* m_quitButton; diff --git a/src/Client/States/OptionState.cpp b/src/Client/States/OptionState.cpp index 45fd5874..e59a4473 100644 --- a/src/Client/States/OptionState.cpp +++ b/src/Client/States/OptionState.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include +#include namespace bw { @@ -11,7 +11,7 @@ namespace bw AbstractState(std::move(stateData)), m_previousState(std::move(previousState)) { - ConfigFile& playerConfig = GetStateData().app->GetPlayerSettings(); + ConfigFile& playerConfig = GetStateData().appComponent->GetPlayerSettings(); m_optionWidget = CreateWidget(playerConfig); m_optionWidget->EnableBackground(true); @@ -23,14 +23,14 @@ namespace bw }); } - void OptionState::Leave(Ndk::StateMachine& fsm) + void OptionState::Leave(Nz::StateMachine& fsm) { AbstractState::Leave(fsm); - GetStateData().app->SavePlayerConfig(); + GetStateData().appComponent->SavePlayerConfig(); } - bool OptionState::Update(Ndk::StateMachine& fsm, float /*elapsedTime*/) + bool OptionState::Update(Nz::StateMachine& fsm, Nz::Time /*elapsedTime*/) { if (m_nextState) fsm.ChangeState(std::move(m_nextState)); diff --git a/src/Client/States/OptionState.hpp b/src/Client/States/OptionState.hpp index 1ae8ea76..82fcc436 100644 --- a/src/Client/States/OptionState.hpp +++ b/src/Client/States/OptionState.hpp @@ -9,8 +9,6 @@ #include #include -#include -#include #include #include @@ -23,8 +21,8 @@ namespace bw ~OptionState() = default; private: - void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; + void Leave(Nz::StateMachine& fsm) override; + bool Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) override; void LayoutWidgets() override; diff --git a/src/Client/States/ServerListState.cpp b/src/Client/States/ServerListState.cpp index 01c501bf..d53b0716 100644 --- a/src/Client/States/ServerListState.cpp +++ b/src/Client/States/ServerListState.cpp @@ -4,12 +4,12 @@ #include #include -#include -#include +#include #include #include #include -#include +#include +#include #include namespace bw @@ -19,16 +19,19 @@ namespace bw constexpr Nz::UInt32 MasterServerDataVersion = 1U; } - constexpr float RefreshTime = 15.f; + constexpr Nz::Time RefreshTime = Nz::Time::Seconds(15); ServerListState::ServerListState(std::shared_ptr stateData, std::shared_ptr previousState) : AbstractState(std::move(stateData)), m_previousState(std::move(previousState)) { - if (WebService::IsInitialized()) - m_webService.emplace(GetStateData().app->GetLogger()); + if (GetStateData().appComponent->HasWebService()) + m_webService = &GetStateData().appComponent->GetWebService(); else - bwLog(GetStateData().app->GetLogger(), LogLevel::Warning, "web services are not initialized, server listing will not work"); + { + bwLog(GetStateData().appComponent->GetLogger(), LogLevel::Warning, "web services are not initialized, server listing will not work"); + m_webService = nullptr; + } m_serverListWidget = GetStateData().canvas->Add(); @@ -55,7 +58,7 @@ namespace bw OnDirectConnectionPressed(); }); - const std::string& masterServerList = GetStateData().app->GetConfig().GetStringValue("ServerSettings.MasterServers"); + const std::string& masterServerList = GetStateData().appComponent->GetConfig().GetStringValue("ServerSettings.MasterServers"); SplitStringAny(masterServerList, "\f\n\r\t\v ", [&](const std::string_view& masterServerURI) { if (!masterServerURI.empty()) @@ -68,25 +71,25 @@ namespace bw ServerListState::~ServerListState() { //FIXME: ScrollAreaWidget uses SetParent which is broken as it doesn't register children to parent - m_serverListWidget->SetParent(&GetStateData().canvas.value()); + //m_serverListWidget->SetParent(&GetStateData().canvas.value()); m_serverListWidget->Destroy(); } - void ServerListState::Enter(Ndk::StateMachine& fsm) + void ServerListState::Enter(Nz::StateMachine& fsm) { AbstractState::Enter(fsm); m_serverListWidget->Show(); } - void ServerListState::Leave(Ndk::StateMachine& fsm) + void ServerListState::Leave(Nz::StateMachine& fsm) { AbstractState::Leave(fsm); m_serverListWidget->Hide(); } - bool ServerListState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) + bool ServerListState::Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; @@ -98,10 +101,7 @@ namespace bw fsm.ChangeState(std::move(m_nextState)); if (m_webService) - { - m_webService->Poll(); RefreshServers(elapsedTime); - } return true; } @@ -180,19 +180,19 @@ namespace bw void ServerListState::OnServerConnectionPressed(const std::string& masterServer, const std::string& uuid) { - std::unique_ptr request = WebRequest::Get(masterServer + "/server/" + uuid + "/connection_details", [this, stateData = GetStateDataPtr(), masterServer, uuid](WebRequestResult&& result) + std::unique_ptr request = m_webService->CreateGetRequest(masterServer + "/server/" + uuid + "/connection_details", [this, stateData = GetStateDataPtr(), masterServer, uuid](Nz::WebRequestResult&& result) { if (!result) { - bwLog(stateData->app->GetLogger(), LogLevel::Error, "failed to connect to server {0} from {1}, connect request failed: {2}", uuid, masterServer, result.GetErrorMessage()); + bwLog(stateData->appComponent->GetLogger(), LogLevel::Error, "failed to connect to server {0} from {1}, connect request failed: {2}", uuid, masterServer, result.GetErrorMessage()); return; } - switch (result.GetReponseCode()) + switch (result.GetStatusCode()) { case 200: { - bwLog(stateData->app->GetLogger(), LogLevel::Debug, "successfully received connection info of {0} from {1}", uuid, masterServer); + bwLog(stateData->appComponent->GetLogger(), LogLevel::Debug, "successfully received connection info of {0} from {1}", uuid, masterServer); nlohmann::json connectionDetails; try @@ -201,25 +201,25 @@ namespace bw } catch (const std::exception& e) { - bwLog(stateData->app->GetLogger(), LogLevel::Error, "failed to parse connection details: {0}", e.what()); + bwLog(stateData->appComponent->GetLogger(), LogLevel::Error, "failed to parse connection details: {0}", e.what()); return; } Nz::UInt32 dataVersion = connectionDetails.value("data_version", 0); if (dataVersion != MasterServerDataVersion) - bwLog(stateData->app->GetLogger(), LogLevel::Warning, "unexpected data version (expected {0}, got {1})", MasterServerDataVersion, dataVersion); + bwLog(stateData->appComponent->GetLogger(), LogLevel::Warning, "unexpected data version (expected {0}, got {1})", MasterServerDataVersion, dataVersion); std::string addresses = connectionDetails.value("ip", ""); if (addresses.empty()) { - bwLog(stateData->app->GetLogger(), LogLevel::Error, "missing ip field, aborting connection."); + bwLog(stateData->appComponent->GetLogger(), LogLevel::Error, "missing ip field, aborting connection."); return; } Nz::UInt16 serverPort = connectionDetails.value("port", Nz::UInt16(0)); if (serverPort == 0) { - bwLog(stateData->app->GetLogger(), LogLevel::Error, "missing or invalid port field ({0}), aborting connection.", serverPort); + bwLog(stateData->appComponent->GetLogger(), LogLevel::Error, "missing or invalid port field ({0}), aborting connection.", serverPort); return; } @@ -239,12 +239,12 @@ namespace bw } default: - bwLog(stateData->app->GetLogger(), LogLevel::Error, "failed to connect to server {0} from {1}, request failed with code {2}", uuid, masterServer, result.GetReponseCode()); + bwLog(stateData->appComponent->GetLogger(), LogLevel::Error, "failed to connect to server {0} from {1}, request failed with code {2}", uuid, masterServer, result.GetStatusCode()); break; } }); - m_webService->AddRequest(std::move(request)); + m_webService->QueueRequest(std::move(request)); } void ServerListState::RefreshServers(Nz::Time elapsedTime) @@ -255,23 +255,23 @@ namespace bw MasterServerData& masterServerData = it.value(); masterServerData.timeBeforeRefresh -= elapsedTime; - if (masterServerData.timeBeforeRefresh < 0.f) + if (masterServerData.timeBeforeRefresh < Nz::Time::Zero()) { - masterServerData.timeBeforeRefresh = RefreshTime / 2.f; + masterServerData.timeBeforeRefresh = RefreshTime / Nz::Time::Seconds(2.f); - std::unique_ptr request = WebRequest::Get(masterServer + "/servers", [this, stateData = GetStateDataPtr(), url = masterServer](WebRequestResult&& result) + std::unique_ptr request = m_webService->CreateGetRequest(masterServer + "/servers", [this, stateData = GetStateDataPtr(), url = masterServer](Nz::WebRequestResult&& result) { if (!result) { - bwLog(stateData->app->GetLogger(), LogLevel::Error, "failed to refresh server list from {0}, register request failed: {1}", url, result.GetErrorMessage()); + bwLog(stateData->appComponent->GetLogger(), LogLevel::Error, "failed to refresh server list from {0}, register request failed: {1}", url, result.GetErrorMessage()); return; } - switch (result.GetReponseCode()) + switch (result.GetStatusCode()) { case 200: { - bwLog(stateData->app->GetLogger(), LogLevel::Debug, "successfully refreshed server list from {0}", url); + bwLog(stateData->appComponent->GetLogger(), LogLevel::Debug, "successfully refreshed server list from {0}", url); UpdateServerList(url, nlohmann::json::parse(result.GetBody())); @@ -283,12 +283,12 @@ namespace bw } default: - bwLog(stateData->app->GetLogger(), LogLevel::Error, "failed to refresh server list from {0}, request failed with code {1}", url, result.GetReponseCode()); + bwLog(stateData->appComponent->GetLogger(), LogLevel::Error, "failed to refresh server list from {0}, request failed with code {1}", url, result.GetStatusCode()); break; } }); - m_webService->AddRequest(std::move(request)); + m_webService->QueueRequest(std::move(request)); } } } @@ -305,7 +305,7 @@ namespace bw Nz::UInt32 dataVersion = serverListDoc.value("data_version", 0); if (dataVersion != MasterServerDataVersion) - bwLog(stateData.app->GetLogger(), LogLevel::Warning, "unexpected data version (expected {0}, got {1})", MasterServerDataVersion, dataVersion); + bwLog(stateData.appComponent->GetLogger(), LogLevel::Warning, "unexpected data version (expected {0}, got {1})", MasterServerDataVersion, dataVersion); tsl::hopscotch_map newServerList; @@ -314,14 +314,14 @@ namespace bw std::string uuid = serverDoc.value("uuid", ""); if (uuid.empty()) { - bwLog(stateData.app->GetLogger(), LogLevel::Error, "got server without mandatory uuid field"); + bwLog(stateData.appComponent->GetLogger(), LogLevel::Error, "got server without mandatory uuid field"); continue; } Nz::UInt32 version = serverDoc.value("game_version", Nz::UInt32(0)); if (version != GameVersion) { - bwLog(stateData.app->GetLogger(), LogLevel::Debug, "ignored server {0} because version didn't match (got {1}, expected {2})", uuid, version, GameVersion); + bwLog(stateData.appComponent->GetLogger(), LogLevel::Debug, "ignored server {0} because version didn't match (got {1}, expected {2})", uuid, version, GameVersion); continue; } @@ -344,7 +344,7 @@ namespace bw else { if (masterServerData.receivedData) - bwLog(stateData.app->GetLogger(), LogLevel::Debug, "server {0} appeared (from {1})", uuid, masterServer); + bwLog(stateData.appComponent->GetLogger(), LogLevel::Debug, "server {0} appeared (from {1})", uuid, masterServer); // New server serverData.connectButton = m_serverListWidget->Add(); @@ -396,7 +396,7 @@ namespace bw for (auto&& [uuid, serverData] : masterServerData.serverList) { - bwLog(stateData.app->GetLogger(), LogLevel::Debug, "server {0} disappeared (from {1})", uuid, masterServer); + bwLog(stateData.appComponent->GetLogger(), LogLevel::Debug, "server {0} disappeared (from {1})", uuid, masterServer); // Delete old servers serverData.connectButton->Destroy(); @@ -405,7 +405,7 @@ namespace bw if (!masterServerData.receivedData) { - bwLog(stateData.app->GetLogger(), LogLevel::Debug, "received {0} server(s) from {1}", newServerList.size(), masterServer); + bwLog(stateData.appComponent->GetLogger(), LogLevel::Debug, "received {0} server(s) from {1}", newServerList.size(), masterServer); masterServerData.receivedData = true; } diff --git a/src/Client/States/ServerListState.hpp b/src/Client/States/ServerListState.hpp index 3f510810..b79340d8 100644 --- a/src/Client/States/ServerListState.hpp +++ b/src/Client/States/ServerListState.hpp @@ -7,10 +7,9 @@ #ifndef BURGWAR_STATES_SERVERLISTSTATE_HPP #define BURGWAR_STATES_SERVERLISTSTATE_HPP -#include +#include #include -#include -#include +#include #include #include #include @@ -26,9 +25,9 @@ namespace bw ~ServerListState(); private: - void Enter(Ndk::StateMachine& fsm) override; - void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; + void Enter(Nz::StateMachine& fsm) override; + void Leave(Nz::StateMachine& fsm) override; + bool Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) override; void LayoutWidgets() override; @@ -49,7 +48,7 @@ namespace bw struct MasterServerData { tsl::hopscotch_map serverList; - float timeBeforeRefresh = 0.f; + Nz::Time timeBeforeRefresh = Nz::Time::Zero(); bool receivedData = false; //< Did we already successfully refresh from this master server? }; @@ -57,12 +56,12 @@ namespace bw Nz::ButtonWidget* m_backButton; Nz::ButtonWidget* m_directConnectButton; Nz::ScrollAreaWidget* m_serverListScrollbar; + Nz::WebService* m_webService; std::shared_ptr m_previousState; std::shared_ptr m_nextGameState; std::shared_ptr m_nextState; std::vector> m_tempOrderedServerList; tsl::hopscotch_map m_masterServers; - std::optional m_webService; }; } diff --git a/src/Client/States/StartServerState.cpp b/src/Client/States/StartServerState.cpp index 919cb1fa..1cd92ac0 100644 --- a/src/Client/States/StartServerState.cpp +++ b/src/Client/States/StartServerState.cpp @@ -4,20 +4,17 @@ #include #include -#include +#include +#include #include #include #include -#include #include #include #include #include #include -#include -#include -#include -#include +#include #include #include @@ -34,14 +31,14 @@ namespace bw m_background->EnableBackground(true); m_background->SetBackgroundColor(Nz::Color(0, 0, 0, 100)); - m_serverConfigLayout = m_background->Add(Ndk::BoxLayoutOrientation_Vertical); + m_serverConfigLayout = m_background->Add(Nz::BoxLayoutOrientation::TopToBottom); m_serverConfigLayout->SetPosition(10.f, 10.f); m_title = m_serverConfigLayout->Add(); m_title->UpdateText(Nz::SimpleTextDrawer::Draw("Server configuration", 36)); m_title->CenterHorizontal(); - Ndk::BoxLayout* gamemodeLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); + Nz::BoxLayout* gamemodeLayout = m_serverConfigLayout->Add(Nz::BoxLayoutOrientation::LeftToRight); Nz::LabelWidget* gamemodeLabel = gamemodeLayout->Add(); gamemodeLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Gamemode: ", 24)); @@ -52,7 +49,7 @@ namespace bw m_gamemodeArea->SetTextColor(Nz::Color::Black()); m_gamemodeArea->SetMaximumHeight(m_gamemodeArea->GetMinimumHeight()); - Ndk::BoxLayout* mapLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); + Nz::BoxLayout* mapLayout = m_serverConfigLayout->Add(Nz::BoxLayoutOrientation::LeftToRight); Nz::LabelWidget* mapLabel = mapLayout->Add(); mapLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Map: ", 24)); @@ -63,7 +60,7 @@ namespace bw m_mapArea->SetTextColor(Nz::Color::Black()); m_mapArea->SetMaximumHeight(m_mapArea->GetMinimumHeight()); - Ndk::BoxLayout* portLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); + Nz::BoxLayout* portLayout = m_serverConfigLayout->Add(Nz::BoxLayoutOrientation::LeftToRight); Nz::LabelWidget* portLabel = portLayout->Add(); portLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Port: ", 24)); @@ -81,10 +78,14 @@ namespace bw return true; }); - m_listServerCheckbox = m_serverConfigLayout->Add(); - m_listServerCheckbox->UpdateText(Nz::SimpleTextDrawer::Draw("Register the server online", 24)); + Nz::BoxLayout* listServerLayout = m_serverConfigLayout->Add(Nz::BoxLayoutOrientation::LeftToRight); - m_nameLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); + Nz::LabelWidget* listServerLabel = listServerLayout->Add(); + listServerLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Register the server online", 24)); + + m_listServerCheckbox = listServerLayout->Add(); + + m_nameLayout = m_serverConfigLayout->Add(Nz::BoxLayoutOrientation::LeftToRight); Nz::LabelWidget* nameLabel = m_nameLayout->Add(); nameLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Name: ", 24)); @@ -95,7 +96,7 @@ namespace bw m_nameArea->SetTextColor(Nz::Color::Black()); m_nameArea->SetMaximumHeight(m_mapArea->GetMinimumHeight()); - m_descriptionLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); + m_descriptionLayout = m_serverConfigLayout->Add(Nz::BoxLayoutOrientation::LeftToRight); Nz::LabelWidget* descLabel = m_descriptionLayout->Add(); descLabel->UpdateText(Nz::SimpleTextDrawer::Draw("Description: ", 24)); @@ -106,7 +107,7 @@ namespace bw m_descriptionArea->SetTextColor(Nz::Color::Black()); m_descriptionArea->SetMaximumHeight(m_mapArea->GetMinimumHeight()); - Ndk::BoxLayout* buttonLayout = m_serverConfigLayout->Add(Ndk::BoxLayoutOrientation_Horizontal); + Nz::BoxLayout* buttonLayout = m_serverConfigLayout->Add(Nz::BoxLayoutOrientation::LeftToRight); m_backButton = buttonLayout->Add(); m_backButton->UpdateText(Nz::SimpleTextDrawer::Draw("Back", 24)); @@ -125,11 +126,11 @@ namespace bw }); } - void StartServerState::Enter(Ndk::StateMachine& fsm) + void StartServerState::Enter(Nz::StateMachine& fsm) { AbstractState::Enter(fsm); - const ConfigFile& playerConfig = GetStateData().app->GetPlayerSettings(); + const ConfigFile& playerConfig = GetStateData().appComponent->GetPlayerSettings(); m_descriptionArea->SetText(playerConfig.GetStringValue("StartServer.Description")); m_gamemodeArea->SetText(playerConfig.GetStringValue("StartServer.Gamemode")); @@ -139,7 +140,7 @@ namespace bw m_portArea->SetText(std::to_string(playerConfig.GetIntegerValue("StartServer.Port"))); } - bool StartServerState::Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) + bool StartServerState::Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) { if (!AbstractState::Update(fsm, elapsedTime)) return false; @@ -159,7 +160,7 @@ namespace bw void StartServerState::OnStartServerPressed() { - ClientApp* app = GetStateData().app; + ClientAppComponent* app = GetStateData().appComponent; std::string gamemode = m_gamemodeArea->GetText(); if (gamemode.empty()) @@ -176,14 +177,15 @@ namespace bw } std::string serverPort = m_portArea->GetText(); - if (serverPort.IsEmpty()) + if (serverPort.empty()) { UpdateStatus("Error: blank server port", Nz::Color::Red()); return; } - long long rawPort; - if (!serverPort.ToInteger(&rawPort) || rawPort < 0 || rawPort > 0xFFFF) + bool ok; + long long rawPort = Nz::StringToNumber(serverPort, 10, &ok); + if (!ok || rawPort < 0 || rawPort > 0xFFFF) { UpdateStatus("Error: " + serverPort + " is not a valid port", Nz::Color::Red()); return; @@ -240,7 +242,7 @@ namespace bw matchSettings.name = std::move(serverName); matchSettings.registerToMasterServer = listServer; matchSettings.port = static_cast(rawPort); - matchSettings.tickDuration = 1.f / config.GetFloatValue("ServerSettings.TickRate"); + matchSettings.tickDuration = Nz::Time::TickDuration(config.GetFloatValue("ServerSettings.TickRate")); Match::ModSettings modSettings; diff --git a/src/Client/States/StartServerState.hpp b/src/Client/States/StartServerState.hpp index b56acd1f..603aaf04 100644 --- a/src/Client/States/StartServerState.hpp +++ b/src/Client/States/StartServerState.hpp @@ -8,8 +8,8 @@ #define BURGWAR_STATES_LOGINSTATE_HPP #include -#include -#include +#include +#include #include #include @@ -22,8 +22,8 @@ namespace bw ~StartServerState() = default; private: - void Enter(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, Nz::Time elapsedTime) override; + void Enter(Nz::StateMachine& fsm) override; + bool Update(Nz::StateMachine& fsm, Nz::Time elapsedTime) override; void LayoutWidgets() override; @@ -35,9 +35,9 @@ namespace bw std::shared_ptr m_previousState; std::shared_ptr m_nextGameState; std::shared_ptr m_nextState; - Ndk::BoxLayout* m_descriptionLayout; - Ndk::BoxLayout* m_nameLayout; - Ndk::BoxLayout* m_serverConfigLayout; + Nz::BoxLayout* m_descriptionLayout; + Nz::BoxLayout* m_nameLayout; + Nz::BoxLayout* m_serverConfigLayout; Nz::BaseWidget* m_background; Nz::ButtonWidget* m_backButton; Nz::ButtonWidget* m_startServerButton; diff --git a/src/Client/States/StateData.hpp b/src/Client/States/StateData.hpp index 64297607..5463fba1 100644 --- a/src/Client/States/StateData.hpp +++ b/src/Client/States/StateData.hpp @@ -7,21 +7,30 @@ #ifndef BURGWAR_STATES_STATEDATA_HPP #define BURGWAR_STATES_STATEDATA_HPP -#include +#include +#include +#include #include #include #include +namespace Nz +{ + class ApplicationBase; +} + namespace bw { - class ClientApp; + class ClientAppComponent; struct StateData { std::optional canvas; - ClientApp* app; - entt::registry* world; - Nz::RenderWindow* window; + ClientAppComponent* appComponent; + Nz::ApplicationBase* app; + Nz::EnttWorld* world; + Nz::Window* window; + Nz::WindowSwapchain* swapchain; }; } diff --git a/src/Client/main.cpp b/src/Client/main.cpp index 361b3bf6..ac4936b7 100644 --- a/src/Client/main.cpp +++ b/src/Client/main.cpp @@ -4,22 +4,34 @@ #include #include +#include +#include +#include +#include +#include #include -#include +#include +#include #include
int BurgWarGame(int argc, char* argv[]) { - Nz::Initializer network; - bw::ClientApp app(argc, argv); - app.EnableFPSCounter(true); + Nz::Renderer::Config config; + config.preferredAPI = Nz::RenderAPI::OpenGL; - Nz::Audio::SetSpeedOfSound(343.3f * 100.f); + Nz::Application app(argc, argv, config); + app.AddComponent(); + app.AddComponent(); + app.AddComponent(); + app.AddComponent(argc, argv); + //app.EnableFPSCounter(true); - Nz::SoundBufferParams params; + //Nz::Audio::SetSpeedOfSound(343.3f * 100.f); + + /*Nz::SoundBufferParams params; params.forceMono = true; - Nz::SoundBufferManager::SetDefaultParameters(params); + Nz::SoundBufferManager::SetDefaultParameters(params);*/ return app.Run(); } diff --git a/src/ClientLib/Camera.cpp b/src/ClientLib/Camera.cpp index ffe371a7..d9924290 100644 --- a/src/ClientLib/Camera.cpp +++ b/src/ClientLib/Camera.cpp @@ -3,23 +3,25 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include +#include #include #include namespace bw { - Camera::Camera(entt::registry& registry, Nz::RenderTarget* renderTarget, bool perspective) : + Camera::Camera(Nz::EnttWorld& world, Nz::RenderTarget* renderTarget, bool perspective) : m_isPerspective(!perspective), // To enable it after m_zoomFactor(1.f) { constexpr float fov = 30.f; - m_cameraEntity = entt::handle(registry, registry.create()); + m_cameraEntity = world.CreateEntity(); auto& camera = m_cameraEntity->emplace(renderTarget, Nz::ProjectionType::Orthographic); camera.UpdateFOV(fov); camera.UpdateTarget(renderTarget); camera.UpdateZFar(20000.f); + camera.UpdateRenderMask(2); m_cameraEntity->emplace(); @@ -60,16 +62,14 @@ namespace bw Nz::Vector2f Camera::Project(const Nz::Vector2f& worldPosition) const { - throw std::runtime_error("EnTT TODO"); - //auto& entityCamera = m_cameraEntity->get(); - //return Nz::Vector2f(entityCamera.Project(worldPosition)); + auto& entityCamera = m_cameraEntity->get(); + return Nz::Vector2f(entityCamera.Project(worldPosition)); } Nz::Vector3f Camera::Project(const Nz::Vector3f& worldPosition) const { - throw std::runtime_error("EnTT TODO"); - //auto& entityCamera = m_cameraEntity->get(); - //return entityCamera.Project(worldPosition); + auto& entityCamera = m_cameraEntity->get(); + return entityCamera.Project(worldPosition); } void Camera::MoveBy(const Nz::Vector2f& offset) @@ -113,20 +113,14 @@ namespace bw Nz::Vector2f Camera::Unproject(const Nz::Vector2f& screenPosition) const { - throw std::runtime_error("EnTT TODO"); - - //auto& entityCamera = m_cameraEntity->get(); - - //return Nz::Vector2f(entityCamera.Unproject(Nz::Vector3f(screenPosition.x, screenPosition.y, m_projectedDepth))); + auto& entityCamera = m_cameraEntity->get(); + return Nz::Vector2f(entityCamera.Unproject(Nz::Vector3f(screenPosition.x, screenPosition.y, m_projectedDepth))); } Nz::Vector3f Camera::Unproject(const Nz::Vector3f& screenPosition) const { - throw std::runtime_error("EnTT TODO"); - - //auto& entityCamera = m_cameraEntity->get(); - - //return entityCamera.Unproject(screenPosition); + auto& entityCamera = m_cameraEntity->get(); + return entityCamera.Unproject(screenPosition); } void Camera::UpdateProjection() @@ -174,8 +168,7 @@ namespace bw initialPosition.z = size.y * 0.5f * m_invFovTan; entityNode.SetInitialPosition(initialPosition); - throw std::runtime_error("EnTT TODO"); - //m_projectedDepth = entityCamera.Project({ 0.f, 0.f, 0.f }).z; + m_projectedDepth = entityCamera.Project({ 0.f, 0.f, 0.f }).z; } else entityCamera.UpdateSize(size); diff --git a/src/ClientLib/ClientEditorAppComponent.cpp b/src/ClientLib/ClientEditorAppComponent.cpp index 6b340f65..a1a1a753 100644 --- a/src/ClientLib/ClientEditorAppComponent.cpp +++ b/src/ClientLib/ClientEditorAppComponent.cpp @@ -23,7 +23,7 @@ namespace bw { namespace { - static constexpr const char* PlayerSettingsFile = "playerconfig.lua"; + static constexpr std::string_view PlayerSettingsFile = "playerconfig.lua"; } ClientEditorAppComponent::ClientEditorAppComponent(Nz::ApplicationBase& app, int argc, char* argv[], LogSide side, const SharedAppConfig& configFile) : diff --git a/src/ClientLib/ClientEditorLayer.cpp b/src/ClientLib/ClientEditorLayer.cpp index e027e617..5c548edf 100644 --- a/src/ClientLib/ClientEditorLayer.cpp +++ b/src/ClientLib/ClientEditorLayer.cpp @@ -11,66 +11,29 @@ namespace bw { ClientEditorLayer::ClientEditorLayer(SharedMatch& match, LayerIndex layerIndex) : - SharedLayer(match, layerIndex) + SharedLayer(match, layerIndex), + m_frameSystemGraph(GetWorld()), + m_preFrameSystemGraph(GetWorld()), + m_postFrameSystemGraph(GetWorld()) { - auto& systemGraph = GetSystemGraph(); - systemGraph.AddSystem(); - systemGraph.AddSystem(); - systemGraph.AddSystem(); + m_frameSystemGraph.AddSystem(); + m_frameSystemGraph.AddSystem(); + m_preFrameSystemGraph.AddSystem(); + m_postFrameSystemGraph.AddSystem(); } - /*void ClientEditorLayer::FrameUpdate(Nz::Time elapsedTime) + void ClientEditorLayer::FrameUpdate(Nz::Time elapsedTime) { - entt::registry& world = GetWorld(); - world.ForEachSystem([](Ndk::BaseSystem& system) - { - system.Enable(false); - }); - - world.GetSystem().Enable(true); - world.GetSystem().Enable(true); - - world.Update(elapsedTime); + m_frameSystemGraph.Update(elapsedTime); } void ClientEditorLayer::PreFrameUpdate(Nz::Time elapsedTime) { - entt::registry& world = GetWorld(); - world.ForEachSystem([](Ndk::BaseSystem& system) - { - system.Enable(false); - }); - - world.GetSystem().Enable(true); - - world.Update(elapsedTime); + m_preFrameSystemGraph.Update(elapsedTime); } void ClientEditorLayer::PostFrameUpdate(Nz::Time elapsedTime) { - entt::registry& world = GetWorld(); - world.ForEachSystem([](Ndk::BaseSystem& system) - { - system.Enable(false); - }); - - world.GetSystem().Enable(true); - - world.Update(elapsedTime); + m_postFrameSystemGraph.Update(elapsedTime); } - - void ClientEditorLayer::TickUpdate(Nz::Time elapsedTime) - { - entt::registry& world = GetWorld(); - world.ForEachSystem([](Ndk::BaseSystem& system) - { - system.Enable(true); - }); - - world.GetSystem().Enable(false); - world.GetSystem().Enable(false); - world.GetSystem().Enable(false); - - SharedLayer::TickUpdate(elapsedTime); - }*/ } diff --git a/src/ClientLib/ClientLayer.cpp b/src/ClientLib/ClientLayer.cpp index 76e612e8..0f813c1e 100644 --- a/src/ClientLib/ClientLayer.cpp +++ b/src/ClientLib/ClientLayer.cpp @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include namespace bw @@ -285,7 +285,7 @@ namespace bw { auto& physProperties = *entityData.physicsProperties; - if (Nz::RigidBody2DComponent* entityPhys = layerEntity->GetEntity().try_get()) + if (Nz::ChipmunkRigidBody2DComponent* entityPhys = layerEntity->GetEntity().try_get()) { entityPhys->SetMass(physProperties.mass, false); entityPhys->SetMomentOfInertia(physProperties.momentOfInertia); @@ -457,7 +457,7 @@ namespace bw { entt::handle entity = localEntity.GetEntity(); - auto& entityPhys = entity.get(); + auto& entityPhys = entity.get(); entityPhys.SetMass(packet.mass, false); entityPhys.SetMomentOfInertia(packet.momentOfInertia); diff --git a/src/ClientLib/ClientLayerEntity.cpp b/src/ClientLib/ClientLayerEntity.cpp index d2fae808..dfc12ec0 100644 --- a/src/ClientLib/ClientLayerEntity.cpp +++ b/src/ClientLib/ClientLayerEntity.cpp @@ -39,7 +39,7 @@ namespace bw { assert(IsPhysical()); - auto& entityPhys = GetEntity().get(); + auto& entityPhys = GetEntity().get(); return entityPhys.GetAngularVelocity(); } @@ -47,12 +47,14 @@ namespace bw { if (!m_ghostEntity) { - /*entt::entity ghostEntity = GetEntity()->GetWorld()->CreateEntity(); - ghostEntity->AddComponent(); + entt::registry& registry = *GetEntity().registry(); + + entt::handle ghostEntity(registry, registry.create()); + ghostEntity.emplace(); m_ghostEntity = std::make_unique(m_layer, ghostEntity, ClientsideId, m_layer.GetClientMatch().AllocateClientUniqueId()); - for (auto& renderable : m_attachedRenderables) + /*for (auto& renderable : m_attachedRenderables) { if (std::unique_ptr clonedRenderable = renderable.renderable->Clone()) { @@ -86,7 +88,7 @@ namespace bw { assert(IsPhysical()); - auto& entityPhys = GetEntity().get(); + auto& entityPhys = GetEntity().get(); return entityPhys.GetVelocity(); } @@ -94,7 +96,7 @@ namespace bw { assert(IsPhysical()); - auto& entityPhys = GetEntity().get(); + auto& entityPhys = GetEntity().get(); return entityPhys.GetPosition(); } @@ -102,7 +104,7 @@ namespace bw { assert(IsPhysical()); - auto& entityPhys = GetEntity().get(); + auto& entityPhys = GetEntity().get(); return entityPhys.GetRotation(); } diff --git a/src/ClientLib/ClientMatch.cpp b/src/ClientLib/ClientMatch.cpp index f19eece8..2a5ad85e 100644 --- a/src/ClientLib/ClientMatch.cpp +++ b/src/ClientLib/ClientMatch.cpp @@ -46,11 +46,12 @@ namespace bw { - ClientMatch::ClientMatch(ClientEditorAppComponent& burgApp, Nz::Window* window, Nz::RenderTarget* renderTarget, Nz::Canvas* canvas, ClientSession& session, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData) : + ClientMatch::ClientMatch(ClientEditorAppComponent& burgApp, Nz::Window* window, Nz::RenderTarget* renderTarget, Nz::Canvas* canvas, Nz::EnttWorld& renderWorld, ClientSession& session, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData) : SharedMatch(burgApp, LogSide::Client, "local", Nz::Time::Seconds(matchData.tickDuration)), m_gamemodeName(matchData.gamemode), m_canvas(canvas), m_freeClientId(-1), + m_renderWorld(renderWorld), m_renderTarget(renderTarget), m_window(window), m_activeLayerIndex(NoLayer), @@ -95,16 +96,15 @@ namespace bw auto& playerSettings = burgApp.GetPlayerSettings(); - m_renderWorld.systemGraph.AddSystem(); - m_renderWorld.systemGraph.AddSystem(*this); - m_renderWorld.systemGraph.AddSystem(playerSettings); + m_renderWorld.AddSystem(*this); + m_renderWorld.AddSystem(playerSettings); - m_camera.emplace(m_renderWorld.registry, renderTarget, true); - m_camera->SetZoomFactor(0.8f); - - m_currentLayer = entt::handle(m_renderWorld.registry, m_renderWorld.registry.create()); + m_currentLayer = m_renderWorld.CreateEntity(); m_currentLayer.emplace(); - m_currentLayer.emplace(m_renderWorld.registry, m_currentLayer); + m_currentLayer.emplace(m_renderWorld, m_currentLayer); + + m_camera.emplace(m_renderWorld, renderTarget, false); + m_camera->SetZoomFactor(0.8f); InitializeRemoteConsole(); @@ -571,7 +571,7 @@ namespace bw } else { - auto& ghostNode = serverEntity.serverGhost->GetComponent(); + auto& ghostNode = serverEntity.serverGhost->GetComponent(); ghostNode.SetPosition(position); ghostNode.SetRotation(rotation); } @@ -611,7 +611,7 @@ namespace bw layerPtr->SyncVisuals(); } - m_renderWorld.systemGraph.Update(elapsedTime); + //m_renderWorld.Update(elapsedTime); if (m_gamemode) m_gamemode->ExecuteCallback(elapsedTime); @@ -1491,13 +1491,16 @@ namespace bw if (playerInputData.movement) { auto& playerMovement = controlledEntity.get(); - auto& playerPhysics = controlledEntity.get(); + auto& playerPhysics = controlledEntity.get(); playerMovement.UpdateGroundState(playerInputData.movement->isOnGround); playerMovement.UpdateJumpTime(playerInputData.movement->jumpTime); playerMovement.UpdateWasJumpingState(playerInputData.movement->wasJumping); - playerPhysics.SetFriction(0, playerInputData.movement->friction); - playerPhysics.SetSurfaceVelocity(0, playerInputData.movement->surfaceVelocity); + if (playerPhysics.GetShapeCount() > 0) + { + playerPhysics.SetFriction(0, playerInputData.movement->friction); + playerPhysics.SetSurfaceVelocity(0, playerInputData.movement->surfaceVelocity); + } } // WTF? @@ -1732,15 +1735,18 @@ namespace bw auto entity = controllerData.controlledEntity->GetEntity(); if (PlayerMovementComponent* playerMovement = entity.try_get()) { - auto& playerPhysics = entity.get(); + auto& playerPhysics = entity.get(); auto& movementData = playerData.movement.emplace(); movementData.isOnGround = playerMovement->IsOnGround(); movementData.jumpTime = playerMovement->GetJumpTime(); movementData.wasJumping = playerMovement->WasJumping(); - movementData.friction = playerPhysics.GetFriction(0); - movementData.surfaceVelocity = playerPhysics.GetSurfaceVelocity(0); + if (playerPhysics.GetShapeCount() > 0) + { + movementData.friction = playerPhysics.GetFriction(0); + movementData.surfaceVelocity = playerPhysics.GetSurfaceVelocity(0); + } } if (InputComponent* inputComponent = entity.try_get()) diff --git a/src/ClientLib/EscapeMenu.cpp b/src/ClientLib/EscapeMenu.cpp index 24832550..3289fce0 100644 --- a/src/ClientLib/EscapeMenu.cpp +++ b/src/ClientLib/EscapeMenu.cpp @@ -122,13 +122,13 @@ namespace bw m_backgroundWidget->Resize({ maxWidth, height }); - float cursor = padding; + float cursor = height - padding; for (Nz::ButtonWidget* button : buttons) { button->SetPosition(0.f, cursor); button->CenterHorizontal(); - cursor += button->GetHeight() + buttonPadding; + cursor -= button->GetHeight() + buttonPadding; } } else diff --git a/src/ClientLib/HttpDownloadManager.cpp b/src/ClientLib/HttpDownloadManager.cpp index 4b95aeb9..94d6c071 100644 --- a/src/ClientLib/HttpDownloadManager.cpp +++ b/src/ClientLib/HttpDownloadManager.cpp @@ -11,11 +11,11 @@ namespace bw { - HttpDownloadManager::HttpDownloadManager(const Logger& logger, std::vector baseDownloadUrls, std::size_t maxSimultaneousDownload) : + HttpDownloadManager::HttpDownloadManager(Nz::WebService& webService, const Logger& logger, std::vector baseDownloadUrls, std::size_t maxSimultaneousDownload) : m_nextFileIndex(0), m_baseDownloadUrls(std::move(baseDownloadUrls)), m_logger(logger), - m_webService(logger) + m_webService(webService) { assert(!m_baseDownloadUrls.empty()); for (std::string& downloadUrl : m_baseDownloadUrls) @@ -83,7 +83,9 @@ namespace bw std::string downloadUrl = m_baseDownloadUrls[pendingDownload.downloadUrlIndex] + "/" + pendingDownload.downloadPath; - std::unique_ptr webRequest = WebRequest::Get(downloadUrl); + std::unique_ptr webRequest = m_webService.AllocateRequest(); + webRequest->SetupGet(); + webRequest->SetURL(downloadUrl); webRequest->SetMaximumFileSize(pendingDownload.expectedSize); webRequest->SetDataCallback([this, &request](const void* data, std::size_t size) @@ -112,7 +114,7 @@ namespace bw return true; }); - webRequest->SetResultCallback([this, &request](WebRequestResult&& result) + webRequest->SetResultCallback([this, &request](Nz::WebRequestResult&& result) { // Handle download end PendingFile& pendingDownload = m_downloadList[request.fileIndex]; @@ -127,7 +129,7 @@ namespace bw if (result) { - if (long responseCode = result.GetReponseCode(); responseCode == 200) + if (long responseCode = result.GetStatusCode(); responseCode == 200) { if (pendingDownload.downloadedSize == pendingDownload.expectedSize) { @@ -203,7 +205,7 @@ namespace bw request.file.Open(filePath, Nz::OpenMode::WriteOnly | Nz::OpenMode::Truncate); request.keepInMemory = pendingDownload.keepInMemory; - m_webService.AddRequest(std::move(webRequest)); + m_webService.QueueRequest(std::move(webRequest)); OnDownloadStarted(this, m_nextFileIndex, downloadUrl); diff --git a/src/ClientLib/LayerVisualEntity.cpp b/src/ClientLib/LayerVisualEntity.cpp index 8b1bf5e8..05c3157f 100644 --- a/src/ClientLib/LayerVisualEntity.cpp +++ b/src/ClientLib/LayerVisualEntity.cpp @@ -11,8 +11,8 @@ #include #include #include +#include #include -#include #include namespace bw @@ -158,7 +158,7 @@ namespace bw bool LayerVisualEntity::IsPhysical() const { - return m_entity->try_get() != nullptr; //< TODO: Cache this? + return m_entity->try_get() != nullptr; //< TODO: Cache this? } void LayerVisualEntity::SyncVisuals() @@ -230,7 +230,7 @@ namespace bw if (CollisionDataComponent* entityCollData = m_entity->try_get()) { - auto& entityCollider = m_entity->get(); + auto& entityCollider = m_entity->get(); entityCollider.SetGeom(entityCollData->BuildCollider(newScale), false, false); } @@ -240,7 +240,7 @@ namespace bw { if (IsPhysical()) { - auto& entityPhys = m_entity->get(); + auto& entityPhys = m_entity->get(); entityPhys.SetPosition(position); entityPhys.SetRotation(rotation); } @@ -256,7 +256,7 @@ namespace bw { if (IsPhysical()) { - auto& entityPhys = m_entity->get(); + auto& entityPhys = m_entity->get(); entityPhys.SetAngularVelocity(angularVel); entityPhys.SetPosition(position); entityPhys.SetRotation(rotation); diff --git a/src/ClientLib/Scripting/ClientEditorEntityStore.cpp b/src/ClientLib/Scripting/ClientEditorEntityStore.cpp index 76c96b82..acbf277e 100644 --- a/src/ClientLib/Scripting/ClientEditorEntityStore.cpp +++ b/src/ClientLib/Scripting/ClientEditorEntityStore.cpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include namespace bw diff --git a/src/ClientLib/Scripting/ClientElementLibrary.cpp b/src/ClientLib/Scripting/ClientElementLibrary.cpp index 248db381..0da780d5 100644 --- a/src/ClientLib/Scripting/ClientElementLibrary.cpp +++ b/src/ClientLib/Scripting/ClientElementLibrary.cpp @@ -14,8 +14,10 @@ #include #include #include +#include +#include +#include #include -#include #include #include @@ -98,17 +100,17 @@ namespace bw else color = Nz::Color::White(); - //TODO: Don't create a material everytime - /*Nz::MaterialRef mat = Nz::Material::New("Translucent2D"); - if (!texturePath.empty()) - mat->SetDiffuseMap(m_assetStore.GetTexture(texturePath)); + std::shared_ptr mat = Nz::Graphics::Instance()->GetDefaultMaterials().basicTransparent->Clone(); - auto& sampler = mat->GetDiffuseSampler(); - sampler.SetFilterMode(Nz::SamplerFilter_Bilinear); + Nz::TextureSamplerInfo samplerInfo; + samplerInfo.magFilter = Nz::SamplerFilter::Linear; + samplerInfo.minFilter = Nz::SamplerFilter::Linear; if (repeatTexture) - sampler.SetWrapMode(Nz::SamplerWrap_Repeat); + samplerInfo.wrapModeU = samplerInfo.wrapModeV = Nz::SamplerWrap::Repeat; + + mat->SetTextureProperty("BaseColorMap", m_assetStore.GetTexture(texturePath), samplerInfo); - std::shared_ptr sprite = std::make_shared(); + std::shared_ptr sprite = std::make_shared(std::move(mat)); sprite->SetColor(color); sprite->SetTextureCoords(textureCoords); @@ -158,7 +160,7 @@ namespace bw Sprite scriptSprite(visualComponent.GetLayerVisual(), sprite, transformMatrix, renderOrder); scriptSprite.Show(); - return scriptSprite;*/ + return scriptSprite; }); elementTable["AddText"] = LuaFunction([this](const sol::table& entityTable, const sol::table& parameters) diff --git a/src/ClientLib/Scripting/ClientEntityLibrary.cpp b/src/ClientLib/Scripting/ClientEntityLibrary.cpp index 69897bfb..230fe15d 100644 --- a/src/ClientLib/Scripting/ClientEntityLibrary.cpp +++ b/src/ClientLib/Scripting/ClientEntityLibrary.cpp @@ -16,12 +16,14 @@ #include #include #include +#include +#include #include #include -//#include +#include #include #include -#include +#include #include namespace bw @@ -35,10 +37,20 @@ namespace bw void ClientEntityLibrary::InitRigidBody(lua_State* L, entt::handle entity, float mass) { - SharedEntityLibrary::InitRigidBody(L, entity, mass); + std::shared_ptr collider; + if (auto* rigidBody = entity.try_get()) + { + collider = rigidBody->GetGeom(); + entity.erase(); + } + + auto& entityMatch = entity.get(); + auto& physics = entityMatch.GetClientMatch().GetLayer(entityMatch.GetLayerIndex()).GetPhysicsSystem(); + + auto& entityPhys = entity.emplace(physics.CreateRigidBody(mass, collider)); - //entity.get().EnableNodeSynchronization(false); - entity.emplace(); + //entity.get().EnableNodeSynchronization(false); + entity.emplace_or_replace(); } void ClientEntityLibrary::RegisterClientLibrary(sol::table& elementMetatable) @@ -77,20 +89,11 @@ namespace bw if (materials.empty()) return {}; - /*std::shared_ptr tileMap = Nz::TileMap::New(mapSize, cellSize, materials.size()); + std::shared_ptr tileMap = std::make_shared(mapSize, cellSize, materials.size()); for (auto&& [materialPath, matIndex] : materials) { - Nz::MaterialRef material = Nz::Material::New(); //< FIXME - material->SetDiffuseMap(m_assetStore.GetTexture(materialPath)); - - if (material) - { - // Force alpha blending - material->Configure("Translucent2D"); - material->SetDiffuseMap(m_assetStore.GetTexture(materialPath)); //< FIXME - } - else - material = Nz::Material::GetDefault(); + std::shared_ptr material = Nz::Graphics::Instance()->GetDefaultMaterials().basicTransparent->Clone(); + material->SetTextureProperty("BaseColorMap", m_assetStore.GetTexture(materialPath)); tileMap->SetMaterial(matIndex, material); } @@ -117,20 +120,19 @@ namespace bw auto matIt = materials.find(tileData.materialPath); assert(matIt != materials.end()); - tileMap->EnableTile(tilePos, tileData.texCoords, Nz::Color::White, matIt->second); + tileMap->EnableTile(tilePos, tileData.texCoords, Nz::Color::White(), matIt->second); } } } Nz::Matrix4f transformMatrix = Nz::Matrix4f::Identity(); - auto& visualComponent = entity->GetComponent(); + auto& visualComponent = entity.get(); Tilemap scriptTilemap(visualComponent.GetLayerVisual(), std::move(tileMap), transformMatrix, renderOrder); scriptTilemap.Show(); - return scriptTilemap;*/ - return {}; + return scriptTilemap; }); elementMetatable["ClearLayers"] = LuaFunction([](const sol::table& entityTable) diff --git a/src/ClientLib/Scripting/ClientScriptingLibrary.cpp b/src/ClientLib/Scripting/ClientScriptingLibrary.cpp index 9ad8bf6d..8595be8f 100644 --- a/src/ClientLib/Scripting/ClientScriptingLibrary.cpp +++ b/src/ClientLib/Scripting/ClientScriptingLibrary.cpp @@ -103,7 +103,7 @@ namespace bw Nz::Vector2f position = parameters.get_or("Position", Nz::Vector2f::Zero()); float scale = parameters.get_or("Scale", 1.f); - Ndk::EntityHandle lifeOwner; + entt::handle lifeOwner; if (std::optional lifeOwnerEntitytable = parameters.get_or>("LifeOwner", std::nullopt); lifeOwnerEntitytable) lifeOwner = AssertScriptEntity(*lifeOwnerEntitytable); @@ -122,7 +122,7 @@ namespace bw } } - Ndk::EntityHandle parentEntity; + entt::handle parentEntity; if (std::optional propertyTableOpt = parameters.get_or>("Parent", std::nullopt); propertyTableOpt) parentEntity = AssertScriptEntity(propertyTableOpt.value()); @@ -133,17 +133,12 @@ namespace bw if (!entityOpt) TriggerLuaError(L, "failed to create \"" + entityType + "\""); - entt::entity entity = layer.RegisterEntity(std::move(entityOpt.value())).GetEntity(); + entt::handle entity = layer.RegisterEntity(std::move(entityOpt.value())).GetEntity(); if (lifeOwner) - { - if (!lifeOwner->HasComponent()) - lifeOwner->AddComponent(); - - lifeOwner->GetComponent().Register(entity); - } + lifeOwner.get_or_emplace(lifeOwner).Register(entity); - auto& scriptComponent = entity->GetComponent(); + auto& scriptComponent = entity.get(); return scriptComponent.GetTable(); }); @@ -244,6 +239,7 @@ namespace bw { ClientMatch& match = GetMatch(); +#if 0 const ParticleRegistry& registry = match.GetParticleRegistry(); const auto& layout = registry.GetLayout(particleType); if (!layout) @@ -257,8 +253,8 @@ namespace bw { // Do nothing })); - return ParticleGroup(registry, particleGroupEntity); +#endif }); } @@ -279,35 +275,30 @@ namespace bw ClientMatch& match = GetMatch(); const auto& assetDirectory = match.GetAssetStore().GetAssetDirectory(); - VirtualDirectory::Entry entry; - if (!assetDirectory->GetEntry(musicPath, &entry)) - return sol::make_object(L, std::make_pair(sol::nil, "file not found")); - - Nz::Music music; + std::unique_ptr music; - bool loaded = std::visit([&](auto&& arg) + bool loaded = assetDirectory->GetEntry(musicPath, [&](const Nz::VirtualDirectory::Entry& entry) { - using T = std::decay_t; - if constexpr (std::is_same_v) - { - bwLog(m_logger, LogLevel::Info, "Loading asset from memory"); - return music.OpenFromMemory(arg.data(), arg.size()); - } - else if constexpr (std::is_same_v) - { - bwLog(m_logger, LogLevel::Info, "Loading asset from {}", arg.generic_u8string()); - return music.OpenFromFile(arg.generic_u8string()); - } - else if constexpr (std::is_same_v) + return std::visit([&](auto&& arg) { - return false; - } - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); - }, entry); + using T = std::decay_t; + if constexpr (std::is_same_v) + { + bwLog(m_logger, LogLevel::Info, "Loading asset from {}", arg.stream->GetPath().generic_u8string()); + music = std::make_unique(); + return music->OpenFromStream(*arg.stream); + } + else if constexpr (std::is_same_v) + { + return false; + } + else + static_assert(AlwaysFalse::value, "non-exhaustive visitor"); + }, entry); + }); if (!loaded) - return sol::make_object(L, std::make_pair(sol::nil, "failed to open music")); + return sol::make_object(L, std::make_pair(sol::nil, "file not found")); return sol::make_object(L, Music(match.GetApplication(), std::move(music))); }); @@ -382,11 +373,11 @@ namespace bw if (controlledEntityId == InvalidEntityId) return sol::nil; - entt::entity controlledEntity = GetMatch().RetrieveEntityByUniqueId(controlledEntityId); + entt::handle controlledEntity = GetMatch().RetrieveEntityByUniqueId(controlledEntityId); if (!controlledEntity) return sol::nil; - auto& scriptComponent = controlledEntity->GetComponent(); + auto& scriptComponent = controlledEntity.get(); return scriptComponent.GetTable(); }), diff --git a/src/ClientLib/Scripting/ClientWeaponLibrary.cpp b/src/ClientLib/Scripting/ClientWeaponLibrary.cpp index eba31a45..bfd2e189 100644 --- a/src/ClientLib/Scripting/ClientWeaponLibrary.cpp +++ b/src/ClientLib/Scripting/ClientWeaponLibrary.cpp @@ -8,13 +8,12 @@ #include #include #include -#include -#include -#include +#include +#include #include -#include -#include -#include +#include +#include +#include #include namespace bw @@ -30,7 +29,7 @@ namespace bw { auto shootFunc = [](const sol::table& weaponTable, Nz::Vector2f startPos, Nz::Vector2f direction, Nz::UInt16 /*damage*/, float pushbackForce = 0.f) { - entt::handle entity = AssertScriptEntity(weaponTable); + /*entt::handle entity = AssertScriptEntity(weaponTable); entt::registry* world = entity->GetWorld(); assert(world); @@ -69,7 +68,7 @@ namespace bw const auto& trailEntity = localLayer.GetWorld().CreateEntity(); trailEntity->AddComponent(clientMatch, localLayer.GetLayerIndex(), trailId); - auto& trailNode = trailEntity->AddComponent(); + auto& trailNode = trailEntity->AddComponent(); trailNode.SetPosition(startPos); trailNode.SetRotation(Nz::Quaternionf::RotationBetween(Nz::Vector3f::UnitX(), direction)); @@ -79,7 +78,7 @@ namespace bw ClientLayerEntity layerEntity(localLayer, trailEntity, ClientLayerEntity::ClientsideId, trailId); layerEntity.AttachRenderable(trailSprite, Nz::Matrix4f::Identity(), -1); - entityClientMatch.GetLayer().RegisterEntity(std::move(layerEntity)); + entityClientMatch.GetLayer().RegisterEntity(std::move(layerEntity));*/ }; elementMetatable["Shoot"] = sol::overload( diff --git a/src/ClientLib/Scripting/ClientWeaponStore.cpp b/src/ClientLib/Scripting/ClientWeaponStore.cpp index 5ac5d822..31d7ed13 100644 --- a/src/ClientLib/Scripting/ClientWeaponStore.cpp +++ b/src/ClientLib/Scripting/ClientWeaponStore.cpp @@ -11,35 +11,35 @@ #include #include #include +#include #include #include -#include -#include namespace bw { - std::optional ClientWeaponStore::InstantiateWeapon(ClientLayer& layer, std::size_t entityIndex, Nz::UInt32 serverId, EntityId uniqueId, const PropertyValueMap& properties, entt::entity parent) + std::optional ClientWeaponStore::InstantiateWeapon(ClientLayer& layer, std::size_t entityIndex, Nz::UInt32 serverId, EntityId uniqueId, const PropertyValueMap& properties, entt::handle parent) { const auto& weaponClass = GetElement(entityIndex); - Nz::MaterialRef mat = Nz::Material::New("Translucent2D"); - mat->SetDiffuseMap(m_assetStore.GetTexture(weaponClass->spriteName)); - auto& sampler = mat->GetDiffuseSampler(); - sampler.SetFilterMode(Nz::SamplerFilter_Bilinear); + Nz::TextureSamplerInfo samplerInfo; + samplerInfo.magFilter = Nz::SamplerFilter::Linear; - std::shared_ptr sprite = Nz::Sprite::New(); - sprite->SetMaterial(mat); + std::shared_ptr material = Nz::Graphics::Instance()->GetDefaultMaterials().basicTransparent->Clone(); + material->SetTextureProperty("BaseColorMap", m_assetStore.GetTexture(weaponClass->spriteName)); + material->SetTextureSamplerProperty("BaseColorMap", samplerInfo); + + std::shared_ptr sprite = std::make_shared(std::move(material)); sprite->SetSize(sprite->GetSize() * weaponClass->scale); Nz::Vector2f burgerSize = sprite->GetSize(); sprite->SetOrigin(weaponClass->spriteOrigin); - entt::entity weapon = CreateEntity(layer.GetWorld(), weaponClass, properties); + entt::handle weapon = CreateEntity(layer.GetWorld(), weaponClass, properties); ClientLayerEntity layerEntity(layer, weapon, serverId, uniqueId); layerEntity.AttachRenderable(sprite, Nz::Matrix4f::Identity(), -1); - weapon->AddComponent(layerEntity.CreateHandle()); - weapon->AddComponent(layer.GetClientMatch(), layer.GetLayerIndex(), uniqueId); + weapon.emplace(layerEntity.CreateHandle()); + weapon.emplace(layer.GetClientMatch(), layer.GetLayerIndex(), uniqueId); SharedWeaponStore::InitializeWeapon(*weaponClass, weapon, parent); diff --git a/src/ClientLib/Scripting/Music.cpp b/src/ClientLib/Scripting/Music.cpp index eb50c3e6..f848f259 100644 --- a/src/ClientLib/Scripting/Music.cpp +++ b/src/ClientLib/Scripting/Music.cpp @@ -9,15 +9,47 @@ namespace bw { - Music::Music(ClientEditorAppComponent& app, Nz::Music music) : - m_music(std::move(music)) + Music::Music(ClientEditorAppComponent& app, std::unique_ptr music) : + m_music(std::move(music)), + m_app(app) { auto& playerSettings = app.GetPlayerSettings(); + m_music->SetVolume(playerSettings.GetIntegerValue("Sound.MusicVolume")); - m_music.SetVolume(playerSettings.GetIntegerValue("Sound.MusicVolume")); + ConnectSignals(); + } + + Music::Music(Music&& music) noexcept : + m_music(std::move(music.m_music)), + m_app(music.m_app) + { + music.DisconnectSignals(); + ConnectSignals(); + } + + Music& Music::operator=(Music&& music) noexcept + { + assert(&m_app == &music.m_app); + + music.DisconnectSignals(); + + m_music = std::move(music.m_music); + + ConnectSignals(); + return *this; + } + + void Music::ConnectSignals() + { + auto& playerSettings = m_app.GetPlayerSettings(); m_musicVolumeUpdateSlot.Connect(playerSettings.GetIntegerUpdateSignal("Sound.MusicVolume"), [this](long long newValue) { - m_music.SetVolume(float(newValue)); + m_music->SetVolume(float(newValue)); }); } + + void Music::DisconnectSignals() + { + m_musicVolumeUpdateSlot.Disconnect(); + } } diff --git a/src/ClientLib/Scripting/ParticleGroup.cpp b/src/ClientLib/Scripting/ParticleGroup.cpp index 57f56cf1..a1ac0c7c 100644 --- a/src/ClientLib/Scripting/ParticleGroup.cpp +++ b/src/ClientLib/Scripting/ParticleGroup.cpp @@ -4,17 +4,17 @@ #include #include -#include +//#include #include #include namespace bw { - ParticleGroup::ParticleGroup(const ParticleRegistry& particleRegistry, entt::entity particleGroup) : + ParticleGroup::ParticleGroup(const ParticleRegistry& particleRegistry, entt::handle particleGroup) : m_entity(particleGroup), m_registry(particleRegistry) { - assert(m_entity && m_entity->HasComponent()); + //assert(m_entity && m_entity->HasComponent()); } void ParticleGroup::AddController(const std::string& controllerName, const sol::table& parameters) @@ -22,11 +22,11 @@ namespace bw if (!m_entity) throw std::runtime_error("Particle group has been killed"); - auto controllerRef = m_registry.InstantiateController(controllerName, parameters); + /*auto controllerRef = m_registry.InstantiateController(controllerName, parameters); assert(controllerRef); auto& particleGroup = m_entity->GetComponent(); - particleGroup.AddController(std::move(controllerRef)); + particleGroup.AddController(std::move(controllerRef));*/ } void ParticleGroup::AddGenerator(const std::string& generatorName, const sol::table& parameters) @@ -34,11 +34,11 @@ namespace bw if (!m_entity) throw std::runtime_error("Particle group has been killed"); - auto generatorRef = m_registry.InstantiateGenerator(generatorName, parameters); + /*auto generatorRef = m_registry.InstantiateGenerator(generatorName, parameters); assert(generatorRef); auto& particleGroup = m_entity->GetComponent(); - particleGroup.AddGenerator(std::move(generatorRef)); + particleGroup.AddGenerator(std::move(generatorRef));*/ } void ParticleGroup::GenerateParticles(unsigned int count) @@ -46,8 +46,8 @@ namespace bw if (!m_entity) throw std::runtime_error("Particle group has been killed"); - auto& particleGroup = m_entity->GetComponent(); - particleGroup.GenerateParticles(count); + /*auto& particleGroup = m_entity->GetComponent(); + particleGroup.GenerateParticles(count);*/ } std::size_t ParticleGroup::GetParticleCount() const @@ -55,14 +55,14 @@ namespace bw if (!m_entity) throw std::runtime_error("Particle group has been killed"); - auto& particleGroup = m_entity->GetComponent(); - return particleGroup.GetParticleCount(); + /*auto& particleGroup = m_entity->GetComponent(); + return particleGroup.GetParticleCount();*/ } void ParticleGroup::Kill() { if (m_entity) - m_entity->Kill(); + m_entity->destroy(); } void ParticleGroup::SetRenderer(const std::string& rendererName, const sol::table& parameters) @@ -70,10 +70,10 @@ namespace bw if (!m_entity) throw std::runtime_error("Particle group has been killed"); - auto rendererRef = m_registry.InstantiateRenderer(rendererName, parameters); + /*auto rendererRef = m_registry.InstantiateRenderer(rendererName, parameters); assert(rendererRef); auto& particleGroup = m_entity->GetComponent(); - particleGroup.SetRenderer(std::move(rendererRef)); + particleGroup.SetRenderer(std::move(rendererRef));*/ } } diff --git a/src/ClientLib/Scripting/Sound.cpp b/src/ClientLib/Scripting/Sound.cpp index d5275960..157cb5c2 100644 --- a/src/ClientLib/Scripting/Sound.cpp +++ b/src/ClientLib/Scripting/Sound.cpp @@ -7,7 +7,7 @@ namespace bw { - float Sound::GetDuration() const + Nz::Time Sound::GetDuration() const { if (!m_sound) throw std::runtime_error("Invalid sound"); diff --git a/src/ClientLib/Scripting/Sprite.cpp b/src/ClientLib/Scripting/Sprite.cpp index 5ea5f03a..b02f0f21 100644 --- a/src/ClientLib/Scripting/Sprite.cpp +++ b/src/ClientLib/Scripting/Sprite.cpp @@ -25,13 +25,13 @@ namespace bw Nz::RectCorner rectCorner; if (corner == "TopLeft") - rectCorner = Nz::RectCorner_LeftTop; + rectCorner = Nz::RectCorner::LeftTop; else if (corner == "TopRight") - rectCorner = Nz::RectCorner_RightTop; + rectCorner = Nz::RectCorner::RightTop; else if (corner == "BottomLeft") - rectCorner = Nz::RectCorner_LeftBottom; + rectCorner = Nz::RectCorner::LeftBottom; else if (corner == "BottomRight") - rectCorner = Nz::RectCorner_RightBottom; + rectCorner = Nz::RectCorner::RightBottom; else throw std::runtime_error("Invalid corner " + std::string(corner)); @@ -53,19 +53,19 @@ namespace bw { { "TopLeft", - Nz::RectCorner_LeftTop + Nz::RectCorner::LeftTop }, { "TopRight", - Nz::RectCorner_RightTop + Nz::RectCorner::RightTop }, { "BottomLeft", - Nz::RectCorner_LeftBottom + Nz::RectCorner::LeftBottom }, { "BottomRight", - Nz::RectCorner_RightBottom + Nz::RectCorner::RightBottom } } }; diff --git a/src/ClientLib/Scripting/Text.cpp b/src/ClientLib/Scripting/Text.cpp index 8fa23a5c..19da6d40 100644 --- a/src/ClientLib/Scripting/Text.cpp +++ b/src/ClientLib/Scripting/Text.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -15,7 +16,7 @@ namespace bw if (!m_visualEntity) throw std::runtime_error("Invalid text"); - m_textSprite->SetColor(color); + m_textSprite->GetMaterial()->SetValueProperty("BaseColor", color); } void Text::SetHoveringHeight(float hoveringHeight) diff --git a/src/ClientLib/SoundEntity.cpp b/src/ClientLib/SoundEntity.cpp index be80dc45..bd5afc5a 100644 --- a/src/ClientLib/SoundEntity.cpp +++ b/src/ClientLib/SoundEntity.cpp @@ -6,17 +6,16 @@ #include #include #include -#include namespace bw { SoundEntity::SoundEntity(entt::registry& renderWorld, ClientLayerSoundHandle layerSoundHandle, float depth) : - m_entity(renderWorld.CreateEntity()), + m_entity(entt::handle(renderWorld, renderWorld.create())), m_layerSound(std::move(layerSoundHandle)), m_depth(depth) { - m_entity->AddComponent(); - m_entity->AddComponent(); + m_entity->emplace(); + m_entity->emplace(); m_layerSound->RegisterAudibleSound(this); } @@ -24,7 +23,7 @@ namespace bw SoundEntity::SoundEntity(entt::registry& renderWorld, ClientLayerSoundHandle layerSoundHandle, const Nz::Node& parentNode, float depth) : SoundEntity(renderWorld, std::move(layerSoundHandle), depth) { - m_entity.get().SetParent(parentNode); + m_entity->get().SetParent(parentNode); } SoundEntity::SoundEntity(SoundEntity&& entity) noexcept : @@ -47,14 +46,14 @@ namespace bw if (soundIndex >= m_soundIds.size()) m_soundIds.resize(soundIndex + 1); - auto& nodeComponent = m_entity.get(); - auto& soundEmitterComponent = m_entity->GetComponent(); + auto& nodeComponent = m_entity->get(); + auto& soundEmitterComponent = m_entity->get(); m_soundIds[soundIndex] = soundEmitterComponent.PlaySound(soundBuffer, nodeComponent.GetPosition(), true, isLooping, isSpatialized); } void SoundEntity::StopSound(std::size_t soundIndex) { - auto& soundEmitterComponent = m_entity->GetComponent(); + auto& soundEmitterComponent = m_entity->get(); assert(soundIndex < m_soundIds.size()); soundEmitterComponent.StopSound(m_soundIds[soundIndex]); @@ -62,7 +61,7 @@ namespace bw void SoundEntity::Update(const Nz::Vector2f& position) { - auto& visualNode = m_entity.get(); + auto& visualNode = m_entity->get(); visualNode.SetPosition(position); // Make sure parenting doesn't change our depth diff --git a/src/ClientLib/Systems/FrameCallbackSystem.cpp b/src/ClientLib/Systems/FrameCallbackSystem.cpp index 97eb0f1a..f12809ff 100644 --- a/src/ClientLib/Systems/FrameCallbackSystem.cpp +++ b/src/ClientLib/Systems/FrameCallbackSystem.cpp @@ -14,7 +14,7 @@ namespace bw m_scriptDestroyConnection = m_registry.on_destroy().connect<&FrameCallbackSystem::OnScriptDestroy>(this); } - void FrameCallbackSystem::Update(float /*elapsedTime*/) + void FrameCallbackSystem::Update(Nz::Time /*elapsedTime*/) { for (entt::entity entity : m_frameUpdateEntities) { diff --git a/src/ClientLib/Systems/PostFrameCallbackSystem.cpp b/src/ClientLib/Systems/PostFrameCallbackSystem.cpp index 128b2d2d..c22b2e21 100644 --- a/src/ClientLib/Systems/PostFrameCallbackSystem.cpp +++ b/src/ClientLib/Systems/PostFrameCallbackSystem.cpp @@ -14,7 +14,7 @@ namespace bw m_scriptDestroyConnection = m_registry.on_destroy().connect<&PostFrameCallbackSystem::OnScriptDestroy>(this); } - void PostFrameCallbackSystem::Update(float /*elapsedTime*/) + void PostFrameCallbackSystem::Update(Nz::Time /*elapsedTime*/) { for (entt::entity entity : m_frameUpdateEntities) { diff --git a/src/ClientLib/Systems/SoundSystem.cpp b/src/ClientLib/Systems/SoundSystem.cpp index 80be1eb6..09d22caa 100644 --- a/src/ClientLib/Systems/SoundSystem.cpp +++ b/src/ClientLib/Systems/SoundSystem.cpp @@ -32,11 +32,11 @@ namespace bw void SoundSystem::Update(Nz::Time elapsedTime) { - float invElapsedTime = 1.f / elapsedTime; + float invElapsedTime = 1.f / elapsedTime.AsSeconds(); m_observer.each([&](entt::entity entity) { - if (m_registry.try_get(entity) && m_registry.try_get()) + if (m_registry.try_get(entity) && m_registry.try_get(entity)) m_movableEntities.insert(entity); }); @@ -110,7 +110,7 @@ namespace bw break; } - float score = 1.f - float(soundEntry.sound.GetPlayingOffset()) / soundEntry.sound.GetDuration(); + float score = 1.f - soundEntry.sound.GetPlayingOffset().AsSeconds() / soundEntry.sound.GetDuration().AsSeconds(); if (score > bestScore) { bestScore = score; diff --git a/src/ClientLib/Systems/VisualInterpolationSystem.cpp b/src/ClientLib/Systems/VisualInterpolationSystem.cpp index 2cac207f..ffda0d3f 100644 --- a/src/ClientLib/Systems/VisualInterpolationSystem.cpp +++ b/src/ClientLib/Systems/VisualInterpolationSystem.cpp @@ -5,8 +5,7 @@ #include #include #include -#include -#include +#include #include #include @@ -29,14 +28,14 @@ namespace bw }); float C = 10.f; - float factor = 1.f - std::exp(-elapsedTime * C); + float factor = 1.f - std::exp(-elapsedTime.AsSeconds() * C); - auto view = m_registry.view(); + auto view = m_registry.view(); for (entt::entity entity : view) { auto& entityLerp = m_registry.get(entity); auto& entityNode = m_registry.get(entity); - auto& entityPhysics = m_registry.get(entity); + auto& entityPhysics = m_registry.get(entity); // x = x + (target-x) * (1-Exp(-deltaTime*C)) Nz::RadianAnglef sourceRot = entityLerp.GetLastRotation(); diff --git a/src/ClientLib/VisualEntity.cpp b/src/ClientLib/VisualEntity.cpp index 31b99558..380e6e02 100644 --- a/src/ClientLib/VisualEntity.cpp +++ b/src/ClientLib/VisualEntity.cpp @@ -4,31 +4,32 @@ #include #include -#include +#include +#include #include -#include namespace bw { - VisualEntity::VisualEntity(entt::registry& renderWorld, LayerVisualEntityHandle visualEntityHandle, int baseRenderOrder) : + VisualEntity::VisualEntity(Nz::EnttWorld& renderWorld, LayerVisualEntityHandle visualEntityHandle, int baseRenderOrder) : m_entity(renderWorld.CreateEntity()), m_visualEntity(std::move(visualEntityHandle)), m_baseRenderOrder(baseRenderOrder) { - m_entity->AddComponent(); - m_entity->AddComponent(); + m_entity->emplace(); + m_entity->emplace(); m_visualEntity->RegisterVisualEntity(this); } - VisualEntity::VisualEntity(entt::registry& renderWorld, LayerVisualEntityHandle visualEntityHandle, const Nz::Node& parentNode, int baseRenderOrder) : + VisualEntity::VisualEntity(Nz::EnttWorld& renderWorld, LayerVisualEntityHandle visualEntityHandle, const Nz::Node& parentNode, int baseRenderOrder) : VisualEntity(renderWorld, std::move(visualEntityHandle), baseRenderOrder) { - m_entity.get().SetParent(parentNode); + m_entity->get().SetParent(parentNode); } VisualEntity::VisualEntity(VisualEntity&& entity) noexcept : m_hoveringRenderables(std::move(entity.m_hoveringRenderables)), + m_renderables(std::move(entity.m_renderables)), m_entity(std::move(entity.m_entity)), m_visualEntity(std::move(entity.m_visualEntity)), m_baseRenderOrder(entity.m_baseRenderOrder) @@ -45,7 +46,7 @@ namespace bw void VisualEntity::Update(const Nz::Vector2f& position, const Nz::Quaternionf& rotation, const Nz::Vector2f& scale) { - auto& visualNode = m_entity.get(); + auto& visualNode = m_entity->get(); visualNode.SetPosition(position); visualNode.SetRotation(rotation); visualNode.SetScale(scale); @@ -57,12 +58,12 @@ namespace bw if (!m_hoveringRenderables.empty()) { - auto& visualGfx = m_entity->GetComponent(); + auto& visualGfx = m_entity->get(); Nz::Vector3f absoluteScale = visualNode.GetScale(Nz::CoordSys::Global); Nz::Vector2f positiveScale(std::abs(absoluteScale.x), std::abs(absoluteScale.y)); - const Nz::Boxf& aabb = visualGfx.GetAABB(); + /*const Nz::Boxf& aabb = visualGfx.GetAABB(); float halfHeight = aabb.height / 2.f; Nz::Vector3f center = aabb.GetCenter(); @@ -71,25 +72,39 @@ namespace bw auto& node = hoveringRenderable.entity.get(); node.SetPosition(center.x, center.y - halfHeight - absoluteScale.y * hoveringRenderable.offset); node.SetScale(positiveScale); - } + }*/ } } void VisualEntity::AttachHoveringRenderable(std::shared_ptr renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder, float hoverOffset) { + entt::registry& registry = *m_entity.GetEntity().registry(); + auto& hoveringRenderable = m_hoveringRenderables.emplace_back(); - hoveringRenderable.entity = m_entity->GetWorld()->CreateEntity(); - hoveringRenderable.entity->AddComponent(); hoveringRenderable.offset = hoverOffset; hoveringRenderable.renderable = std::move(renderable); - auto& gfxComponent = hoveringRenderable.entity->AddComponent(); - gfxComponent.Attach(hoveringRenderable.renderable, offsetMatrix, renderOrder); + hoveringRenderable.entity = entt::handle(registry, registry.create()); + auto& node = hoveringRenderable.entity->emplace(); + node.SetParent(m_entity); + //node.SetTransformMatrix(offsetMatrix); + + auto& gfxComponent = hoveringRenderable.entity->emplace(hoveringRenderable.renderable, 2); } void VisualEntity::AttachRenderable(std::shared_ptr renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder) { - m_entity->GetComponent().Attach(std::move(renderable), offsetMatrix, m_baseRenderOrder + renderOrder); + entt::registry& registry = *m_entity.GetEntity().registry(); + + auto& hoveringRenderable = m_renderables.emplace_back(); + hoveringRenderable.renderable = std::move(renderable); + + hoveringRenderable.entity = entt::handle(registry, registry.create()); + auto& node = hoveringRenderable.entity->emplace(); + node.SetParent(m_entity); + //node.SetTransformMatrix(offsetMatrix); + + auto& gfxComponent = hoveringRenderable.entity->emplace(hoveringRenderable.renderable, 2); } void VisualEntity::DetachHoveringRenderable(const std::shared_ptr& renderable) @@ -108,7 +123,16 @@ namespace bw void VisualEntity::DetachRenderable(const std::shared_ptr& renderable) { - m_entity->GetComponent().Detach(renderable); + for (auto it = m_renderables.begin(); it != m_renderables.end(); ++it) + { + auto& hoveringRenderable = *it; + + if (hoveringRenderable.renderable == renderable) + { + m_renderables.erase(it); + break; + } + } } void VisualEntity::UpdateHoveringRenderableHoveringHeight(const std::shared_ptr& renderable, float newHoveringHeight) @@ -129,7 +153,7 @@ namespace bw { if (hoveringRenderable.renderable == renderable) { - hoveringRenderable.entity->GetComponent().UpdateLocalMatrix(renderable, offsetMatrix); + hoveringRenderable.entity->get().SetTransformMatrix(offsetMatrix); break; } } @@ -141,7 +165,7 @@ namespace bw { if (hoveringRenderable.renderable == renderable) { - hoveringRenderable.entity->GetComponent().UpdateRenderOrder(renderable, renderOrder); + //hoveringRenderable.entity->GetComponent().UpdateRenderOrder(renderable, renderOrder); break; } } @@ -149,11 +173,18 @@ namespace bw void VisualEntity::UpdateRenderableMatrix(const std::shared_ptr& renderable, const Nz::Matrix4f& offsetMatrix) { - m_entity->GetComponent().UpdateLocalMatrix(renderable, offsetMatrix); + for (auto& hoveringRenderable : m_renderables) + { + if (hoveringRenderable.renderable == renderable) + { + hoveringRenderable.entity->get().SetTransformMatrix(offsetMatrix); + break; + } + } } void VisualEntity::UpdateRenderableRenderOrder(const std::shared_ptr& renderable, int renderOrder) { - m_entity->GetComponent().UpdateRenderOrder(renderable, m_baseRenderOrder + renderOrder); + //m_entity->GetComponent().UpdateRenderOrder(renderable, m_baseRenderOrder + renderOrder); } } diff --git a/src/CoreLib/BasicPlayerMovementController.cpp b/src/CoreLib/BasicPlayerMovementController.cpp index 19460a0d..08c9449a 100644 --- a/src/CoreLib/BasicPlayerMovementController.cpp +++ b/src/CoreLib/BasicPlayerMovementController.cpp @@ -5,12 +5,12 @@ #include #include #include -#include -#include +#include +#include namespace bw { - bool BasicPlayerMovementController::PreSolveCollision(PlayerMovementComponent& playerMovement, entt::entity /*collisionBody*/, Nz::Arbiter2D& arbiter) const + bool BasicPlayerMovementController::PreSolveCollision(PlayerMovementComponent& playerMovement, entt::entity /*collisionBody*/, Nz::ChipmunkArbiter2D& arbiter) const { Nz::Vector2f up = Nz::Vector2f::UnitY(); @@ -23,7 +23,7 @@ namespace bw return true; } - void BasicPlayerMovementController::UpdateVelocity(const PlayerInputData& inputs, PlayerMovementComponent& playerMovement, Nz::RigidBody2D& rigidBody, const Nz::Vector2f& gravity, float damping, float dt) const + void BasicPlayerMovementController::UpdateVelocity(const PlayerInputData& inputs, PlayerMovementComponent& playerMovement, Nz::ChipmunkRigidBody2D& rigidBody, const Nz::Vector2f& gravity, float damping, float dt) const { bool isOnGround = playerMovement.IsOnGround(); bool disableGravity = false; diff --git a/src/CoreLib/BurgAppComponent.cpp b/src/CoreLib/BurgAppComponent.cpp index 17f071a6..eaaf8803 100644 --- a/src/CoreLib/BurgAppComponent.cpp +++ b/src/CoreLib/BurgAppComponent.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -27,6 +28,7 @@ #include #include #include +#include #include #include @@ -58,25 +60,22 @@ namespace bw assert(!s_application); s_application = this; - InstallInterruptHandlers(); - m_logger.RegisterSink(std::make_shared()); m_logger.SetMinimumLogLevel(LogLevel::Debug); - std::string error; - if (WebService::Initialize(&error)) + try + { + m_webService = Nz::Network::Instance()->InstantiateWebService(); + } + catch (const std::exception& e) { - bwLog(GetLogger(), LogLevel::Debug, "libcurl has been loaded"); - m_webService.emplace(m_logger); + bwLog(GetLogger(), LogLevel::Error, "failed to initialize web services ({0}), some functionalities will not work", e); } - else - bwLog(GetLogger(), LogLevel::Error, "failed to initialize web services ({0}), some functionalities will not work", error); } BurgAppComponent::~BurgAppComponent() { m_webService.reset(); - WebService::Uninitialize(); assert(s_application); s_application = nullptr; @@ -90,57 +89,6 @@ namespace bw m_webService->Poll(); } - void BurgAppComponent::HandleInterruptSignal(const char* signalName) - { - assert(s_application); - bwLog(s_application->GetLogger(), LogLevel::Info, "received interruption signal {0}, exiting...", signalName); - - s_application->GetApp().Quit(); - } - - void BurgAppComponent::InstallInterruptHandlers() - { - bool succeeded = false; - -#if defined(NAZARA_PLATFORM_WINDOWS) - succeeded = SetConsoleCtrlHandler([](DWORD ctrlType) -> BOOL - { - switch (ctrlType) - { - case CTRL_C_EVENT: HandleInterruptSignal("CTRL_C"); break; - case CTRL_BREAK_EVENT: HandleInterruptSignal("CTRL_BREAK"); break; - case CTRL_CLOSE_EVENT: HandleInterruptSignal("CTRL_CLOSE"); break; - case CTRL_LOGOFF_EVENT: HandleInterruptSignal("CTRL_LOGOFF"); break; - case CTRL_SHUTDOWN_EVENT: HandleInterruptSignal("CTRL_SHUTDOWN"); break; - default: - { - std::string signalName = ""; - HandleInterruptSignal(signalName.c_str()); - } - } - - return TRUE; - }, TRUE); -#elif defined(NAZARA_PLATFORM_POSIX) - struct sigaction action; - sigemptyset(&action.sa_mask); - action.sa_flags = 0; - action.sa_handler = [](int sig) - { - HandleInterruptSignal(strsignal(sig)); - }; - - if (sigaction(SIGINT, &action, nullptr) != 0) - succeeded = false; - - if (sigaction(SIGTERM, &action, nullptr) != 0) - succeeded = false; -#endif - - if (!succeeded) - bwLog(GetLogger(), LogLevel::Error, "failed to install interruption signal handlers"); - } - void BurgAppComponent::LoadMods() { const std::string& modDir = m_config.GetStringValue("Resources.ModDirectory"); diff --git a/src/CoreLib/Components/CollisionDataComponent.cpp b/src/CoreLib/Components/CollisionDataComponent.cpp index 6c778125..193fd0a4 100644 --- a/src/CoreLib/Components/CollisionDataComponent.cpp +++ b/src/CoreLib/Components/CollisionDataComponent.cpp @@ -7,7 +7,7 @@ namespace bw { - std::shared_ptr CollisionDataComponent::BuildCollider(float scale) const + std::shared_ptr CollisionDataComponent::BuildCollider(float scale) const { if (m_colliders.empty()) { @@ -23,29 +23,29 @@ namespace bw { // Multiple colliders - std::vector> simpleColliders; + std::vector> simpleColliders; simpleColliders.reserve(m_colliders.size()); for (const auto& collider : m_colliders) simpleColliders.emplace_back(ToCollider(collider, scale)); - std::shared_ptr compound = std::make_shared(std::move(simpleColliders)); + std::shared_ptr compound = std::make_shared(std::move(simpleColliders)); compound->OverridesCollisionProperties(false); return compound; } } - std::shared_ptr CollisionDataComponent::ToCollider(const Collider& collider, float scale) + std::shared_ptr CollisionDataComponent::ToCollider(const Collider& collider, float scale) { - return std::visit([&](auto&& arg) -> std::shared_ptr + return std::visit([&](auto&& arg) -> std::shared_ptr { using T = std::decay_t; - std::shared_ptr collider; + std::shared_ptr collider; if constexpr (std::is_same_v) - collider = std::make_shared(arg.radius * scale, arg.offset * scale); + collider = std::make_shared(arg.radius * scale, arg.offset * scale); else if constexpr (std::is_same_v) { Nz::Rectf scaledRect = arg.data; @@ -54,10 +54,10 @@ namespace bw scaledRect.width *= scale; scaledRect.height *= scale; - collider = std::make_shared(scaledRect); + collider = std::make_shared(scaledRect); } else if constexpr (std::is_same_v) - collider = std::make_shared(arg.from * scale, arg.fromNeighbor * scale, arg.to * scale, arg.toNeighbor * scale); + collider = std::make_shared(arg.from * scale, arg.fromNeighbor * scale, arg.to * scale, arg.toNeighbor * scale); else static_assert(AlwaysFalse::value, "non-exhaustive visitor"); diff --git a/src/CoreLib/MasterServerEntry.cpp b/src/CoreLib/MasterServerEntry.cpp index e129348e..72d943f0 100644 --- a/src/CoreLib/MasterServerEntry.cpp +++ b/src/CoreLib/MasterServerEntry.cpp @@ -17,10 +17,10 @@ namespace bw constexpr Nz::UInt32 MasterServerDataVersion = 1U; } - MasterServerEntry::MasterServerEntry(Match& match, std::string masterServerURL) : + MasterServerEntry::MasterServerEntry(Nz::WebService& webService, Match& match, std::string masterServerURL) : m_masterServerURL(std::move(masterServerURL)), - m_match(match), - m_webService(m_match.GetLogger()) + m_webService(webService), + m_match(match) { } @@ -73,7 +73,7 @@ namespace bw return serverData; } - void MasterServerEntry::HandleResponse(WebRequestResult&& result, bool refresh) + void MasterServerEntry::HandleResponse(Nz::WebRequestResult&& result, bool refresh) { if (!result) { @@ -81,7 +81,7 @@ namespace bw return; } - switch (result.GetReponseCode()) + switch (result.GetStatusCode()) { case 200: { @@ -102,14 +102,14 @@ namespace bw std::string ipv4Url = ipv4UrlValue; if (!ipv4Url.empty()) { - std::unique_ptr request = WebRequest::Post(ipv4Url, [&](WebRequestResult&& result) + std::unique_ptr request = m_webService.CreatePostRequest(ipv4Url, [&](Nz::WebRequestResult&& result) { if (result.HasSucceeded()) { - if (result.GetReponseCode() == 200) + if (result.GetStatusCode() == 200) bwLog(m_match.GetLogger(), LogLevel::Debug, "successfully registered ipv4 to master server {0}", m_masterServerURL); else - bwLog(m_match.GetLogger(), LogLevel::Error, "failed to register ipv4 to master server {0}, unexpected response {1}: {2}", m_masterServerURL, result.GetReponseCode(), result.GetBody()); + bwLog(m_match.GetLogger(), LogLevel::Error, "failed to register ipv4 to master server {0}, unexpected response {1}: {2}", m_masterServerURL, result.GetStatusCode(), result.GetBody()); } else bwLog(m_match.GetLogger(), LogLevel::Error, "failed to register ipv4 to master server {0}: {1}", m_masterServerURL, result.GetErrorMessage()); @@ -122,7 +122,7 @@ namespace bw request->SetJSonContent(requestData.dump()); - m_webService.AddRequest(std::move(request)); + m_webService.QueueRequest(std::move(request)); } } } @@ -152,14 +152,14 @@ namespace bw } default: - bwLog(m_match.GetLogger(), LogLevel::Info, (refresh) ? "failed to refresh to {0}: refresh request failed with code {1}" : "failed to register to {0}: register request failed with code {1}", m_masterServerURL, result.GetReponseCode()); + bwLog(m_match.GetLogger(), LogLevel::Info, (refresh) ? "failed to refresh to {0}: refresh request failed with code {1}" : "failed to register to {0}: register request failed with code {1}", m_masterServerURL, result.GetStatusCode()); break; } } void MasterServerEntry::Refresh() { - std::unique_ptr request = WebRequest::Post(m_masterServerURL + "/servers", [&](WebRequestResult&& result) + std::unique_ptr request = m_webService.CreatePostRequest(m_masterServerURL + "/servers", [&](Nz::WebRequestResult&& result) { HandleResponse(std::move(result), true); }); @@ -171,13 +171,13 @@ namespace bw request->SetJSonContent(serverData.dump()); - m_webService.AddRequest(std::move(request)); + m_webService.QueueRequest(std::move(request)); m_timeBeforeRefresh = Nz::Time::Seconds(15.f); } void MasterServerEntry::Register() { - std::unique_ptr request = WebRequest::Post(m_masterServerURL + "/servers", [&](WebRequestResult&& result) + std::unique_ptr request = m_webService.CreatePostRequest(m_masterServerURL + "/servers", [&](Nz::WebRequestResult&& result) { HandleResponse(std::move(result), false); }); @@ -186,7 +186,7 @@ namespace bw request->SetJSonContent(BuildServerInfo().dump()); - m_webService.AddRequest(std::move(request)); + m_webService.QueueRequest(std::move(request)); m_timeBeforeRefresh = Nz::Time::Seconds(15.f); } } diff --git a/src/CoreLib/Match.cpp b/src/CoreLib/Match.cpp index 97c77360..5d964c90 100644 --- a/src/CoreLib/Match.cpp +++ b/src/CoreLib/Match.cpp @@ -24,7 +24,7 @@ #include #include #include -#include +#include #include #include #include @@ -57,7 +57,7 @@ namespace bw BuildMatchData(); - if (WebService::IsInitialized()) + if (m_app.HasWebService()) { if (m_settings.registerToMasterServer && m_settings.port != 0) { @@ -65,7 +65,7 @@ namespace bw SplitStringAny(masterServerList, "\f\n\r\t\v ", [&](const std::string_view& masterServerURI) { if (!masterServerURI.empty()) - m_masterServerEntries.emplace_back(std::make_unique(*this, std::string(masterServerURI))); + m_masterServerEntries.emplace_back(std::make_unique(app.GetWebService(), *this, std::string(masterServerURI))); return true; }); @@ -692,7 +692,7 @@ namespace bw debugPacket << layerId; debugPacket << entityId; - Nz::RigidBody2DComponent* entityPhys = entity.try_get(); + Nz::ChipmunkRigidBody2DComponent* entityPhys = entity.try_get(); bool isPhysical = (entityPhys != nullptr); debugPacket << isPhysical; diff --git a/src/CoreLib/NoclipPlayerMovementController.cpp b/src/CoreLib/NoclipPlayerMovementController.cpp index e83d9bca..6d4a11aa 100644 --- a/src/CoreLib/NoclipPlayerMovementController.cpp +++ b/src/CoreLib/NoclipPlayerMovementController.cpp @@ -5,12 +5,12 @@ #include #include #include -#include -#include +#include +#include namespace bw { - void NoclipPlayerMovementController::UpdateVelocity(const PlayerInputData& inputs, PlayerMovementComponent& /*playerMovement*/, Nz::RigidBody2D& rigidBody, const Nz::Vector2f& /*gravity*/, float damping, float dt) const + void NoclipPlayerMovementController::UpdateVelocity(const PlayerInputData& inputs, PlayerMovementComponent& /*playerMovement*/, Nz::ChipmunkRigidBody2D& rigidBody, const Nz::Vector2f& /*gravity*/, float damping, float dt) const { constexpr float noclipVelocity = 2000.f; constexpr float noclipAccelTime = 0.2f; diff --git a/src/CoreLib/Player.cpp b/src/CoreLib/Player.cpp index f2aaed6e..40b3ff2d 100644 --- a/src/CoreLib/Player.cpp +++ b/src/CoreLib/Player.cpp @@ -25,7 +25,7 @@ #include #include #include -#include +#include namespace bw { @@ -162,7 +162,7 @@ namespace bw { if (lastTick && m_shouldSendWeapons) { - Packets::PlayerWeapons weaponPacket; + /*Packets::PlayerWeapons weaponPacket; weaponPacket.localIndex = m_localIndex; weaponPacket.layerIndex = m_layerIndex; @@ -184,7 +184,7 @@ namespace bw } } - m_session.GetVisibility().PushEntitiesPacket(m_layerIndex, std::move(weaponIds), std::move(weaponPacket)); + m_session.GetVisibility().PushEntitiesPacket(m_layerIndex, std::move(weaponIds), std::move(weaponPacket));*/ m_shouldSendWeapons = false; } diff --git a/src/CoreLib/PlayerMovementController.cpp b/src/CoreLib/PlayerMovementController.cpp index 4155a6fc..545acc37 100644 --- a/src/CoreLib/PlayerMovementController.cpp +++ b/src/CoreLib/PlayerMovementController.cpp @@ -8,7 +8,7 @@ namespace bw { PlayerMovementController::~PlayerMovementController() = default; - bool PlayerMovementController::PreSolveCollision(PlayerMovementComponent& /*playerMovement*/, entt::entity /*collisionBody*/, Nz::Arbiter2D& /*arbiter*/) const + bool PlayerMovementController::PreSolveCollision(PlayerMovementComponent& /*playerMovement*/, entt::entity /*collisionBody*/, Nz::ChipmunkArbiter2D& /*arbiter*/) const { return true; } diff --git a/src/CoreLib/Scripting/AbstractScriptingLibrary.cpp b/src/CoreLib/Scripting/AbstractScriptingLibrary.cpp index 5c6f1001..c31f5c2e 100644 --- a/src/CoreLib/Scripting/AbstractScriptingLibrary.cpp +++ b/src/CoreLib/Scripting/AbstractScriptingLibrary.cpp @@ -179,7 +179,7 @@ namespace bw sol::state& luaState = context.GetLuaState(); luaState["include"] = LuaFunction([&](sol::this_state L, const std::string& scriptName) { - std::filesystem::path scriptPath = context.GetCurrentFolder() / std::filesystem::u8path(scriptName); + std::filesystem::path scriptPath = context.GetCurrentFolder() / Nz::Utf8Path(scriptName); auto result = context.Load(scriptPath.generic_u8string()); if (!result) diff --git a/src/CoreLib/Scripting/Constraint.cpp b/src/CoreLib/Scripting/Constraint.cpp index 4f43397a..7be24edc 100644 --- a/src/CoreLib/Scripting/Constraint.cpp +++ b/src/CoreLib/Scripting/Constraint.cpp @@ -7,11 +7,11 @@ namespace bw { - Constraint::Constraint(entt::handle entity, Nz::Constraint2DHandle constraint) : + Constraint::Constraint(entt::handle entity, Nz::ChipmunkConstraint2DHandle constraint) : m_entity(entity), m_constraint(std::move(constraint)) { - m_onDestruction.Connect(m_constraint->OnHandledObjectDestruction, [this](Nz::HandledObject*) { + m_onDestruction.Connect(m_constraint->OnHandledObjectDestruction, [this](Nz::HandledObject*) { KillEntity(); }); } @@ -21,7 +21,7 @@ namespace bw m_constraint(std::move(constraint.m_constraint)) { constraint.m_onDestruction.Disconnect(); - m_onDestruction.Connect(m_constraint->OnHandledObjectDestruction, [this](Nz::HandledObject*) { + m_onDestruction.Connect(m_constraint->OnHandledObjectDestruction, [this](Nz::HandledObject*) { KillEntity(); }); } @@ -98,37 +98,37 @@ namespace bw float PinConstraint::GetDistance() const { AssertValid(); - return GetConstraint()->GetDistance(); + return GetConstraint()->GetDistance(); } void PinConstraint::SetDistance(float distance) { AssertValid(); - GetConstraint()->SetDistance(distance); + GetConstraint()->SetDistance(distance); } Nz::RadianAnglef RotaryLimitConstraint::GetMaxAngle() const { AssertValid(); - return GetConstraint()->GetMaxAngle(); + return GetConstraint()->GetMaxAngle(); } Nz::RadianAnglef RotaryLimitConstraint::GetMinAngle() const { AssertValid(); - return GetConstraint()->GetMinAngle(); + return GetConstraint()->GetMinAngle(); } void RotaryLimitConstraint::SetMaxAngle(Nz::RadianAnglef maxAngle) { AssertValid(); - GetConstraint()->SetMaxAngle(maxAngle); + GetConstraint()->SetMaxAngle(maxAngle); } void RotaryLimitConstraint::SetMinAngle(Nz::RadianAnglef minAngle) { AssertValid(); - GetConstraint()->SetMinAngle(minAngle); + GetConstraint()->SetMinAngle(minAngle); } } diff --git a/src/CoreLib/Scripting/ScriptingContext.cpp b/src/CoreLib/Scripting/ScriptingContext.cpp index 6e55ac74..0ec433ea 100644 --- a/src/CoreLib/Scripting/ScriptingContext.cpp +++ b/src/CoreLib/Scripting/ScriptingContext.cpp @@ -314,6 +314,8 @@ namespace bw return {}; } + entry.stream->SetCursorPos(0); + std::string content(fileSize, '\0'); if (entry.stream->Read(&content[0], fileSize) != fileSize) { diff --git a/src/CoreLib/Scripting/ServerElementLibrary.cpp b/src/CoreLib/Scripting/ServerElementLibrary.cpp index f873ce71..800fec40 100644 --- a/src/CoreLib/Scripting/ServerElementLibrary.cpp +++ b/src/CoreLib/Scripting/ServerElementLibrary.cpp @@ -13,8 +13,8 @@ #include #include #include -#include -#include +#include +#include #include #include @@ -166,7 +166,7 @@ namespace bw if (CollisionDataComponent* entityCollData = entity.try_get()) { - auto& entityCollider = entity.get(); + auto& entityCollider = entity.get(); entityCollider.SetGeom(entityCollData->BuildCollider(newScale), false, false); } diff --git a/src/CoreLib/Scripting/ServerEntityLibrary.cpp b/src/CoreLib/Scripting/ServerEntityLibrary.cpp index 804cc1e1..6725b956 100644 --- a/src/CoreLib/Scripting/ServerEntityLibrary.cpp +++ b/src/CoreLib/Scripting/ServerEntityLibrary.cpp @@ -3,6 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include +#include #include #include #include @@ -113,6 +114,21 @@ namespace bw }); } + void ServerEntityLibrary::InitRigidBody(lua_State* L, entt::handle entity, float mass) + { + std::shared_ptr collider; + if (auto* rigidBody = entity.try_get()) + { + collider = rigidBody->GetGeom(); + entity.erase(); + } + + auto& entityMatch = entity.get(); + auto& physics = entityMatch.GetMatch().GetLayer(entityMatch.GetLayerIndex()).GetPhysicsSystem(); + + entity.emplace_or_replace(physics.CreateRigidBody(mass, collider)); + } + void ServerEntityLibrary::SetDirection(lua_State* L, entt::handle entity, const Nz::Vector2f& upVector) { SharedEntityLibrary::SetDirection(L, entity, upVector); diff --git a/src/CoreLib/Scripting/ServerEntityStore.cpp b/src/CoreLib/Scripting/ServerEntityStore.cpp index 003f2039..7f72f6bb 100644 --- a/src/CoreLib/Scripting/ServerEntityStore.cpp +++ b/src/CoreLib/Scripting/ServerEntityStore.cpp @@ -105,7 +105,7 @@ namespace bw entt::registry& registry = layer.GetWorld(); entt::handle entity = CreateEntity(layer, entityIndex, uniqueId, position, rotation, properties, parent); - if (entity) + if (!entity) return entt::handle{}; if (!InitializeEntity(entity)) diff --git a/src/CoreLib/Scripting/SharedEntityLibrary.cpp b/src/CoreLib/Scripting/SharedEntityLibrary.cpp index eb88a671..55e9cbc9 100644 --- a/src/CoreLib/Scripting/SharedEntityLibrary.cpp +++ b/src/CoreLib/Scripting/SharedEntityLibrary.cpp @@ -18,7 +18,7 @@ #include #include #include -#include +#include #include #include @@ -160,25 +160,11 @@ namespace bw RegisterSharedLibrary(elementMetatable); } - void SharedEntityLibrary::InitRigidBody(lua_State* /*L*/, entt::handle entity, float mass) - { - entity.remove(); - - auto& entityMatch = entity.get(); - auto& physics = entityMatch.GetMatch().GetLayer(entityMatch.GetLayerIndex()).GetPhysicsSystem(); - - auto& entityPhys = entity.emplace(physics.CreateRigidBody(mass)); - - // Temp fix because of a Nazara bug - auto& entityNode = entity.get(); - entityPhys.SetRotation(AngleFromQuaternion(entityNode.GetRotation(Nz::CoordSys::Global))); - } - void SharedEntityLibrary::SetDirection(lua_State* L, entt::handle entity, const Nz::Vector2f& upVector) { Nz::RadianAnglef angle(std::atan2(upVector.y, upVector.x) + Nz::Pi / 2.f); - if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + if (Nz::ChipmunkRigidBody2DComponent* rigidBody = entity.try_get()) rigidBody->SetRotation(angle); auto& nodeComponent = entity.get(); @@ -187,19 +173,19 @@ namespace bw void SharedEntityLibrary::SetMass(lua_State* /*L*/, entt::handle entity, float mass, bool recomputeMomentOfInertia) { - if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + if (Nz::ChipmunkRigidBody2DComponent* rigidBody = entity.try_get()) rigidBody->SetMass(mass, recomputeMomentOfInertia); } void SharedEntityLibrary::SetMomentOfInertia(lua_State* /*L*/, entt::handle entity, float momentOfInertia) { - if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + if (Nz::ChipmunkRigidBody2DComponent* rigidBody = entity.try_get()) rigidBody->SetMomentOfInertia(momentOfInertia); } void SharedEntityLibrary::SetPosition(lua_State* L, entt::handle entity, const Nz::Vector2f& position) { - if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + if (Nz::ChipmunkRigidBody2DComponent* rigidBody = entity.try_get()) rigidBody->SetPosition(position); auto& nodeComponent = entity.get(); @@ -208,7 +194,7 @@ namespace bw void SharedEntityLibrary::SetRotation(lua_State* L, entt::handle entity, const Nz::DegreeAnglef& rotation) { - if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + if (Nz::ChipmunkRigidBody2DComponent* rigidBody = entity.try_get()) rigidBody->SetRotation(rotation); auto& nodeComponent = entity.get(); @@ -240,7 +226,7 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + if (Nz::ChipmunkRigidBody2DComponent* rigidBody = entity.try_get()) rigidBody->AddForce(force); }); @@ -248,7 +234,7 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + if (Nz::ChipmunkRigidBody2DComponent* rigidBody = entity.try_get()) rigidBody->AddImpulse(force); }); @@ -267,7 +253,7 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + if (Nz::ChipmunkRigidBody2DComponent* rigidBody = entity.try_get()) rigidBody->ForceSleep(); }); @@ -310,7 +296,7 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + if (Nz::ChipmunkRigidBody2DComponent* rigidBody = entity.try_get()) return sol::make_object(L, rigidBody->GetMass()); else return sol::nil; @@ -320,7 +306,7 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + if (Nz::ChipmunkRigidBody2DComponent* rigidBody = entity.try_get()) return sol::make_object(L, rigidBody->GetMomentOfInertia()); else return sol::nil; @@ -374,7 +360,7 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - Nz::RigidBody2DComponent* physComponent = entity.try_get(); + Nz::ChipmunkRigidBody2DComponent* physComponent = entity.try_get(); if (!physComponent) return Nz::Vector2f::Zero(); @@ -432,7 +418,7 @@ namespace bw elementMetatable["IsSleeping"] = LuaFunction([](const sol::table& entityTable) { entt::handle entity = AssertScriptEntity(entityTable); - if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + if (Nz::ChipmunkRigidBody2DComponent* rigidBody = entity.try_get()) return rigidBody->IsSleeping(); else return false; @@ -442,11 +428,11 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - if (Nz::RigidBody2DComponent* rigidBody = entity.try_get()) + if (Nz::ChipmunkRigidBody2DComponent* rigidBody = entity.try_get()) { if (fn) { - rigidBody->SetVelocityFunction([entity, fn = std::move(fn)](Nz::RigidBody2D& body2D, const Nz::Vector2f& gravity, float damping, float deltaTime) + rigidBody->SetVelocityFunction([entity, fn = std::move(fn)](Nz::ChipmunkRigidBody2D& body2D, const Nz::Vector2f& gravity, float damping, float deltaTime) { auto& entityScript = entity.get(); @@ -481,7 +467,7 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - Nz::RigidBody2DComponent* physComponent = entity.try_get(); + Nz::ChipmunkRigidBody2DComponent* physComponent = entity.try_get(); if (!physComponent) return; @@ -495,7 +481,7 @@ namespace bw std::size_t colliderCount = colliderTable.size(); auto& entityNode = entity.get(); - auto& entityCollData = entity.emplace(); + auto& entityCollData = entity.emplace_or_replace(); if (colliderCount <= 1) { @@ -529,13 +515,13 @@ namespace bw } } - std::shared_ptr collider = entityCollData.BuildCollider(entityNode.GetScale().y); + std::shared_ptr collider = entityCollData.BuildCollider(entityNode.GetScale().y); - Nz::RigidBody2DComponent* physComponent = entity.try_get(); + Nz::ChipmunkRigidBody2DComponent* physComponent = entity.try_get(); if (!physComponent) { InitRigidBody(L, entity, 0.f); - physComponent = &entity.get(); + physComponent = &entity.get(); } physComponent->SetGeom(std::move(collider)); @@ -560,7 +546,7 @@ namespace bw elementMetatable["SetMass"] = sol::overload( LuaFunction([=](sol::this_state L, const sol::table& entityTable, float mass) { - SetMass(L, entityTable, mass); + SetMass(L, entityTable, mass); }), LuaFunction(SetMass) ); @@ -597,7 +583,7 @@ namespace bw { entt::handle entity = AssertScriptEntity(entityTable); - Nz::RigidBody2DComponent* physComponent = entity.try_get(); + Nz::ChipmunkRigidBody2DComponent* physComponent = entity.try_get(); if (!physComponent) return; diff --git a/src/CoreLib/Scripting/SharedScriptingLibrary.cpp b/src/CoreLib/Scripting/SharedScriptingLibrary.cpp index fe7918f5..3dd163f8 100644 --- a/src/CoreLib/Scripting/SharedScriptingLibrary.cpp +++ b/src/CoreLib/Scripting/SharedScriptingLibrary.cpp @@ -17,8 +17,8 @@ #include #include #include -#include -#include +#include +#include #include namespace bw diff --git a/src/CoreLib/SharedLayer.cpp b/src/CoreLib/SharedLayer.cpp index ee9be9c2..2f642866 100644 --- a/src/CoreLib/SharedLayer.cpp +++ b/src/CoreLib/SharedLayer.cpp @@ -13,7 +13,7 @@ #include #include #include -#include +#include #include #include @@ -25,7 +25,7 @@ namespace bw m_layerIndex(layerIndex) { m_systemGraph.AddSystem(); - m_systemGraph.AddSystem(); + m_systemGraph.AddSystem(); //m_systemGraph.AddSystem(); m_systemGraph.AddSystem(match); @@ -34,7 +34,7 @@ namespace bw m_systemGraph.AddSystem(match); m_systemGraph.AddSystem(match); - Nz::PhysWorld2D& physics = m_systemGraph.GetSystem().GetPhysWorld(); + Nz::ChipmunkPhysWorld2D& physics = m_systemGraph.GetSystem().GetPhysWorld(); physics.SetGravity(Nz::Vector2f(0.f, 9.81f * 192.f)); physics.SetMaxStepCount(1); physics.SetSleepTime(Nz::Time::Zero()); diff --git a/src/CoreLib/SharedMatch.cpp b/src/CoreLib/SharedMatch.cpp index 681ad644..3c47fae7 100644 --- a/src/CoreLib/SharedMatch.cpp +++ b/src/CoreLib/SharedMatch.cpp @@ -48,6 +48,8 @@ namespace bw m_timerManager.Update(m_currentTime); OnTick(m_tickTimer < m_tickDuration); + + m_currentTick++; } } } diff --git a/src/CoreLib/Systems/NetworkSyncSystem.cpp b/src/CoreLib/Systems/NetworkSyncSystem.cpp index 2437a096..b6eaf596 100644 --- a/src/CoreLib/Systems/NetworkSyncSystem.cpp +++ b/src/CoreLib/Systems/NetworkSyncSystem.cpp @@ -61,7 +61,7 @@ namespace bw for (entt::entity entity : m_physicsEntities) { - auto& entityPhys = m_registry.get(entity); + auto& entityPhys = m_registry.get(entity); if (entityPhys.IsSleeping()) continue; @@ -118,7 +118,7 @@ namespace bw auto& entityNode = m_registry.get(entity); creationEvent.scale = entityNode.GetScale().y; //< x is affected by the "looking right" flag - if (Nz::RigidBody2DComponent* entityPhys = m_registry.try_get(entity)) + if (Nz::ChipmunkRigidBody2DComponent* entityPhys = m_registry.try_get(entity)) { creationEvent.position = entityPhys->GetPosition(); creationEvent.rotation = entityPhys->GetRotation(); @@ -216,7 +216,7 @@ namespace bw const NetworkSyncComponent& syncComponent = m_registry.get(entity); movementEvent.entityId = syncComponent.GetNetworkId(); - if (Nz::RigidBody2DComponent* entityPhys = m_registry.try_get(entity)) + if (Nz::ChipmunkRigidBody2DComponent* entityPhys = m_registry.try_get(entity)) { //TODO: Handle parents? movementEvent.position = entityPhys->GetPosition(); @@ -258,7 +258,7 @@ namespace bw assert(m_entitySlots.find(entity) == m_entitySlots.end()); auto& slots = m_entitySlots.emplace(entity, EntitySlots()).first.value(); - if (m_registry.try_get(entity)) + if (m_registry.try_get(entity)) m_physicsEntities.insert(entity); else m_staticEntities.insert(entity); @@ -389,7 +389,7 @@ namespace bw for (entt::entity entity : m_physicsUpdateEntities) { const auto& entityNetwork = m_registry.get(entity); - const auto& entityPhysics = m_registry.get(entity); + const auto& entityPhysics = m_registry.get(entity); EntityPhysics& physicsEvent = m_physicsEvent.emplace_back(); physicsEvent.entityId = entityNetwork.GetNetworkId(); diff --git a/src/CoreLib/Systems/PlayerMovementSystem.cpp b/src/CoreLib/Systems/PlayerMovementSystem.cpp index 224a9e89..2278b6af 100644 --- a/src/CoreLib/Systems/PlayerMovementSystem.cpp +++ b/src/CoreLib/Systems/PlayerMovementSystem.cpp @@ -3,8 +3,8 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include -#include -#include +#include +#include #include #include #include @@ -14,7 +14,7 @@ namespace bw { PlayerMovementSystem::PlayerMovementSystem(entt::registry& registry) : - m_controllerObserver(registry, entt::collector.group()), + m_controllerObserver(registry, entt::collector.group()), m_registry(registry) { m_inputDestroyConnection = registry.on_destroy().connect<&PlayerMovementSystem::OnInputDestroy>(this); @@ -33,8 +33,8 @@ namespace bw { assert(m_inputControlledEntities.find(entity) == m_inputControlledEntities.end()); - auto& entityPhys = m_registry.get(entity); - entityPhys.SetVelocityFunction([handle = entt::handle(m_registry, entity)](Nz::RigidBody2D& rigidBody, const Nz::Vector2f& gravity, float damping, float dt) + auto& entityPhys = m_registry.get(entity); + entityPhys.SetVelocityFunction([handle = entt::handle(m_registry, entity)](Nz::ChipmunkRigidBody2D& rigidBody, const Nz::Vector2f& gravity, float damping, float dt) { auto& movementComponent = handle.get(); @@ -53,20 +53,20 @@ namespace bw m_inputControlledEntities.emplace(entity); }); - auto view = m_registry.view(); + auto view = m_registry.view(); for (entt::entity entity : view) { auto& inputComponent = view.get(entity); auto& playerMovement = view.get(entity); auto& nodeComponent = view.get(entity); - auto& entityPhys = view.get(entity); + auto& entityPhys = view.get(entity); const auto& inputs = inputComponent.GetInputs(); Nz::Vector2f up = Nz::Vector2f::UnitY(); bool isOnGround = false; - entityPhys.ForEachArbiter([&](Nz::Arbiter2D& arbiter) + entityPhys.ForEachArbiter([&](Nz::ChipmunkArbiter2D& arbiter) { if (up.DotProduct(arbiter.GetNormal()) > 0.75f) isOnGround = true; @@ -87,7 +87,7 @@ namespace bw if (it == m_inputControlledEntities.end()) return; - auto& entityPhys = registry.get(entity); + auto& entityPhys = registry.get(entity); entityPhys.ResetVelocityFunction(); m_inputControlledEntities.erase(it); @@ -99,7 +99,7 @@ namespace bw if (it == m_inputControlledEntities.end()) return; - auto& entityPhys = registry.get(entity); + auto& entityPhys = registry.get(entity); entityPhys.ResetVelocityFunction(); m_inputControlledEntities.erase(it); diff --git a/src/CoreLib/TerrainLayer.cpp b/src/CoreLib/TerrainLayer.cpp index f0056aef..b1e758ab 100644 --- a/src/CoreLib/TerrainLayer.cpp +++ b/src/CoreLib/TerrainLayer.cpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include namespace bw { diff --git a/src/CoreLib/WebRequest.cpp b/src/CoreLib/WebRequest.cpp deleted file mode 100644 index f0e3ce50..00000000 --- a/src/CoreLib/WebRequest.cpp +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include -#include -#include //< include last because of curl/curl.h - -namespace bw -{ - WebRequest::WebRequest() : - m_isUserAgentSet(false) - { - auto& libcurl = WebService::GetLibcurl(); - - m_curlHandle = libcurl.easy_init(); - } - - WebRequest::~WebRequest() - { - auto& libcurl = WebService::GetLibcurl(); - if (m_curlHandle) - libcurl.easy_cleanup(m_curlHandle); - - if (m_headerList) - libcurl.slist_free_all(m_headerList); - } - - void WebRequest::ForceProtocol(Nz::NetProtocol protocol) - { - assert(protocol != Nz::NetProtocol::Unknown); - - auto& libcurl = WebService::GetLibcurl(); - switch (protocol) - { - case Nz::NetProtocol::Any: - libcurl.easy_setopt(m_curlHandle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER); - break; - - case Nz::NetProtocol::IPv4: - libcurl.easy_setopt(m_curlHandle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); - break; - - case Nz::NetProtocol::IPv6: - libcurl.easy_setopt(m_curlHandle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6); - break; - - case Nz::NetProtocol::Unknown: - break; - } - } - - void WebRequest::SetJSonContent(const std::string_view& encodedJSon) - { - auto& libcurl = WebService::GetLibcurl(); - - SetHeader("Content-Type", "application/json"); - libcurl.easy_setopt(m_curlHandle, CURLOPT_POSTFIELDSIZE_LARGE, curl_off_t(encodedJSon.size())); - libcurl.easy_setopt(m_curlHandle, CURLOPT_COPYPOSTFIELDS, encodedJSon.data()); - } - - void WebRequest::SetMaximumFileSize(Nz::UInt64 maxFileSize) - { - auto& libcurl = WebService::GetLibcurl(); - - curl_off_t maxSize = maxFileSize; - libcurl.easy_setopt(m_curlHandle, CURLOPT_MAXFILESIZE_LARGE, maxSize); - } - - void WebRequest::SetServiceName(const std::string_view& serviceName) - { - auto& libcurl = WebService::GetLibcurl(); - - if (!serviceName.empty()) - { - //TODO Nz::StackString? - std::string userAgent = WebService::GetUserAgent(); - userAgent.reserve(userAgent.size() + 3 + serviceName.size()); - userAgent.append(" - "); - userAgent.append(serviceName.data(), serviceName.size()); - - libcurl.easy_setopt(m_curlHandle, CURLOPT_USERAGENT, userAgent.data()); - } - else - libcurl.easy_setopt(m_curlHandle, CURLOPT_USERAGENT, WebService::GetUserAgent().c_str()); - - m_isUserAgentSet = true; - } - - void WebRequest::SetURL(const std::string& url) - { - auto& libcurl = WebService::GetLibcurl(); - - libcurl.easy_setopt(m_curlHandle, CURLOPT_URL, url.data()); - } - - void WebRequest::SetupGet() - { - auto& libcurl = WebService::GetLibcurl(); - - libcurl.easy_setopt(m_curlHandle, CURLOPT_HTTPGET, long(1)); - } - - void WebRequest::SetupPost() - { - auto& libcurl = WebService::GetLibcurl(); - - libcurl.easy_setopt(m_curlHandle, CURLOPT_POST, long(1)); - } - - std::unique_ptr WebRequest::Get(const std::string& url, ResultCallback callback) - { - std::unique_ptr request = std::make_unique(); - request->SetURL(url); - request->SetResultCallback(std::move(callback)); - request->SetupGet(); - - return request; - } - - std::unique_ptr WebRequest::Post(const std::string& url, ResultCallback callback) - { - std::unique_ptr request = std::make_unique(); - request->SetURL(url); - request->SetResultCallback(std::move(callback)); - request->SetupPost(); - - return request; - } - - CURL* WebRequest::Prepare() - { - auto& libcurl = WebService::GetLibcurl(); - - if (!m_headers.empty()) - { - for (auto&& [header, value] : m_headers) - { - std::string headerValue = (!value.empty()) ? header + ": " + value : header + ";"; - m_headerList = libcurl.slist_append(m_headerList, headerValue.c_str()); - } - - libcurl.easy_setopt(m_curlHandle, CURLOPT_HTTPHEADER, m_headerList.Get()); - } - - if (!m_isUserAgentSet) - libcurl.easy_setopt(m_curlHandle, CURLOPT_USERAGENT, WebService::GetUserAgent().c_str()); - - return m_curlHandle; - } -} diff --git a/src/CoreLib/WebRequestResult.cpp b/src/CoreLib/WebRequestResult.cpp deleted file mode 100644 index ebb40b27..00000000 --- a/src/CoreLib/WebRequestResult.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include -#include -#include //< include last because of curl/curl.h - -namespace bw -{ - Nz::UInt64 WebRequestResult::GetDownloadedSize() const - { - assert(HasSucceeded()); - - auto& libcurl = WebService::GetLibcurl(); - - curl_off_t downloadedSize = 0; - libcurl.easy_getinfo(m_curlHandle, CURLINFO_SIZE_DOWNLOAD_T, &downloadedSize); - - return downloadedSize; - } - - std::size_t WebRequestResult::GetDownloadSpeed() const - { - assert(HasSucceeded()); - - auto& libcurl = WebService::GetLibcurl(); - - curl_off_t downloadSpeed = 0; - libcurl.easy_getinfo(m_curlHandle, CURLINFO_SPEED_DOWNLOAD_T, &downloadSpeed); - - return downloadSpeed; - } - - long WebRequestResult::GetReponseCode() const - { - assert(HasSucceeded()); - - auto& libcurl = WebService::GetLibcurl(); - - long responseCode; - libcurl.easy_getinfo(m_curlHandle, CURLINFO_RESPONSE_CODE, &responseCode); - - return responseCode; - } -} diff --git a/src/CoreLib/WebService.cpp b/src/CoreLib/WebService.cpp deleted file mode 100644 index b1b4e0a0..00000000 --- a/src/CoreLib/WebService.cpp +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include -#include -#include -#include -#include //< include last because of curl/curl.h -#include - -namespace bw -{ - WebService::WebService(const Logger& logger) : - m_logger(logger) - { - assert(IsInitialized()); - m_curlMulti = s_curlLibrary->multi_init(); - } - - WebService::~WebService() - { - assert(IsInitialized()); - - if (m_curlMulti) - { - for (auto&& [handle, request] : m_activeRequests) - s_curlLibrary->multi_remove_handle(m_curlMulti, handle); - - s_curlLibrary->multi_cleanup(m_curlMulti); - } - } - - void WebService::AddRequest(std::unique_ptr&& request) - { - assert(m_curlMulti); - assert(request); - - CURL* handle = request->Prepare(); - - curl_write_callback writeCallback = [](char* ptr, std::size_t size, std::size_t nmemb, void* userdata) -> std::size_t - { - WebRequest* request = static_cast(userdata); - - std::size_t totalSize = size * nmemb; - if (!request->OnBodyResponse(ptr, totalSize)) - return 0; - - return totalSize; - }; - - s_curlLibrary->easy_setopt(handle, CURLOPT_WRITEFUNCTION, writeCallback); - s_curlLibrary->easy_setopt(handle, CURLOPT_WRITEDATA, request.get()); - - m_activeRequests.emplace(handle, std::move(request)); - - s_curlLibrary->multi_add_handle(m_curlMulti, handle); - } - - void WebService::Poll() - { - assert(m_curlMulti); - - int reportedActiveRequest; - CURLMcode err = s_curlLibrary->multi_perform(m_curlMulti, &reportedActiveRequest); - if (err != CURLM_OK) - { - bwLog(m_logger, LogLevel::Error, "[WebService] curl_multi_perform failed with {0}: {1}", err, s_curlLibrary->multi_strerror(err)); - return; - } - - CURLMsg* m; - do - { - int msgq; - m = s_curlLibrary->multi_info_read(m_curlMulti, &msgq); - if (m && (m->msg == CURLMSG_DONE)) - { - CURL* handle = m->easy_handle; - - auto it = m_activeRequests.find(handle); - assert(it != m_activeRequests.end()); - - WebRequest& request = *it->second; - - if (m->data.result == CURLE_OK) - request.TriggerCallback(); - else - request.TriggerCallback(s_curlLibrary->easy_strerror(m->data.result)); - - s_curlLibrary->multi_remove_handle(m_curlMulti, handle); - - m_activeRequests.erase(handle); - } - } - while (m); - } - - bool WebService::Initialize(std::string* error) - { - assert(!IsInitialized()); - - std::unique_ptr libcurl = std::make_unique(); - for (const char* libname : { "libcurl" NAZARA_DYNLIB_EXTENSION, "libcurl-d" NAZARA_DYNLIB_EXTENSION }) - { - Nz::ErrorFlags errFlags(Nz::ErrorMode::Silent); - if (libcurl->library.Load(libname)) - break; - } - - if (!libcurl->library.IsLoaded()) - { - if (error) - *error = "failed to load libcurl: " + libcurl->library.GetLastError(); - - return false; - } - - auto LoadFunction = [&](auto& funcPtr, const char* symbolName) - { - funcPtr = reinterpret_cast>(libcurl->library.GetSymbol(symbolName)); - if (!funcPtr) - throw std::runtime_error("failed to load " + std::string(symbolName) + " from curl"); - }; - - try - { -#define BURGWAR_CURL_FUNCTION(F) LoadFunction(libcurl-> F, "curl_" #F); - -#include - } - catch (const std::exception& e) - { - if (error) - *error = e.what(); - - return false; - } - - if (libcurl->global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK) - return false; - - curl_version_info_data* curlVersionData = libcurl->version_info(CURLVERSION_NOW); - - s_userAgent = "Burg'War/" + - std::to_string(GameMajorVersion) + "." + std::to_string(GameMinorVersion) + "." + std::to_string(GamePatchVersion) + - " WebService - curl/" + std::string(curlVersionData->version); - - s_curlLibrary = std::move(libcurl); - return true; - } - - void WebService::Uninitialize() - { - if (IsInitialized()) - { - s_curlLibrary->global_cleanup(); - s_curlLibrary.reset(); - - s_userAgent = std::string(); //< force buffer deletion - } - } - - std::string WebService::s_userAgent; - std::unique_ptr WebService::s_curlLibrary; -} diff --git a/src/MapEditor/Components/CanvasComponent.cpp b/src/MapEditor/Components/CanvasComponent.cpp deleted file mode 100644 index 5dfa7a30..00000000 --- a/src/MapEditor/Components/CanvasComponent.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (C) 2020 Jérôme Leclercq -// This file is part of the "Burgwar" project -// For conditions of distribution and use, see copyright notice in LICENSE - -#include - -namespace bw -{ - Ndk::ComponentIndex CanvasComponent::componentIndex; -} diff --git a/src/MapEditor/Components/CanvasComponent.hpp b/src/MapEditor/Components/CanvasComponent.hpp index c4e76647..b1e338a9 100644 --- a/src/MapEditor/Components/CanvasComponent.hpp +++ b/src/MapEditor/Components/CanvasComponent.hpp @@ -9,13 +9,12 @@ #include #include -#include namespace bw { class MapCanvas; - class CanvasComponent : public Ndk::Component + class CanvasComponent { public: inline CanvasComponent(MapCanvas& mapCanvas, LayerIndex layerIndex, EntityId uniqueId); @@ -26,8 +25,6 @@ namespace bw inline const MapCanvas& GetMapCanvas() const; inline EntityId GetUniqueId() const; - static Ndk::ComponentIndex componentIndex; - private: EntityId m_uniqueId; LayerIndex m_layerIndex; diff --git a/src/MapEditor/Gizmos/CameraMovement.cpp b/src/MapEditor/Gizmos/CameraMovement.cpp index 9d24757c..b955484e 100644 --- a/src/MapEditor/Gizmos/CameraMovement.cpp +++ b/src/MapEditor/Gizmos/CameraMovement.cpp @@ -5,7 +5,6 @@ #include #include #include -#include constexpr float zoomLevel = 10.f; constexpr float maxZoomLevel = zoomLevel; @@ -35,7 +34,7 @@ namespace bw if (mouseButton.button != Nz::Mouse::Middle && mouseButton.button != Nz::Mouse::Right) return false; - m_cursorController.UpdateCursor(Nz::Cursor::Get(Nz::SystemCursor_Move)); + m_cursorController.UpdateCursor(Nz::Cursor::Get(Nz::SystemCursor::Move)); m_isActive = true; m_originalWorldPos = m_camera.Unproject({ float(mouseButton.x), float(mouseButton.y) }); @@ -47,7 +46,7 @@ namespace bw if (mouseButton.button != Nz::Mouse::Middle && mouseButton.button != Nz::Mouse::Right) return false; - m_cursorController.UpdateCursor(Nz::Cursor::Get(Nz::SystemCursor_Default)); + m_cursorController.UpdateCursor(Nz::Cursor::Get(Nz::SystemCursor::Default)); m_isActive = false; return true; diff --git a/src/MapEditor/Gizmos/CameraMovement.hpp b/src/MapEditor/Gizmos/CameraMovement.hpp index bc0c076d..32d3510a 100644 --- a/src/MapEditor/Gizmos/CameraMovement.hpp +++ b/src/MapEditor/Gizmos/CameraMovement.hpp @@ -9,8 +9,7 @@ #include #include -#include -#include +#include namespace bw { diff --git a/src/MapEditor/Gizmos/EditorGizmo.cpp b/src/MapEditor/Gizmos/EditorGizmo.cpp index db2ff1df..43c60e39 100644 --- a/src/MapEditor/Gizmos/EditorGizmo.cpp +++ b/src/MapEditor/Gizmos/EditorGizmo.cpp @@ -3,11 +3,12 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include +#include +#include #include #include #include #include -#include #include namespace bw @@ -15,10 +16,10 @@ namespace bw EditorGizmo::EditorGizmo(entt::registry& renderWorld, std::vector entities) : m_targetEntities(std::move(entities)) { - m_selectionOverlayEntity = renderWorld.CreateEntity(); - m_selectionOverlayEntity->AddComponent(); + m_selectionOverlayEntity = entt::handle(renderWorld, renderWorld.create()); + m_selectionOverlayEntity->emplace(); - auto& node = m_selectionOverlayEntity->AddComponent(); + auto& node = m_selectionOverlayEntity->emplace(); node.SetInheritRotation(false); node.SetInheritScale(false); @@ -46,21 +47,21 @@ namespace bw Nz::Vector3f origin = globalAABB.GetCenter(); - auto& node = m_selectionOverlayentity.get(); + auto& node = m_selectionOverlayEntity->get(); node.SetPosition(origin); - auto& gfx = m_selectionOverlayEntity->GetComponent(); + auto& gfx = m_selectionOverlayEntity->get(); gfx.Clear(); std::shared_ptr aabbModel = GenerateBoxModel(); - gfx.Attach(aabbModel, Nz::Matrix4f::Transform(globalAABB.GetPosition() - origin, Nz::Quaternionf::Identity(), globalAABB.GetLengths()), std::numeric_limits::max()); + /*gfx.Attach(aabbModel, Nz::Matrix4f::Transform(globalAABB.GetPosition() - origin, Nz::Quaternionf::Identity(), globalAABB.GetLengths()), std::numeric_limits::max()); if (aabbs.size() > 1) { for (const Nz::Boxf& aabb : aabbs) gfx.Attach(aabbModel, Nz::Matrix4f::Transform(aabb.GetPosition() - origin, Nz::Quaternionf::Identity(), aabb.GetLengths()), std::numeric_limits::max() - 1); - } + }*/ } std::shared_ptr EditorGizmo::GenerateBoxModel() @@ -88,38 +89,38 @@ namespace bw std::array positions = { { - box.GetCorner(Nz::BoxCorner_FarLeftBottom), - box.GetCorner(Nz::BoxCorner_NearLeftBottom), - box.GetCorner(Nz::BoxCorner_NearRightBottom), - box.GetCorner(Nz::BoxCorner_FarRightBottom), - box.GetCorner(Nz::BoxCorner_FarLeftTop), - box.GetCorner(Nz::BoxCorner_NearLeftTop), - box.GetCorner(Nz::BoxCorner_NearRightTop), - box.GetCorner(Nz::BoxCorner_FarRightTop) + box.GetCorner(Nz::BoxCorner::FarLeftBottom), + box.GetCorner(Nz::BoxCorner::NearLeftBottom), + box.GetCorner(Nz::BoxCorner::NearRightBottom), + box.GetCorner(Nz::BoxCorner::FarRightBottom), + box.GetCorner(Nz::BoxCorner::FarLeftTop), + box.GetCorner(Nz::BoxCorner::NearLeftTop), + box.GetCorner(Nz::BoxCorner::NearRightTop), + box.GetCorner(Nz::BoxCorner::FarRightTop) } }; - Nz::IndexBufferRef boxIndexBuffer = Nz::IndexBuffer::New(false, Nz::UInt32(indices.size()), Nz::DataStorage_Hardware, Nz::BufferUsageFlags{}); + std::shared_ptr boxIndexBuffer = std::make_shared(false, Nz::UInt32(indices.size()), Nz::DataStorage::Hardware, Nz::BufferUsageFlags{}); boxIndexBuffer->Fill(indices.data(), 0, Nz::UInt32(indices.size())); - Nz::VertexBufferRef boxVertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), Nz::UInt32(positions.size()), Nz::DataStorage_Hardware, Nz::BufferUsageFlags{}); + std::shared_ptr boxVertexBuffer = std::make_shared(Nz::VertexDeclaration::Get(Nz::VertexLayout::XYZ), Nz::UInt32(positions.size()), Nz::DataStorage_Hardware, Nz::BufferUsageFlags{}); boxVertexBuffer->Fill(positions.data(), 0, Nz::UInt32(positions.size())); - Nz::StaticMeshRef boxMesh = Nz::StaticMesh::New(boxVertexBuffer, boxIndexBuffer); + std::shared_ptr boxMesh = std::make_shared(boxVertexBuffer, boxIndexBuffer); boxMesh->GenerateAABB(); - boxMesh->SetPrimitiveMode(Nz::PrimitiveMode_LineList); + boxMesh->SetPrimitiveMode(Nz::PrimitiveMode::LineList); - Nz::MeshRef mesh = Nz::Mesh::New(); + std::shared_ptr mesh = std::make_shared(); mesh->CreateStatic(); mesh->AddSubMesh(boxMesh); - Nz::MaterialRef translucent = Nz::Material::New(); - translucent->SetDiffuseColor(Nz::Color::Orange); - translucent->EnableDepthBuffer(false); + std::shared_ptr gfxMesh = Nz::GraphicalMesh::BuildFromMesh(*mesh); + + std::shared_ptr translucentMat = Nz::Graphics::Instance()->GetDefaultMaterials().basicTransparent->Clone(); + translucentMat->SetValueProperty("BaseColor", Nz::Color::Orange()); - std::shared_ptr model = Nz::Model::New(); - model->SetMesh(mesh); - model->SetMaterial(0, translucent); + std::shared_ptr model = std::make_shared(std::move(gfxMesh)); + model->SetMaterial(0, std::move(translucentMat)); return model; } diff --git a/src/MapEditor/Gizmos/EditorGizmo.hpp b/src/MapEditor/Gizmos/EditorGizmo.hpp index dc59b1b4..bb76bd42 100644 --- a/src/MapEditor/Gizmos/EditorGizmo.hpp +++ b/src/MapEditor/Gizmos/EditorGizmo.hpp @@ -8,7 +8,7 @@ #define BURGWAR_MAPEDITOR_EDITORGIZMO_HPP #include -#include +#include #include #include @@ -20,7 +20,7 @@ namespace bw EditorGizmo(entt::registry& renderWorld, std::vector entities); virtual ~EditorGizmo(); - inline entt::entity GetSelectionOverlayEntity() const; + inline entt::handle GetSelectionOverlayEntity() const; inline const std::vector& GetTargetEntities() const; virtual bool OnMouseButtonPressed(const Nz::WindowEvent::MouseButtonEvent& mouseButton) = 0; diff --git a/src/MapEditor/Gizmos/EditorGizmo.inl b/src/MapEditor/Gizmos/EditorGizmo.inl index 75324e3a..f8456301 100644 --- a/src/MapEditor/Gizmos/EditorGizmo.inl +++ b/src/MapEditor/Gizmos/EditorGizmo.inl @@ -6,7 +6,7 @@ namespace bw { - inline entt::entity EditorGizmo::GetSelectionOverlayEntity() const + inline entt::handle EditorGizmo::GetSelectionOverlayEntity() const { return m_selectionOverlayEntity; } diff --git a/src/MapEditor/Gizmos/PositionGizmo.cpp b/src/MapEditor/Gizmos/PositionGizmo.cpp index 85cfd3a6..a236ecf0 100644 --- a/src/MapEditor/Gizmos/PositionGizmo.cpp +++ b/src/MapEditor/Gizmos/PositionGizmo.cpp @@ -6,9 +6,9 @@ #include #include #include -#include +#include +#include #include -#include namespace bw { @@ -19,40 +19,40 @@ namespace bw m_movementType(MovementType::None), m_positionAlignment(positionAlignment) { - m_spriteDefaultColors[MovementType::XAxis] = Nz::Color::Red; - m_spriteDefaultColors[MovementType::YAxis] = Nz::Color::Blue; + m_spriteDefaultColors[MovementType::XAxis] = Nz::Color::Red(); + m_spriteDefaultColors[MovementType::YAxis] = Nz::Color::Blue(); m_spriteDefaultColors[MovementType::XYAxis] = Nz::Color(255, 255, 255, 128); - Nz::MaterialRef translucent = Nz::Material::New("Translucent2D"); + std::shared_ptr translucent = Nz::Graphics::Instance()->GetDefaultMaterials().basicTransparent->Clone(); - m_sprites[MovementType::XYAxis] = Nz::Sprite::New(); + m_sprites[MovementType::XYAxis] = std::make_shared(translucent); m_sprites[MovementType::XYAxis]->SetMaterial(translucent); m_sprites[MovementType::XYAxis]->SetColor(m_spriteDefaultColors[MovementType::XYAxis]); - m_sprites[MovementType::XYAxis]->SetSize(16.f, 16.f); + m_sprites[MovementType::XYAxis]->SetSize({ 16.f, 16.f }); m_sprites[MovementType::XYAxis]->SetOrigin(Nz::Vector2f(0.f, 16.f)); - m_sprites[MovementType::XAxis] = Nz::Sprite::New(); - m_sprites[MovementType::XAxis]->SetMaterial(Nz::MaterialLibrary::Get("GizmoArrow")); + /*m_sprites[MovementType::XAxis] = std::make_shared(translucent); + //m_sprites[MovementType::XAxis]->SetMaterial(Nz::MaterialLibrary::Get("GizmoArrow")); m_sprites[MovementType::XAxis]->SetColor(m_spriteDefaultColors[MovementType::XAxis]); m_sprites[MovementType::XAxis]->SetSize(m_sprites[MovementType::XAxis]->GetSize() / 2.f); m_sprites[MovementType::XAxis]->SetOrigin(Nz::Vector2f(0.f, m_sprites[MovementType::XAxis]->GetSize().y / 2.f)); - m_sprites[MovementType::YAxis] = Nz::Sprite::New(*m_sprites[MovementType::XAxis]); - m_sprites[MovementType::YAxis]->SetColor(m_spriteDefaultColors[MovementType::YAxis]); + m_sprites[MovementType::YAxis] = std::make_shared(*m_sprites[MovementType::XAxis]); + m_sprites[MovementType::YAxis]->SetColor(m_spriteDefaultColors[MovementType::YAxis]);*/ m_allowedMovements[MovementType::XAxis].Set(1.f, 0.f); m_allowedMovements[MovementType::YAxis].Set(0.f, 1.f); m_allowedMovements[MovementType::XYAxis].Set(1.f, 1.f); - entt::entity selectionOverlayEntity = GetSelectionOverlayEntity(); - m_arrowEntity = selectionOverlayEntity->GetWorld()->CreateEntity(); + entt::handle selectionOverlayEntity = GetSelectionOverlayEntity(); + m_arrowEntity = entt::handle(*selectionOverlayEntity.registry(), selectionOverlayEntity.registry()->create()); - auto& gfx = m_arrowEntity->AddComponent(); - gfx.Attach(m_sprites[MovementType::XYAxis], 2); - gfx.Attach(m_sprites[MovementType::XAxis], 1); - gfx.Attach(m_sprites[MovementType::YAxis], Nz::Matrix4f::Rotate(Nz::DegreeAnglef(-90.f)), 1); + auto& gfx = m_arrowEntity->emplace(); + gfx.AttachRenderable(m_sprites[MovementType::XYAxis], 2); + gfx.AttachRenderable(m_sprites[MovementType::XAxis], 1); + gfx.AttachRenderable(m_sprites[MovementType::YAxis], Nz::Matrix4f::Rotate(Nz::DegreeAnglef(-90.f)), 1); - auto& node = m_arrowEntity->AddComponent(); + auto& node = m_arrowEntity->emplace(); node.SetInheritRotation(false); node.SetInheritScale(false); node.SetParent(selectionOverlayEntity); @@ -61,7 +61,7 @@ namespace bw for (const LayerVisualEntityHandle& visualEntity : GetTargetEntities()) { - auto& entityNode = visualEntity->GetEntity()->GetComponent(); + auto& entityNode = visualEntity->GetEntity().get(); m_entitiesOffsets.push_back(Nz::Vector2f(entityNode.GetPosition(Nz::CoordSys::Global)) - arrowPosition); } } @@ -77,7 +77,7 @@ namespace bw Nz::Vector3f start = m_camera.Unproject(Nz::Vector3f(float(mouseButton.x), float(mouseButton.y), 0.f)); Nz::Vector3f end = m_camera.Unproject(Nz::Vector3f(float(mouseButton.x), float(mouseButton.y), 1.f)); - auto& graphicsComponent = m_arrowEntity->GetComponent(); + auto& graphicsComponent = m_arrowEntity->get(); Nz::Rayf ray(start, end - start); diff --git a/src/MapEditor/Logic/EditorMode.hpp b/src/MapEditor/Logic/EditorMode.hpp index 56988131..eef1f15a 100644 --- a/src/MapEditor/Logic/EditorMode.hpp +++ b/src/MapEditor/Logic/EditorMode.hpp @@ -7,7 +7,7 @@ #ifndef BURGWAR_MAPEDITOR_SCRIPTING_EDITOR_MODE_HPP #define BURGWAR_MAPEDITOR_SCRIPTING_EDITOR_MODE_HPP -#include +#include #include namespace bw diff --git a/src/MapEditor/Widgets/EditorWindow.cpp b/src/MapEditor/Widgets/EditorWindow.cpp index f3841789..ac1cad8c 100644 --- a/src/MapEditor/Widgets/EditorWindow.cpp +++ b/src/MapEditor/Widgets/EditorWindow.cpp @@ -707,7 +707,7 @@ namespace bw textures.insert(texturePath); }); - std::filesystem::path gameResourceFolder = std::filesystem::u8path(m_config.GetStringValue("Resources.AssetDirectory")); + std::filesystem::path gameResourceFolder = Nz::Utf8Path(m_config.GetStringValue("Resources.AssetDirectory")); std::vector& assets = map.GetAssets(); assets.clear(); @@ -716,7 +716,7 @@ namespace bw for (const std::string& texturePath : textures) { - std::filesystem::path fullPath = gameResourceFolder / std::filesystem::u8path(texturePath); + std::filesystem::path fullPath = gameResourceFolder / Nz::Utf8Path(texturePath); auto& asset = assets.emplace_back(); asset.filepath = texturePath; @@ -1581,7 +1581,7 @@ namespace bw { Map map; - std::filesystem::path workingMapPath = std::filesystem::u8path(mapFolder.toStdString()); + std::filesystem::path workingMapPath = Nz::Utf8Path(mapFolder.toStdString()); try { map = Map::LoadFromDirectory(workingMapPath); diff --git a/src/MapEditor/Widgets/EditorWindow.hpp b/src/MapEditor/Widgets/EditorWindow.hpp index a3654382..6083de5b 100644 --- a/src/MapEditor/Widgets/EditorWindow.hpp +++ b/src/MapEditor/Widgets/EditorWindow.hpp @@ -7,7 +7,6 @@ #ifndef BURGWAR_MAPEDITOR_WIDGETS_EDITORWINDOW_HPP #define BURGWAR_MAPEDITOR_WIDGETS_EDITORWINDOW_HPP -#include #include #include #include diff --git a/src/MapEditor/Widgets/EditorWindowPrefabs.hpp b/src/MapEditor/Widgets/EditorWindowPrefabs.hpp index 76718f93..3004fbd1 100644 --- a/src/MapEditor/Widgets/EditorWindowPrefabs.hpp +++ b/src/MapEditor/Widgets/EditorWindowPrefabs.hpp @@ -7,7 +7,6 @@ #ifndef BURGWAR_MAPEDITOR_WIDGETS_EDITORWINDOWPREFABS_HPP #define BURGWAR_MAPEDITOR_WIDGETS_EDITORWINDOWPREFABS_HPP -#include #include class QMenu; diff --git a/src/MapEditor/Widgets/EntityInfoDialog.hpp b/src/MapEditor/Widgets/EntityInfoDialog.hpp index cfc69a4e..ca433858 100644 --- a/src/MapEditor/Widgets/EntityInfoDialog.hpp +++ b/src/MapEditor/Widgets/EntityInfoDialog.hpp @@ -8,11 +8,11 @@ #define BURGWAR_MAPEDITOR_WIDGETS_ENTITYINFODIALOG_HPP #include -#include #include #include #include #include +#include #include #include #include @@ -113,7 +113,7 @@ namespace bw bool isArray; }; - Ndk::EntityHandle m_targetEntity; + entt::handle m_targetEntity; EntityId m_entityUniqueId; LayerIndex m_entityLayer; std::size_t m_entityTypeIndex; diff --git a/src/MapEditor/Widgets/MapCanvas.cpp b/src/MapEditor/Widgets/MapCanvas.cpp index 79f72f4d..16187a04 100644 --- a/src/MapEditor/Widgets/MapCanvas.cpp +++ b/src/MapEditor/Widgets/MapCanvas.cpp @@ -30,12 +30,12 @@ namespace bw { MapCanvas::MapCanvas(EditorWindow& editor, QWidget* parent) : - SharedMatch(editor, LogSide::Editor, "editor", 1.f / 60.f), + SharedMatch(editor, LogSide::Editor, "editor", Nz::Time::TickDuration(60)), WorldCanvas(parent), m_editor(editor), m_isPhysicsDebugDrawEnabled(false) { - entt::registry& world = GetWorld(); + entt::registry& world = GetSystemGraph(); world.AddSystem(); world.AddSystem(); @@ -170,11 +170,11 @@ namespace bw m_isPhysicsDebugDrawEnabled = enable; } - void MapCanvas::ForEachEntity(std::function func) + void MapCanvas::ForEachEntity(tl::function_ref func) { for (auto&& [uniqueId, visualEntityHandle] : m_entitiesByUniqueId) { - entt::entity entity = visualEntityHandle->GetEntity(); + entt::handle entity = visualEntityHandle->GetEntity(); if (!entity) continue; @@ -284,9 +284,9 @@ namespace bw m_weaponStore->LoadDirectory("weapons"); m_weaponStore->Resolve(); - ForEachEntity([this](entt::entity entity) + ForEachEntity([this](entt::handle entity) { - if (entity->HasComponent()) + if (entity.try_get()) m_entityStore->UpdateEntityElement(entity); }); @@ -307,7 +307,7 @@ namespace bw m_layers.emplace_back(*this, LayerIndex(i)); } - entt::entity MapCanvas::RetrieveEntityByUniqueId(EntityId uniqueId) const + entt::handle MapCanvas::RetrieveEntityByUniqueId(EntityId uniqueId) const { auto it = m_entitiesByUniqueId.find(uniqueId); if (it == m_entitiesByUniqueId.end()) @@ -325,12 +325,16 @@ namespace bw return it->second; } - EntityId MapCanvas::RetrieveUniqueIdByEntity(entt::entity entity) const + EntityId MapCanvas::RetrieveUniqueIdByEntity(entt::handle entity) const { - if (!entity || !entity->HasComponent()) + if (!entity) return InvalidEntityId; - return entity->GetComponent().GetUniqueId(); + CanvasComponent* canvasComponent = entity.try_get(); + if (!canvasComponent) + return InvalidEntityId; + + return canvasComponent->GetUniqueId(); } void MapCanvas::ShowGrid(bool show) diff --git a/src/MapEditor/Widgets/MapCanvas.hpp b/src/MapEditor/Widgets/MapCanvas.hpp index 4ae6a071..79ba3285 100644 --- a/src/MapEditor/Widgets/MapCanvas.hpp +++ b/src/MapEditor/Widgets/MapCanvas.hpp @@ -19,7 +19,6 @@ #include #include #include -#include #include #include @@ -44,7 +43,7 @@ namespace bw void EditEntitiesPosition(const std::vector& entityIds); void EnablePhysicsDebugDraw(bool enable); - void ForEachEntity(std::function func) override; + void ForEachEntity(tl::function_ref func) override; template void ForEachEntity(F&& func); template void ForEachMapEntity(F&& func); @@ -67,9 +66,9 @@ namespace bw void ReloadScripts(); void ResetLayers(std::size_t layerCount); - entt::entity RetrieveEntityByUniqueId(EntityId uniqueId) const override; + entt::handle RetrieveEntityByUniqueId(EntityId uniqueId) const override; const LayerVisualEntityHandle& RetrieveLayerEntityByUniqueId(EntityId uniqueId) const; - EntityId RetrieveUniqueIdByEntity(entt::entity entity) const override; + EntityId RetrieveUniqueIdByEntity(entt::handle entity) const override; void ShowGrid(bool show); diff --git a/src/MapEditor/Widgets/NazaraCanvas.cpp b/src/MapEditor/Widgets/NazaraCanvas.cpp index 53d77240..63c9d0b9 100644 --- a/src/MapEditor/Widgets/NazaraCanvas.cpp +++ b/src/MapEditor/Widgets/NazaraCanvas.cpp @@ -27,7 +27,7 @@ namespace bw m_updateTimer.setInterval(1000 / 60); m_updateTimer.connect(&m_updateTimer, &QTimer::timeout, [this]() { - OnUpdate(m_updateTimer.intervalAsDuration().count() / 1000.f); + OnUpdate(Nz::Time::FromDuration(m_updateTimer.intervalAsDuration())); }); } @@ -36,11 +36,6 @@ namespace bw m_updateTimer.stop(); } - Nz::Vector2ui NazaraCanvas::GetSize() const - { - return Nz::Vector2ui(Nz::Vector2i(width(), height())); - } - QSize NazaraCanvas::minimumSizeHint() const { return QSize(640, 480); @@ -51,9 +46,14 @@ namespace bw return QSize(); } - void NazaraCanvas::resizeEvent(QResizeEvent*) + void NazaraCanvas::resizeEvent(QResizeEvent* resize) { - OnWindowResized(); + Nz::WindowEvent event; + event.type = Nz::WindowEventType::Resized; + event.size.width = resize->size().width(); + event.size.height = resize->size().height(); + + HandleEvent(event); } void NazaraCanvas::showEvent(QShowEvent*) @@ -64,7 +64,20 @@ namespace bw XFlush(QX11Info::display()); #endif - Nz::RenderWindow::Create(reinterpret_cast(winId())); + Nz::WindowHandle windowHandle; +#if defined(NAZARA_PLATFORM_WINDOWS) + windowHandle.type = Nz::WindowBackend::Windows; + windowHandle.windows.window = reinterpret_cast(winId()); +#elif defined(NAZARA_PLATFORM_LINUX) + windowHandle.type = Nz::WindowBackend::X11; + windowHandle.x11.display = nullptr; + windowHandle.x11.window = winId(); +#elif defined(NAZARA_PLATFORM_MACOS) + windowHandle.type = Nz::WindowBackend::Cocoa; + windowHandle.cocoa.window = reinterpret_cast(winId()); +#endif + + Create(windowHandle); } OnShow(); @@ -80,9 +93,9 @@ namespace bw m_updateTimer.stop(); Nz::WindowEvent event; - event.type = Nz::WindowEventType_LostFocus; + event.type = Nz::WindowEventType::LostFocus; - PushEvent(event); + HandleEvent(event); } void NazaraCanvas::OnShow() @@ -90,15 +103,14 @@ namespace bw m_updateTimer.start(); Nz::WindowEvent event; - event.type = Nz::WindowEventType_GainedFocus; + event.type = Nz::WindowEventType::GainedFocus; - PushEvent(event); + HandleEvent(event); } - void NazaraCanvas::OnUpdate(float /*elapsedTime*/) + void NazaraCanvas::OnUpdate(Nz::Time /*elapsedTime*/) { ProcessEvents(); - Display(); } void NazaraCanvas::closeEvent(QCloseEvent* /*event*/) @@ -160,7 +172,7 @@ namespace bw Qt::KeyboardModifiers modifiers = keyEvent->modifiers(); Nz::WindowEvent event; - event.type = Nz::WindowEventType_KeyPressed; + event.type = Nz::WindowEventType::KeyPressed; event.key.alt = modifiers & Qt::AltModifier; event.key.control = modifiers & Qt::ControlModifier; event.key.repeated = keyEvent->isAutoRepeat(); @@ -169,7 +181,7 @@ namespace bw event.key.virtualKey = key.value(); event.key.scancode = Nz::Keyboard::ToScanCode(event.key.virtualKey); - PushEvent(event); + HandleEvent(event); ignoreEvent = true; } @@ -178,11 +190,11 @@ namespace bw if (!u32str.empty()) { Nz::WindowEvent event; - event.type = Nz::WindowEventType_TextEntered; + event.type = Nz::WindowEventType::TextEntered; event.text.character = u32str[0]; event.text.repeated = keyEvent->isAutoRepeat(); - PushEvent(event); + HandleEvent(event); } if (ignoreEvent) @@ -201,7 +213,7 @@ namespace bw Qt::KeyboardModifiers modifiers = keyEvent->modifiers(); Nz::WindowEvent event; - event.type = Nz::WindowEventType_KeyReleased; + event.type = Nz::WindowEventType::KeyReleased; event.key.alt = modifiers & Qt::AltModifier; event.key.control = modifiers & Qt::ControlModifier; event.key.repeated = keyEvent->isAutoRepeat(); @@ -210,7 +222,7 @@ namespace bw event.key.virtualKey = key.value(); event.key.scancode = Nz::Keyboard::ToScanCode(event.key.virtualKey); - PushEvent(event); + HandleEvent(event); return true; } @@ -227,12 +239,12 @@ namespace bw auto pos = mouseButtonEvent->pos(); Nz::WindowEvent event; - event.type = Nz::WindowEventType_MouseButtonPressed; + event.type = Nz::WindowEventType::MouseButtonPressed; event.mouseButton.x = pos.x(); event.mouseButton.y = pos.y(); event.mouseButton.button = button.value(); - PushEvent(event); + HandleEvent(event); return true; } @@ -249,12 +261,12 @@ namespace bw auto pos = mouseButtonEvent->pos(); Nz::WindowEvent event; - event.type = Nz::WindowEventType_MouseButtonReleased; + event.type = Nz::WindowEventType::MouseButtonReleased; event.mouseButton.x = pos.x(); event.mouseButton.y = pos.y(); event.mouseButton.button = button.value(); - PushEvent(event); + HandleEvent(event); return true; } @@ -264,18 +276,18 @@ namespace bw case QEvent::HoverEnter: { Nz::WindowEvent event; - event.type = Nz::WindowEventType_MouseEntered; + event.type = Nz::WindowEventType::MouseEntered; - PushEvent(event); + HandleEvent(event); return true; } case QEvent::HoverLeave: { Nz::WindowEvent event; - event.type = Nz::WindowEventType_MouseLeft; + event.type = Nz::WindowEventType::MouseLeft; - PushEvent(event); + HandleEvent(event); return true; } @@ -286,13 +298,13 @@ namespace bw auto oldPos = hoverEvent->oldPos(); Nz::WindowEvent event; - event.type = Nz::WindowEventType_MouseMoved; + event.type = Nz::WindowEventType::MouseMoved; event.mouseMove.x = newPos.x(); event.mouseMove.y = newPos.y(); event.mouseMove.deltaX = newPos.x() - oldPos.x(); event.mouseMove.deltaY = newPos.y() - oldPos.y(); - PushEvent(event); + HandleEvent(event); return true; } @@ -301,10 +313,10 @@ namespace bw QWheelEvent* wheelEvent = static_cast(e); Nz::WindowEvent event; - event.type = Nz::WindowEventType_MouseWheelMoved; + event.type = Nz::WindowEventType::MouseWheelMoved; event.mouseWheel.delta = wheelEvent->angleDelta().ry() / 120.f; - PushEvent(event); + HandleEvent(event); return true; } diff --git a/src/MapEditor/Widgets/NazaraCanvas.hpp b/src/MapEditor/Widgets/NazaraCanvas.hpp index 2e4f3f05..c3f9b40f 100644 --- a/src/MapEditor/Widgets/NazaraCanvas.hpp +++ b/src/MapEditor/Widgets/NazaraCanvas.hpp @@ -7,20 +7,19 @@ #ifndef BURGWAR_MAPEDITOR_WIDGETS_NAZARACANVAS_HPP #define BURGWAR_MAPEDITOR_WIDGETS_NAZARACANVAS_HPP -#include +#include +#include #include #include namespace bw { - class NazaraCanvas : public QWidget, public Nz::RenderWindow + class NazaraCanvas : public QWidget, public Nz::Window { public: NazaraCanvas(QWidget* parent = nullptr); virtual ~NazaraCanvas(); - Nz::Vector2ui GetSize() const override; - QSize minimumSizeHint() const override; QSize sizeHint() const override; diff --git a/src/MapEditor/Widgets/ScrollCanvas.hpp b/src/MapEditor/Widgets/ScrollCanvas.hpp index df4e0b6d..859330cb 100644 --- a/src/MapEditor/Widgets/ScrollCanvas.hpp +++ b/src/MapEditor/Widgets/ScrollCanvas.hpp @@ -9,7 +9,6 @@ #include #include -#include #include #include diff --git a/src/MapEditor/Widgets/WorldCanvas.cpp b/src/MapEditor/Widgets/WorldCanvas.cpp index 217fc44a..9681f274 100644 --- a/src/MapEditor/Widgets/WorldCanvas.cpp +++ b/src/MapEditor/Widgets/WorldCanvas.cpp @@ -7,17 +7,17 @@ #include #include #include -#include +#include namespace bw { WorldCanvas::WorldCanvas(QWidget* parent) : NazaraCanvas(parent), m_backgroundColor(Nz::Color::Black()), + m_systemGraph(m_world), m_camera(m_world, this, true) { - Ndk::RenderSystem& renderSystem = m_world.AddSystem(); - renderSystem.SetGlobalUp(Nz::Vector3f::Down()); + Nz::RenderSystem& renderSystem = m_systemGraph.AddSystem(); Nz::WindowEventHandler& eventHandler = GetEventHandler(); diff --git a/src/MapEditor/Widgets/WorldCanvas.hpp b/src/MapEditor/Widgets/WorldCanvas.hpp index b0452bd1..f41aa35c 100644 --- a/src/MapEditor/Widgets/WorldCanvas.hpp +++ b/src/MapEditor/Widgets/WorldCanvas.hpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include namespace bw @@ -52,6 +52,7 @@ namespace bw std::optional m_cameraMovement; Nz::Color m_backgroundColor; entt::registry m_world; + Nz::EnttSystemGraph m_systemGraph; Camera m_camera; }; } diff --git a/src/MapTool/main.cpp b/src/MapTool/main.cpp index 63b9727b..2a782689 100644 --- a/src/MapTool/main.cpp +++ b/src/MapTool/main.cpp @@ -111,7 +111,7 @@ int BurgWarMapTool(int argc, char* argv[]) } } } - catch (const cxxopts::OptionException& e) + catch (const cxxopts::exceptions::exception& e) { fmt::print(stderr, "{}\n{}\n", e.what(), options.help()); } diff --git a/src/Server/ServerAppComponent.cpp b/src/Server/ServerAppComponent.cpp index b8b350ef..9c6285f5 100644 --- a/src/Server/ServerAppComponent.cpp +++ b/src/Server/ServerAppComponent.cpp @@ -3,6 +3,7 @@ // For conditions of distribution and use, see copyright notice in LICENSE #include +#include #include namespace bw @@ -14,6 +15,11 @@ namespace bw if (!m_configFile.LoadFromFile("serverconfig.lua")) throw std::runtime_error("failed to load config file"); + Nz::AppFilesystemComponent& appFilesystem = app.GetComponent(); + appFilesystem.Mount("assets", Nz::Utf8Path(m_configFile.GetStringValue("Resources.AssetDirectory"))); + appFilesystem.Mount("mods", Nz::Utf8Path(m_configFile.GetStringValue("Resources.ModDirectory"))); + appFilesystem.Mount("scripts", Nz::Utf8Path(m_configFile.GetStringValue("Resources.ScriptDirectory"))); + LoadMods(); Nz::UInt16 maxPlayerCount = m_configFile.GetIntegerValue("ServerSettings.MaxPlayerCount"); diff --git a/src/Server/main.cpp b/src/Server/main.cpp index 7f3fe5fa..f9d66ac8 100644 --- a/src/Server/main.cpp +++ b/src/Server/main.cpp @@ -2,7 +2,9 @@ // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE +#include #include +#include #include #include #include @@ -11,6 +13,9 @@ int BurgWarServer(int argc, char* argv[]) { Nz::Application app(argc, argv); + app.AddComponent(); + app.AddComponent(); + app.AddComponent(); return app.Run(); diff --git a/xmake-requires.lock b/xmake-requires.lock deleted file mode 100644 index 8fff1a38..00000000 --- a/xmake-requires.lock +++ /dev/null @@ -1,420 +0,0 @@ -{ - __meta__ = { - version = "1.0" - }, - ["linux|x86_64"] = { - ["cmake#31fecfc4"] = { - repo = { - branch = "master", - commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", - url = "https://gitlab.com/tboox/xmake-repo.git" - }, - version = "3.22.1" - }, - ["concurrentqueue#31fecfc4"] = { - branch = "master", - repo = { - branch = "master", - commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", - url = "https://gitlab.com/tboox/xmake-repo.git" - }, - version = "master" - }, - ["cxxopts#31fecfc4"] = { - repo = { - branch = "master", - commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", - url = "https://gitlab.com/tboox/xmake-repo.git" - }, - version = "v2.2.0" - }, - ["fmt#7572102e"] = { - repo = { - branch = "master", - commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", - url = "https://gitlab.com/tboox/xmake-repo.git" - }, - version = "8.1.1" - }, - ["hopscotch-map#31fecfc4"] = { - repo = { - branch = "master", - commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", - url = "https://gitlab.com/tboox/xmake-repo.git" - }, - version = "v2.3.0" - }, - ["libcurl#31fecfc4"] = { - repo = { - branch = "master", - commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", - url = "https://gitlab.com/tboox/xmake-repo.git" - }, - version = "7.82.0" - }, - ["nazaraengine 2021.08.28#31fecfc4"] = { - repo = { - url = "xmake-repo" - }, - version = "2021.08.28" - }, - ["nazaraengine~server 2021.08.28#e1c6474d"] = { - repo = { - url = "xmake-repo" - }, - version = "2021.08.28" - }, - ["nlohmann_json#31fecfc4"] = { - repo = { - branch = "master", - commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", - url = "https://gitlab.com/tboox/xmake-repo.git" - }, - version = "v3.10.5" - }, - ["openssl#31fecfc4"] = { - repo = { - branch = "master", - commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", - url = "https://gitlab.com/tboox/xmake-repo.git" - }, - version = "1.1.1m" - }, - ["sol2 v3.2.1#72267bd5"] = { - repo = { - branch = "master", - commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", - url = "https://gitlab.com/tboox/xmake-repo.git" - }, - version = "v3.2.1" - }, - ["tl_expected#31fecfc4"] = { - repo = { - branch = "master", - commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", - url = "https://gitlab.com/tboox/xmake-repo.git" - }, - version = "v1.0.0" - }, - ["tl_function_ref#31fecfc4"] = { - repo = { - branch = "master", - commit = "ae90f6cdc5d558856976f5d7709e875ea0cd02c4", - url = "https://gitlab.com/tboox/xmake-repo.git" - }, - version = "v1.0.0" - } - }, - ["windows|x64"] = { - ["brotli#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "1.0.9" - }, - ["bzip2#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "1.0.8" - }, - ["chipmunk2d#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "7.0.3" - }, - ["cmake#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "3.24.2" - }, - ["concurrentqueue#31fecfc4"] = { - branch = "master", - repo = { - branch = "master", - commit = "f881bf0478fb7210197d5079522041997ab94f34", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "master" - }, - ["cxxopts#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v3.0.0" - }, - ["dr_wav#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "0.12.19" - }, - ["efsw#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "1.1.0" - }, - ["entt 3.10.1#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v3.10.1" - }, - ["fmt#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "9.1.0" - }, - ["fmt#7572102e"] = { - repo = { - branch = "master", - commit = "8bbde2f876ebb123723243fdb1db7321503df67b", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "9.1.0" - }, - ["freetype#feb50816"] = { - repo = { - branch = "master", - commit = "71a1727013cbaf7a193154a5d2d24f0c6c568140", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "2.12.1" - }, - ["frozen#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "1.1.1" - }, - ["hopscotch-map#31fecfc4"] = { - repo = { - branch = "master", - commit = "f881bf0478fb7210197d5079522041997ab94f34", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v2.3.0" - }, - ["kiwisolver#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "1.4.4" - }, - ["libcurl#31fecfc4"] = { - repo = { - branch = "master", - commit = "8bbde2f876ebb123723243fdb1db7321503df67b", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "7.84.0" - }, - ["libflac#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "1.3.3" - }, - ["libogg#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v1.3.4" - }, - ["libpng#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v1.6.37" - }, - ["libsdl#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "2.24.2" - }, - ["libvorbis#3c9faad2"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "1.3.7" - }, - ["meson#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "0.62.1" - }, - ["minimp3#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "2021.05.29" - }, - ["nazaraengine#6e0ce8a6"] = { - repo = { - url = "xmake-repo" - }, - version = "2022.11.05" - }, - ["nazarautils#31fecfc4"] = { - repo = { - commit = "5727e994c2b90e34bc01773e1d35f147640b818e", - url = "https://github.com/NazaraEngine/xmake-repo" - }, - version = "2022.11.19" - }, - ["newtondynamics3#c806eb3e"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v3.14d" - }, - ["ninja#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "1.11.0" - }, - ["nlohmann_json#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v3.11.2" - }, - ["nzsl#97361567"] = { - repo = { - commit = "5727e994c2b90e34bc01773e1d35f147640b818e", - url = "https://github.com/NazaraEngine/xmake-repo" - }, - version = "2022.11.19" - }, - ["openal-soft#67114504"] = { - repo = { - branch = "master", - commit = "d52551c039b87921184893a4097eb1572455b683", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "1.22.2" - }, - ["ordered_map#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v1.0.0" - }, - ["pkgconf#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "1.9.3" - }, - ["python 3.x#31fecfc4"] = { - repo = { - branch = "master", - commit = "71a1727013cbaf7a193154a5d2d24f0c6c568140", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "3.10.6" - }, - ["sol2 v3.2.1#72267bd5"] = { - repo = { - branch = "master", - commit = "f881bf0478fb7210197d5079522041997ab94f34", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v3.2.1" - }, - ["stackwalker master#31fecfc4"] = { - branch = "master", - repo = { - branch = "master", - commit = "f881bf0478fb7210197d5079522041997ab94f34", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "master" - }, - ["stb#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "2021.09.10" - }, - ["tl_expected#31fecfc4"] = { - repo = { - branch = "master", - commit = "f881bf0478fb7210197d5079522041997ab94f34", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v1.0.0" - }, - ["tl_function_ref#31fecfc4"] = { - repo = { - branch = "master", - commit = "f881bf0478fb7210197d5079522041997ab94f34", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v1.0.0" - }, - ["zlib#31fecfc4"] = { - repo = { - branch = "master", - commit = "b099c3cb052586bf8201ac509cdba4d02ee6b3eb", - url = "https://github.com/xmake-io/xmake-repo.git" - }, - version = "v1.2.12" - } - } -} \ No newline at end of file diff --git a/xmake.lua b/xmake.lua index 3298e78f..7332a8d5 100644 --- a/xmake.lua +++ b/xmake.lua @@ -3,17 +3,17 @@ set_xmakever("2.5.6") option("build_mapeditor", { default = true, showmenu = true, description = "Should the map editor be compiled as part of the project? (requires Qt)" }) -set_policy("package.requires_lock", true) +--set_policy("package.requires_lock", true) set_project("BurgWar") set_version("0.2.0") add_repositories("nazara-engine-repo https://github.com/NazaraEngine/xmake-repo") -add_requires("cxxopts", "concurrentqueue", "entt 3.11.1", "hopscotch-map", "nlohmann_json", "tl_expected", "tl_function_ref") +add_requires("cxxopts", "concurrentqueue", "hopscotch-map", "nlohmann_json", "tl_expected", "tl_function_ref") add_requires("fmt", { configs = { header_only = false, pic = true } }) add_requires("libcurl", { optional = true }) -add_requires("nazaraengine", { configs = { debug = is_mode("debug", "asan"), shared = true } }) +add_requires("nazaraengine", { configs = { debug = is_mode("debug", "asan"), shared = true, entt = true, with_symbols = is_mode("debug", "releasedbg") } }) add_requires("sol2 v3.2.1", { verify = false, configs = { includes_lua = false } }) if is_plat("windows") then @@ -21,7 +21,7 @@ if is_plat("windows") then end add_requireconfs("fmt", "stackwalker", { debug = is_mode("debug", "asan") }) -add_requireconfs("libcurl") +add_requireconfs("libcurl", { configs = { shared = true }}) set_allowedmodes("asan", "debug", "releasedbg") set_allowedplats("windows", "mingw", "linux", "macosx") @@ -104,8 +104,8 @@ target("CoreLib") add_headerfiles("include/(CoreLib/**.hpp)", "include/(CoreLib/**.inl)") add_headerfiles("src/CoreLib/**.hpp", "src/CoreLib/**.inl") add_files("src/CoreLib/**.cpp") - add_packages("concurrentqueue", "entt", "fmt", "hopscotch-map", "nlohmann_json", "sol2", "tl_expected", "tl_function_ref", { public = true }) - add_packages("nazaraengine", { components = { "core", "network", "physics2d", "utility" }, public = true }) + add_packages("concurrentqueue", "fmt", "hopscotch-map", "nlohmann_json", "sol2", "tl_expected", "tl_function_ref", { public = true }) + add_packages("nazaraengine", { components = { "core", "network", "chipmunkphysics2d", "utility" }, public = true }) add_packages("libcurl", { public = true, links = {} }) if is_plat("windows") then @@ -182,7 +182,7 @@ target("ClientLib") add_headerfiles("include/(ClientLib/**.hpp)", "include/(ClientLib/**.inl)") add_headerfiles("src/ClientLib/**.hpp", "src/ClientLib/**.inl") add_files("src/ClientLib/**.cpp") - add_packages("nazaraengine", { components = { "graphics", "platform", "renderer", "widgets" }, public = true }) + add_packages("nazaraengine", { components = { "audio", "graphics", "platform", "renderer", "widgets" }, public = true }) target("Main") set_group("Common") From df4b59279a46d4c3b95b3e29524c4f2a3dc172e0 Mon Sep 17 00:00:00 2001 From: SirLynix Date: Tue, 26 Dec 2023 12:39:19 +0100 Subject: [PATCH 12/17] Fixes for latest Nazara version (and C++20) --- include/ClientLib/Camera.hpp | 4 +- include/ClientLib/Chatbox.hpp | 4 +- include/ClientLib/ClientConsole.hpp | 2 +- include/ClientLib/ClientMatch.hpp | 4 +- include/ClientLib/Console.hpp | 4 +- include/ClientLib/EscapeMenu.hpp | 1 - include/ClientLib/LayerVisualEntity.hpp | 12 +-- include/ClientLib/LayerVisualEntity.inl | 2 +- include/ClientLib/Scripting/Sprite.hpp | 12 +-- include/ClientLib/Scripting/Sprite.inl | 14 +-- include/ClientLib/Scripting/Text.hpp | 8 +- include/ClientLib/Scripting/Text.inl | 16 +-- include/ClientLib/Scripting/Tilemap.hpp | 8 +- include/ClientLib/Scripting/Tilemap.inl | 14 +-- include/ClientLib/VisualEntity.hpp | 10 +- include/ClientLib/VisualEntity.inl | 21 ++-- include/CoreLib/AssetStore.inl | 2 +- include/CoreLib/LogSystem/Logger.hpp | 3 +- include/CoreLib/LogSystem/Logger.inl | 4 +- include/CoreLib/LogSystem/LoggerProxy.hpp | 2 +- include/CoreLib/LogSystem/LoggerProxy.inl | 4 +- include/CoreLib/Map.hpp | 8 +- include/CoreLib/Scripting/NetworkPacket.inl | 4 +- include/CoreLib/Scripting/ScriptStore.inl | 18 ++-- .../CoreLib/Scripting/ScriptingContext.inl | 2 +- include/CoreLib/Scripting/ScriptingUtils.inl | 2 + scripts/entities/burger/cl_init.lua | 2 + scripts/entities/burger/shared.lua | 4 + scripts/entities/tilemap.lua | 2 +- scripts/gamemodes/base/cl_camera.lua | 2 + src/Client/ClientAppComponent.cpp | 7 +- src/Client/States/AbstractState.cpp | 3 +- src/Client/States/AbstractState.hpp | 1 + src/Client/States/BackgroundState.cpp | 6 +- src/Client/States/Game/ConnectedState.cpp | 4 +- src/Client/States/Game/GameState.cpp | 2 +- .../States/Game/ResourceDownloadState.cpp | 8 +- src/Client/States/ServerListState.cpp | 18 ++-- src/Client/States/StateData.hpp | 3 + src/Client/main.cpp | 5 +- src/ClientLib/Camera.cpp | 3 +- src/ClientLib/Chatbox.cpp | 8 +- src/ClientLib/ClientConsole.cpp | 4 +- src/ClientLib/ClientLayer.cpp | 2 +- src/ClientLib/ClientLayerEntity.cpp | 23 +++-- src/ClientLib/ClientMatch.cpp | 36 +++---- src/ClientLib/Console.cpp | 4 +- src/ClientLib/HttpDownloadManager.cpp | 8 +- src/ClientLib/LayerVisualEntity.cpp | 61 ++++++------ src/ClientLib/PacketDownloadManager.cpp | 6 +- .../Scripting/ClientElementLibrary.cpp | 24 +++-- .../Scripting/ClientEntityLibrary.cpp | 19 ++-- src/ClientLib/Scripting/ClientGamemode.cpp | 4 +- .../Scripting/ClientScriptingLibrary.cpp | 2 +- src/ClientLib/Scripting/ClientWeaponStore.cpp | 5 +- src/ClientLib/Scripting/Sprite.cpp | 10 +- src/ClientLib/Scripting/Text.cpp | 10 +- src/ClientLib/Scripting/Tilemap.cpp | 6 +- src/ClientLib/VisualEntity.cpp | 40 +++----- src/CoreLib/ConfigFile.cpp | 4 +- src/CoreLib/Map.cpp | 97 ++++++++++++++++--- src/CoreLib/MasterServerEntry.cpp | 8 +- src/CoreLib/Match.cpp | 18 ++-- src/CoreLib/MatchClientSession.cpp | 10 +- src/CoreLib/Mod.cpp | 14 +-- src/CoreLib/Player.cpp | 8 +- .../Scripting/AbstractScriptingLibrary.cpp | 2 +- src/CoreLib/Scripting/ScriptingContext.cpp | 36 +++---- src/CoreLib/Scripting/ServerEntityLibrary.cpp | 17 +++- src/CoreLib/Scripting/ServerGamemode.cpp | 6 +- .../Scripting/ServerScriptingLibrary.cpp | 4 +- src/MapEditor/Scripting/EditorGamemode.cpp | 4 +- src/MapEditor/Widgets/EditorWindow.cpp | 20 ++-- src/MapEditor/Widgets/EditorWindowPrefabs.cpp | 4 +- src/MapTool/main.cpp | 7 +- xmake.lua | 2 +- 76 files changed, 434 insertions(+), 354 deletions(-) diff --git a/include/ClientLib/Camera.hpp b/include/ClientLib/Camera.hpp index 412f57e6..9998f000 100644 --- a/include/ClientLib/Camera.hpp +++ b/include/ClientLib/Camera.hpp @@ -9,10 +9,10 @@ #include #include +#include #include #include #include -#include #include namespace Nz @@ -29,7 +29,7 @@ namespace bw class BURGWAR_CLIENTLIB_API Camera : public Nz::HandledObject { public: - Camera(Nz::EnttWorld& world, Nz::RenderTarget* renderTarget, bool perspective); + Camera(Nz::EnttWorld& world, std::shared_ptr renderTarget, bool perspective); Camera(const Camera&) = delete; Camera(Camera&&) = delete; ~Camera() = default; diff --git a/include/ClientLib/Chatbox.hpp b/include/ClientLib/Chatbox.hpp index 8cb616da..e2e634fd 100644 --- a/include/ClientLib/Chatbox.hpp +++ b/include/ClientLib/Chatbox.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include @@ -36,7 +36,7 @@ namespace bw using Item = std::variant; - Chatbox(const Logger& logger, Nz::RenderTarget* rt, Nz::Canvas* canvas); + Chatbox(const Logger& logger, const Nz::RenderTarget& renderTarget, Nz::Canvas* canvas); Chatbox(const Chatbox&) = delete; Chatbox(Chatbox&&) = delete; ~Chatbox(); diff --git a/include/ClientLib/ClientConsole.hpp b/include/ClientLib/ClientConsole.hpp index 9b8a5f00..4fd278bc 100644 --- a/include/ClientLib/ClientConsole.hpp +++ b/include/ClientLib/ClientConsole.hpp @@ -20,7 +20,7 @@ namespace bw class BURGWAR_CLIENTLIB_API ClientConsole : public Console { public: - ClientConsole(const Logger& logger, Nz::RenderTarget* window, Nz::Canvas* canvas, std::shared_ptr scriptingLibrary, const std::shared_ptr& scriptDir); + ClientConsole(const Logger& logger, const Nz::RenderTarget& renderTarget, Nz::Canvas* canvas, std::shared_ptr scriptingLibrary, const std::shared_ptr& scriptDir); ClientConsole(const ClientConsole&) = delete; ClientConsole(ClientConsole&&) = delete; ~ClientConsole() = default; diff --git a/include/ClientLib/ClientMatch.hpp b/include/ClientLib/ClientMatch.hpp index a5cb8c3d..8205c3fa 100644 --- a/include/ClientLib/ClientMatch.hpp +++ b/include/ClientLib/ClientMatch.hpp @@ -55,7 +55,7 @@ namespace bw friend ClientSession; public: - ClientMatch(ClientEditorAppComponent& burgApp, Nz::Window* window, Nz::RenderTarget* renderTarget, Nz::Canvas* canvas, Nz::EnttWorld& renderWorld, ClientSession& session, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData); + ClientMatch(ClientEditorAppComponent& burgApp, Nz::Window* window, std::shared_ptr renderTarget, Nz::Canvas* canvas, Nz::EnttWorld& renderWorld, ClientSession& session, const Packets::AuthSuccess& authSuccess, const Packets::MatchData& matchData); ClientMatch(const ClientMatch&) = delete; ClientMatch(ClientMatch&&) = delete; ~ClientMatch(); @@ -268,6 +268,7 @@ namespace bw typename Nz::Signal::ConnectionGuard m_nicknameUpdateSlot; + std::shared_ptr m_renderTarget; std::optional m_assetStore; std::optional m_entityStore; std::optional m_weaponStore; @@ -289,7 +290,6 @@ namespace bw entt::handle m_currentLayer; EntityId m_freeClientId; Nz::EnttWorld& m_renderWorld; - Nz::RenderTarget* m_renderTarget; Nz::Window* m_window; Nz::UInt16 m_activeLayerIndex; tsl::hopscotch_map m_entitiesByUniqueId; diff --git a/include/ClientLib/Console.hpp b/include/ClientLib/Console.hpp index d6718dd4..cc4a9ab4 100644 --- a/include/ClientLib/Console.hpp +++ b/include/ClientLib/Console.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include @@ -21,7 +21,7 @@ namespace bw public: using ExecuteCallback = std::function; - Console(Nz::RenderTarget* window, Nz::Canvas* canvas); + Console(const Nz::RenderTarget& window, Nz::Canvas* canvas); Console(const Console&) = delete; Console(Console&&) = delete; ~Console(); diff --git a/include/ClientLib/EscapeMenu.hpp b/include/ClientLib/EscapeMenu.hpp index 0b461028..8ca71c1a 100644 --- a/include/ClientLib/EscapeMenu.hpp +++ b/include/ClientLib/EscapeMenu.hpp @@ -9,7 +9,6 @@ #include #include -#include #include #include #include diff --git a/include/ClientLib/LayerVisualEntity.hpp b/include/ClientLib/LayerVisualEntity.hpp index c732b37a..4c2d39a5 100644 --- a/include/ClientLib/LayerVisualEntity.hpp +++ b/include/ClientLib/LayerVisualEntity.hpp @@ -37,8 +37,8 @@ namespace bw LayerVisualEntity(LayerVisualEntity&& entity) noexcept; virtual ~LayerVisualEntity(); - void AttachHoveringRenderable(std::shared_ptr renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder, float hoveringHeight); - void AttachRenderable(std::shared_ptr renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder); + void AttachHoveringRenderable(std::shared_ptr renderable, const Nz::Vector3f& offset, const Nz::Quaternionf& rotation, float hoveringHeight); + void AttachRenderable(std::shared_ptr renderable, const Nz::Vector3f& offset, const Nz::Quaternionf& rotation); void DetachHoveringRenderable(const std::shared_ptr& renderable); void DetachRenderable(const std::shared_ptr& renderable); @@ -59,8 +59,8 @@ namespace bw void SyncVisuals(); void UpdateHoveringRenderableHoveringHeight(const std::shared_ptr& renderable, float newHoveringHeight); - void UpdateHoveringRenderableMatrix(const std::shared_ptr& renderable, const Nz::Matrix4f& offsetMatrix); - void UpdateRenderableMatrix(const std::shared_ptr& renderable, const Nz::Matrix4f& offsetMatrix); + void UpdateHoveringRenderableTransform(const std::shared_ptr& renderable, const Nz::Vector3f& offset, const Nz::Quaternionf& rotation); + void UpdateRenderableTransform(const std::shared_ptr& renderable, const Nz::Vector3f& offset, const Nz::Quaternionf& rotation); void UpdateScale(float newScale); void UpdateState(const Nz::Vector2f& position, const Nz::RadianAnglef& rotation); void UpdateState(const Nz::Vector2f& position, const Nz::RadianAnglef& rotation, const Nz::Vector2f& linearVel, const Nz::RadianAnglef& angularVel); @@ -76,8 +76,8 @@ namespace bw struct RenderableData { std::shared_ptr renderable; - Nz::Matrix4f offsetMatrix; - int renderOrder; + Nz::Quaternionf rotation; + Nz::Vector3f offset; }; struct HoveringRenderableData diff --git a/include/ClientLib/LayerVisualEntity.inl b/include/ClientLib/LayerVisualEntity.inl index 595536ea..1759556e 100644 --- a/include/ClientLib/LayerVisualEntity.inl +++ b/include/ClientLib/LayerVisualEntity.inl @@ -25,7 +25,7 @@ namespace bw void LayerVisualEntity::ForEachRenderable(Func&& func) const { for (const auto& renderableData : m_attachedRenderables) - func(std::as_const(renderableData.renderable), std::as_const(renderableData.offsetMatrix), std::as_const(renderableData.renderOrder)); + func(std::as_const(renderableData.renderable), std::as_const(renderableData.offset), std::as_const(renderableData.rotation)); } inline entt::handle LayerVisualEntity::GetEntity() const diff --git a/include/ClientLib/Scripting/Sprite.hpp b/include/ClientLib/Scripting/Sprite.hpp index e5a3a9bd..f9dd6112 100644 --- a/include/ClientLib/Scripting/Sprite.hpp +++ b/include/ClientLib/Scripting/Sprite.hpp @@ -19,7 +19,7 @@ namespace bw class BURGWAR_CLIENTLIB_API Sprite { public: - inline Sprite(LayerVisualEntityHandle visualEntity, std::shared_ptr sprite, const Nz::Matrix4f& transformMatrix, int renderOrder); + inline Sprite(LayerVisualEntityHandle visualEntity, std::shared_ptr sprite, const Nz::Vector2f& offset, const Nz::DegreeAnglef& rotation); Sprite(const Sprite&) = delete; Sprite(Sprite&&) noexcept = default; ~Sprite() = default; @@ -32,8 +32,8 @@ namespace bw inline bool IsValid() const; inline bool IsVisible() const; - void SetColor(Nz::Color color); - void SetCornerColor(const std::string_view& corner, Nz::Color cornerColor); + void SetColor(const Nz::Color& color); + void SetCornerColor(const std::string_view& corner, const Nz::Color& cornerColor); void SetCornerColors(const sol::table& cornerTable); inline void SetOffset(const Nz::Vector2f& newOffset); inline void SetRotation(const Nz::DegreeAnglef& newRotation); @@ -44,12 +44,12 @@ namespace bw Sprite& operator=(Sprite&&) noexcept = default; private: - void UpdateTransformMatrix(); + void UpdateTransform(); LayerVisualEntityHandle m_visualEntity; - Nz::Matrix4f m_transformMatrix; + Nz::DegreeAnglef m_rotation; + Nz::Vector2f m_offset; std::shared_ptr m_sprite; - int m_renderOrder; bool m_isVisible; }; } diff --git a/include/ClientLib/Scripting/Sprite.inl b/include/ClientLib/Scripting/Sprite.inl index 1028029e..88bb666c 100644 --- a/include/ClientLib/Scripting/Sprite.inl +++ b/include/ClientLib/Scripting/Sprite.inl @@ -6,11 +6,11 @@ namespace bw { - inline Sprite::Sprite(LayerVisualEntityHandle visualEntity, std::shared_ptr sprite, const Nz::Matrix4f& transformMatrix, int renderOrder) : + inline Sprite::Sprite(LayerVisualEntityHandle visualEntity, std::shared_ptr sprite, const Nz::Vector2f& offset, const Nz::DegreeAnglef& rotation) : m_visualEntity(std::move(visualEntity)), - m_transformMatrix(transformMatrix), + m_rotation(rotation), + m_offset(offset), m_sprite(std::move(sprite)), - m_renderOrder(renderOrder), m_isVisible(false) { } @@ -42,16 +42,16 @@ namespace bw inline void Sprite::SetOffset(const Nz::Vector2f& newOffset) { - m_transformMatrix.SetTranslation(newOffset); + m_offset = newOffset; - UpdateTransformMatrix(); + UpdateTransform(); } inline void Sprite::SetRotation(const Nz::DegreeAnglef& newRotation) { - m_transformMatrix.SetRotation(newRotation); + m_rotation = newRotation; - UpdateTransformMatrix(); + UpdateTransform(); } inline void Sprite::SetSize(const Nz::Vector2f& newSize) diff --git a/include/ClientLib/Scripting/Text.hpp b/include/ClientLib/Scripting/Text.hpp index 4cdfff14..6ce8a023 100644 --- a/include/ClientLib/Scripting/Text.hpp +++ b/include/ClientLib/Scripting/Text.hpp @@ -20,7 +20,7 @@ namespace bw class Text { public: - inline Text(LayerVisualEntityHandle visualEntity, Nz::SimpleTextDrawer drawer, std::shared_ptr textSprite, const Nz::Matrix4f& transformMatrix, int renderOrder, bool isHovering); + inline Text(LayerVisualEntityHandle visualEntity, Nz::SimpleTextDrawer drawer, std::shared_ptr textSprite, const Nz::Vector2f& offset, const Nz::DegreeAnglef& rotation, bool isHovering); Text(const Text&) = delete; Text(Text&&) = default; ~Text() = default; @@ -45,16 +45,16 @@ namespace bw private: void UpdateTextSprite(); - void UpdateTransformMatrix(); + void UpdateTransform(); LayerVisualEntityHandle m_visualEntity; - Nz::Matrix4f m_transformMatrix; + Nz::DegreeAnglef m_rotation; + Nz::Vector2f m_offset; Nz::SimpleTextDrawer m_drawer; std::shared_ptr m_textSprite; bool m_isHovering; bool m_isVisible; float m_hoveringHeight; - int m_renderOrder; }; } diff --git a/include/ClientLib/Scripting/Text.inl b/include/ClientLib/Scripting/Text.inl index 0840a36e..9473989d 100644 --- a/include/ClientLib/Scripting/Text.inl +++ b/include/ClientLib/Scripting/Text.inl @@ -6,15 +6,15 @@ namespace bw { - inline Text::Text(LayerVisualEntityHandle visualEntity, Nz::SimpleTextDrawer drawer, std::shared_ptr textSprite, const Nz::Matrix4f& transformMatrix, int renderOrder, bool isHovering) : + inline Text::Text(LayerVisualEntityHandle visualEntity, Nz::SimpleTextDrawer drawer, std::shared_ptr textSprite, const Nz::Vector2f& offset, const Nz::DegreeAnglef& rotation, bool isHovering) : m_visualEntity(std::move(visualEntity)), - m_transformMatrix(transformMatrix), + m_rotation(rotation), + m_offset(offset), m_drawer(std::move(drawer)), m_textSprite(std::move(textSprite)), m_isHovering(isHovering), m_isVisible(false), - m_hoveringHeight(0.f), - m_renderOrder(renderOrder) + m_hoveringHeight(0.f) { } @@ -46,16 +46,16 @@ namespace bw inline void Text::SetOffset(const Nz::Vector2f& newOffset) { - m_transformMatrix.SetTranslation(newOffset); + m_offset = newOffset; - UpdateTransformMatrix(); + UpdateTransform(); } inline void Text::SetRotation(const Nz::DegreeAnglef& newRotation) { - m_transformMatrix.SetRotation(newRotation); + m_rotation = newRotation; - UpdateTransformMatrix(); + UpdateTransform(); } inline void Text::SetText(const std::string& text) diff --git a/include/ClientLib/Scripting/Tilemap.hpp b/include/ClientLib/Scripting/Tilemap.hpp index f35d20f1..b6178728 100644 --- a/include/ClientLib/Scripting/Tilemap.hpp +++ b/include/ClientLib/Scripting/Tilemap.hpp @@ -20,7 +20,7 @@ namespace bw class BURGWAR_CLIENTLIB_API Tilemap { public: - inline Tilemap(LayerVisualEntityHandle visualEntity, std::shared_ptr tilemap, const Nz::Matrix4f& transformMatrix, int renderOrder); + inline Tilemap(LayerVisualEntityHandle visualEntity, std::shared_ptr tilemap, const Nz::Vector2f& offset, const Nz::DegreeAnglef& rotation); Tilemap(const Tilemap&) = delete; Tilemap(Tilemap&&) noexcept = default; ~Tilemap() = default; @@ -43,12 +43,12 @@ namespace bw Tilemap& operator=(Tilemap&&) noexcept = default; private: - void UpdateTransformMatrix(); + void UpdateTransform(); LayerVisualEntityHandle m_visualEntity; - Nz::Matrix4f m_transformMatrix; + Nz::DegreeAnglef m_rotation; + Nz::Vector2f m_offset; std::shared_ptr m_tilemap; - int m_renderOrder; bool m_isVisible; }; } diff --git a/include/ClientLib/Scripting/Tilemap.inl b/include/ClientLib/Scripting/Tilemap.inl index d217573a..384ef144 100644 --- a/include/ClientLib/Scripting/Tilemap.inl +++ b/include/ClientLib/Scripting/Tilemap.inl @@ -6,11 +6,11 @@ namespace bw { - inline Tilemap::Tilemap(LayerVisualEntityHandle visualEntity, std::shared_ptr tilemap, const Nz::Matrix4f& transformMatrix, int renderOrder) : + inline Tilemap::Tilemap(LayerVisualEntityHandle visualEntity, std::shared_ptr tilemap, const Nz::Vector2f& offset, const Nz::DegreeAnglef& rotation) : m_visualEntity(std::move(visualEntity)), - m_transformMatrix(transformMatrix), + m_rotation(rotation), + m_offset(offset), m_tilemap(std::move(tilemap)), - m_renderOrder(renderOrder), m_isVisible(false) { } @@ -47,15 +47,15 @@ namespace bw inline void Tilemap::SetOffset(const Nz::Vector2f& newOffset) { - m_transformMatrix.SetTranslation(newOffset); + m_offset = newOffset; - UpdateTransformMatrix(); + UpdateTransform(); } inline void Tilemap::SetRotation(const Nz::DegreeAnglef& newRotation) { - m_transformMatrix.SetRotation(newRotation); + m_rotation = newRotation; - UpdateTransformMatrix(); + UpdateTransform(); } } diff --git a/include/ClientLib/VisualEntity.hpp b/include/ClientLib/VisualEntity.hpp index 916865c4..a517cbac 100644 --- a/include/ClientLib/VisualEntity.hpp +++ b/include/ClientLib/VisualEntity.hpp @@ -44,19 +44,17 @@ namespace bw VisualEntity& operator=(VisualEntity&& entity) = delete; private: - void AttachHoveringRenderable(std::shared_ptr renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder, float hoverOffset); - void AttachRenderable(std::shared_ptr renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder); + void AttachHoveringRenderable(std::shared_ptr renderable, const Nz::Vector3f& offset, const Nz::Quaternionf& rotation, float hoverOffset); + void AttachRenderable(std::shared_ptr renderable, const Nz::Vector3f& offset, const Nz::Quaternionf& rotation); void DetachHoveringRenderable(const std::shared_ptr& renderable); void DetachRenderable(const std::shared_ptr& renderable); inline void Enable(bool enable); void UpdateHoveringRenderableHoveringHeight(const std::shared_ptr& renderable, float newHoveringHeight); - void UpdateHoveringRenderableMatrix(const std::shared_ptr& renderable, const Nz::Matrix4f& offsetMatrix); - void UpdateHoveringRenderableRenderOrder(const std::shared_ptr& renderable, int renderOrder); + void UpdateHoveringRenderableTransform(const std::shared_ptr& renderable, const Nz::Vector3f& offset, const Nz::Quaternionf& rotation); - void UpdateRenderableMatrix(const std::shared_ptr& renderable, const Nz::Matrix4f& offsetMatrix); - void UpdateRenderableRenderOrder(const std::shared_ptr& renderable, int renderOrder); + void UpdateRenderableTransform(const std::shared_ptr& renderable, const Nz::Vector3f& offset, const Nz::Quaternionf& rotation); struct HoveringRenderable { diff --git a/include/ClientLib/VisualEntity.inl b/include/ClientLib/VisualEntity.inl index 33f46dbd..27d603c1 100644 --- a/include/ClientLib/VisualEntity.inl +++ b/include/ClientLib/VisualEntity.inl @@ -14,14 +14,19 @@ namespace bw inline void VisualEntity::Enable(bool enable) { - if (enable) - m_entity->remove(); - else - m_entity->emplace_or_replace(); - // TODO - /* + auto EnableEntity = [enable](const entt::handle& entity) + { + if (enable) + entity.remove(); + else + entity.emplace_or_replace(); + }; + + EnableEntity(m_entity); + for (auto& renderable : m_renderables) + EnableEntity(renderable.entity); + for (auto& hoveringRenderable : m_hoveringRenderables) - hoveringRenderable.entity->Enable(enable); - */ + EnableEntity(hoveringRenderable.entity); } } diff --git a/include/CoreLib/AssetStore.inl b/include/CoreLib/AssetStore.inl index 6625bf9b..f3deaad5 100644 --- a/include/CoreLib/AssetStore.inl +++ b/include/CoreLib/AssetStore.inl @@ -41,7 +41,7 @@ namespace bw if constexpr (std::is_same_v) { - bwLog(m_logger, LogLevel::Info, "Loading asset from {}", arg.stream->GetPath().generic_u8string()); + bwLog(m_logger, LogLevel::Info, "Loading asset from {}", arg.stream->GetPath()); return (resource = ResourceType::LoadFromStream(*arg.stream, params)) != nullptr; } else if constexpr (std::is_base_of_v) diff --git a/include/CoreLib/LogSystem/Logger.hpp b/include/CoreLib/LogSystem/Logger.hpp index c191e2c5..5ceb78d5 100644 --- a/include/CoreLib/LogSystem/Logger.hpp +++ b/include/CoreLib/LogSystem/Logger.hpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -44,7 +45,7 @@ namespace bw Logger(Logger&&) noexcept = default; ~Logger() = default; - template void LogFormat(const LogContext& context, Args&& ... args) const; + template void LogFormat(const LogContext& context, fmt::format_string fmt, Args&& ... args) const; void Log(const LogContext& context, std::string content) const override; void LogRaw(const LogContext& context, std::string_view content) const override; diff --git a/include/CoreLib/LogSystem/Logger.inl b/include/CoreLib/LogSystem/Logger.inl index 7c81891b..c7f7020d 100644 --- a/include/CoreLib/LogSystem/Logger.inl +++ b/include/CoreLib/LogSystem/Logger.inl @@ -22,9 +22,9 @@ namespace bw } template - void Logger::LogFormat(const LogContext& context, Args&&... args) const + void Logger::LogFormat(const LogContext& context, fmt::format_string fmt, Args&& ... args) const { - Log(context, fmt::format(std::forward(args)...)); + Log(context, fmt::format(fmt, std::forward(args)...)); } template diff --git a/include/CoreLib/LogSystem/LoggerProxy.hpp b/include/CoreLib/LogSystem/LoggerProxy.hpp index 1c5e4268..2e882e0a 100644 --- a/include/CoreLib/LogSystem/LoggerProxy.hpp +++ b/include/CoreLib/LogSystem/LoggerProxy.hpp @@ -22,7 +22,7 @@ namespace bw LoggerProxy(LoggerProxy&&) noexcept = default; ~LoggerProxy() = default; - template void LogFormat(const LogContext& context, Args&& ... args) const; + template void LogFormat(const LogContext& context, fmt::format_string fmt, Args&& ... args) const; void Log(const LogContext& context, std::string content) const override; void LogRaw(const LogContext& context, std::string_view content) const override; diff --git a/include/CoreLib/LogSystem/LoggerProxy.inl b/include/CoreLib/LogSystem/LoggerProxy.inl index 53a907ed..8fa645a2 100644 --- a/include/CoreLib/LogSystem/LoggerProxy.inl +++ b/include/CoreLib/LogSystem/LoggerProxy.inl @@ -14,9 +14,9 @@ namespace bw } template - void LoggerProxy::LogFormat(const LogContext& context, Args&&... args) const + void LoggerProxy::LogFormat(const LogContext& context, fmt::format_string fmt, Args&&... args) const { - Log(context, fmt::format(std::forward(args)...)); + Log(context, fmt::format(fmt, std::forward(args)...)); } inline LogContextPtr LoggerProxy::PushContext() const diff --git a/include/CoreLib/Map.hpp b/include/CoreLib/Map.hpp index aec01114..b9a639b4 100644 --- a/include/CoreLib/Map.hpp +++ b/include/CoreLib/Map.hpp @@ -141,16 +141,22 @@ namespace bw static nlohmann::json Serialize(const Map& map); static nlohmann::json SerializeEntity(const Entity& entity); static Map Unserialize(const nlohmann::json& mapInfo); - static Entity UnserializeEntity(const nlohmann::json& entityInfo); + static Entity UnserializeEntity(const nlohmann::json& entityInfo, Nz::UInt16 fileVersion); private: bool CheckEntityIndices() const; void LoadFromBinaryInternal(const std::filesystem::path& mapFile); void LoadFromDirectoryInternal(const std::filesystem::path& mapFolder); + void HandleVersionUpdate(Nz::UInt16 fileVersion); + void HandleVersionUpdate(Asset& asset, Nz::UInt16 fileVersion); + void HandleVersionUpdate(Entity& entity, Nz::UInt16 fileVersion); + void HandleVersionUpdate(Layer& layer, Nz::UInt16 fileVersion); + void HandleVersionUpdate(Script& script, Nz::UInt16 fileVersion); inline void RegisterEntity(EntityId uniqueId, LayerIndex layerIndex, std::size_t entityIndex); void Sanitize(); inline void UnregisterEntity(EntityId uniqueId); + std::vector m_assets; std::vector m_layers; std::vector