diff options
Diffstat (limited to 'src')
76 files changed, 677 insertions, 710 deletions
diff --git a/src/crepe/Asset.h b/src/crepe/Asset.h new file mode 100644 index 0000000..9051c5e --- /dev/null +++ b/src/crepe/Asset.h @@ -0,0 +1,41 @@ +#pragma once + +#include <fstream> +#include <iostream> +#include <string> + +namespace crepe { + +/** + * \brief Asset location helper + * + * This class is used to locate and canonicalize paths to game asset files, and should *always* + * be used when retrieving files from disk. + */ +class Asset { +public: + /** + * \param src Unique identifier to asset + */ + Asset(const std::string & src); + +public: + /** + * \brief Get an input stream to the contents of this asset + * \return Input stream with file contents + */ + std::istream & get_stream(); + /** + * \brief Get the canonical path to this asset + * \return Canonical path to this asset + */ + const std::string & get_canonical() const; + +private: + //! Canonical path to asset + const std::string src; + //! File handle (stream) + std::ifstream file; +}; + +} // namespace crepe diff --git a/src/crepe/CMakeLists.txt b/src/crepe/CMakeLists.txt index d72d4a0..df15b8f 100644 --- a/src/crepe/CMakeLists.txt +++ b/src/crepe/CMakeLists.txt @@ -3,7 +3,6 @@ target_sources(crepe PUBLIC ComponentManager.cpp Component.cpp Collider.cpp - Exception.cpp Resource.cpp ) @@ -14,8 +13,6 @@ target_sources(crepe PUBLIC FILE_SET HEADERS FILES Collider.h ValueBroker.h ValueBroker.hpp - Exception.h - Exception.hpp Resource.h ) diff --git a/src/crepe/Collider.cpp b/src/crepe/Collider.cpp index 113ba61..bbec488 100644 --- a/src/crepe/Collider.cpp +++ b/src/crepe/Collider.cpp @@ -1,3 +1,5 @@ #include "Collider.h" using namespace crepe; + +Collider::Collider(game_object_id_t id) : Component(id) {} diff --git a/src/crepe/Collider.h b/src/crepe/Collider.h index a1e9095..827f83d 100644 --- a/src/crepe/Collider.h +++ b/src/crepe/Collider.h @@ -6,7 +6,7 @@ namespace crepe { class Collider : public Component { public: - using Component::Component; + Collider(game_object_id_t id); int size; }; diff --git a/src/crepe/Component.h b/src/crepe/Component.h index 7734335..2e4ef7d 100644 --- a/src/crepe/Component.h +++ b/src/crepe/Component.h @@ -9,8 +9,8 @@ class ComponentManager; /** * \brief Base class for all components * - * This class is the base class for all components. It provides a common - * interface for all components. + * This class is the base class for all components. It provides a common interface for all + * components. */ class Component { public: @@ -32,12 +32,15 @@ protected: //! Only ComponentManager can create components friend class ComponentManager; +public: + virtual ~Component() = default; + +public: /** * \brief Get the maximum number of instances for this component * - * This method returns -1 by default, which means that there is no limit - * for the number of instances. Concrete components can override this method - * to set a limit. + * This method returns -1 by default, which means that there is no limit for the number of + * instances. Concrete components can override this method to set a limit. * * \return The maximum number of instances for this component */ diff --git a/src/crepe/ComponentManager.cpp b/src/crepe/ComponentManager.cpp index 7af0380..e310577 100644 --- a/src/crepe/ComponentManager.cpp +++ b/src/crepe/ComponentManager.cpp @@ -6,6 +6,9 @@ using namespace crepe; using namespace std; +ComponentManager::ComponentManager() { dbg_trace(); } +ComponentManager::~ComponentManager() { dbg_trace(); } + void ComponentManager::delete_all_components_of_id(game_object_id_t id) { // Loop through all the types (in the unordered_map<>) for (auto & [type, componentArray] : this->components) { @@ -18,18 +21,14 @@ void ComponentManager::delete_all_components_of_id(game_object_id_t id) { } void ComponentManager::delete_all_components() { - // Clear the whole unordered_map<> this->components.clear(); + this->next_id = 0; } -ComponentManager::ComponentManager() { dbg_trace(); } -ComponentManager::~ComponentManager() { dbg_trace(); } - GameObject ComponentManager::new_object(const string & name, const string & tag, - const Vector2 & position, - double rotation, double scale) { - GameObject object{*this, this->next_id, name, tag, - position, rotation, scale}; + const Vector2 & position, double rotation, + double scale) { + GameObject object{*this, this->next_id, name, tag, position, rotation, scale}; this->next_id++; return object; } diff --git a/src/crepe/ComponentManager.h b/src/crepe/ComponentManager.h index 51c84a4..2107453 100644 --- a/src/crepe/ComponentManager.h +++ b/src/crepe/ComponentManager.h @@ -1,14 +1,14 @@ #pragma once -#include <forward_list> #include <memory> #include <typeindex> #include <unordered_map> #include <vector> -#include "Component.h" #include "api/Vector2.h" +#include "Component.h" + namespace crepe { class GameObject; @@ -16,20 +16,48 @@ class GameObject; /** * \brief Manages all components * - * This class manages all components. It provides methods to add, delete and get - * components. + * This class manages all components. It provides methods to add, delete and get components. */ class ComponentManager { + // TODO: This relation should be removed! I (loek) believe that the scene manager should + // create/destroy components because the GameObject's are stored in concrete Scene classes, + // which will in turn call GameObject's destructor, which will in turn call + // ComponentManager::delete_components_by_id or something. This is a pretty major change, so + // here is a comment and temporary fix instead :tada: + friend class SceneManager; + public: ComponentManager(); // dbg_trace ~ComponentManager(); // dbg_trace + /** + * \brief Create a new game object using the component manager + * + * \param name Metadata::name (required) + * \param tag Metadata::tag (optional, empty by default) + * \param position Transform::position (optional, origin by default) + * \param rotation Transform::rotation (optional, 0 by default) + * \param scale Transform::scale (optional, 1 by default) + * + * \returns GameObject interface + * + * \note This method automatically assigns a new entity ID + */ + GameObject new_object(const std::string & name, const std::string & tag = "", + const Vector2 & position = {0, 0}, double rotation = 0, + double scale = 1); + protected: /** + * GameObject is used as an interface to add/remove components, and the game programmer is + * supposed to use it instead of interfacing with the component manager directly. + */ + friend class GameObject; + /** * \brief Add a component to the ComponentManager * - * This method adds a component to the ComponentManager. The component is - * created with the given arguments and added to the ComponentManager. + * This method adds a component to the ComponentManager. The component is created with the + * given arguments and added to the ComponentManager. * * \tparam T The type of the component * \tparam Args The types of the arguments @@ -39,11 +67,6 @@ protected: */ template <typename T, typename... Args> T & add_component(game_object_id_t id, Args &&... args); - //! GameObject is used as an interface to add components instead of the - // component manager directly - friend class GameObject; - -public: /** * \brief Delete all components of a specific type and id * @@ -77,6 +100,8 @@ public: * This method deletes all components. */ void delete_all_components(); + +public: /** * \brief Get all components of a specific type and id * @@ -87,8 +112,7 @@ public: * \return A vector of all components of the specific type and id */ template <typename T> - std::vector<std::reference_wrapper<T>> - get_components_by_id(game_object_id_t id) const; + std::vector<std::reference_wrapper<T>> get_components_by_id(game_object_id_t id) const; /** * \brief Get all components of a specific type * @@ -100,31 +124,22 @@ public: template <typename T> std::vector<std::reference_wrapper<T>> get_components_by_type() const; - // TODO: doxygen - GameObject new_object(const std::string & name, - const std::string & tag = "", - const Vector2 & position = {0, 0}, - double rotation = 0, double scale = 0); - private: /** * \brief The components * - * This unordered_map stores all components. The key is the type of the - * component and the value is a vector of vectors of unique pointers to the - * components. - * Every component type has its own vector of vectors of unique pointers to - * the components. The first vector is for the ids of the GameObjects and the - * second vector is for the components (because a GameObject might have multiple - * components). + * This unordered_map stores all components. The key is the type of the component and the + * value is a vector of vectors of unique pointers to the components. + * + * Every component type has its own vector of vectors of unique pointers to the components. + * The first vector is for the ids of the GameObjects and the second vector is for the + * components (because a GameObject might have multiple components). */ - std::unordered_map<std::type_index, - std::vector<std::vector<std::unique_ptr<Component>>>> + std::unordered_map<std::type_index, std::vector<std::vector<std::unique_ptr<Component>>>> components; - //! ID of next GameObject + //! ID of next GameObject allocated by \c ComponentManager::new_object game_object_id_t next_id = 0; - std::forward_list<std::unique_ptr<GameObject>> objects; }; } // namespace crepe diff --git a/src/crepe/ComponentManager.hpp b/src/crepe/ComponentManager.hpp index 98efb49..be99cac 100644 --- a/src/crepe/ComponentManager.hpp +++ b/src/crepe/ComponentManager.hpp @@ -40,7 +40,6 @@ T & ComponentManager::add_component(game_object_id_t id, Args &&... args) { // Check if the vector size is not greater than get_instances_max int max_instances = instance->get_instances_max(); if (max_instances != -1 && components[type][id].size() >= max_instances) { - // TODO: Exception throw std::runtime_error( "Exceeded maximum number of instances for this component type"); } @@ -61,8 +60,7 @@ void ComponentManager::delete_components_by_id(game_object_id_t id) { // Find the type (in the unordered_map<>) if (this->components.find(type) != this->components.end()) { // Get the correct vector<> - vector<vector<unique_ptr<Component>>> & component_array - = this->components[type]; + vector<vector<unique_ptr<Component>>> & component_array = this->components[type]; // Make sure that the id (that we are looking for) is within the boundaries of the vector<> if (id < component_array.size()) { @@ -93,12 +91,10 @@ ComponentManager::get_components_by_id(game_object_id_t id) const { // Create an empty vector<> vector<reference_wrapper<T>> component_vector; - if (this->components.find(type) == this->components.end()) - return component_vector; + if (this->components.find(type) == this->components.end()) return component_vector; // Get the correct vector<> - const vector<vector<unique_ptr<Component>>> & component_array - = this->components.at(type); + const vector<vector<unique_ptr<Component>>> & component_array = this->components.at(type); // Make sure that the id (that we are looking for) is within the boundaries of the vector<> if (id >= component_array.size()) return component_vector; @@ -118,8 +114,7 @@ ComponentManager::get_components_by_id(game_object_id_t id) const { } template <typename T> -std::vector<std::reference_wrapper<T>> -ComponentManager::get_components_by_type() const { +std::vector<std::reference_wrapper<T>> ComponentManager::get_components_by_type() const { using namespace std; // Determine the type of T (this is used as the key of the unordered_map<>) @@ -129,12 +124,10 @@ ComponentManager::get_components_by_type() const { vector<reference_wrapper<T>> component_vector; // Find the type (in the unordered_map<>) - if (this->components.find(type) == this->components.end()) - return component_vector; + if (this->components.find(type) == this->components.end()) return component_vector; // Get the correct vector<> - const vector<vector<unique_ptr<Component>>> & component_array - = this->components.at(type); + const vector<vector<unique_ptr<Component>>> & component_array = this->components.at(type); // Loop through the whole vector<> for (const vector<unique_ptr<Component>> & component : component_array) { diff --git a/src/crepe/Exception.cpp b/src/crepe/Exception.cpp deleted file mode 100644 index 5a24e7e..0000000 --- a/src/crepe/Exception.cpp +++ /dev/null @@ -1,8 +0,0 @@ -#include "Exception.h" - -using namespace crepe; -using namespace std; - -const char * Exception::what() const noexcept { return error.c_str(); } - -Exception::Exception(const string & msg) { this->error = msg; } diff --git a/src/crepe/Exception.h b/src/crepe/Exception.h deleted file mode 100644 index 580fc16..0000000 --- a/src/crepe/Exception.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include <exception> -#include <format> -#include <string> - -namespace crepe { - -//! Exception class -class Exception : public std::exception { -public: - //! Exception with plain message - Exception(const std::string & msg); - - //! Exception with \c std::format message - template <class... Args> - Exception(std::format_string<Args...> fmt, Args &&... args); - - //! Get formatted error message - const char * what() const noexcept; - -protected: - Exception() = default; - - //! Formatted error message - std::string error; -}; - -} // namespace crepe - -#include "Exception.hpp" diff --git a/src/crepe/Exception.hpp b/src/crepe/Exception.hpp deleted file mode 100644 index 7c462a3..0000000 --- a/src/crepe/Exception.hpp +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include "Exception.h" - -namespace crepe { - -template <class... Args> -Exception::Exception(std::format_string<Args...> fmt, Args &&... args) { - this->error = std::format(fmt, std::forward<Args>(args)...); -} - -} // namespace crepe diff --git a/src/crepe/Particle.cpp b/src/crepe/Particle.cpp index 582edf4..1068cbf 100644 --- a/src/crepe/Particle.cpp +++ b/src/crepe/Particle.cpp @@ -2,8 +2,8 @@ using namespace crepe; -void Particle::reset(uint32_t lifespan, const Vector2 & position, - const Vector2 & velocity, double angle) { +void Particle::reset(uint32_t lifespan, const Vector2 & position, const Vector2 & velocity, + double angle) { // Initialize the particle state this->time_in_life = 0; this->lifespan = lifespan; diff --git a/src/crepe/Particle.h b/src/crepe/Particle.h index 3eaebc3..19859fe 100644 --- a/src/crepe/Particle.h +++ b/src/crepe/Particle.h @@ -9,9 +9,9 @@ namespace crepe { /** * \brief Represents a particle in the particle emitter. * - * This class stores information about a single particle, including its position, - * velocity, lifespan, and other properties. Particles can be updated over time - * to simulate movement and can also be reset or stopped. + * This class stores information about a single particle, including its position, velocity, + * lifespan, and other properties. Particles can be updated over time to simulate movement and + * can also be reset or stopped. */ class Particle { // TODO: add friend particleSsytem and rendersystem. Unit test will fail. @@ -35,20 +35,20 @@ public: /** * \brief Resets the particle with new properties. * - * This method initializes the particle with a specific lifespan, position, - * velocity, and angle, marking it as active and resetting its life counter. + * This method initializes the particle with a specific lifespan, position, velocity, and + * angle, marking it as active and resetting its life counter. * * \param lifespan The lifespan of the particle in amount of updates. * \param position The starting position of the particle. * \param velocity The initial velocity of the particle. * \param angle The angle of the particle's trajectory or orientation. */ - void reset(uint32_t lifespan, const Vector2 & position, - const Vector2 & velocity, double angle); + void reset(uint32_t lifespan, const Vector2 & position, const Vector2 & velocity, + double angle); /** * \brief Updates the particle's state. * - * Advances the particle's position based on its velocity and applies accumulated forces. + * Advances the particle's position based on its velocity and applies accumulated forces. * Deactivates the particle if its lifespan has expired. */ void update(); diff --git a/src/crepe/ValueBroker.h b/src/crepe/ValueBroker.h index d844d6a..673b660 100644 --- a/src/crepe/ValueBroker.h +++ b/src/crepe/ValueBroker.h @@ -7,10 +7,9 @@ namespace crepe { /** * \brief Give reference to value through custom set/get functions * - * This class can be used to abstract direct access to any arbitrary value - * through a custom get and set function passed to its constructor. Consumers - * of this type may want to wrap it in a \c Proxy so it behaves like a regular - * variable. + * This class can be used to abstract direct access to any arbitrary value through a custom get + * and set function passed to its constructor. Consumers of this type may want to wrap it in a + * \c Proxy so it behaves like a regular variable. * * \tparam T Type of the underlying variable */ diff --git a/src/crepe/api/Animator.cpp b/src/crepe/api/Animator.cpp index 54b2ec3..464b0fd 100644 --- a/src/crepe/api/Animator.cpp +++ b/src/crepe/api/Animator.cpp @@ -1,6 +1,4 @@ -#include <cstdint> - #include "util/Log.h" #include "Animator.h" @@ -9,8 +7,7 @@ using namespace crepe; -Animator::Animator(game_object_id_t id, Sprite & ss, int row, int col, - int col_animator) +Animator::Animator(game_object_id_t id, Sprite & ss, int row, int col, int col_animator) : Component(id), spritesheet(ss), row(row), diff --git a/src/crepe/api/Animator.h b/src/crepe/api/Animator.h index 75b8139..53f4b91 100644 --- a/src/crepe/api/Animator.h +++ b/src/crepe/api/Animator.h @@ -1,7 +1,5 @@ #pragma once -#include <cstdint> - #include "Component.h" #include "Sprite.h" @@ -11,11 +9,11 @@ class AnimatorSystem; class SDLContext; /** - * \brief The Animator component is used to animate sprites by managing the movement - * and frame changes within a sprite sheet. + * \brief The Animator component is used to animate sprites by managing the movement and frame + * changes within a sprite sheet. * - * This component allows for controlling sprite animation through rows and columns of a sprite sheet. - * It can be used to play animations, loop them, or stop them. + * This component allows for controlling sprite animation through rows and columns of a sprite + * sheet. It can be used to play animations, loop them, or stop them. */ class Animator : public Component { @@ -29,15 +27,17 @@ public: * \brief Constructs an Animator object that will control animations for a sprite sheet. * * \param id The unique identifier for the component, typically assigned automatically. - * \param spritesheet A reference to the Sprite object which holds the sprite sheet for animation. + * \param spritesheet A reference to the Sprite object which holds the sprite sheet for + * animation. * \param row The maximum number of rows in the sprite sheet. * \param col The maximum number of columns in the sprite sheet. - * \param col__animate The specific col index of the sprite sheet to animate. This allows selecting which col to animate from multiple col in the sheet. + * \param col_animate The specific col index of the sprite sheet to animate. This allows + * selecting which col to animate from multiple col in the sheet. * - * This constructor sets up the Animator with the given parameters, and initializes the animation system. + * This constructor sets up the Animator with the given parameters, and initializes the + * animation system. */ - Animator(game_object_id_t id, Sprite & spritesheet, int row, int col, - int col_animate); + Animator(uint32_t id, Sprite & spritesheet, int row, int col, int col_animate); ~Animator(); // dbg_trace Animator(const Animator &) = delete; diff --git a/src/crepe/api/AssetManager.h b/src/crepe/api/AssetManager.h new file mode 100644 index 0000000..fee6780 --- /dev/null +++ b/src/crepe/api/AssetManager.h @@ -0,0 +1,62 @@ +#pragma once + +#include <any> +#include <memory> +#include <string> +#include <unordered_map> + +namespace crepe { + +/** + * \brief The AssetManager is responsible for storing and managing assets over multiple scenes. + * + * The AssetManager ensures that assets are loaded once and can be accessed across different + * scenes. It caches assets to avoid reloading them every time a scene is loaded. Assets are + * retained in memory until the AssetManager is destroyed, at which point the cached assets are + * cleared. + */ +class AssetManager { + +private: + //! A cache that holds all the assets, accessible by their file path, over multiple scenes. + std::unordered_map<std::string, std::any> asset_cache; + +private: + AssetManager(); + virtual ~AssetManager(); + +public: + AssetManager(const AssetManager &) = delete; + AssetManager(AssetManager &&) = delete; + AssetManager & operator=(const AssetManager &) = delete; + AssetManager & operator=(AssetManager &&) = delete; + + /** + * \brief Retrieves the singleton instance of the AssetManager. + * + * \return A reference to the single instance of the AssetManager. + */ + static AssetManager & get_instance(); + +public: + /** + * \brief Caches an asset by loading it from the given file path. + * + * \param file_path The path to the asset file to load. + * \param reload If true, the asset will be reloaded from the file, even if it is already + * cached. + * \tparam T The type of asset to cache (e.g., texture, sound, etc.). + * + * \return A shared pointer to the cached asset. + * + * This template function caches the asset at the given file path. If the asset is already + * cached and `reload` is false, the existing cached version will be returned. Otherwise, the + * asset will be reloaded and added to the cache. + */ + template <typename T> + std::shared_ptr<T> cache(const std::string & file_path, bool reload = false); +}; + +} // namespace crepe + +#include "AssetManager.hpp" diff --git a/src/crepe/api/AssetManager.hpp b/src/crepe/api/AssetManager.hpp new file mode 100644 index 0000000..1c0e978 --- /dev/null +++ b/src/crepe/api/AssetManager.hpp @@ -0,0 +1,22 @@ +#pragma once + +#include "AssetManager.h" + +namespace crepe { + +template <typename asset> +std::shared_ptr<asset> AssetManager::cache(const std::string & file_path, bool reload) { + auto it = asset_cache.find(file_path); + + if (!reload && it != asset_cache.end()) { + return std::any_cast<std::shared_ptr<asset>>(it->second); + } + + std::shared_ptr<asset> new_asset = std::make_shared<asset>(file_path.c_str()); + + asset_cache[file_path] = new_asset; + + return new_asset; +} + +} // namespace crepe diff --git a/src/crepe/api/BehaviorScript.h b/src/crepe/api/BehaviorScript.h index 2982358..9d85d4c 100644 --- a/src/crepe/api/BehaviorScript.h +++ b/src/crepe/api/BehaviorScript.h @@ -3,6 +3,7 @@ #include <memory> #include "../Component.h" + #include "GameObject.h" namespace crepe { @@ -14,20 +15,26 @@ class Script; /** * \brief Script component * - * This class acts as a (component) wrapper around an instance of (a class - * derivatived from) \c Script. \c BehaviorScript is the only ECS component - * that stores member function implementations as data. + * This class acts as a (component) wrapper around an instance of (a class derivatived from) \c + * Script. \c BehaviorScript is the only ECS component that stores member function + * implementations as data. */ class BehaviorScript : public Component { protected: + /** + * \param id Parent \c GameObject id + * \param component_manager Reference to component manager (passed through to \c Script + * instance) + * + * \note Calls to this constructor (should) always pass through \c GameObject::add_component, + * which has an exception for this specific component type. This was done so the user does + * not have to pass references used within \c Script to each \c BehaviorScript instance. + */ BehaviorScript(game_object_id_t id, ComponentManager & component_manager); //! Only ComponentManager is allowed to instantiate BehaviorScript friend class ComponentManager; public: - ~BehaviorScript() = default; - -public: /** * \brief Set the concrete script of this component * @@ -39,29 +46,23 @@ public: BehaviorScript & set_script(); protected: - //! ScriptSystem needs direct access to the script instance - friend class ScriptSystem; - //! Flag to indicate if script->init() has been called already - bool initialized = false; //! Script instance std::unique_ptr<Script> script = nullptr; - //! Reference to component manager - ComponentManager & component_manager; + //! ScriptSystem needs direct access to the script instance + friend class ScriptSystem; -private: - //! Script accesses the component manager directly via its parent - // (BehaviorScript) reference - friend class Script; +protected: + //! Reference to component manager (passed to Script) + ComponentManager & component_manager; }; /** * \brief Add a BehaviorScript component to this game object * - * The \c BehaviorScript class is the only exception to the ECS harmony, and - * requires a reference to the component manager passed to its constructor in - * order to function normally. This is because the \c BehaviorScript (and \c - * Script) classes are the only component-related classes that store - * implemented member functions as data. + * The \c BehaviorScript class is the only exception to the ECS harmony, and requires a + * reference to the component manager passed to its constructor in order to function normally. + * This is because the \c BehaviorScript (and \c Script) classes are the only component-related + * classes that store implemented member functions as data. */ template <> BehaviorScript & GameObject::add_component<BehaviorScript>(); diff --git a/src/crepe/api/BehaviorScript.hpp b/src/crepe/api/BehaviorScript.hpp index eec26da..d80321d 100644 --- a/src/crepe/api/BehaviorScript.hpp +++ b/src/crepe/api/BehaviorScript.hpp @@ -14,7 +14,7 @@ BehaviorScript & BehaviorScript::set_script() { dbg_trace(); static_assert(std::is_base_of<Script, T>::value); Script * s = new T(); - s->parent_ref = this; + s->game_object_id = this->game_object_id; s->component_manager_ref = &this->component_manager; this->script = std::unique_ptr<Script>(s); return *this; diff --git a/src/crepe/api/CMakeLists.txt b/src/crepe/api/CMakeLists.txt index b452f37..cca0e8b 100644 --- a/src/crepe/api/CMakeLists.txt +++ b/src/crepe/api/CMakeLists.txt @@ -1,7 +1,6 @@ target_sources(crepe PUBLIC AudioSource.cpp BehaviorScript.cpp - Script.cpp GameObject.cpp Rigidbody.cpp ParticleEmitter.cpp diff --git a/src/crepe/api/Camera.h b/src/crepe/api/Camera.h index d8c08a6..e0cda34 100644 --- a/src/crepe/api/Camera.h +++ b/src/crepe/api/Camera.h @@ -1,7 +1,5 @@ #pragma once -#include <cstdint> - #include "Color.h" #include "Component.h" @@ -11,9 +9,8 @@ namespace crepe { * \class Camera * \brief Represents a camera component for rendering in the game. * - * The Camera class defines the view parameters, including background color, - * aspect ratio, position, and zoom level. It controls what part of the game - * world is visible on the screen. + * The Camera class defines the view parameters, including background color, aspect ratio, + * position, and zoom level. It controls what part of the game world is visible on the screen. */ class Camera : public Component { diff --git a/src/crepe/api/Config.h b/src/crepe/api/Config.h index c3f9474..13eabd1 100644 --- a/src/crepe/api/Config.h +++ b/src/crepe/api/Config.h @@ -4,16 +4,21 @@ namespace crepe { +/** + * \brief Global configuration interface + * + * This class stores engine default settings. Properties on this class are only supposed to be + * modified *before* execution is handed over from the game programmer to the engine (i.e. the + * main loop is started). + */ class Config { -private: - Config() = default; - -public: - ~Config() = default; - public: //! Retrieve handle to global Config instance static Config & get_instance(); + +private: + Config() = default; + // singleton Config(const Config &) = delete; Config(Config &&) = delete; @@ -26,8 +31,7 @@ public: /** * \brief Log level * - * Only messages with equal or higher severity than this value will be - * logged. + * Only messages with equal or higher priority than this value will be logged. */ Log::Level level = Log::Level::INFO; /** @@ -43,8 +47,8 @@ public: /** * \brief Save file location * - * This location is used by the constructor of SaveManager, and should be - * set before save manager functionality is attempted to be used. + * This location is used by the constructor of SaveManager, and should be set before save + * manager functionality is attempted to be used. */ std::string location = "save.crepe.db"; } savemgr; diff --git a/src/crepe/api/GameObject.cpp b/src/crepe/api/GameObject.cpp index 4f3c639..287e81d 100644 --- a/src/crepe/api/GameObject.cpp +++ b/src/crepe/api/GameObject.cpp @@ -7,10 +7,9 @@ using namespace crepe; using namespace std; -GameObject::GameObject(ComponentManager & component_manager, - game_object_id_t id, const std::string & name, - const std::string & tag, const Vector2 & position, - double rotation, double scale) +GameObject::GameObject(ComponentManager & component_manager, game_object_id_t id, + const std::string & name, const std::string & tag, + const Vector2 & position, double rotation, double scale) : id(id), component_manager(component_manager) { diff --git a/src/crepe/api/GameObject.h b/src/crepe/api/GameObject.h index 73ff0b8..34ef8bb 100644 --- a/src/crepe/api/GameObject.h +++ b/src/crepe/api/GameObject.h @@ -12,15 +12,14 @@ class ComponentManager; /** * \brief Represents a GameObject * - * This class represents a GameObject. The GameObject class is only used - * as an interface for the game programmer. The actual implementation is - * done in the ComponentManager. + * This class represents a GameObject. The GameObject class is only used as an interface for + * the game programmer. The actual implementation is done in the ComponentManager. */ class GameObject { private: /** - * This constructor creates a new GameObject. It creates a new - * Transform and Metadata component and adds them to the ComponentManager. + * This constructor creates a new GameObject. It creates a new Transform and Metadata + * component and adds them to the ComponentManager. * * \param component_manager Reference to component_manager * \param id The id of the GameObject @@ -31,8 +30,8 @@ private: * \param scale The scale of the GameObject */ GameObject(ComponentManager & component_manager, game_object_id_t id, - const std::string & name, const std::string & tag, - const Vector2 & position, double rotation, double scale); + const std::string & name, const std::string & tag, const Vector2 & position, + double rotation, double scale); //! ComponentManager instances GameObject friend class ComponentManager; @@ -40,9 +39,9 @@ public: /** * \brief Set the parent of this GameObject * - * This method sets the parent of this GameObject. It sets the parent - * in the Metadata component of this GameObject and adds this GameObject - * to the children list of the parent GameObject. + * This method sets the parent of this GameObject. It sets the parent in the Metadata + * component of this GameObject and adds this GameObject to the children list of the parent + * GameObject. * * \param parent The parent GameObject */ @@ -50,8 +49,8 @@ public: /** * \brief Add a component to the GameObject * - * This method adds a component to the GameObject. It forwards the - * arguments to the ComponentManager. + * This method adds a component to the GameObject. It forwards the arguments to the + * ComponentManager. * * \tparam T The type of the component * \tparam Args The types of the arguments diff --git a/src/crepe/api/LoopManager.cpp b/src/crepe/api/LoopManager.cpp index f0788ab..a64366f 100644 --- a/src/crepe/api/LoopManager.cpp +++ b/src/crepe/api/LoopManager.cpp @@ -22,10 +22,6 @@ LoopManager::LoopManager() { this->load_system<ScriptSystem>(); } -ComponentManager & LoopManager::get_component_manager() { - return this->component_manager; -} - void LoopManager::process_input() { SDLContext::get_instance().handle_events(this->game_running); } diff --git a/src/crepe/api/LoopManager.h b/src/crepe/api/LoopManager.h index 288dca2..f6904be 100644 --- a/src/crepe/api/LoopManager.h +++ b/src/crepe/api/LoopManager.h @@ -68,18 +68,32 @@ private: bool game_running = false; -protected: - ComponentManager & get_component_manager(); - template <class T> - T & get_system(); - private: + //! Component manager instance ComponentManager component_manager{}; - std::unordered_map<std::type_index, std::unique_ptr<System>> systems; private: + /** + * \brief Collection of System instances + * + * This map holds System instances indexed by the system's class typeid. It is filled in the + * constructor of \c LoopManager using LoopManager::load_system. + */ + std::unordered_map<std::type_index, std::unique_ptr<System>> systems; + /** + * \brief Initialize a system + * \tparam T System type (must be derivative of \c System) + */ template <class T> void load_system(); + /** + * \brief Retrieve a reference to ECS system + * \tparam T System type + * \returns Reference to system instance + * \throws std::runtime_error if the System is not initialized + */ + template <class T> + T & get_system(); }; } // namespace crepe diff --git a/src/crepe/api/LoopManager.hpp b/src/crepe/api/LoopManager.hpp index 8fb9aa3..0b14fdb 100644 --- a/src/crepe/api/LoopManager.hpp +++ b/src/crepe/api/LoopManager.hpp @@ -1,9 +1,9 @@ #pragma once #include <cassert> +#include <format> #include <memory> -#include "../Exception.h" #include "../system/System.h" #include "LoopManager.h" @@ -18,7 +18,7 @@ T & LoopManager::get_system() { const type_info & type = typeid(T); if (!this->systems.contains(type)) - throw Exception("LoopManager: %s is not initialized", type.name()); + throw runtime_error(format("LoopManager: {} is not initialized", type.name())); System * system = this->systems.at(type).get(); T * concrete_system = dynamic_cast<T *>(system); diff --git a/src/crepe/api/LoopTimer.cpp b/src/crepe/api/LoopTimer.cpp index b3aec22..a9800b7 100644 --- a/src/crepe/api/LoopTimer.cpp +++ b/src/crepe/api/LoopTimer.cpp @@ -24,9 +24,8 @@ void LoopTimer::start() { void LoopTimer::update() { auto current_frame_time = std::chrono::steady_clock::now(); // Convert to duration in seconds for delta time - this->delta_time - = std::chrono::duration_cast<std::chrono::duration<double>>( - current_frame_time - last_frame_time); + this->delta_time = std::chrono::duration_cast<std::chrono::duration<double>>( + current_frame_time - last_frame_time); if (this->delta_time > this->maximum_delta_time) { this->delta_time = this->maximum_delta_time; @@ -39,17 +38,11 @@ void LoopTimer::update() { double LoopTimer::get_delta_time() const { return this->delta_time.count(); } -double LoopTimer::get_current_time() const { - return this->elapsed_time.count(); -} +double LoopTimer::get_current_time() const { return this->elapsed_time.count(); } -void LoopTimer::advance_fixed_update() { - this->elapsed_fixed_time += this->fixed_delta_time; -} +void LoopTimer::advance_fixed_update() { this->elapsed_fixed_time += this->fixed_delta_time; } -double LoopTimer::get_fixed_delta_time() const { - return this->fixed_delta_time.count(); -} +double LoopTimer::get_fixed_delta_time() const { return this->fixed_delta_time.count(); } void LoopTimer::set_fps(int fps) { this->fps = fps; @@ -66,13 +59,13 @@ void LoopTimer::enforce_frame_rate() { std::chrono::steady_clock::time_point current_frame_time = std::chrono::steady_clock::now(); std::chrono::milliseconds frame_duration - = std::chrono::duration_cast<std::chrono::milliseconds>( - current_frame_time - this->last_frame_time); + = std::chrono::duration_cast<std::chrono::milliseconds>(current_frame_time + - this->last_frame_time); if (frame_duration < this->frame_target_time) { std::chrono::milliseconds delay_time - = std::chrono::duration_cast<std::chrono::milliseconds>( - this->frame_target_time - frame_duration); + = std::chrono::duration_cast<std::chrono::milliseconds>(this->frame_target_time + - frame_duration); if (delay_time.count() > 0) { SDLContext::get_instance().delay(delay_time.count()); } diff --git a/src/crepe/api/LoopTimer.h b/src/crepe/api/LoopTimer.h index 85687be..f277d7b 100644 --- a/src/crepe/api/LoopTimer.h +++ b/src/crepe/api/LoopTimer.h @@ -1,124 +1,123 @@ #pragma once #include <chrono> -#include <cstdint> namespace crepe { class LoopTimer { public: /** - * \brief Get the singleton instance of LoopTimer. - * - * \return A reference to the LoopTimer instance. - */ + * \brief Get the singleton instance of LoopTimer. + * + * \return A reference to the LoopTimer instance. + */ static LoopTimer & get_instance(); /** - * \brief Get the current delta time for the current frame. - * - * \return Delta time in seconds since the last frame. - */ + * \brief Get the current delta time for the current frame. + * + * \return Delta time in seconds since the last frame. + */ double get_delta_time() const; /** - * \brief Get the current game time. - * - * \note The current game time may vary from real-world elapsed time. - * It is the cumulative sum of each frame's delta time. - * - * \return Elapsed game time in seconds. - */ + * \brief Get the current game time. + * + * \note The current game time may vary from real-world elapsed time. It is the cumulative + * sum of each frame's delta time. + * + * \return Elapsed game time in seconds. + */ double get_current_time() const; /** - * \brief Set the target frames per second (FPS). - * - * \param fps The desired frames rendered per second. - */ + * \brief Set the target frames per second (FPS). + * + * \param fps The desired frames rendered per second. + */ void set_fps(int fps); /** - * \brief Get the current frames per second (FPS). - * - * \return Current FPS. - */ + * \brief Get the current frames per second (FPS). + * + * \return Current FPS. + */ int get_fps() const; /** - * \brief Get the current game scale. - * - * \return The current game scale, where 0 = paused, 1 = normal speed, and values > 1 speed up the game. - */ + * \brief Get the current game scale. + * + * \return The current game scale, where 0 = paused, 1 = normal speed, and values > 1 speed + * up the game. + */ double get_game_scale() const; /** - * \brief Set the game scale. - * - * \param game_scale The desired game scale (0 = pause, 1 = normal speed, > 1 = speed up). - */ + * \brief Set the game scale. + * + * \param game_scale The desired game scale (0 = pause, 1 = normal speed, > 1 = speed up). + */ void set_game_scale(double game_scale); private: friend class LoopManager; /** - * \brief Start the loop timer. - * - * Initializes the timer to begin tracking frame times. - */ + * \brief Start the loop timer. + * + * Initializes the timer to begin tracking frame times. + */ void start(); /** - * \brief Enforce the frame rate limit. - * - * Ensures that the game loop does not exceed the target FPS by delaying - * frame updates as necessary. - */ + * \brief Enforce the frame rate limit. + * + * Ensures that the game loop does not exceed the target FPS by delaying frame updates as + * necessary. + */ void enforce_frame_rate(); /** - * \brief Get the fixed delta time for consistent updates. - * - * Fixed delta time is used for operations that require uniform time steps, - * such as physics calculations. - * - * \return Fixed delta time in seconds. - */ + * \brief Get the fixed delta time for consistent updates. + * + * Fixed delta time is used for operations that require uniform time steps, such as physics + * calculations. + * + * \return Fixed delta time in seconds. + */ double get_fixed_delta_time() const; /** - * \brief Get the accumulated lag in the game loop. - * - * Lag represents the difference between the target frame time and the - * actual frame time, useful for managing fixed update intervals. - * - * \return Accumulated lag in seconds. - */ + * \brief Get the accumulated lag in the game loop. + * + * Lag represents the difference between the target frame time and the actual frame time, + * useful for managing fixed update intervals. + * + * \return Accumulated lag in seconds. + */ double get_lag() const; /** - * \brief Construct a new LoopTimer object. - * - * Private constructor for singleton pattern to restrict instantiation - * outside the class. - */ + * \brief Construct a new LoopTimer object. + * + * Private constructor for singleton pattern to restrict instantiation outside the class. + */ LoopTimer(); /** - * \brief Update the timer to the current frame. - * - * Calculates and updates the delta time for the current frame and adds it to - * the cumulative game time. - */ + * \brief Update the timer to the current frame. + * + * Calculates and updates the delta time for the current frame and adds it to the cumulative + * game time. + */ void update(); /** - * \brief Advance the game loop by a fixed update interval. - * - * This method progresses the game state by a consistent, fixed time step, - * allowing for stable updates independent of frame rate fluctuations. - */ + * \brief Advance the game loop by a fixed update interval. + * + * This method progresses the game state by a consistent, fixed time step, allowing for + * stable updates independent of frame rate fluctuations. + */ void advance_fixed_update(); private: @@ -131,11 +130,9 @@ private: //! Delta time for the current frame in seconds std::chrono::duration<double> delta_time{0.0}; //! Target time per frame in seconds - std::chrono::duration<double> frame_target_time - = std::chrono::seconds(1) / fps; + std::chrono::duration<double> frame_target_time = std::chrono::seconds(1) / fps; //! Fixed delta time for fixed updates in seconds - std::chrono::duration<double> fixed_delta_time - = std::chrono::seconds(1) / 50; + std::chrono::duration<double> fixed_delta_time = std::chrono::seconds(1) / 50; //! Total elapsed game time in seconds std::chrono::duration<double> elapsed_time{0.0}; //! Total elapsed time for fixed updates in seconds diff --git a/src/crepe/api/Metadata.h b/src/crepe/api/Metadata.h index c61e006..235d42f 100644 --- a/src/crepe/api/Metadata.h +++ b/src/crepe/api/Metadata.h @@ -10,8 +10,8 @@ namespace crepe { /** * \brief Metadata component * - * This class represents the Metadata component. It stores the name, tag, parent - * and children of a GameObject. + * This class represents the Metadata component. It stores the name, tag, parent and children + * of a GameObject. */ class Metadata : public Component { public: @@ -20,8 +20,7 @@ public: * \param name The name of the GameObject * \param tag The tag of the GameObject */ - Metadata(game_object_id_t id, const std::string & name, - const std::string & tag); + Metadata(game_object_id_t id, const std::string & name, const std::string & tag); /** * \brief Get the maximum number of instances for this component * diff --git a/src/crepe/api/ParticleEmitter.cpp b/src/crepe/api/ParticleEmitter.cpp index 35f960d..90b77a0 100644 --- a/src/crepe/api/ParticleEmitter.cpp +++ b/src/crepe/api/ParticleEmitter.cpp @@ -2,8 +2,7 @@ using namespace crepe; -ParticleEmitter::ParticleEmitter(game_object_id_t game_object_id, - const Data & data) +ParticleEmitter::ParticleEmitter(game_object_id_t game_object_id, const Data & data) : Component(game_object_id), data(data) { for (size_t i = 0; i < this->data.max_particles; i++) { diff --git a/src/crepe/api/ParticleEmitter.h b/src/crepe/api/ParticleEmitter.h index a9e872f..33112e1 100644 --- a/src/crepe/api/ParticleEmitter.h +++ b/src/crepe/api/ParticleEmitter.h @@ -13,16 +13,16 @@ class Sprite; /** * \brief Data holder for particle emission parameters. * - * The ParticleEmitter class stores configuration data for particle properties, - * defining the characteristics and boundaries of particle emissions. + * The ParticleEmitter class stores configuration data for particle properties, defining the + * characteristics and boundaries of particle emissions. */ class ParticleEmitter : public Component { public: /** * \brief Defines the boundary within which particles are constrained. * - * This structure specifies the boundary's size and offset, as well as the - * behavior of particles upon reaching the boundary limits. + * This structure specifies the boundary's size and offset, as well as the behavior of + * particles upon reaching the boundary limits. */ struct Boundary { //! boundary width (midpoint is emitter location) @@ -38,8 +38,8 @@ public: /** * \brief Holds parameters that control particle emission. * - * Contains settings for the emitter’s position, particle speed, angle, lifespan, - * boundary, and the sprite used for rendering particles. + * Contains settings for the emitter’s position, particle speed, angle, lifespan, boundary, + * and the sprite used for rendering particles. */ struct Data { //! position of the emitter diff --git a/src/crepe/api/Rigidbody.h b/src/crepe/api/Rigidbody.h index 2e20288..3e5c7a3 100644 --- a/src/crepe/api/Rigidbody.h +++ b/src/crepe/api/Rigidbody.h @@ -1,7 +1,5 @@ #pragma once -#include <cstdint> - #include "../Component.h" #include "Vector2.h" @@ -11,8 +9,8 @@ namespace crepe { /** * \brief Rigidbody class * - * This class is used by the physics sytem and collision system. - * It configures how to system interact with the gameobject for movement and collisions. + * This class is used by the physics sytem and collision system. It configures how to system + * interact with the gameobject for movement and collisions. */ class Rigidbody : public Component { public: @@ -32,8 +30,8 @@ public: /** * \brief PhysicsConstraints to constrain movement * - * This struct configures the movement constraint for this object. - * If a constraint is enabled the systems will not move the object. + * This struct configures the movement constraint for this object. If a constraint is enabled + * the systems will not move the object. */ struct PhysicsConstraints { //! X constraint diff --git a/src/crepe/api/SaveManager.cpp b/src/crepe/api/SaveManager.cpp index 2974b91..c5f43ea 100644 --- a/src/crepe/api/SaveManager.cpp +++ b/src/crepe/api/SaveManager.cpp @@ -139,14 +139,11 @@ ValueBroker<T> SaveManager::get(const string & key, const T & default_value) { } template ValueBroker<uint8_t> SaveManager::get(const string &, const uint8_t &); template ValueBroker<int8_t> SaveManager::get(const string &, const int8_t &); -template ValueBroker<uint16_t> SaveManager::get(const string &, - const uint16_t &); +template ValueBroker<uint16_t> SaveManager::get(const string &, const uint16_t &); template ValueBroker<int16_t> SaveManager::get(const string &, const int16_t &); -template ValueBroker<uint32_t> SaveManager::get(const string &, - const uint32_t &); +template ValueBroker<uint32_t> SaveManager::get(const string &, const uint32_t &); template ValueBroker<int32_t> SaveManager::get(const string &, const int32_t &); -template ValueBroker<uint64_t> SaveManager::get(const string &, - const uint64_t &); +template ValueBroker<uint64_t> SaveManager::get(const string &, const uint64_t &); template ValueBroker<int64_t> SaveManager::get(const string &, const int64_t &); template ValueBroker<float> SaveManager::get(const string &, const float &); template ValueBroker<double> SaveManager::get(const string &, const double &); diff --git a/src/crepe/api/SaveManager.h b/src/crepe/api/SaveManager.h index 4be85fb..3d8c852 100644 --- a/src/crepe/api/SaveManager.h +++ b/src/crepe/api/SaveManager.h @@ -24,7 +24,8 @@ public: * \brief Get a read/write reference to a value and initialize it if it does not yet exist * * \param key The value key - * \param default_value Value to initialize \c key with if it does not already exist in the database + * \param default_value Value to initialize \c key with if it does not already exist in the + * database * * \return Read/write reference to the value */ @@ -38,8 +39,8 @@ public: * * \return Read/write reference to the value * - * \note Attempting to read this value before it is initialized (i.e. set) - * will result in an exception + * \note Attempting to read this value before it is initialized (i.e. set) will result in an + * exception */ template <typename T> ValueBroker<T> get(const std::string & key); @@ -102,8 +103,8 @@ private: * * \returns DB instance * - * This function exists because DB is a facade class, which can't directly be - * used in the API without workarounds + * This function exists because DB is a facade class, which can't directly be used in the API + * without workarounds * * TODO: better solution */ diff --git a/src/crepe/api/Scene.h b/src/crepe/api/Scene.h index 334f306..0e516b6 100644 --- a/src/crepe/api/Scene.h +++ b/src/crepe/api/Scene.h @@ -4,16 +4,19 @@ namespace crepe { +class SceneManager; class ComponentManager; class Scene { -public: +protected: Scene(ComponentManager & mgr, const std::string & name); - virtual ~Scene() = default; + friend class SceneManager; - virtual void load_scene() = 0; +public: + virtual ~Scene() = default; public: + virtual void load_scene() = 0; const std::string name; protected: diff --git a/src/crepe/api/SceneManager.cpp b/src/crepe/api/SceneManager.cpp index 4a38787..7fb5cb0 100644 --- a/src/crepe/api/SceneManager.cpp +++ b/src/crepe/api/SceneManager.cpp @@ -16,11 +16,10 @@ void SceneManager::load_next_scene() { // next scene not set if (this->next_scene.empty()) return; - auto it - = find_if(this->scenes.begin(), this->scenes.end(), - [&next_scene = this->next_scene](unique_ptr<Scene> & scene) { - return scene->name == next_scene; - }); + auto it = find_if(this->scenes.begin(), this->scenes.end(), + [&next_scene = this->next_scene](unique_ptr<Scene> & scene) { + return scene->name == next_scene; + }); // next scene not found if (it == this->scenes.end()) return; diff --git a/src/crepe/api/SceneManager.h b/src/crepe/api/SceneManager.h index 553194f..e854794 100644 --- a/src/crepe/api/SceneManager.h +++ b/src/crepe/api/SceneManager.h @@ -13,7 +13,6 @@ class ComponentManager; class SceneManager { public: SceneManager(ComponentManager & mgr); - virtual ~SceneManager() = default; public: /** @@ -38,8 +37,6 @@ public: private: std::vector<std::unique_ptr<Scene>> scenes; std::string next_scene; - -protected: ComponentManager & component_manager; }; diff --git a/src/crepe/api/Script.cpp b/src/crepe/api/Script.cpp deleted file mode 100644 index 390cec7..0000000 --- a/src/crepe/api/Script.cpp +++ /dev/null @@ -1,3 +0,0 @@ -#include "Script.h" - -using namespace crepe; diff --git a/src/crepe/api/Script.h b/src/crepe/api/Script.h index 68a46d7..2b70379 100644 --- a/src/crepe/api/Script.h +++ b/src/crepe/api/Script.h @@ -2,6 +2,8 @@ #include <vector> +#include "../types.h" + namespace crepe { class ScriptSystem; @@ -11,33 +13,31 @@ class ComponentManager; /** * \brief Script interface * - * This class is used as a base class for user-defined scripts that can be - * added to game objects using the \c BehaviorScript component. + * This class is used as a base class for user-defined scripts that can be added to game + * objects using the \c BehaviorScript component. + * + * \note Additional *events* (like Unity's OnDisable and OnEnable) should be implemented as + * member or lambda methods in derivative user script classes and registered in \c init(). */ class Script { - //! ScriptSystem calls \c update() - friend class crepe::ScriptSystem; - protected: /** * \brief Script initialization function * * This function is called during the ScriptSystem::update() routine *before* - * Script::update() if it (a) has not yet been called and (b) the \c - * BehaviorScript component holding this script instance is active. + * Script::update() if it (a) has not yet been called and (b) the \c BehaviorScript component + * holding this script instance is active. */ virtual void init() {} /** * \brief Script update function * - * This function is called during the ScriptSystem::update() routine if the - * \c BehaviorScript component holding this script instance is active. + * This function is called during the ScriptSystem::update() routine if the \c BehaviorScript + * component holding this script instance is active. */ virtual void update() {} - // NOTE: additional *events* (like unity's OnDisable and OnEnable) should be - // implemented as member methods in derivative user script classes and - // registered in init(), otherwise this class will balloon in size with each - // added event. + //! ScriptSystem calls \c init() and \c update() + friend class crepe::ScriptSystem; protected: /** @@ -47,11 +47,12 @@ protected: * * \returns Reference to component * - * \throws nullptr if this game object does not have a component matching - * type \c T + * \throws nullptr if this game object does not have a component matching type \c T */ template <typename T> T & get_component() const; + // TODO: make get_component calls for component types that can have more than 1 instance + // cause compile-time errors /** * \brief Get all components of type \c T on this game object (utility) @@ -64,18 +65,22 @@ protected: std::vector<std::reference_wrapper<T>> get_components() const; protected: - // NOTE: Script must have a constructor without arguments so the game - // programmer doesn't need to manually add `using Script::Script` to their - // concrete script class. + // NOTE: Script must have a constructor without arguments so the game programmer doesn't need + // to manually add `using Script::Script` to their concrete script class. Script() = default; //! Only \c BehaviorScript instantiates Script friend class BehaviorScript; private: - // These references are set by BehaviorScript immediately after calling the - // constructor of Script. - BehaviorScript * parent_ref = nullptr; + // These references are set by BehaviorScript immediately after calling the constructor of + // Script. + game_object_id_t game_object_id = -1; ComponentManager * component_manager_ref = nullptr; + // TODO: use OptionalRef instead of pointer + +private: + //! Flag to indicate if \c init() has been called already + bool initialized = false; }; } // namespace crepe diff --git a/src/crepe/api/Script.hpp b/src/crepe/api/Script.hpp index aceb38b..a064a90 100644 --- a/src/crepe/api/Script.hpp +++ b/src/crepe/api/Script.hpp @@ -1,7 +1,6 @@ #pragma once #include "../ComponentManager.h" -#include "../Exception.h" #include "BehaviorScript.h" #include "Script.h" @@ -10,21 +9,20 @@ namespace crepe { template <typename T> T & Script::get_component() const { - std::vector<std::reference_wrapper<T>> all_components - = this->get_components<T>(); + using namespace std; + vector<reference_wrapper<T>> all_components = this->get_components<T>(); if (all_components.size() < 1) - throw Exception("Script: no component found with type = {}", - typeid(T).name()); + throw runtime_error( + format("Script: no component found with type = {}", typeid(T).name())); return all_components.back().get(); } template <typename T> std::vector<std::reference_wrapper<T>> Script::get_components() const { - auto & parent = *this->parent_ref; auto & mgr = *this->component_manager_ref; - return mgr.get_components_by_id<T>(parent.game_object_id); + return mgr.get_components_by_id<T>(this->game_object_id); } } // namespace crepe diff --git a/src/crepe/api/Sprite.cpp b/src/crepe/api/Sprite.cpp index ac0079e..bd2d5cf 100644 --- a/src/crepe/api/Sprite.cpp +++ b/src/crepe/api/Sprite.cpp @@ -10,8 +10,8 @@ using namespace std; using namespace crepe; -Sprite::Sprite(game_object_id_t id, const shared_ptr<Texture> image, - const Color & color, const FlipSettings & flip) +Sprite::Sprite(game_object_id_t id, const shared_ptr<Texture> image, const Color & color, + const FlipSettings & flip) : Component(id), color(color), flip(flip), diff --git a/src/crepe/api/Sprite.h b/src/crepe/api/Sprite.h index deb3f93..0192793 100644 --- a/src/crepe/api/Sprite.h +++ b/src/crepe/api/Sprite.h @@ -1,6 +1,5 @@ #pragma once -#include <cstdint> #include <memory> #include "Color.h" @@ -28,8 +27,8 @@ class AnimatorSystem; /** * \brief Represents a renderable sprite component. * - * A renderable sprite that can be displayed in the game. It includes a texture, - * color, and flip settings, and is managed in layers with defined sorting orders. + * A renderable sprite that can be displayed in the game. It includes a texture, color, and + * flip settings, and is managed in layers with defined sorting orders. */ class Sprite : public Component { @@ -43,8 +42,8 @@ public: * \param color Color tint applied to the sprite. * \param flip Flip settings for horizontal and vertical orientation. */ - Sprite(game_object_id_t id, const std::shared_ptr<Texture> image, - const Color & color, const FlipSettings & flip); + Sprite(game_object_id_t id, const std::shared_ptr<Texture> image, const Color & color, + const FlipSettings & flip); /** * \brief Destroys the Sprite instance. @@ -81,7 +80,8 @@ private: //! Reads the all the variables plus the sprite_rect friend class AnimatorSystem; - //! Render area of the sprite this will also be adjusted by the AnimatorSystem if an Animator object is present in GameObject + //! Render area of the sprite this will also be adjusted by the AnimatorSystem if an Animator + // object is present in GameObject Rect sprite_rect; }; diff --git a/src/crepe/api/Texture.h b/src/crepe/api/Texture.h index b89bc17..6965223 100644 --- a/src/crepe/api/Texture.h +++ b/src/crepe/api/Texture.h @@ -1,8 +1,7 @@ #pragma once -// FIXME: this header can't be included because this is an API header, and SDL2 -// development headers won't be bundled with crepe. Why is this facade in the -// API namespace? +// FIXME: this header can't be included because this is an API header, and SDL2 development +// headers won't be bundled with crepe. Why is this facade in the API namespace? #include <SDL2/SDL_render.h> #include <functional> @@ -19,8 +18,8 @@ class Animator; * \class Texture * \brief Manages texture loading and properties. * - * The Texture class is responsible for loading an image from a source - * and providing access to its dimensions. Textures can be used for rendering. + * The Texture class is responsible for loading an image from a source and providing access to + * its dimensions. Textures can be used for rendering. */ class Texture { @@ -41,8 +40,7 @@ public: * \brief Destroys the Texture instance, freeing associated resources. */ ~Texture(); - // FIXME: this constructor shouldn't be necessary because this class doesn't - // manage memory + // FIXME: this constructor shouldn't be necessary because this class doesn't manage memory /** * \brief Gets the width of the texture. diff --git a/src/crepe/api/Transform.cpp b/src/crepe/api/Transform.cpp index e9108c4..cd944bd 100644 --- a/src/crepe/api/Transform.cpp +++ b/src/crepe/api/Transform.cpp @@ -4,8 +4,7 @@ using namespace crepe; -Transform::Transform(game_object_id_t id, const Vector2 & point, - double rotation, double scale) +Transform::Transform(game_object_id_t id, const Vector2 & point, double rotation, double scale) : Component(id), position(point), rotation(rotation), diff --git a/src/crepe/api/Transform.h b/src/crepe/api/Transform.h index 902dafa..18aa293 100644 --- a/src/crepe/api/Transform.h +++ b/src/crepe/api/Transform.h @@ -9,8 +9,8 @@ namespace crepe { /** * \brief Transform component * - * This class represents the Transform component. It stores the position, - * rotation and scale of a GameObject. + * This class represents the Transform component. It stores the position, rotation and scale of + * a GameObject. */ class Transform : public Component { public: @@ -28,9 +28,11 @@ protected: * \param rotation The rotation of the GameObject * \param scale The scale of the GameObject */ - Transform(game_object_id_t id, const Vector2 & point, double rotation = 0, - double scale = 0); - //! There is always exactly one transform component per entity + Transform(game_object_id_t id, const Vector2 & point, double rotation, double scale); + /** + * There is always exactly one transform component per entity + * \return 1 + */ virtual int get_instances_max() const { return 1; } //! ComponentManager instantiates all components friend class ComponentManager; diff --git a/src/crepe/api/Vector2.cpp b/src/crepe/api/Vector2.cpp index 97b74ac..30b968e 100644 --- a/src/crepe/api/Vector2.cpp +++ b/src/crepe/api/Vector2.cpp @@ -2,17 +2,11 @@ using namespace crepe; -Vector2 Vector2::operator-(const Vector2 & other) const { - return {x - other.x, y - other.y}; -} +Vector2 Vector2::operator-(const Vector2 & other) const { return {x - other.x, y - other.y}; } -Vector2 Vector2::operator+(const Vector2 & other) const { - return {x + other.x, y + other.y}; -} +Vector2 Vector2::operator+(const Vector2 & other) const { return {x + other.x, y + other.y}; } -Vector2 Vector2::operator*(double scalar) const { - return {x * scalar, y * scalar}; -} +Vector2 Vector2::operator*(double scalar) const { return {x * scalar, y * scalar}; } Vector2 & Vector2::operator*=(const Vector2 & other) { x *= other.x; @@ -34,10 +28,6 @@ Vector2 & Vector2::operator+=(double other) { Vector2 Vector2::operator-() const { return {-x, -y}; } -bool Vector2::operator==(const Vector2 & other) const { - return x == other.x && y == other.y; -} +bool Vector2::operator==(const Vector2 & other) const { return x == other.x && y == other.y; } -bool Vector2::operator!=(const Vector2 & other) const { - return !(*this == other); -} +bool Vector2::operator!=(const Vector2 & other) const { return !(*this == other); } diff --git a/src/crepe/facade/DB.cpp b/src/crepe/facade/DB.cpp index 80047a6..d5d19dc 100644 --- a/src/crepe/facade/DB.cpp +++ b/src/crepe/facade/DB.cpp @@ -1,6 +1,5 @@ #include <cstring> -#include "Exception.h" #include "util/Log.h" #include "DB.h" @@ -15,18 +14,18 @@ DB::DB(const string & path) { // init database struct libdb::DB * db; if ((ret = libdb::db_create(&db, NULL, 0)) != 0) - throw Exception("db_create: {}", libdb::db_strerror(ret)); + throw runtime_error(format("db_create: {}", libdb::db_strerror(ret))); this->db = {db, [](libdb::DB * db) { db->close(db, 0); }}; // load or create database file - ret = this->db->open(this->db.get(), NULL, path.c_str(), NULL, - libdb::DB_BTREE, DB_CREATE, 0); - if (ret != 0) throw Exception("db->open: {}", libdb::db_strerror(ret)); + ret = this->db->open(this->db.get(), NULL, path.c_str(), NULL, libdb::DB_BTREE, DB_CREATE, + 0); + if (ret != 0) throw runtime_error(format("db->open: {}", libdb::db_strerror(ret))); // create cursor libdb::DBC * cursor; ret = this->db->cursor(this->db.get(), NULL, &cursor, 0); - if (ret != 0) throw Exception("db->cursor: {}", libdb::db_strerror(ret)); + if (ret != 0) throw runtime_error(format("db->cursor: {}", libdb::db_strerror(ret))); this->cursor = {cursor, [](libdb::DBC * cursor) { cursor->close(cursor); }}; } @@ -44,21 +43,24 @@ string DB::get(const string & key) { memset(&db_val, 0, sizeof(libdb::DBT)); int ret = this->cursor->get(this->cursor.get(), &db_key, &db_val, DB_FIRST); - if (ret != 0) throw Exception("cursor->get: {}", libdb::db_strerror(ret)); - return {static_cast<char *>(db_val.data), db_val.size}; + if (ret == 0) return {static_cast<char *>(db_val.data), db_val.size}; + + string err = format("cursor->get: {}", libdb::db_strerror(ret)); + if (ret == DB_NOTFOUND) throw out_of_range(err); + else throw runtime_error(err); } void DB::set(const string & key, const string & value) { libdb::DBT db_key = this->to_thing(key); libdb::DBT db_val = this->to_thing(value); int ret = this->db->put(this->db.get(), NULL, &db_key, &db_val, 0); - if (ret != 0) throw Exception("cursor->get: {}", libdb::db_strerror(ret)); + if (ret != 0) throw runtime_error(format("cursor->get: {}", libdb::db_strerror(ret))); } -bool DB::has(const std::string & key) noexcept { +bool DB::has(const std::string & key) { try { this->get(key); - } catch (...) { + } catch (std::out_of_range &) { return false; } return true; diff --git a/src/crepe/facade/DB.h b/src/crepe/facade/DB.h index 7c757a2..629b0eb 100644 --- a/src/crepe/facade/DB.h +++ b/src/crepe/facade/DB.h @@ -15,8 +15,8 @@ namespace crepe { /** * \brief Berkeley DB facade * - * Berkeley DB is a simple key-value database that stores arbitrary data as - * both key and value. This facade uses STL strings as keys/values. + * Berkeley DB is a simple key-value database that stores arbitrary data as both key and value. + * This facade uses STL strings as keys/values. */ class DB { public: @@ -34,7 +34,8 @@ public: * * \return The value * - * \throws Exception if value is not found in DB or other error occurs + * \throws std::out_of_range if value is not found in DB + * \throws std::runtime_error if other error occurs */ std::string get(const std::string & key); /** @@ -43,7 +44,7 @@ public: * \param key The value key * \param value The value to store * - * \throws Exception if an error occurs + * \throws std::runtime_error if an error occurs */ void set(const std::string & key, const std::string & value); /** @@ -53,7 +54,7 @@ public: * * \returns True if the key exists, or false if it does not */ - bool has(const std::string & key) noexcept; + bool has(const std::string & key); private: //! RAII wrapper around \c DB struct diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index 5527803..f2daada 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -10,17 +10,16 @@ #include <iostream> #include <memory> #include <string> -#include <utility> #include "../api/Sprite.h" #include "../api/Texture.h" #include "../api/Transform.h" #include "../util/Log.h" -#include "Exception.h" #include "SDLContext.h" using namespace crepe; +using namespace std; SDLContext & SDLContext::get_instance() { static SDLContext instance; @@ -33,41 +32,37 @@ SDLContext::SDLContext() { if (SDL_Init(SDL_INIT_VIDEO) < 0) { // FIXME: throw exception - std::cerr << "SDL could not initialize! SDL_Error: " << SDL_GetError() - << std::endl; + std::cerr << "SDL could not initialize! SDL_Error: " << SDL_GetError() << std::endl; return; } - SDL_Window * tmp_window = SDL_CreateWindow( - "Crepe Game Engine", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, - this->viewport.w, this->viewport.h, 0); + SDL_Window * tmp_window + = SDL_CreateWindow("Crepe Game Engine", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, + this->viewport.w, this->viewport.h, 0); if (!tmp_window) { // FIXME: throw exception - std::cerr << "Window could not be created! SDL_Error: " - << SDL_GetError() << std::endl; + std::cerr << "Window could not be created! SDL_Error: " << SDL_GetError() << std::endl; return; } - this->game_window - = {tmp_window, [](SDL_Window * window) { SDL_DestroyWindow(window); }}; + this->game_window = {tmp_window, [](SDL_Window * window) { SDL_DestroyWindow(window); }}; - SDL_Renderer * tmp_renderer = SDL_CreateRenderer( - this->game_window.get(), -1, SDL_RENDERER_ACCELERATED); + SDL_Renderer * tmp_renderer + = SDL_CreateRenderer(this->game_window.get(), -1, SDL_RENDERER_ACCELERATED); if (!tmp_renderer) { // FIXME: throw exception - std::cerr << "Renderer could not be created! SDL_Error: " - << SDL_GetError() << std::endl; + std::cerr << "Renderer could not be created! SDL_Error: " << SDL_GetError() + << std::endl; SDL_DestroyWindow(this->game_window.get()); return; } - this->game_renderer = {tmp_renderer, [](SDL_Renderer * renderer) { - SDL_DestroyRenderer(renderer); - }}; + this->game_renderer + = {tmp_renderer, [](SDL_Renderer * renderer) { SDL_DestroyRenderer(renderer); }}; int img_flags = IMG_INIT_PNG; if (!(IMG_Init(img_flags) & img_flags)) { // FIXME: throw exception - std::cout << "SDL_image could not initialize! SDL_image Error: " - << IMG_GetError() << std::endl; + std::cout << "SDL_image could not initialize! SDL_image Error: " << IMG_GetError() + << std::endl; } } @@ -106,12 +101,9 @@ void SDLContext::handle_events(bool & running) { } void SDLContext::clear_screen() { SDL_RenderClear(this->game_renderer.get()); } -void SDLContext::present_screen() { - SDL_RenderPresent(this->game_renderer.get()); -} +void SDLContext::present_screen() { SDL_RenderPresent(this->game_renderer.get()); } -void SDLContext::draw(const Sprite & sprite, const Transform & transform, - const Camera & cam) { +void SDLContext::draw(const Sprite & sprite, const Transform & transform, const Camera & cam) { SDL_RendererFlip render_flip = (SDL_RendererFlip) ((SDL_FLIP_HORIZONTAL * sprite.flip.flip_x) @@ -136,9 +128,7 @@ void SDLContext::draw(const Sprite & sprite, const Transform & transform, .h = static_cast<int>(adjusted_h), }; - SDL_RenderCopyEx(this->game_renderer.get(), - sprite.sprite_image->texture.get(), &srcrect, - + SDL_RenderCopyEx(this->game_renderer.get(), sprite.sprite_image->texture.get(), &srcrect, &dstrect, transform.rotation, NULL, render_flip); } @@ -148,8 +138,8 @@ void SDLContext::camera(const Camera & cam) { this->viewport.x = static_cast<int>(cam.x) - (SCREEN_WIDTH / 2); this->viewport.y = static_cast<int>(cam.y) - (SCREEN_HEIGHT / 2); - SDL_SetRenderDrawColor(this->game_renderer.get(), cam.bg_color.r, - cam.bg_color.g, cam.bg_color.b, cam.bg_color.a); + SDL_SetRenderDrawColor(this->game_renderer.get(), cam.bg_color.r, cam.bg_color.g, + cam.bg_color.b, cam.bg_color.a); } uint64_t SDLContext::get_ticks() const { return SDL_GetTicks64(); } @@ -162,22 +152,18 @@ SDLContext::texture_from_path(const std::string & path) { tmp = IMG_Load("asset/texture/ERROR.png"); } - std::unique_ptr<SDL_Surface, std::function<void(SDL_Surface *)>> - img_surface; - img_surface - = {tmp, [](SDL_Surface * surface) { SDL_FreeSurface(surface); }}; + std::unique_ptr<SDL_Surface, std::function<void(SDL_Surface *)>> img_surface; + img_surface = {tmp, [](SDL_Surface * surface) { SDL_FreeSurface(surface); }}; - SDL_Texture * tmp_texture = SDL_CreateTextureFromSurface( - this->game_renderer.get(), img_surface.get()); + SDL_Texture * tmp_texture + = SDL_CreateTextureFromSurface(this->game_renderer.get(), img_surface.get()); if (tmp_texture == nullptr) { - throw Exception("Texture cannot be load from {}", path); + throw runtime_error(format("Texture cannot be load from {}", path)); } - std::unique_ptr<SDL_Texture, std::function<void(SDL_Texture *)>> - img_texture; - img_texture = {tmp_texture, - [](SDL_Texture * texture) { SDL_DestroyTexture(texture); }}; + std::unique_ptr<SDL_Texture, std::function<void(SDL_Texture *)>> img_texture; + img_texture = {tmp_texture, [](SDL_Texture * texture) { SDL_DestroyTexture(texture); }}; return img_texture; } diff --git a/src/crepe/facade/SDLContext.h b/src/crepe/facade/SDLContext.h index 536dec5..007092b 100644 --- a/src/crepe/facade/SDLContext.h +++ b/src/crepe/facade/SDLContext.h @@ -17,9 +17,8 @@ const int SCREEN_HEIGHT = 480; namespace crepe { -// TODO: SDL_Keycode is defined in a header not distributed with crepe, which -// means this typedef is unusable when crepe is packaged. Wouter will fix this -// later. +// TODO: SDL_Keycode is defined in a header not distributed with crepe, which means this +// typedef is unusable when crepe is packaged. Wouter will fix this later. typedef SDL_Keycode CREPE_KEYCODES; class Texture; @@ -29,8 +28,8 @@ class LoopManager; * \class SDLContext * \brief Facade for the SDL library * - * SDLContext is a singleton that handles the SDL window and renderer, provides methods - * for event handling, and rendering to the screen. It is never used directly by the user + * SDLContext is a singleton that handles the SDL window and renderer, provides methods for + * event handling, and rendering to the screen. It is never used directly by the user */ class SDLContext { @@ -68,9 +67,8 @@ private: /** * \brief Pauses the execution for a specified duration. * - * This function uses SDL's delay function to halt the program execution - * for a given number of milliseconds, allowing for frame rate control - * or other timing-related functionality. + * This function uses SDL's delay function to halt the program execution for a given number + * of milliseconds, allowing for frame rate control or other timing-related functionality. * * \param ms Duration of the delay in milliseconds. */ @@ -127,8 +125,7 @@ private: * \param transform Reference to the Transform for positioning. * \param camera Reference to the Camera for view adjustments. */ - void draw(const Sprite & sprite, const Transform & transform, - const Camera & camera); + void draw(const Sprite & sprite, const Transform & transform, const Camera & camera); //! Clears the screen, preparing for a new frame. void clear_screen(); @@ -147,8 +144,7 @@ private: std::unique_ptr<SDL_Window, std::function<void(SDL_Window *)>> game_window; //! renderer for the crepe engine - std::unique_ptr<SDL_Renderer, std::function<void(SDL_Renderer *)>> - game_renderer; + std::unique_ptr<SDL_Renderer, std::function<void(SDL_Renderer *)>> game_renderer; //! viewport for the camera window SDL_Rect viewport = {0, 0, 640, 480}; diff --git a/src/crepe/facade/Sound.h b/src/crepe/facade/Sound.h index 94b1996..a84aa8c 100644 --- a/src/crepe/facade/Sound.h +++ b/src/crepe/facade/Sound.h @@ -23,29 +23,26 @@ public: /** * \brief Pause this sample * - * Pauses this sound if it is playing, or does nothing if it is already - * paused. The playhead position is saved, such that calling \c play() after - * this function makes the sound resume. + * Pauses this sound if it is playing, or does nothing if it is already paused. The playhead + * position is saved, such that calling \c play() after this function makes the sound resume. */ void pause(); /** * \brief Play this sample * - * Resume playback if this sound is paused, or start from the beginning of - * the sample. + * Resume playback if this sound is paused, or start from the beginning of the sample. * - * \note This class only saves a reference to the most recent 'voice' of this - * sound. Calling \c play() while the sound is already playing causes - * multiple instances of the sample to play simultaniously. The sample - * started last is the one that is controlled afterwards. + * \note This class only saves a reference to the most recent 'voice' of this sound. Calling + * \c play() while the sound is already playing causes multiple instances of the sample to + * play simultaniously. The sample started last is the one that is controlled afterwards. */ void play(); /** * \brief Reset playhead position * - * Resets the playhead position so that calling \c play() after this function - * makes it play from the start of the sample. If the sound is not paused - * before calling this function, this function will stop playback. + * Resets the playhead position so that calling \c play() after this function makes it play + * from the start of the sample. If the sound is not paused before calling this function, + * this function will stop playback. */ void rewind(); /** diff --git a/src/crepe/system/AnimatorSystem.h b/src/crepe/system/AnimatorSystem.h index aa97084..56cc7b3 100644 --- a/src/crepe/system/AnimatorSystem.h +++ b/src/crepe/system/AnimatorSystem.h @@ -22,7 +22,8 @@ public: * \brief Updates the Animator components. * * This method is called periodically (likely every frame) to update the state of all - * Animator components, moving the animations forward and managing their behavior (e.g., looping). + * Animator components, moving the animations forward and managing their behavior (e.g., + * looping). */ void update() override; // FIXME: never say "likely" in the documentation lmao diff --git a/src/crepe/system/ParticleSystem.cpp b/src/crepe/system/ParticleSystem.cpp index 33db52e..7316309 100644 --- a/src/crepe/system/ParticleSystem.cpp +++ b/src/crepe/system/ParticleSystem.cpp @@ -20,13 +20,10 @@ void ParticleSystem::update() { for (ParticleEmitter & emitter : emitters) { // Get transform linked to emitter const Transform & transform - = mgr.get_components_by_id<Transform>(emitter.game_object_id) - .front() - .get(); + = mgr.get_components_by_id<Transform>(emitter.game_object_id).front().get(); // Emit particles based on emission_rate - int updates - = calculate_update(this->update_count, emitter.data.emission_rate); + int updates = calculate_update(this->update_count, emitter.data.emission_rate); for (size_t i = 0; i < updates; i++) { emit_particle(emitter, transform); } @@ -45,8 +42,7 @@ void ParticleSystem::update() { this->update_count = (this->update_count + 1) % this->MAX_UPDATE_COUNT; } -void ParticleSystem::emit_particle(ParticleEmitter & emitter, - const Transform & transform) { +void ParticleSystem::emit_particle(ParticleEmitter & emitter, const Transform & transform) { constexpr double DEG_TO_RAD = M_PI / 180.0; Vector2 initial_position = emitter.data.position + transform.position; @@ -57,13 +53,13 @@ void ParticleSystem::emit_particle(ParticleEmitter & emitter, = generate_random_speed(emitter.data.min_speed, emitter.data.max_speed); double angle_radians = random_angle * DEG_TO_RAD; - Vector2 velocity = {random_speed * std::cos(angle_radians), - random_speed * std::sin(angle_radians)}; + Vector2 velocity + = {random_speed * std::cos(angle_radians), random_speed * std::sin(angle_radians)}; for (Particle & particle : emitter.data.particles) { if (!particle.active) { - particle.reset(emitter.data.end_lifespan, initial_position, - velocity, random_angle); + particle.reset(emitter.data.end_lifespan, initial_position, velocity, + random_angle); break; } } @@ -81,10 +77,8 @@ int ParticleSystem::calculate_update(int count, double emission) const { return static_cast<int>(emission); } -void ParticleSystem::check_bounds(ParticleEmitter & emitter, - const Transform & transform) { - Vector2 offset = emitter.data.boundary.offset + transform.position - + emitter.data.position; +void ParticleSystem::check_bounds(ParticleEmitter & emitter, const Transform & transform) { + Vector2 offset = emitter.data.boundary.offset + transform.position + emitter.data.position; double half_width = emitter.data.boundary.width / 2.0; double half_height = emitter.data.boundary.height / 2.0; @@ -95,8 +89,8 @@ void ParticleSystem::check_bounds(ParticleEmitter & emitter, for (Particle & particle : emitter.data.particles) { const Vector2 & position = particle.position; - bool within_bounds = (position.x >= LEFT && position.x <= RIGHT - && position.y >= TOP && position.y <= BOTTOM); + bool within_bounds = (position.x >= LEFT && position.x <= RIGHT && position.y >= TOP + && position.y <= BOTTOM); if (!within_bounds) { if (emitter.data.boundary.reset_on_exit) { @@ -112,30 +106,25 @@ void ParticleSystem::check_bounds(ParticleEmitter & emitter, } } -double ParticleSystem::generate_random_angle(double min_angle, - double max_angle) const { +double ParticleSystem::generate_random_angle(double min_angle, double max_angle) const { if (min_angle == max_angle) { return min_angle; } else if (min_angle < max_angle) { return min_angle - + static_cast<double>(std::rand() - % static_cast<int>(max_angle - min_angle)); + + static_cast<double>(std::rand() % static_cast<int>(max_angle - min_angle)); } else { double angle_offset = (360 - min_angle) + max_angle; - double random_angle = min_angle - + static_cast<double>( - std::rand() % static_cast<int>(angle_offset)); + double random_angle + = min_angle + static_cast<double>(std::rand() % static_cast<int>(angle_offset)); return (random_angle >= 360) ? random_angle - 360 : random_angle; } } -double ParticleSystem::generate_random_speed(double min_speed, - double max_speed) const { +double ParticleSystem::generate_random_speed(double min_speed, double max_speed) const { if (min_speed == max_speed) { return min_speed; } else { return min_speed - + static_cast<double>(std::rand() - % static_cast<int>(max_speed - min_speed)); + + static_cast<double>(std::rand() % static_cast<int>(max_speed - min_speed)); } } diff --git a/src/crepe/system/ParticleSystem.h b/src/crepe/system/ParticleSystem.h index 0acc2b9..c647284 100644 --- a/src/crepe/system/ParticleSystem.h +++ b/src/crepe/system/ParticleSystem.h @@ -4,40 +4,36 @@ #include "System.h" -#include "System.h" - namespace crepe { class ParticleEmitter; class Transform; /** - * \brief ParticleSystem class responsible for managing particle emission, - * updates, and bounds checking. - */ + * \brief ParticleSystem class responsible for managing particle emission, updates, and bounds + * checking. + */ class ParticleSystem : public System { public: using System::System; /** - * \brief Updates all particle emitters by emitting particles, updating - * particle states, and checking bounds. + * \brief Updates all particle emitters by emitting particles, updating particle states, and + * checking bounds. */ void update() override; private: /** - * \brief Emits a particle from the specified emitter based on its emission - * properties. + * \brief Emits a particle from the specified emitter based on its emission properties. * * \param emitter Reference to the ParticleEmitter. - * \param transform Const reference to the Transform component associated - * with the emitter. + * \param transform Const reference to the Transform component associated with the emitter. */ void emit_particle(ParticleEmitter & emitter, const Transform & transform); /** - * \brief Calculates the number of times particles should be emitted based on - * emission rate and update count. + * \brief Calculates the number of times particles should be emitted based on emission rate + * and update count. * * \param count Current update count. * \param emission Emission rate. @@ -46,18 +42,16 @@ private: int calculate_update(int count, double emission) const; /** - * \brief Checks whether particles are within the emitter’s boundary, resets - * or stops particles if they exit. + * \brief Checks whether particles are within the emitter’s boundary, resets or stops + * particles if they exit. * * \param emitter Reference to the ParticleEmitter. - * \param transform Const reference to the Transform component associated - * with the emitter. + * \param transform Const reference to the Transform component associated with the emitter. */ void check_bounds(ParticleEmitter & emitter, const Transform & transform); /** - * \brief Generates a random angle for particle emission within the specified - * range. + * \brief Generates a random angle for particle emission within the specified range. * * \param min_angle Minimum emission angle in degrees. * \param max_angle Maximum emission angle in degrees. @@ -66,8 +60,7 @@ private: double generate_random_angle(double min_angle, double max_angle) const; /** - * \brief Generates a random speed for particle emission within the specified - * range. + * \brief Generates a random speed for particle emission within the specified range. * * \param min_speed Minimum emission speed. * \param max_speed Maximum emission speed. @@ -79,8 +72,8 @@ private: //! Counter to count updates to determine how many times emit_particle is // called. unsigned int update_count = 0; - //! Determines the lowest amount of emission rate (1000 = 0.001 = 1 particle - // per 1000 updates). + //! Determines the lowest amount of emission rate (1000 = 0.001 = 1 particle per 1000 + // updates). static constexpr unsigned int MAX_UPDATE_COUNT = 100; }; diff --git a/src/crepe/system/PhysicsSystem.cpp b/src/crepe/system/PhysicsSystem.cpp index da79707..4a7dbfb 100644 --- a/src/crepe/system/PhysicsSystem.cpp +++ b/src/crepe/system/PhysicsSystem.cpp @@ -29,17 +29,15 @@ void PhysicsSystem::update() { // Add gravity if (rigidbody.data.use_gravity) { rigidbody.data.linear_velocity.y - += (rigidbody.data.mass - * rigidbody.data.gravity_scale * gravity); + += (rigidbody.data.mass * rigidbody.data.gravity_scale + * gravity); } // Add damping if (rigidbody.data.angular_damping != 0) { - rigidbody.data.angular_velocity - *= rigidbody.data.angular_damping; + rigidbody.data.angular_velocity *= rigidbody.data.angular_damping; } if (rigidbody.data.linear_damping != Vector2{0, 0}) { - rigidbody.data.linear_velocity - *= rigidbody.data.linear_damping; + rigidbody.data.linear_velocity *= rigidbody.data.linear_damping; } // Max velocity check @@ -75,21 +73,17 @@ void PhysicsSystem::update() { // Move object if (!rigidbody.data.constraints.rotation) { - transform.rotation - += rigidbody.data.angular_velocity; - transform.rotation - = std::fmod(transform.rotation, 360.0); + transform.rotation += rigidbody.data.angular_velocity; + transform.rotation = std::fmod(transform.rotation, 360.0); if (transform.rotation < 0) { transform.rotation += 360.0; } } if (!rigidbody.data.constraints.x) { - transform.position.x - += rigidbody.data.linear_velocity.x; + transform.position.x += rigidbody.data.linear_velocity.x; } if (!rigidbody.data.constraints.y) { - transform.position.y - += rigidbody.data.linear_velocity.y; + transform.position.y += rigidbody.data.linear_velocity.y; } } } diff --git a/src/crepe/system/PhysicsSystem.h b/src/crepe/system/PhysicsSystem.h index 5433a0f..227ab69 100644 --- a/src/crepe/system/PhysicsSystem.h +++ b/src/crepe/system/PhysicsSystem.h @@ -7,8 +7,8 @@ namespace crepe { /** * \brief System that controls all physics * - * This class is a physics system that uses a rigidbody and transform - * to add physics to a game object. + * This class is a physics system that uses a rigidbody and transform to add physics to a game + * object. */ class PhysicsSystem : public System { public: diff --git a/src/crepe/system/RenderSystem.cpp b/src/crepe/system/RenderSystem.cpp index 0d37808..fa3d0de 100644 --- a/src/crepe/system/RenderSystem.cpp +++ b/src/crepe/system/RenderSystem.cpp @@ -11,18 +11,13 @@ using namespace crepe; -void RenderSystem::clear_screen() const { - SDLContext::get_instance().clear_screen(); -} +void RenderSystem::clear_screen() const { SDLContext::get_instance().clear_screen(); } -void RenderSystem::present_screen() const { - SDLContext::get_instance().present_screen(); -} +void RenderSystem::present_screen() const { SDLContext::get_instance().present_screen(); } void RenderSystem::update_camera() { ComponentManager & mgr = this->component_manager; - std::vector<std::reference_wrapper<Camera>> cameras - = mgr.get_components_by_type<Camera>(); + std::vector<std::reference_wrapper<Camera>> cameras = mgr.get_components_by_type<Camera>(); for (Camera & cam : cameras) { SDLContext::get_instance().camera(cam); @@ -32,13 +27,11 @@ void RenderSystem::update_camera() { void RenderSystem::render_sprites() const { ComponentManager & mgr = this->component_manager; - std::vector<std::reference_wrapper<Sprite>> sprites - = mgr.get_components_by_type<Sprite>(); + std::vector<std::reference_wrapper<Sprite>> sprites = mgr.get_components_by_type<Sprite>(); SDLContext & render = SDLContext::get_instance(); for (const Sprite & sprite : sprites) { - auto transforms - = mgr.get_components_by_id<Transform>(sprite.game_object_id); + auto transforms = mgr.get_components_by_id<Transform>(sprite.game_object_id); render.draw(sprite, transforms[0], *curr_cam); } } diff --git a/src/crepe/system/RenderSystem.h b/src/crepe/system/RenderSystem.h index da4e910..87ec494 100644 --- a/src/crepe/system/RenderSystem.h +++ b/src/crepe/system/RenderSystem.h @@ -10,9 +10,9 @@ namespace crepe { * \class RenderSystem * \brief Manages rendering operations for all game objects. * - * RenderSystem is responsible for rendering sprites, clearing and presenting the screen, - * and managing the active camera. It functions as a singleton, providing centralized - * rendering services for the application. + * RenderSystem is responsible for rendering sprites, clearing and presenting the screen, and + * managing the active camera. It functions as a singleton, providing centralized rendering + * services for the application. */ class RenderSystem : public System { public: diff --git a/src/crepe/system/ScriptSystem.cpp b/src/crepe/system/ScriptSystem.cpp index f4a826b..c4d724c 100644 --- a/src/crepe/system/ScriptSystem.cpp +++ b/src/crepe/system/ScriptSystem.cpp @@ -18,10 +18,9 @@ void ScriptSystem::update() { for (auto & script_ref : scripts) { Script & script = script_ref.get(); - BehaviorScript & component = *script.parent_ref; - if (!component.initialized) { + if (!script.initialized) { script.init(); - component.initialized = true; + script.initialized = true; } script.update(); } diff --git a/src/crepe/util/Log.cpp b/src/crepe/util/Log.cpp index e583734..84d80a8 100644 --- a/src/crepe/util/Log.cpp +++ b/src/crepe/util/Log.cpp @@ -1,9 +1,8 @@ -#include <cstdarg> -#include <cstdio> -#include <cstdlib> +#include <iostream> #include <string> #include "../api/Config.h" + #include "Log.h" using namespace crepe; @@ -33,6 +32,6 @@ void Log::log(const Level & level, const string & msg) { if (!out.ends_with("\n")) out += "\n"; // TODO: also log to file or smth - fwrite(out.c_str(), 1, out.size(), stdout); - fflush(stdout); + cout.write(out.data(), out.size()); + cout.flush(); } diff --git a/src/crepe/util/Log.h b/src/crepe/util/Log.h index 01452b2..d55b11e 100644 --- a/src/crepe/util/Log.h +++ b/src/crepe/util/Log.h @@ -9,16 +9,14 @@ // utility macros #define _crepe_logf_here(level, fmt, ...) \ - crepe::Log::logf( \ - level, "{}" fmt, \ - crepe::LogColor().fg_white(false).str(std::format( \ - "{} ({}:{})", __PRETTY_FUNCTION__, __FILE_NAME__, __LINE__)), \ - __VA_ARGS__) + crepe::Log::logf(level, "{}" fmt, \ + crepe::LogColor().fg_white(false).str(std::format( \ + "{} ({}:{})", __PRETTY_FUNCTION__, __FILE_NAME__, __LINE__)), \ + __VA_ARGS__) // very illegal global function-style macros // NOLINTBEGIN -#define dbg_logf(fmt, ...) \ - _crepe_logf_here(crepe::Log::Level::DEBUG, ": " fmt, __VA_ARGS__) +#define dbg_logf(fmt, ...) _crepe_logf_here(crepe::Log::Level::DEBUG, ": " fmt, __VA_ARGS__) #define dbg_log(str) _crepe_logf_here(crepe::Log::Level::DEBUG, ": {}", str) #define dbg_trace() _crepe_logf_here(crepe::Log::Level::TRACE, "", "") // NOLINTEND @@ -59,8 +57,7 @@ public: * \param args Format arguments */ template <class... Args> - static void logf(const Level & level, std::format_string<Args...> fmt, - Args &&... args); + static void logf(const Level & level, std::format_string<Args...> fmt, Args &&... args); /** * \brief Format a message and log it (with default severity \c INFO) @@ -76,6 +73,8 @@ private: * \brief Output a message prefix depending on the log level * * \param level Message severity + * + * \return Colored message severity prefix string */ static std::string prefix(const Level & level); }; diff --git a/src/crepe/util/Log.hpp b/src/crepe/util/Log.hpp index 651f076..c2156cd 100644 --- a/src/crepe/util/Log.hpp +++ b/src/crepe/util/Log.hpp @@ -10,8 +10,7 @@ void Log::logf(std::format_string<Args...> fmt, Args &&... args) { } template <class... Args> -void Log::logf(const Level & level, std::format_string<Args...> fmt, - Args &&... args) { +void Log::logf(const Level & level, std::format_string<Args...> fmt, Args &&... args) { Log::log(level, std::format(fmt, std::forward<Args>(args)...)); } diff --git a/src/crepe/util/LogColor.cpp b/src/crepe/util/LogColor.cpp index ae44d72..5411898 100644 --- a/src/crepe/util/LogColor.cpp +++ b/src/crepe/util/LogColor.cpp @@ -1,6 +1,7 @@ #include <cstdarg> #include "../api/Config.h" + #include "LogColor.h" using namespace crepe; @@ -27,51 +28,19 @@ LogColor & LogColor::reset() { return *this; } -LogColor & LogColor::fg_black(bool bright) { - return this->add_code(bright ? 90 : 30); -} -LogColor & LogColor::fg_red(bool bright) { - return this->add_code(bright ? 91 : 31); -} -LogColor & LogColor::fg_green(bool bright) { - return this->add_code(bright ? 92 : 32); -} -LogColor & LogColor::fg_yellow(bool bright) { - return this->add_code(bright ? 93 : 33); -} -LogColor & LogColor::fg_blue(bool bright) { - return this->add_code(bright ? 94 : 34); -} -LogColor & LogColor::fg_magenta(bool bright) { - return this->add_code(bright ? 95 : 35); -} -LogColor & LogColor::fg_cyan(bool bright) { - return this->add_code(bright ? 96 : 36); -} -LogColor & LogColor::fg_white(bool bright) { - return this->add_code(bright ? 97 : 37); -} -LogColor & LogColor::bg_black(bool bright) { - return this->add_code(bright ? 100 : 40); -} -LogColor & LogColor::bg_red(bool bright) { - return this->add_code(bright ? 101 : 41); -} -LogColor & LogColor::bg_green(bool bright) { - return this->add_code(bright ? 102 : 42); -} -LogColor & LogColor::bg_yellow(bool bright) { - return this->add_code(bright ? 103 : 43); -} -LogColor & LogColor::bg_blue(bool bright) { - return this->add_code(bright ? 104 : 44); -} -LogColor & LogColor::bg_magenta(bool bright) { - return this->add_code(bright ? 105 : 45); -} -LogColor & LogColor::bg_cyan(bool bright) { - return this->add_code(bright ? 106 : 46); -} -LogColor & LogColor::bg_white(bool bright) { - return this->add_code(bright ? 107 : 47); -} +LogColor & LogColor::fg_black(bool bright) { return this->add_code(bright ? 90 : 30); } +LogColor & LogColor::fg_red(bool bright) { return this->add_code(bright ? 91 : 31); } +LogColor & LogColor::fg_green(bool bright) { return this->add_code(bright ? 92 : 32); } +LogColor & LogColor::fg_yellow(bool bright) { return this->add_code(bright ? 93 : 33); } +LogColor & LogColor::fg_blue(bool bright) { return this->add_code(bright ? 94 : 34); } +LogColor & LogColor::fg_magenta(bool bright) { return this->add_code(bright ? 95 : 35); } +LogColor & LogColor::fg_cyan(bool bright) { return this->add_code(bright ? 96 : 36); } +LogColor & LogColor::fg_white(bool bright) { return this->add_code(bright ? 97 : 37); } +LogColor & LogColor::bg_black(bool bright) { return this->add_code(bright ? 100 : 40); } +LogColor & LogColor::bg_red(bool bright) { return this->add_code(bright ? 101 : 41); } +LogColor & LogColor::bg_green(bool bright) { return this->add_code(bright ? 102 : 42); } +LogColor & LogColor::bg_yellow(bool bright) { return this->add_code(bright ? 103 : 43); } +LogColor & LogColor::bg_blue(bool bright) { return this->add_code(bright ? 104 : 44); } +LogColor & LogColor::bg_magenta(bool bright) { return this->add_code(bright ? 105 : 45); } +LogColor & LogColor::bg_cyan(bool bright) { return this->add_code(bright ? 106 : 46); } +LogColor & LogColor::bg_white(bool bright) { return this->add_code(bright ? 107 : 47); } diff --git a/src/crepe/util/LogColor.h b/src/crepe/util/LogColor.h index 4b65127..132fb94 100644 --- a/src/crepe/util/LogColor.h +++ b/src/crepe/util/LogColor.h @@ -12,7 +12,13 @@ namespace crepe { */ class LogColor { public: - //! Get color code as stl string (or color content string) + /** + * \brief Get color code as STL string + * + * \param content If given, color this string and append a color reset escape sequence. + * + * \returns Color escape sequence + */ const std::string str(const std::string & content = "") const; public: @@ -20,6 +26,13 @@ public: LogColor & reset(); public: + /** + * \name Foreground colors + * + * These functions set the foreground (text) color. The \c bright parameter + * makes the color brighter, or bold on some terminals. + * \{ + */ LogColor & fg_black(bool bright = false); LogColor & fg_red(bool bright = false); LogColor & fg_green(bool bright = false); @@ -28,8 +41,16 @@ public: LogColor & fg_magenta(bool bright = false); LogColor & fg_cyan(bool bright = false); LogColor & fg_white(bool bright = false); + /// \} public: + /** + * \name Background colors + * + * These functions set the background color. The \c bright parameter makes + * the color brighter. + * \{ + */ LogColor & bg_black(bool bright = false); LogColor & bg_red(bool bright = false); LogColor & bg_green(bool bright = false); @@ -38,6 +59,7 @@ public: LogColor & bg_magenta(bool bright = false); LogColor & bg_cyan(bool bright = false); LogColor & bg_white(bool bright = false); + /// \} private: /** diff --git a/src/crepe/util/Proxy.h b/src/crepe/util/Proxy.h index f84e462..b34f7c6 100644 --- a/src/crepe/util/Proxy.h +++ b/src/crepe/util/Proxy.h @@ -7,8 +7,8 @@ namespace crepe { /** * \brief Utility wrapper for \c ValueBroker * - * This class can be used to to wrap a ValueBroker instance so it behaves like - * a regular variable. + * This class can be used to to wrap a ValueBroker instance so it behaves like a regular + * variable. * * \tparam T Type of the underlying variable */ diff --git a/src/example/asset_manager.cpp b/src/example/asset_manager.cpp index a2ca8c3..660b318 100644 --- a/src/example/asset_manager.cpp +++ b/src/example/asset_manager.cpp @@ -6,18 +6,17 @@ using namespace crepe; int main() { - // this needs to be called before the asset manager otherwise the destructor - // of sdl is not in the right order + // this needs to be called before the asset manager otherwise the destructor of sdl is not in + // the right order { Texture test("asset/texture/img.png"); } - // FIXME: make it so the issue described by the above comment is not possible - // (i.e. the order in which internal classes are instantiated should not - // impact the way the engine works). + // FIXME: make it so the issue described by the above comment is not possible (i.e. the order + // in which internal classes are instantiated should not impact the way the engine works). auto & mgr = AssetManager::get_instance(); { - // TODO: [design] the Sound class can't be directly included by the user as - // it includes SoLoud headers. + // TODO: [design] the Sound class can't be directly included by the user as it includes + // SoLoud headers. auto bgm = mgr.cache<Sound>("mwe/audio/bgm.ogg"); auto sfx1 = mgr.cache<Sound>("mwe/audio/sfx1.wav"); auto sfx2 = mgr.cache<Sound>("mwe/audio/sfx2.wav"); diff --git a/src/example/audio_internal.cpp b/src/example/audio_internal.cpp index 9b60e6b..e23d485 100644 --- a/src/example/audio_internal.cpp +++ b/src/example/audio_internal.cpp @@ -42,8 +42,7 @@ int main() { // Start the background track bgm.play(); - // Play each sample sequentially while pausing and resuming the background - // track + // Play each sample sequentially while pausing and resuming the background track this_thread::sleep_for(500ms); sfx1.play(); this_thread::sleep_for(500ms); diff --git a/src/example/components_internal.cpp b/src/example/components_internal.cpp index eeecdc0..2a232a9 100644 --- a/src/example/components_internal.cpp +++ b/src/example/components_internal.cpp @@ -27,8 +27,6 @@ int main() { auto start_adding = chrono::high_resolution_clock::now(); - GameObject * game_object[OBJ_COUNT]; - for (int i = 0; i < OBJ_COUNT; ++i) { GameObject obj = mgr.new_object("Name", "Tag"); obj.add_component<Sprite>("test"); @@ -44,10 +42,8 @@ int main() { auto stop_looping = chrono::high_resolution_clock::now(); - auto add_time = chrono::duration_cast<chrono::microseconds>(stop_adding - - start_adding); - auto loop_time = chrono::duration_cast<chrono::microseconds>(stop_looping - - stop_adding); + auto add_time = chrono::duration_cast<chrono::microseconds>(stop_adding - start_adding); + auto loop_time = chrono::duration_cast<chrono::microseconds>(stop_looping - stop_adding); printf("add time: %ldus\n", add_time.count()); printf("loop time: %ldus\n", loop_time.count()); diff --git a/src/example/ecs.cpp b/src/example/ecs.cpp index 5f83da1..d5ba51b 100644 --- a/src/example/ecs.cpp +++ b/src/example/ecs.cpp @@ -14,14 +14,10 @@ int main() { // Create a few GameObjects try { GameObject body = mgr.new_object("body", "person", Vector2{0, 0}, 0, 1); - GameObject right_leg - = mgr.new_object("rightLeg", "person", Vector2{1, 1}, 0, 1); - GameObject left_leg - = mgr.new_object("leftLeg", "person", Vector2{1, 1}, 0, 1); - GameObject right_foot - = mgr.new_object("rightFoot", "person", Vector2{2, 2}, 0, 1); - GameObject left_foot - = mgr.new_object("leftFoot", "person", Vector2{2, 2}, 0, 1); + GameObject right_leg = mgr.new_object("rightLeg", "person", Vector2{1, 1}, 0, 1); + GameObject left_leg = mgr.new_object("leftLeg", "person", Vector2{1, 1}, 0, 1); + GameObject right_foot = mgr.new_object("rightFoot", "person", Vector2{2, 2}, 0, 1); + GameObject left_foot = mgr.new_object("leftFoot", "person", Vector2{2, 2}, 0, 1); // Set the parent of each GameObject right_foot.set_parent(right_leg); @@ -36,24 +32,21 @@ int main() { } // Get the Metadata and Transform components of each GameObject - vector<reference_wrapper<Metadata>> metadata - = mgr.get_components_by_type<Metadata>(); - vector<reference_wrapper<Transform>> transform - = mgr.get_components_by_type<Transform>(); + vector<reference_wrapper<Metadata>> metadata = mgr.get_components_by_type<Metadata>(); + vector<reference_wrapper<Transform>> transform = mgr.get_components_by_type<Transform>(); // Print the Metadata and Transform components for (auto & m : metadata) { cout << "Id: " << m.get().game_object_id << " Name: " << m.get().name - << " Tag: " << m.get().tag << " Parent: " << m.get().parent - << " Children: "; + << " Tag: " << m.get().tag << " Parent: " << m.get().parent << " Children: "; for (auto & c : m.get().children) { cout << c << " "; } cout << endl; } for (auto & t : transform) { - cout << "Id: " << t.get().game_object_id << " Position: [" - << t.get().position.x << ", " << t.get().position.y << "]" << endl; + cout << "Id: " << t.get().game_object_id << " Position: [" << t.get().position.x + << ", " << t.get().position.y << "]" << endl; } return 0; diff --git a/src/example/particles.cpp b/src/example/particles.cpp index b65671a..d4638a2 100644 --- a/src/example/particles.cpp +++ b/src/example/particles.cpp @@ -14,12 +14,11 @@ using namespace crepe; using namespace std; int main(int argc, char * argv[]) { - ComponentManager mgr; + ComponentManager mgr{}; GameObject game_object = mgr.new_object("", "", Vector2{0, 0}, 0, 0); Color color(0, 0, 0, 0); Sprite test_sprite = game_object.add_component<Sprite>( - make_shared<Texture>("asset/texture/img.png"), color, - FlipSettings{true, true}); + make_shared<Texture>("asset/texture/img.png"), color, FlipSettings{true, true}); game_object.add_component<ParticleEmitter>(ParticleEmitter::Data{ .position = {0, 0}, .max_particles = 100, diff --git a/src/example/rendering.cpp b/src/example/rendering.cpp index 2157bdc..c813524 100644 --- a/src/example/rendering.cpp +++ b/src/example/rendering.cpp @@ -31,15 +31,13 @@ int main() { { Color color(0, 0, 0, 0); obj.add_component<Sprite>( - make_shared<Texture>("asset/texture/img.png"), color, - FlipSettings{false, false}); + make_shared<Texture>("asset/texture/img.png"), color, FlipSettings{false, false}); obj.add_component<Camera>(Color::get_red()); } { Color color(0, 0, 0, 0); obj1.add_component<Sprite>( - make_shared<Texture>("asset/texture/second.png"), color, - FlipSettings{true, true}); + make_shared<Texture>("asset/texture/second.png"), color, FlipSettings{true, true}); } /* diff --git a/src/example/scene_manager.cpp b/src/example/scene_manager.cpp index 24ab72e..accec7d 100644 --- a/src/example/scene_manager.cpp +++ b/src/example/scene_manager.cpp @@ -16,12 +16,9 @@ public: void load_scene() { auto & mgr = this->component_manager; - GameObject object1 - = mgr.new_object("scene_1", "tag_scene_1", Vector2{0, 0}, 0, 1); - GameObject object2 - = mgr.new_object("scene_1", "tag_scene_1", Vector2{1, 0}, 0, 1); - GameObject object3 - = mgr.new_object("scene_1", "tag_scene_1", Vector2{2, 0}, 0, 1); + GameObject object1 = mgr.new_object("scene_1", "tag_scene_1", Vector2{0, 0}, 0, 1); + GameObject object2 = mgr.new_object("scene_1", "tag_scene_1", Vector2{1, 0}, 0, 1); + GameObject object3 = mgr.new_object("scene_1", "tag_scene_1", Vector2{2, 0}, 0, 1); } }; @@ -31,14 +28,10 @@ public: void load_scene() { auto & mgr = this->component_manager; - GameObject object1 - = mgr.new_object("scene_2", "tag_scene_2", Vector2{0, 0}, 0, 1); - GameObject object2 - = mgr.new_object("scene_2", "tag_scene_2", Vector2{0, 1}, 0, 1); - GameObject object3 - = mgr.new_object("scene_2", "tag_scene_2", Vector2{0, 2}, 0, 1); - GameObject object4 - = mgr.new_object("scene_2", "tag_scene_2", Vector2{0, 3}, 0, 1); + GameObject object1 = mgr.new_object("scene_2", "tag_scene_2", Vector2{0, 0}, 0, 1); + GameObject object2 = mgr.new_object("scene_2", "tag_scene_2", Vector2{0, 1}, 0, 1); + GameObject object3 = mgr.new_object("scene_2", "tag_scene_2", Vector2{0, 2}, 0, 1); + GameObject object4 = mgr.new_object("scene_2", "tag_scene_2", Vector2{0, 3}, 0, 1); } }; @@ -50,8 +43,8 @@ int main() { scene_mgr.add_scene<ConcreteScene1>("scene1"); scene_mgr.add_scene<ConcreteScene2>("scene2"); - // There is no need to call set_next_scene() at the beginning because the - // first scene will be automatically set as the next scene + // There is no need to call set_next_scene() at the beginnen, because the first scene will be + // automatically set as the next scene // Load scene1 (the first scene added) scene_mgr.load_next_scene(); diff --git a/src/test/ParticleTest.cpp b/src/test/ParticleTest.cpp index cd2ec2a..cfbbc0e 100644 --- a/src/test/ParticleTest.cpp +++ b/src/test/ParticleTest.cpp @@ -79,8 +79,7 @@ public: TEST_F(ParticlesTest, spawnParticle) { Config::get_instance().physics.gravity = 1; ComponentManager & mgr = this->component_manager; - ParticleEmitter & emitter - = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); + ParticleEmitter & emitter = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); emitter.data.end_lifespan = 5; emitter.data.boundary.height = 100; emitter.data.boundary.width = 100; @@ -124,8 +123,7 @@ TEST_F(ParticlesTest, spawnParticle) { TEST_F(ParticlesTest, moveParticleHorizontal) { Config::get_instance().physics.gravity = 1; ComponentManager & mgr = this->component_manager; - ParticleEmitter & emitter - = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); + ParticleEmitter & emitter = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); emitter.data.end_lifespan = 100; emitter.data.boundary.height = 100; emitter.data.boundary.width = 100; @@ -142,8 +140,7 @@ TEST_F(ParticlesTest, moveParticleHorizontal) { TEST_F(ParticlesTest, moveParticleVertical) { Config::get_instance().physics.gravity = 1; ComponentManager & mgr = this->component_manager; - ParticleEmitter & emitter - = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); + ParticleEmitter & emitter = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); emitter.data.end_lifespan = 100; emitter.data.boundary.height = 100; emitter.data.boundary.width = 100; @@ -161,8 +158,7 @@ TEST_F(ParticlesTest, moveParticleVertical) { TEST_F(ParticlesTest, boundaryParticleReset) { Config::get_instance().physics.gravity = 1; ComponentManager & mgr = this->component_manager; - ParticleEmitter & emitter - = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); + ParticleEmitter & emitter = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); emitter.data.end_lifespan = 100; emitter.data.boundary.height = 10; emitter.data.boundary.width = 10; @@ -181,8 +177,7 @@ TEST_F(ParticlesTest, boundaryParticleReset) { TEST_F(ParticlesTest, boundaryParticleStop) { Config::get_instance().physics.gravity = 1; ComponentManager & mgr = this->component_manager; - ParticleEmitter & emitter - = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); + ParticleEmitter & emitter = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); emitter.data.end_lifespan = 100; emitter.data.boundary.height = 10; emitter.data.boundary.width = 10; diff --git a/src/test/PhysicsTest.cpp b/src/test/PhysicsTest.cpp index edb76e9..1e37c26 100644 --- a/src/test/PhysicsTest.cpp +++ b/src/test/PhysicsTest.cpp @@ -49,8 +49,7 @@ public: TEST_F(PhysicsTest, gravity) { Config::get_instance().physics.gravity = 1; ComponentManager & mgr = this->component_manager; - vector<reference_wrapper<Transform>> transforms - = mgr.get_components_by_id<Transform>(0); + vector<reference_wrapper<Transform>> transforms = mgr.get_components_by_id<Transform>(0); const Transform & transform = transforms.front().get(); ASSERT_FALSE(transforms.empty()); EXPECT_EQ(transform.position.y, 0); @@ -64,8 +63,7 @@ TEST_F(PhysicsTest, gravity) { TEST_F(PhysicsTest, max_velocity) { ComponentManager & mgr = this->component_manager; - vector<reference_wrapper<Rigidbody>> rigidbodies - = mgr.get_components_by_id<Rigidbody>(0); + vector<reference_wrapper<Rigidbody>> rigidbodies = mgr.get_components_by_id<Rigidbody>(0); Rigidbody & rigidbody = rigidbodies.front().get(); ASSERT_FALSE(rigidbodies.empty()); EXPECT_EQ(rigidbody.data.linear_velocity.y, 0); @@ -88,11 +86,9 @@ TEST_F(PhysicsTest, max_velocity) { TEST_F(PhysicsTest, movement) { Config::get_instance().physics.gravity = 0; ComponentManager & mgr = this->component_manager; - vector<reference_wrapper<Rigidbody>> rigidbodies - = mgr.get_components_by_id<Rigidbody>(0); + vector<reference_wrapper<Rigidbody>> rigidbodies = mgr.get_components_by_id<Rigidbody>(0); Rigidbody & rigidbody = rigidbodies.front().get(); - vector<reference_wrapper<Transform>> transforms - = mgr.get_components_by_id<Transform>(0); + vector<reference_wrapper<Transform>> transforms = mgr.get_components_by_id<Transform>(0); const Transform & transform = transforms.front().get(); ASSERT_FALSE(rigidbodies.empty()); ASSERT_FALSE(transforms.empty()); |