From 73d81ca331c3b4571262fff9e6e4743df97228af Mon Sep 17 00:00:00 2001 From: Allan Legemaate Date: Tue, 16 Mar 2021 17:01:35 -0400 Subject: [PATCH 01/24] Start working on ECS --- CMakeLists.txt | 25 +++--- examples/ex_collision.cpp | 18 ++-- examples/ex_fps.cpp | 9 +- examples/ex_keyboard.cpp | 11 +-- examples/ex_mouse.cpp | 13 +-- examples/ex_particles.cpp | 63 ++++++++------ examples/ex_rotate.cpp | 2 +- examples/ex_ui.cpp | 3 +- include/components/Component.h | 24 ++++++ include/components/Transform.h | 55 ++++++++++++ include/entities/GameObject.h | 129 ++++++++--------------------- include/entities/ParticleEmitter.h | 5 +- include/scene/Scene.h | 12 +-- src/components/Component.cpp | 18 ++++ src/components/Transform.cpp | 26 ++++++ src/entities/GameObject.cpp | 80 ++++-------------- src/entities/Particle.cpp | 12 +-- src/entities/ParticleEmitter.cpp | 19 ++--- src/entities/Sprite.cpp | 10 ++- src/entities/ui/Button.cpp | 18 ++-- src/entities/ui/Checkbox.cpp | 20 +++-- src/entities/ui/Image.cpp | 8 +- src/entities/ui/Inputbox.cpp | 22 +++-- src/entities/ui/Label.cpp | 2 +- src/entities/ui/UIElement.cpp | 7 +- src/scene/Scene.cpp | 33 ++++---- 26 files changed, 345 insertions(+), 299 deletions(-) create mode 100644 include/components/Component.h create mode 100644 include/components/Transform.h create mode 100644 src/components/Component.cpp create mode 100644 src/components/Transform.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 54a7f2b..66b0af5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -67,20 +67,17 @@ endif(EMSCRIPTEN) # Install info if (EMSCRIPTEN) - if (NOT CMAKE_TOOLCHAIN_FILE) - message("CMAKE_TOOLCHAIN_FILE not provided, can not automatically install") - else() - get_filename_component(EMSDK_DIR ${CMAKE_TOOLCHAIN_FILE} DIRECTORY) - set(EMSDK_DIR ${EMSDK_DIR}/../../../system) - message("Lib install directory set to ${EMSDK_DIR}") - - install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} - ARCHIVE DESTINATION ${EMSDK_DIR}/lib - LIBRARY DESTINATION ${EMSDK_DIR}/lib - RUNTIME DESTINATION ${EMSDK_DIR}/bin) - - install(DIRECTORY include/ DESTINATION ${EMSDK_DIR}/include/${PROJECT_NAME}) - endif() + get_filename_component(EMSDK_DIR ${CMAKE_TOOLCHAIN_FILE} DIRECTORY) + set(EMSDK_DIR ${EMSDK_DIR}/../../../system) + message("Lib install directory set to ${EMSDK_DIR}") + + install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + ARCHIVE DESTINATION ${EMSDK_DIR}/lib + LIBRARY DESTINATION ${EMSDK_DIR}/lib + RUNTIME DESTINATION ${EMSDK_DIR}/bin) + + install(DIRECTORY include/ DESTINATION ${EMSDK_DIR}/include/${PROJECT_NAME}) + elseif (WIN32) install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} ARCHIVE DESTINATION C:/msys64/mingw32/lib diff --git a/examples/ex_collision.cpp b/examples/ex_collision.cpp index e85e7e6..122af42 100644 --- a/examples/ex_collision.cpp +++ b/examples/ex_collision.cpp @@ -27,14 +27,14 @@ class DemoScene : public afk::Scene { assets.loadImage("lenna", "assets/lenna.png"); assets.loadFont("freesans", "assets/freesans.ttf", 12); - auto& lenna_1 = add(*this, "lenna"); - lenna_1.setPosition(10, 10); - lenna_1.setSize(40, 40); + auto& lenna_1 = add(*this, "lenna", 10, 10); + lenna_1.transform.width = 40; + lenna_1.transform.height = 40; lenna_1_id = lenna_1.id; - auto& lenna_2 = add(*this, "lenna"); - lenna_2.setPosition(10, 80); - lenna_2.setSize(40, 40); + auto& lenna_2 = add(*this, "lenna", 10, 80); + lenna_2.transform.width = 40; + lenna_2.transform.height = 40; lenna_2_id = lenna_2.id; auto& label = add(*this, 0, 0); @@ -48,11 +48,13 @@ class DemoScene : public afk::Scene { auto& lenna_2 = get(lenna_2_id); if (input.mouseDown(afk::MouseButtons::LEFT)) { - lenna_1.setPosition(input.mouseX(), input.mouseY()); + lenna_1.transform.x = input.mouseX(); + lenna_1.transform.y = input.mouseY(); } if (input.mouseDown(afk::MouseButtons::RIGHT)) { - lenna_2.setPosition(input.mouseX(), input.mouseY()); + lenna_2.transform.x = input.mouseX(); + lenna_2.transform.y = input.mouseY(); } if (lenna_1.isColliding(lenna_2)) { diff --git a/examples/ex_fps.cpp b/examples/ex_fps.cpp index e43247b..5bf5095 100644 --- a/examples/ex_fps.cpp +++ b/examples/ex_fps.cpp @@ -42,7 +42,8 @@ class DemoScene : public afk::Scene { for (unsigned int i = 0; i < NUM_SPRITE; i++) { afk::Sprite& sprite = add(*this, "lenna"); - sprite.setSize(SPRITE_SIZE, SPRITE_SIZE); + sprite.transform.width = SPRITE_SIZE; + sprite.transform.height = SPRITE_SIZE; sprites[i] = sprite.id; } } @@ -58,9 +59,9 @@ class DemoScene : public afk::Scene { for (unsigned int i = 0; i < NUM_SPRITE; i++) { afk::Sprite& sprite = get(sprites[i]); - sprite.setPosition(fmod(iter + i, SCREEN_W), - sin(iter / 100.0f + i) * SCREEN_H_2 + SCREEN_H_2); - sprite.setAngle(sprite.getAngle() + delta / 10.0f); + sprite.transform.x = fmod(iter + i, SCREEN_W); + sprite.transform.y = sin(iter / 100.0f + i) * SCREEN_H_2 + SCREEN_H_2; + sprite.transform.angle += delta / 10.0f; } } diff --git a/examples/ex_keyboard.cpp b/examples/ex_keyboard.cpp index 7d2298d..04913f2 100644 --- a/examples/ex_keyboard.cpp +++ b/examples/ex_keyboard.cpp @@ -18,7 +18,8 @@ class Character : public afk::Sprite { Character(afk::Scene& scene, const float x, const float y) : Sprite(scene, x, y) { setTexture("lenna"); - setSize(30, 30); + transform.width = 30; + transform.height = 30; } void update(Uint32 delta) { @@ -26,16 +27,16 @@ class Character : public afk::Sprite { float speed = delta / 10.0f; if (scene.input.keyDown(afk::Keys::UP)) { - setPosition(x, y - speed); + transform.y -= speed; } if (scene.input.keyDown(afk::Keys::DOWN)) { - setPosition(x, y + speed); + transform.y += speed; } if (scene.input.keyDown(afk::Keys::LEFT)) { - setPosition(x - speed, y); + transform.x -= speed; } if (scene.input.keyDown(afk::Keys::RIGHT)) { - setPosition(x + speed, y); + transform.x += speed; } } }; diff --git a/examples/ex_mouse.cpp b/examples/ex_mouse.cpp index 478aac1..d0fbb32 100644 --- a/examples/ex_mouse.cpp +++ b/examples/ex_mouse.cpp @@ -25,10 +25,9 @@ class DemoScene : public afk::Scene { assets.loadImage("lenna", "assets/lenna.png"); - afk::Sprite& lenna = add(*this, "lenna"); - - lenna.setSize(30, 30); - lenna.setPosition(100, 100); + afk::Sprite& lenna = add(*this, "lenna", 100, 100); + lenna.transform.width = 30; + lenna.transform.height = 30; lennaId = lenna.id; } @@ -38,10 +37,12 @@ class DemoScene : public afk::Scene { afk::Sprite& lenna = get(lennaId); if (input.mousePressed(afk::MouseButtons::LEFT)) { - lenna.setPosition(input.mouseX(), input.mouseY()); + lenna.transform.x = input.mouseX(); + lenna.transform.y = input.mouseY(); } if (input.mouseDown(afk::MouseButtons::RIGHT)) { - lenna.setSize(input.mouseX(), input.mouseY()); + lenna.transform.width = input.mouseX(); + lenna.transform.height = input.mouseY(); } } diff --git a/examples/ex_particles.cpp b/examples/ex_particles.cpp index 3d666ce..02205bd 100644 --- a/examples/ex_particles.cpp +++ b/examples/ex_particles.cpp @@ -15,6 +15,8 @@ #include "../include/scene/Scene.h" #include "../include/services/Services.h" +#include + class DemoScene : public afk::Scene { public: void start() { @@ -29,54 +31,61 @@ class DemoScene : public afk::Scene { assets.loadImage("fuzzball", "assets/fuzzball.png"); afk::ParticleEmitter& emitter = add(*this, 256, 256); - emitter.setSize(30, 30); + emitter.transform.width = 30; + emitter.transform.height = 30; for (int i = 0; i < 100; i++) { - afk::Particle particle(*this, 0, 0, 0, afk::ParticleType::SQUARE); - particle.setLifespan(afk::Random::randomInt(100, 1000)); - particle.setSize(10.0f, 3.0f); - particle.setColor(afk::color::rgb(128, 22, 22), - afk::color::rgb(100, 100, 100)); - particle.setVelocity(afk::Random::randomFloat(-5.0f, 5.0f), - afk::Random::randomFloat(-1.0f, -2.0f)); - particle.setAcceleration(0, 0.2f); - emitter.addParticle(particle); + auto particle = std::make_unique( + *this, 0, 0, 0, afk::ParticleType::SQUARE); + particle->setLifespan(afk::Random::randomInt(100, 1000)); + particle->setSize(10.0f, 3.0f); + particle->setColor(afk::color::rgb(128, 22, 22), + afk::color::rgb(100, 100, 100)); + particle->setVelocity(afk::Random::randomFloat(-5.0f, 5.0f), + afk::Random::randomFloat(-1.0f, -2.0f)); + particle->setAcceleration(0, 0.2f); + // emitter.addParticle(particle); } afk::ParticleEmitter& emitter_2 = add(*this, 128, 256); - emitter_2.setSize(1, 1); + emitter_2.transform.width = 1; + emitter_2.transform.height = 1; for (int i = 0; i < 100; i++) { - afk::Particle particle(*this, 0, 0, 0, afk::ParticleType::CIRCLE); - particle.setLifespan(afk::Random::randomInt(100, 200)); - particle.setSize(3.0f, 2.0f); - particle.setColor(afk::color::blue, afk::color::white); - particle.setVelocity(afk::Random::randomFloat(-5, 5), -100); - particle.setAcceleration(0, 3.0f); - emitter_2.addParticle(particle); + auto particle = std::make_unique( + *this, 0, 0, 0, afk::ParticleType::CIRCLE); + particle->setLifespan(afk::Random::randomInt(100, 200)); + particle->setSize(3.0f, 2.0f); + particle->setColor(afk::color::blue, afk::color::white); + particle->setVelocity(afk::Random::randomFloat(-5, 5), -100); + particle->setAcceleration(0, 3.0f); + // emitter_2.addParticle(particle); } afk::ParticleEmitter& emitter_3 = add(*this, 384, 256); - emitter_3.setSize(5, 5); + emitter_3.transform.width = 5; + emitter_3.transform.height = 5; smoke_id = emitter_3.id; for (int i = 0; i < 400; i++) { - afk::Particle particle(*this, 0, 0, 0, afk::ParticleType::IMAGE); - particle.setLifespan(afk::Random::randomInt(800, 1500)); - particle.setTexture("fuzzball"); - particle.setSize(16.0f, 20.0f); - particle.setVelocity(afk::Random::randomFloat(2.0f, 2.5f), -5.0f); - emitter_3.addParticle(particle); + auto particle = std::make_unique(*this, 0, 0, 0, + afk::ParticleType::IMAGE); + particle->setLifespan(afk::Random::randomInt(800, 1500)); + particle->setTexture("fuzzball"); + particle->setSize(16.0f, 20.0f); + particle->setVelocity(afk::Random::randomFloat(2.0f, 2.5f), -5.0f); + // emitter_3.addParticle(particle); } } void update(Uint32 delta) { Scene::update(delta); - get(smoke_id).setPosition(input.mouseX(), - input.mouseY()); + auto& smoke_emitter = get(smoke_id); + smoke_emitter.transform.x = input.mouseX(); + smoke_emitter.transform.y = input.mouseY(); } void stop() { logger.log("Stopping!"); } diff --git a/examples/ex_rotate.cpp b/examples/ex_rotate.cpp index 0a813cf..a422e14 100644 --- a/examples/ex_rotate.cpp +++ b/examples/ex_rotate.cpp @@ -33,7 +33,7 @@ class DemoScene : public afk::Scene { Scene::update(delta); afk::Sprite& lenna = get(lennaId); - lenna.setAngle(lenna.getAngle() + delta / 10.0f); + lenna.transform.angle += delta / 10.0f; } void stop() { logger.log("Stopping!"); } diff --git a/examples/ex_ui.cpp b/examples/ex_ui.cpp index 8b33d07..29925dc 100644 --- a/examples/ex_ui.cpp +++ b/examples/ex_ui.cpp @@ -66,7 +66,8 @@ class DemoScene : public afk::Scene { afk::Image& image = add(*this, 10, 120); image.setTexture("lenna"); - image.setSize(20, 20); + image.transform.width = 20; + image.transform.height = 20; image.setOnClick([]() { afk::MessageBox message_box(afk::MessageBoxType::INFO); message_box.setTitle("Nice"); diff --git a/include/components/Component.h b/include/components/Component.h new file mode 100644 index 0000000..b5db795 --- /dev/null +++ b/include/components/Component.h @@ -0,0 +1,24 @@ +/** + * @file Component.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Base component + * @version 0.1 + * @date 2021-03-15 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef INCLUDE_COMPONENTS_COMPONENT_H_ +#define INCLUDE_COMPONENTS_COMPONENT_H_ + +namespace afk { + +class Component { + public: + Component(); + virtual ~Component() = default; +}; + +} // namespace afk + +#endif // INCLUDE_COMPONENTS_COMPONENT_H_ diff --git a/include/components/Transform.h b/include/components/Transform.h new file mode 100644 index 0000000..df27fe6 --- /dev/null +++ b/include/components/Transform.h @@ -0,0 +1,55 @@ +/** + * @file Transform.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Transform, stores positioning + * @version 0.1 + * @date 2021-03-15 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef INCLUDE_COMPONENTS_TRANSFORM_H_ +#define INCLUDE_COMPONENTS_TRANSFORM_H_ + +#include "Component.h" + +namespace afk { + +class Transform : public Component { + public: + /** + * @brief Construct a new Transform object + * + */ + Transform(); + + virtual ~Transform() = default; + + /// X position on x y plane + float x; + + /// Y position on x y plane + float y; + + /// Z position, used for sorting + int z; + + /// Height in pixels of game object + int height; + + /// Width in pixels of game object + int width; + + /// Rotation + float angle; + + /// Last position y + int last_x; + + /// Last position x + int last_y; +}; + +} // namespace afk + +#endif // INCLUDE_COMPONENTS_TRANSFORM_H_ diff --git a/include/entities/GameObject.h b/include/entities/GameObject.h index 066b2c1..47fe082 100644 --- a/include/entities/GameObject.h +++ b/include/entities/GameObject.h @@ -14,9 +14,14 @@ #define INCLUDE_ENTITIES_GAMEOBJECT_H_ #include +#include +#include #include #include +#include "../components/Component.h" +#include "../components/Transform.h" + /// Unique id type alias using ObjId = Uint32; @@ -99,7 +104,7 @@ class GameObject { * @param other Some other game object * @return True on collision, else false */ - bool isColliding(const GameObject& other); + bool isColliding(GameObject& other); /** * @brief Checks collision between this game object and another. @@ -118,24 +123,6 @@ class GameObject { */ virtual void onCollide(GameObject& other); - /** - * @brief Set the size of game object in pixels - * - */ - void setSize(const unsigned int width, const unsigned int height); - - /** - * @brief Set the position of game object in pixels - * - */ - void setPosition(const float x, const float y); - - /** - * @brief Set angle of game object in degrees - * - */ - void setAngle(const float angle); - /** * @brief Set the visibility of the GameObject. Will not draw when not * visible. @@ -159,48 +146,6 @@ class GameObject { */ void setHooked(const bool hooked); - /** - * @brief Get the width of the game object - * - * @return Width of game object - */ - int getWidth() const; - - /** - * @brief Get the height of the game object - * - * @return Height of game object - */ - int getHeight() const; - - /** - * @brief Get x position of game object - * - * @return X position - */ - float getX() const; - - /** - * @brief Get y position of game object - * - * @return Y position - */ - float getY() const; - - /** - * @brief Get z position of game object. Used for z sorting - * - * @return Z position - */ - int getZ() const; - - /** - * @brief Get the angle of the game object. - * - * @return Angle - */ - float getAngle() const; - /** * @brief Get the visibility of game object * @@ -225,14 +170,33 @@ class GameObject { */ bool getHooked() const; - /** - * @brief Definition for < operator. Less than if z is less than the other - * game object. - * - * @param obj Other game object - * @return True if the z of this game object is less than the other - */ - bool operator<(const GameObject& obj) const { return (z < obj.getZ()); } + template + T& addComponent() { + std::size_t id = typeid(T).hash_code(); + components[id] = std::make_unique(); + return dynamic_cast(*components[id]); + } + + template + T& getComponent() { + std::size_t id = typeid(T).hash_code(); + return dynamic_cast(*components[id]); + } + + template + void removeComponent() { + std::size_t id = typeid(T).hash_code(); + components.erase(id); + } + + template + bool hasComponent() const { + std::size_t id = typeid(T).hash_code(); + return components.count(id) > 0; + } + + /// Components + Transform transform; /// Autoassigned unique id const ObjId id; @@ -241,24 +205,6 @@ class GameObject { /// Reference to registered scene Scene& scene; - /// X position on x y plane - float x; - - /// Y position on x y plane - float y; - - /// Z position, used for sorting - int z; - - /// Height in pixels of game object - int height; - - /// Width in pixels of game object - int width; - - /// Rotation - float angle; - /// Visibility bool visible; @@ -268,12 +214,6 @@ class GameObject { /// Hooked bool hooked; - /// Delta x - float last_x; - - /// Delta y - float last_y; - private: /// Parent Id ObjId parent_id; @@ -283,6 +223,9 @@ class GameObject { /// Colliders std::vector colliders; + + /// Components + std::map> components{}; }; } // namespace afk diff --git a/include/entities/ParticleEmitter.h b/include/entities/ParticleEmitter.h index 8f0bc22..7403069 100644 --- a/include/entities/ParticleEmitter.h +++ b/include/entities/ParticleEmitter.h @@ -12,6 +12,7 @@ #ifndef INCLUDE_ENTITIES_PARTICLEEMITTER_H_ #define INCLUDE_ENTITIES_PARTICLEEMITTER_H_ +#include #include #include "GameObject.h" @@ -66,7 +67,7 @@ class ParticleEmitter : public GameObject { * @param particle Particle to add * @param count Number of particles to push back, defaults to 1 */ - void addParticle(const Particle& particle, const Uint32 count = 1); + void addParticle(std::unique_ptr particle); /** * @brief Disable more particles from being emitted @@ -82,7 +83,7 @@ class ParticleEmitter : public GameObject { protected: /// Particles - std::vector particles; + std::vector> particles; /// Emitting state bool emitting; diff --git a/include/scene/Scene.h b/include/scene/Scene.h index 7ee692a..e1e8d23 100644 --- a/include/scene/Scene.h +++ b/include/scene/Scene.h @@ -87,10 +87,10 @@ class Scene { GameObject* obj = new T(std::forward(args)...); // Add to lookup - lookup_map[obj->id] = update_pool.size(); + entity_map[obj->id] = entities.size(); // Push - update_pool.emplace_back(obj); + entities.emplace_back(obj); // Force sort on next update need_sort = true; @@ -147,8 +147,8 @@ class Scene { std::to_string(id)); } - unsigned int index = lookup_map[id]; - return *update_pool.at(index); + unsigned int index = entity_map[id]; + return *entities.at(index); } /// Service references @@ -162,10 +162,10 @@ class Scene { private: /// Holds game objects - std::vector> update_pool; + std::vector> entities; /// Quick gameobject lookup - std::map lookup_map; + std::map entity_map; /// Store objects to be removed std::vector remove_pool; diff --git a/src/components/Component.cpp b/src/components/Component.cpp new file mode 100644 index 0000000..88d08d7 --- /dev/null +++ b/src/components/Component.cpp @@ -0,0 +1,18 @@ +/** + * @file Component.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Implementation of base component + * @version 0.1 + * @date 2021-03-15 + * + * @copyright Copyright (c) 2021 + * + */ +#include "components/Component.h" + +namespace afk { + +// Constructor +Component::Component() {} + +} // namespace afk diff --git a/src/components/Transform.cpp b/src/components/Transform.cpp new file mode 100644 index 0000000..875b3f7 --- /dev/null +++ b/src/components/Transform.cpp @@ -0,0 +1,26 @@ +/** + * @file Transform.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Implementation of transform component + * @version 0.1 + * @date 2021-03-15 + * + * @copyright Copyright (c) 2021 + * + */ +#include "components/Transform.h" + +namespace afk { + +Transform::Transform() + : Component(), + x(0), + y(0), + z(0), + height(0), + width(0), + angle(0), + last_x(0), + last_y(0) {} + +} // namespace afk diff --git a/src/entities/GameObject.cpp b/src/entities/GameObject.cpp index e85c4aa..7360106 100644 --- a/src/entities/GameObject.cpp +++ b/src/entities/GameObject.cpp @@ -10,10 +10,10 @@ */ #include "entities/GameObject.h" -#include "scene/Scene.h" - #include +#include "scene/Scene.h" + namespace afk { // Set incrementing index count @@ -23,19 +23,16 @@ ObjId GameObject::index = 1; GameObject::GameObject(Scene& scene, const float x, const float y, const int z) : id(GameObject::index), scene(scene), - x(x), - y(y), - z(z), - height(0), - width(0), - angle(0.0f), visible(true), enabled(true), hooked(true), - last_x(0), - last_y(0), parent_id(0) { GameObject::index += 1; + + // Set transform + transform.x = x; + transform.y = y; + transform.z = z; } // Destructor @@ -48,10 +45,6 @@ void GameObject::update(Uint32 delta) { // Update void GameObject::updateInternal() { - // Update delta position - last_x = x; - last_y = y; - // Parent functions if (parent_id != 0) { // Autoremove if parent is dead @@ -62,8 +55,8 @@ void GameObject::updateInternal() { hooked = parent.getHooked(); // Set position - x += parent.x - parent.last_x; - y += parent.y - parent.last_y; + transform.x += parent.transform.x - parent.transform.last_x; + transform.y += parent.transform.y - parent.transform.last_y; } catch (const KeyLookupException&) { scene.remove(id); @@ -100,9 +93,11 @@ void GameObject::removeCollider(const ObjId obj_id) { } // Is colliding with game object -bool GameObject::isColliding(const GameObject& other) { - return x < other.x + other.width && x + width > other.x && - y < other.y + other.height && y + height > other.y; +bool GameObject::isColliding(GameObject& other) { + return transform.x < other.transform.x + other.transform.width && + transform.x + transform.width > other.transform.x && + transform.y < other.transform.y + other.transform.height && + transform.y + transform.height > other.transform.y; } // Collide game objects @@ -122,23 +117,6 @@ void GameObject::onCollide(GameObject& other) { (void)(other); } -// Set the size of game object in pixels -void GameObject::setSize(const unsigned int width, const unsigned int height) { - this->width = width; - this->height = height; -} - -// Set the position of game object in pixels -void GameObject::setPosition(const float x, const float y) { - this->x = x; - this->y = y; -} - -// Set angle of game object in degrees -void GameObject::setAngle(const float angle) { - this->angle = angle; -} - // Set visibility void GameObject::setVisible(const bool visible) { this->visible = visible; @@ -154,36 +132,6 @@ void GameObject::setHooked(const bool hooked) { this->hooked = hooked; } -// Get z index -int GameObject::getWidth() const { - return this->width; -} - -// Get z index -int GameObject::getHeight() const { - return this->height; -} - -// Get z index -float GameObject::getX() const { - return this->x; -} - -// Get z index -float GameObject::getY() const { - return this->y; -} - -// Get z index -int GameObject::getZ() const { - return this->z; -} - -// Get z index -float GameObject::getAngle() const { - return this->angle; -} - // Get visibility bool GameObject::getVisible() const { return this->visible; diff --git a/src/entities/Particle.cpp b/src/entities/Particle.cpp index bc80204..b8e749e 100644 --- a/src/entities/Particle.cpp +++ b/src/entities/Particle.cpp @@ -40,8 +40,8 @@ void Particle::update(Uint32 delta) { } // Update velocity - x += (velocity_x + acceleration_x * age) / 1000 * delta; - y += (velocity_y + acceleration_y * age) / 1000 * delta; + transform.x += (velocity_x + acceleration_x * age) / 1000 * delta; + transform.y += (velocity_y + acceleration_y * age) / 1000 * delta; // Its dead this->age += 4.0f; @@ -68,16 +68,16 @@ void Particle::draw() { // Switch over type switch (type) { case ParticleType::SQUARE: - primitives::rectfill(x, y, size, size, color); + primitives::rectfill(transform.x, transform.y, size, size, color); break; case ParticleType::CIRCLE: - primitives::circle(x, y, size, color); + primitives::circle(transform.x, transform.y, size, color); break; case ParticleType::PIXEL: - primitives::pixel(x, y, color); + primitives::pixel(transform.x, transform.y, color); break; case ParticleType::IMAGE: - texture.drawEx(x, y, size, size, 0); + texture.drawEx(transform.x, transform.y, size, size, 0); default: break; } diff --git a/src/entities/ParticleEmitter.cpp b/src/entities/ParticleEmitter.cpp index 6ef8734..1ab6367 100644 --- a/src/entities/ParticleEmitter.cpp +++ b/src/entities/ParticleEmitter.cpp @@ -33,7 +33,7 @@ ParticleEmitter::ParticleEmitter(Scene& scene, // Draw void ParticleEmitter::draw() { for (auto& particle : particles) { - particle.draw(); + particle->draw(); } } @@ -44,23 +44,22 @@ void ParticleEmitter::update(Uint32 delta) { } for (auto& particle : particles) { - particle.update(delta); + particle->update(delta); - if (particle.dead() && emitting && current_tick >= frequency) { + if (particle->dead() && emitting && current_tick >= frequency) { current_tick -= frequency; particle.reset(); - particle.setPosition(Random::randomInt(x, x + width), - Random::randomInt(y, y + width)); + transform.x = + Random::randomInt(transform.x, transform.x + transform.width); + transform.y = + Random::randomInt(transform.y, transform.y + transform.width); } } } // Add -void ParticleEmitter::addParticle(const Particle& particle, - const Uint32 count) { - for (Uint32 i = 0; i < count; i++) { - particles.push_back(Particle(particle)); - } +void ParticleEmitter::addParticle(std::unique_ptr particle) { + particles.push_back(std::move(particle)); } // Enable diff --git a/src/entities/Sprite.cpp b/src/entities/Sprite.cpp index 41718f5..d3a4163 100644 --- a/src/entities/Sprite.cpp +++ b/src/entities/Sprite.cpp @@ -35,18 +35,20 @@ Sprite::~Sprite() {} void Sprite::setTexture(const std::string& texture) { this->texture = scene.assets.getImage(texture); - this->width = this->texture.getWidth(); - this->height = this->texture.getHeight(); + transform.width = this->texture.getWidth(); + transform.height = this->texture.getHeight(); } // Draw void Sprite::draw() { // Draw image - texture.drawEx(x, y, width, height, angle); + texture.drawEx(transform.x, transform.y, transform.width, transform.height, + transform.angle); // Draw bounding box if (Services::getConfigService().get("debug", false)) { - primitives::rect(x, y, width, height, color::red); + primitives::rect(transform.x, transform.y, transform.width, + transform.height, color::red); } } diff --git a/src/entities/ui/Button.cpp b/src/entities/ui/Button.cpp index 403bbce..7cb3dcd 100644 --- a/src/entities/ui/Button.cpp +++ b/src/entities/ui/Button.cpp @@ -26,21 +26,23 @@ const int DEFAULT_PADDING = 5; // Ctor Button::Button(Scene& scene, const float x, const float y, const int z) : UIElement(scene, x, y, z) { - width = DEFAULT_WIDTH; - height = DEFAULT_HEIGHT; + transform.width = DEFAULT_WIDTH; + transform.height = DEFAULT_HEIGHT; } // Draw button void Button::draw() { // Draw button background - primitives::rectfill(x, y, width, height, color::white); + primitives::rectfill(transform.x, transform.y, transform.width, + transform.height, color::white); // Draw button border - primitives::rect(x, y, width, height, color::black); + primitives::rect(transform.x, transform.y, transform.width, transform.height, + color::black); // Text - font.draw(x + DEFAULT_PADDING, y + DEFAULT_PADDING, text, color::black, - text_align); + font.draw(transform.x + DEFAULT_PADDING, transform.y + DEFAULT_PADDING, text, + color::black, text_align); } // Override text setter @@ -48,8 +50,8 @@ void Button::sizeToText() { if (!font.exists()) { return; } - height = font.getHeight() + DEFAULT_PADDING * 2; - width = font.getWidth(text) + DEFAULT_PADDING * 2; + transform.height = font.getHeight() + DEFAULT_PADDING * 2; + transform.width = font.getWidth(text) + DEFAULT_PADDING * 2; } } // namespace afk diff --git a/src/entities/ui/Checkbox.cpp b/src/entities/ui/Checkbox.cpp index 01f4f74..f63fef6 100644 --- a/src/entities/ui/Checkbox.cpp +++ b/src/entities/ui/Checkbox.cpp @@ -25,25 +25,31 @@ namespace afk { // Ctor Checkbox::Checkbox(Scene& scene, const float x, const float y, const int z) : UIElement(scene, x, y, z), checked(false), onCheck(nullptr) { - this->height = DEFAULT_HEIGHT; - this->width = DEFAULT_WIDTH; + transform.height = DEFAULT_HEIGHT; + transform.width = DEFAULT_WIDTH; } // Draw checkbox void Checkbox::draw() { // Draw checkbox background - primitives::rectfill(x, y, width, height, color::white); + primitives::rectfill(transform.x, transform.y, transform.width, + transform.height, color::white); // Draw checkbox border - primitives::rect(x, y, width, height, color::black); + primitives::rect(transform.x, transform.y, transform.width, transform.height, + color::black); if (checked) { - primitives::rectfill(x + width / 4, y + height / 4, width - width / 2, - height - height / 2, color::black); + primitives::rectfill(transform.x + transform.width / 4, + transform.y + transform.height / 4, + transform.width - transform.width / 2, + transform.height - transform.height / 2, color::black); } // Draw text label - font.draw(x + width + 10, y + height - font.getHeight(), text, color::black); + font.draw(transform.x + transform.width + 10, + transform.y + transform.height - font.getHeight(), text, + color::black); } // Check checkbox stat diff --git a/src/entities/ui/Image.cpp b/src/entities/ui/Image.cpp index bd9ce9f..5c9c9d5 100644 --- a/src/entities/ui/Image.cpp +++ b/src/entities/ui/Image.cpp @@ -20,13 +20,15 @@ Image::Image(Scene& scene, const float x, const float y, const int z) // Draw image void Image::draw() { - texture.drawEx(x, y, width, height, angle); + texture.drawEx(transform.x, transform.y, transform.width, transform.height, + transform.angle); } void Image::setTexture(const std::string& texture) { this->texture = scene.assets.getImage(texture); - this->width = this->texture.getWidth(); - this->height = this->texture.getHeight(); + + transform.width = this->texture.getWidth(); + transform.height = this->texture.getHeight(); } } // namespace afk diff --git a/src/entities/ui/Inputbox.cpp b/src/entities/ui/Inputbox.cpp index 974f718..ca6bbd4 100644 --- a/src/entities/ui/Inputbox.cpp +++ b/src/entities/ui/Inputbox.cpp @@ -31,34 +31,38 @@ const int DEFAULT_PADDING = 5; // Ctor Inputbox::Inputbox(Scene& scene, const float x, const float y, const int z) : UIElement(scene, x, y, z), iter(text.end()), onChange(nullptr) { - this->height = DEFAULT_HEIGHT; - this->width = DEFAULT_WIDTH; + transform.height = DEFAULT_HEIGHT; + transform.width = DEFAULT_WIDTH; } // Draw checkbox void Inputbox::draw() { // Draw checkbox background - primitives::rectfill(x, y, width, height, color::white); + primitives::rectfill(transform.x, transform.y, transform.width, + transform.height, color::white); // Draw checkbox border - primitives::rect(x, y, width, height, color::black); + primitives::rect(transform.x, transform.y, transform.width, transform.height, + color::black); // Focus border if (id == UIElement::focused) { - primitives::rect(x + 1, y + 1, width - 2, height - 2, color::black); + primitives::rect(transform.x + 1, transform.y + 1, transform.width - 2, + transform.height - 2, color::black); } // Draw text label - font.draw(x + DEFAULT_PADDING, y + height - font.getHeight(), text, + font.draw(transform.x + DEFAULT_PADDING, + transform.y + transform.height - font.getHeight(), text, color::black); // Draw the caret std::string edit_pos = text.substr(0, std::distance(text.begin(), iter)); int line_x = font.getWidth(edit_pos); - afk::primitives::line(line_x + x + DEFAULT_PADDING, y + 2, - line_x + x + DEFAULT_PADDING, y + height - 2, - afk::color::black); + afk::primitives::line(line_x + transform.x + DEFAULT_PADDING, transform.y + 2, + line_x + transform.x + DEFAULT_PADDING, + transform.y + transform.height - 2, afk::color::black); } // Update loop diff --git a/src/entities/ui/Label.cpp b/src/entities/ui/Label.cpp index 5bf552a..351d6c4 100644 --- a/src/entities/ui/Label.cpp +++ b/src/entities/ui/Label.cpp @@ -23,7 +23,7 @@ Label::Label(Scene& scene, const float x, const float y, const int z) // Draw label void Label::draw() { // Text - font.draw(x, y, text, color::black, text_align); + font.draw(transform.x, transform.y, text, color::black, text_align); } } // namespace afk diff --git a/src/entities/ui/UIElement.cpp b/src/entities/ui/UIElement.cpp index 0380579..5463e1b 100644 --- a/src/entities/ui/UIElement.cpp +++ b/src/entities/ui/UIElement.cpp @@ -51,9 +51,10 @@ void UIElement::update(Uint32 delta) { InputService& input = Services::getInputService(); if (input.mousePressed(MouseButtons::LEFT)) { - bool is_colliding = input.mouseX() < x + width && - input.mouseY() < y + height && input.mouseX() > x && - input.mouseY() > y; + bool is_colliding = input.mouseX() < transform.x + transform.width && + input.mouseY() < transform.y + transform.height && + input.mouseX() > transform.x && + input.mouseY() > transform.y; if (is_colliding) { UIElement::focused = id; diff --git a/src/scene/Scene.cpp b/src/scene/Scene.cpp index 15f8fe5..42c4fcb 100644 --- a/src/scene/Scene.cpp +++ b/src/scene/Scene.cpp @@ -30,14 +30,14 @@ Scene::Scene() // Internal cleanup (on switch scene) void Scene::stopInternal() { - update_pool.clear(); - lookup_map.clear(); + entities.clear(); + entity_map.clear(); } // Draw internal method void Scene::draw() { // Draw - for (auto& obj : update_pool) { + for (auto& obj : entities) { if (obj->getVisible() && obj->getHooked()) { obj->draw(); } @@ -47,27 +47,27 @@ void Scene::draw() { // Internal update method void Scene::update(Uint32 delta) { // Update all (we need to indices here since updates can add objects) - for (Uint32 i = 0; i < update_pool.size(); ++i) { - if (update_pool.at(i)->getEnabled() && update_pool.at(i)->getHooked()) { - update_pool.at(i)->update(delta); + for (Uint32 i = 0; i < entities.size(); ++i) { + if (entities.at(i)->getEnabled() && entities.at(i)->getHooked()) { + entities.at(i)->update(delta); } } // Internal updates - for (auto& obj : update_pool) { + for (auto& obj : entities) { obj->updateInternal(); } // Remove any game objects that need to be cleaned up for (auto& id : remove_pool) { // Get vector index - auto index = lookup_map.at(id); + auto index = entity_map.at(id); // Erase game object - update_pool.erase(update_pool.begin() + index); + entities.erase(entities.begin() + index); // Remove from lookup map - lookup_map.erase(id); + entity_map.erase(id); // We will need a sort after this need_sort = true; @@ -79,12 +79,15 @@ void Scene::update(Uint32 delta) { // Sort flag toggled if (need_sort) { // Z sort, use defined < operator - std::sort(update_pool.begin(), update_pool.end(), - [](auto& obj1, auto& obj2) -> bool { return *obj1 < *obj2; }); + std::sort(entities.begin(), entities.end(), + [](std::unique_ptr& obj1, + std::unique_ptr& obj2) -> bool { + return obj1->transform.z < obj2->transform.z; + }); // Repopulate lookup map - for (unsigned int i = 0; i < update_pool.size(); i++) { - lookup_map[update_pool.at(i)->id] = i; + for (unsigned int i = 0; i < entities.size(); i++) { + entity_map[entities.at(i)->id] = i; } // Done sorting @@ -99,7 +102,7 @@ void Scene::remove(const ObjId id) { // Check if obj id exists in scene bool Scene::has(const ObjId id) { - return lookup_map.count(id) == 1; + return entity_map.count(id) == 1; } } // namespace afk From e0c9a54f3b3f014686a39950231941ef98446512 Mon Sep 17 00:00:00 2001 From: Allan Legemaate Date: Wed, 17 Mar 2021 13:39:48 -0400 Subject: [PATCH 02/24] Test sprite component --- examples/ex_keyboard.cpp | 34 ++++- include/components/Sprite.h | 33 +++++ include/components/Transform.h | 2 - include/entities/GameObject.h | 37 +----- include/scene/Scene.h | 166 +++++++++++++++++++----- include/services/assets/AssetService.h | 10 +- include/services/config/ConfigService.h | 5 +- src/components/Sprite.cpp | 20 +++ src/entities/GameObject.cpp | 6 +- src/scene/Scene.cpp | 92 +++++++++---- 10 files changed, 291 insertions(+), 114 deletions(-) create mode 100644 include/components/Sprite.h create mode 100644 src/components/Sprite.cpp diff --git a/examples/ex_keyboard.cpp b/examples/ex_keyboard.cpp index 04913f2..d389beb 100644 --- a/examples/ex_keyboard.cpp +++ b/examples/ex_keyboard.cpp @@ -9,22 +9,22 @@ * */ #include "../include/Game.h" -#include "../include/entities/Sprite.h" +#include "../include/components/Sprite.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" -class Character : public afk::Sprite { +class Character : public afk::GameObject { public: Character(afk::Scene& scene, const float x, const float y) - : Sprite(scene, x, y) { - setTexture("lenna"); + : GameObject(scene, x, y) { + auto& sprite = scene.addComponent(id); + sprite.texture = scene.assets.getImage("lenna"); + transform.width = 30; transform.height = 30; } void update(Uint32 delta) { - Sprite::update(delta); - float speed = delta / 10.0f; if (scene.input.keyDown(afk::Keys::UP)) { transform.y -= speed; @@ -53,10 +53,30 @@ class DemoScene : public afk::Scene { assets.loadImage("lenna", "assets/lenna.png"); - add(*this, 100, 100); + ObjId id = add(*this, 100, 100).id; + character_ids.push_back(id); + } + + void update(Uint32 delta) override { + if (input.keyPressed(afk::Keys::A)) { + ObjId id = add(*this, 100, 100).id; + character_ids.push_back(id); + } + if (input.keyPressed(afk::Keys::R)) { + if (character_ids.size() > 0) { + ObjId id = character_ids.back(); + remove(id); + character_ids.pop_back(); + } + } + + Scene::update(delta); } void stop() { logger.log("Stopping!"); } + + private: + std::vector character_ids; }; class MainGame : public afk::Game { diff --git a/include/components/Sprite.h b/include/components/Sprite.h new file mode 100644 index 0000000..22367c1 --- /dev/null +++ b/include/components/Sprite.h @@ -0,0 +1,33 @@ +/** + * @file Sprite.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Stores sprite information for rendering engine + * @version 0.1 + * @date 2021-03-15 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef INCLUDE_COMPONENTS_SPRITE_H_ +#define INCLUDE_COMPONENTS_SPRITE_H_ + +#include "../assets/Texture.h" +#include "Component.h" + +namespace afk { + +class Sprite : public Component { + public: + /** + * @brief Construct a new Sprite object + * + */ + Sprite(); + + /// Texture of Sprite + Texture texture; +}; + +} // namespace afk + +#endif // INCLUDE_COMPONENTS_SPRITE_H_ diff --git a/include/components/Transform.h b/include/components/Transform.h index df27fe6..ae1fd23 100644 --- a/include/components/Transform.h +++ b/include/components/Transform.h @@ -23,8 +23,6 @@ class Transform : public Component { */ Transform(); - virtual ~Transform() = default; - /// X position on x y plane float x; diff --git a/include/entities/GameObject.h b/include/entities/GameObject.h index 47fe082..816e68a 100644 --- a/include/entities/GameObject.h +++ b/include/entities/GameObject.h @@ -14,9 +14,6 @@ #define INCLUDE_ENTITIES_GAMEOBJECT_H_ #include -#include -#include -#include #include #include "../components/Component.h" @@ -170,33 +167,8 @@ class GameObject { */ bool getHooked() const; - template - T& addComponent() { - std::size_t id = typeid(T).hash_code(); - components[id] = std::make_unique(); - return dynamic_cast(*components[id]); - } - - template - T& getComponent() { - std::size_t id = typeid(T).hash_code(); - return dynamic_cast(*components[id]); - } - - template - void removeComponent() { - std::size_t id = typeid(T).hash_code(); - components.erase(id); - } - - template - bool hasComponent() const { - std::size_t id = typeid(T).hash_code(); - return components.count(id) > 0; - } - /// Components - Transform transform; + Transform& transform; /// Autoassigned unique id const ObjId id; @@ -218,14 +190,11 @@ class GameObject { /// Parent Id ObjId parent_id; - /// Static id counter - static ObjId index; - /// Colliders std::vector colliders; - /// Components - std::map> components{}; + /// Static id counter + static ObjId index; }; } // namespace afk diff --git a/include/scene/Scene.h b/include/scene/Scene.h index e1e8d23..08e1f76 100644 --- a/include/scene/Scene.h +++ b/include/scene/Scene.h @@ -11,9 +11,9 @@ #ifndef INCLUDE_SCENE_SCENE_H_ #define INCLUDE_SCENE_SCENE_H_ -#include #include #include +#include #include #include @@ -26,6 +26,10 @@ * */ namespace afk { + +using ComponentArray = std::vector>; +using ComponentMap = std::unordered_map; + class Scene { public: /** @@ -73,17 +77,17 @@ class Scene { void stopInternal(); /** - * @brief Add game object to update and draw pool, returns by reference + * @brief Add GameObject to update and draw pool, returns by reference * - * @tparam T Type of game object + * @tparam T Type of GameObject * @tparam Args Arguments to forward to T * @param args Argument values which will be forwarded to T when constructing - * a new game object - * @return Reference to created game object + * a new GameObject + * @return Reference to created GameObject */ template T& add(Args&&... args) { - // Create the game object + // Create the GameObject GameObject* obj = new T(std::forward(args)...); // Add to lookup @@ -100,28 +104,12 @@ class Scene { } /** - * @brief Removes a game object from the scene pool - * - * @param id Id of object to remove - */ - void remove(const ObjId id); - - /** - * @brief Check if obj id exists in scene + * @brief Gets a GameObject by id and casts to type T * - * @param id Object id to check - * @return true If the object exists - * @return false If the object does not exist - */ - bool has(const ObjId id); - - /** - * @brief Gets a game object by id and casts to type T - * - * @tparam T Type of game object - * @param id Id of game object to look up - * @return Reference to game object if found - * @throws KeyLookupException if game object could not be found + * @tparam T Type of GameObject + * @param id ObjId of GameObject to look up + * @return Reference to GameObject if found + * @throws KeyLookupException if GameObject could not be found */ template T& get(const ObjId id) { @@ -135,11 +123,11 @@ class Scene { } /** - * @brief Gets a game object by id without the cast + * @brief Gets a GameObject by id without the cast * - * @param id Id of game object to look up - * @return Reference to game object if found - * @throws KeyLookupException if game object could not be found + * @param id ObjId of GameObject to look up + * @return Reference to GameObject if found + * @throws KeyLookupException if GameObject could not be found */ GameObject& get(const ObjId id) { if (!has(id)) { @@ -151,21 +139,129 @@ class Scene { return *entities.at(index); } - /// Service references + /** + * @brief Removes a GameObject from the scene pool + * + * @param id ObjId of GameObject to remove + */ + void remove(const ObjId id); + + /** + * @brief Check if GameObject id exists in scene + * + * @param id ObjId to check + * @return true If the GameObject exists + * @return false If the GameObject does not exist + */ + bool has(const ObjId id); + + /** + * @brief Add a component to the scene, linked to a GameObject by obj_id + * + * @tparam T Subclass of component + * @param obj_id ObjId of GameObject to attach to + * @return T& Reference to the component + */ + template + T& addComponent(const ObjId obj_id) { + // Get type code + std::size_t id = typeid(T).hash_code(); + + // Add to component map + component_map[id][obj_id] = components[id].size(); + + // Add component to vector + components[id].emplace_back(new T()); + + // Get the component + return getComponent(obj_id); + } + + /** + * @brief Get the Component object + * + * @tparam T Subclass of component + * @param obj_id ObjId of GameObject to search for component + * @return T& Reference to the component + */ + template + T& getComponent(const ObjId obj_id) { + // Get type code + const std::size_t id = typeid(T).hash_code(); + + // Find index in component map + unsigned int index = component_map[id][obj_id]; + + // Cast and return + return dynamic_cast(*components[id].at(index)); + } + + /** + * @brief Remove a component from an object + * + * @tparam T Type of component + * @param obj_id ObjId of GameObject to remove component from + */ + template + void removeComponent(const ObjId obj_id) { + // Get type code + const std::size_t id = typeid(T).hash_code(); + + // Remove by id + removeComponentById(obj_id, id); + } + + /** + * @brief Check if a GameObject has a component attached + * + * @tparam T Type of component + * @param obj_id ObjId of GameObject to check + */ + template + bool hasComponent(const ObjId obj_id) const { + // Get type code + std::size_t id = typeid(T).hash_code(); + + // Check count of id for type + return component_map.at(id).count(obj_id) != 0; + } + + /// Audio service reference AudioService& audio; + + /// Logger service reference LoggingService& logger; + + /// Display service reference DisplayService& display; + + /// Asset service reference AssetService& assets; + + /// Input service reference InputService& input; + + /// Scene service reference SceneService& scene; + + /// Config service reference ConfigService& config; private: - /// Holds game objects + /// Remove component by type id + void removeComponentById(const ObjId obj_id, const std::size_t id); + + /// Holds GameObjects std::vector> entities; - /// Quick gameobject lookup - std::map entity_map; + /// Quick GameObjects lookup + std::unordered_map entity_map; + + /// Hold GameObject Components + std::unordered_map components; + + /// Quick lookup of GameObject Components + std::unordered_map component_map; /// Store objects to be removed std::vector remove_pool; diff --git a/include/services/assets/AssetService.h b/include/services/assets/AssetService.h index 62cea34..d86087e 100644 --- a/include/services/assets/AssetService.h +++ b/include/services/assets/AssetService.h @@ -11,8 +11,8 @@ #ifndef INCLUDE_SERVICES_ASSETS_ASSETSERVICE_H_ #define INCLUDE_SERVICES_ASSETS_ASSETSERVICE_H_ -#include #include +#include #include "../../assets/Font.h" #include "../../assets/Sound.h" @@ -130,16 +130,16 @@ class AssetService { private: /// Container that stores all Sound assets - std::map loaded_audio; + std::unordered_map loaded_audio; /// Container that stores all Image assets - std::map loaded_image; + std::unordered_map loaded_image; /// Container that stores all Font assets - std::map loaded_font; + std::unordered_map loaded_font; /// Container that stores all Stream assets - std::map loaded_stream; + std::unordered_map loaded_stream; }; } // namespace afk diff --git a/include/services/config/ConfigService.h b/include/services/config/ConfigService.h index c2ad4b7..7a29988 100644 --- a/include/services/config/ConfigService.h +++ b/include/services/config/ConfigService.h @@ -11,9 +11,10 @@ #ifndef INCLUDE_SERVICES_CONFIG_CONFIGSERVICE_H_ #define INCLUDE_SERVICES_CONFIG_CONFIGSERVICE_H_ -#include #include #include +#include +#include namespace afk { @@ -117,7 +118,7 @@ class ConfigService { bool autosave; /// Container which stores all settings - std::map settings; + std::unordered_map settings; }; } // namespace afk diff --git a/src/components/Sprite.cpp b/src/components/Sprite.cpp new file mode 100644 index 0000000..93b0fed --- /dev/null +++ b/src/components/Sprite.cpp @@ -0,0 +1,20 @@ +/** + * @file Sprite.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Implementation of sprite component + * @version 0.1 + * @date 2021-03-15 + * + * @copyright Copyright (c) 2021 + * + */ +#include "components/Sprite.h" + +#include "services/Services.h" + +namespace afk { + +// Construct component +Sprite::Sprite() : Component(), texture() {} + +} // namespace afk diff --git a/src/entities/GameObject.cpp b/src/entities/GameObject.cpp index 7360106..9e53944 100644 --- a/src/entities/GameObject.cpp +++ b/src/entities/GameObject.cpp @@ -21,7 +21,8 @@ ObjId GameObject::index = 1; // Constructor GameObject::GameObject(Scene& scene, const float x, const float y, const int z) - : id(GameObject::index), + : transform(scene.addComponent(GameObject::index)), + id(GameObject::index), scene(scene), visible(true), enabled(true), @@ -35,7 +36,7 @@ GameObject::GameObject(Scene& scene, const float x, const float y, const int z) transform.z = z; } -// Destructor +// Destructor, remove components GameObject::~GameObject() {} // Update @@ -57,7 +58,6 @@ void GameObject::updateInternal() { // Set position transform.x += parent.transform.x - parent.transform.last_x; transform.y += parent.transform.y - parent.transform.last_y; - } catch (const KeyLookupException&) { scene.remove(id); } diff --git a/src/scene/Scene.cpp b/src/scene/Scene.cpp index 42c4fcb..1707320 100644 --- a/src/scene/Scene.cpp +++ b/src/scene/Scene.cpp @@ -13,6 +13,8 @@ #include #include "common/Exceptions.h" +#include "components/Sprite.h" +#include "components/Transform.h" #include "entities/GameObject.h" namespace afk { @@ -40,6 +42,16 @@ void Scene::draw() { for (auto& obj : entities) { if (obj->getVisible() && obj->getHooked()) { obj->draw(); + + // Render system + if (hasComponent(obj->id)) { + Sprite& sprite = getComponent(obj->id); + Transform& transform = getComponent(obj->id); + + // Draw image + sprite.texture.drawEx(transform.x, transform.y, transform.width, + transform.height, transform.angle); + } } } } @@ -59,39 +71,46 @@ void Scene::update(Uint32 delta) { } // Remove any game objects that need to be cleaned up - for (auto& id : remove_pool) { - // Get vector index - auto index = entity_map.at(id); + if (remove_pool.size() > 0) { + for (auto& elem : remove_pool) { + logger.log("Removing ID: " + std::to_string(elem)); + } - // Erase game object - entities.erase(entities.begin() + index); + for (const auto& obj_id : remove_pool) { + // Get vector index + unsigned int entity_index = entity_map[obj_id]; - // Remove from lookup map - entity_map.erase(id); + // Remove from lookup map + entity_map.erase(obj_id); - // We will need a sort after this - need_sort = true; - } + // Erase game object while keeping most indicies correct + entities[entity_index] = std::move(entities.back()); + entities.pop_back(); - // Clear remove pool - remove_pool.clear(); + // Update moved index + if (entities.size() > 0) { + auto& moved_obj = *entities[entity_index]; + entity_map[moved_obj.id] = entity_index; + } - // Sort flag toggled - if (need_sort) { - // Z sort, use defined < operator - std::sort(entities.begin(), entities.end(), - [](std::unique_ptr& obj1, - std::unique_ptr& obj2) -> bool { - return obj1->transform.z < obj2->transform.z; - }); - - // Repopulate lookup map - for (unsigned int i = 0; i < entities.size(); i++) { - entity_map[entities.at(i)->id] = i; + // Erase components + for (auto& comp_entry : component_map) { + removeComponentById(obj_id, comp_entry.first); + } } - // Done sorting - need_sort = false; + // Clear remove pool + remove_pool.clear(); + } + + // Sort sprites + if (need_sort) { + const std::size_t id = typeid(Sprite).hash_code(); + + // std::sort(components[id].begin(), components[id].end(), [](auto& c1, + // auto& c2) { + // return obj1->transform.z < obj2->transform.z; + // }); } } @@ -105,4 +124,25 @@ bool Scene::has(const ObjId id) { return entity_map.count(id) == 1; } +// Remove component by type id +void Scene::removeComponentById(const ObjId obj_id, const std::size_t id) { + // Check has + if (component_map[id].count(obj_id) > 0) { + // Copy index + int comp_index = component_map[id][obj_id]; + + // Erase from map + component_map[id].erase(obj_id); + + // Erase component + components[id][comp_index] = std::move(components[id].back()); + components[id].pop_back(); + + // Update moved index + if (components[id].size() > 0) { + component_map[id][obj_id] = comp_index; + } + } +} + } // namespace afk From 269219b4a093ca6bb09ffb25bb661f15804326de Mon Sep 17 00:00:00 2001 From: Allan Legemaate Date: Thu, 18 Mar 2021 17:41:57 -0400 Subject: [PATCH 03/24] Add collision component --- examples/ex_collision.cpp | 20 ++++++++++++--- include/components/Collider.h | 30 ++++++++++++++++++++++ include/components/Component.h | 6 ++++- include/components/Sprite.h | 2 +- include/components/Transform.h | 2 +- include/entities/GameObject.h | 46 +--------------------------------- include/entities/ObjId.h | 17 +++++++++++++ include/scene/Scene.h | 2 +- src/components/Collider.cpp | 20 +++++++++++++++ src/components/Component.cpp | 2 +- src/components/Sprite.cpp | 2 +- src/components/Transform.cpp | 4 +-- src/entities/GameObject.cpp | 45 --------------------------------- src/scene/Scene.cpp | 33 ++++++++++++++++++++---- 14 files changed, 124 insertions(+), 107 deletions(-) create mode 100644 include/components/Collider.h create mode 100644 include/entities/ObjId.h create mode 100644 src/components/Collider.cpp diff --git a/examples/ex_collision.cpp b/examples/ex_collision.cpp index 122af42..61fb749 100644 --- a/examples/ex_collision.cpp +++ b/examples/ex_collision.cpp @@ -9,7 +9,8 @@ * */ #include "../include/Game.h" -#include "../include/entities/Sprite.h" +#include "../include/components/Collider.h" +#include "../include/components/Sprite.h" #include "../include/entities/ui/Label.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" @@ -27,12 +28,20 @@ class DemoScene : public afk::Scene { assets.loadImage("lenna", "assets/lenna.png"); assets.loadFont("freesans", "assets/freesans.ttf", 12); - auto& lenna_1 = add(*this, "lenna", 10, 10); + auto& lenna_1 = add(*this, 10, 10); + addComponent(lenna_1.id); + auto& lenna_1_sprite = getComponent(lenna_1.id); + lenna_1_sprite.texture = assets.getImage("lenna"); + addComponent(lenna_1.id); lenna_1.transform.width = 40; lenna_1.transform.height = 40; lenna_1_id = lenna_1.id; - auto& lenna_2 = add(*this, "lenna", 10, 80); + auto& lenna_2 = add(*this, 10, 80); + addComponent(lenna_2.id); + auto& lenna_2_sprite = getComponent(lenna_2.id); + lenna_2_sprite.texture = assets.getImage("lenna"); + addComponent(lenna_2.id); lenna_2.transform.width = 40; lenna_2.transform.height = 40; lenna_2_id = lenna_2.id; @@ -57,11 +66,14 @@ class DemoScene : public afk::Scene { lenna_2.transform.y = input.mouseY(); } - if (lenna_1.isColliding(lenna_2)) { + auto& collider = getComponent(lenna_1_id); + if (collider.collisions.size() > 0) { label.setText("Colliding!"); } else { label.setText("Not colliding"); } + + Scene::update(delta); } void stop() { logger.log("Stopping!"); } diff --git a/include/components/Collider.h b/include/components/Collider.h new file mode 100644 index 0000000..c8d5b5f --- /dev/null +++ b/include/components/Collider.h @@ -0,0 +1,30 @@ + + +/** + * @file Component.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Base component + * @version 0.1 + * @date 2021-03-15 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef INCLUDE_COMPONENTS_COLLIDER_H_ +#define INCLUDE_COMPONENTS_COLLIDER_H_ + +#include +#include "components/Component.h" + +namespace afk { + +class Collider : public Component { + public: + explicit Collider(ObjId obj_id); + + std::vector collisions; +}; + +} // namespace afk + +#endif // INCLUDE_COMPONENTS_COLLIDER_H_ diff --git a/include/components/Component.h b/include/components/Component.h index b5db795..eb08385 100644 --- a/include/components/Component.h +++ b/include/components/Component.h @@ -11,12 +11,16 @@ #ifndef INCLUDE_COMPONENTS_COMPONENT_H_ #define INCLUDE_COMPONENTS_COMPONENT_H_ +#include "entities/ObjId.h" + namespace afk { class Component { public: - Component(); + explicit Component(ObjId obj_id); virtual ~Component() = default; + + const ObjId obj_id; }; } // namespace afk diff --git a/include/components/Sprite.h b/include/components/Sprite.h index 22367c1..16a2545 100644 --- a/include/components/Sprite.h +++ b/include/components/Sprite.h @@ -22,7 +22,7 @@ class Sprite : public Component { * @brief Construct a new Sprite object * */ - Sprite(); + explicit Sprite(ObjId obj_id); /// Texture of Sprite Texture texture; diff --git a/include/components/Transform.h b/include/components/Transform.h index ae1fd23..dc886dd 100644 --- a/include/components/Transform.h +++ b/include/components/Transform.h @@ -21,7 +21,7 @@ class Transform : public Component { * @brief Construct a new Transform object * */ - Transform(); + explicit Transform(ObjId obj_id); /// X position on x y plane float x; diff --git a/include/entities/GameObject.h b/include/entities/GameObject.h index 816e68a..30ba75e 100644 --- a/include/entities/GameObject.h +++ b/include/entities/GameObject.h @@ -14,13 +14,9 @@ #define INCLUDE_ENTITIES_GAMEOBJECT_H_ #include -#include -#include "../components/Component.h" #include "../components/Transform.h" - -/// Unique id type alias -using ObjId = Uint32; +#include "ObjId.h" namespace afk { @@ -83,43 +79,6 @@ class GameObject { */ void setParent(const ObjId parent_id); - /** - * @brief Add a collider with a game object - * - */ - void addCollider(const ObjId obj_id); - - /** - * @brief Remove a collider with a game object - * - */ - void removeCollider(const ObjId obj_id); - - /** - * @brief Checks collision between this game object and another. - * - * @param other Some other game object - * @return True on collision, else false - */ - bool isColliding(GameObject& other); - - /** - * @brief Checks collision between this game object and another. - * Calls on collide on both objects if there is a collision - * - * @param other Some other game object - * @return True on collision, else false - */ - bool collide(GameObject& other); - - /** - * @brief Callback which is triggered on collision with another game object if - * registered with the Scene. - * - * @param other The game object which is being collided with. - */ - virtual void onCollide(GameObject& other); - /** * @brief Set the visibility of the GameObject. Will not draw when not * visible. @@ -190,9 +149,6 @@ class GameObject { /// Parent Id ObjId parent_id; - /// Colliders - std::vector colliders; - /// Static id counter static ObjId index; }; diff --git a/include/entities/ObjId.h b/include/entities/ObjId.h new file mode 100644 index 0000000..b465b2e --- /dev/null +++ b/include/entities/ObjId.h @@ -0,0 +1,17 @@ +/** + * @file ObjId.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Declaration of ObjId type + * @version 0.1 + * @date 2017-01-03 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef INCLUDE_ENTITIES_OBJID_H_ +#define INCLUDE_ENTITIES_OBJID_H_ + +/// Unique id type alias +using ObjId = unsigned int; + +#endif // INCLUDE_ENTITIES_OBJID_H_ diff --git a/include/scene/Scene.h b/include/scene/Scene.h index 08e1f76..de45ed3 100644 --- a/include/scene/Scene.h +++ b/include/scene/Scene.h @@ -171,7 +171,7 @@ class Scene { component_map[id][obj_id] = components[id].size(); // Add component to vector - components[id].emplace_back(new T()); + components[id].emplace_back(new T(obj_id)); // Get the component return getComponent(obj_id); diff --git a/src/components/Collider.cpp b/src/components/Collider.cpp new file mode 100644 index 0000000..b376f9c --- /dev/null +++ b/src/components/Collider.cpp @@ -0,0 +1,20 @@ +/** + * @file Sprite.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Implementation of Collider component + * @version 0.1 + * @date 2021-03-15 + * + * @copyright Copyright (c) 2021 + * + */ +#include "components/Collider.h" + +#include "services/Services.h" + +namespace afk { + +// Construct component +Collider::Collider(ObjId obj_id) : Component(obj_id) {} + +} // namespace afk diff --git a/src/components/Component.cpp b/src/components/Component.cpp index 88d08d7..c5c00ff 100644 --- a/src/components/Component.cpp +++ b/src/components/Component.cpp @@ -13,6 +13,6 @@ namespace afk { // Constructor -Component::Component() {} +Component::Component(ObjId obj_id) : obj_id(obj_id) {} } // namespace afk diff --git a/src/components/Sprite.cpp b/src/components/Sprite.cpp index 93b0fed..9b2d344 100644 --- a/src/components/Sprite.cpp +++ b/src/components/Sprite.cpp @@ -15,6 +15,6 @@ namespace afk { // Construct component -Sprite::Sprite() : Component(), texture() {} +Sprite::Sprite(ObjId obj_id) : Component(obj_id), texture() {} } // namespace afk diff --git a/src/components/Transform.cpp b/src/components/Transform.cpp index 875b3f7..f8a66a0 100644 --- a/src/components/Transform.cpp +++ b/src/components/Transform.cpp @@ -12,8 +12,8 @@ namespace afk { -Transform::Transform() - : Component(), +Transform::Transform(ObjId obj_id) + : Component(obj_id), x(0), y(0), z(0), diff --git a/src/entities/GameObject.cpp b/src/entities/GameObject.cpp index 9e53944..2c19f20 100644 --- a/src/entities/GameObject.cpp +++ b/src/entities/GameObject.cpp @@ -62,13 +62,6 @@ void GameObject::updateInternal() { scene.remove(id); } } - - // Colliders - std::remove_if(colliders.begin(), colliders.end(), - [&](const auto& obj_id) { return !scene.has(obj_id); }); - for (auto& obj_id : colliders) { - collide(scene.get(obj_id)); - } } // Draw @@ -79,44 +72,6 @@ void GameObject::setParent(const ObjId parent_id) { this->parent_id = parent_id; } -// Add a collider with a game object -void GameObject::addCollider(const ObjId obj_id) { - colliders.push_back(obj_id); -} - -// Remove a collider with a game object -void GameObject::removeCollider(const ObjId obj_id) { - auto it = std::find(colliders.begin(), colliders.end(), obj_id); - if (it != colliders.end()) { - colliders.erase(it); - } -} - -// Is colliding with game object -bool GameObject::isColliding(GameObject& other) { - return transform.x < other.transform.x + other.transform.width && - transform.x + transform.width > other.transform.x && - transform.y < other.transform.y + other.transform.height && - transform.y + transform.height > other.transform.y; -} - -// Collide game objects -bool GameObject::collide(GameObject& other) { - bool colliding = isColliding(other); - - if (colliding) { - this->onCollide(other); - other.onCollide(*this); - } - - return colliding; -} - -// On collide can be overriden -void GameObject::onCollide(GameObject& other) { - (void)(other); -} - // Set visibility void GameObject::setVisible(const bool visible) { this->visible = visible; diff --git a/src/scene/Scene.cpp b/src/scene/Scene.cpp index 1707320..e597639 100644 --- a/src/scene/Scene.cpp +++ b/src/scene/Scene.cpp @@ -13,6 +13,7 @@ #include #include "common/Exceptions.h" +#include "components/Collider.h" #include "components/Sprite.h" #include "components/Transform.h" #include "entities/GameObject.h" @@ -70,12 +71,34 @@ void Scene::update(Uint32 delta) { obj->updateInternal(); } - // Remove any game objects that need to be cleaned up - if (remove_pool.size() > 0) { - for (auto& elem : remove_pool) { - logger.log("Removing ID: " + std::to_string(elem)); + // Collision system + std::size_t c_type = typeid(Collider).hash_code(); + ComponentArray& colliders = components[c_type]; + for (auto& comp : colliders) { + Collider& collider = dynamic_cast(*comp); + collider.collisions.clear(); + } + + for (auto& collider_1 : colliders) { + for (auto& collider_2 : colliders) { + Collider& col_1 = dynamic_cast(*collider_1); + Collider& col_2 = dynamic_cast(*collider_2); + Transform& tra_1 = getComponent(collider_1->obj_id); + Transform& tra_2 = getComponent(collider_2->obj_id); + + bool colliding = + tra_1.x < tra_2.x + tra_2.width && tra_1.x + tra_1.width > tra_2.x && + tra_1.y < tra_2.y + tra_2.height && tra_1.y + tra_1.height > tra_2.y; + + if (colliding) { + col_1.collisions.push_back(col_2.obj_id); + col_2.collisions.push_back(col_1.obj_id); + } } + } + // Remove any game objects that need to be cleaned up + if (remove_pool.size() > 0) { for (const auto& obj_id : remove_pool) { // Get vector index unsigned int entity_index = entity_map[obj_id]; @@ -105,7 +128,7 @@ void Scene::update(Uint32 delta) { // Sort sprites if (need_sort) { - const std::size_t id = typeid(Sprite).hash_code(); + // const std::size_t id = typeid(Sprite).hash_code(); // std::sort(components[id].begin(), components[id].end(), [](auto& c1, // auto& c2) { From 58c7e1c617807c9062b161e8209b2a49fdcbbfb6 Mon Sep 17 00:00:00 2001 From: alegemaate Date: Wed, 20 Apr 2022 22:25:53 -0400 Subject: [PATCH 04/24] feat: use EnTT --- .gitignore | 5 +- .vscode/settings.json | 11 +- .vscode/tasks.json | 20 ++- CMakeLists.txt | 20 +-- examples/CMakeLists.txt | 7 +- examples/ex_collision.cpp | 18 +-- examples/ex_fps.cpp | 35 +++--- examples/ex_keyboard.cpp | 58 ++++----- examples/ex_mouse.cpp | 25 ++-- examples/ex_particles.cpp | 86 ++++++------- examples/ex_physics.cpp | 77 ++++++++++++ examples/ex_rotate.cpp | 16 ++- examples/ex_sound.cpp | 1 - examples/ex_sprite.cpp | 9 +- examples/ex_ui.cpp | 4 +- include/common/Vec.h | 35 ++++++ include/components/Collider.h | 30 ----- include/components/Component.h | 28 ----- include/components/Particle.h | 144 ++++++++++++++++++++++ include/components/ParticleEmitter.h | 54 +++++++++ include/components/Physics.h | 44 +++++++ include/components/Sprite.h | 14 +-- include/components/Transform.h | 36 ++---- include/components/ui/Label.h | 39 ++++++ include/entities/GameObject.h | 6 +- include/entities/ObjId.h | 2 +- include/entities/Particle.h | 172 -------------------------- include/entities/ParticleEmitter.h | 106 ---------------- include/entities/Sprite.h | 91 -------------- include/scene/Scene.h | 174 ++++----------------------- include/systems/ParticleSystem.h | 124 +++++++++++++++++++ include/systems/PhysicsSystem.h | 41 +++++++ include/systems/RenderSystem.h | 38 ++++++ include/systems/UISystem.h | 37 ++++++ src/Game.cpp | 2 + src/assets/Texture.cpp | 6 +- src/color/Color.cpp | 18 ++- src/common/math.cpp | 6 +- src/common/str.cpp | 6 +- src/components/Collider.cpp | 20 --- src/components/Component.cpp | 18 --- src/components/Sprite.cpp | 20 --- src/components/Transform.cpp | 26 ---- src/entities/GameObject.cpp | 42 +++---- src/entities/Particle.cpp | 139 --------------------- src/entities/ParticleEmitter.cpp | 75 ------------ src/entities/Sprite.cpp | 55 --------- src/entities/ui/Button.cpp | 21 ++-- src/entities/ui/Checkbox.cpp | 24 ++-- src/entities/ui/Image.cpp | 8 +- src/entities/ui/Inputbox.cpp | 27 +++-- src/entities/ui/Label.cpp | 3 +- src/entities/ui/UIElement.cpp | 9 +- src/primitives/Primitives.cpp | 6 +- src/scene/Scene.cpp | 141 ++-------------------- 55 files changed, 952 insertions(+), 1327 deletions(-) create mode 100644 examples/ex_physics.cpp create mode 100644 include/common/Vec.h delete mode 100644 include/components/Collider.h delete mode 100644 include/components/Component.h create mode 100644 include/components/Particle.h create mode 100644 include/components/ParticleEmitter.h create mode 100644 include/components/Physics.h create mode 100644 include/components/ui/Label.h delete mode 100644 include/entities/Particle.h delete mode 100644 include/entities/ParticleEmitter.h delete mode 100644 include/entities/Sprite.h create mode 100644 include/systems/ParticleSystem.h create mode 100644 include/systems/PhysicsSystem.h create mode 100644 include/systems/RenderSystem.h create mode 100644 include/systems/UISystem.h delete mode 100644 src/components/Collider.cpp delete mode 100644 src/components/Component.cpp delete mode 100644 src/components/Sprite.cpp delete mode 100644 src/components/Transform.cpp delete mode 100644 src/entities/Particle.cpp delete mode 100644 src/entities/ParticleEmitter.cpp delete mode 100644 src/entities/Sprite.cpp diff --git a/.gitignore b/.gitignore index 0c6d177..cc55d64 100644 --- a/.gitignore +++ b/.gitignore @@ -48,4 +48,7 @@ Makefile install_manifest.txt bin docs -lib \ No newline at end of file +lib +compile_commands.json +.idea +build \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index a76a135..2361886 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -111,7 +111,12 @@ "filesystem": "cpp", "unordered_set": "cpp", "*.inc": "cpp", - "*.def": "cpp" + "*.def": "cpp", + "numbers": "cpp", + "semaphore": "cpp", + "any": "cpp", + "codecvt": "cpp" }, - "cmake.configureOnOpen": true -} \ No newline at end of file + "cmake.configureOnOpen": true, + "sonarlint.pathToCompileCommands": "c:\\Users\\alege\\Documents\\GitHub\\AfkLib\\compile_commands.json" +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 435c849..cb16d03 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -6,10 +6,28 @@ "type": "shell", "command": "make -j24", "problemMatcher": ["$gcc"], + "group": "build" + }, + { + "type": "cppbuild", + "label": "C/C++: g++.exe build active file", + "command": "C:\\msys64\\mingw32\\bin\\g++.exe", + "args": [ + "-fdiagnostics-color=always", + "-g", + "${file}", + "-o", + "${fileDirname}\\${fileBasenameNoExtension}.exe" + ], + "options": { + "cwd": "${fileDirname}" + }, + "problemMatcher": ["$gcc"], "group": { "kind": "build", "isDefault": true - } + }, + "detail": "Task generated by Debugger." } ] } diff --git a/CMakeLists.txt b/CMakeLists.txt index 66b0af5..ee3c82a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,25 +2,26 @@ cmake_minimum_required(VERSION 3.11) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) -set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) -set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/lib) +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/lib) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin) +set(CMAKE_EXPORT_COMPILE_COMMANDS on) project (afk VERSION 1.0.0 LANGUAGES CXX) # Add sources -file(GLOB_RECURSE SOURCES ${CMAKE_BINARY_DIR}/src/*.cpp) -file(GLOB_RECURSE HEADERS ${CMAKE_BINARY_DIR}/include/*.h) +file(GLOB_RECURSE SOURCES ${CMAKE_SOURCE_DIR}/src/*.cpp) +file(GLOB_RECURSE HEADERS ${CMAKE_SOURCE_DIR}/include/*.h) # Create lib add_library(${PROJECT_NAME} STATIC ${SOURCES} ${HEADERS}) # Add compile options target_compile_options(${PROJECT_NAME} PRIVATE -O2 -Wall -Wextra -pedantic) - + # Add include target_include_directories(${PROJECT_NAME} PUBLIC - $ + $ $ PRIVATE src) @@ -60,9 +61,10 @@ else(EMSCRIPTEN) find_library(SDL_TTF_LIBRARY NAMES SDL2_ttf REQUIRED) find_library(SDL_GFX_LIBRARY NAMES SDL2_gfx REQUIRED) find_library(SDL_MAIN_LIBRARY NAMES SDL2main REQUIRED) + find_package(EnTT REQUIRED) # Link Libs - target_link_libraries(${PROJECT_NAME} ${SDL_LIBRARY} ${SDL_MIXER_LIBRARY} ${SDL_IMAGE_LIBRARY} ${SDL_TTF_LIBRARY} ${SDL_GFX_LIBRARY} ${SDL_MAIN_LIBRARY}) + target_link_libraries(${PROJECT_NAME} ${SDL_LIBRARY} ${SDL_MIXER_LIBRARY} ${SDL_IMAGE_LIBRARY} ${SDL_TTF_LIBRARY} ${SDL_GFX_LIBRARY} ${SDL_MAIN_LIBRARY} EnTT::EnTT) endif(EMSCRIPTEN) # Install info @@ -103,4 +105,4 @@ else() endif() # Examples -include(${CMAKE_BINARY_DIR}/examples/CMakeLists.txt) \ No newline at end of file +include(${CMAKE_SOURCE_DIR}/examples/CMakeLists.txt) \ No newline at end of file diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 79e1509..585efa6 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -16,11 +16,13 @@ if(NOT EMSCRIPTEN) find_library(SDL_TTF_LIBRARY NAMES SDL2_ttf REQUIRED) find_library(SDL_GFX_LIBRARY NAMES SDL2_gfx REQUIRED) find_library(SDL_MAIN_LIBRARY NAMES SDL2main REQUIRED) + find_package(EnTT REQUIRED) endif(NOT EMSCRIPTEN) # Build examples -set(EXAMPLES ex_display ex_collision ex_sprite ex_ui ex_message_box ex_fps ex_keyboard ex_mouse ex_sound ex_particles ex_rotate) +# ex_collision ex_ui ex_message_box +set(EXAMPLES ex_display ex_sprite ex_rotate ex_fps ex_mouse ex_physics ex_sound ex_particles ex_keyboard) foreach(EX_NAME ${EXAMPLES}) add_executable(${EX_NAME} ${CMAKE_CURRENT_LIST_DIR}/${EX_NAME}.cpp) @@ -72,7 +74,8 @@ foreach(EX_NAME ${EXAMPLES}) ${SDL_MIXER_LIBRARY} ${SDL_IMAGE_LIBRARY} ${SDL_TTF_LIBRARY} - ${SDL_GFX_LIBRARY} + ${SDL_GFX_LIBRARY} + EnTT::EnTT afk ) endif(EMSCRIPTEN) diff --git a/examples/ex_collision.cpp b/examples/ex_collision.cpp index 61fb749..a94948f 100644 --- a/examples/ex_collision.cpp +++ b/examples/ex_collision.cpp @@ -33,8 +33,8 @@ class DemoScene : public afk::Scene { auto& lenna_1_sprite = getComponent(lenna_1.id); lenna_1_sprite.texture = assets.getImage("lenna"); addComponent(lenna_1.id); - lenna_1.transform.width = 40; - lenna_1.transform.height = 40; + lenna_1.transform.size.x = 40; + lenna_1.transform.size.y = 40; lenna_1_id = lenna_1.id; auto& lenna_2 = add(*this, 10, 80); @@ -42,8 +42,8 @@ class DemoScene : public afk::Scene { auto& lenna_2_sprite = getComponent(lenna_2.id); lenna_2_sprite.texture = assets.getImage("lenna"); addComponent(lenna_2.id); - lenna_2.transform.width = 40; - lenna_2.transform.height = 40; + lenna_2.transform.size.x = 40; + lenna_2.transform.size.y = 40; lenna_2_id = lenna_2.id; auto& label = add(*this, 0, 0); @@ -52,18 +52,18 @@ class DemoScene : public afk::Scene { } void update(Uint32 delta) { - auto& label = get(label_id); + auto& label = getComponent(label_id); auto& lenna_1 = get(lenna_1_id); auto& lenna_2 = get(lenna_2_id); if (input.mouseDown(afk::MouseButtons::LEFT)) { - lenna_1.transform.x = input.mouseX(); - lenna_1.transform.y = input.mouseY(); + lenna_1.transform.position.x = input.mouseX(); + lenna_1.transform.position.y = input.mouseY(); } if (input.mouseDown(afk::MouseButtons::RIGHT)) { - lenna_2.transform.x = input.mouseX(); - lenna_2.transform.y = input.mouseY(); + lenna_2.transform.position.x = input.mouseX(); + lenna_2.transform.position.y = input.mouseY(); } auto& collider = getComponent(lenna_1_id); diff --git a/examples/ex_fps.cpp b/examples/ex_fps.cpp index 5bf5095..88e82c0 100644 --- a/examples/ex_fps.cpp +++ b/examples/ex_fps.cpp @@ -10,8 +10,9 @@ */ #include "../include/Game.h" -#include "../include/entities/Sprite.h" -#include "../include/entities/ui/Label.h" +#include "../include/components/Sprite.h" +#include "../include/components/Transform.h" +#include "../include/components/ui/Label.h" #include "../include/random/RandomGenerator.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" @@ -35,16 +36,19 @@ class DemoScene : public afk::Scene { assets.loadFont("freesans", "assets/freesans.ttf", 64); assets.loadImage("lenna", "assets/lenna.png"); - afk::Label& label = add(*this, 10, 5, 100); + label_id = createEntity(); + createComponent(label_id, afk::Vec3(10, 5, 0)); + auto& label = createComponent(label_id); label.setText("FPS"); label.setFont("freesans"); - label_id = label.id; for (unsigned int i = 0; i < NUM_SPRITE; i++) { - afk::Sprite& sprite = add(*this, "lenna"); - sprite.transform.width = SPRITE_SIZE; - sprite.transform.height = SPRITE_SIZE; - sprites[i] = sprite.id; + auto entity = createEntity(); + createComponent(entity, "lenna"); + auto& transform = createComponent(entity); + transform.size.x = SPRITE_SIZE; + transform.size.y = SPRITE_SIZE; + sprites[i] = entity; } } @@ -55,21 +59,22 @@ class DemoScene : public afk::Scene { int fps = display.getFps(); - get(label_id).setText(std::to_string(fps)); + auto& label = getComponent(label_id); + label.setText(std::to_string(fps)); for (unsigned int i = 0; i < NUM_SPRITE; i++) { - afk::Sprite& sprite = get(sprites[i]); - sprite.transform.x = fmod(iter + i, SCREEN_W); - sprite.transform.y = sin(iter / 100.0f + i) * SCREEN_H_2 + SCREEN_H_2; - sprite.transform.angle += delta / 10.0f; + auto& transform = getComponent(sprites[i]); + transform.position.x = fmod(iter + i, SCREEN_W); + transform.position.y = sin(iter / 100.0f + i) * SCREEN_H_2 + SCREEN_H_2; + transform.angle += delta / 10.0f; } } void stop() { logger.log("Stopping!"); } private: - ObjId label_id = -1; - ObjId sprites[NUM_SPRITE]; + entt::entity label_id; + entt::entity sprites[NUM_SPRITE]; float iter = 0; }; diff --git a/examples/ex_keyboard.cpp b/examples/ex_keyboard.cpp index d389beb..56ff847 100644 --- a/examples/ex_keyboard.cpp +++ b/examples/ex_keyboard.cpp @@ -10,36 +10,31 @@ */ #include "../include/Game.h" #include "../include/components/Sprite.h" +#include "../include/components/Transform.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" -class Character : public afk::GameObject { - public: - Character(afk::Scene& scene, const float x, const float y) - : GameObject(scene, x, y) { - auto& sprite = scene.addComponent(id); - sprite.texture = scene.assets.getImage("lenna"); - - transform.width = 30; - transform.height = 30; - } +void characterSystem(entt::registry& registry, + afk::InputService& input, + Uint32 delta) { + auto view = registry.view(); - void update(Uint32 delta) { + for (auto [entity, transform] : view.each()) { float speed = delta / 10.0f; - if (scene.input.keyDown(afk::Keys::UP)) { - transform.y -= speed; + if (input.keyDown(afk::Keys::UP)) { + transform.position.y -= speed; } - if (scene.input.keyDown(afk::Keys::DOWN)) { - transform.y += speed; + if (input.keyDown(afk::Keys::DOWN)) { + transform.position.y += speed; } - if (scene.input.keyDown(afk::Keys::LEFT)) { - transform.x -= speed; + if (input.keyDown(afk::Keys::LEFT)) { + transform.position.x -= speed; } - if (scene.input.keyDown(afk::Keys::RIGHT)) { - transform.x += speed; + if (input.keyDown(afk::Keys::RIGHT)) { + transform.position.x += speed; } } -}; +} class DemoScene : public afk::Scene { public: @@ -53,30 +48,39 @@ class DemoScene : public afk::Scene { assets.loadImage("lenna", "assets/lenna.png"); - ObjId id = add(*this, 100, 100).id; + createCharacter(); + } + + void createCharacter() { + entt::entity id = createEntity(); + createComponent(id, afk::Vec3(100, 100, 0), + afk::Vec2(40, 40)); + createComponent(id, "lenna"); character_ids.push_back(id); } void update(Uint32 delta) override { + Scene::update(delta); + if (input.keyPressed(afk::Keys::A)) { - ObjId id = add(*this, 100, 100).id; - character_ids.push_back(id); + createCharacter(); } + if (input.keyPressed(afk::Keys::R)) { if (character_ids.size() > 0) { - ObjId id = character_ids.back(); - remove(id); + entt::entity id = character_ids.back(); + destroyEntity(id); character_ids.pop_back(); } } - Scene::update(delta); + characterSystem(getRegistry(), input, delta); } void stop() { logger.log("Stopping!"); } private: - std::vector character_ids; + std::vector character_ids; }; class MainGame : public afk::Game { diff --git a/examples/ex_mouse.cpp b/examples/ex_mouse.cpp index d0fbb32..6ae78da 100644 --- a/examples/ex_mouse.cpp +++ b/examples/ex_mouse.cpp @@ -9,7 +9,8 @@ * */ #include "../include/Game.h" -#include "../include/entities/Sprite.h" +#include "../include/components/Sprite.h" +#include "../include/components/Transform.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" @@ -25,31 +26,31 @@ class DemoScene : public afk::Scene { assets.loadImage("lenna", "assets/lenna.png"); - afk::Sprite& lenna = add(*this, "lenna", 100, 100); - lenna.transform.width = 30; - lenna.transform.height = 30; - lennaId = lenna.id; + lennaId = createEntity(); + createComponent(lennaId, "lenna"); + createComponent(lennaId, afk::Vec3(100, 100, 0), + afk::Vec2(30, 30)); } void update(Uint32 delta) { Scene::update(delta); - afk::Sprite& lenna = get(lennaId); + auto& transform = getComponent(lennaId); - if (input.mousePressed(afk::MouseButtons::LEFT)) { - lenna.transform.x = input.mouseX(); - lenna.transform.y = input.mouseY(); + if (input.mouseDown(afk::MouseButtons::LEFT)) { + transform.position.x = input.mouseX(); + transform.position.y = input.mouseY(); } if (input.mouseDown(afk::MouseButtons::RIGHT)) { - lenna.transform.width = input.mouseX(); - lenna.transform.height = input.mouseY(); + transform.size.x = input.mouseX(); + transform.size.y = input.mouseY(); } } void stop() { logger.log("Stopping!"); } private: - ObjId lennaId; + entt::entity lennaId; }; int main(int argv, char** args) { diff --git a/examples/ex_particles.cpp b/examples/ex_particles.cpp index 02205bd..04042eb 100644 --- a/examples/ex_particles.cpp +++ b/examples/ex_particles.cpp @@ -10,7 +10,10 @@ */ #include "../include/Game.h" #include "../include/color/Color.h" -#include "../include/entities/ParticleEmitter.h" +#include "../include/common/Vec.h" +#include "../include/components/Particle.h" +#include "../include/components/ParticleEmitter.h" +#include "../include/components/Transform.h" #include "../include/random/RandomGenerator.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" @@ -30,68 +33,67 @@ class DemoScene : public afk::Scene { assets.loadImage("fuzzball", "assets/fuzzball.png"); - afk::ParticleEmitter& emitter = add(*this, 256, 256); - emitter.transform.width = 30; - emitter.transform.height = 30; + emitter_1_id = createEntity(); + auto& emitter_1 = createComponent(emitter_1_id, 10); + createComponent(emitter_1_id, afk::Vec3(256, 256, 0), + afk::Vec2(30, 30)); for (int i = 0; i < 100; i++) { - auto particle = std::make_unique( - *this, 0, 0, 0, afk::ParticleType::SQUARE); - particle->setLifespan(afk::Random::randomInt(100, 1000)); - particle->setSize(10.0f, 3.0f); - particle->setColor(afk::color::rgb(128, 22, 22), - afk::color::rgb(100, 100, 100)); - particle->setVelocity(afk::Random::randomFloat(-5.0f, 5.0f), - afk::Random::randomFloat(-1.0f, -2.0f)); - particle->setAcceleration(0, 0.2f); - // emitter.addParticle(particle); + auto& [particle, physics] = emitter_1.addParticle(); + particle.setType(afk::ParticleType::SQUARE); + particle.setLifespan(afk::Random::randomInt(100, 1000)); + particle.setSize(10.0f, 3.0f); + particle.setColor(afk::color::rgb(128, 22, 22), + afk::color::rgb(100, 100, 100)); + physics.setVelocity(afk::Random::randomFloat(-5.0f, 5.0f), + afk::Random::randomFloat(-1.0f, -2.0f)); + physics.setAcceleration(0, 2.0f); } - afk::ParticleEmitter& emitter_2 = - add(*this, 128, 256); - emitter_2.transform.width = 1; - emitter_2.transform.height = 1; + emitter_2_id = createEntity(); + auto& emitter_2 = createComponent(emitter_2_id, 10); + createComponent(emitter_2_id, afk::Vec3(128, 256, 0), + afk::Vec2(1, 1)); for (int i = 0; i < 100; i++) { - auto particle = std::make_unique( - *this, 0, 0, 0, afk::ParticleType::CIRCLE); - particle->setLifespan(afk::Random::randomInt(100, 200)); - particle->setSize(3.0f, 2.0f); - particle->setColor(afk::color::blue, afk::color::white); - particle->setVelocity(afk::Random::randomFloat(-5, 5), -100); - particle->setAcceleration(0, 3.0f); - // emitter_2.addParticle(particle); + auto& [particle, physics] = emitter_2.addParticle(); + particle.setType(afk::ParticleType::CIRCLE); + particle.setLifespan(afk::Random::randomInt(1000, 2000)); + particle.setSize(3.0f, 2.0f); + particle.setColor(afk::color::blue, afk::color::white); + physics.setVelocity(afk::Random::randomFloat(-20.0, 20.0), -200.0f); + physics.setAcceleration(0, 200.0f); } - afk::ParticleEmitter& emitter_3 = - add(*this, 384, 256); - emitter_3.transform.width = 5; - emitter_3.transform.height = 5; - smoke_id = emitter_3.id; + emitter_3_id = createEntity(); + auto& emitter_3 = createComponent(emitter_3_id, 10); + createComponent(emitter_3_id, afk::Vec3(384, 256, 0), + afk::Vec2(5, 5)); for (int i = 0; i < 400; i++) { - auto particle = std::make_unique(*this, 0, 0, 0, - afk::ParticleType::IMAGE); - particle->setLifespan(afk::Random::randomInt(800, 1500)); - particle->setTexture("fuzzball"); - particle->setSize(16.0f, 20.0f); - particle->setVelocity(afk::Random::randomFloat(2.0f, 2.5f), -5.0f); - // emitter_3.addParticle(particle); + auto& [particle, physics] = emitter_3.addParticle(); + particle.setType(afk::ParticleType::IMAGE); + particle.setLifespan(afk::Random::randomInt(800, 1500)); + particle.setSize(16.0f, 20.0f); + particle.setTexture("fuzzball"); + physics.setVelocity(afk::Random::randomFloat(2.0f, 2.5f), -5.0f); } } void update(Uint32 delta) { Scene::update(delta); - auto& smoke_emitter = get(smoke_id); - smoke_emitter.transform.x = input.mouseX(); - smoke_emitter.transform.y = input.mouseY(); + auto& smoke_transform = getComponent(emitter_3_id); + smoke_transform.position.x = input.mouseX(); + smoke_transform.position.y = input.mouseY(); } void stop() { logger.log("Stopping!"); } private: - ObjId smoke_id; + entt::entity emitter_1_id; + entt::entity emitter_2_id; + entt::entity emitter_3_id; }; int main(int argv, char** args) { diff --git a/examples/ex_physics.cpp b/examples/ex_physics.cpp new file mode 100644 index 0000000..45ddd90 --- /dev/null +++ b/examples/ex_physics.cpp @@ -0,0 +1,77 @@ +/** + * @file ex_physics.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Demonstrates usage of physics component + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#include "../include/Game.h" +#include "../include/common/Vec.h" +#include "../include/components/Physics.h" +#include "../include/components/Sprite.h" +#include "../include/components/Transform.h" +#include "../include/scene/Scene.h" + +void bounceSystem(entt::registry& registry) { + auto view = registry.view(); + + for (auto [entity, transform, physics] : view.each()) { + if (transform.position.x > 512 - transform.size.x) { + physics.velocity.x *= -1; + } + if (transform.position.y > 512 - transform.size.y) { + physics.velocity.y *= -1; + } + if (transform.position.x < 0) { + physics.velocity.x *= -1; + } + if (transform.position.y < 0) { + physics.velocity.y *= -1; + } + } +} + +class DemoScene : public afk::Scene { + public: + void start() { + logger.log("Starting!"); + + display.setWindowSize(512, 512); + display.setBufferSize(512, 512); + display.setMode(afk::DisplayMode::WINDOWED); + display.setTitle("ex_physics"); + + assets.loadImage("lenna", "assets/lenna.png"); + + lennaId = createEntity(); + createComponent(lennaId, "lenna"); + createComponent(lennaId, afk::Vec3(0, 0, 0), + afk::Vec2(40, 40)); + createComponent(lennaId, afk::Vec2(100.0f, 400.0f)); + } + + void update(Uint32 delta) { + Scene::update(delta); + bounceSystem(getRegistry()); + } + + void stop() { logger.log("Stopping!"); } + + private: + entt::entity lennaId; +}; + +int main(int argv, char** args) { + afk::Game game = afk::Game(); + + afk::SceneService& scenes = afk::Services::getSceneService(); + scenes.addScene("demo"); + scenes.setNextScene("demo"); + + game.start(); + + return 0; +} diff --git a/examples/ex_rotate.cpp b/examples/ex_rotate.cpp index a422e14..6613aa4 100644 --- a/examples/ex_rotate.cpp +++ b/examples/ex_rotate.cpp @@ -9,7 +9,9 @@ * */ #include "../include/Game.h" -#include "../include/entities/Sprite.h" +#include "../include/common/Vec.h" +#include "../include/components/Sprite.h" +#include "../include/components/Transform.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" @@ -25,21 +27,23 @@ class DemoScene : public afk::Scene { assets.loadImage("lenna", "assets/lenna.png"); - afk::Sprite& lenna = add(*this, "lenna"); - lennaId = lenna.id; + lennaId = createEntity(); + createComponent(lennaId, "lenna"); + createComponent(lennaId, afk::Vec3(156, 156, 0), + afk::Vec2(200, 200)); } void update(Uint32 delta) { Scene::update(delta); - afk::Sprite& lenna = get(lennaId); - lenna.transform.angle += delta / 10.0f; + auto& transform = getComponent(lennaId); + transform.angle += delta / 10.0f; } void stop() { logger.log("Stopping!"); } private: - ObjId lennaId; + entt::entity lennaId; }; int main(int argv, char** args) { diff --git a/examples/ex_sound.cpp b/examples/ex_sound.cpp index e8c5884..af537d7 100644 --- a/examples/ex_sound.cpp +++ b/examples/ex_sound.cpp @@ -9,7 +9,6 @@ * */ #include "../include/Game.h" -#include "../include/entities/Sprite.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" diff --git a/examples/ex_sprite.cpp b/examples/ex_sprite.cpp index f8c3299..7bd32a5 100644 --- a/examples/ex_sprite.cpp +++ b/examples/ex_sprite.cpp @@ -9,7 +9,9 @@ * */ #include "../include/Game.h" -#include "../include/entities/Sprite.h" +#include "../include/common/Vec.h" +#include "../include/components/Sprite.h" +#include "../include/components/Transform.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" @@ -25,7 +27,10 @@ class DemoScene : public afk::Scene { assets.loadImage("lenna", "assets/lenna.png"); - add(*this, "lenna"); + auto sprite = createEntity(); + createComponent(sprite, "lenna"); + createComponent(sprite, afk::Vec3(0, 0, 0), + afk::Vec2(50, 50)); } void stop() { logger.log("Stopping!"); } diff --git a/examples/ex_ui.cpp b/examples/ex_ui.cpp index 29925dc..0f41832 100644 --- a/examples/ex_ui.cpp +++ b/examples/ex_ui.cpp @@ -66,8 +66,8 @@ class DemoScene : public afk::Scene { afk::Image& image = add(*this, 10, 120); image.setTexture("lenna"); - image.transform.width = 20; - image.transform.height = 20; + image.transform.size.x = 20; + image.transform.size.y = 20; image.setOnClick([]() { afk::MessageBox message_box(afk::MessageBoxType::INFO); message_box.setTitle("Nice"); diff --git a/include/common/Vec.h b/include/common/Vec.h new file mode 100644 index 0000000..393d291 --- /dev/null +++ b/include/common/Vec.h @@ -0,0 +1,35 @@ +/** + * @file vec.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Vec types + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef INCLUDE_COMMON_VEC_H_ +#define INCLUDE_COMMON_VEC_H_ + +namespace afk { + +struct Vec2 { + Vec2() : x(0), y(0) {} + Vec2(float x, float y) : x(x), y(y) {} + + float x; + float y; +}; + +struct Vec3 { + Vec3() : x(0), y(0), z(0) {} + Vec3(float x, float y, float z) : x(x), y(y), z(z) {} + + float x; + float y; + float z; +}; + +} // namespace afk + +#endif // INCLUDE_COMMON_VEC_H_ diff --git a/include/components/Collider.h b/include/components/Collider.h deleted file mode 100644 index c8d5b5f..0000000 --- a/include/components/Collider.h +++ /dev/null @@ -1,30 +0,0 @@ - - -/** - * @file Component.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Base component - * @version 0.1 - * @date 2021-03-15 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_COMPONENTS_COLLIDER_H_ -#define INCLUDE_COMPONENTS_COLLIDER_H_ - -#include -#include "components/Component.h" - -namespace afk { - -class Collider : public Component { - public: - explicit Collider(ObjId obj_id); - - std::vector collisions; -}; - -} // namespace afk - -#endif // INCLUDE_COMPONENTS_COLLIDER_H_ diff --git a/include/components/Component.h b/include/components/Component.h deleted file mode 100644 index eb08385..0000000 --- a/include/components/Component.h +++ /dev/null @@ -1,28 +0,0 @@ -/** - * @file Component.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Base component - * @version 0.1 - * @date 2021-03-15 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_COMPONENTS_COMPONENT_H_ -#define INCLUDE_COMPONENTS_COMPONENT_H_ - -#include "entities/ObjId.h" - -namespace afk { - -class Component { - public: - explicit Component(ObjId obj_id); - virtual ~Component() = default; - - const ObjId obj_id; -}; - -} // namespace afk - -#endif // INCLUDE_COMPONENTS_COMPONENT_H_ diff --git a/include/components/Particle.h b/include/components/Particle.h new file mode 100644 index 0000000..1799048 --- /dev/null +++ b/include/components/Particle.h @@ -0,0 +1,144 @@ +/** + * @file Particle.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Particle + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef INCLUDE_COMPONENTS_PARTICLE_H_ +#define INCLUDE_COMPONENTS_PARTICLE_H_ + +#include +#include "../color/Color.h" +#include "../common/Vec.h" + +namespace afk { + +enum class ParticleType : int { + PIXEL, + SQUARE, + CIRCLE, + IMAGE, + NONE, +}; + +struct Particle { + /// Constructor + Particle(ParticleType type = ParticleType::PIXEL) + : type(type), + start_size(1), + end_size(1), + age(0), + lifespan(1000), + start_color(color::black), + end_color(color::black), + texture(""){}; + + Particle(const Particle& part) + : type(part.type), + start_size(part.start_size), + end_size(part.end_size), + age(0), + lifespan(part.lifespan), + start_color(part.start_color), + end_color(part.end_color), + texture(part.texture){}; + + /** + * @brief Set the type + * + * @param type Type of particle + */ + void setType(ParticleType type) { this->type = type; } + + /** + * @brief Set the size of the particle in pixels + * + * @param size Size of particle + */ + void setSize(const float size) { + this->start_size = size; + this->end_size = size; + } + + /** + * @brief Set the size of particle over lifespan + * + * @param start_size Size to start at + * @param end_size Size to end at + */ + void setSize(const float start_size, const float end_size) { + this->start_size = start_size; + this->end_size = end_size; + } + + /** + * @brief Set the lifespan of particle in ms + * + * @param lifespan Number of ms to stay alive + */ + void setLifespan(const float lifespan) { + this->lifespan = lifespan; + this->age = lifespan; + } + + /** + * @brief Set the particle color + * + * @param color Color to set to + */ + void setColor(const color::Color& color) { + this->start_color = color; + this->end_color = color; + } + + /** + * @brief Set the particle color over lifespan + * + * @param start_color Starting color + * @param end_color Ending color + */ + void setColor(const color::Color& start_color, + const color::Color& end_color) { + this->start_color = start_color; + this->end_color = end_color; + } + + /** + * @brief Set the texture id of the particle + * + * @param texture Texture id + */ + void setTexture(const std::string& texture) { this->texture = texture; } + + /// Type of particle + ParticleType type; + + /// Starting size + float start_size; + + /// Ending size + float end_size; + + /// Current age + float age; + + /// Max lifespan + float lifespan; + + /// Start color + color::Color start_color; + + /// End color + color::Color end_color; + + /// String + std::string texture; +}; + +} // namespace afk + +#endif // INCLUDE_COMPONENTS_PARTICLE_H_ diff --git a/include/components/ParticleEmitter.h b/include/components/ParticleEmitter.h new file mode 100644 index 0000000..c91bc08 --- /dev/null +++ b/include/components/ParticleEmitter.h @@ -0,0 +1,54 @@ +/** + * @file ParticleEmitter.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Manage particles + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef INCLUDE_COMPONENTS_PARTICLE_EMITTER_H_ +#define INCLUDE_COMPONENTS_PARTICLE_EMITTER_H_ + +#include +#include +#include + +#include "../color/Color.h" +#include "../common/Vec.h" +#include "./Particle.h" +#include "./Physics.h" + +namespace afk { + +using ParticleTemplate = std::pair; + +struct ParticleEmitter { + /// Constructor + ParticleEmitter(float frequency) : frequency(frequency), counter(0){}; + + /** + * @brief Add a particle to the emitter pool + * + * @param particle Particle template to add + * @return Particle& Reference to added particle + */ + ParticleTemplate& addParticle() { + templates.emplace_back(std::make_pair(Particle(), Physics())); + return templates.back(); + } + + /// Particle templates + std::vector templates; + + /// Frequency of emit + float frequency; + + /// Counter + float counter; +}; + +} // namespace afk + +#endif // INCLUDE_COMPONENTS_PARTICLE_EMITTER_H_ diff --git a/include/components/Physics.h b/include/components/Physics.h new file mode 100644 index 0000000..7850c12 --- /dev/null +++ b/include/components/Physics.h @@ -0,0 +1,44 @@ +/** + * @file Physics.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Physics data component + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef INCLUDE_COMPONENTS_PHYSICS_H_ +#define INCLUDE_COMPONENTS_PHYSICS_H_ + +#include "../common/Vec.h" + +namespace afk { + +struct Physics { + /// Constructors + Physics(Vec2 velocity, Vec2 acceleration) + : velocity(velocity), acceleration(acceleration) {} + + Physics(Vec2 velocity) : velocity(velocity) {} + + Physics() {} + + void setVelocity(Vec2 velocity) { this->velocity = velocity; } + + void setVelocity(float x, float y) { this->velocity = Vec2(x, y); } + + void setAcceleration(Vec2 acceleration) { this->acceleration = acceleration; } + + void setAcceleration(float x, float y) { this->acceleration = Vec2(x, y); } + + /// X and Y velocity + Vec2 velocity; + + /// X and Y acceleration + Vec2 acceleration; +}; + +} // namespace afk + +#endif // INCLUDE_COMPONENTS_PHYSICS_H_ diff --git a/include/components/Sprite.h b/include/components/Sprite.h index 16a2545..70c7a47 100644 --- a/include/components/Sprite.h +++ b/include/components/Sprite.h @@ -11,21 +11,13 @@ #ifndef INCLUDE_COMPONENTS_SPRITE_H_ #define INCLUDE_COMPONENTS_SPRITE_H_ -#include "../assets/Texture.h" -#include "Component.h" +#include namespace afk { -class Sprite : public Component { - public: - /** - * @brief Construct a new Sprite object - * - */ - explicit Sprite(ObjId obj_id); - +struct SpriteComponent { /// Texture of Sprite - Texture texture; + std::string texture; }; } // namespace afk diff --git a/include/components/Transform.h b/include/components/Transform.h index dc886dd..6fd44c6 100644 --- a/include/components/Transform.h +++ b/include/components/Transform.h @@ -11,41 +11,19 @@ #ifndef INCLUDE_COMPONENTS_TRANSFORM_H_ #define INCLUDE_COMPONENTS_TRANSFORM_H_ -#include "Component.h" +#include "../common/Vec.h" namespace afk { -class Transform : public Component { - public: - /** - * @brief Construct a new Transform object - * - */ - explicit Transform(ObjId obj_id); +struct Transform { + /// Position on x y z plane + Vec3 position; - /// X position on x y plane - float x; - - /// Y position on x y plane - float y; - - /// Z position, used for sorting - int z; - - /// Height in pixels of game object - int height; - - /// Width in pixels of game object - int width; + /// Size + Vec2 size; /// Rotation - float angle; - - /// Last position y - int last_x; - - /// Last position x - int last_y; + float angle = 0.0f; }; } // namespace afk diff --git a/include/components/ui/Label.h b/include/components/ui/Label.h new file mode 100644 index 0000000..9de9ac6 --- /dev/null +++ b/include/components/ui/Label.h @@ -0,0 +1,39 @@ +/** + * @file Label.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief UI Label + * @version 0.1 + * @date 2021-03-15 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef INCLUDE_COMPONENTS_LABEL_H_ +#define INCLUDE_COMPONENTS_LABEL_H_ + +#include + +namespace afk { + +struct LabelComponent { + /// Constructor + LabelComponent() : text(""), font("") {} + + LabelComponent(const std::string& text, const std::string& font) + : text(text), font(font) {} + + /// Text of Label + std::string text; + + /// Font of label + std::string font; + + /// Setters + void setText(const std::string& text) { this->text = text; } + + void setFont(const std::string& font) { this->font = font; } +}; + +} // namespace afk + +#endif // INCLUDE_COMPONENTS_LABEL_H_ diff --git a/include/entities/GameObject.h b/include/entities/GameObject.h index 30ba75e..cbb3c52 100644 --- a/include/entities/GameObject.h +++ b/include/entities/GameObject.h @@ -16,13 +16,11 @@ #include #include "../components/Transform.h" +#include "../scene/Scene.h" #include "ObjId.h" namespace afk { -// Forward declare scene class -class Scene; - /** * @brief A collidable object! Parent class for many others * @@ -127,7 +125,7 @@ class GameObject { bool getHooked() const; /// Components - Transform& transform; + Transform transform; /// Autoassigned unique id const ObjId id; diff --git a/include/entities/ObjId.h b/include/entities/ObjId.h index b465b2e..b22e7fe 100644 --- a/include/entities/ObjId.h +++ b/include/entities/ObjId.h @@ -12,6 +12,6 @@ #define INCLUDE_ENTITIES_OBJID_H_ /// Unique id type alias -using ObjId = unsigned int; +using ObjId = unsigned long long; #endif // INCLUDE_ENTITIES_OBJID_H_ diff --git a/include/entities/Particle.h b/include/entities/Particle.h deleted file mode 100644 index 8571159..0000000 --- a/include/entities/Particle.h +++ /dev/null @@ -1,172 +0,0 @@ -/** - * @file Particle.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Just little blips that make things look cool - * @version 0.1 - * @date 2021-03-08 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_PARTICLE_H_ -#define INCLUDE_ENTITIES_PARTICLE_H_ - -#include "../entities/Sprite.h" -#include "../primitives/Primitives.h" - -namespace afk { - -/** - * @brief Possible types of particles - * - */ -enum class ParticleType : int { - PIXEL, - SQUARE, - CIRCLE, - IMAGE, - NONE, -}; - -/** - * @brief Represents a single Particle - * - */ -class Particle : public Sprite { - public: - /** - * @brief Create a new particle - * - * @param x X position - * @param y Y position - * @param type Type of particle - */ - explicit Particle(Scene& scene, - float x = 0.0f, - float y = 0.0f, - float z = 0, - ParticleType type = ParticleType::PIXEL); - - /** - * @brief Update particle - * - * @param delta Time since last call in ms - * - */ - void update(Uint32 delta) override; - - /** - * @brief Draw particle - * - */ - void draw() override; - - /** - * @brief Set the size of the particle in pixels - * - * @param size Size of particle - */ - void setSize(const float size); - - /** - * @brief Set the size of particle over lifespan - * - * @param start_size Size to start at - * @param end_size Size to end at - */ - void setSize(const float start_size, const float end_size); - - /** - * @brief Set the velocity of particle - * - * @param x X velocity in pixels per second - * @param y Y velocity in pixels per second - */ - void setVelocity(const float x, const float y); - - /** - * @brief Set the acceleration of particle - * - * @param x X acceleration in pixels per second - * @param y Y acceleration in pixels per second - */ - void setAcceleration(const float x, const float y); - - /** - * @brief Set the lifespan of particle in ms - * - * @param lifespan Number of ms to stay alive - */ - void setLifespan(const float lifespan); - - /** - * @brief Set the particle color - * - * @param color Color to set to - */ - void setColor(const color::Color& color); - - /** - * @brief Set the particle color over lifespan - * - * @param start_color Starting color - * @param end_color Ending color - */ - void setColor(const color::Color& start_color, const color::Color& end_color); - - /** - * @brief Reset age - * - */ - void reset(); - - /** - * @brief Check if dead - * - */ - bool dead(); - - private: - /// Type of particle - ParticleType type; - - /// Starting size - float start_size; - - /// Ending size - float end_size; - - /// Velocity x - float velocity_x; - - /// Velocity y - float velocity_y; - - /// Acceleration x - float acceleration_x; - - /// Acceleration y - float acceleration_y; - - /// Current age - float age; - - /// Max lifespan - float lifespan; - - /// Start color - color::Color start_color; - - /// End color - color::Color end_color; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_PARTICLE_H_ - -/** - * @example ex_particles.cpp - * This is an example of how to use the ParticleEmitter class to create particle - * effects. - */ diff --git a/include/entities/ParticleEmitter.h b/include/entities/ParticleEmitter.h deleted file mode 100644 index 7403069..0000000 --- a/include/entities/ParticleEmitter.h +++ /dev/null @@ -1,106 +0,0 @@ -/** - * @file ParticleEmitter.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief A particle emitter. Can be fed a particle to emit - * and configured. - * @version 0.1 - * @date 2021-03-06 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_PARTICLEEMITTER_H_ -#define INCLUDE_ENTITIES_PARTICLEEMITTER_H_ - -#include -#include - -#include "GameObject.h" -#include "Particle.h" - -namespace afk { - -/** - * @brief Particle Emitter - * - */ -class ParticleEmitter : public GameObject { - public: - /** - * @brief Construct a new ParticleEmitter object - * - * @param scene Reference to scene which is stored in game object - * @param x X position - * @param y Y position - * @param z Z position (for sorting) - * @param frequency Frequency in ms to emit, 0 is burst - */ - explicit ParticleEmitter(Scene& scene, - const float x = 0.0f, - const float y = 0.0f, - const int z = 0, - const int frequency = 0); - - /** - * @brief Destroy the ParticleEmitter object - * - */ - virtual ~ParticleEmitter() {} - - /** - * @brief Hook into draw loop - * - */ - void draw() override; - - /** - * @brief Hook into update loop - * - * @param delta Time since last call in ms - * - */ - void update(Uint32 delta) override; - - /** - * @brief Add particles to system - * - * @param particle Particle to add - * @param count Number of particles to push back, defaults to 1 - */ - void addParticle(std::unique_ptr particle); - - /** - * @brief Disable more particles from being emitted - * - */ - void enable(); - - /** - * @brief Enable particle emitting - * - */ - void disable(); - - protected: - /// Particles - std::vector> particles; - - /// Emitting state - bool emitting; - - /// Frequency to emit in ms - int frequency; - - /// Current tick - int current_tick; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_PARTICLEEMITTER_H_ - -/** - * @example ex_particles.cpp - * This is an example of how to use the ParticleEmitter class to create particle - * effects. - */ diff --git a/include/entities/Sprite.h b/include/entities/Sprite.h deleted file mode 100644 index 282b510..0000000 --- a/include/entities/Sprite.h +++ /dev/null @@ -1,91 +0,0 @@ -/** - * @file Sprite.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Simple textured GameObject - * @version 0.1 - * @date 2020-10-20 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_SPRITE_H_ -#define INCLUDE_ENTITIES_SPRITE_H_ - -#include - -#include "../assets/Texture.h" -#include "GameObject.h" - -namespace afk { - -/** - * @brief A simple texturable game object - * - */ -class Sprite : public GameObject { - public: - /** - * @brief Construct a new Sprite object - * - * @param scene Reference to scene which is stored in game object - * @param x X position - * @param y Y position - * @param z Z position (for sorting) - */ - explicit Sprite(Scene& scene, - const float x = 0.0f, - const float y = 0.0f, - const int z = 0); - - /** - * @brief Construct a new Sprite object - * - * @param scene Reference to scene which is stored in game object - * @param texture Id of texture to assign to sprite - * @param x X position - * @param y Y position - * @param z Z position (for sorting) - */ - Sprite(Scene& scene, - const std::string& texture, - const float x = 0.0f, - const float y = 0.0f, - const int z = 0); - - /** - * @brief Destroy the Sprite object - * - */ - virtual ~Sprite(); - - /** - * @brief Hook into draw loop - * - */ - void draw() override; - - /** - * @brief Set the Texture of the sprite - * - * @param texture Id of texture to assign - */ - void setTexture(const std::string& texture); - - protected: - /// Texture of Sprite - Texture texture; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_SPRITE_H_ - -/** - * @example ex_sprite.cpp - * This example shows basic usage of a sprite - */ - -/** - * @example ex_fps.cpp - * This example shows a stress test of sprites - */ diff --git a/include/scene/Scene.h b/include/scene/Scene.h index de45ed3..65ee94c 100644 --- a/include/scene/Scene.h +++ b/include/scene/Scene.h @@ -11,6 +11,7 @@ #ifndef INCLUDE_SCENE_SCENE_H_ #define INCLUDE_SCENE_SCENE_H_ +#include #include #include #include @@ -18,7 +19,6 @@ #include #include "../common/Exceptions.h" -#include "../entities/GameObject.h" #include "../services/Services.h" /** @@ -27,9 +27,6 @@ */ namespace afk { -using ComponentArray = std::vector>; -using ComponentMap = std::unordered_map; - class Scene { public: /** @@ -77,154 +74,50 @@ class Scene { void stopInternal(); /** - * @brief Add GameObject to update and draw pool, returns by reference - * - * @tparam T Type of GameObject - * @tparam Args Arguments to forward to T - * @param args Argument values which will be forwarded to T when constructing - * a new GameObject - * @return Reference to created GameObject - */ - template - T& add(Args&&... args) { - // Create the GameObject - GameObject* obj = new T(std::forward(args)...); - - // Add to lookup - entity_map[obj->id] = entities.size(); - - // Push - entities.emplace_back(obj); - - // Force sort on next update - need_sort = true; - - // Return the object! - return get(obj->id); - } - - /** - * @brief Gets a GameObject by id and casts to type T - * - * @tparam T Type of GameObject - * @param id ObjId of GameObject to look up - * @return Reference to GameObject if found - * @throws KeyLookupException if GameObject could not be found - */ - template - T& get(const ObjId id) { - GameObject& obj = get(id); - try { - return dynamic_cast(obj); - } catch (...) { - throw KeyLookupException("Could not cast entity " + std::to_string(id) + - " to type"); - } - } - - /** - * @brief Gets a GameObject by id without the cast - * - * @param id ObjId of GameObject to look up - * @return Reference to GameObject if found - * @throws KeyLookupException if GameObject could not be found - */ - GameObject& get(const ObjId id) { - if (!has(id)) { - throw KeyLookupException("Could not find entity by id " + - std::to_string(id)); - } - - unsigned int index = entity_map[id]; - return *entities.at(index); - } - - /** - * @brief Removes a GameObject from the scene pool - * - * @param id ObjId of GameObject to remove - */ - void remove(const ObjId id); - - /** - * @brief Check if GameObject id exists in scene + * @brief Register a new entity * - * @param id ObjId to check - * @return true If the GameObject exists - * @return false If the GameObject does not exist + * @return entt::entity */ - bool has(const ObjId id); + entt::entity createEntity() { return registry.create(); } /** - * @brief Add a component to the scene, linked to a GameObject by obj_id + * @brief Remove an entity * - * @tparam T Subclass of component - * @param obj_id ObjId of GameObject to attach to - * @return T& Reference to the component + * @param entity Entity to remove */ - template - T& addComponent(const ObjId obj_id) { - // Get type code - std::size_t id = typeid(T).hash_code(); - - // Add to component map - component_map[id][obj_id] = components[id].size(); - - // Add component to vector - components[id].emplace_back(new T(obj_id)); - - // Get the component - return getComponent(obj_id); - } + void destroyEntity(entt::entity entity) { registry.destroy(entity); } /** - * @brief Get the Component object + * @brief Add a component to an entity * - * @tparam T Subclass of component - * @param obj_id ObjId of GameObject to search for component - * @return T& Reference to the component + * @tparam T Type of component + * @tparam Args Type of arguments to provide to component constructor + * @param id Entity to assign to + * @param args Arguments accepted by component */ - template - T& getComponent(const ObjId obj_id) { - // Get type code - const std::size_t id = typeid(T).hash_code(); - - // Find index in component map - unsigned int index = component_map[id][obj_id]; - - // Cast and return - return dynamic_cast(*components[id].at(index)); + template + T& createComponent(entt::entity id, Args&&... args) { + return registry.emplace(id, std::forward(args)...); } /** - * @brief Remove a component from an object + * @brief Get a component for a given entity * * @tparam T Type of component - * @param obj_id ObjId of GameObject to remove component from + * @param id Id of entity + * @return T& Returned component reference */ template - void removeComponent(const ObjId obj_id) { - // Get type code - const std::size_t id = typeid(T).hash_code(); - - // Remove by id - removeComponentById(obj_id, id); + T& getComponent(entt::entity id) { + return registry.get(id); } /** - * @brief Check if a GameObject has a component attached + * @brief Get a reference to the registry * - * @tparam T Type of component - * @param obj_id ObjId of GameObject to check + * @return entt::registry& Registry reference */ - template - bool hasComponent(const ObjId obj_id) const { - // Get type code - std::size_t id = typeid(T).hash_code(); - - // Check count of id for type - return component_map.at(id).count(obj_id) != 0; - } + entt::registry& getRegistry() { return registry; } /// Audio service reference AudioService& audio; @@ -248,26 +141,11 @@ class Scene { ConfigService& config; private: - /// Remove component by type id - void removeComponentById(const ObjId obj_id, const std::size_t id); - - /// Holds GameObjects - std::vector> entities; - - /// Quick GameObjects lookup - std::unordered_map entity_map; - - /// Hold GameObject Components - std::unordered_map components; - - /// Quick lookup of GameObject Components - std::unordered_map component_map; - - /// Store objects to be removed - std::vector remove_pool; - /// Needs sorting bool need_sort; + + /// Entity registry + entt::registry registry; }; } // namespace afk diff --git a/include/systems/ParticleSystem.h b/include/systems/ParticleSystem.h new file mode 100644 index 0000000..c794677 --- /dev/null +++ b/include/systems/ParticleSystem.h @@ -0,0 +1,124 @@ +/** + * @file ParticleSystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of updating and rendering particles + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef INCLUDE_SYSTEMS_PARTICLE_SYSTEM_H_ +#define INCLUDE_SYSTEMS_PARTICLE_SYSTEM_H_ + +#include +#include +#include + +#include "common/math.h" +#include "components/Particle.h" +#include "components/ParticleEmitter.h" +#include "components/Transform.h" +#include "primitives/Primitives.h" +#include "random/RandomGenerator.h" +#include "services/assets/AssetService.h" + +/** + * @brief ParticleSystem + * + */ +namespace afk::systems { + +void particleSystem(entt::registry& registry, float delta) { + auto particle_view = registry.view(); + + int count = 0; + for (auto [entity, tran, particle] : particle_view.each()) { + tran.size.x = math::lerp(particle.start_size, particle.end_size, + particle.age / particle.lifespan); + tran.size.y = tran.size.x; + + particle.age += delta; + if (particle.age > particle.lifespan) { + registry.destroy(entity); + } + + count++; + } + + auto system_view = registry.view(); + + for (auto [entity, tran, emitter] : system_view.each()) { + emitter.counter += delta; + + while (emitter.counter > emitter.frequency && + emitter.templates.size() > 0) { + int index = Random::randomInt(0, emitter.templates.size() - 1); + auto& [particle, physics] = emitter.templates.at(index); + + emitter.counter -= emitter.frequency; + + const float start_x = + tran.position.x + Random::randomFloat(0, tran.size.x); + const float start_y = + tran.position.y + Random::randomFloat(0, tran.size.y); + + const auto& particle_id = registry.create(); + registry.emplace(particle_id, particle); + registry.emplace(particle_id, physics); + registry.emplace( + particle_id, Vec3(start_x, start_y, tran.position.z), + Vec2(particle.start_size, particle.start_size)); + } + } +} + +void particleRenderSystem(entt::registry& registry, + AssetService& assetService) { + auto view = registry.view(); + + for (auto [entity, tran, particle] : view.each()) { + float life_percent = particle.age / particle.lifespan; + + // Lerp size + float size = + math::lerp(particle.start_size, particle.end_size, life_percent); + + // Lerp color + Uint8 r = + math::lerp(particle.start_color.r, particle.end_color.r, life_percent); + Uint8 g = + math::lerp(particle.start_color.g, particle.end_color.g, life_percent); + Uint8 b = + math::lerp(particle.start_color.b, particle.end_color.b, life_percent); + Uint8 a = + math::lerp(particle.start_color.a, particle.end_color.a, life_percent); + color::Color color = {r, g, b, a}; + + // Switch over type + switch (particle.type) { + case ParticleType::SQUARE: + primitives::rectfill(tran.position.x, tran.position.y, size, size, + color); + break; + case ParticleType::CIRCLE: + primitives::circle(tran.position.x, tran.position.y, size, color); + break; + case ParticleType::PIXEL: + primitives::pixel(tran.position.x, tran.position.y, color); + break; + case ParticleType::IMAGE: { + auto texture = assetService.getImage(particle.texture); + texture.drawEx(tran.position.x, tran.position.y, tran.size.x, + tran.size.y, tran.angle); + break; + } + default: + break; + } + } +} + +} // namespace afk::systems + +#endif // INCLUDE_SYSTEMS_PARTICLE_SYSTEM_H_ \ No newline at end of file diff --git a/include/systems/PhysicsSystem.h b/include/systems/PhysicsSystem.h new file mode 100644 index 0000000..bfdd0b5 --- /dev/null +++ b/include/systems/PhysicsSystem.h @@ -0,0 +1,41 @@ +/** + * @file PhysicsSystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of updating transforms + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef INCLUDE_SYSTEMS_PHYSICS_SYSTEM_H_ +#define INCLUDE_SYSTEMS_PHYSICS_SYSTEM_H_ + +#include + +#include "components/Physics.h" +#include "components/Transform.h" +#include "services/assets/AssetService.h" + +/** + * @brief PhysicsSystem + * + */ +namespace afk::systems { + +void physicsSystem(entt::registry& registry, Uint32 delta) { + auto view = registry.view(); + + const float delta_seconds = delta / 1000.0f; + + for (auto [entity, tran, physics] : view.each()) { + tran.position.x += physics.velocity.x * delta_seconds; + tran.position.y += physics.velocity.y * delta_seconds; + physics.velocity.x += physics.acceleration.x * delta_seconds; + physics.velocity.y += physics.acceleration.y * delta_seconds; + } +} + +} // namespace afk::systems + +#endif // INCLUDE_SYSTEMS_PHYSICS_SYSTEM_H_ \ No newline at end of file diff --git a/include/systems/RenderSystem.h b/include/systems/RenderSystem.h new file mode 100644 index 0000000..21b83c3 --- /dev/null +++ b/include/systems/RenderSystem.h @@ -0,0 +1,38 @@ +/** + * @file RenderSystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of rendering components + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef INCLUDE_SYSTEMS_RENDER_SYSTEM_H_ +#define INCLUDE_SYSTEMS_RENDER_SYSTEM_H_ + +#include + +#include "components/Sprite.h" +#include "components/Transform.h" +#include "services/assets/AssetService.h" + +/** + * @brief RenderSystem + * + */ +namespace afk::systems { + +void renderSystem(entt::registry& registry, AssetService& assetService) { + auto view = registry.view(); + + for (auto [entity, tran, sprite] : view.each()) { + auto texture = assetService.getImage(sprite.texture); + texture.drawEx(tran.position.x, tran.position.y, tran.size.x, tran.size.y, + tran.angle); + } +} + +} // namespace afk::systems + +#endif // INCLUDE_SYSTEMS_RENDER_SYSTEM_H_ \ No newline at end of file diff --git a/include/systems/UISystem.h b/include/systems/UISystem.h new file mode 100644 index 0000000..887d64d --- /dev/null +++ b/include/systems/UISystem.h @@ -0,0 +1,37 @@ +/** + * @file UISystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of rendering components + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef INCLUDE_SYSTEMS_UI_SYSTEM_H_ +#define INCLUDE_SYSTEMS_UI_SYSTEM_H_ + +#include + +#include "components/Transform.h" +#include "components/ui/Label.h" +#include "services/assets/AssetService.h" + +/** + * @brief UISystem + * + */ +namespace afk::systems { + +void uiSystem(entt::registry& registry, AssetService& assetService) { + auto view = registry.view(); + + for (auto [entity, tran, label] : view.each()) { + auto font = assetService.getFont(label.font); + font.draw(tran.position.x, tran.position.y, label.text); + } +} + +} // namespace afk::systems + +#endif // INCLUDE_SYSTEMS_UI_SYSTEM_H_ \ No newline at end of file diff --git a/src/Game.cpp b/src/Game.cpp index ae95c3a..a212ba4 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -100,6 +100,8 @@ void Game::start() { showErrorDialog("File Error", e.what()); } catch (const std::runtime_error& e) { showErrorDialog("Runtime Error", e.what()); + } catch (const std::exception& e) { + showErrorDialog("Exception", e.what()); } catch (...) { showErrorDialog("Unknown Error", "An unknown error has occured :("); } diff --git a/src/assets/Texture.cpp b/src/assets/Texture.cpp index 7fc4061..94721ff 100644 --- a/src/assets/Texture.cpp +++ b/src/assets/Texture.cpp @@ -22,7 +22,7 @@ namespace afk { Texture::Texture() : texture(nullptr) {} // Constructor with path -Texture::Texture(const std::string& path) { +Texture::Texture(const std::string& path) : texture(nullptr) { load(path); } @@ -105,12 +105,12 @@ void Texture::drawEx(const int x, SDL_Rect target = {x, y, width, height}; SDL_Point center = {width / 2, height / 2}; - SDL_RendererFlip flip = static_cast(mode); + auto flip = static_cast(mode); SDL_RenderCopyEx(renderer, texture, nullptr, &target, angle, ¢er, flip); } -// Load SDL texture from file +// Load an SDL texture from file SDL_Texture* Texture::loadTexture(const std::string& path) { // Attempt to load SDL_Surface* temp_surface = IMG_Load(path.c_str()); diff --git a/src/color/Color.cpp b/src/color/Color.cpp index b51a995..956c63a 100644 --- a/src/color/Color.cpp +++ b/src/color/Color.cpp @@ -10,8 +10,7 @@ */ #include "color/Color.h" -namespace afk { -namespace color { +namespace afk::color { // Create color from RGB Color rgb(const Uint8 r, const Uint8 g, const Uint8 b) { @@ -25,12 +24,12 @@ Color rgba(const Uint8 r, const Uint8 g, const Uint8 b, const Uint8 a) { // Create color from int Color intToColor(const Uint32 colour) { - Color tempcol; - tempcol.r = (colour >> 16) & 0xFF; - tempcol.g = (colour >> 8) & 0xFF; - tempcol.b = colour & 0xFF; - tempcol.a = 255; - return tempcol; + Color tempCol; + tempCol.r = (colour >> 16) & 0xFF; + tempCol.g = (colour >> 8) & 0xFF; + tempCol.b = colour & 0xFF; + tempCol.a = 255; + return tempCol; } // Convert rgb to int @@ -48,5 +47,4 @@ Uint32 colorToInt(const Color colour) { return rgbaToInt(colour.r, colour.g, colour.b, colour.a); } -} // namespace color -} // namespace afk +} // namespace afk::color diff --git a/src/common/math.cpp b/src/common/math.cpp index 052f2e8..a60839f 100644 --- a/src/common/math.cpp +++ b/src/common/math.cpp @@ -11,8 +11,7 @@ #include "common/math.h" -namespace afk { -namespace math { +namespace afk::math { // Lerp between two values float lerp(float start, float end, float progress) { @@ -30,5 +29,4 @@ float clamp(float value, float min, float max) { return value; } -} // namespace math -} // namespace afk +} // namespace afk::math diff --git a/src/common/str.cpp b/src/common/str.cpp index 625126c..531cab9 100644 --- a/src/common/str.cpp +++ b/src/common/str.cpp @@ -12,8 +12,7 @@ #include -namespace afk { -namespace str { +namespace afk::str { // Checks bool isInteger(const std::string& str) { @@ -55,5 +54,4 @@ float toFloat(const std::string& str) { return std::stof(str); } -} // namespace str -} // namespace afk +} // namespace afk::str diff --git a/src/components/Collider.cpp b/src/components/Collider.cpp deleted file mode 100644 index b376f9c..0000000 --- a/src/components/Collider.cpp +++ /dev/null @@ -1,20 +0,0 @@ -/** - * @file Sprite.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of Collider component - * @version 0.1 - * @date 2021-03-15 - * - * @copyright Copyright (c) 2021 - * - */ -#include "components/Collider.h" - -#include "services/Services.h" - -namespace afk { - -// Construct component -Collider::Collider(ObjId obj_id) : Component(obj_id) {} - -} // namespace afk diff --git a/src/components/Component.cpp b/src/components/Component.cpp deleted file mode 100644 index c5c00ff..0000000 --- a/src/components/Component.cpp +++ /dev/null @@ -1,18 +0,0 @@ -/** - * @file Component.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of base component - * @version 0.1 - * @date 2021-03-15 - * - * @copyright Copyright (c) 2021 - * - */ -#include "components/Component.h" - -namespace afk { - -// Constructor -Component::Component(ObjId obj_id) : obj_id(obj_id) {} - -} // namespace afk diff --git a/src/components/Sprite.cpp b/src/components/Sprite.cpp deleted file mode 100644 index 9b2d344..0000000 --- a/src/components/Sprite.cpp +++ /dev/null @@ -1,20 +0,0 @@ -/** - * @file Sprite.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of sprite component - * @version 0.1 - * @date 2021-03-15 - * - * @copyright Copyright (c) 2021 - * - */ -#include "components/Sprite.h" - -#include "services/Services.h" - -namespace afk { - -// Construct component -Sprite::Sprite(ObjId obj_id) : Component(obj_id), texture() {} - -} // namespace afk diff --git a/src/components/Transform.cpp b/src/components/Transform.cpp deleted file mode 100644 index f8a66a0..0000000 --- a/src/components/Transform.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/** - * @file Transform.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of transform component - * @version 0.1 - * @date 2021-03-15 - * - * @copyright Copyright (c) 2021 - * - */ -#include "components/Transform.h" - -namespace afk { - -Transform::Transform(ObjId obj_id) - : Component(obj_id), - x(0), - y(0), - z(0), - height(0), - width(0), - angle(0), - last_x(0), - last_y(0) {} - -} // namespace afk diff --git a/src/entities/GameObject.cpp b/src/entities/GameObject.cpp index 2c19f20..57179cb 100644 --- a/src/entities/GameObject.cpp +++ b/src/entities/GameObject.cpp @@ -12,8 +12,6 @@ #include -#include "scene/Scene.h" - namespace afk { // Set incrementing index count @@ -21,8 +19,7 @@ ObjId GameObject::index = 1; // Constructor GameObject::GameObject(Scene& scene, const float x, const float y, const int z) - : transform(scene.addComponent(GameObject::index)), - id(GameObject::index), + : id(GameObject::index), scene(scene), visible(true), enabled(true), @@ -31,9 +28,9 @@ GameObject::GameObject(Scene& scene, const float x, const float y, const int z) GameObject::index += 1; // Set transform - transform.x = x; - transform.y = y; - transform.z = z; + transform.position.x = x; + transform.position.y = y; + transform.position.z = z; } // Destructor, remove components @@ -47,21 +44,22 @@ void GameObject::update(Uint32 delta) { // Update void GameObject::updateInternal() { // Parent functions - if (parent_id != 0) { - // Autoremove if parent is dead - try { - auto& parent = scene.get(parent_id); - - // Set hooked state - hooked = parent.getHooked(); - - // Set position - transform.x += parent.transform.x - parent.transform.last_x; - transform.y += parent.transform.y - parent.transform.last_y; - } catch (const KeyLookupException&) { - scene.remove(id); - } - } + // if (parent_id != 0) { + // // Autoremove if parent is dead + // try { + // auto& parent = scene.getComponent(parent_id); + + // // Set hooked state + // hooked = parent.getHooked(); + + // // Set position + // transform.position.x += parent.transform.position.x - + // parent.transform.last_x; transform.position.y += + // parent.transform.position.y - parent.transform.last_y; + // } catch (const KeyLookupException&) { + // // scene.remove(id); + // } + // } } // Draw diff --git a/src/entities/Particle.cpp b/src/entities/Particle.cpp deleted file mode 100644 index b8e749e..0000000 --- a/src/entities/Particle.cpp +++ /dev/null @@ -1,139 +0,0 @@ -/** - * @file Particle.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of Particle - * @version 0.1 - * @date 2021-03-08 - * - * @copyright Copyright (c) 2021 - * - */ -#include "entities/Particle.h" -#include "common/math.h" -#include "scene/Scene.h" - -namespace afk { - -// Constructor -Particle::Particle(Scene& scene, - const float x, - const float y, - const float z, - const ParticleType type) - : Sprite(scene, x, y, z), - type(type), - start_size(1), - end_size(1), - velocity_x(0), - velocity_y(0), - acceleration_x(0), - acceleration_y(0), - age(0), - lifespan(1000), - start_color(color::black), - end_color(color::black) {} - -// Logic -void Particle::update(Uint32 delta) { - if (dead()) { - return; - } - - // Update velocity - transform.x += (velocity_x + acceleration_x * age) / 1000 * delta; - transform.y += (velocity_y + acceleration_y * age) / 1000 * delta; - - // Its dead - this->age += 4.0f; -} - -// Draw -void Particle::draw() { - if (dead()) { - return; - } - - float life_percent = age / lifespan; - - // Lerp size - float size = math::lerp(start_size, end_size, life_percent); - - // Lerp color - Uint8 r = math::lerp(start_color.r, end_color.r, life_percent); - Uint8 g = math::lerp(start_color.g, end_color.g, life_percent); - Uint8 b = math::lerp(start_color.b, end_color.b, life_percent); - Uint8 a = math::lerp(start_color.a, end_color.a, life_percent); - color::Color color = {r, g, b, a}; - - // Switch over type - switch (type) { - case ParticleType::SQUARE: - primitives::rectfill(transform.x, transform.y, size, size, color); - break; - case ParticleType::CIRCLE: - primitives::circle(transform.x, transform.y, size, color); - break; - case ParticleType::PIXEL: - primitives::pixel(transform.x, transform.y, color); - break; - case ParticleType::IMAGE: - texture.drawEx(transform.x, transform.y, size, size, 0); - default: - break; - } -} - -// Set the size of the particle in pixels -void Particle::setSize(const float size) { - this->start_size = size; - this->end_size = size; -} - -// Set the size of particle over lifespan -void Particle::setSize(const float start_size, const float end_size) { - this->start_size = start_size; - this->end_size = end_size; -} - -// Set the velocity of particle -void Particle::setVelocity(const float x, const float y) { - this->velocity_x = x; - this->velocity_y = y; -} - -// Set the accleration of particle -void Particle::setAcceleration(const float x, const float y) { - this->acceleration_x = x; - this->acceleration_y = y; -} - -// Set the lifespan of particle in ms, start dead -void Particle::setLifespan(const float lifespan) { - this->lifespan = lifespan; - this->age = lifespan; -} - -// Set the particle color -void Particle::setColor(const color::Color& color) { - this->start_color = color; - this->end_color = color; -} - -// Set the particle color over lifespan -void Particle::setColor(const color::Color& start_color, - const color::Color& end_color) { - this->start_color = start_color; - this->end_color = end_color; -} - -// Reest age -void Particle::reset() { - this->age = 0; -} - -// Check if dead -bool Particle::dead() { - return this->age >= this->lifespan; -} - -} // namespace afk diff --git a/src/entities/ParticleEmitter.cpp b/src/entities/ParticleEmitter.cpp deleted file mode 100644 index 1ab6367..0000000 --- a/src/entities/ParticleEmitter.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @file ParticleEmitter.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of a particle emitter. - * and configured. - * @version 0.1 - * @date 2021-03-06 - * - * @copyright Copyright (c) 2021 - * - */ -#include "entities/ParticleEmitter.h" - -#include "color/Color.h" -#include "primitives/Primitives.h" -#include "random/RandomGenerator.h" -#include "scene/Scene.h" -#include "services/Services.h" - -namespace afk { - -// Constructor -ParticleEmitter::ParticleEmitter(Scene& scene, - const float x, - const float y, - const int z, - const int frequency) - : GameObject(scene, x, y, z), - emitting(true), - frequency(frequency), - current_tick(0) {} - -// Draw -void ParticleEmitter::draw() { - for (auto& particle : particles) { - particle->draw(); - } -} - -// Update -void ParticleEmitter::update(Uint32 delta) { - if (emitting) { - current_tick += delta; - } - - for (auto& particle : particles) { - particle->update(delta); - - if (particle->dead() && emitting && current_tick >= frequency) { - current_tick -= frequency; - particle.reset(); - transform.x = - Random::randomInt(transform.x, transform.x + transform.width); - transform.y = - Random::randomInt(transform.y, transform.y + transform.width); - } - } -} - -// Add -void ParticleEmitter::addParticle(std::unique_ptr particle) { - particles.push_back(std::move(particle)); -} - -// Enable -void ParticleEmitter::enable() { - this->emitting = true; -} - -// Disable -void ParticleEmitter::disable() { - this->emitting = false; -} - -} // namespace afk diff --git a/src/entities/Sprite.cpp b/src/entities/Sprite.cpp deleted file mode 100644 index d3a4163..0000000 --- a/src/entities/Sprite.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/** - * @file Sprite.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of Sprite - * @version 0.1 - * @date 2020-10-20 - * - * @copyright Copyright (c) 2021 - * - */ -#include "entities/Sprite.h" - -#include "color/Color.h" -#include "primitives/Primitives.h" -#include "scene/Scene.h" - -namespace afk { - -// Constructor -Sprite::Sprite(Scene& scene, const float x, const float y, const int z) - : GameObject(scene, x, y, z) {} - -// Constructor -Sprite::Sprite(Scene& scene, - const std::string& texture, - const float x, - const float y, - const int z) - : Sprite(scene, x, y, z) { - setTexture(texture); -} - -// Destructor -Sprite::~Sprite() {} - -void Sprite::setTexture(const std::string& texture) { - this->texture = scene.assets.getImage(texture); - transform.width = this->texture.getWidth(); - transform.height = this->texture.getHeight(); -} - -// Draw -void Sprite::draw() { - // Draw image - texture.drawEx(transform.x, transform.y, transform.width, transform.height, - transform.angle); - - // Draw bounding box - if (Services::getConfigService().get("debug", false)) { - primitives::rect(transform.x, transform.y, transform.width, - transform.height, color::red); - } -} - -} // namespace afk diff --git a/src/entities/ui/Button.cpp b/src/entities/ui/Button.cpp index 7cb3dcd..6480b2c 100644 --- a/src/entities/ui/Button.cpp +++ b/src/entities/ui/Button.cpp @@ -26,23 +26,24 @@ const int DEFAULT_PADDING = 5; // Ctor Button::Button(Scene& scene, const float x, const float y, const int z) : UIElement(scene, x, y, z) { - transform.width = DEFAULT_WIDTH; - transform.height = DEFAULT_HEIGHT; + transform.size.x = DEFAULT_WIDTH; + transform.size.y = DEFAULT_HEIGHT; } // Draw button void Button::draw() { // Draw button background - primitives::rectfill(transform.x, transform.y, transform.width, - transform.height, color::white); + primitives::rectfill(transform.position.x, transform.position.y, + transform.size.x, transform.size.y, color::white); // Draw button border - primitives::rect(transform.x, transform.y, transform.width, transform.height, - color::black); + primitives::rect(transform.position.x, transform.position.y, transform.size.x, + transform.size.y, color::black); // Text - font.draw(transform.x + DEFAULT_PADDING, transform.y + DEFAULT_PADDING, text, - color::black, text_align); + font.draw(transform.position.x + DEFAULT_PADDING, + transform.position.y + DEFAULT_PADDING, text, color::black, + text_align); } // Override text setter @@ -50,8 +51,8 @@ void Button::sizeToText() { if (!font.exists()) { return; } - transform.height = font.getHeight() + DEFAULT_PADDING * 2; - transform.width = font.getWidth(text) + DEFAULT_PADDING * 2; + transform.size.y = font.getHeight() + DEFAULT_PADDING * 2; + transform.size.x = font.getWidth(text) + DEFAULT_PADDING * 2; } } // namespace afk diff --git a/src/entities/ui/Checkbox.cpp b/src/entities/ui/Checkbox.cpp index f63fef6..bf8937e 100644 --- a/src/entities/ui/Checkbox.cpp +++ b/src/entities/ui/Checkbox.cpp @@ -25,30 +25,30 @@ namespace afk { // Ctor Checkbox::Checkbox(Scene& scene, const float x, const float y, const int z) : UIElement(scene, x, y, z), checked(false), onCheck(nullptr) { - transform.height = DEFAULT_HEIGHT; - transform.width = DEFAULT_WIDTH; + transform.size.y = DEFAULT_HEIGHT; + transform.size.x = DEFAULT_WIDTH; } // Draw checkbox void Checkbox::draw() { // Draw checkbox background - primitives::rectfill(transform.x, transform.y, transform.width, - transform.height, color::white); + primitives::rectfill(transform.position.x, transform.position.y, + transform.size.x, transform.size.y, color::white); // Draw checkbox border - primitives::rect(transform.x, transform.y, transform.width, transform.height, - color::black); + primitives::rect(transform.position.x, transform.position.y, transform.size.x, + transform.size.y, color::black); if (checked) { - primitives::rectfill(transform.x + transform.width / 4, - transform.y + transform.height / 4, - transform.width - transform.width / 2, - transform.height - transform.height / 2, color::black); + primitives::rectfill(transform.position.x + transform.size.x / 4, + transform.position.y + transform.size.y / 4, + transform.size.x - transform.size.x / 2, + transform.size.y - transform.size.y / 2, color::black); } // Draw text label - font.draw(transform.x + transform.width + 10, - transform.y + transform.height - font.getHeight(), text, + font.draw(transform.position.x + transform.size.x + 10, + transform.position.y + transform.size.y - font.getHeight(), text, color::black); } diff --git a/src/entities/ui/Image.cpp b/src/entities/ui/Image.cpp index 5c9c9d5..ef69ae4 100644 --- a/src/entities/ui/Image.cpp +++ b/src/entities/ui/Image.cpp @@ -20,15 +20,15 @@ Image::Image(Scene& scene, const float x, const float y, const int z) // Draw image void Image::draw() { - texture.drawEx(transform.x, transform.y, transform.width, transform.height, - transform.angle); + texture.drawEx(transform.position.x, transform.position.y, transform.size.x, + transform.size.y, transform.angle); } void Image::setTexture(const std::string& texture) { this->texture = scene.assets.getImage(texture); - transform.width = this->texture.getWidth(); - transform.height = this->texture.getHeight(); + transform.size.x = this->texture.getWidth(); + transform.size.y = this->texture.getHeight(); } } // namespace afk diff --git a/src/entities/ui/Inputbox.cpp b/src/entities/ui/Inputbox.cpp index ca6bbd4..dccacf3 100644 --- a/src/entities/ui/Inputbox.cpp +++ b/src/entities/ui/Inputbox.cpp @@ -31,38 +31,39 @@ const int DEFAULT_PADDING = 5; // Ctor Inputbox::Inputbox(Scene& scene, const float x, const float y, const int z) : UIElement(scene, x, y, z), iter(text.end()), onChange(nullptr) { - transform.height = DEFAULT_HEIGHT; - transform.width = DEFAULT_WIDTH; + transform.size.y = DEFAULT_HEIGHT; + transform.size.x = DEFAULT_WIDTH; } // Draw checkbox void Inputbox::draw() { // Draw checkbox background - primitives::rectfill(transform.x, transform.y, transform.width, - transform.height, color::white); + primitives::rectfill(transform.position.x, transform.position.y, + transform.size.x, transform.size.y, color::white); // Draw checkbox border - primitives::rect(transform.x, transform.y, transform.width, transform.height, - color::black); + primitives::rect(transform.position.x, transform.position.y, transform.size.x, + transform.size.y, color::black); // Focus border if (id == UIElement::focused) { - primitives::rect(transform.x + 1, transform.y + 1, transform.width - 2, - transform.height - 2, color::black); + primitives::rect(transform.position.x + 1, transform.position.y + 1, + transform.size.x - 2, transform.size.y - 2, color::black); } // Draw text label - font.draw(transform.x + DEFAULT_PADDING, - transform.y + transform.height - font.getHeight(), text, + font.draw(transform.position.x + DEFAULT_PADDING, + transform.position.y + transform.size.y - font.getHeight(), text, color::black); // Draw the caret std::string edit_pos = text.substr(0, std::distance(text.begin(), iter)); int line_x = font.getWidth(edit_pos); - afk::primitives::line(line_x + transform.x + DEFAULT_PADDING, transform.y + 2, - line_x + transform.x + DEFAULT_PADDING, - transform.y + transform.height - 2, afk::color::black); + afk::primitives::line( + line_x + transform.position.x + DEFAULT_PADDING, transform.position.y + 2, + line_x + transform.position.x + DEFAULT_PADDING, + transform.position.y + transform.size.y - 2, afk::color::black); } // Update loop diff --git a/src/entities/ui/Label.cpp b/src/entities/ui/Label.cpp index 351d6c4..e20ae35 100644 --- a/src/entities/ui/Label.cpp +++ b/src/entities/ui/Label.cpp @@ -23,7 +23,8 @@ Label::Label(Scene& scene, const float x, const float y, const int z) // Draw label void Label::draw() { // Text - font.draw(transform.x, transform.y, text, color::black, text_align); + font.draw(transform.position.x, transform.position.y, text, color::black, + text_align); } } // namespace afk diff --git a/src/entities/ui/UIElement.cpp b/src/entities/ui/UIElement.cpp index 5463e1b..6656cd0 100644 --- a/src/entities/ui/UIElement.cpp +++ b/src/entities/ui/UIElement.cpp @@ -51,10 +51,11 @@ void UIElement::update(Uint32 delta) { InputService& input = Services::getInputService(); if (input.mousePressed(MouseButtons::LEFT)) { - bool is_colliding = input.mouseX() < transform.x + transform.width && - input.mouseY() < transform.y + transform.height && - input.mouseX() > transform.x && - input.mouseY() > transform.y; + bool is_colliding = + input.mouseX() < transform.position.x + transform.size.x && + input.mouseY() < transform.position.y + transform.size.y && + input.mouseX() > transform.position.x && + input.mouseY() > transform.position.y; if (is_colliding) { UIElement::focused = id; diff --git a/src/primitives/Primitives.cpp b/src/primitives/Primitives.cpp index d677a79..145dd25 100644 --- a/src/primitives/Primitives.cpp +++ b/src/primitives/Primitives.cpp @@ -13,8 +13,7 @@ #include "primitives/Primitives.h" #include "services/Services.h" -namespace afk { -namespace primitives { +namespace afk::primitives { // Draw a rectangle void rect(const Sint32 x, @@ -67,5 +66,4 @@ void line(const Sint16 x1, lineRGBA(renderer, x1, y1, x2, y2, colour.r, colour.g, colour.b, colour.a); } -} // namespace primitives -} // namespace afk +} // namespace afk::primitives diff --git a/src/scene/Scene.cpp b/src/scene/Scene.cpp index e597639..b1f35b7 100644 --- a/src/scene/Scene.cpp +++ b/src/scene/Scene.cpp @@ -10,13 +10,10 @@ */ #include "scene/Scene.h" -#include - -#include "common/Exceptions.h" -#include "components/Collider.h" -#include "components/Sprite.h" -#include "components/Transform.h" -#include "entities/GameObject.h" +#include "systems/ParticleSystem.h" +#include "systems/PhysicsSystem.h" +#include "systems/RenderSystem.h" +#include "systems/UISystem.h" namespace afk { @@ -33,139 +30,21 @@ Scene::Scene() // Internal cleanup (on switch scene) void Scene::stopInternal() { - entities.clear(); - entity_map.clear(); + // entities.clear(); } // Draw internal method void Scene::draw() { // Draw - for (auto& obj : entities) { - if (obj->getVisible() && obj->getHooked()) { - obj->draw(); - - // Render system - if (hasComponent(obj->id)) { - Sprite& sprite = getComponent(obj->id); - Transform& transform = getComponent(obj->id); - - // Draw image - sprite.texture.drawEx(transform.x, transform.y, transform.width, - transform.height, transform.angle); - } - } - } + systems::renderSystem(registry, assets); + systems::uiSystem(registry, assets); + systems::particleRenderSystem(registry, assets); } // Internal update method void Scene::update(Uint32 delta) { - // Update all (we need to indices here since updates can add objects) - for (Uint32 i = 0; i < entities.size(); ++i) { - if (entities.at(i)->getEnabled() && entities.at(i)->getHooked()) { - entities.at(i)->update(delta); - } - } - - // Internal updates - for (auto& obj : entities) { - obj->updateInternal(); - } - - // Collision system - std::size_t c_type = typeid(Collider).hash_code(); - ComponentArray& colliders = components[c_type]; - for (auto& comp : colliders) { - Collider& collider = dynamic_cast(*comp); - collider.collisions.clear(); - } - - for (auto& collider_1 : colliders) { - for (auto& collider_2 : colliders) { - Collider& col_1 = dynamic_cast(*collider_1); - Collider& col_2 = dynamic_cast(*collider_2); - Transform& tra_1 = getComponent(collider_1->obj_id); - Transform& tra_2 = getComponent(collider_2->obj_id); - - bool colliding = - tra_1.x < tra_2.x + tra_2.width && tra_1.x + tra_1.width > tra_2.x && - tra_1.y < tra_2.y + tra_2.height && tra_1.y + tra_1.height > tra_2.y; - - if (colliding) { - col_1.collisions.push_back(col_2.obj_id); - col_2.collisions.push_back(col_1.obj_id); - } - } - } - - // Remove any game objects that need to be cleaned up - if (remove_pool.size() > 0) { - for (const auto& obj_id : remove_pool) { - // Get vector index - unsigned int entity_index = entity_map[obj_id]; - - // Remove from lookup map - entity_map.erase(obj_id); - - // Erase game object while keeping most indicies correct - entities[entity_index] = std::move(entities.back()); - entities.pop_back(); - - // Update moved index - if (entities.size() > 0) { - auto& moved_obj = *entities[entity_index]; - entity_map[moved_obj.id] = entity_index; - } - - // Erase components - for (auto& comp_entry : component_map) { - removeComponentById(obj_id, comp_entry.first); - } - } - - // Clear remove pool - remove_pool.clear(); - } - - // Sort sprites - if (need_sort) { - // const std::size_t id = typeid(Sprite).hash_code(); - - // std::sort(components[id].begin(), components[id].end(), [](auto& c1, - // auto& c2) { - // return obj1->transform.z < obj2->transform.z; - // }); - } -} - -// Remove game object from scene -void Scene::remove(const ObjId id) { - remove_pool.push_back(id); -} - -// Check if obj id exists in scene -bool Scene::has(const ObjId id) { - return entity_map.count(id) == 1; -} - -// Remove component by type id -void Scene::removeComponentById(const ObjId obj_id, const std::size_t id) { - // Check has - if (component_map[id].count(obj_id) > 0) { - // Copy index - int comp_index = component_map[id][obj_id]; - - // Erase from map - component_map[id].erase(obj_id); - - // Erase component - components[id][comp_index] = std::move(components[id].back()); - components[id].pop_back(); - - // Update moved index - if (components[id].size() > 0) { - component_map[id][obj_id] = comp_index; - } - } + systems::physicsSystem(registry, delta); + systems::particleSystem(registry, delta); } } // namespace afk From 3a8b23e4a904cca9b7c862260c86568545a0bbc4 Mon Sep 17 00:00:00 2001 From: alegemaate Date: Fri, 22 Apr 2022 18:40:38 -0400 Subject: [PATCH 05/24] feat: add collision system --- CMakeLists.txt | 138 +++++++++------- examples/CMakeLists.txt | 23 ++- examples/ex_collision.cpp | 59 ++++--- examples/ex_fps.cpp | 8 +- examples/ex_keyboard.cpp | 2 +- examples/ex_message_box.cpp | 4 +- examples/ex_mouse.cpp | 2 +- examples/ex_particles.cpp | 18 +- examples/ex_physics.cpp | 2 +- examples/ex_rotate.cpp | 2 +- examples/ex_sprite.cpp | 2 +- examples/ex_ui.cpp | 12 +- include/assets/Font.h | 2 +- include/assets/Texture.h | 2 +- include/{color => common}/Color.h | 0 include/common/random.h | 41 +++++ include/components/Collider.h | 22 +++ include/components/Particle.h | 2 +- include/components/ParticleEmitter.h | 2 +- include/components/Sprite.h | 2 +- include/components/ui/Label.h | 6 +- include/entities/GameObject.h | 156 ------------------ include/entities/ObjId.h | 17 -- include/entities/ui/Button.h | 63 ------- include/entities/ui/Checkbox.h | 84 ---------- include/entities/ui/Image.h | 65 -------- include/entities/ui/Inputbox.h | 81 --------- include/entities/ui/Label.h | 53 ------ include/entities/ui/UIElement.h | 117 ------------- include/primitives/Primitives.h | 2 +- include/random/RandomGenerator.h | 49 ------ include/scene/Scene.h | 30 +++- include/services/display/DisplayService.h | 2 +- include/systems/CollisionSystem.h | 54 ++++++ include/systems/ParticleSystem.h | 12 +- include/systems/PhysicsSystem.h | 4 +- include/systems/RenderSystem.h | 6 +- include/systems/UISystem.h | 6 +- include/{entities => }/ui/MessageBox.h | 0 src/Game.cpp | 3 +- src/assets/Font.cpp | 2 +- src/assets/Texture.cpp | 2 +- src/{color => common}/Color.cpp | 2 +- .../RandomGenerator.cpp => common/random.cpp} | 12 +- src/entities/GameObject.cpp | 103 ------------ src/entities/ui/Button.cpp | 58 ------- src/entities/ui/Checkbox.cpp | 81 --------- src/entities/ui/Image.cpp | 34 ---- src/entities/ui/Inputbox.cpp | 156 ------------------ src/entities/ui/Label.cpp | 30 ---- src/entities/ui/UIElement.cpp | 84 ---------- src/scene/Scene.cpp | 34 +++- src/services/display/DisplayService.cpp | 2 +- src/{entities => }/ui/MessageBox.cpp | 2 +- 54 files changed, 351 insertions(+), 1406 deletions(-) rename include/{color => common}/Color.h (100%) create mode 100644 include/common/random.h create mode 100644 include/components/Collider.h delete mode 100644 include/entities/GameObject.h delete mode 100644 include/entities/ObjId.h delete mode 100644 include/entities/ui/Button.h delete mode 100644 include/entities/ui/Checkbox.h delete mode 100644 include/entities/ui/Image.h delete mode 100644 include/entities/ui/Inputbox.h delete mode 100644 include/entities/ui/Label.h delete mode 100644 include/entities/ui/UIElement.h delete mode 100644 include/random/RandomGenerator.h create mode 100644 include/systems/CollisionSystem.h rename include/{entities => }/ui/MessageBox.h (100%) rename src/{color => common}/Color.cpp (97%) rename src/{random/RandomGenerator.cpp => common/random.cpp} (64%) delete mode 100644 src/entities/GameObject.cpp delete mode 100644 src/entities/ui/Button.cpp delete mode 100644 src/entities/ui/Checkbox.cpp delete mode 100644 src/entities/ui/Image.cpp delete mode 100644 src/entities/ui/Inputbox.cpp delete mode 100644 src/entities/ui/Label.cpp delete mode 100644 src/entities/ui/UIElement.cpp rename src/{entities => }/ui/MessageBox.cpp (97%) diff --git a/CMakeLists.txt b/CMakeLists.txt index ee3c82a..bc89bbf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4,7 +4,7 @@ set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/lib) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/lib) -set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/build) set(CMAKE_EXPORT_COMPILE_COMMANDS on) project (afk VERSION 1.0.0 LANGUAGES CXX) @@ -30,78 +30,100 @@ set_target_properties(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION 1) +# Find libs + +if(EMSCRIPTEN) + set(EnTT_DIR "C:/Users/alege/Documents/GitHub/emsdk/upstream/lib/cmake/EnTT") + find_package(EnTT REQUIRED) + +else(EMSCRIPTEN) + find_package(EnTT REQUIRED) + find_library(SDL_LIBRARY NAMES SDL2 REQUIRED) + find_library(SDL_MIXER_LIBRARY NAMES SDL2_mixer REQUIRED) + find_library(SDL_IMAGE_LIBRARY NAMES SDL2_image REQUIRED) + find_library(SDL_TTF_LIBRARY NAMES SDL2_ttf REQUIRED) + find_library(SDL_GFX_LIBRARY NAMES SDL2_gfx REQUIRED) + find_library(SDL_MAIN_LIBRARY NAMES SDL2main REQUIRED) +endif(EMSCRIPTEN) + +# Emscripten specific options if(EMSCRIPTEN) - target_compile_options( - ${PROJECT_NAME} - PRIVATE - -sUSE_SDL=2 - -sUSE_SDL_IMAGE=2 - -sUSE_SDL_TTF=2 - -sUSE_SDL_MIXER=2 - -sUSE_SDL_GFX=2 - -sSDL2_IMAGE_FORMATS=["png"] - ) - target_link_libraries( - ${PROJECT_NAME} - -sWASM=1 - -sUSE_SDL=2 - -sUSE_SDL_IMAGE=2 - -sUSE_SDL_TTF=2 - -sUSE_SDL_MIXER=2 - -sUSE_SDL_GFX=2 - -sSDL2_IMAGE_FORMATS=["png"] - -sDEMANGLE_SUPPORT=1 - ) - target_link_libraries(${PROJECT_NAME} -sUSE_SDL=2 -fsanitize=address) + target_compile_options( + ${PROJECT_NAME} + PRIVATE + -sUSE_SDL=2 + -sUSE_SDL_IMAGE=2 + -sUSE_SDL_TTF=2 + -sUSE_SDL_MIXER=2 + -sUSE_SDL_GFX=2 + -sSDL2_IMAGE_FORMATS=["png"] + ) + target_link_libraries( + ${PROJECT_NAME} + -sWASM=1 + -sUSE_SDL=2 + -sUSE_SDL_IMAGE=2 + -sUSE_SDL_TTF=2 + -sUSE_SDL_MIXER=2 + -sUSE_SDL_GFX=2 + -sSDL2_IMAGE_FORMATS=["png"] + -sDEMANGLE_SUPPORT=1 + EnTT::EnTT + ) + target_link_libraries(${PROJECT_NAME} -sUSE_SDL=2 -fsanitize=address) + +# All other system options else(EMSCRIPTEN) - # Find libs - find_library(SDL_LIBRARY NAMES SDL2 REQUIRED) - find_library(SDL_MIXER_LIBRARY NAMES SDL2_mixer REQUIRED) - find_library(SDL_IMAGE_LIBRARY NAMES SDL2_image REQUIRED) - find_library(SDL_TTF_LIBRARY NAMES SDL2_ttf REQUIRED) - find_library(SDL_GFX_LIBRARY NAMES SDL2_gfx REQUIRED) - find_library(SDL_MAIN_LIBRARY NAMES SDL2main REQUIRED) - find_package(EnTT REQUIRED) - - # Link Libs - target_link_libraries(${PROJECT_NAME} ${SDL_LIBRARY} ${SDL_MIXER_LIBRARY} ${SDL_IMAGE_LIBRARY} ${SDL_TTF_LIBRARY} ${SDL_GFX_LIBRARY} ${SDL_MAIN_LIBRARY} EnTT::EnTT) -endif(EMSCRIPTEN) + target_link_libraries( + ${PROJECT_NAME} + ${SDL_LIBRARY} + ${SDL_MIXER_LIBRARY} + ${SDL_IMAGE_LIBRARY} + ${SDL_TTF_LIBRARY} + ${SDL_GFX_LIBRARY} + ${SDL_MAIN_LIBRARY} + EnTT::EnTT + ) +endif(EMSCRIPTEN) # Install info if (EMSCRIPTEN) - get_filename_component(EMSDK_DIR ${CMAKE_TOOLCHAIN_FILE} DIRECTORY) - set(EMSDK_DIR ${EMSDK_DIR}/../../../system) - message("Lib install directory set to ${EMSDK_DIR}") + get_filename_component(EMSDK_DIR ${CMAKE_TOOLCHAIN_FILE} DIRECTORY) + set(EMSDK_DIR ${EMSDK_DIR}/../../../system) + message("Lib install directory set to ${EMSDK_DIR}") - install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} - ARCHIVE DESTINATION ${EMSDK_DIR}/lib - LIBRARY DESTINATION ${EMSDK_DIR}/lib - RUNTIME DESTINATION ${EMSDK_DIR}/bin) + install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + ARCHIVE DESTINATION ${EMSDK_DIR}/lib + LIBRARY DESTINATION ${EMSDK_DIR}/lib + RUNTIME DESTINATION ${EMSDK_DIR}/bin) - install(DIRECTORY include/ DESTINATION ${EMSDK_DIR}/include/${PROJECT_NAME}) + install(DIRECTORY include/ DESTINATION ${EMSDK_DIR}/include/${PROJECT_NAME}) +# Msys2 specific elseif (WIN32) - install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} - ARCHIVE DESTINATION C:/msys64/mingw32/lib - LIBRARY DESTINATION C:/msys64/mingw32/lib - RUNTIME DESTINATION C:/msys64/mingw32/bin) + install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + ARCHIVE DESTINATION C:/msys64/mingw32/lib + LIBRARY DESTINATION C:/msys64/mingw32/lib + RUNTIME DESTINATION C:/msys64/mingw32/bin) + + install(DIRECTORY include/ DESTINATION C:/msys64/mingw32/include/${PROJECT_NAME}) - install(DIRECTORY include/ DESTINATION C:/msys64/mingw32/include/${PROJECT_NAME}) + install(EXPORT ${PROJECT_NAME} DESTINATION C:/msys64/mingw32/share/${PROJECT_NAME}/cmake) + export(TARGETS ${PROJECT_NAME} FILE ${PROJECT_NAME}.cmake) - install(EXPORT ${PROJECT_NAME} DESTINATION C:/msys64/mingw32/share/${PROJECT_NAME}/cmake) - export(TARGETS ${PROJECT_NAME} FILE ${PROJECT_NAME}.cmake) +# Linux mac etc. else() - include(GNUInstallDirs) + include(GNUInstallDirs) - install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) + install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) - install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}) + install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}) - install(EXPORT ${PROJECT_NAME} DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/${PROJECT_NAME}/cmake) - export(TARGETS ${PROJECT_NAME} FILE ${PROJECT_NAME}.cmake) + install(EXPORT ${PROJECT_NAME} DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/${PROJECT_NAME}/cmake) + export(TARGETS ${PROJECT_NAME} FILE ${PROJECT_NAME}.cmake) endif() # Examples diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 585efa6..c183249 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -2,14 +2,18 @@ cmake_minimum_required(VERSION 3.11) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/build) # Add include dir -include_directories(${CMAKE_BINARY_DIR}/include) -include_directories(${CMAKE_BINARY_DIR}/bin) +include_directories(${CMAKE_SOURCE_DIR}/include) +include_directories(${CMAKE_SOURCE_DIR}/build) # Find libs -if(NOT EMSCRIPTEN) +if(EMSCRIPTEN) + set(EnTT_DIR "C:/Users/alege/Documents/GitHub/emsdk/upstream/lib/cmake/EnTT") + find_package(EnTT REQUIRED) + +else(EMSCRIPTEN) find_library(SDL_LIBRARY NAMES SDL2 REQUIRED) find_library(SDL_MIXER_LIBRARY NAMES SDL2_mixer REQUIRED) find_library(SDL_IMAGE_LIBRARY NAMES SDL2_image REQUIRED) @@ -17,12 +21,12 @@ if(NOT EMSCRIPTEN) find_library(SDL_GFX_LIBRARY NAMES SDL2_gfx REQUIRED) find_library(SDL_MAIN_LIBRARY NAMES SDL2main REQUIRED) find_package(EnTT REQUIRED) -endif(NOT EMSCRIPTEN) +endif(EMSCRIPTEN) # Build examples # ex_collision ex_ui ex_message_box -set(EXAMPLES ex_display ex_sprite ex_rotate ex_fps ex_mouse ex_physics ex_sound ex_particles ex_keyboard) +set(EXAMPLES ex_display ex_sprite ex_rotate ex_fps ex_mouse ex_physics ex_sound ex_particles ex_keyboard ex_collision) foreach(EX_NAME ${EXAMPLES}) add_executable(${EX_NAME} ${CMAKE_CURRENT_LIST_DIR}/${EX_NAME}.cpp) @@ -41,6 +45,7 @@ foreach(EX_NAME ${EXAMPLES}) -sUSE_SDL_GFX=2 -sSDL2_IMAGE_FORMATS=["png"] ) + target_link_libraries( ${EX_NAME} -sWASM=1 @@ -52,8 +57,11 @@ foreach(EX_NAME ${EXAMPLES}) -sSDL2_IMAGE_FORMATS=["png"] -sDEMANGLE_SUPPORT=1 -sTOTAL_MEMORY=512MB + -sDISABLE_EXCEPTION_CATCHING=0 + EnTT::EnTT afk ) + set_target_properties( ${EX_NAME} PROPERTIES @@ -66,6 +74,7 @@ foreach(EX_NAME ${EXAMPLES}) if(MINGW) target_link_libraries(${EX_NAME} -lmingw32) endif(MINGW) + target_link_libraries( ${EX_NAME} -lm @@ -82,4 +91,4 @@ foreach(EX_NAME ${EXAMPLES}) endforeach() # Export assets -file(COPY ${CMAKE_CURRENT_LIST_DIR}/assets/ DESTINATION ${CMAKE_BINARY_DIR}/bin/assets/) +file(COPY ${CMAKE_CURRENT_LIST_DIR}/assets/ DESTINATION ${CMAKE_SOURCE_DIR}/build/assets/) diff --git a/examples/ex_collision.cpp b/examples/ex_collision.cpp index a94948f..ffba877 100644 --- a/examples/ex_collision.cpp +++ b/examples/ex_collision.cpp @@ -11,7 +11,8 @@ #include "../include/Game.h" #include "../include/components/Collider.h" #include "../include/components/Sprite.h" -#include "../include/entities/ui/Label.h" +#include "../include/components/Transform.h" +#include "../include/components/ui/Label.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" @@ -28,46 +29,42 @@ class DemoScene : public afk::Scene { assets.loadImage("lenna", "assets/lenna.png"); assets.loadFont("freesans", "assets/freesans.ttf", 12); - auto& lenna_1 = add(*this, 10, 10); - addComponent(lenna_1.id); - auto& lenna_1_sprite = getComponent(lenna_1.id); - lenna_1_sprite.texture = assets.getImage("lenna"); - addComponent(lenna_1.id); - lenna_1.transform.size.x = 40; - lenna_1.transform.size.y = 40; - lenna_1_id = lenna_1.id; - - auto& lenna_2 = add(*this, 10, 80); - addComponent(lenna_2.id); - auto& lenna_2_sprite = getComponent(lenna_2.id); - lenna_2_sprite.texture = assets.getImage("lenna"); - addComponent(lenna_2.id); - lenna_2.transform.size.x = 40; - lenna_2.transform.size.y = 40; - lenna_2_id = lenna_2.id; - - auto& label = add(*this, 0, 0); + lenna_1_id = createEntity(); + createComponent(lenna_1_id, afk::Vec3(10, 10, 0), + afk::Vec2(40, 40)); + createComponent(lenna_1_id, "lenna"); + createComponent(lenna_1_id); + + lenna_2_id = createEntity(); + createComponent(lenna_2_id, afk::Vec3(10, 80, 0), + afk::Vec2(40, 40)); + createComponent(lenna_2_id, "lenna"); + createComponent(lenna_2_id); + + label_id = createEntity(); + createComponent(label_id, afk::Vec3(10, 5, 0)); + auto& label = createComponent(label_id); + label.setText("FPS"); label.setFont("freesans"); - label_id = label.id; } void update(Uint32 delta) { auto& label = getComponent(label_id); - auto& lenna_1 = get(lenna_1_id); - auto& lenna_2 = get(lenna_2_id); + auto& lenna_1 = getComponent(lenna_1_id); + auto& lenna_2 = getComponent(lenna_2_id); if (input.mouseDown(afk::MouseButtons::LEFT)) { - lenna_1.transform.position.x = input.mouseX(); - lenna_1.transform.position.y = input.mouseY(); + lenna_1.position.x = input.mouseX(); + lenna_1.position.y = input.mouseY(); } if (input.mouseDown(afk::MouseButtons::RIGHT)) { - lenna_2.transform.position.x = input.mouseX(); - lenna_2.transform.position.y = input.mouseY(); + lenna_2.position.x = input.mouseX(); + lenna_2.position.y = input.mouseY(); } auto& collider = getComponent(lenna_1_id); - if (collider.collisions.size() > 0) { + if (collider.colliding) { label.setText("Colliding!"); } else { label.setText("Not colliding"); @@ -79,9 +76,9 @@ class DemoScene : public afk::Scene { void stop() { logger.log("Stopping!"); } private: - ObjId lenna_1_id; - ObjId lenna_2_id; - ObjId label_id; + entt::entity lenna_1_id; + entt::entity lenna_2_id; + entt::entity label_id; }; int main(int argv, char** args) { diff --git a/examples/ex_fps.cpp b/examples/ex_fps.cpp index 88e82c0..76ec35b 100644 --- a/examples/ex_fps.cpp +++ b/examples/ex_fps.cpp @@ -10,10 +10,10 @@ */ #include "../include/Game.h" +#include "../include/common/random.h" #include "../include/components/Sprite.h" #include "../include/components/Transform.h" #include "../include/components/ui/Label.h" -#include "../include/random/RandomGenerator.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" @@ -38,13 +38,13 @@ class DemoScene : public afk::Scene { label_id = createEntity(); createComponent(label_id, afk::Vec3(10, 5, 0)); - auto& label = createComponent(label_id); + auto& label = createComponent(label_id); label.setText("FPS"); label.setFont("freesans"); for (unsigned int i = 0; i < NUM_SPRITE; i++) { auto entity = createEntity(); - createComponent(entity, "lenna"); + createComponent(entity, "lenna"); auto& transform = createComponent(entity); transform.size.x = SPRITE_SIZE; transform.size.y = SPRITE_SIZE; @@ -59,7 +59,7 @@ class DemoScene : public afk::Scene { int fps = display.getFps(); - auto& label = getComponent(label_id); + auto& label = getComponent(label_id); label.setText(std::to_string(fps)); for (unsigned int i = 0; i < NUM_SPRITE; i++) { diff --git a/examples/ex_keyboard.cpp b/examples/ex_keyboard.cpp index 56ff847..f24f7e7 100644 --- a/examples/ex_keyboard.cpp +++ b/examples/ex_keyboard.cpp @@ -55,7 +55,7 @@ class DemoScene : public afk::Scene { entt::entity id = createEntity(); createComponent(id, afk::Vec3(100, 100, 0), afk::Vec2(40, 40)); - createComponent(id, "lenna"); + createComponent(id, "lenna"); character_ids.push_back(id); } diff --git a/examples/ex_message_box.cpp b/examples/ex_message_box.cpp index f947353..0d320ed 100644 --- a/examples/ex_message_box.cpp +++ b/examples/ex_message_box.cpp @@ -9,10 +9,10 @@ * */ #include "../include/Game.h" -#include "../include/entities/ui/Button.h" -#include "../include/entities/ui/MessageBox.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" +#include "../include/ui/Button.h" +#include "../include/ui/MessageBox.h" class DemoScene : public afk::Scene { public: diff --git a/examples/ex_mouse.cpp b/examples/ex_mouse.cpp index 6ae78da..62a280e 100644 --- a/examples/ex_mouse.cpp +++ b/examples/ex_mouse.cpp @@ -27,7 +27,7 @@ class DemoScene : public afk::Scene { assets.loadImage("lenna", "assets/lenna.png"); lennaId = createEntity(); - createComponent(lennaId, "lenna"); + createComponent(lennaId, "lenna"); createComponent(lennaId, afk::Vec3(100, 100, 0), afk::Vec2(30, 30)); } diff --git a/examples/ex_particles.cpp b/examples/ex_particles.cpp index 04042eb..060ec65 100644 --- a/examples/ex_particles.cpp +++ b/examples/ex_particles.cpp @@ -9,12 +9,12 @@ * */ #include "../include/Game.h" -#include "../include/color/Color.h" +#include "../include/common/Color.h" #include "../include/common/Vec.h" +#include "../include/common/random.h" #include "../include/components/Particle.h" #include "../include/components/ParticleEmitter.h" #include "../include/components/Transform.h" -#include "../include/random/RandomGenerator.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" @@ -41,12 +41,12 @@ class DemoScene : public afk::Scene { for (int i = 0; i < 100; i++) { auto& [particle, physics] = emitter_1.addParticle(); particle.setType(afk::ParticleType::SQUARE); - particle.setLifespan(afk::Random::randomInt(100, 1000)); + particle.setLifespan(afk::random::randomInt(100, 1000)); particle.setSize(10.0f, 3.0f); particle.setColor(afk::color::rgb(128, 22, 22), afk::color::rgb(100, 100, 100)); - physics.setVelocity(afk::Random::randomFloat(-5.0f, 5.0f), - afk::Random::randomFloat(-1.0f, -2.0f)); + physics.setVelocity(afk::random::randomFloat(-5.0f, 5.0f), + afk::random::randomFloat(-1.0f, -2.0f)); physics.setAcceleration(0, 2.0f); } @@ -58,10 +58,10 @@ class DemoScene : public afk::Scene { for (int i = 0; i < 100; i++) { auto& [particle, physics] = emitter_2.addParticle(); particle.setType(afk::ParticleType::CIRCLE); - particle.setLifespan(afk::Random::randomInt(1000, 2000)); + particle.setLifespan(afk::random::randomInt(1000, 2000)); particle.setSize(3.0f, 2.0f); particle.setColor(afk::color::blue, afk::color::white); - physics.setVelocity(afk::Random::randomFloat(-20.0, 20.0), -200.0f); + physics.setVelocity(afk::random::randomFloat(-20.0, 20.0), -200.0f); physics.setAcceleration(0, 200.0f); } @@ -73,10 +73,10 @@ class DemoScene : public afk::Scene { for (int i = 0; i < 400; i++) { auto& [particle, physics] = emitter_3.addParticle(); particle.setType(afk::ParticleType::IMAGE); - particle.setLifespan(afk::Random::randomInt(800, 1500)); + particle.setLifespan(afk::random::randomInt(800, 1500)); particle.setSize(16.0f, 20.0f); particle.setTexture("fuzzball"); - physics.setVelocity(afk::Random::randomFloat(2.0f, 2.5f), -5.0f); + physics.setVelocity(afk::random::randomFloat(2.0f, 2.5f), -5.0f); } } diff --git a/examples/ex_physics.cpp b/examples/ex_physics.cpp index 45ddd90..068c848 100644 --- a/examples/ex_physics.cpp +++ b/examples/ex_physics.cpp @@ -47,7 +47,7 @@ class DemoScene : public afk::Scene { assets.loadImage("lenna", "assets/lenna.png"); lennaId = createEntity(); - createComponent(lennaId, "lenna"); + createComponent(lennaId, "lenna"); createComponent(lennaId, afk::Vec3(0, 0, 0), afk::Vec2(40, 40)); createComponent(lennaId, afk::Vec2(100.0f, 400.0f)); diff --git a/examples/ex_rotate.cpp b/examples/ex_rotate.cpp index 6613aa4..7014763 100644 --- a/examples/ex_rotate.cpp +++ b/examples/ex_rotate.cpp @@ -28,7 +28,7 @@ class DemoScene : public afk::Scene { assets.loadImage("lenna", "assets/lenna.png"); lennaId = createEntity(); - createComponent(lennaId, "lenna"); + createComponent(lennaId, "lenna"); createComponent(lennaId, afk::Vec3(156, 156, 0), afk::Vec2(200, 200)); } diff --git a/examples/ex_sprite.cpp b/examples/ex_sprite.cpp index 7bd32a5..9bf5e00 100644 --- a/examples/ex_sprite.cpp +++ b/examples/ex_sprite.cpp @@ -28,7 +28,7 @@ class DemoScene : public afk::Scene { assets.loadImage("lenna", "assets/lenna.png"); auto sprite = createEntity(); - createComponent(sprite, "lenna"); + createComponent(sprite, "lenna"); createComponent(sprite, afk::Vec3(0, 0, 0), afk::Vec2(50, 50)); } diff --git a/examples/ex_ui.cpp b/examples/ex_ui.cpp index 0f41832..2d88bf3 100644 --- a/examples/ex_ui.cpp +++ b/examples/ex_ui.cpp @@ -9,14 +9,14 @@ * */ #include "../include/Game.h" -#include "../include/entities/ui/Button.h" -#include "../include/entities/ui/Checkbox.h" -#include "../include/entities/ui/Image.h" -#include "../include/entities/ui/Inputbox.h" -#include "../include/entities/ui/Label.h" -#include "../include/entities/ui/MessageBox.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" +#include "../include/ui/Button.h" +#include "../include/ui/Checkbox.h" +#include "../include/ui/Image.h" +#include "../include/ui/Inputbox.h" +#include "../include/ui/Label.h" +#include "../include/ui/MessageBox.h" class DemoScene : public afk::Scene { public: diff --git a/include/assets/Font.h b/include/assets/Font.h index 0f736f6..e24f5b8 100644 --- a/include/assets/Font.h +++ b/include/assets/Font.h @@ -14,7 +14,7 @@ #include #include -#include "../color/Color.h" +#include "../common/Color.h" namespace afk { diff --git a/include/assets/Texture.h b/include/assets/Texture.h index 5dd5dfb..87e03b5 100644 --- a/include/assets/Texture.h +++ b/include/assets/Texture.h @@ -14,7 +14,7 @@ #include #include -#include "../color/Color.h" +#include "../common/Color.h" namespace afk { diff --git a/include/color/Color.h b/include/common/Color.h similarity index 100% rename from include/color/Color.h rename to include/common/Color.h diff --git a/include/common/random.h b/include/common/random.h new file mode 100644 index 0000000..d088d3c --- /dev/null +++ b/include/common/random.h @@ -0,0 +1,41 @@ +/** + * @file RandomGenerator.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Static helper class that can create random numbers. + * @version 0.1 + * @date 2020-08-11 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef INCLUDE_RANDOM_RANDOMGENERATOR_H_ +#define INCLUDE_RANDOM_RANDOMGENERATOR_H_ + +#include + +namespace afk::random { + +/** + * @brief Returns a random float between two numbers + * + * @param min Min number + * @param max Max number + * @return Random number + */ +float randomFloat(const float min, const float max); + +/** + * @brief Returns a random int between two numbers + * + * @param min Min number + * @param max Max number + * @return Random number + */ +int randomInt(const int min, const int max); + +/// Random number generator +extern std::mt19937 rng; + +} // namespace afk::random + +#endif // INCLUDE_RANDOM_RANDOMGENERATOR_H_ diff --git a/include/components/Collider.h b/include/components/Collider.h new file mode 100644 index 0000000..15af415 --- /dev/null +++ b/include/components/Collider.h @@ -0,0 +1,22 @@ +/** + * @file Collider.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Collider data component + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef INCLUDE_COMPONENTS_COLLIDER_H_ +#define INCLUDE_COMPONENTS_COLLIDER_H_ + +namespace afk { + +struct Collider { + bool colliding = false; +}; + +} // namespace afk + +#endif // INCLUDE_COMPONENTS_COLLIDER_H_ diff --git a/include/components/Particle.h b/include/components/Particle.h index 1799048..6e0ab51 100644 --- a/include/components/Particle.h +++ b/include/components/Particle.h @@ -12,7 +12,7 @@ #define INCLUDE_COMPONENTS_PARTICLE_H_ #include -#include "../color/Color.h" +#include "../common/Color.h" #include "../common/Vec.h" namespace afk { diff --git a/include/components/ParticleEmitter.h b/include/components/ParticleEmitter.h index c91bc08..c40e196 100644 --- a/include/components/ParticleEmitter.h +++ b/include/components/ParticleEmitter.h @@ -15,7 +15,7 @@ #include #include -#include "../color/Color.h" +#include "../common/Color.h" #include "../common/Vec.h" #include "./Particle.h" #include "./Physics.h" diff --git a/include/components/Sprite.h b/include/components/Sprite.h index 70c7a47..27b28bb 100644 --- a/include/components/Sprite.h +++ b/include/components/Sprite.h @@ -15,7 +15,7 @@ namespace afk { -struct SpriteComponent { +struct Sprite { /// Texture of Sprite std::string texture; }; diff --git a/include/components/ui/Label.h b/include/components/ui/Label.h index 9de9ac6..fbcde84 100644 --- a/include/components/ui/Label.h +++ b/include/components/ui/Label.h @@ -15,11 +15,11 @@ namespace afk { -struct LabelComponent { +struct Label { /// Constructor - LabelComponent() : text(""), font("") {} + Label() : text(""), font("") {} - LabelComponent(const std::string& text, const std::string& font) + Label(const std::string& text, const std::string& font) : text(text), font(font) {} /// Text of Label diff --git a/include/entities/GameObject.h b/include/entities/GameObject.h deleted file mode 100644 index cbb3c52..0000000 --- a/include/entities/GameObject.h +++ /dev/null @@ -1,156 +0,0 @@ -/** - * @file GameObject.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief A general purpose game object, generally absctracted in sub classes. - * @see Sprite - * @see Button - * @version 0.1 - * @date 2017-01-03 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_GAMEOBJECT_H_ -#define INCLUDE_ENTITIES_GAMEOBJECT_H_ - -#include - -#include "../components/Transform.h" -#include "../scene/Scene.h" -#include "ObjId.h" - -namespace afk { - -/** - * @brief A collidable object! Parent class for many others - * - */ -class GameObject { - public: - /** - * @brief Construct a new GameObject - * - * @param scene Reference to scene which is stored in game object - * @param x X position - * @param y Y position - * @param z Z position (for sorting) - */ - explicit GameObject(Scene& scene, - const float x = 0.0f, - const float y = 0.0f, - const int z = 0); - - /** - * @brief Destroy the GameObject - * - */ - virtual ~GameObject(); - - /** - * @brief Update loop to be overriden by derived classes. Automatically called - * by Scene. - * - * @param delta Time since last call in ms - */ - virtual void update(Uint32 delta); - - /** - * @brief Internal game object management - * - */ - void updateInternal(); - - /** - * @brief Draw loop to be overriden by derived classes. Automatically called - * by Scene. - * - * Do not add other game objects in the draw loop! This will cause undefined - * behaviour. - * - */ - virtual void draw(); - - /** - * @brief Set gameobject parent - * - * @param parent_id - */ - void setParent(const ObjId parent_id); - - /** - * @brief Set the visibility of the GameObject. Will not draw when not - * visible. - * - * @param visible Visibility to set to - */ - void setVisible(const bool visible); - - /** - * @brief Set the enabled of the GameObject. Will not update when not enabled. - * - * @param enabled Enabled to set to - */ - void setEnabled(const bool enabled); - - /** - * @brief Set hooked state. This removes the GameObject from the draw and - * update loop as well as its children. - * - * @param hooked Enabled to set to - */ - void setHooked(const bool hooked); - - /** - * @brief Get the visibility of game object - * - * @return true If visible - * @return false If not visible - */ - bool getVisible() const; - - /** - * @brief Check if enabled - * - * @return true If enabled - * @return false If not enabled - */ - bool getEnabled() const; - - /** - * @brief Check if enabled - * - * @return true If enabled - * @return false If not enabled - */ - bool getHooked() const; - - /// Components - Transform transform; - - /// Autoassigned unique id - const ObjId id; - - protected: - /// Reference to registered scene - Scene& scene; - - /// Visibility - bool visible; - - /// Enabled - bool enabled; - - /// Hooked - bool hooked; - - private: - /// Parent Id - ObjId parent_id; - - /// Static id counter - static ObjId index; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_GAMEOBJECT_H_ diff --git a/include/entities/ObjId.h b/include/entities/ObjId.h deleted file mode 100644 index b22e7fe..0000000 --- a/include/entities/ObjId.h +++ /dev/null @@ -1,17 +0,0 @@ -/** - * @file ObjId.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Declaration of ObjId type - * @version 0.1 - * @date 2017-01-03 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_OBJID_H_ -#define INCLUDE_ENTITIES_OBJID_H_ - -/// Unique id type alias -using ObjId = unsigned long long; - -#endif // INCLUDE_ENTITIES_OBJID_H_ diff --git a/include/entities/ui/Button.h b/include/entities/ui/Button.h deleted file mode 100644 index a929a4b..0000000 --- a/include/entities/ui/Button.h +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @file Button.h - * @author - * Allan Legemaate (alegemaate@gmail.com) - * Danny Van Stemp (dannyvanstemp@gmail.com) - * @brief A ui elemenent that accepts a click callback. - * @version 0.1 - * @date 2017-04-11 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_UI_BUTTON_H_ -#define INCLUDE_ENTITIES_UI_BUTTON_H_ - -#include "UIElement.h" - -#include - -#include "../../assets/Texture.h" - -namespace afk { - -/** - * @brief Implementation of clickable UI Button - * - */ -class Button : public UIElement { - public: - /** - * @brief Construct a new Button object - * - * @param scene Scene to add element to - * @param x X position of element - * @param y Y position of element - * @param z Z position of element (for sorting) - */ - explicit Button(Scene& scene, - const float x = 0, - const float y = 0, - const int z = 0); - - /** - * @brief Draw the button to the screen. - * - */ - void draw() override; - - /** - * @brief Helper to size button to text - * - */ - void sizeToText(); -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_UI_BUTTON_H_ - -/** - * @example ex_ui.cpp - * This example shows how to use various ui elements - */ diff --git a/include/entities/ui/Checkbox.h b/include/entities/ui/Checkbox.h deleted file mode 100644 index 3bf8b41..0000000 --- a/include/entities/ui/Checkbox.h +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @file Checkbox.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief UI Checkbox - * @version 0.1 - * @date 2021-03-12 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_UI_CHECKBOX_H_ -#define INCLUDE_ENTITIES_UI_CHECKBOX_H_ - -#include "UIElement.h" - -#include - -namespace afk { - -/** - * @brief Implementation of clickable UI Button - * - */ -class Checkbox : public UIElement { - public: - /** - * @brief Construct a new Checkbox object - * - * @param scene Scene to add element to - * @param x X position of element - * @param y Y position of element - * @param z Z position of element (for sorting) - */ - explicit Checkbox(Scene& scene, - const float x = 0, - const float y = 0, - const int z = 0); - - /** - * @brief Draw the checkbox to the screen. - * - */ - void draw() override; - - /** - * @brief Check if checkbox checked - * - */ - bool getChecked() const; - - /** - * @brief Set checked state - * - */ - void setChecked(const bool checked); - - /** - * @brief Set the onCheck function which will be called when element is - * check - * - * @param func function to assign to onCheck - */ - void setOnCheck(std::function func); - - protected: - /// Intercept on click - void handleOnClick() override; - - private: - /// Checked state - bool checked; - - /// On check callback - std::function onCheck; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_UI_CHECKBOX_H_ - -/** - * @example ex_ui.cpp - * This example shows how to use various ui elements - */ diff --git a/include/entities/ui/Image.h b/include/entities/ui/Image.h deleted file mode 100644 index ca56e18..0000000 --- a/include/entities/ui/Image.h +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @file Image.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief UI Image - * @version 0.1 - * @date 2021-03-12 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_UI_IMAGE_H_ -#define INCLUDE_ENTITIES_UI_IMAGE_H_ - -#include - -#include "../../assets/Texture.h" -#include "UIElement.h" - -namespace afk { - -/** - * @brief A simple texturable game object - * - */ -class Image : public UIElement { - public: - /** - * @brief Construct a new Image object - * - * @param scene Reference to scene which is stored in game object - * @param x X position - * @param y Y position - * @param z Z position (for sorting) - */ - explicit Image(Scene& scene, - const float x = 0.0f, - const float y = 0.0f, - const int z = 0); - - /** - * @brief Hook into draw loop - * - */ - void draw() override; - - /** - * @brief Set the Texture of the sprite - * - * @param texture Id of texture to assign - */ - void setTexture(const std::string& texture); - - protected: - /// Texture of Image - Texture texture; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_UI_IMAGE_H_ - -/** - * @example ex_ui.cpp - * This example shows how to use various ui elements - */ diff --git a/include/entities/ui/Inputbox.h b/include/entities/ui/Inputbox.h deleted file mode 100644 index 0895c0f..0000000 --- a/include/entities/ui/Inputbox.h +++ /dev/null @@ -1,81 +0,0 @@ -/** - * @file Inputbox.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief UI Inputbox - * @version 0.1 - * @date 2021-03-12 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_UI_INPUTBOX_H_ -#define INCLUDE_ENTITIES_UI_INPUTBOX_H_ - -#include "UIElement.h" - -#include - -namespace afk { - -/** - * @brief Implementation of clickable UI Button - * - */ -class Inputbox : public UIElement { - public: - /** - * @brief Construct a new Inputbox object - * - * @param scene Scene to add element to - * @param x X position of element - * @param y Y position of element - * @param z Z position of element (for sorting) - */ - explicit Inputbox(Scene& scene, - const float x = 0, - const float y = 0, - const int z = 0); - - /** - * @brief Draw the inputbox to the screen. - * - */ - void draw() override; - - /** - * @brief Update loop override - * - */ - void update(Uint32 delta) override; - - /** - * @brief Set the onChange function which will be called when element text - * changes - * - * @param func function to assign to onChange - */ - void setOnChange(std::function func); - - /** - * @brief Set the text of the input box - * - * @param text Text to insert - */ - void setText(const std::string& text) override; - - private: - /// Text iterator - std::string::iterator iter; - - /// On check callback - std::function onChange; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_UI_INPUTBOX_H_ - -/** - * @example ex_ui.cpp - * This example shows how to use various ui elements - */ diff --git a/include/entities/ui/Label.h b/include/entities/ui/Label.h deleted file mode 100644 index 4db00b8..0000000 --- a/include/entities/ui/Label.h +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @file Label.h - * @author - * Allan Legemaate (alegemaate@gmail.com) - * Danny Van Stemp (dannyvanstemp@gmail.com) - * @brief UI Label that simply displays text. - * @version 0.1 - * @date 2018-11-25 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_UI_LABEL_H_ -#define INCLUDE_ENTITIES_UI_LABEL_H_ - -#include "UIElement.h" - -#include -namespace afk { - -/** - * @brief Implementation of Label class - */ -class Label : public UIElement { - public: - /** - * @brief Construct a new Label object - * - * @param scene Scene to add element to - * @param x X position of element - * @param y Y position of element - * @param z Z position of element (for sorting) - */ - explicit Label(Scene& scene, - const float x = 0, - const float y = 0, - const int z = 0); - - /** - * @brief Draw the label to the screen. - * - */ - void draw() override; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_UI_LABEL_H_ - -/** - * @example ex_ui.cpp - * This example shows how to use various ui elements - */ diff --git a/include/entities/ui/UIElement.h b/include/entities/ui/UIElement.h deleted file mode 100644 index 8a1acac..0000000 --- a/include/entities/ui/UIElement.h +++ /dev/null @@ -1,117 +0,0 @@ -/** - * @file UIElement.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Parent class of many other UIElement subclasses. Handles most things - * that all UIElements may need. - * @version 0.1 - * @date 2020-11-01 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_UI_UIELEMENT_H_ -#define INCLUDE_ENTITIES_UI_UIELEMENT_H_ - -#include -#include - -#include "../../assets/Font.h" -#include "../GameObject.h" - -namespace afk { - -/** - * @brief Parent class for other UI elements such as buttons and labels. - * - */ -class UIElement : public GameObject { - public: - /** - * @brief Construct a new UIElement object - * - * @param scene Scene to add element to - * @param x X position of element - * @param y Y position of element - * @param z Z position of element (for sorting) - */ - UIElement(Scene& scene, const float x, const float y, const int z); - - /** - * @brief Draw the ui element to the screen. Can be overriden by other ui - * elements. - * - */ - void draw() override; - - /** - * @brief Update ui element. Checks for collisions and clicks. - * - * @param delta Time since last call in ms - * - */ - void update(Uint32 delta) override; - - /** - * @brief Set the font to use for displaying text - * - * @param font id of font to render text with - */ - void setFont(const std::string& font); - - /** - * @brief Set the text align of font - * - * @param align Text align - */ - void setTextAlign(const TextAlign align); - - /** - * @brief Set the text to display on ui element - * - * @param text to display - */ - virtual void setText(const std::string& text); - - /** - * @brief Set the onClick function which will be called when element is - * clicked - * - * @param func function to assign to onClick - */ - void setOnClick(std::function func); - - /** - * @brief Get the text - * - * @returns text - */ - std::string getText() const; - - protected: - /// Font to use for displaying text - Font font; - - // Font align - TextAlign text_align; - - /// Text to display where applicable - std::string text; - - /// Intermediate on click handler - virtual void handleOnClick(); - - /// Holds reference to onClick function - std::function onClick; - - /// Stores id of focused element - static ObjId focused; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_UI_UIELEMENT_H_ - -/** - * @example ex_ui.cpp - * This example shows how to use various ui elements - */ diff --git a/include/primitives/Primitives.h b/include/primitives/Primitives.h index 74e41c5..fa7abae 100644 --- a/include/primitives/Primitives.h +++ b/include/primitives/Primitives.h @@ -12,7 +12,7 @@ #ifndef INCLUDE_PRIMITIVES_PRIMITIVES_H_ #define INCLUDE_PRIMITIVES_PRIMITIVES_H_ -#include "../color/Color.h" +#include "../common/Color.h" namespace afk { namespace primitives { diff --git a/include/random/RandomGenerator.h b/include/random/RandomGenerator.h deleted file mode 100644 index 048f06c..0000000 --- a/include/random/RandomGenerator.h +++ /dev/null @@ -1,49 +0,0 @@ -/** - * @file RandomGenerator.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Static helper class that can create random numbers. - * @version 0.1 - * @date 2020-08-11 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_RANDOM_RANDOMGENERATOR_H_ -#define INCLUDE_RANDOM_RANDOMGENERATOR_H_ - -#include - -namespace afk { - -/** - * @brief Random number generator - * - */ -class Random { - public: - /** - * @brief Returns a random float between two numbers - * - * @param min Min number - * @param max Max number - * @return Random number - */ - static float randomFloat(const float min, const float max); - - /** - * @brief Returns a random int between two numbers - * - * @param min Min number - * @param max Max number - * @return Random number - */ - static int randomInt(const int min, const int max); - - private: - /// Random number generator - static std::mt19937 rng; -}; - -} // namespace afk - -#endif // INCLUDE_RANDOM_RANDOMGENERATOR_H_ diff --git a/include/scene/Scene.h b/include/scene/Scene.h index 65ee94c..96f75ac 100644 --- a/include/scene/Scene.h +++ b/include/scene/Scene.h @@ -19,6 +19,7 @@ #include #include "../common/Exceptions.h" +#include "../components/Transform.h" #include "../services/Services.h" /** @@ -78,14 +79,14 @@ class Scene { * * @return entt::entity */ - entt::entity createEntity() { return registry.create(); } + entt::entity createEntity(); /** * @brief Remove an entity * * @param entity Entity to remove */ - void destroyEntity(entt::entity entity) { registry.destroy(entity); } + void destroyEntity(entt::entity entity); /** * @brief Add a component to an entity @@ -97,7 +98,25 @@ class Scene { */ template T& createComponent(entt::entity id, Args&&... args) { - return registry.emplace(id, std::forward(args)...); + auto& component = registry.emplace(id, std::forward(args)...); + + // Sort always (inefficient!) + registry.sort([](const auto& lhs, const auto& rhs) { + return lhs.position.z < rhs.position.z; + }); + + return component; + } + + /** + * @brief Add a component to an entity without args + * + * @tparam T Type of component + * @param id Entity to assign to + */ + template + T& createComponent(entt::entity id) { + return registry.emplace(id); } /** @@ -117,7 +136,7 @@ class Scene { * * @return entt::registry& Registry reference */ - entt::registry& getRegistry() { return registry; } + entt::registry& getRegistry(); /// Audio service reference AudioService& audio; @@ -141,9 +160,6 @@ class Scene { ConfigService& config; private: - /// Needs sorting - bool need_sort; - /// Entity registry entt::registry registry; }; diff --git a/include/services/display/DisplayService.h b/include/services/display/DisplayService.h index 6c5792f..be85e76 100644 --- a/include/services/display/DisplayService.h +++ b/include/services/display/DisplayService.h @@ -16,7 +16,7 @@ #include #include -#include "../../color/Color.h" +#include "../../common/Color.h" #include "../Service.h" const int FRAME_BUFFER_SIZE = 50; diff --git a/include/systems/CollisionSystem.h b/include/systems/CollisionSystem.h new file mode 100644 index 0000000..9879301 --- /dev/null +++ b/include/systems/CollisionSystem.h @@ -0,0 +1,54 @@ +/** + * @file CollisionSystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of updating transforms + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef INCLUDE_SYSTEMS_COLLISION_SYSTEM_H_ +#define INCLUDE_SYSTEMS_COLLISION_SYSTEM_H_ + +#include + +#include "components/Collider.h" +#include "components/Transform.h" +#include "services/assets/AssetService.h" + +namespace afk::systems { + +/** + * @brief CollisionSystem + * + */ +void collisionSystem(entt::registry& registry) { + auto view = registry.view(); + + for (auto [entity, tran, collider] : view.each()) { + // Reset state + collider.colliding = false; + + for (auto [entity_other, tran_other, collider_other] : view.each()) { + // Check if is entity + if (entity == entity_other) { + continue; + } + + // Check if colliding + if (tran.position.x > tran_other.position.x + tran_other.size.x || + tran.position.x + tran.size.x < tran_other.position.x || + tran.position.y > tran_other.position.y + tran_other.size.y || + tran.position.y + tran.size.y < tran_other.position.y) { + continue; + } + + collider.colliding = true; + } + } +} + +} // namespace afk::systems + +#endif // INCLUDE_SYSTEMS_COLLISION_SYSTEM_H_ \ No newline at end of file diff --git a/include/systems/ParticleSystem.h b/include/systems/ParticleSystem.h index c794677..5fa7466 100644 --- a/include/systems/ParticleSystem.h +++ b/include/systems/ParticleSystem.h @@ -16,19 +16,19 @@ #include #include "common/math.h" +#include "common/random.h" #include "components/Particle.h" #include "components/ParticleEmitter.h" #include "components/Transform.h" #include "primitives/Primitives.h" -#include "random/RandomGenerator.h" #include "services/assets/AssetService.h" +namespace afk::systems { + /** * @brief ParticleSystem * */ -namespace afk::systems { - void particleSystem(entt::registry& registry, float delta) { auto particle_view = registry.view(); @@ -53,15 +53,15 @@ void particleSystem(entt::registry& registry, float delta) { while (emitter.counter > emitter.frequency && emitter.templates.size() > 0) { - int index = Random::randomInt(0, emitter.templates.size() - 1); + int index = random::randomInt(0, emitter.templates.size() - 1); auto& [particle, physics] = emitter.templates.at(index); emitter.counter -= emitter.frequency; const float start_x = - tran.position.x + Random::randomFloat(0, tran.size.x); + tran.position.x + random::randomFloat(0, tran.size.x); const float start_y = - tran.position.y + Random::randomFloat(0, tran.size.y); + tran.position.y + random::randomFloat(0, tran.size.y); const auto& particle_id = registry.create(); registry.emplace(particle_id, particle); diff --git a/include/systems/PhysicsSystem.h b/include/systems/PhysicsSystem.h index bfdd0b5..8f0bdf7 100644 --- a/include/systems/PhysicsSystem.h +++ b/include/systems/PhysicsSystem.h @@ -17,12 +17,12 @@ #include "components/Transform.h" #include "services/assets/AssetService.h" +namespace afk::systems { + /** * @brief PhysicsSystem * */ -namespace afk::systems { - void physicsSystem(entt::registry& registry, Uint32 delta) { auto view = registry.view(); diff --git a/include/systems/RenderSystem.h b/include/systems/RenderSystem.h index 21b83c3..3dd7d1d 100644 --- a/include/systems/RenderSystem.h +++ b/include/systems/RenderSystem.h @@ -17,14 +17,14 @@ #include "components/Transform.h" #include "services/assets/AssetService.h" +namespace afk::systems { + /** * @brief RenderSystem * */ -namespace afk::systems { - void renderSystem(entt::registry& registry, AssetService& assetService) { - auto view = registry.view(); + auto view = registry.view(); for (auto [entity, tran, sprite] : view.each()) { auto texture = assetService.getImage(sprite.texture); diff --git a/include/systems/UISystem.h b/include/systems/UISystem.h index 887d64d..3138832 100644 --- a/include/systems/UISystem.h +++ b/include/systems/UISystem.h @@ -17,14 +17,14 @@ #include "components/ui/Label.h" #include "services/assets/AssetService.h" +namespace afk::systems { + /** * @brief UISystem * */ -namespace afk::systems { - void uiSystem(entt::registry& registry, AssetService& assetService) { - auto view = registry.view(); + auto view = registry.view(); for (auto [entity, tran, label] : view.each()) { auto font = assetService.getFont(label.font); diff --git a/include/entities/ui/MessageBox.h b/include/ui/MessageBox.h similarity index 100% rename from include/entities/ui/MessageBox.h rename to include/ui/MessageBox.h diff --git a/src/Game.cpp b/src/Game.cpp index a212ba4..21d8a4e 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -11,9 +11,8 @@ #include "Game.h" #include "common/Exceptions.h" -#include "entities/ui/MessageBox.h" -#include "random/RandomGenerator.h" #include "services/Services.h" +#include "ui/MessageBox.h" #ifdef __EMSCRIPTEN__ #include diff --git a/src/assets/Font.cpp b/src/assets/Font.cpp index 55bbe26..dfc9e7d 100644 --- a/src/assets/Font.cpp +++ b/src/assets/Font.cpp @@ -10,7 +10,7 @@ */ #include "assets/Font.h" -#include "color/Color.h" +#include "common/Color.h" #include "common/Exceptions.h" #include "services/Services.h" diff --git a/src/assets/Texture.cpp b/src/assets/Texture.cpp index 94721ff..46cc9e3 100644 --- a/src/assets/Texture.cpp +++ b/src/assets/Texture.cpp @@ -12,7 +12,7 @@ #include -#include "color/Color.h" +#include "common/Color.h" #include "common/Exceptions.h" #include "services/Services.h" diff --git a/src/color/Color.cpp b/src/common/Color.cpp similarity index 97% rename from src/color/Color.cpp rename to src/common/Color.cpp index 956c63a..1413043 100644 --- a/src/color/Color.cpp +++ b/src/common/Color.cpp @@ -8,7 +8,7 @@ * @copyright Copyright (c) 2021 * */ -#include "color/Color.h" +#include "common/Color.h" namespace afk::color { diff --git a/src/random/RandomGenerator.cpp b/src/common/random.cpp similarity index 64% rename from src/random/RandomGenerator.cpp rename to src/common/random.cpp index accb412..78d87c9 100644 --- a/src/random/RandomGenerator.cpp +++ b/src/common/random.cpp @@ -8,25 +8,25 @@ * @copyright Copyright (c) 2021 * */ -#include "random/RandomGenerator.h" +#include "common/random.h" #include -namespace afk { +namespace afk::random { // Init generator -std::mt19937 Random::rng = std::mt19937(std::random_device{}()); +std::mt19937 rng = std::mt19937(std::random_device{}()); // Random Float -float Random::randomFloat(const float min, const float max) { +float randomFloat(const float min, const float max) { std::uniform_real_distribution float_dist{min, max}; return float_dist(rng); } // Random Int -int Random::randomInt(const int min, const int max) { +int randomInt(const int min, const int max) { std::uniform_int_distribution int_dist{min, max}; return int_dist(rng); } -} // namespace afk +} // namespace afk::random diff --git a/src/entities/GameObject.cpp b/src/entities/GameObject.cpp deleted file mode 100644 index 57179cb..0000000 --- a/src/entities/GameObject.cpp +++ /dev/null @@ -1,103 +0,0 @@ -/** - * @file GameObject.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of GameObject class - * @version 0.1 - * @date 2017-01-03 - * - * @copyright Copyright (c) 2021 - * - */ -#include "entities/GameObject.h" - -#include - -namespace afk { - -// Set incrementing index count -ObjId GameObject::index = 1; - -// Constructor -GameObject::GameObject(Scene& scene, const float x, const float y, const int z) - : id(GameObject::index), - scene(scene), - visible(true), - enabled(true), - hooked(true), - parent_id(0) { - GameObject::index += 1; - - // Set transform - transform.position.x = x; - transform.position.y = y; - transform.position.z = z; -} - -// Destructor, remove components -GameObject::~GameObject() {} - -// Update -void GameObject::update(Uint32 delta) { - (void)delta; -} - -// Update -void GameObject::updateInternal() { - // Parent functions - // if (parent_id != 0) { - // // Autoremove if parent is dead - // try { - // auto& parent = scene.getComponent(parent_id); - - // // Set hooked state - // hooked = parent.getHooked(); - - // // Set position - // transform.position.x += parent.transform.position.x - - // parent.transform.last_x; transform.position.y += - // parent.transform.position.y - parent.transform.last_y; - // } catch (const KeyLookupException&) { - // // scene.remove(id); - // } - // } -} - -// Draw -void GameObject::draw() {} - -// Add child -void GameObject::setParent(const ObjId parent_id) { - this->parent_id = parent_id; -} - -// Set visibility -void GameObject::setVisible(const bool visible) { - this->visible = visible; -} - -// Set enabled -void GameObject::setEnabled(const bool enabled) { - this->enabled = enabled; -} - -// Set hooked -void GameObject::setHooked(const bool hooked) { - this->hooked = hooked; -} - -// Get visibility -bool GameObject::getVisible() const { - return this->visible; -} - -// Get enabled -bool GameObject::getEnabled() const { - return this->enabled; -} - -// Get hooked -bool GameObject::getHooked() const { - return this->hooked; -} - -} // namespace afk diff --git a/src/entities/ui/Button.cpp b/src/entities/ui/Button.cpp deleted file mode 100644 index 6480b2c..0000000 --- a/src/entities/ui/Button.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @file Button.cpp - * @author - * Allan Legemaate (alegemaate@gmail.com) - * Danny Van Stemp (dannyvanstemp@gmail.com) - * @brief Implementation of Button - * @version 0.1 - * @date 2017-04-11 - * - * @copyright Copyright (c) 2021 - * - */ -#include "entities/ui/Button.h" - -#include "color/Color.h" -#include "primitives/Primitives.h" -#include "scene/Scene.h" -#include "services/Services.h" - -namespace afk { - -const int DEFAULT_HEIGHT = 20; -const int DEFAULT_WIDTH = 20; -const int DEFAULT_PADDING = 5; - -// Ctor -Button::Button(Scene& scene, const float x, const float y, const int z) - : UIElement(scene, x, y, z) { - transform.size.x = DEFAULT_WIDTH; - transform.size.y = DEFAULT_HEIGHT; -} - -// Draw button -void Button::draw() { - // Draw button background - primitives::rectfill(transform.position.x, transform.position.y, - transform.size.x, transform.size.y, color::white); - - // Draw button border - primitives::rect(transform.position.x, transform.position.y, transform.size.x, - transform.size.y, color::black); - - // Text - font.draw(transform.position.x + DEFAULT_PADDING, - transform.position.y + DEFAULT_PADDING, text, color::black, - text_align); -} - -// Override text setter -void Button::sizeToText() { - if (!font.exists()) { - return; - } - transform.size.y = font.getHeight() + DEFAULT_PADDING * 2; - transform.size.x = font.getWidth(text) + DEFAULT_PADDING * 2; -} - -} // namespace afk diff --git a/src/entities/ui/Checkbox.cpp b/src/entities/ui/Checkbox.cpp deleted file mode 100644 index bf8937e..0000000 --- a/src/entities/ui/Checkbox.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/** - * @file Checkbox.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of UI Checkbox - * @version 0.1 - * @date 2021-03-12 - * - * @copyright Copyright (c) 2021 - * - */ -#include - -#include "entities/ui/Checkbox.h" - -#include "color/Color.h" -#include "primitives/Primitives.h" -#include "scene/Scene.h" -#include "services/Services.h" - -const int DEFAULT_HEIGHT = 20; -const int DEFAULT_WIDTH = 20; - -namespace afk { - -// Ctor -Checkbox::Checkbox(Scene& scene, const float x, const float y, const int z) - : UIElement(scene, x, y, z), checked(false), onCheck(nullptr) { - transform.size.y = DEFAULT_HEIGHT; - transform.size.x = DEFAULT_WIDTH; -} - -// Draw checkbox -void Checkbox::draw() { - // Draw checkbox background - primitives::rectfill(transform.position.x, transform.position.y, - transform.size.x, transform.size.y, color::white); - - // Draw checkbox border - primitives::rect(transform.position.x, transform.position.y, transform.size.x, - transform.size.y, color::black); - - if (checked) { - primitives::rectfill(transform.position.x + transform.size.x / 4, - transform.position.y + transform.size.y / 4, - transform.size.x - transform.size.x / 2, - transform.size.y - transform.size.y / 2, color::black); - } - - // Draw text label - font.draw(transform.position.x + transform.size.x + 10, - transform.position.y + transform.size.y - font.getHeight(), text, - color::black); -} - -// Check checkbox stat -bool Checkbox::getChecked() const { - return checked; -} - -// Set checked state -void Checkbox::setChecked(const bool checked) { - this->checked = checked; -} - -// Set on click -void Checkbox::setOnCheck(std::function func) { - this->onCheck = func; -} - -// On click interceptor -void Checkbox::handleOnClick() { - checked = !checked; - if (onCheck) { - onCheck(checked); - } - if (onClick) { - onClick(); - } -} - -} // namespace afk diff --git a/src/entities/ui/Image.cpp b/src/entities/ui/Image.cpp deleted file mode 100644 index ef69ae4..0000000 --- a/src/entities/ui/Image.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/** - * @file Image.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Texturable ui element - * @version 0.1 - * @date 2021-03-12 - * - * @copyright Copyright (c) 2021 - * - */ -#include "entities/ui/Image.h" - -#include "scene/Scene.h" - -namespace afk { - -// Detailed constructor -Image::Image(Scene& scene, const float x, const float y, const int z) - : UIElement(scene, x, y, z) {} - -// Draw image -void Image::draw() { - texture.drawEx(transform.position.x, transform.position.y, transform.size.x, - transform.size.y, transform.angle); -} - -void Image::setTexture(const std::string& texture) { - this->texture = scene.assets.getImage(texture); - - transform.size.x = this->texture.getWidth(); - transform.size.y = this->texture.getHeight(); -} - -} // namespace afk diff --git a/src/entities/ui/Inputbox.cpp b/src/entities/ui/Inputbox.cpp deleted file mode 100644 index dccacf3..0000000 --- a/src/entities/ui/Inputbox.cpp +++ /dev/null @@ -1,156 +0,0 @@ -/** - * @file Inputbox.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of UI Inputbox - * @version 0.1 - * @date 2021-03-12 - * - * @copyright Copyright (c) 2021 - * - */ -#include -#include - -#include "entities/ui/Inputbox.h" - -#include "color/Color.h" -#include "primitives/Primitives.h" -#include "scene/Scene.h" -#include "services/Services.h" - -namespace afk { - -const int NUMBER_OFFSET = 19; -const int LOWER_OFFSET = 93; -const int UPPER_OFFSET = 61; - -const int DEFAULT_HEIGHT = 20; -const int DEFAULT_WIDTH = 100; -const int DEFAULT_PADDING = 5; - -// Ctor -Inputbox::Inputbox(Scene& scene, const float x, const float y, const int z) - : UIElement(scene, x, y, z), iter(text.end()), onChange(nullptr) { - transform.size.y = DEFAULT_HEIGHT; - transform.size.x = DEFAULT_WIDTH; -} - -// Draw checkbox -void Inputbox::draw() { - // Draw checkbox background - primitives::rectfill(transform.position.x, transform.position.y, - transform.size.x, transform.size.y, color::white); - - // Draw checkbox border - primitives::rect(transform.position.x, transform.position.y, transform.size.x, - transform.size.y, color::black); - - // Focus border - if (id == UIElement::focused) { - primitives::rect(transform.position.x + 1, transform.position.y + 1, - transform.size.x - 2, transform.size.y - 2, color::black); - } - - // Draw text label - font.draw(transform.position.x + DEFAULT_PADDING, - transform.position.y + transform.size.y - font.getHeight(), text, - color::black); - - // Draw the caret - std::string edit_pos = text.substr(0, std::distance(text.begin(), iter)); - int line_x = font.getWidth(edit_pos); - - afk::primitives::line( - line_x + transform.position.x + DEFAULT_PADDING, transform.position.y + 2, - line_x + transform.position.x + DEFAULT_PADDING, - transform.position.y + transform.size.y - 2, afk::color::black); -} - -// Update loop -void Inputbox::update(Uint32 delta) { - // Update parent - UIElement::update(delta); - - // Ensure focused - if (id != UIElement::focused) { - return; - } - - int lastKeyInt = scene.input.lastKeyPressed(); - afk::Keys lastKey = static_cast(lastKeyInt); - bool shiftDown = scene.input.keyDown(afk::Keys::LSHIFT) || - scene.input.keyDown(afk::Keys::RSHIFT); - bool ctrlDown = scene.input.keyDown(afk::Keys::LCTRL) || - scene.input.keyDown(afk::Keys::RCTRL); - - // Ignore blank key - if (lastKey == afk::Keys::UNKNOWN) { - return; - } - - // Letters - if (lastKey >= afk::Keys::A && lastKey <= afk::Keys::Z) { - if (shiftDown) { - iter = text.insert(iter, lastKeyInt + UPPER_OFFSET); - } else { - iter = text.insert(iter, lastKeyInt + LOWER_OFFSET); - } - std::advance(iter, 1); - } - - // Numbers - else if (lastKey >= afk::Keys::ONE && lastKey <= afk::Keys::NINE) { - iter = text.insert(iter, lastKeyInt + NUMBER_OFFSET); - std::advance(iter, 1); - } - - // Special zero case - else if (lastKey == afk::Keys::ZERO) { - iter = text.insert(iter, 48); - std::advance(iter, 1); - } - - // Space - else if (lastKey == afk::Keys::SPACE) { - iter = text.insert(iter, 32); - std::advance(iter, 1); - } - - // Backspace - else if (lastKey == afk::Keys::BACKSPACE && iter != text.begin()) { - if (ctrlDown) { - iter = text.erase(text.begin(), iter); - } else { - std::advance(iter, -1); - iter = text.erase(iter); - } - } - - // Delete - else if (lastKey == afk::Keys::DELETE && iter != text.end()) { - iter = text.erase(iter); - } - - // Right - else if (lastKey == afk::Keys::RIGHT && iter != text.end()) { - std::advance(iter, 1); - } - - // Left - else if (lastKey == afk::Keys::LEFT && iter != text.begin()) { - std::advance(iter, -1); - } -} - -// Set text -void Inputbox::setText(const std::string& text) { - this->text = text; - iter = this->text.end(); -} - -// Set on click -void Inputbox::setOnChange(std::function func) { - this->onChange = func; -} - -} // namespace afk diff --git a/src/entities/ui/Label.cpp b/src/entities/ui/Label.cpp deleted file mode 100644 index e20ae35..0000000 --- a/src/entities/ui/Label.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/** - * @file Label.cpp - * @author - * Allan Legemaate (alegemaate@gmail.com) - * Danny Van Stemp (dannyvanstemp@gmail.com) - * @brief Implementation of Label class - * @version 0.1 - * @date 2018-11-25 - * - * @copyright Copyright (c) 2021 - * - */ -#include "entities/ui/Label.h" - -#include "color/Color.h" - -namespace afk { - -// Detailed constructor -Label::Label(Scene& scene, const float x, const float y, const int z) - : UIElement(scene, x, y, z) {} - -// Draw label -void Label::draw() { - // Text - font.draw(transform.position.x, transform.position.y, text, color::black, - text_align); -} - -} // namespace afk diff --git a/src/entities/ui/UIElement.cpp b/src/entities/ui/UIElement.cpp deleted file mode 100644 index 6656cd0..0000000 --- a/src/entities/ui/UIElement.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @file UIElement.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of UIElement - * @version 0.1 - * @date 2020-11-01 - * - * @copyright Copyright (c) 2021 - * - */ -#include "entities/ui/UIElement.h" - -#include -#include "scene/Scene.h" -#include "services/Services.h" - -namespace afk { - -// Static -ObjId UIElement::focused = 0; - -// Constructor -UIElement::UIElement(Scene& scene, const float x, const float y, const int z) - : GameObject(scene, x, y, z), - text_align(TextAlign::LEFT), - text(""), - onClick(nullptr) {} - -// Set font of element -void UIElement::setFont(const std::string& font) { - if (font != "") { - this->font = Services::getAssetService().getFont(font); - } -} - -// Set text align -void UIElement::setTextAlign(const TextAlign align) { - text_align = align; -} - -// Set text of element -void UIElement::setText(const std::string& text) { - this->text = text; -} - -// Draw -void UIElement::draw() {} - -// Update -void UIElement::update(Uint32 delta) { - InputService& input = Services::getInputService(); - - if (input.mousePressed(MouseButtons::LEFT)) { - bool is_colliding = - input.mouseX() < transform.position.x + transform.size.x && - input.mouseY() < transform.position.y + transform.size.y && - input.mouseX() > transform.position.x && - input.mouseY() > transform.position.y; - - if (is_colliding) { - UIElement::focused = id; - handleOnClick(); - } - } -} - -// Set on click -void UIElement::setOnClick(std::function func) { - this->onClick = func; -} - -// Get text -std::string UIElement::getText() const { - return text; -} - -// Intermediate on click hanlder -void UIElement::handleOnClick() { - if (onClick) { - onClick(); - } -} - -} // namespace afk diff --git a/src/scene/Scene.cpp b/src/scene/Scene.cpp index b1f35b7..dad894b 100644 --- a/src/scene/Scene.cpp +++ b/src/scene/Scene.cpp @@ -10,6 +10,7 @@ */ #include "scene/Scene.h" +#include "systems/CollisionSystem.h" #include "systems/ParticleSystem.h" #include "systems/PhysicsSystem.h" #include "systems/RenderSystem.h" @@ -25,12 +26,13 @@ Scene::Scene() assets(afk::Services::getAssetService()), input(afk::Services::getInputService()), scene(afk::Services::getSceneService()), - config(afk::Services::getConfigService()), - need_sort(false) {} + config(afk::Services::getConfigService()) {} -// Internal cleanup (on switch scene) -void Scene::stopInternal() { - // entities.clear(); +// Internal update method +void Scene::update(Uint32 delta) { + systems::collisionSystem(registry); + systems::physicsSystem(registry, delta); + systems::particleSystem(registry, delta); } // Draw internal method @@ -41,10 +43,24 @@ void Scene::draw() { systems::particleRenderSystem(registry, assets); } -// Internal update method -void Scene::update(Uint32 delta) { - systems::physicsSystem(registry, delta); - systems::particleSystem(registry, delta); +// Internal cleanup (on switch scene) +void Scene::stopInternal() { + // entities.clear(); +} + +// Register a new entity +entt::entity Scene::createEntity() { + return registry.create(); +} + +// Remove an entity +void Scene::destroyEntity(entt::entity entity) { + registry.destroy(entity); +} + +// Get a reference to the registry +entt::registry& Scene::getRegistry() { + return registry; } } // namespace afk diff --git a/src/services/display/DisplayService.cpp b/src/services/display/DisplayService.cpp index 82acb2b..6b5fd66 100644 --- a/src/services/display/DisplayService.cpp +++ b/src/services/display/DisplayService.cpp @@ -17,7 +17,7 @@ #include "common/Exceptions.h" #include "scene/Scene.h" -#include "color/Color.h" +#include "common/Color.h" #include "services/Services.h" namespace afk { diff --git a/src/entities/ui/MessageBox.cpp b/src/ui/MessageBox.cpp similarity index 97% rename from src/entities/ui/MessageBox.cpp rename to src/ui/MessageBox.cpp index 58d01a3..25ca435 100644 --- a/src/entities/ui/MessageBox.cpp +++ b/src/ui/MessageBox.cpp @@ -8,7 +8,7 @@ * @copyright Copyright (c) 2021 * */ -#include "entities/ui/MessageBox.h" +#include "ui/MessageBox.h" #include "services/Services.h" From 8148c3b4128e0c5e0fee51b6a0d1fb7ea40b1c97 Mon Sep 17 00:00:00 2001 From: alegemaate Date: Fri, 22 Apr 2022 19:14:51 -0400 Subject: [PATCH 06/24] refactor: tidy code --- examples/CMakeLists.txt | 4 +- examples/ex_collision.cpp | 13 +++--- examples/ex_fps.cpp | 10 ++--- examples/ex_keyboard.cpp | 11 +++-- examples/ex_message_box.cpp | 69 +++++++++++++++++-------------- examples/ex_mouse.cpp | 6 +-- examples/ex_particles.cpp | 12 ++---- examples/ex_physics.cpp | 9 ++-- examples/ex_rotate.cpp | 6 +-- examples/ex_sprite.cpp | 3 +- include/components/components.h | 21 ++++++++++ include/components/ui.h | 17 ++++++++ include/components/ui/Button.h | 39 +++++++++++++++++ include/components/ui/Label.h | 6 +-- include/entities/Entity.h | 23 +++++++++++ include/scene/Scene.h | 20 ++++----- include/systems/CollisionSystem.h | 4 +- include/systems/ParticleSystem.h | 5 +-- include/systems/PhysicsSystem.h | 2 +- include/systems/RenderSystem.h | 2 +- include/systems/UISystem.h | 14 +++++-- src/scene/Scene.cpp | 6 +-- 22 files changed, 202 insertions(+), 100 deletions(-) create mode 100644 include/components/components.h create mode 100644 include/components/ui.h create mode 100644 include/components/ui/Button.h create mode 100644 include/entities/Entity.h diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index c183249..c6e1091 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -25,8 +25,8 @@ endif(EMSCRIPTEN) # Build examples -# ex_collision ex_ui ex_message_box -set(EXAMPLES ex_display ex_sprite ex_rotate ex_fps ex_mouse ex_physics ex_sound ex_particles ex_keyboard ex_collision) +# ex_collision ex_ui +set(EXAMPLES ex_display ex_sprite ex_rotate ex_fps ex_mouse ex_physics ex_sound ex_particles ex_keyboard ex_collision ex_message_box) foreach(EX_NAME ${EXAMPLES}) add_executable(${EX_NAME} ${CMAKE_CURRENT_LIST_DIR}/${EX_NAME}.cpp) diff --git a/examples/ex_collision.cpp b/examples/ex_collision.cpp index ffba877..78724f4 100644 --- a/examples/ex_collision.cpp +++ b/examples/ex_collision.cpp @@ -9,10 +9,9 @@ * */ #include "../include/Game.h" -#include "../include/components/Collider.h" -#include "../include/components/Sprite.h" -#include "../include/components/Transform.h" -#include "../include/components/ui/Label.h" +#include "../include/components/components.h" +#include "../include/components/ui.h" +#include "../include/entities/Entity.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" @@ -76,9 +75,9 @@ class DemoScene : public afk::Scene { void stop() { logger.log("Stopping!"); } private: - entt::entity lenna_1_id; - entt::entity lenna_2_id; - entt::entity label_id; + afk::entity lenna_1_id; + afk::entity lenna_2_id; + afk::entity label_id; }; int main(int argv, char** args) { diff --git a/examples/ex_fps.cpp b/examples/ex_fps.cpp index 76ec35b..bd442cc 100644 --- a/examples/ex_fps.cpp +++ b/examples/ex_fps.cpp @@ -11,9 +11,9 @@ #include "../include/Game.h" #include "../include/common/random.h" -#include "../include/components/Sprite.h" -#include "../include/components/Transform.h" -#include "../include/components/ui/Label.h" +#include "../include/components/components.h" +#include "../include/components/ui.h" +#include "../include/entities/Entity.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" @@ -73,8 +73,8 @@ class DemoScene : public afk::Scene { void stop() { logger.log("Stopping!"); } private: - entt::entity label_id; - entt::entity sprites[NUM_SPRITE]; + afk::entity label_id; + afk::entity sprites[NUM_SPRITE]; float iter = 0; }; diff --git a/examples/ex_keyboard.cpp b/examples/ex_keyboard.cpp index f24f7e7..fc5f7b1 100644 --- a/examples/ex_keyboard.cpp +++ b/examples/ex_keyboard.cpp @@ -9,12 +9,11 @@ * */ #include "../include/Game.h" -#include "../include/components/Sprite.h" -#include "../include/components/Transform.h" +#include "../include/components/components.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" -void characterSystem(entt::registry& registry, +void characterSystem(afk::registry& registry, afk::InputService& input, Uint32 delta) { auto view = registry.view(); @@ -52,7 +51,7 @@ class DemoScene : public afk::Scene { } void createCharacter() { - entt::entity id = createEntity(); + afk::entity id = createEntity(); createComponent(id, afk::Vec3(100, 100, 0), afk::Vec2(40, 40)); createComponent(id, "lenna"); @@ -68,7 +67,7 @@ class DemoScene : public afk::Scene { if (input.keyPressed(afk::Keys::R)) { if (character_ids.size() > 0) { - entt::entity id = character_ids.back(); + afk::entity id = character_ids.back(); destroyEntity(id); character_ids.pop_back(); } @@ -80,7 +79,7 @@ class DemoScene : public afk::Scene { void stop() { logger.log("Stopping!"); } private: - std::vector character_ids; + std::vector character_ids; }; class MainGame : public afk::Game { diff --git a/examples/ex_message_box.cpp b/examples/ex_message_box.cpp index 0d320ed..fbfbdd8 100644 --- a/examples/ex_message_box.cpp +++ b/examples/ex_message_box.cpp @@ -9,11 +9,10 @@ * */ #include "../include/Game.h" +#include "../include/components/ui.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" -#include "../include/ui/Button.h" #include "../include/ui/MessageBox.h" - class DemoScene : public afk::Scene { public: void start() { @@ -26,38 +25,44 @@ class DemoScene : public afk::Scene { assets.loadFont("freesans", "assets/freesans.ttf", 12); - afk::Button& button1 = add(*this, 10, 10, 10); - button1.setFont("freesans"); - button1.setText("Question Message"); - button1.sizeToText(); - button1.setOnClick([]() { - afk::MessageBox message_box(afk::MessageBoxType::INFO); - message_box.setTitle("Info"); - message_box.setText("Text"); - message_box.show(); - }); + auto button_1 = createEntity(); + createComponent(button_1, afk::Vec3(10, 10, 10)); + auto& button_1_button = createComponent(button_1); + button_1_button.setFont("freesans"); + button_1_button.setText("Question Message"); + // button_1_button.sizeToText(); + // button_1_button.setOnClick([]() { + // afk::MessageBox message_box(afk::MessageBoxType::INFO); + // message_box.setTitle("Info"); + // message_box.setText("Text"); + // message_box.show(); + // }); - afk::Button& button2 = add(*this, 10, 50, 10); - button2.setFont("freesans"); - button2.setText("Warning Message"); - button2.sizeToText(); - button2.setOnClick([]() { - afk::MessageBox message_box(afk::MessageBoxType::WARN); - message_box.setTitle("Warning"); - message_box.setText("Text"); - message_box.show(); - }); + auto button_2 = createEntity(); + createComponent(button_2, afk::Vec3(10, 50, 10)); + auto& button_2_button = createComponent(button_2); + button_2_button.setFont("freesans"); + button_2_button.setText("Warning Message"); + // button_2_button.sizeToText(); + // button_2_button.setOnClick([]() { + // afk::MessageBox message_box(afk::MessageBoxType::WARN); + // message_box.setTitle("Warning"); + // message_box.setText("Text"); + // message_box.show(); + // }); - afk::Button& button3 = add(*this, 10, 90, 10); - button3.setFont("freesans"); - button3.setText("Error Message"); - button3.sizeToText(); - button3.setOnClick([]() { - afk::MessageBox message_box(afk::MessageBoxType::ERROR); - message_box.setTitle("Error"); - message_box.setText("Text"); - message_box.show(); - }); + auto button_3 = createEntity(); + createComponent(button_3, afk::Vec3(10, 90, 10)); + auto& button_3_button = createComponent(button_3); + button_3_button.setFont("freesans"); + button_3_button.setText("Error Message"); + // button_3_button.sizeToText(); + // button_3_button.setOnClick([]() { + // afk::MessageBox message_box(afk::MessageBoxType::ERROR); + // message_box.setTitle("Error"); + // message_box.setText("Text"); + // message_box.show(); + // }); } void stop() { logger.log("Stopping!"); } diff --git a/examples/ex_mouse.cpp b/examples/ex_mouse.cpp index 62a280e..d826dba 100644 --- a/examples/ex_mouse.cpp +++ b/examples/ex_mouse.cpp @@ -9,8 +9,8 @@ * */ #include "../include/Game.h" -#include "../include/components/Sprite.h" -#include "../include/components/Transform.h" +#include "../include/components/components.h" +#include "../include/entities/Entity.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" @@ -50,7 +50,7 @@ class DemoScene : public afk::Scene { void stop() { logger.log("Stopping!"); } private: - entt::entity lennaId; + afk::entity lennaId; }; int main(int argv, char** args) { diff --git a/examples/ex_particles.cpp b/examples/ex_particles.cpp index 060ec65..8ce5cf7 100644 --- a/examples/ex_particles.cpp +++ b/examples/ex_particles.cpp @@ -12,14 +12,10 @@ #include "../include/common/Color.h" #include "../include/common/Vec.h" #include "../include/common/random.h" -#include "../include/components/Particle.h" -#include "../include/components/ParticleEmitter.h" -#include "../include/components/Transform.h" +#include "../include/components/components.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" -#include - class DemoScene : public afk::Scene { public: void start() { @@ -91,9 +87,9 @@ class DemoScene : public afk::Scene { void stop() { logger.log("Stopping!"); } private: - entt::entity emitter_1_id; - entt::entity emitter_2_id; - entt::entity emitter_3_id; + afk::entity emitter_1_id; + afk::entity emitter_2_id; + afk::entity emitter_3_id; }; int main(int argv, char** args) { diff --git a/examples/ex_physics.cpp b/examples/ex_physics.cpp index 068c848..d1c76d0 100644 --- a/examples/ex_physics.cpp +++ b/examples/ex_physics.cpp @@ -10,12 +10,11 @@ */ #include "../include/Game.h" #include "../include/common/Vec.h" -#include "../include/components/Physics.h" -#include "../include/components/Sprite.h" -#include "../include/components/Transform.h" +#include "../include/components/components.h" +#include "../include/entities/Entity.h" #include "../include/scene/Scene.h" -void bounceSystem(entt::registry& registry) { +void bounceSystem(afk::registry& registry) { auto view = registry.view(); for (auto [entity, transform, physics] : view.each()) { @@ -61,7 +60,7 @@ class DemoScene : public afk::Scene { void stop() { logger.log("Stopping!"); } private: - entt::entity lennaId; + afk::entity lennaId; }; int main(int argv, char** args) { diff --git a/examples/ex_rotate.cpp b/examples/ex_rotate.cpp index 7014763..f2ce7f1 100644 --- a/examples/ex_rotate.cpp +++ b/examples/ex_rotate.cpp @@ -10,8 +10,8 @@ */ #include "../include/Game.h" #include "../include/common/Vec.h" -#include "../include/components/Sprite.h" -#include "../include/components/Transform.h" +#include "../include/components/components.h" +#include "../include/entities/Entity.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" @@ -43,7 +43,7 @@ class DemoScene : public afk::Scene { void stop() { logger.log("Stopping!"); } private: - entt::entity lennaId; + afk::entity lennaId; }; int main(int argv, char** args) { diff --git a/examples/ex_sprite.cpp b/examples/ex_sprite.cpp index 9bf5e00..d3cacb1 100644 --- a/examples/ex_sprite.cpp +++ b/examples/ex_sprite.cpp @@ -10,8 +10,7 @@ */ #include "../include/Game.h" #include "../include/common/Vec.h" -#include "../include/components/Sprite.h" -#include "../include/components/Transform.h" +#include "../include/components/components.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" diff --git a/include/components/components.h b/include/components/components.h new file mode 100644 index 0000000..6b740f9 --- /dev/null +++ b/include/components/components.h @@ -0,0 +1,21 @@ +/** + * @file components.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Export all components + * @version 0.1 + * @date 2022-04-22 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef INCLUDE_COMPONENTS_COMPONENTS_H_ +#define INCLUDE_COMPONENTS_COMPONENTS_H_ + +#include "./Collider.h" +#include "./Particle.h" +#include "./ParticleEmitter.h" +#include "./Physics.h" +#include "./Sprite.h" +#include "./Transform.h" + +#endif // INCLUDE_COMPONENTS_COMPONENTS_H_ diff --git a/include/components/ui.h b/include/components/ui.h new file mode 100644 index 0000000..7ff2299 --- /dev/null +++ b/include/components/ui.h @@ -0,0 +1,17 @@ +/** + * @file ui.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Export all ui components + * @version 0.1 + * @date 2022-04-22 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef INCLUDE_COMPONENTS_UI_H_ +#define INCLUDE_COMPONENTS_UI_H_ + +#include "./ui/Button.h" +#include "./ui/Label.h" + +#endif // INCLUDE_COMPONENTS_UI_H_ diff --git a/include/components/ui/Button.h b/include/components/ui/Button.h new file mode 100644 index 0000000..e41252f --- /dev/null +++ b/include/components/ui/Button.h @@ -0,0 +1,39 @@ +/** + * @file Button.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief UI Button + * @version 0.1 + * @date 2021-03-15 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef INCLUDE_COMPONENTS_UI_BUTTON_H_ +#define INCLUDE_COMPONENTS_UI_BUTTON_H_ + +#include + +namespace afk { + +struct Button { + /// Constructor + Button() : text(""), font("") {} + + Button(const std::string& text, const std::string& font) + : text(text), font(font) {} + + /// Text of Button + std::string text; + + /// Font of label + std::string font; + + /// Setters + void setText(const std::string& text) { this->text = text; } + + void setFont(const std::string& font) { this->font = font; } +}; + +} // namespace afk + +#endif // INCLUDE_COMPONENTS_UI_BUTTON_H_ diff --git a/include/components/ui/Label.h b/include/components/ui/Label.h index fbcde84..67d31a5 100644 --- a/include/components/ui/Label.h +++ b/include/components/ui/Label.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_COMPONENTS_LABEL_H_ -#define INCLUDE_COMPONENTS_LABEL_H_ +#ifndef INCLUDE_COMPONENTS_UI_LABEL_H_ +#define INCLUDE_COMPONENTS_UI_LABEL_H_ #include @@ -36,4 +36,4 @@ struct Label { } // namespace afk -#endif // INCLUDE_COMPONENTS_LABEL_H_ +#endif // INCLUDE_COMPONENTS_UI_LABEL_H_ diff --git a/include/entities/Entity.h b/include/entities/Entity.h new file mode 100644 index 0000000..c1637a0 --- /dev/null +++ b/include/entities/Entity.h @@ -0,0 +1,23 @@ +/** + * @file Entity.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Entity identifier alias + * @version 0.1 + * @date 2022-04-22 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef INCLUDE_ENTITIES_ENTITY_H_ +#define INCLUDE_ENTITIES_ENTITY_H_ + +#include + +namespace afk { + +using entity = entt::entity; +using registry = entt::registry; + +} // namespace afk + +#endif // INCLUDE_ENTITIES_ENTITY_H_ diff --git a/include/scene/Scene.h b/include/scene/Scene.h index 96f75ac..a3f8385 100644 --- a/include/scene/Scene.h +++ b/include/scene/Scene.h @@ -11,7 +11,6 @@ #ifndef INCLUDE_SCENE_SCENE_H_ #define INCLUDE_SCENE_SCENE_H_ -#include #include #include #include @@ -20,6 +19,7 @@ #include "../common/Exceptions.h" #include "../components/Transform.h" +#include "../include/entities/Entity.h" #include "../services/Services.h" /** @@ -77,16 +77,16 @@ class Scene { /** * @brief Register a new entity * - * @return entt::entity + * @return entity */ - entt::entity createEntity(); + entity createEntity(); /** * @brief Remove an entity * * @param entity Entity to remove */ - void destroyEntity(entt::entity entity); + void destroyEntity(entity entity); /** * @brief Add a component to an entity @@ -97,7 +97,7 @@ class Scene { * @param args Arguments accepted by component */ template - T& createComponent(entt::entity id, Args&&... args) { + T& createComponent(entity id, Args&&... args) { auto& component = registry.emplace(id, std::forward(args)...); // Sort always (inefficient!) @@ -115,7 +115,7 @@ class Scene { * @param id Entity to assign to */ template - T& createComponent(entt::entity id) { + T& createComponent(entity id) { return registry.emplace(id); } @@ -127,16 +127,16 @@ class Scene { * @return T& Returned component reference */ template - T& getComponent(entt::entity id) { + T& getComponent(entity id) { return registry.get(id); } /** * @brief Get a reference to the registry * - * @return entt::registry& Registry reference + * @return registry& Registry reference */ - entt::registry& getRegistry(); + registry& getRegistry(); /// Audio service reference AudioService& audio; @@ -161,7 +161,7 @@ class Scene { private: /// Entity registry - entt::registry registry; + registry registry; }; } // namespace afk diff --git a/include/systems/CollisionSystem.h b/include/systems/CollisionSystem.h index 9879301..ceb7de1 100644 --- a/include/systems/CollisionSystem.h +++ b/include/systems/CollisionSystem.h @@ -3,7 +3,7 @@ * @author Allan Legemaate (alegemaate@gmail.com) * @brief System in charge of updating transforms * @version 0.1 - * @date 2022-04-20 + * @date 2022-04-22 * * @copyright Copyright (c) 2022 * @@ -23,7 +23,7 @@ namespace afk::systems { * @brief CollisionSystem * */ -void collisionSystem(entt::registry& registry) { +void collisionSystem(registry& registry) { auto view = registry.view(); for (auto [entity, tran, collider] : view.each()) { diff --git a/include/systems/ParticleSystem.h b/include/systems/ParticleSystem.h index 5fa7466..871926a 100644 --- a/include/systems/ParticleSystem.h +++ b/include/systems/ParticleSystem.h @@ -29,7 +29,7 @@ namespace afk::systems { * @brief ParticleSystem * */ -void particleSystem(entt::registry& registry, float delta) { +void particleSystem(registry& registry, float delta) { auto particle_view = registry.view(); int count = 0; @@ -73,8 +73,7 @@ void particleSystem(entt::registry& registry, float delta) { } } -void particleRenderSystem(entt::registry& registry, - AssetService& assetService) { +void particleRenderSystem(registry& registry, AssetService& assetService) { auto view = registry.view(); for (auto [entity, tran, particle] : view.each()) { diff --git a/include/systems/PhysicsSystem.h b/include/systems/PhysicsSystem.h index 8f0bdf7..0f6bea3 100644 --- a/include/systems/PhysicsSystem.h +++ b/include/systems/PhysicsSystem.h @@ -23,7 +23,7 @@ namespace afk::systems { * @brief PhysicsSystem * */ -void physicsSystem(entt::registry& registry, Uint32 delta) { +void physicsSystem(registry& registry, Uint32 delta) { auto view = registry.view(); const float delta_seconds = delta / 1000.0f; diff --git a/include/systems/RenderSystem.h b/include/systems/RenderSystem.h index 3dd7d1d..da6cde5 100644 --- a/include/systems/RenderSystem.h +++ b/include/systems/RenderSystem.h @@ -23,7 +23,7 @@ namespace afk::systems { * @brief RenderSystem * */ -void renderSystem(entt::registry& registry, AssetService& assetService) { +void renderSystem(registry& registry, AssetService& assetService) { auto view = registry.view(); for (auto [entity, tran, sprite] : view.each()) { diff --git a/include/systems/UISystem.h b/include/systems/UISystem.h index 3138832..700ed53 100644 --- a/include/systems/UISystem.h +++ b/include/systems/UISystem.h @@ -14,6 +14,7 @@ #include #include "components/Transform.h" +#include "components/ui/Button.h" #include "components/ui/Label.h" #include "services/assets/AssetService.h" @@ -23,13 +24,18 @@ namespace afk::systems { * @brief UISystem * */ -void uiSystem(entt::registry& registry, AssetService& assetService) { - auto view = registry.view(); - - for (auto [entity, tran, label] : view.each()) { +void uiSystem(registry& registry, AssetService& assetService) { + auto view_labels = registry.view(); + for (auto [entity, tran, label] : view_labels.each()) { auto font = assetService.getFont(label.font); font.draw(tran.position.x, tran.position.y, label.text); } + + auto view_buttons = registry.view(); + for (auto [entity, tran, button] : view_buttons.each()) { + auto font = assetService.getFont(button.font); + font.draw(tran.position.x, tran.position.y, button.text); + } } } // namespace afk::systems diff --git a/src/scene/Scene.cpp b/src/scene/Scene.cpp index dad894b..83471ca 100644 --- a/src/scene/Scene.cpp +++ b/src/scene/Scene.cpp @@ -49,17 +49,17 @@ void Scene::stopInternal() { } // Register a new entity -entt::entity Scene::createEntity() { +entity Scene::createEntity() { return registry.create(); } // Remove an entity -void Scene::destroyEntity(entt::entity entity) { +void Scene::destroyEntity(entity entity) { registry.destroy(entity); } // Get a reference to the registry -entt::registry& Scene::getRegistry() { +registry& Scene::getRegistry() { return registry; } From 8477fbd50c993b025270db2f4a713e693c7eaa4b Mon Sep 17 00:00:00 2001 From: alegemaate Date: Fri, 22 Apr 2022 19:34:33 -0400 Subject: [PATCH 07/24] fix: reinstate ex_message_box --- examples/ex_message_box.cpp | 45 ++++++++++++++------------- include/components/ui/Button.h | 23 +++++++++++++- include/services/input/InputService.h | 11 +++++++ include/systems/UISystem.h | 24 +++++++++++++- src/scene/Scene.cpp | 2 +- src/services/input/InputService.cpp | 9 ++++++ 6 files changed, 90 insertions(+), 24 deletions(-) diff --git a/examples/ex_message_box.cpp b/examples/ex_message_box.cpp index fbfbdd8..166c10a 100644 --- a/examples/ex_message_box.cpp +++ b/examples/ex_message_box.cpp @@ -26,43 +26,46 @@ class DemoScene : public afk::Scene { assets.loadFont("freesans", "assets/freesans.ttf", 12); auto button_1 = createEntity(); - createComponent(button_1, afk::Vec3(10, 10, 10)); + createComponent(button_1, afk::Vec3(10, 10, 10), + afk::Vec2(160, 20)); auto& button_1_button = createComponent(button_1); button_1_button.setFont("freesans"); button_1_button.setText("Question Message"); // button_1_button.sizeToText(); - // button_1_button.setOnClick([]() { - // afk::MessageBox message_box(afk::MessageBoxType::INFO); - // message_box.setTitle("Info"); - // message_box.setText("Text"); - // message_box.show(); - // }); + button_1_button.setOnClick([]() { + afk::MessageBox message_box(afk::MessageBoxType::INFO); + message_box.setTitle("Info"); + message_box.setText("Text"); + message_box.show(); + }); auto button_2 = createEntity(); - createComponent(button_2, afk::Vec3(10, 50, 10)); + createComponent(button_2, afk::Vec3(10, 50, 10), + afk::Vec2(160, 20)); auto& button_2_button = createComponent(button_2); button_2_button.setFont("freesans"); button_2_button.setText("Warning Message"); // button_2_button.sizeToText(); - // button_2_button.setOnClick([]() { - // afk::MessageBox message_box(afk::MessageBoxType::WARN); - // message_box.setTitle("Warning"); - // message_box.setText("Text"); - // message_box.show(); - // }); + button_2_button.setOnClick([]() { + afk::MessageBox message_box(afk::MessageBoxType::WARN); + message_box.setTitle("Warning"); + message_box.setText("Text"); + message_box.show(); + }); auto button_3 = createEntity(); - createComponent(button_3, afk::Vec3(10, 90, 10)); + createComponent(button_3, afk::Vec3(10, 90, 10), + afk::Vec2(160, 20)); auto& button_3_button = createComponent(button_3); button_3_button.setFont("freesans"); button_3_button.setText("Error Message"); // button_3_button.sizeToText(); - // button_3_button.setOnClick([]() { - // afk::MessageBox message_box(afk::MessageBoxType::ERROR); - // message_box.setTitle("Error"); - // message_box.setText("Text"); - // message_box.show(); - // }); + button_3_button.setOnClick([]() { + afk::MessageBox message_box(afk::MessageBoxType::ERROR); + message_box.setTitle("Error"); + message_box.setText("Text"); + message_box.show(); + }); } void stop() { logger.log("Stopping!"); } diff --git a/include/components/ui/Button.h b/include/components/ui/Button.h index e41252f..1dfb19f 100644 --- a/include/components/ui/Button.h +++ b/include/components/ui/Button.h @@ -11,6 +11,7 @@ #ifndef INCLUDE_COMPONENTS_UI_BUTTON_H_ #define INCLUDE_COMPONENTS_UI_BUTTON_H_ +#include #include namespace afk { @@ -28,10 +29,30 @@ struct Button { /// Font of label std::string font; - /// Setters + /// On click callback + std::function onClick; + + /** + * @brief Set the text to display on ui element + * + * @param text to display + */ void setText(const std::string& text) { this->text = text; } + /** + * @brief Set the font to use for displaying text + * + * @param font id of font to render text with + */ void setFont(const std::string& font) { this->font = font; } + + /** + * @brief Set the onClick function which will be called when element is + * clicked + * + * @param func function to assign to onClick + */ + void setOnClick(std::function func) { this->onClick = func; }; }; } // namespace afk diff --git a/include/services/input/InputService.h b/include/services/input/InputService.h index 346b98e..73762d6 100644 --- a/include/services/input/InputService.h +++ b/include/services/input/InputService.h @@ -15,6 +15,7 @@ #include #include +#include "../../common/Vec.h" #include "../Service.h" #include "JoystickState.h" #include "KeyboardState.h" @@ -136,6 +137,16 @@ class InputService : public Service { */ bool mouseDown(const MouseButtons button) const; + /** + * @brief Get whether mouse is over a given area + * + * @param position Position to check + * @param size Size of area + * + * @return Over state + */ + bool mouseOver(const Vec2 position, const Vec2 size) const; + /** * @brief Get mouse x position * diff --git a/include/systems/UISystem.h b/include/systems/UISystem.h index 700ed53..f729374 100644 --- a/include/systems/UISystem.h +++ b/include/systems/UISystem.h @@ -13,10 +13,12 @@ #include +#include "common/Color.h" #include "components/Transform.h" #include "components/ui/Button.h" #include "components/ui/Label.h" #include "services/assets/AssetService.h" +#include "services/input/InputService.h" namespace afk::systems { @@ -24,7 +26,9 @@ namespace afk::systems { * @brief UISystem * */ -void uiSystem(registry& registry, AssetService& assetService) { +void uiSystem(registry& registry, + AssetService& assetService, + InputService& inputService) { auto view_labels = registry.view(); for (auto [entity, tran, label] : view_labels.each()) { auto font = assetService.getFont(label.font); @@ -33,8 +37,26 @@ void uiSystem(registry& registry, AssetService& assetService) { auto view_buttons = registry.view(); for (auto [entity, tran, button] : view_buttons.each()) { + // Draw button background + primitives::rectfill(tran.position.x, tran.position.y, tran.size.x, + tran.size.y, color::white); + + // Draw button border + primitives::rect(tran.position.x, tran.position.y, tran.size.x, tran.size.y, + color::black); + + // Draw text auto font = assetService.getFont(button.font); font.draw(tran.position.x, tran.position.y, button.text); + + if (button.onClick) { + if (inputService.mouseDown(MouseButtons::LEFT)) { + if (inputService.mouseOver(Vec2(tran.position.x, tran.position.y), + Vec2(tran.size.x, tran.size.y))) { + button.onClick(); + } + } + } } } diff --git a/src/scene/Scene.cpp b/src/scene/Scene.cpp index 83471ca..9906d89 100644 --- a/src/scene/Scene.cpp +++ b/src/scene/Scene.cpp @@ -39,7 +39,7 @@ void Scene::update(Uint32 delta) { void Scene::draw() { // Draw systems::renderSystem(registry, assets); - systems::uiSystem(registry, assets); + systems::uiSystem(registry, assets, input); systems::particleRenderSystem(registry, assets); } diff --git a/src/services/input/InputService.cpp b/src/services/input/InputService.cpp index b45dd5f..fa61fe1 100644 --- a/src/services/input/InputService.cpp +++ b/src/services/input/InputService.cpp @@ -230,6 +230,15 @@ bool InputService::mouseDown(const MouseButtons button) const { return mouse_state.button[static_cast(button)]; } +// Get mouse button down state +bool InputService::mouseOver(const Vec2 position, const Vec2 size) const { + if (mouse_state.x < position.x || mouse_state.x > position.x + size.x || + mouse_state.y < position.y || mouse_state.y > position.y + size.y) { + return false; + } + return true; +} + // Get mouse x position int InputService::mouseX() const { return mouse_state.x; From 38b592752101c83eecc2cc904436fe5c1e9c788f Mon Sep 17 00:00:00 2001 From: alegemaate Date: Sat, 23 Apr 2022 14:21:31 -0400 Subject: [PATCH 08/24] refactor: clean up code --- .gitignore | 3 +- README.md | 2 +- examples/ex_collision.cpp | 55 ++- examples/ex_display.cpp | 7 +- examples/ex_fps.cpp | 25 +- examples/ex_keyboard.cpp | 33 +- examples/ex_message_box.cpp | 74 ++-- examples/ex_mouse.cpp | 23 +- examples/ex_particles.cpp | 43 +-- examples/ex_physics.cpp | 20 +- examples/ex_rotate.cpp | 19 +- examples/ex_sound.cpp | 7 +- examples/ex_sprite.cpp | 3 +- examples/ex_ui.cpp | 26 +- include/Game.h | 13 +- include/assets/Font.h | 30 +- include/assets/Sound.h | 20 +- include/assets/Stream.h | 8 +- include/assets/Texture.h | 30 +- include/common/Color.h | 44 +-- include/common/Exceptions.h | 14 +- include/common/Vec.h | 6 +- include/common/math.h | 14 +- include/common/random.h | 10 +- include/common/str.h | 12 +- include/components/Collider.h | 6 +- include/components/Particle.h | 74 ++-- include/components/ParticleEmitter.h | 9 +- include/components/Physics.h | 10 +- include/components/Sprite.h | 6 +- include/components/Transform.h | 6 +- include/components/components.h | 6 +- include/components/ui.h | 6 +- include/components/ui/Button.h | 17 +- include/components/ui/Label.h | 13 +- include/entities/Entity.h | 10 +- include/primitives/Primitives.h | 39 +- include/scene/Scene.h | 26 +- include/services/Service.h | 8 +- include/services/Services.h | 22 +- include/services/assets/AssetService.h | 20 +- include/services/audio/AudioService.h | 18 +- include/services/config/ConfigService.h | 26 +- include/services/display/DisplayService.h | 78 ++-- include/services/events/EventQueue.h | 16 +- include/services/input/InputService.h | 54 +-- include/services/input/JoystickCodes.h | 42 +- include/services/input/JoystickState.h | 14 +- include/services/input/KeyboardKeys.h | 360 +++++++++--------- include/services/input/KeyboardState.h | 28 +- include/services/input/MouseState.h | 42 +- .../services/logging/DebugLoggingService.h | 6 +- include/services/logging/LoggingService.h | 8 +- include/services/scene/SceneService.h | 26 +- include/systems/CollisionSystem.h | 38 +- include/systems/ParticleSystem.h | 107 +----- include/systems/PhysicsSystem.h | 25 +- include/systems/RenderSystem.h | 19 +- include/systems/UISystem.h | 47 +-- include/ui/MessageBox.h | 12 +- src/Game.cpp | 15 +- src/assets/Font.cpp | 37 +- src/assets/Sound.cpp | 22 +- src/assets/Stream.cpp | 8 +- src/assets/Texture.cpp | 31 +- src/common/Color.cpp | 19 +- src/common/random.cpp | 10 +- src/primitives/Primitives.cpp | 16 +- src/scene/Scene.cpp | 8 +- src/services/Services.cpp | 34 +- src/services/assets/AssetService.cpp | 39 +- src/services/config/ConfigService.cpp | 24 +- src/services/display/DisplayService.cpp | 139 ++++--- src/services/events/EventQueue.cpp | 28 +- src/services/input/InputService.cpp | 112 +++--- src/services/scene/SceneService.cpp | 46 +-- src/systems/CollisionSystem.cpp | 44 +++ src/systems/ParticleSystem.cpp | 115 ++++++ src/systems/PhysicsSystem.cpp | 35 ++ src/systems/RenderSystem.cpp | 31 ++ src/systems/UISystem.cpp | 58 +++ src/ui/MessageBox.cpp | 13 +- 82 files changed, 1367 insertions(+), 1302 deletions(-) create mode 100644 src/systems/CollisionSystem.cpp create mode 100644 src/systems/ParticleSystem.cpp create mode 100644 src/systems/PhysicsSystem.cpp create mode 100644 src/systems/RenderSystem.cpp create mode 100644 src/systems/UISystem.cpp diff --git a/.gitignore b/.gitignore index cc55d64..184ef93 100644 --- a/.gitignore +++ b/.gitignore @@ -51,4 +51,5 @@ docs lib compile_commands.json .idea -build \ No newline at end of file +build +Testing/ \ No newline at end of file diff --git a/README.md b/README.md index 3b040d8..628b626 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Allans FrameworK +# Allan's FrameworK ![Build Windows](https://github.com/AdsGames/AfkLib/workflows/Build%20Windows/badge.svg) ![Build Linux](https://github.com/AdsGames/AfkLib/workflows/Build%20Linux/badge.svg) diff --git a/examples/ex_collision.cpp b/examples/ex_collision.cpp index 78724f4..e6973f6 100644 --- a/examples/ex_collision.cpp +++ b/examples/ex_collision.cpp @@ -13,56 +13,55 @@ #include "../include/components/ui.h" #include "../include/entities/Entity.h" #include "../include/scene/Scene.h" -#include "../include/services/Services.h" class DemoScene : public afk::Scene { public: - void start() { + void start() override { logger.log("Starting!"); display.setWindowSize(512, 512); display.setBufferSize(512, 512); - display.setMode(afk::DisplayMode::WINDOWED); + display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_collision"); assets.loadImage("lenna", "assets/lenna.png"); assets.loadFont("freesans", "assets/freesans.ttf", 12); - lenna_1_id = createEntity(); - createComponent(lenna_1_id, afk::Vec3(10, 10, 0), + lennaEntity1 = createEntity(); + createComponent(lennaEntity1, afk::Vec3(10, 10, 0), afk::Vec2(40, 40)); - createComponent(lenna_1_id, "lenna"); - createComponent(lenna_1_id); + createComponent(lennaEntity1, "lenna"); + createComponent(lennaEntity1); - lenna_2_id = createEntity(); - createComponent(lenna_2_id, afk::Vec3(10, 80, 0), + lennaEntity2 = createEntity(); + createComponent(lennaEntity2, afk::Vec3(10, 80, 0), afk::Vec2(40, 40)); - createComponent(lenna_2_id, "lenna"); - createComponent(lenna_2_id); + createComponent(lennaEntity2, "lenna"); + createComponent(lennaEntity2); - label_id = createEntity(); - createComponent(label_id, afk::Vec3(10, 5, 0)); - auto& label = createComponent(label_id); + labelEntity = createEntity(); + createComponent(labelEntity, afk::Vec3(10, 5, 0)); + auto& label = createComponent(labelEntity); label.setText("FPS"); label.setFont("freesans"); } - void update(Uint32 delta) { - auto& label = getComponent(label_id); - auto& lenna_1 = getComponent(lenna_1_id); - auto& lenna_2 = getComponent(lenna_2_id); + void update(uint32_t delta) override { + auto& label = getComponent(labelEntity); + auto& lennaTransform1 = getComponent(lennaEntity1); + auto& lennaTransform2 = getComponent(lennaEntity2); - if (input.mouseDown(afk::MouseButtons::LEFT)) { - lenna_1.position.x = input.mouseX(); - lenna_1.position.y = input.mouseY(); + if (input.mouseDown(afk::MouseButtons::Left)) { + lennaTransform1.position.x = input.mouseX(); + lennaTransform1.position.y = input.mouseY(); } - if (input.mouseDown(afk::MouseButtons::RIGHT)) { - lenna_2.position.x = input.mouseX(); - lenna_2.position.y = input.mouseY(); + if (input.mouseDown(afk::MouseButtons::Right)) { + lennaTransform2.position.x = input.mouseX(); + lennaTransform2.position.y = input.mouseY(); } - auto& collider = getComponent(lenna_1_id); + auto& collider = getComponent(lennaEntity1); if (collider.colliding) { label.setText("Colliding!"); } else { @@ -75,9 +74,9 @@ class DemoScene : public afk::Scene { void stop() { logger.log("Stopping!"); } private: - afk::entity lenna_1_id; - afk::entity lenna_2_id; - afk::entity label_id; + afk::Entity lennaEntity1; + afk::Entity lennaEntity2; + afk::Entity labelEntity; }; int main(int argv, char** args) { diff --git a/examples/ex_display.cpp b/examples/ex_display.cpp index bf9d180..79120be 100644 --- a/examples/ex_display.cpp +++ b/examples/ex_display.cpp @@ -10,20 +10,19 @@ */ #include "../include/Game.h" #include "../include/scene/Scene.h" -#include "../include/services/Services.h" class DemoScene : public afk::Scene { public: - void start() { + void start() override { logger.log("Starting!"); display.setWindowSize(100, 100); display.setBufferSize(100, 100); - display.setMode(afk::DisplayMode::WINDOWED); + display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_display"); } - void stop() { logger.log("Stopping!"); } + void stop() override { logger.log("Stopping!"); } }; int main(int argv, char** args) { diff --git a/examples/ex_fps.cpp b/examples/ex_fps.cpp index bd442cc..86f979b 100644 --- a/examples/ex_fps.cpp +++ b/examples/ex_fps.cpp @@ -15,7 +15,6 @@ #include "../include/components/ui.h" #include "../include/entities/Entity.h" #include "../include/scene/Scene.h" -#include "../include/services/Services.h" const int NUM_SPRITE = 100; const int SCREEN_H = 400; @@ -25,41 +24,41 @@ const int SPRITE_SIZE = 20; class DemoScene : public afk::Scene { public: - void start() { + void start() override { logger.log("Starting!"); display.setWindowSize(SCREEN_W, SCREEN_H); display.setBufferSize(SCREEN_W, SCREEN_H); - display.setMode(afk::DisplayMode::WINDOWED); + display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_fps"); assets.loadFont("freesans", "assets/freesans.ttf", 64); assets.loadImage("lenna", "assets/lenna.png"); - label_id = createEntity(); - createComponent(label_id, afk::Vec3(10, 5, 0)); - auto& label = createComponent(label_id); + labelEntity = createEntity(); + createComponent(labelEntity, afk::Vec3(10, 5, 0)); + auto& label = createComponent(labelEntity); label.setText("FPS"); label.setFont("freesans"); - for (unsigned int i = 0; i < NUM_SPRITE; i++) { + for (auto& sprite : sprites) { auto entity = createEntity(); createComponent(entity, "lenna"); auto& transform = createComponent(entity); transform.size.x = SPRITE_SIZE; transform.size.y = SPRITE_SIZE; - sprites[i] = entity; + sprite = entity; } } - void update(Uint32 delta) { + void update(uint32_t delta) override { Scene::update(delta); iter += static_cast(delta) / 10.0f; int fps = display.getFps(); - auto& label = getComponent(label_id); + auto& label = getComponent(labelEntity); label.setText(std::to_string(fps)); for (unsigned int i = 0; i < NUM_SPRITE; i++) { @@ -70,11 +69,11 @@ class DemoScene : public afk::Scene { } } - void stop() { logger.log("Stopping!"); } + void stop() override { logger.log("Stopping!"); } private: - afk::entity label_id; - afk::entity sprites[NUM_SPRITE]; + afk::Entity labelEntity; + afk::Entity sprites[NUM_SPRITE]; float iter = 0; }; diff --git a/examples/ex_keyboard.cpp b/examples/ex_keyboard.cpp index fc5f7b1..055828e 100644 --- a/examples/ex_keyboard.cpp +++ b/examples/ex_keyboard.cpp @@ -11,25 +11,24 @@ #include "../include/Game.h" #include "../include/components/components.h" #include "../include/scene/Scene.h" -#include "../include/services/Services.h" -void characterSystem(afk::registry& registry, +void characterSystem(afk::Registry& registry, afk::InputService& input, - Uint32 delta) { + uint32_t delta) { auto view = registry.view(); for (auto [entity, transform] : view.each()) { float speed = delta / 10.0f; - if (input.keyDown(afk::Keys::UP)) { + if (input.keyDown(afk::Keys::Up)) { transform.position.y -= speed; } - if (input.keyDown(afk::Keys::DOWN)) { + if (input.keyDown(afk::Keys::Down)) { transform.position.y += speed; } - if (input.keyDown(afk::Keys::LEFT)) { + if (input.keyDown(afk::Keys::Left)) { transform.position.x -= speed; } - if (input.keyDown(afk::Keys::RIGHT)) { + if (input.keyDown(afk::Keys::Right)) { transform.position.x += speed; } } @@ -37,12 +36,12 @@ void characterSystem(afk::registry& registry, class DemoScene : public afk::Scene { public: - void start() { + void start() override { logger.log("Starting!"); display.setWindowSize(512, 512); display.setBufferSize(512, 512); - display.setMode(afk::DisplayMode::WINDOWED); + display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_keyboard"); assets.loadImage("lenna", "assets/lenna.png"); @@ -51,14 +50,14 @@ class DemoScene : public afk::Scene { } void createCharacter() { - afk::entity id = createEntity(); + afk::Entity id = createEntity(); createComponent(id, afk::Vec3(100, 100, 0), afk::Vec2(40, 40)); createComponent(id, "lenna"); - character_ids.push_back(id); + entityIds.push_back(id); } - void update(Uint32 delta) override { + void update(uint32_t delta) override { Scene::update(delta); if (input.keyPressed(afk::Keys::A)) { @@ -66,20 +65,20 @@ class DemoScene : public afk::Scene { } if (input.keyPressed(afk::Keys::R)) { - if (character_ids.size() > 0) { - afk::entity id = character_ids.back(); + if (entityIds.size() > 0) { + afk::Entity id = entityIds.back(); destroyEntity(id); - character_ids.pop_back(); + entityIds.pop_back(); } } characterSystem(getRegistry(), input, delta); } - void stop() { logger.log("Stopping!"); } + void stop() override { logger.log("Stopping!"); } private: - std::vector character_ids; + std::vector entityIds; }; class MainGame : public afk::Game { diff --git a/examples/ex_message_box.cpp b/examples/ex_message_box.cpp index 166c10a..7de673e 100644 --- a/examples/ex_message_box.cpp +++ b/examples/ex_message_box.cpp @@ -11,64 +11,64 @@ #include "../include/Game.h" #include "../include/components/ui.h" #include "../include/scene/Scene.h" -#include "../include/services/Services.h" #include "../include/ui/MessageBox.h" + class DemoScene : public afk::Scene { public: - void start() { + void start() override { logger.log("Starting!"); display.setWindowSize(256, 256); display.setBufferSize(256, 256); - display.setMode(afk::DisplayMode::WINDOWED); + display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_message_box"); assets.loadFont("freesans", "assets/freesans.ttf", 12); - auto button_1 = createEntity(); - createComponent(button_1, afk::Vec3(10, 10, 10), + auto buttonEntity1 = createEntity(); + createComponent(buttonEntity1, afk::Vec3(10, 10, 10), afk::Vec2(160, 20)); - auto& button_1_button = createComponent(button_1); - button_1_button.setFont("freesans"); - button_1_button.setText("Question Message"); - // button_1_button.sizeToText(); - button_1_button.setOnClick([]() { - afk::MessageBox message_box(afk::MessageBoxType::INFO); - message_box.setTitle("Info"); - message_box.setText("Text"); - message_box.show(); + auto& button1 = createComponent(buttonEntity1); + button1.setFont("freesans"); + button1.setText("Question Message"); + // button1.sizeToText(); + button1.setOnClick([]() { + afk::MessageBox messageBox(afk::MessageBoxType::Info); + messageBox.setTitle("Info"); + messageBox.setText("Text"); + messageBox.show(); }); - auto button_2 = createEntity(); - createComponent(button_2, afk::Vec3(10, 50, 10), + auto buttonEntity2 = createEntity(); + createComponent(buttonEntity2, afk::Vec3(10, 50, 10), afk::Vec2(160, 20)); - auto& button_2_button = createComponent(button_2); - button_2_button.setFont("freesans"); - button_2_button.setText("Warning Message"); - // button_2_button.sizeToText(); - button_2_button.setOnClick([]() { - afk::MessageBox message_box(afk::MessageBoxType::WARN); - message_box.setTitle("Warning"); - message_box.setText("Text"); - message_box.show(); + auto& button2 = createComponent(buttonEntity2); + button2.setFont("freesans"); + button2.setText("Warning Message"); + // button2.sizeToText(); + button2.setOnClick([]() { + afk::MessageBox messageBox(afk::MessageBoxType::Warn); + messageBox.setTitle("Warning"); + messageBox.setText("Text"); + messageBox.show(); }); - auto button_3 = createEntity(); - createComponent(button_3, afk::Vec3(10, 90, 10), + auto buttonEntity3 = createEntity(); + createComponent(buttonEntity3, afk::Vec3(10, 90, 10), afk::Vec2(160, 20)); - auto& button_3_button = createComponent(button_3); - button_3_button.setFont("freesans"); - button_3_button.setText("Error Message"); - // button_3_button.sizeToText(); - button_3_button.setOnClick([]() { - afk::MessageBox message_box(afk::MessageBoxType::ERROR); - message_box.setTitle("Error"); - message_box.setText("Text"); - message_box.show(); + auto& button3 = createComponent(buttonEntity3); + button3.setFont("freesans"); + button3.setText("Error Message"); + // button3.sizeToText(); + button3.setOnClick([]() { + afk::MessageBox messageBox(afk::MessageBoxType::Error); + messageBox.setTitle("Error"); + messageBox.setText("Text"); + messageBox.show(); }); } - void stop() { logger.log("Stopping!"); } + void stop() override { logger.log("Stopping!"); } }; class MainGame : public afk::Game { diff --git a/examples/ex_mouse.cpp b/examples/ex_mouse.cpp index d826dba..e432785 100644 --- a/examples/ex_mouse.cpp +++ b/examples/ex_mouse.cpp @@ -12,45 +12,44 @@ #include "../include/components/components.h" #include "../include/entities/Entity.h" #include "../include/scene/Scene.h" -#include "../include/services/Services.h" class DemoScene : public afk::Scene { public: - void start() { + void start() override { logger.log("Starting!"); display.setWindowSize(512, 512); display.setBufferSize(512, 512); - display.setMode(afk::DisplayMode::WINDOWED); + display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_mouse"); assets.loadImage("lenna", "assets/lenna.png"); - lennaId = createEntity(); - createComponent(lennaId, "lenna"); - createComponent(lennaId, afk::Vec3(100, 100, 0), + lennaEntity = createEntity(); + createComponent(lennaEntity, "lenna"); + createComponent(lennaEntity, afk::Vec3(100, 100, 0), afk::Vec2(30, 30)); } - void update(Uint32 delta) { + void update(uint32_t delta) override { Scene::update(delta); - auto& transform = getComponent(lennaId); + auto& transform = getComponent(lennaEntity); - if (input.mouseDown(afk::MouseButtons::LEFT)) { + if (input.mouseDown(afk::MouseButtons::Left)) { transform.position.x = input.mouseX(); transform.position.y = input.mouseY(); } - if (input.mouseDown(afk::MouseButtons::RIGHT)) { + if (input.mouseDown(afk::MouseButtons::Right)) { transform.size.x = input.mouseX(); transform.size.y = input.mouseY(); } } - void stop() { logger.log("Stopping!"); } + void stop() override { logger.log("Stopping!"); } private: - afk::entity lennaId; + afk::Entity lennaEntity; }; int main(int argv, char** args) { diff --git a/examples/ex_particles.cpp b/examples/ex_particles.cpp index 8ce5cf7..1faf9dc 100644 --- a/examples/ex_particles.cpp +++ b/examples/ex_particles.cpp @@ -14,7 +14,6 @@ #include "../include/common/random.h" #include "../include/components/components.h" #include "../include/scene/Scene.h" -#include "../include/services/Services.h" class DemoScene : public afk::Scene { public: @@ -23,20 +22,20 @@ class DemoScene : public afk::Scene { display.setWindowSize(512, 512); display.setBufferSize(512, 512); - display.setMode(afk::DisplayMode::WINDOWED); + display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_particles"); display.setBackgroundColor(afk::color::black); assets.loadImage("fuzzball", "assets/fuzzball.png"); - emitter_1_id = createEntity(); - auto& emitter_1 = createComponent(emitter_1_id, 10); - createComponent(emitter_1_id, afk::Vec3(256, 256, 0), + emitterEntity1 = createEntity(); + auto& emitter1 = createComponent(emitterEntity1, 10); + createComponent(emitterEntity1, afk::Vec3(256, 256, 0), afk::Vec2(30, 30)); for (int i = 0; i < 100; i++) { - auto& [particle, physics] = emitter_1.addParticle(); - particle.setType(afk::ParticleType::SQUARE); + auto& [particle, physics] = emitter1.addParticle(); + particle.setType(afk::ParticleType::Square); particle.setLifespan(afk::random::randomInt(100, 1000)); particle.setSize(10.0f, 3.0f); particle.setColor(afk::color::rgb(128, 22, 22), @@ -46,14 +45,14 @@ class DemoScene : public afk::Scene { physics.setAcceleration(0, 2.0f); } - emitter_2_id = createEntity(); - auto& emitter_2 = createComponent(emitter_2_id, 10); - createComponent(emitter_2_id, afk::Vec3(128, 256, 0), + emitterEntity2 = createEntity(); + auto& emitter2 = createComponent(emitterEntity2, 10); + createComponent(emitterEntity2, afk::Vec3(128, 256, 0), afk::Vec2(1, 1)); for (int i = 0; i < 100; i++) { - auto& [particle, physics] = emitter_2.addParticle(); - particle.setType(afk::ParticleType::CIRCLE); + auto& [particle, physics] = emitter2.addParticle(); + particle.setType(afk::ParticleType::Circle); particle.setLifespan(afk::random::randomInt(1000, 2000)); particle.setSize(3.0f, 2.0f); particle.setColor(afk::color::blue, afk::color::white); @@ -61,14 +60,14 @@ class DemoScene : public afk::Scene { physics.setAcceleration(0, 200.0f); } - emitter_3_id = createEntity(); - auto& emitter_3 = createComponent(emitter_3_id, 10); - createComponent(emitter_3_id, afk::Vec3(384, 256, 0), + emitterEntity3 = createEntity(); + auto& emitter3 = createComponent(emitterEntity3, 10); + createComponent(emitterEntity3, afk::Vec3(384, 256, 0), afk::Vec2(5, 5)); for (int i = 0; i < 400; i++) { - auto& [particle, physics] = emitter_3.addParticle(); - particle.setType(afk::ParticleType::IMAGE); + auto& [particle, physics] = emitter3.addParticle(); + particle.setType(afk::ParticleType::Image); particle.setLifespan(afk::random::randomInt(800, 1500)); particle.setSize(16.0f, 20.0f); particle.setTexture("fuzzball"); @@ -76,10 +75,10 @@ class DemoScene : public afk::Scene { } } - void update(Uint32 delta) { + void update(uint32_t delta) { Scene::update(delta); - auto& smoke_transform = getComponent(emitter_3_id); + auto& smoke_transform = getComponent(emitterEntity3); smoke_transform.position.x = input.mouseX(); smoke_transform.position.y = input.mouseY(); } @@ -87,9 +86,9 @@ class DemoScene : public afk::Scene { void stop() { logger.log("Stopping!"); } private: - afk::entity emitter_1_id; - afk::entity emitter_2_id; - afk::entity emitter_3_id; + afk::Entity emitterEntity1; + afk::Entity emitterEntity2; + afk::Entity emitterEntity3; }; int main(int argv, char** args) { diff --git a/examples/ex_physics.cpp b/examples/ex_physics.cpp index d1c76d0..5035d35 100644 --- a/examples/ex_physics.cpp +++ b/examples/ex_physics.cpp @@ -14,7 +14,7 @@ #include "../include/entities/Entity.h" #include "../include/scene/Scene.h" -void bounceSystem(afk::registry& registry) { +void bounceSystem(afk::Registry& registry) { auto view = registry.view(); for (auto [entity, transform, physics] : view.each()) { @@ -35,32 +35,32 @@ void bounceSystem(afk::registry& registry) { class DemoScene : public afk::Scene { public: - void start() { + void start() override { logger.log("Starting!"); display.setWindowSize(512, 512); display.setBufferSize(512, 512); - display.setMode(afk::DisplayMode::WINDOWED); + display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_physics"); assets.loadImage("lenna", "assets/lenna.png"); - lennaId = createEntity(); - createComponent(lennaId, "lenna"); - createComponent(lennaId, afk::Vec3(0, 0, 0), + lennaEntity = createEntity(); + createComponent(lennaEntity, "lenna"); + createComponent(lennaEntity, afk::Vec3(0, 0, 0), afk::Vec2(40, 40)); - createComponent(lennaId, afk::Vec2(100.0f, 400.0f)); + createComponent(lennaEntity, afk::Vec2(100.0f, 400.0f)); } - void update(Uint32 delta) { + void update(uint32_t delta) override { Scene::update(delta); bounceSystem(getRegistry()); } - void stop() { logger.log("Stopping!"); } + void stop() override { logger.log("Stopping!"); } private: - afk::entity lennaId; + afk::Entity lennaEntity; }; int main(int argv, char** args) { diff --git a/examples/ex_rotate.cpp b/examples/ex_rotate.cpp index f2ce7f1..bc729a6 100644 --- a/examples/ex_rotate.cpp +++ b/examples/ex_rotate.cpp @@ -13,37 +13,36 @@ #include "../include/components/components.h" #include "../include/entities/Entity.h" #include "../include/scene/Scene.h" -#include "../include/services/Services.h" class DemoScene : public afk::Scene { public: - void start() { + void start() override { logger.log("Starting!"); display.setWindowSize(512, 512); display.setBufferSize(512, 512); - display.setMode(afk::DisplayMode::WINDOWED); + display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_sprite"); assets.loadImage("lenna", "assets/lenna.png"); - lennaId = createEntity(); - createComponent(lennaId, "lenna"); - createComponent(lennaId, afk::Vec3(156, 156, 0), + lennaEntity = createEntity(); + createComponent(lennaEntity, "lenna"); + createComponent(lennaEntity, afk::Vec3(156, 156, 0), afk::Vec2(200, 200)); } - void update(Uint32 delta) { + void update(uint32_t delta) override { Scene::update(delta); - auto& transform = getComponent(lennaId); + auto& transform = getComponent(lennaEntity); transform.angle += delta / 10.0f; } - void stop() { logger.log("Stopping!"); } + void stop() override { logger.log("Stopping!"); } private: - afk::entity lennaId; + afk::Entity lennaEntity; }; int main(int argv, char** args) { diff --git a/examples/ex_sound.cpp b/examples/ex_sound.cpp index af537d7..df2d70c 100644 --- a/examples/ex_sound.cpp +++ b/examples/ex_sound.cpp @@ -10,7 +10,6 @@ */ #include "../include/Game.h" #include "../include/scene/Scene.h" -#include "../include/services/Services.h" class DemoScene : public afk::Scene { public: @@ -18,15 +17,15 @@ class DemoScene : public afk::Scene { logger.log("Starting!"); display.setWindowSize(512, 512); display.setBufferSize(512, 512); - display.setMode(afk::DisplayMode::WINDOWED); + display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_mouse"); assets.loadAudio("win", "assets/win.wav"); } - void update(Uint32 delta) { + void update(uint32_t delta) { Scene::update(delta); - if (input.mousePressed(afk::MouseButtons::LEFT)) { + if (input.mousePressed(afk::MouseButtons::Left)) { audio.playSound("win", 1.0f, 0.0f, 1.0f, false); } } diff --git a/examples/ex_sprite.cpp b/examples/ex_sprite.cpp index d3cacb1..43cda24 100644 --- a/examples/ex_sprite.cpp +++ b/examples/ex_sprite.cpp @@ -12,7 +12,6 @@ #include "../include/common/Vec.h" #include "../include/components/components.h" #include "../include/scene/Scene.h" -#include "../include/services/Services.h" class DemoScene : public afk::Scene { public: @@ -21,7 +20,7 @@ class DemoScene : public afk::Scene { display.setWindowSize(512, 512); display.setBufferSize(512, 512); - display.setMode(afk::DisplayMode::WINDOWED); + display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_sprite"); assets.loadImage("lenna", "assets/lenna.png"); diff --git a/examples/ex_ui.cpp b/examples/ex_ui.cpp index 2d88bf3..955b061 100644 --- a/examples/ex_ui.cpp +++ b/examples/ex_ui.cpp @@ -36,24 +36,24 @@ class DemoScene : public afk::Scene { button.setFont("freesans"); button.sizeToText(); button.setOnClick([]() { - afk::MessageBox message_box(afk::MessageBoxType::INFO); - message_box.setTitle("Nice"); - message_box.setText("You Clicked\nThe button"); - message_box.show(); + afk::MessageBox messsageBox(afk::MessageBoxType::INFO); + messsageBox.setTitle("Nice"); + messsageBox.setText("You Clicked\nThe button"); + messsageBox.show(); }); afk::Checkbox& checkbox = add(*this, 10, 40); checkbox.setText("CHECK ME"); checkbox.setFont("freesans"); checkbox.setOnCheck([](const bool checked) { - afk::MessageBox message_box(afk::MessageBoxType::INFO); - message_box.setTitle("Nice"); + afk::MessageBox messsageBox(afk::MessageBoxType::INFO); + messsageBox.setTitle("Nice"); if (checked) { - message_box.setText("The checkbox is checked"); + messsageBox.setText("The checkbox is checked"); } else { - message_box.setText("The checkbox is unchecked"); + messsageBox.setText("The checkbox is unchecked"); } - message_box.show(); + messsageBox.show(); }); afk::Label& label = add(*this, 10, 70); @@ -69,10 +69,10 @@ class DemoScene : public afk::Scene { image.transform.size.x = 20; image.transform.size.y = 20; image.setOnClick([]() { - afk::MessageBox message_box(afk::MessageBoxType::INFO); - message_box.setTitle("Nice"); - message_box.setText("Clicked the image"); - message_box.show(); + afk::MessageBox messsageBox(afk::MessageBoxType::INFO); + messsageBox.setTitle("Nice"); + messsageBox.setText("Clicked the image"); + messsageBox.show(); }); } diff --git a/include/Game.h b/include/Game.h index 64e385f..90659ea 100644 --- a/include/Game.h +++ b/include/Game.h @@ -8,9 +8,10 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_GAME_H_ -#define INCLUDE_GAME_H_ +#ifndef AFK_GAME_H +#define AFK_GAME_H +#include #include #include "services/Service.h" @@ -40,21 +41,21 @@ class Game : public Service { * * @return name */ - std::string getName() const; + std::string getName() const override; /** * @brief Starts the main game loop * * @param scene_id Initial scene to start with */ - void start(); + void start() const; /** * @brief Notify about changes in queue * * @param ev event to be processed */ - void notify(const SDL_Event& ev); + void notify(const SDL_Event& ev) override; private: /** @@ -69,4 +70,4 @@ class Game : public Service { } // namespace afk -#endif // INCLUDE_GAME_H_ +#endif // AFK_GAME_H diff --git a/include/assets/Font.h b/include/assets/Font.h index e24f5b8..7481286 100644 --- a/include/assets/Font.h +++ b/include/assets/Font.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_ASSETS_FONT_H_ -#define INCLUDE_ASSETS_FONT_H_ +#ifndef AFK_FONT_H +#define AFK_FONT_H #include #include @@ -18,7 +18,7 @@ namespace afk { -enum class TextAlign { LEFT, RIGHT, CENTER }; +enum class TextAlign { Left, Right, Center }; /** * @brief Easy interface to interact with SDL fonts @@ -38,7 +38,7 @@ class Font { * @param size Size of font to load * @throws FileIOException If font can not be found at path */ - Font(const std::string& path, const int size); + Font(const std::string& path, int size); /** * @brief Load and assign font from given path @@ -47,7 +47,7 @@ class Font { * @param size Size of font to load * @throws FileIOException If font can not be found at path */ - void load(const std::string& path, const int size); + void load(const std::string& path, int size); /** * @brief Draw font at position @@ -58,11 +58,11 @@ class Font { * @param colour colour to colour text * @param align Text alignment, defaults to left */ - void draw(const int x, - const int y, + void draw(int x, + int y, const std::string& text, - const color::Color colour = color::black, - const TextAlign align = TextAlign::LEFT); + color::Color colour = color::black, + TextAlign align = TextAlign::Left); /** * @brief Get the height of the font @@ -84,7 +84,7 @@ class Font { * * @return Size of font loaded */ - int getSize(); + int getSize() const; /** * @brief Check if font has been loaded @@ -103,13 +103,13 @@ class Font { * @return TTF_Font* File that has been loaded * @throws FileIOException If font can not be found at path */ - static TTF_Font* loadFont(const std::string& path, const int size); + static TTF_Font* loadFont(const std::string& path, int size); /// Pointer to referenced font TTF_Font* font; /// Size of font - int font_size; + int fontSize; /** * @brief Helper for rendering text @@ -120,10 +120,10 @@ class Font { * @return SDL_Texture* New texture containing string */ SDL_Texture* renderText(SDL_Renderer* renderer, - const std::string text, - const color::Color colour); + const std::string& text, + color::Color colour); }; } // namespace afk -#endif // INCLUDE_ASSETS_FONT_H_ +#endif // AFK_FONT_H diff --git a/include/assets/Sound.h b/include/assets/Sound.h index 21db98a..540da90 100644 --- a/include/assets/Sound.h +++ b/include/assets/Sound.h @@ -10,10 +10,12 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_ASSETS_SOUND_H_ -#define INCLUDE_ASSETS_SOUND_H_ +#ifndef AFK_SOUND_H +#define AFK_SOUND_H +#include #include +#include #include namespace afk { @@ -54,10 +56,10 @@ class Sound { * @param speed Speed (unused) * @param loop Loop mode */ - void play(const float gain = 1.0f, - const float pan = 0.0f, - const float speed = 1.0f, - const bool loop = false); + void play(float gain = 1.0f, + float pan = 0.0f, + float speed = 1.0f, + bool loop = false); private: /** @@ -73,12 +75,12 @@ class Sound { Mix_Chunk* sample; /// Allocated channel - Uint32 channel; + int32_t channel; /// Current number of channels - static Uint32 channel_counter; + static uint32_t channelCounter; }; } // namespace afk -#endif // INCLUDE_ASSETS_SOUND_H_ +#endif // AFK_SOUND_H diff --git a/include/assets/Stream.h b/include/assets/Stream.h index 80bd6ff..67c6bb9 100644 --- a/include/assets/Stream.h +++ b/include/assets/Stream.h @@ -9,8 +9,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_ASSETS_STREAM_H_ -#define INCLUDE_ASSETS_STREAM_H_ +#ifndef AFK_STREAM_H +#define AFK_STREAM_H #include #include @@ -43,7 +43,7 @@ class Stream { * * @param loop Loop mode */ - void play(const bool loop = false); + void play(bool loop = false); /** * @brief Stop this instance of the stream from playing @@ -82,4 +82,4 @@ class Stream { } // namespace afk -#endif // INCLUDE_ASSETS_STREAM_H_ +#endif // AFK_STREAM_H diff --git a/include/assets/Texture.h b/include/assets/Texture.h index 87e03b5..4c9ed61 100644 --- a/include/assets/Texture.h +++ b/include/assets/Texture.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_ASSETS_TEXTURE_H_ -#define INCLUDE_ASSETS_TEXTURE_H_ +#ifndef AFK_TEXTURE_H +#define AFK_TEXTURE_H #include #include @@ -23,9 +23,9 @@ namespace afk { * */ enum class TextureDrawMode { - DEFAULT = 0, - FLIP_H = 2, - FLIP_V = 1, + Default = 0, + FlipH = 2, + FlipV = 1, }; /** @@ -62,7 +62,7 @@ class Texture { * @param width Width in pixels * @param height Height in pixels */ - void create(const int width, const int height); + void create(int width, int height); /** * @brief Draw bitmap to screen @@ -71,7 +71,7 @@ class Texture { * @param y Y position to draw to * @see drawScaled */ - void draw(const int x, const int y) const; + void draw(int x, int y) const; /** * @brief Draw scaled texture to screen @@ -81,14 +81,14 @@ class Texture { * @param width Width to scale to * @param height Height to scale to * @param angle Rotation of draw - * @param mode Optinal draw mode + * @param mode Optional draw mode */ - void drawEx(const int x, - const int y, - const int width, - const int height, - const float angle = 0.0f, - const TextureDrawMode mode = TextureDrawMode::DEFAULT) const; + void drawEx(int x, + int y, + int width, + int height, + float angle = 0.0f, + TextureDrawMode mode = TextureDrawMode::Default) const; /** * @brief Get the width of the texture @@ -127,4 +127,4 @@ class Texture { } // namespace afk -#endif // INCLUDE_ASSETS_TEXTURE_H_ +#endif // AFK_TEXTURE_H diff --git a/include/common/Color.h b/include/common/Color.h index ce9fc4a..de74141 100644 --- a/include/common/Color.h +++ b/include/common/Color.h @@ -8,23 +8,22 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_COLOR_COLOR_H_ -#define INCLUDE_COLOR_COLOR_H_ +#ifndef AFK_COLOR_H +#define AFK_COLOR_H -#include +#include -namespace afk { -namespace color { +namespace afk::color { // Color struct Color { - Uint8 r; - Uint8 g; - Uint8 b; - Uint8 a; + uint8_t r; + uint8_t g; + uint8_t b; + uint8_t a; }; -// Color defenitions +// Color definitions static const Color black = {0, 0, 0, 255}; static const Color white = {255, 255, 255, 255}; static const Color red = {255, 0, 0, 255}; @@ -42,7 +41,7 @@ static const Color purple = {0, 255, 255, 255}; * @param b Blue value * @return Color */ -Color rgb(const Uint8 r, const Uint8 g, const Uint8 b); +Color rgb(uint8_t r, uint8_t g, uint8_t b); /** * @brief Create SDL Color from rgba values @@ -53,7 +52,7 @@ Color rgb(const Uint8 r, const Uint8 g, const Uint8 b); * @param a Alpha value * @return Color */ -Color rgba(const Uint8 r, const Uint8 g, const Uint8 b, const Uint8 a); +Color rgba(uint8_t r, uint8_t g, uint8_t b, uint8_t a); /** * @brief Convert int representation of color to an Color @@ -61,7 +60,7 @@ Color rgba(const Uint8 r, const Uint8 g, const Uint8 b, const Uint8 a); * @param colour Integer representation of color * @return Color */ -Color intToColor(const Uint32 colour); +Color intToColor(uint32_t colour); /** * @brief Convert rgb values to an integer color @@ -69,9 +68,9 @@ Color intToColor(const Uint32 colour); * @param r Red value * @param g Green value * @param b Blue value - * @return Uint32 + * @return uint32_t */ -Uint32 rgbToInt(const Uint8 r, const Uint8 g, const Uint8 b); +uint32_t rgbToInt(uint8_t r, uint8_t g, uint8_t b); /** * @brief Convert rgba values to an integer color @@ -80,19 +79,18 @@ Uint32 rgbToInt(const Uint8 r, const Uint8 g, const Uint8 b); * @param g Green value * @param b Blue value * @param a Alpha value - * @return Uint32 + * @return uint32_t */ -Uint32 rgbaToInt(const Uint8 r, const Uint8 g, const Uint8 b, const Uint8 a); +uint32_t rgbaToInt(uint8_t r, uint8_t g, uint8_t b, uint8_t a); /** - * @brief Convert Color to Uint32 representation + * @brief Convert Color to uint32_t representation * * @param colour Color to convert - * @return Uint32 + * @return uint32_t */ -Uint32 colorToInt(const Color colour); +uint32_t colorToInt(Color colour); -} // namespace color -} // namespace afk +} // namespace afk::color -#endif // INCLUDE_COLOR_COLOR_H_ +#endif // AFK_COLOR_H diff --git a/include/common/Exceptions.h b/include/common/Exceptions.h index 3313a69..f5fd74e 100644 --- a/include/common/Exceptions.h +++ b/include/common/Exceptions.h @@ -1,7 +1,7 @@ /** * @file Exceptions.h * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Interally used exceptions. These can be handled properly in the main + * @brief Internally used exceptions. These can be handled properly in the main * game class. * @version 0.1 * @date 2021-03-08 @@ -9,8 +9,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_COMMON_EXCEPTIONS_H_ -#define INCLUDE_COMMON_EXCEPTIONS_H_ +#ifndef AFK_EXCEPTIONS_H +#define AFK_EXCEPTIONS_H #include #include @@ -21,14 +21,14 @@ namespace afk { * @brief Exception raised when a file is not found * */ -class FileIOException : public std::runtime_error { +class FileIoException : public std::runtime_error { public: /** * @brief Construct a new File I O Exception object * * @param msg Message to pass to runtime_error. */ - explicit FileIOException(const std::string& msg) : std::runtime_error(msg) {} + explicit FileIoException(const std::string& msg) : std::runtime_error(msg) {} }; /** @@ -106,7 +106,7 @@ class SceneLookupException : public std::runtime_error { }; /** - * @brief Exception raised when an assertian fails + * @brief Exception raised when an assertion fails * */ class AssertionFailedException : public std::runtime_error { @@ -122,4 +122,4 @@ class AssertionFailedException : public std::runtime_error { } // namespace afk -#endif // INCLUDE_COMMON_EXCEPTIONS_H_ +#endif // AFK_EXCEPTIONS_H diff --git a/include/common/Vec.h b/include/common/Vec.h index 393d291..aa7cd7a 100644 --- a/include/common/Vec.h +++ b/include/common/Vec.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2022 * */ -#ifndef INCLUDE_COMMON_VEC_H_ -#define INCLUDE_COMMON_VEC_H_ +#ifndef AFK_VEC_H +#define AFK_VEC_H namespace afk { @@ -32,4 +32,4 @@ struct Vec3 { } // namespace afk -#endif // INCLUDE_COMMON_VEC_H_ +#endif // AFK_VEC_H diff --git a/include/common/math.h b/include/common/math.h index cb38788..2f6c068 100644 --- a/include/common/math.h +++ b/include/common/math.h @@ -8,11 +8,10 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_COMMON_MATH_H_ -#define INCLUDE_COMMON_MATH_H_ +#ifndef AFK_MATH_H +#define AFK_MATH_H -namespace afk { -namespace math { +namespace afk::math { /** * @brief Lerp between two values @@ -20,7 +19,7 @@ namespace math { * @param start Start value * @param end End value * @param progress Progress from 0.0-1.0 - * @return float Lerped value + * @return float Lerp-ed value */ float lerp(float start, float end, float progress); @@ -34,7 +33,6 @@ float lerp(float start, float end, float progress); */ float clamp(float value, float min, float max); -} // namespace math -} // namespace afk +} // namespace afk::math -#endif // INCLUDE_COMMON_MATH_H_ +#endif // AFK_MATH_H diff --git a/include/common/random.h b/include/common/random.h index d088d3c..ad4abef 100644 --- a/include/common/random.h +++ b/include/common/random.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_RANDOM_RANDOMGENERATOR_H_ -#define INCLUDE_RANDOM_RANDOMGENERATOR_H_ +#ifndef AFK_RANDOM_H +#define AFK_RANDOM_H #include @@ -22,7 +22,7 @@ namespace afk::random { * @param max Max number * @return Random number */ -float randomFloat(const float min, const float max); +float randomFloat(float min, float max); /** * @brief Returns a random int between two numbers @@ -31,11 +31,11 @@ float randomFloat(const float min, const float max); * @param max Max number * @return Random number */ -int randomInt(const int min, const int max); +int randomInt(int min, int max); /// Random number generator extern std::mt19937 rng; } // namespace afk::random -#endif // INCLUDE_RANDOM_RANDOMGENERATOR_H_ +#endif // AFK_RANDOM_H diff --git a/include/common/str.h b/include/common/str.h index f86614a..fe7c305 100644 --- a/include/common/str.h +++ b/include/common/str.h @@ -8,16 +8,15 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_COMMON_STR_H_ -#define INCLUDE_COMMON_STR_H_ +#ifndef AFK_STR_H +#define AFK_STR_H #include #include #include "Exceptions.h" -namespace afk { -namespace str { +namespace afk::str { /** * @brief Check if string is an integer @@ -97,7 +96,6 @@ std::string format(const std::string& format, Args... args) { return std::string(buf.get(), buf.get() + size - 1); } -} // namespace str -} // namespace afk +} // namespace afk::str -#endif // INCLUDE_COMMON_STR_H_ +#endif // AFK_STR_H diff --git a/include/components/Collider.h b/include/components/Collider.h index 15af415..cddcc08 100644 --- a/include/components/Collider.h +++ b/include/components/Collider.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2022 * */ -#ifndef INCLUDE_COMPONENTS_COLLIDER_H_ -#define INCLUDE_COMPONENTS_COLLIDER_H_ +#ifndef AFK_COLLIDER_H +#define AFK_COLLIDER_H namespace afk { @@ -19,4 +19,4 @@ struct Collider { } // namespace afk -#endif // INCLUDE_COMPONENTS_COLLIDER_H_ +#endif // AFK_COLLIDER_H diff --git a/include/components/Particle.h b/include/components/Particle.h index 6e0ab51..29da0c9 100644 --- a/include/components/Particle.h +++ b/include/components/Particle.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_COMPONENTS_PARTICLE_H_ -#define INCLUDE_COMPONENTS_PARTICLE_H_ +#ifndef AFK_PARTICLE_H +#define AFK_PARTICLE_H #include #include "../common/Color.h" @@ -18,33 +18,32 @@ namespace afk { enum class ParticleType : int { - PIXEL, - SQUARE, - CIRCLE, - IMAGE, - NONE, + Pixel, + Square, + Circle, + Image, + None, }; struct Particle { /// Constructor - Particle(ParticleType type = ParticleType::PIXEL) + explicit Particle(ParticleType type = ParticleType::Pixel) : type(type), - start_size(1), - end_size(1), + startSize(1), + endSize(1), age(0), lifespan(1000), - start_color(color::black), - end_color(color::black), - texture(""){}; + startColor(color::black), + endColor(color::black){}; Particle(const Particle& part) : type(part.type), - start_size(part.start_size), - end_size(part.end_size), + startSize(part.startSize), + endSize(part.endSize), age(0), lifespan(part.lifespan), - start_color(part.start_color), - end_color(part.end_color), + startColor(part.startColor), + endColor(part.endColor), texture(part.texture){}; /** @@ -60,19 +59,19 @@ struct Particle { * @param size Size of particle */ void setSize(const float size) { - this->start_size = size; - this->end_size = size; + this->startSize = size; + this->endSize = size; } /** * @brief Set the size of particle over lifespan * - * @param start_size Size to start at - * @param end_size Size to end at + * @param startSize Size to start at + * @param endSize Size to end at */ - void setSize(const float start_size, const float end_size) { - this->start_size = start_size; - this->end_size = end_size; + void setSize(const float startSize, const float endSize) { + this->startSize = startSize; + this->endSize = endSize; } /** @@ -91,20 +90,19 @@ struct Particle { * @param color Color to set to */ void setColor(const color::Color& color) { - this->start_color = color; - this->end_color = color; + this->startColor = color; + this->endColor = color; } /** * @brief Set the particle color over lifespan * - * @param start_color Starting color - * @param end_color Ending color + * @param startColor Starting color + * @param endColor Ending color */ - void setColor(const color::Color& start_color, - const color::Color& end_color) { - this->start_color = start_color; - this->end_color = end_color; + void setColor(const color::Color& startColor, const color::Color& endColor) { + this->startColor = startColor; + this->endColor = endColor; } /** @@ -118,22 +116,22 @@ struct Particle { ParticleType type; /// Starting size - float start_size; + float startSize; /// Ending size - float end_size; + float endSize; /// Current age - float age; + uint32_t age; /// Max lifespan float lifespan; /// Start color - color::Color start_color; + color::Color startColor; /// End color - color::Color end_color; + color::Color endColor; /// String std::string texture; @@ -141,4 +139,4 @@ struct Particle { } // namespace afk -#endif // INCLUDE_COMPONENTS_PARTICLE_H_ +#endif // AFK_PARTICLE_H diff --git a/include/components/ParticleEmitter.h b/include/components/ParticleEmitter.h index c40e196..45841d2 100644 --- a/include/components/ParticleEmitter.h +++ b/include/components/ParticleEmitter.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2022 * */ -#ifndef INCLUDE_COMPONENTS_PARTICLE_EMITTER_H_ -#define INCLUDE_COMPONENTS_PARTICLE_EMITTER_H_ +#ifndef AFK_PARTICLEEMITTER_H +#define AFK_PARTICLEEMITTER_H #include #include @@ -26,7 +26,8 @@ using ParticleTemplate = std::pair; struct ParticleEmitter { /// Constructor - ParticleEmitter(float frequency) : frequency(frequency), counter(0){}; + explicit ParticleEmitter(float frequency) + : frequency(frequency), counter(0){}; /** * @brief Add a particle to the emitter pool @@ -51,4 +52,4 @@ struct ParticleEmitter { } // namespace afk -#endif // INCLUDE_COMPONENTS_PARTICLE_EMITTER_H_ +#endif // AFK_PARTICLEEMITTER_H diff --git a/include/components/Physics.h b/include/components/Physics.h index 7850c12..93c5dc4 100644 --- a/include/components/Physics.h +++ b/include/components/Physics.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2022 * */ -#ifndef INCLUDE_COMPONENTS_PHYSICS_H_ -#define INCLUDE_COMPONENTS_PHYSICS_H_ +#ifndef AFK_PHYSICS_H +#define AFK_PHYSICS_H #include "../common/Vec.h" @@ -20,9 +20,9 @@ struct Physics { Physics(Vec2 velocity, Vec2 acceleration) : velocity(velocity), acceleration(acceleration) {} - Physics(Vec2 velocity) : velocity(velocity) {} + explicit Physics(Vec2 velocity) : velocity(velocity) {} - Physics() {} + Physics() = default; void setVelocity(Vec2 velocity) { this->velocity = velocity; } @@ -41,4 +41,4 @@ struct Physics { } // namespace afk -#endif // INCLUDE_COMPONENTS_PHYSICS_H_ +#endif // AFK_PHYSICS_H diff --git a/include/components/Sprite.h b/include/components/Sprite.h index 27b28bb..5c6e7b5 100644 --- a/include/components/Sprite.h +++ b/include/components/Sprite.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_COMPONENTS_SPRITE_H_ -#define INCLUDE_COMPONENTS_SPRITE_H_ +#ifndef AFK_SPRITE_H +#define AFK_SPRITE_H #include @@ -22,4 +22,4 @@ struct Sprite { } // namespace afk -#endif // INCLUDE_COMPONENTS_SPRITE_H_ +#endif // AFK_SPRITE_H diff --git a/include/components/Transform.h b/include/components/Transform.h index 6fd44c6..22e5476 100644 --- a/include/components/Transform.h +++ b/include/components/Transform.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_COMPONENTS_TRANSFORM_H_ -#define INCLUDE_COMPONENTS_TRANSFORM_H_ +#ifndef AFK_TRANSFORM_H +#define AFK_TRANSFORM_H #include "../common/Vec.h" @@ -28,4 +28,4 @@ struct Transform { } // namespace afk -#endif // INCLUDE_COMPONENTS_TRANSFORM_H_ +#endif // AFK_TRANSFORM_H diff --git a/include/components/components.h b/include/components/components.h index 6b740f9..ae28748 100644 --- a/include/components/components.h +++ b/include/components/components.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2022 * */ -#ifndef INCLUDE_COMPONENTS_COMPONENTS_H_ -#define INCLUDE_COMPONENTS_COMPONENTS_H_ +#ifndef AFK_COMPONENTS_H +#define AFK_COMPONENTS_H #include "./Collider.h" #include "./Particle.h" @@ -18,4 +18,4 @@ #include "./Sprite.h" #include "./Transform.h" -#endif // INCLUDE_COMPONENTS_COMPONENTS_H_ +#endif // AFK_COMPONENTS_H diff --git a/include/components/ui.h b/include/components/ui.h index 7ff2299..fd49f2a 100644 --- a/include/components/ui.h +++ b/include/components/ui.h @@ -8,10 +8,10 @@ * @copyright Copyright (c) 2022 * */ -#ifndef INCLUDE_COMPONENTS_UI_H_ -#define INCLUDE_COMPONENTS_UI_H_ +#ifndef AFK_UI_H +#define AFK_UI_H #include "./ui/Button.h" #include "./ui/Label.h" -#endif // INCLUDE_COMPONENTS_UI_H_ +#endif // AFK_UI_H diff --git a/include/components/ui/Button.h b/include/components/ui/Button.h index 1dfb19f..87ed3dd 100644 --- a/include/components/ui/Button.h +++ b/include/components/ui/Button.h @@ -8,20 +8,21 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_COMPONENTS_UI_BUTTON_H_ -#define INCLUDE_COMPONENTS_UI_BUTTON_H_ +#ifndef AFK_BUTTON_H +#define AFK_BUTTON_H #include #include +#include namespace afk { struct Button { /// Constructor - Button() : text(""), font("") {} + Button() = default; - Button(const std::string& text, const std::string& font) - : text(text), font(font) {} + Button(std::string text, std::string font) + : text(std::move(text)), font(std::move(font)) {} /// Text of Button std::string text; @@ -52,9 +53,11 @@ struct Button { * * @param func function to assign to onClick */ - void setOnClick(std::function func) { this->onClick = func; }; + void setOnClick(std::function func) { + this->onClick = std::move(func); + }; }; } // namespace afk -#endif // INCLUDE_COMPONENTS_UI_BUTTON_H_ +#endif // AFK_BUTTON_H diff --git a/include/components/ui/Label.h b/include/components/ui/Label.h index 67d31a5..85e29e7 100644 --- a/include/components/ui/Label.h +++ b/include/components/ui/Label.h @@ -8,19 +8,20 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_COMPONENTS_UI_LABEL_H_ -#define INCLUDE_COMPONENTS_UI_LABEL_H_ +#ifndef AFK_LABEL_H +#define AFK_LABEL_H #include +#include namespace afk { struct Label { /// Constructor - Label() : text(""), font("") {} + Label() = default; - Label(const std::string& text, const std::string& font) - : text(text), font(font) {} + Label(std::string text, std::string font) + : text(std::move(text)), font(std::move(font)) {} /// Text of Label std::string text; @@ -36,4 +37,4 @@ struct Label { } // namespace afk -#endif // INCLUDE_COMPONENTS_UI_LABEL_H_ +#endif // AFK_LABEL_H diff --git a/include/entities/Entity.h b/include/entities/Entity.h index c1637a0..91360f6 100644 --- a/include/entities/Entity.h +++ b/include/entities/Entity.h @@ -8,16 +8,16 @@ * @copyright Copyright (c) 2022 * */ -#ifndef INCLUDE_ENTITIES_ENTITY_H_ -#define INCLUDE_ENTITIES_ENTITY_H_ +#ifndef AFK_ENTITY_H +#define AFK_ENTITY_H #include namespace afk { -using entity = entt::entity; -using registry = entt::registry; +using Entity = entt::entity; +using Registry = entt::registry; } // namespace afk -#endif // INCLUDE_ENTITIES_ENTITY_H_ +#endif // AFK_ENTITY_H diff --git a/include/primitives/Primitives.h b/include/primitives/Primitives.h index fa7abae..1a367c7 100644 --- a/include/primitives/Primitives.h +++ b/include/primitives/Primitives.h @@ -9,13 +9,14 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_PRIMITIVES_PRIMITIVES_H_ -#define INCLUDE_PRIMITIVES_PRIMITIVES_H_ +#ifndef AFK_PRIMITIVES_H +#define AFK_PRIMITIVES_H + +#include #include "../common/Color.h" -namespace afk { -namespace primitives { +namespace afk::primitives { /** * @brief Draw a rectangle border @@ -26,11 +27,7 @@ namespace primitives { * @param h Height of rect * @param colour Colour of rect */ -void rect(const Sint32 x, - const Sint32 y, - const Sint32 w, - const Sint32 h, - color::Color colour); +void rect(int32_t x, int32_t y, int32_t w, int32_t h, color::Color colour); /** * @brief Draw a filled rectangle @@ -41,11 +38,7 @@ void rect(const Sint32 x, * @param h Height of rect * @param colour Colour of rect */ -void rectfill(const Sint32 x, - const Sint32 y, - const Sint32 w, - const Sint32 h, - color::Color colour); +void rectfill(int32_t x, int32_t y, int32_t w, int32_t h, color::Color colour); /** * @brief Draw a circle @@ -55,10 +48,7 @@ void rectfill(const Sint32 x, * @param r Radius * @param colour Colour of circle */ -void circle(const Sint16 cx, - const Sint16 cy, - const Sint16 r, - color::Color colour); +void circle(Sint16 cx, Sint16 cy, Sint16 r, color::Color colour); /** * @brief Draw a single pixel @@ -67,7 +57,7 @@ void circle(const Sint16 cx, * @param y Y position of pixel * @param colour Colour of pixel */ -void pixel(const Sint16 x, const Sint16 y, color::Color colour); +void pixel(Sint16 x, Sint16 y, color::Color colour); /** * @brief Draw line between two points @@ -78,13 +68,8 @@ void pixel(const Sint16 x, const Sint16 y, color::Color colour); * @param y2 Y end position of line * @param colour Colour of line */ -void line(const Sint16 x1, - const Sint16 y1, - const Sint16 x2, - const Sint16 y2, - color::Color colour); +void line(Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, color::Color colour); -} // namespace primitives -} // namespace afk +} // namespace afk::primitives -#endif // INCLUDE_PRIMITIVES_PRIMITIVES_H_ +#endif // AFK_PRIMITIVES_H diff --git a/include/scene/Scene.h b/include/scene/Scene.h index a3f8385..4a11ae0 100644 --- a/include/scene/Scene.h +++ b/include/scene/Scene.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SCENE_SCENE_H_ -#define INCLUDE_SCENE_SCENE_H_ +#ifndef AFK_SCENE_H +#define AFK_SCENE_H #include #include @@ -40,7 +40,7 @@ class Scene { * @brief Destroy the Scene * */ - virtual ~Scene() {} + virtual ~Scene() = default; /** * @brief Start the scene @@ -54,7 +54,7 @@ class Scene { * @param delta Time since last call in ms * */ - virtual void update(Uint32 delta); + virtual void update(uint32_t delta); /** * @brief Draw to be overridden by derived scenes @@ -69,7 +69,7 @@ class Scene { virtual void stop(){}; /** - * @brief Internall cleanup call + * @brief Internal cleanup call * */ void stopInternal(); @@ -79,14 +79,14 @@ class Scene { * * @return entity */ - entity createEntity(); + Entity createEntity(); /** * @brief Remove an entity * * @param entity Entity to remove */ - void destroyEntity(entity entity); + void destroyEntity(Entity entity); /** * @brief Add a component to an entity @@ -97,7 +97,7 @@ class Scene { * @param args Arguments accepted by component */ template - T& createComponent(entity id, Args&&... args) { + T& createComponent(Entity id, Args&&... args) { auto& component = registry.emplace(id, std::forward(args)...); // Sort always (inefficient!) @@ -115,7 +115,7 @@ class Scene { * @param id Entity to assign to */ template - T& createComponent(entity id) { + T& createComponent(Entity id) { return registry.emplace(id); } @@ -127,7 +127,7 @@ class Scene { * @return T& Returned component reference */ template - T& getComponent(entity id) { + T& getComponent(Entity id) { return registry.get(id); } @@ -136,7 +136,7 @@ class Scene { * * @return registry& Registry reference */ - registry& getRegistry(); + Registry& getRegistry(); /// Audio service reference AudioService& audio; @@ -161,8 +161,8 @@ class Scene { private: /// Entity registry - registry registry; + Registry registry; }; } // namespace afk -#endif // INCLUDE_SCENE_SCENE_H_ +#endif // AFK_SCENE_H diff --git a/include/services/Service.h b/include/services/Service.h index fc1a1ca..b7691c3 100644 --- a/include/services/Service.h +++ b/include/services/Service.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_SERVICE_H_ -#define INCLUDE_SERVICES_SERVICE_H_ +#ifndef AFK_SERVICE_H +#define AFK_SERVICE_H #include #include @@ -24,7 +24,7 @@ class Service { /** * @brief Virtual notify to be called by the queue * - * @param event Allegero event to be processed + * @param event SDL event to be processed */ virtual void notify(const SDL_Event& event) = 0; @@ -38,4 +38,4 @@ class Service { } // namespace afk -#endif // INCLUDE_SERVICES_SERVICE_H_ +#endif // AFK_SERVICE_H diff --git a/include/services/Services.h b/include/services/Services.h index a4d780d..e3d7fb3 100644 --- a/include/services/Services.h +++ b/include/services/Services.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_SERVICES_H_ -#define INCLUDE_SERVICES_SERVICES_H_ +#ifndef AFK_SERVICES_H +#define AFK_SERVICES_H #include @@ -87,30 +87,30 @@ class Services { private: /// Internal pointer to current LoggingService instance - static DebugLoggingService logging_service; + static DebugLoggingService loggingService; /// Internal pointer to current Event queue instance - static EventQueue event_service; + static EventQueue eventService; /// Internal pointer to current SceneService queue instance - static SceneService scene_service; + static SceneService sceneService; /// Internal pointer to current DisplayService instance - static DisplayService display_service; + static DisplayService displayService; /// Internal pointer to current InputService instance - static InputService input_service; + static InputService inputService; /// Internal pointer to current AudioService instance - static AudioService audio_service; + static AudioService audioService; /// Internal pointer to current AssetService instance - static AssetService asset_service; + static AssetService assetService; /// Internal pointer to current ConfigService instance - static ConfigService config_service; + static ConfigService configService; }; } // namespace afk -#endif // INCLUDE_SERVICES_SERVICES_H_ +#endif // AFK_SERVICES_H diff --git a/include/services/assets/AssetService.h b/include/services/assets/AssetService.h index d86087e..f8b5134 100644 --- a/include/services/assets/AssetService.h +++ b/include/services/assets/AssetService.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_ASSETS_ASSETSERVICE_H_ -#define INCLUDE_SERVICES_ASSETS_ASSETSERVICE_H_ +#ifndef AFK_ASSETSERVICE_H +#define AFK_ASSETSERVICE_H #include #include @@ -39,7 +39,7 @@ class AssetService { * Cleans up assets upon unloading * */ - virtual ~AssetService(); + virtual ~AssetService() = default; /** * @brief Get reference to audio by key reference @@ -113,9 +113,7 @@ class AssetService { * @throws FileIOException Thrown if file can not be loaded * @see getFont */ - void loadFont(const std::string& key, - const std::string& path, - const int size); + void loadFont(const std::string& key, const std::string& path, int size); /** * @brief Loads an audio stream into memory from a given path. Stream is @@ -130,18 +128,18 @@ class AssetService { private: /// Container that stores all Sound assets - std::unordered_map loaded_audio; + std::unordered_map loadedAudio; /// Container that stores all Image assets - std::unordered_map loaded_image; + std::unordered_map loadedImage; /// Container that stores all Font assets - std::unordered_map loaded_font; + std::unordered_map loadedFont; /// Container that stores all Stream assets - std::unordered_map loaded_stream; + std::unordered_map loadedStream; }; } // namespace afk -#endif // INCLUDE_SERVICES_ASSETS_ASSETSERVICE_H_ +#endif // AFK_ASSETSERVICE_H diff --git a/include/services/audio/AudioService.h b/include/services/audio/AudioService.h index 9917270..4540729 100644 --- a/include/services/audio/AudioService.h +++ b/include/services/audio/AudioService.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_AUDIO_AUDIOSERVICE_H_ -#define INCLUDE_SERVICES_AUDIO_AUDIOSERVICE_H_ +#ifndef AFK_AUDIOSERVICE_H +#define AFK_AUDIOSERVICE_H #include @@ -28,7 +28,7 @@ class AudioService { * @brief Destroy the Audio Service * */ - virtual ~AudioService() {} + virtual ~AudioService() = default; /** * @brief Play sound by id @@ -40,10 +40,10 @@ class AudioService { * @param loop Loop mode */ void playSound(const std::string& key, - const float gain = 1.0f, - const float pan = 0.0f, - const float speed = 1.0f, - const bool loop = false); + float gain = 1.0f, + float pan = 0.0f, + float speed = 1.0f, + bool loop = false); /** * @brief Play audio stream by id @@ -51,7 +51,7 @@ class AudioService { * @param key Id of stream to play * @param loop Loop mode, true for looping, false for one shot */ - void playStream(const std::string& key, const bool loop = false); + void playStream(const std::string& key, bool loop = false); /** * @brief Stop stream by id. Stops all instances of stream currently playing. @@ -63,7 +63,7 @@ class AudioService { } // namespace afk -#endif // INCLUDE_SERVICES_AUDIO_AUDIOSERVICE_H_ +#endif // AFK_AUDIOSERVICE_H /** * @example ex_sound.cpp diff --git a/include/services/config/ConfigService.h b/include/services/config/ConfigService.h index 7a29988..e80912d 100644 --- a/include/services/config/ConfigService.h +++ b/include/services/config/ConfigService.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_CONFIG_CONFIGSERVICE_H_ -#define INCLUDE_SERVICES_CONFIG_CONFIGSERVICE_H_ +#ifndef AFK_CONFIGSERVICE_H +#define AFK_CONFIGSERVICE_H #include #include @@ -93,29 +93,29 @@ class ConfigService { */ template void set(const std::string& key, const T value) { - std::string s_val = std::to_string(value); + std::string sVal = std::to_string(value); - settings[key] = s_val; + settings[key] = sVal; - if (autosave) { + if (autoSave) { save(); } } /** - * @brief Set the autosave config + * @brief Set the auto save config * - * @param autosave If set to true, will autosave on each set to the original + * @param autoSave If set to true, will auto save on each set to the original * file path */ - void setAutosave(const bool autosave); + void setAutoSave(bool autoSave); private: - /// Name of file for save, and autosave reference - std::string file_name; + /// Name of file for save, and auto save reference + std::string fileName; - /// Autosave enabled status - bool autosave; + /// Auto save enabled status + bool autoSave; /// Container which stores all settings std::unordered_map settings; @@ -123,4 +123,4 @@ class ConfigService { } // namespace afk -#endif // INCLUDE_SERVICES_CONFIG_CONFIGSERVICE_H_ +#endif // AFK_CONFIGSERVICE_H diff --git a/include/services/display/DisplayService.h b/include/services/display/DisplayService.h index be85e76..7cba4af 100644 --- a/include/services/display/DisplayService.h +++ b/include/services/display/DisplayService.h @@ -10,8 +10,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_DISPLAY_DISPLAYSERVICE_H_ -#define INCLUDE_SERVICES_DISPLAY_DISPLAYSERVICE_H_ +#ifndef AFK_DISPLAYSERVICE_H +#define AFK_DISPLAYSERVICE_H #include #include @@ -19,7 +19,7 @@ #include "../../common/Color.h" #include "../Service.h" -const int FRAME_BUFFER_SIZE = 50; +const int frameBufferSize = 50; namespace afk { @@ -30,14 +30,14 @@ class Scene; * */ enum class DisplayMode { - /// Stretches window in fullscreen - FULLSCREEN_WINDOW_STRETCH, + /// Stretches window in full screen + FullScreenWindowStretch, /// Shows window in highest resolution without clipping or stretching - FULLSCREEN_WINDOW_LETTERBOX, + FullScreenWindowLetterbox, /// Centers the window at the standard window resolution - FULLSCREEN_WINDOW_CENTER, + FullScreenWindowCenter, /// Shows window in windowed mode at set window size - WINDOWED, + Windowed, }; /** @@ -63,9 +63,9 @@ class DisplayService { * @brief Draw a scene. Calls the draw and draw_internal functions of a given * Scene object * - * @param current_scene Scene to draw + * @param currentScene Scene to draw */ - void draw(Scene* current_scene); + void draw(Scene* currentScene); /** * @brief Set the current display mode. Should be called once on @@ -74,7 +74,7 @@ class DisplayService { * @param mode Display mode to set it to * @see DisplayMode */ - void setMode(const DisplayMode mode); + void setMode(DisplayMode mode); /** * @brief Set the size of the buffer @@ -82,7 +82,7 @@ class DisplayService { * @param width Width of buffer in pixels * @param height Height of buffer in pixels */ - void setBufferSize(const Uint32 width, const Uint32 height); + void setBufferSize(uint32_t width, uint32_t height); /** * @brief Set the size of the window @@ -90,7 +90,7 @@ class DisplayService { * @param width Width of window in pixels * @param height Height of window in pixels */ - void setWindowSize(const Uint32 width, const Uint32 height); + void setWindowSize(uint32_t width, uint32_t height); /** * @brief Get the current display mode @@ -105,42 +105,42 @@ class DisplayService { * * @return Width of buffer in pixels */ - Uint32 getDrawWidth() const; + uint32_t getDrawWidth() const; /** * @brief Get the buffer height * * @return Height of buffer in pixels */ - Uint32 getDrawHeight() const; + uint32_t getDrawHeight() const; /** * @brief Get the x translation of the window * * @return X translation in pixels */ - Uint32 getTranslationX() const; + uint32_t getTranslationX() const; /** * @brief Get the y translation of the window * * @return Y translation in pixels */ - Uint32 getTranslationY() const; + uint32_t getTranslationY() const; /** * @brief Get the current width of the winodw * * @return width of window */ - Uint32 getDisplayServiceWidth() const; + uint32_t getDisplayServiceWidth() const; /** * @brief Get the current height of window * * @return height of window */ - Uint32 getDisplayServiceHeight() const; + uint32_t getDisplayServiceHeight() const; /** * @brief Get the scaling being done on buffer. This is equivalent to buffer @@ -173,10 +173,10 @@ class DisplayService { /** * @brief Resize window to given width and height * - * @param window_w Width in pixels - * @param window_h Height in pixels + * @param windowW Width in pixels + * @param windowH Height in pixels */ - void resize(const Uint32 window_w, const Uint32 window_h); + void resize(uint32_t windowW, uint32_t windowH); /** * @brief Set the window title @@ -222,31 +222,31 @@ class DisplayService { private: /// Width of buffer - Uint32 draw_w = 0; + uint32_t drawW = 0; /// Height of buffer - Uint32 draw_h = 0; + uint32_t drawH = 0; /// Width of window - Uint32 window_w = 0; + uint32_t windowW = 0; /// Height of window - Uint32 window_h = 0; + uint32_t windowH = 0; /// X translation of window - Uint32 translation_x = 0; + uint32_t translationX = 0; /// Y translation of window - Uint32 translation_y = 0; + uint32_t translationY = 0; /// X scaling amount - float scale_x = 0; + float scaleX = 0; /// Y scaling amount - float scale_y = 0; + float scaleY = 0; /// Current display mode - DisplayMode display_mode = DisplayMode::WINDOWED; + DisplayMode displayMode = DisplayMode::Windowed; /// Active window SDL_Window* window = nullptr; @@ -255,19 +255,19 @@ class DisplayService { SDL_Renderer* renderer = nullptr; /// Fps timer - Uint32 old_time = 0; + uint32_t oldTime = 0; /// Frame array for calculating fps - Uint32 frames_array[FRAME_BUFFER_SIZE] = {0}; + uint32_t framesArray[frameBufferSize] = {0}; /// Current fps - Uint32 fps = 0; + uint32_t fps = 0; /// Frame index - Uint32 frame_index = 0; + uint32_t frameIndex = 0; /// Clear color - color::Color clear_color; + color::Color clearColor; /** * @brief Sets the window scaling in percent @@ -275,7 +275,7 @@ class DisplayService { * @param x X scaling percent * @param y Y scaling percent */ - void setScale(const float x, const float y); + void setScale(float x, float y); /** * @brief Set the translation amount in pixels @@ -283,12 +283,12 @@ class DisplayService { * @param x X translation * @param y Y translation */ - void setTranslation(const Uint32 x, const Uint32 y); + void setTranslation(uint32_t x, uint32_t y); }; } // namespace afk -#endif // INCLUDE_SERVICES_DISPLAY_DISPLAYSERVICE_H_ +#endif // AFK_DISPLAYSERVICE_H /** * @example ex_display.cpp diff --git a/include/services/events/EventQueue.h b/include/services/events/EventQueue.h index 17da175..000ba51 100644 --- a/include/services/events/EventQueue.h +++ b/include/services/events/EventQueue.h @@ -9,10 +9,10 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_EVENTS_EVENTQUEUE_H_ -#define INCLUDE_SERVICES_EVENTS_EVENTQUEUE_H_ +#ifndef AFK_EVENTQUEUE_H +#define AFK_EVENTQUEUE_H -#include +#include #include #include "../Service.h" @@ -63,14 +63,14 @@ class EventQueue { * @param time Time in ms to call timer at * @param code User defined code to inject into timer */ - SDL_TimerID registerTimer(const Uint32 time, const char code); + SDL_TimerID registerTimer(uint32_t time, char code); /** * @brief Unregister user timer * - * @param timer Timer to remove from queue + * @param timerId Timer to remove from queue */ - void unregisterTimer(const SDL_TimerID timer); + void unregisterTimer(SDL_TimerID timerId); /** * @brief Timer callback for registered timers @@ -78,7 +78,7 @@ class EventQueue { * @param interval MS per call, interval to run at * @param param User defined params */ - static Uint32 timerCallback(Uint32 interval, void* param); + static uint32_t timerCallback(uint32_t interval, void* param); private: /// List of services which must be notified @@ -87,4 +87,4 @@ class EventQueue { } // namespace afk -#endif // INCLUDE_SERVICES_EVENTS_EVENTQUEUE_H_ +#endif // AFK_EVENTQUEUE_H diff --git a/include/services/input/InputService.h b/include/services/input/InputService.h index 73762d6..a7cf1c7 100644 --- a/include/services/input/InputService.h +++ b/include/services/input/InputService.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_INPUT_INPUTSERVICE_H_ -#define INCLUDE_SERVICES_INPUT_INPUTSERVICE_H_ +#ifndef AFK_INPUTSERVICE_H +#define AFK_INPUTSERVICE_H #include #include @@ -53,14 +53,14 @@ class InputService : public Service { * * @return name */ - std::string getName() const; + std::string getName() const override; /** * @brief Notify input service of recent event * * @param event SDL event to process */ - void notify(const SDL_Event& event); + void notify(const SDL_Event& event) override; /** * @brief Get key just down state @@ -69,7 +69,7 @@ class InputService : public Service { * * @return Key state */ - bool keyPressed(const Keys key) const; + bool keyPressed(Keys key) const; /** * @brief Get key just up state @@ -78,7 +78,7 @@ class InputService : public Service { * * @return Key state */ - bool keyReleased(const Keys key) const; + bool keyReleased(Keys key) const; /** * @brief Get key down state @@ -87,7 +87,7 @@ class InputService : public Service { * * @return Key state */ - bool keyDown(const Keys key) const; + bool keyDown(Keys key) const; /** * @brief Get if any key is down @@ -117,7 +117,7 @@ class InputService : public Service { * * @return Key state */ - bool mousePressed(const MouseButtons button) const; + bool mousePressed(MouseButtons button) const; /** * @brief Get mouse button just up state @@ -126,7 +126,7 @@ class InputService : public Service { * * @return Key state */ - bool mouseReleased(const MouseButtons button) const; + bool mouseReleased(MouseButtons button) const; /** * @brief Get mouse button down state @@ -135,7 +135,7 @@ class InputService : public Service { * * @return Key state */ - bool mouseDown(const MouseButtons button) const; + bool mouseDown(MouseButtons button) const; /** * @brief Get whether mouse is over a given area @@ -145,7 +145,7 @@ class InputService : public Service { * * @return Over state */ - bool mouseOver(const Vec2 position, const Vec2 size) const; + bool mouseOver(Vec2 position, Vec2 size) const; /** * @brief Get mouse x position @@ -175,7 +175,7 @@ class InputService : public Service { * * @return Key state */ - bool joyPressed(const JoystickButtons button) const; + bool joyPressed(JoystickButtons button) const; /** * @brief Get joy button just up state @@ -184,7 +184,7 @@ class InputService : public Service { * * @return Key state */ - bool joyReleased(const JoystickButtons button) const; + bool joyReleased(JoystickButtons button) const; /** * @brief Get joy button down state @@ -193,16 +193,16 @@ class InputService : public Service { * * @return Key state */ - bool joyDown(const JoystickButtons button) const; + bool joyDown(JoystickButtons button) const; private: /** * @brief Joystick button event handler * - * @param event_type Type of sdl event + * @param eventType Type of sdl event * @param event Sdl event to be processed */ - void onJoystickEvent(const Uint32 event_type, const SDL_JoyButtonEvent event); + void onJoystickEvent(uint32_t eventType, SDL_JoyButtonEvent event); /** * @brief Joystick axis and stick event handler @@ -210,7 +210,7 @@ class InputService : public Service { * @param event_type Type of sdl event * @param event Sdl event to be processed */ - void onJoystickEvent(const SDL_JoyAxisEvent event); + void onJoystickEvent(SDL_JoyAxisEvent event); /** * @brief Joystick configuration event @@ -221,46 +221,46 @@ class InputService : public Service { /** * @brief Keyboard event handler * - * @param event_type Type of sdl event + * @param eventType Type of sdl event * @param event Sdl event to be processed */ - void onKeyboardEvent(const Uint32 event_type, const SDL_KeyboardEvent event); + void onKeyboardEvent(uint32_t eventType, SDL_KeyboardEvent event); /** * @brief Mouse axis handler * * @param event Sdl event to be processed */ - void onMouseEvent(const SDL_MouseWheelEvent event); + void onMouseEvent(SDL_MouseWheelEvent event); /** * @brief Mouse wheel handler * * @param event Sdl event to be processed */ - void onMouseEvent(const SDL_MouseMotionEvent event); + void onMouseEvent(SDL_MouseMotionEvent event); /** * @brief Mouse button handler * - * @param event_type Type of sdl event + * @param eventType Type of sdl event * @param event Sdl event to be processed */ - void onMouseEvent(const Uint32 event_type, const SDL_MouseButtonEvent event); + void onMouseEvent(uint32_t eventType, SDL_MouseButtonEvent event); /// Current keyboard state - KeyboardState keyboard_state; + KeyboardState keyboardState; /// Current mouse state - MouseState mouse_state; + MouseState mouseState; /// Current joystick state - JoystickState joystick_state; + JoystickState joystickState; }; } // namespace afk -#endif // INCLUDE_SERVICES_INPUT_INPUTSERVICE_H_ +#endif // AFK_INPUTSERVICE_H /** * @example ex_mouse.cpp diff --git a/include/services/input/JoystickCodes.h b/include/services/input/JoystickCodes.h index 4973700..244cd09 100644 --- a/include/services/input/JoystickCodes.h +++ b/include/services/input/JoystickCodes.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_INPUT_JOYSTICKCODES_H_ -#define INCLUDE_SERVICES_INPUT_JOYSTICKCODES_H_ +#ifndef AFK_JOYSTICKCODES_H +#define AFK_JOYSTICKCODES_H namespace afk { @@ -18,29 +18,29 @@ enum class JoystickButtons { B = 1, X = 2, Y = 3, - BUMPER_RIGHT = 4, - BUMPER_LEFT = 5, - BACK = 8, - START = 9, - PAD_RIGHT = 10, - PAD_LEFT = 11, - PAD_DOWN = 12, - PAD_UP = 13 + BumperRight = 4, + BumperLeft = 5, + Back = 8, + Start = 9, + PadRight = 10, + PadLeft = 11, + PadDown = 12, + PadUp = 13 }; enum class JoystickSticks { - LEFT_STICK_LEFT = 1, - LEFT_STICK_RIGHT = 0, - LEFT_STICK_DOWN = 2, - LEFT_STICK_UP = 3, - RIGHT_STICK_LEFT = 7, - RIGHT_STICK_RIGHT = 6, - RIGHT_STICK_DOWN = 8, - RIGHT_STICK_UP = 9, - LEFT_TRIGGER = 12, - RIGHT_TRIGGER = 18 + LeftStickLeft = 1, + LeftStickRight = 0, + LeftStickDown = 2, + LeftStickUp = 3, + RightStickLeft = 7, + RightStickRight = 6, + RightStickDown = 8, + RightStickUp = 9, + LeftTrigger = 12, + RightTrigger = 18 }; } // namespace afk -#endif // INCLUDE_SERVICES_INPUT_JOYSTICKCODES_H_ +#endif // AFK_JOYSTICKCODES_H diff --git a/include/services/input/JoystickState.h b/include/services/input/JoystickState.h index 755f563..4a47751 100644 --- a/include/services/input/JoystickState.h +++ b/include/services/input/JoystickState.h @@ -10,8 +10,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_INPUT_JOYSTICKSTATE_H_ -#define INCLUDE_SERVICES_INPUT_JOYSTICKSTATE_H_ +#ifndef AFK_JOYSTICKSTATE_H +#define AFK_JOYSTICKSTATE_H #include @@ -89,12 +89,12 @@ struct JoystickState { stickReleased[i] = false; // Pressed since last tick? - if (stick[i] == true && lastTicksStick[i] == false) { + if (stick[i] && !lastTicksStick[i]) { stickMoved[i] = true; } // Released since last tick? - if (stick[i] == false && lastTicksStick[i] == true) { + if (!stick[i] && lastTicksStick[i]) { stickReleased[i] = true; } @@ -113,13 +113,13 @@ struct JoystickState { } // Pressed since last tick? - if (button[i] == true && lastTicksButton[i] == false) { + if (button[i] && !lastTicksButton[i]) { buttonPressed[i] = true; lastButtonPressed = i; } // Released since last tick? - if (button[i] == false && lastTicksButton[i] == true) { + if (!button[i] && lastTicksButton[i]) { buttonReleased[i] = true; lastButtonReleased = i; } @@ -132,4 +132,4 @@ struct JoystickState { } // namespace afk -#endif // INCLUDE_SERVICES_INPUT_JOYSTICKSTATE_H_ +#endif // AFK_JOYSTICKSTATE_H diff --git a/include/services/input/KeyboardKeys.h b/include/services/input/KeyboardKeys.h index 6fbbc4c..f47a9d4 100644 --- a/include/services/input/KeyboardKeys.h +++ b/include/services/input/KeyboardKeys.h @@ -1,20 +1,20 @@ /** * @file KeyboardKeys.h * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Defenitions of keys that can be used by input manager + * @brief Definitions of keys that can be used by input manager * @version 0.1 * @date 2021-03-08 * * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_INPUT_KEYBOARDKEYS_H_ -#define INCLUDE_SERVICES_INPUT_KEYBOARDKEYS_H_ +#ifndef AFK_KEYBOARDKEYS_H +#define AFK_KEYBOARDKEYS_H namespace afk { enum class Keys { - UNKNOWN = 0, + Unknown = 0, A = 4, B = 5, C = 6, @@ -41,34 +41,34 @@ enum class Keys { X = 27, Y = 28, Z = 29, - ONE = 30, - TWO = 31, - THREE = 32, - FOUR = 33, - FIVE = 34, - SIX = 35, - SEVEN = 36, - EIGHT = 37, - NINE = 38, - ZERO = 39, - RETURN = 40, - ESCAPE = 41, - BACKSPACE = 42, - TAB = 43, - SPACE = 44, - MINUS = 45, - EQUALS = 46, - LEFTBRACKET = 47, - RIGHTBRACKET = 48, - BACKSLASH = 49, - NONUSHASH = 50, - SEMICOLON = 51, - APOSTROPHE = 52, - GRAVE = 53, - COMMA = 54, - PERIOD = 55, - SLASH = 56, - CAPSLOCK = 57, + One = 30, + Two = 31, + Three = 32, + Four = 33, + Five = 34, + Six = 35, + Seven = 36, + Eight = 37, + Nine = 38, + Zero = 39, + Return = 40, + Escape = 41, + Backspace = 42, + Tab = 43, + Space = 44, + Minus = 45, + Equals = 46, + Leftbracket = 47, + Rightbracket = 48, + Backslash = 49, + Nonushash = 50, + Semicolon = 51, + Apostrophe = 52, + Grave = 53, + Comma = 54, + Period = 55, + Slash = 56, + Capslock = 57, F1 = 58, F2 = 59, F3 = 60, @@ -81,40 +81,40 @@ enum class Keys { F10 = 67, F11 = 68, F12 = 69, - PRINTSCREEN = 70, - SCROLLLOCK = 71, - PAUSE = 72, - INSERT = 73, - HOME = 74, - PAGEUP = 75, - DELETE = 76, - END = 77, - PAGEDOWN = 78, - RIGHT = 79, - LEFT = 80, - DOWN = 81, - UP = 82, - NUMLOCKCLEAR = 83, - KP_DIVIDE = 84, - KP_MULTIPLY = 85, - KP_MINUS = 86, - KP_PLUS = 87, - KP_ENTER = 88, - KP_1 = 89, - KP_2 = 90, - KP_3 = 91, - KP_4 = 92, - KP_5 = 93, - KP_6 = 94, - KP_7 = 95, - KP_8 = 96, - KP_9 = 97, - KP_0 = 98, - KP_PERIOD = 99, - NONUSBACKSLASH = 100, - APPLICATION = 101, - POWER = 102, - KP_EQUALS = 103, + Printscreen = 70, + Scrolllock = 71, + Pause = 72, + Insert = 73, + Home = 74, + Pageup = 75, + Delete = 76, + End = 77, + Pagedown = 78, + Right = 79, + Left = 80, + Down = 81, + Up = 82, + Numlockclear = 83, + KpDivide = 84, + KpMultiply = 85, + KpMinus = 86, + KpPlus = 87, + KpEnter = 88, + Kp1 = 89, + Kp2 = 90, + Kp3 = 91, + Kp4 = 92, + Kp5 = 93, + Kp6 = 94, + Kp7 = 95, + Kp8 = 96, + Kp9 = 97, + Kp0 = 98, + KpPeriod = 99, + Nonusbackslash = 100, + Application = 101, + Power = 102, + KpEquals = 103, F13 = 104, F14 = 105, F15 = 106, @@ -127,121 +127,121 @@ enum class Keys { F22 = 113, F23 = 114, F24 = 115, - EXECUTE = 116, - HELP = 117, - MENU = 118, - SELECT = 119, - STOP = 120, - AGAIN = 121, - UNDO = 122, - CUT = 123, - COPY = 124, - PASTE = 125, - FIND = 126, - MUTE = 127, - VOLUMEUP = 128, - VOLUMEDOWN = 129, - KP_COMMA = 133, - KP_EQUALSAS400 = 134, - ALTERASE = 153, - SYSREQ = 154, - CANCEL = 155, - CLEAR = 156, - PRIOR = 157, - RETURN2 = 158, - SEPARATOR = 159, - OUT = 160, - OPER = 161, - CLEARAGAIN = 162, - CRSEL = 163, - EXSEL = 164, - KP_00 = 176, - KP_000 = 177, - THOUSANDSSEPARATOR = 178, - DECIMALSEPARATOR = 179, - CURRENCYUNIT = 180, - CURRENCYSUBUNIT = 181, - KP_LEFTPAREN = 182, - KP_RIGHTPAREN = 183, - KP_LEFTBRACE = 184, - KP_RIGHTBRACE = 185, - KP_TAB = 186, - KP_BACKSPACE = 187, - KP_A = 188, - KP_B = 189, - KP_C = 190, - KP_D = 191, - KP_E = 192, - KP_F = 193, - KP_XOR = 194, - KP_POWER = 195, - KP_PERCENT = 196, - KP_LESS = 197, - KP_GREATER = 198, - KP_AMPERSAND = 199, - KP_DBLAMPERSAND = 200, - KP_VERTICALBAR = 201, - KP_DBLVERTICALBAR = 202, - KP_COLON = 203, - KP_HASH = 204, - KP_SPACE = 205, - KP_AT = 206, - KP_EXCLAM = 207, - KP_MEMSTORE = 208, - KP_MEMRECALL = 209, - KP_MEMCLEAR = 210, - KP_MEMADD = 211, - KP_MEMSUBTRACT = 212, - KP_MEMMULTIPLY = 213, - KP_MEMDIVIDE = 214, - KP_PLUSMINUS = 215, - KP_CLEAR = 216, - KP_CLEARENTRY = 217, - KP_BINARY = 218, - KP_OCTAL = 219, - KP_DECIMAL = 220, - KP_HEXADECIMAL = 221, - LCTRL = 224, - LSHIFT = 225, - LALT = 226, - LGUI = 227, - RCTRL = 228, - RSHIFT = 229, - RALT = 230, - RGUI = 231, - MODE = 257, - AUDIONEXT = 258, - AUDIOPREV = 259, - AUDIOSTOP = 260, - AUDIOPLAY = 261, - AUDIOMUTE = 262, - MEDIASELECT = 263, - WWW = 264, - MAIL = 265, - CALCULATOR = 266, - COMPUTER = 267, - AC_SEARCH = 268, - AC_HOME = 269, - AC_BACK = 270, - AC_FORWARD = 271, - AC_STOP = 272, - AC_REFRESH = 273, - AC_BOOKMARKS = 274, - BRIGHTNESSDOWN = 275, - BRIGHTNESSUP = 276, - DISPLAYSWITCH = 277, - KBDILLUMTOGGLE = 278, - KBDILLUMDOWN = 279, - KBDILLUMUP = 280, - EJECT = 281, - SLEEP = 282, - APP1 = 283, - APP2 = 284, - AUDIOREWIND = 285, - AUDIOFASTFORWARD = 286, - MAX = 512 + Execute = 116, + Help = 117, + Menu = 118, + Select = 119, + Stop = 120, + Again = 121, + Undo = 122, + Cut = 123, + Copy = 124, + Paste = 125, + Find = 126, + Mute = 127, + Volumeup = 128, + Volumedown = 129, + KpComma = 133, + KpEqualsas400 = 134, + Alterase = 153, + Sysreq = 154, + Cancel = 155, + Clear = 156, + Prior = 157, + Return2 = 158, + Separator = 159, + Out = 160, + Oper = 161, + Clearagain = 162, + Crsel = 163, + Exsel = 164, + Kp00 = 176, + Kp000 = 177, + Thousandsseparator = 178, + Decimalseparator = 179, + Currencyunit = 180, + Currencysubunit = 181, + KpLeftparen = 182, + KpRightparen = 183, + KpLeftbrace = 184, + KpRightbrace = 185, + KpTab = 186, + KpBackspace = 187, + KpA = 188, + KpB = 189, + KpC = 190, + KpD = 191, + KpE = 192, + KpF = 193, + KpXor = 194, + KpPower = 195, + KpPercent = 196, + KpLess = 197, + KpGreater = 198, + KpAmpersand = 199, + KpDblampersand = 200, + KpVerticalbar = 201, + KpDblverticalbar = 202, + KpColon = 203, + KpHash = 204, + KpSpace = 205, + KpAt = 206, + KpExclam = 207, + KpMemstore = 208, + KpMemrecall = 209, + KpMemclear = 210, + KpMemadd = 211, + KpMemsubtract = 212, + KpMemmultiply = 213, + KpMemdivide = 214, + KpPlusminus = 215, + KpClear = 216, + KpClearentry = 217, + KpBinary = 218, + KpOctal = 219, + KpDecimal = 220, + KpHexadecimal = 221, + Lctrl = 224, + Lshift = 225, + Lalt = 226, + Lgui = 227, + Rctrl = 228, + Rshift = 229, + Ralt = 230, + Rgui = 231, + Mode = 257, + Audionext = 258, + Audioprev = 259, + Audiostop = 260, + Audioplay = 261, + Audiomute = 262, + Mediaselect = 263, + Www = 264, + Mail = 265, + Calculator = 266, + Computer = 267, + AcSearch = 268, + AcHome = 269, + AcBack = 270, + AcForward = 271, + AcStop = 272, + AcRefresh = 273, + AcBookmarks = 274, + Brightnessdown = 275, + Brightnessup = 276, + Displayswitch = 277, + Kbdillumtoggle = 278, + Kbdillumdown = 279, + Kbdillumup = 280, + Eject = 281, + Sleep = 282, + App1 = 283, + App2 = 284, + Audiorewind = 285, + Audiofastforward = 286, + Max = 512 }; } // namespace afk -#endif // INCLUDE_SERVICES_INPUT_KEYBOARDKEYS_H_ +#endif // AFK_KEYBOARDKEYS_H diff --git a/include/services/input/KeyboardState.h b/include/services/input/KeyboardState.h index c6f52c0..9922e2a 100644 --- a/include/services/input/KeyboardState.h +++ b/include/services/input/KeyboardState.h @@ -10,8 +10,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_INPUT_KEYBOARDSTATE_H_ -#define INCLUDE_SERVICES_INPUT_KEYBOARDSTATE_H_ +#ifndef AFK_KEYBOARDSTATE_H +#define AFK_KEYBOARDSTATE_H #include "KeyboardKeys.h" @@ -23,25 +23,25 @@ namespace afk { */ struct KeyboardState { /// Individual key states - bool key[static_cast(Keys::MAX)] = {false}; + bool key[static_cast(Keys::Max)] = {false}; /// keys just pressed - bool keyPressed[static_cast(Keys::MAX)] = {false}; + bool keyPressed[static_cast(Keys::Max)] = {false}; /// keys just released - bool keyReleased[static_cast(Keys::MAX)] = {false}; + bool keyReleased[static_cast(Keys::Max)] = {false}; /// Id of last key pressed - int lastKeyPressed = static_cast(Keys::UNKNOWN); + int lastKeyPressed = static_cast(Keys::Unknown); /// Id of last key released - int lastKeyReleased = static_cast(Keys::UNKNOWN); + int lastKeyReleased = static_cast(Keys::Unknown); /// True if any key down bool anyKeyDown = false; /// Previous key states - bool lastTicksKey[static_cast(Keys::MAX)] = {false}; + bool lastTicksKey[static_cast(Keys::Max)] = {false}; /** * @brief Update the keyboard state @@ -49,12 +49,12 @@ struct KeyboardState { */ void update() { // Reset last key - lastKeyPressed = static_cast(Keys::UNKNOWN); - lastKeyReleased = static_cast(Keys::UNKNOWN); + lastKeyPressed = static_cast(Keys::Unknown); + lastKeyReleased = static_cast(Keys::Unknown); anyKeyDown = false; // Check key just pressed - for (int i = 0; i < static_cast(Keys::MAX); i++) { + for (int i = 0; i < static_cast(Keys::Max); i++) { // Clear old values keyPressed[i] = false; keyReleased[i] = false; @@ -64,13 +64,13 @@ struct KeyboardState { } // Pressed since last tick? - if (key[i] == true && lastTicksKey[i] == false) { + if (key[i] && !lastTicksKey[i]) { keyPressed[i] = true; lastKeyPressed = i; } // Released since last tick? - if (key[i] == false && lastTicksKey[i] == true) { + if (!key[i] && lastTicksKey[i]) { keyReleased[i] = true; lastKeyReleased = i; } @@ -83,4 +83,4 @@ struct KeyboardState { } // namespace afk -#endif // INCLUDE_SERVICES_INPUT_KEYBOARDSTATE_H_ +#endif // AFK_KEYBOARDSTATE_H diff --git a/include/services/input/MouseState.h b/include/services/input/MouseState.h index 92c5a7a..500c16f 100644 --- a/include/services/input/MouseState.h +++ b/include/services/input/MouseState.h @@ -10,8 +10,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_INPUT_MOUSESTATE_H_ -#define INCLUDE_SERVICES_INPUT_MOUSESTATE_H_ +#ifndef AFK_MOUSESTATE_H +#define AFK_MOUSESTATE_H #include #include @@ -19,10 +19,10 @@ namespace afk { enum class MouseButtons { - LEFT = 1, - CENTER = 2, - RIGHT = 3, - MAX = 4, + Left = 1, + Center = 2, + Right = 3, + Max = 4, }; /** @@ -40,25 +40,25 @@ struct MouseState { int z = 0; /// Previous mouse x position - int old_x = 0; + int oldX = 0; /// Previous mouse y position - int old_y = 0; + int oldY = 0; /// Individual button states - bool button[static_cast(MouseButtons::MAX)] = {false}; + bool button[static_cast(MouseButtons::Max)] = {false}; /// Buttons just pressed - bool down[static_cast(MouseButtons::MAX)] = {false}; + bool down[static_cast(MouseButtons::Max)] = {false}; /// Buttons just released - bool up[static_cast(MouseButtons::MAX)] = {false}; + bool up[static_cast(MouseButtons::Max)] = {false}; /// Mouse just moved bool moved = false; /// Previous button states - bool button_old[static_cast(MouseButtons::MAX)] = {false}; + bool buttonOld[static_cast(MouseButtons::Max)] = {false}; /** * @brief Update the mouse state @@ -66,34 +66,34 @@ struct MouseState { */ void update() { // Check if just moved - moved = old_x != x || old_y != y; - old_x = x; - old_y = y; + moved = oldX != x || oldY != y; + oldX = x; + oldY = y; // Check button just pressed - for (int i = 0; i < static_cast(MouseButtons::MAX); i++) { + for (int i = 0; i < static_cast(MouseButtons::Max); i++) { // Just up - if (button_old[i] && !button[i]) { + if (buttonOld[i] && !button[i]) { up[i] = true; } // Just down - if (!button_old[i] && button[i]) { + if (!buttonOld[i] && button[i]) { down[i] = true; } // Same - if (button_old[i] == button[i]) { + if (buttonOld[i] == button[i]) { up[i] = false; down[i] = false; } // Set new old values - button_old[i] = button[i]; + buttonOld[i] = button[i]; } } }; } // namespace afk -#endif // INCLUDE_SERVICES_INPUT_MOUSESTATE_H_ +#endif // AFK_MOUSESTATE_H diff --git a/include/services/logging/DebugLoggingService.h b/include/services/logging/DebugLoggingService.h index 5e1992c..df30092 100644 --- a/include/services/logging/DebugLoggingService.h +++ b/include/services/logging/DebugLoggingService.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_LOGGING_DEBUGLOGGINGSERVICE_H_ -#define INCLUDE_SERVICES_LOGGING_DEBUGLOGGINGSERVICE_H_ +#ifndef AFK_DEBUGLOGGINGSERVICE_H +#define AFK_DEBUGLOGGINGSERVICE_H #include @@ -34,4 +34,4 @@ class DebugLoggingService : public LoggingService { } // namespace afk -#endif // INCLUDE_SERVICES_LOGGING_DEBUGLOGGINGSERVICE_H_ +#endif // AFK_DEBUGLOGGINGSERVICE_H diff --git a/include/services/logging/LoggingService.h b/include/services/logging/LoggingService.h index 52da7c4..f20e81c 100644 --- a/include/services/logging/LoggingService.h +++ b/include/services/logging/LoggingService.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_LOGGING_LOGGINGSERVICE_H_ -#define INCLUDE_SERVICES_LOGGING_LOGGINGSERVICE_H_ +#ifndef AFK_LOGGINGSERVICE_H +#define AFK_LOGGINGSERVICE_H #include namespace afk { @@ -21,7 +21,7 @@ namespace afk { **/ class LoggingService { public: - virtual ~LoggingService() {} + virtual ~LoggingService() = default; /** * @brief Does nothing @@ -33,4 +33,4 @@ class LoggingService { } // namespace afk -#endif // INCLUDE_SERVICES_LOGGING_LOGGINGSERVICE_H_ +#endif // AFK_LOGGINGSERVICE_H diff --git a/include/services/scene/SceneService.h b/include/services/scene/SceneService.h index e89660e..7ef9c1c 100644 --- a/include/services/scene/SceneService.h +++ b/include/services/scene/SceneService.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_SCENE_SCENESERVICE_H_ -#define INCLUDE_SERVICES_SCENE_SCENESERVICE_H_ +#ifndef AFK_SCENESERVICE_H +#define AFK_SCENESERVICE_H #include #include @@ -41,11 +41,11 @@ class SceneService { /** * @brief Add scene to engine * - * @param scene_id to add to engine + * @param sceneId to add to engine */ template - void addScene(const std::string& scene_id) { - scenes.push_back({scene_id, new T()}); + void addScene(const std::string& sceneId) { + scenes.push_back({sceneId, new T()}); } /** @@ -69,9 +69,9 @@ class SceneService { * @brief Set the next scene to be loaded in. Upon calling, deletes current * scene * - * @param scene_id Id of next scene to load + * @param sceneId Id of next scene to load */ - void setNextScene(const std::string& scene_id); + void setNextScene(const std::string& sceneId); private: /** @@ -80,7 +80,7 @@ class SceneService { */ struct SceneType { /// Id of scene - std::string scene_id; + std::string sceneId; /// Scene object Scene* scene; @@ -93,21 +93,21 @@ class SceneService { void changeScene(); /// Current scene pointer - Scene* current_scene; + Scene* currentScene; /// List of scene ids std::vector scenes; /// Current scene - std::string scene_id; + std::string sceneId; /// Next scene to load - std::string next_scene; + std::string nextScene; /// Last tick - Uint32 last_tick; + uint32_t lastTick; }; } // namespace afk -#endif // INCLUDE_SERVICES_SCENE_SCENESERVICE_H_ +#endif // AFK_SCENESERVICE_H diff --git a/include/systems/CollisionSystem.h b/include/systems/CollisionSystem.h index ceb7de1..5dd0d01 100644 --- a/include/systems/CollisionSystem.h +++ b/include/systems/CollisionSystem.h @@ -8,14 +8,10 @@ * @copyright Copyright (c) 2022 * */ -#ifndef INCLUDE_SYSTEMS_COLLISION_SYSTEM_H_ -#define INCLUDE_SYSTEMS_COLLISION_SYSTEM_H_ +#ifndef AFK_COLLISIONSYSTEM_H +#define AFK_COLLISIONSYSTEM_H -#include - -#include "components/Collider.h" -#include "components/Transform.h" -#include "services/assets/AssetService.h" +#include "entities/Entity.h" namespace afk::systems { @@ -23,32 +19,8 @@ namespace afk::systems { * @brief CollisionSystem * */ -void collisionSystem(registry& registry) { - auto view = registry.view(); - - for (auto [entity, tran, collider] : view.each()) { - // Reset state - collider.colliding = false; - - for (auto [entity_other, tran_other, collider_other] : view.each()) { - // Check if is entity - if (entity == entity_other) { - continue; - } - - // Check if colliding - if (tran.position.x > tran_other.position.x + tran_other.size.x || - tran.position.x + tran.size.x < tran_other.position.x || - tran.position.y > tran_other.position.y + tran_other.size.y || - tran.position.y + tran.size.y < tran_other.position.y) { - continue; - } - - collider.colliding = true; - } - } -} +void collisionSystem(Registry& registry); } // namespace afk::systems -#endif // INCLUDE_SYSTEMS_COLLISION_SYSTEM_H_ \ No newline at end of file +#endif // AFK_COLLISIONSYSTEM_H \ No newline at end of file diff --git a/include/systems/ParticleSystem.h b/include/systems/ParticleSystem.h index 871926a..c9a4e2e 100644 --- a/include/systems/ParticleSystem.h +++ b/include/systems/ParticleSystem.h @@ -8,19 +8,11 @@ * @copyright Copyright (c) 2022 * */ -#ifndef INCLUDE_SYSTEMS_PARTICLE_SYSTEM_H_ -#define INCLUDE_SYSTEMS_PARTICLE_SYSTEM_H_ +#ifndef AFK_PARTICLESYSTEM_H +#define AFK_PARTICLESYSTEM_H -#include -#include -#include - -#include "common/math.h" -#include "common/random.h" -#include "components/Particle.h" -#include "components/ParticleEmitter.h" -#include "components/Transform.h" -#include "primitives/Primitives.h" +#include +#include "entities/Entity.h" #include "services/assets/AssetService.h" namespace afk::systems { @@ -29,95 +21,10 @@ namespace afk::systems { * @brief ParticleSystem * */ -void particleSystem(registry& registry, float delta) { - auto particle_view = registry.view(); - - int count = 0; - for (auto [entity, tran, particle] : particle_view.each()) { - tran.size.x = math::lerp(particle.start_size, particle.end_size, - particle.age / particle.lifespan); - tran.size.y = tran.size.x; - - particle.age += delta; - if (particle.age > particle.lifespan) { - registry.destroy(entity); - } - - count++; - } - - auto system_view = registry.view(); - - for (auto [entity, tran, emitter] : system_view.each()) { - emitter.counter += delta; - - while (emitter.counter > emitter.frequency && - emitter.templates.size() > 0) { - int index = random::randomInt(0, emitter.templates.size() - 1); - auto& [particle, physics] = emitter.templates.at(index); - - emitter.counter -= emitter.frequency; - - const float start_x = - tran.position.x + random::randomFloat(0, tran.size.x); - const float start_y = - tran.position.y + random::randomFloat(0, tran.size.y); - - const auto& particle_id = registry.create(); - registry.emplace(particle_id, particle); - registry.emplace(particle_id, physics); - registry.emplace( - particle_id, Vec3(start_x, start_y, tran.position.z), - Vec2(particle.start_size, particle.start_size)); - } - } -} - -void particleRenderSystem(registry& registry, AssetService& assetService) { - auto view = registry.view(); - - for (auto [entity, tran, particle] : view.each()) { - float life_percent = particle.age / particle.lifespan; - - // Lerp size - float size = - math::lerp(particle.start_size, particle.end_size, life_percent); - - // Lerp color - Uint8 r = - math::lerp(particle.start_color.r, particle.end_color.r, life_percent); - Uint8 g = - math::lerp(particle.start_color.g, particle.end_color.g, life_percent); - Uint8 b = - math::lerp(particle.start_color.b, particle.end_color.b, life_percent); - Uint8 a = - math::lerp(particle.start_color.a, particle.end_color.a, life_percent); - color::Color color = {r, g, b, a}; +void particleSystem(Registry& registry, uint32_t delta); - // Switch over type - switch (particle.type) { - case ParticleType::SQUARE: - primitives::rectfill(tran.position.x, tran.position.y, size, size, - color); - break; - case ParticleType::CIRCLE: - primitives::circle(tran.position.x, tran.position.y, size, color); - break; - case ParticleType::PIXEL: - primitives::pixel(tran.position.x, tran.position.y, color); - break; - case ParticleType::IMAGE: { - auto texture = assetService.getImage(particle.texture); - texture.drawEx(tran.position.x, tran.position.y, tran.size.x, - tran.size.y, tran.angle); - break; - } - default: - break; - } - } -} +void particleRenderSystem(Registry& registry, AssetService& assetService); } // namespace afk::systems -#endif // INCLUDE_SYSTEMS_PARTICLE_SYSTEM_H_ \ No newline at end of file +#endif // AFK_PARTICLESYSTEM_H \ No newline at end of file diff --git a/include/systems/PhysicsSystem.h b/include/systems/PhysicsSystem.h index 0f6bea3..55f5488 100644 --- a/include/systems/PhysicsSystem.h +++ b/include/systems/PhysicsSystem.h @@ -8,14 +8,10 @@ * @copyright Copyright (c) 2022 * */ -#ifndef INCLUDE_SYSTEMS_PHYSICS_SYSTEM_H_ -#define INCLUDE_SYSTEMS_PHYSICS_SYSTEM_H_ +#ifndef AFK_PHYSICSSYSTEM_H +#define AFK_PHYSICSSYSTEM_H -#include - -#include "components/Physics.h" -#include "components/Transform.h" -#include "services/assets/AssetService.h" +#include "entities/Entity.h" namespace afk::systems { @@ -23,19 +19,8 @@ namespace afk::systems { * @brief PhysicsSystem * */ -void physicsSystem(registry& registry, Uint32 delta) { - auto view = registry.view(); - - const float delta_seconds = delta / 1000.0f; - - for (auto [entity, tran, physics] : view.each()) { - tran.position.x += physics.velocity.x * delta_seconds; - tran.position.y += physics.velocity.y * delta_seconds; - physics.velocity.x += physics.acceleration.x * delta_seconds; - physics.velocity.y += physics.acceleration.y * delta_seconds; - } -} +void physicsSystem(Registry& registry, uint32_t delta); } // namespace afk::systems -#endif // INCLUDE_SYSTEMS_PHYSICS_SYSTEM_H_ \ No newline at end of file +#endif // AFK_PHYSICSSYSTEM_H \ No newline at end of file diff --git a/include/systems/RenderSystem.h b/include/systems/RenderSystem.h index da6cde5..db249eb 100644 --- a/include/systems/RenderSystem.h +++ b/include/systems/RenderSystem.h @@ -8,13 +8,12 @@ * @copyright Copyright (c) 2022 * */ -#ifndef INCLUDE_SYSTEMS_RENDER_SYSTEM_H_ -#define INCLUDE_SYSTEMS_RENDER_SYSTEM_H_ +#ifndef AFK_RENDERSYSTEM_H +#define AFK_RENDERSYSTEM_H #include -#include "components/Sprite.h" -#include "components/Transform.h" +#include "entities/Entity.h" #include "services/assets/AssetService.h" namespace afk::systems { @@ -23,16 +22,8 @@ namespace afk::systems { * @brief RenderSystem * */ -void renderSystem(registry& registry, AssetService& assetService) { - auto view = registry.view(); - - for (auto [entity, tran, sprite] : view.each()) { - auto texture = assetService.getImage(sprite.texture); - texture.drawEx(tran.position.x, tran.position.y, tran.size.x, tran.size.y, - tran.angle); - } -} +void renderSystem(Registry& registry, AssetService& assetService); } // namespace afk::systems -#endif // INCLUDE_SYSTEMS_RENDER_SYSTEM_H_ \ No newline at end of file +#endif // AFK_RENDERSYSTEM_H \ No newline at end of file diff --git a/include/systems/UISystem.h b/include/systems/UISystem.h index f729374..daf737b 100644 --- a/include/systems/UISystem.h +++ b/include/systems/UISystem.h @@ -8,15 +8,10 @@ * @copyright Copyright (c) 2022 * */ -#ifndef INCLUDE_SYSTEMS_UI_SYSTEM_H_ -#define INCLUDE_SYSTEMS_UI_SYSTEM_H_ +#ifndef AFK_UISYSTEM_H +#define AFK_UISYSTEM_H -#include - -#include "common/Color.h" -#include "components/Transform.h" -#include "components/ui/Button.h" -#include "components/ui/Label.h" +#include "entities/Entity.h" #include "services/assets/AssetService.h" #include "services/input/InputService.h" @@ -26,40 +21,10 @@ namespace afk::systems { * @brief UISystem * */ -void uiSystem(registry& registry, +void uiSystem(Registry& registry, AssetService& assetService, - InputService& inputService) { - auto view_labels = registry.view(); - for (auto [entity, tran, label] : view_labels.each()) { - auto font = assetService.getFont(label.font); - font.draw(tran.position.x, tran.position.y, label.text); - } - - auto view_buttons = registry.view(); - for (auto [entity, tran, button] : view_buttons.each()) { - // Draw button background - primitives::rectfill(tran.position.x, tran.position.y, tran.size.x, - tran.size.y, color::white); - - // Draw button border - primitives::rect(tran.position.x, tran.position.y, tran.size.x, tran.size.y, - color::black); - - // Draw text - auto font = assetService.getFont(button.font); - font.draw(tran.position.x, tran.position.y, button.text); - - if (button.onClick) { - if (inputService.mouseDown(MouseButtons::LEFT)) { - if (inputService.mouseOver(Vec2(tran.position.x, tran.position.y), - Vec2(tran.size.x, tran.size.y))) { - button.onClick(); - } - } - } - } -} + InputService& inputService); } // namespace afk::systems -#endif // INCLUDE_SYSTEMS_UI_SYSTEM_H_ \ No newline at end of file +#endif // AFK_UISYSTEM_H \ No newline at end of file diff --git a/include/ui/MessageBox.h b/include/ui/MessageBox.h index cd2968f..0d7ce4a 100644 --- a/include/ui/MessageBox.h +++ b/include/ui/MessageBox.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_ENTITIES_UI_MESSAGEBOX_H_ -#define INCLUDE_ENTITIES_UI_MESSAGEBOX_H_ +#ifndef AFK_MESSAGEBOX_H +#define AFK_MESSAGEBOX_H #include @@ -20,9 +20,9 @@ namespace afk { * */ enum class MessageBoxType { - WARN, - ERROR, - INFO, + Warn, + Error, + Info, }; /** @@ -77,7 +77,7 @@ class MessageBox { } // namespace afk -#endif // INCLUDE_ENTITIES_UI_MESSAGEBOX_H_ +#endif // AFK_MESSAGEBOX_H /** * @example ex_ui.cpp diff --git a/src/Game.cpp b/src/Game.cpp index 21d8a4e..0cfff82 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -10,6 +10,9 @@ */ #include "Game.h" +#include +#include + #include "common/Exceptions.h" #include "services/Services.h" #include "ui/MessageBox.h" @@ -39,7 +42,7 @@ void loop() { // Exit helper void showErrorDialog(const std::string& title, const std::string& message = "") { - MessageBox error(MessageBoxType::ERROR); + MessageBox error(MessageBoxType::Error); error.setTitle(title); error.setText(message); error.show(); @@ -64,14 +67,14 @@ std::string Game::getName() const { } // Start your engine! -void Game::start() { +void Game::start() const { try { #ifdef __EMSCRIPTEN__ emscripten_set_main_loop(loop, 0, 1); #else float timeDelta = 1000.0f / 30.0f; float timeAcc = 0.0f; - Uint32 startTime = 0; + uint32_t startTime; // Loop while (!closing) { @@ -92,17 +95,17 @@ void Game::start() { Services::getSceneService().draw(); // Inc accumulator - timeAcc += SDL_GetTicks() - startTime; + timeAcc += static_cast(SDL_GetTicks() - startTime); } #endif - } catch (const FileIOException& e) { + } catch (const FileIoException& e) { showErrorDialog("File Error", e.what()); } catch (const std::runtime_error& e) { showErrorDialog("Runtime Error", e.what()); } catch (const std::exception& e) { showErrorDialog("Exception", e.what()); } catch (...) { - showErrorDialog("Unknown Error", "An unknown error has occured :("); + showErrorDialog("Unknown Error", "An unknown error has occurred :("); } } diff --git a/src/assets/Font.cpp b/src/assets/Font.cpp index dfc9e7d..936e9b9 100644 --- a/src/assets/Font.cpp +++ b/src/assets/Font.cpp @@ -10,18 +10,17 @@ */ #include "assets/Font.h" -#include "common/Color.h" #include "common/Exceptions.h" #include "services/Services.h" namespace afk { // Constructor -Font::Font() : font(nullptr), font_size(0) {} +Font::Font() : font(nullptr), fontSize(0) {} // Constructor with path Font::Font(const std::string& path, const int size) - : font(nullptr), font_size(size) { + : font(nullptr), fontSize(size) { load(path, size); } @@ -48,8 +47,8 @@ int Font::getHeight() { } // Get Size of font -int Font::getSize() { - return font_size; +int Font::getSize() const { + return fontSize; } // Check if exists @@ -59,12 +58,12 @@ bool Font::exists() const { // Return width given text int Font::getWidth(const std::string& text) { - if (!font || text == "") { + if (!font || text.empty()) { return 0; } SDL_Renderer* renderer = Services::getDisplayService().getRenderer(); - SDL_Texture* texture = renderText(renderer, text.c_str(), color::black); + SDL_Texture* texture = renderText(renderer, text, color::black); int w; SDL_QueryTexture(texture, nullptr, nullptr, &w, nullptr); @@ -85,7 +84,7 @@ void Font::draw(const int x, } SDL_Renderer* renderer = Services::getDisplayService().getRenderer(); - SDL_Texture* texture = renderText(renderer, text.c_str(), colour); + SDL_Texture* texture = renderText(renderer, text, colour); int w, h; SDL_QueryTexture(texture, nullptr, nullptr, &w, &h); @@ -93,16 +92,16 @@ void Font::draw(const int x, SDL_Rect target = {x, y, w, h}; switch (align) { - case TextAlign::LEFT: - SDL_RenderCopy(renderer, texture, NULL, &target); + case TextAlign::Left: + SDL_RenderCopy(renderer, texture, nullptr, &target); break; - case TextAlign::RIGHT: + case TextAlign::Right: target.x = x - w; - SDL_RenderCopy(renderer, texture, NULL, &target); + SDL_RenderCopy(renderer, texture, nullptr, &target); break; - case TextAlign::CENTER: + case TextAlign::Center: target.x = x - w / 2; - SDL_RenderCopy(renderer, texture, NULL, &target); + SDL_RenderCopy(renderer, texture, nullptr, &target); break; default: break; @@ -114,19 +113,19 @@ void Font::draw(const int x, // Load font from file TTF_Font* Font::loadFont(const std::string& path, const int size) { // Attempt to load - TTF_Font* temp_font = TTF_OpenFont(path.c_str(), size); + TTF_Font* tempFont = TTF_OpenFont(path.c_str(), size); - if (!temp_font) { - throw FileIOException("There was an error loading font " + path + " (" + + if (!tempFont) { + throw FileIoException("There was an error loading font " + path + " (" + TTF_GetError() + ")"); } - return temp_font; + return tempFont; } // Render font to texture SDL_Texture* Font::renderText(SDL_Renderer* renderer, - const std::string text, + const std::string& text, const color::Color colour) { SDL_Surface* surface = TTF_RenderText_Solid( font, text.c_str(), {colour.r, colour.g, colour.b, colour.a}); diff --git a/src/assets/Sound.cpp b/src/assets/Sound.cpp index ca01fd7..534f968 100644 --- a/src/assets/Sound.cpp +++ b/src/assets/Sound.cpp @@ -17,12 +17,12 @@ namespace afk { // Set channel counter to 0 -Uint32 Sound::channel_counter = 0; +uint32_t Sound::channelCounter = 0; // Default constructor Sound::Sound() : sample(nullptr) { - channel = channel_counter; - Sound::channel_counter++; + channel = channelCounter; + Sound::channelCounter++; } // Constructor with path @@ -45,26 +45,26 @@ void Sound::play(const float gain, } // TODO(alegemaate): Frequency - int int_pan = (pan + 1.0f) * 128; - int int_gain = gain * 255; + int intPan = static_cast((pan + 1.0f) * 128.0f); + int intGain = static_cast(gain * 255.0f); - Mix_SetPanning(channel, int_pan, 255 - int_pan); - Mix_Volume(channel, int_gain); + Mix_SetPanning(channel, intPan, 255 - intPan); + Mix_Volume(channel, intGain); Mix_PlayChannel(channel, sample, loop); } // Load sample from file Mix_Chunk* Sound::loadSample(const std::string& path) { // Attempt to load - Mix_Chunk* temp_sample = Mix_LoadWAV(path.c_str()); + Mix_Chunk* tempSample = Mix_LoadWAV(path.c_str()); // Throw exception if file is not loaded - if (!temp_sample) { - throw FileIOException("There was an error loading sound " + path + " (" + + if (!tempSample) { + throw FileIoException("There was an error loading sound " + path + " (" + Mix_GetError() + ")"); } - return temp_sample; + return tempSample; } } // namespace afk diff --git a/src/assets/Stream.cpp b/src/assets/Stream.cpp index a79940d..5074812 100644 --- a/src/assets/Stream.cpp +++ b/src/assets/Stream.cpp @@ -53,15 +53,15 @@ bool Stream::isPlaying() const { // Load SDL sample from file Mix_Music* Stream::loadStream(const std::string& path) { // Attempt to load - Mix_Music* temp_stream = Mix_LoadMUS(path.c_str()); + Mix_Music* tempStream = Mix_LoadMUS(path.c_str()); // Throw exception if file is not loaded - if (!temp_stream) { - throw FileIOException("There was an error loading stream " + path + " (" + + if (!tempStream) { + throw FileIoException("There was an error loading stream " + path + " (" + Mix_GetError() + ")"); } - return temp_stream; + return tempStream; } } // namespace afk diff --git a/src/assets/Texture.cpp b/src/assets/Texture.cpp index 46cc9e3..9ab541f 100644 --- a/src/assets/Texture.cpp +++ b/src/assets/Texture.cpp @@ -12,7 +12,6 @@ #include -#include "common/Color.h" #include "common/Exceptions.h" #include "services/Services.h" @@ -33,22 +32,22 @@ void Texture::load(const std::string& path) { // Create texture with specified dimensions void Texture::create(const int width, const int height) { - SDL_Surface* temp_surface = + SDL_Surface* tempSurface = SDL_CreateRGBSurface(0, width, height, 32, 0, 0, 0, 0); - if (!temp_surface) { + if (!tempSurface) { throw InitException("There was an error creating surface "); } SDL_Renderer* renderer = Services::getDisplayService().getRenderer(); - SDL_Texture* temp_texture = - SDL_CreateTextureFromSurface(renderer, temp_surface); - if (!temp_texture) { + SDL_Texture* tempTexture = + SDL_CreateTextureFromSurface(renderer, tempSurface); + if (!tempTexture) { throw InitException("There was an error creating texture "); } - SDL_FreeSurface(temp_surface); + SDL_FreeSurface(tempSurface); - texture = temp_texture; + texture = tempTexture; } // Return height of loaded texture @@ -113,23 +112,23 @@ void Texture::drawEx(const int x, // Load an SDL texture from file SDL_Texture* Texture::loadTexture(const std::string& path) { // Attempt to load - SDL_Surface* temp_surface = IMG_Load(path.c_str()); - if (!temp_surface) { - throw FileIOException("There was an error loading surface " + path + " (" + + SDL_Surface* tempSurface = IMG_Load(path.c_str()); + if (!tempSurface) { + throw FileIoException("There was an error loading surface " + path + " (" + SDL_GetError() + ")"); } SDL_Renderer* renderer = Services::getDisplayService().getRenderer(); - SDL_Texture* temp_texture = - SDL_CreateTextureFromSurface(renderer, temp_surface); - if (!temp_texture) { + SDL_Texture* tempTexture = + SDL_CreateTextureFromSurface(renderer, tempSurface); + if (!tempTexture) { throw InitException("There was an error creating texture " + path + " (" + SDL_GetError() + ")"); } - SDL_FreeSurface(temp_surface); + SDL_FreeSurface(tempSurface); - return temp_texture; + return tempTexture; } } // namespace afk diff --git a/src/common/Color.cpp b/src/common/Color.cpp index 1413043..4b8a516 100644 --- a/src/common/Color.cpp +++ b/src/common/Color.cpp @@ -13,18 +13,18 @@ namespace afk::color { // Create color from RGB -Color rgb(const Uint8 r, const Uint8 g, const Uint8 b) { +Color rgb(const uint8_t r, const uint8_t g, const uint8_t b) { return rgba(r, g, b, 255); } // Create color from rgba -Color rgba(const Uint8 r, const Uint8 g, const Uint8 b, const Uint8 a) { +Color rgba(const uint8_t r, const uint8_t g, const uint8_t b, const uint8_t a) { return {r, g, b, a}; } // Create color from int -Color intToColor(const Uint32 colour) { - Color tempCol; +Color intToColor(const uint32_t colour) { + Color tempCol = {}; tempCol.r = (colour >> 16) & 0xFF; tempCol.g = (colour >> 8) & 0xFF; tempCol.b = colour & 0xFF; @@ -33,17 +33,20 @@ Color intToColor(const Uint32 colour) { } // Convert rgb to int -Uint32 rgbToInt(const Uint8 r, const Uint8 g, const Uint8 b) { +uint32_t rgbToInt(const uint8_t r, const uint8_t g, const uint8_t b) { return rgbaToInt(r, g, b, 255); } // Convert rgba to int -Uint32 rgbaToInt(const Uint8 r, const Uint8 g, const Uint8 b, const Uint8 a) { - return (Uint32)((a << 24) + (r << 16) + (g << 8) + (b << 0)); +uint32_t rgbaToInt(const uint8_t r, + const uint8_t g, + const uint8_t b, + const uint8_t a) { + return (uint32_t)((a << 24) + (r << 16) + (g << 8) + (b << 0)); } // Convert color to int -Uint32 colorToInt(const Color colour) { +uint32_t colorToInt(const Color colour) { return rgbaToInt(colour.r, colour.g, colour.b, colour.a); } diff --git a/src/common/random.cpp b/src/common/random.cpp index 78d87c9..fb2e86a 100644 --- a/src/common/random.cpp +++ b/src/common/random.cpp @@ -10,8 +10,6 @@ */ #include "common/random.h" -#include - namespace afk::random { // Init generator @@ -19,14 +17,14 @@ std::mt19937 rng = std::mt19937(std::random_device{}()); // Random Float float randomFloat(const float min, const float max) { - std::uniform_real_distribution float_dist{min, max}; - return float_dist(rng); + std::uniform_real_distribution floatDist{min, max}; + return floatDist(rng); } // Random Int int randomInt(const int min, const int max) { - std::uniform_int_distribution int_dist{min, max}; - return int_dist(rng); + std::uniform_int_distribution intDist{min, max}; + return intDist(rng); } } // namespace afk::random diff --git a/src/primitives/Primitives.cpp b/src/primitives/Primitives.cpp index 145dd25..11bb712 100644 --- a/src/primitives/Primitives.cpp +++ b/src/primitives/Primitives.cpp @@ -16,10 +16,10 @@ namespace afk::primitives { // Draw a rectangle -void rect(const Sint32 x, - const Sint32 y, - const Sint32 w, - const Sint32 h, +void rect(const int32_t x, + const int32_t y, + const int32_t w, + const int32_t h, color::Color colour) { SDL_Renderer* renderer = Services::getDisplayService().getRenderer(); @@ -29,10 +29,10 @@ void rect(const Sint32 x, } // Draw a filled rectangle -void rectfill(const Sint32 x, - const Sint32 y, - const Sint32 w, - const Sint32 h, +void rectfill(const int32_t x, + const int32_t y, + const int32_t w, + const int32_t h, color::Color colour) { SDL_Renderer* renderer = Services::getDisplayService().getRenderer(); diff --git a/src/scene/Scene.cpp b/src/scene/Scene.cpp index 9906d89..a34a5ed 100644 --- a/src/scene/Scene.cpp +++ b/src/scene/Scene.cpp @@ -29,7 +29,7 @@ Scene::Scene() config(afk::Services::getConfigService()) {} // Internal update method -void Scene::update(Uint32 delta) { +void Scene::update(uint32_t delta) { systems::collisionSystem(registry); systems::physicsSystem(registry, delta); systems::particleSystem(registry, delta); @@ -49,17 +49,17 @@ void Scene::stopInternal() { } // Register a new entity -entity Scene::createEntity() { +Entity Scene::createEntity() { return registry.create(); } // Remove an entity -void Scene::destroyEntity(entity entity) { +void Scene::destroyEntity(Entity entity) { registry.destroy(entity); } // Get a reference to the registry -registry& Scene::getRegistry() { +Registry& Scene::getRegistry() { return registry; } diff --git a/src/services/Services.cpp b/src/services/Services.cpp index c6e0190..e5b379b 100644 --- a/src/services/Services.cpp +++ b/src/services/Services.cpp @@ -10,50 +10,48 @@ */ #include "services/Services.h" -#include "common/Exceptions.h" - namespace afk { // Init services -DebugLoggingService Services::logging_service; -EventQueue Services::event_service; -SceneService Services::scene_service; -DisplayService Services::display_service; -InputService Services::input_service; -AudioService Services::audio_service; -AssetService Services::asset_service; -ConfigService Services::config_service; +DebugLoggingService Services::loggingService; +EventQueue Services::eventService; +SceneService Services::sceneService; +DisplayService Services::displayService; +InputService Services::inputService; +AudioService Services::audioService; +AssetService Services::assetService; +ConfigService Services::configService; AudioService& Services::getAudioService() { - return audio_service; + return audioService; } AssetService& Services::getAssetService() { - return asset_service; + return assetService; } DisplayService& Services::getDisplayService() { - return display_service; + return displayService; } ConfigService& Services::getConfigService() { - return config_service; + return configService; } LoggingService& Services::getLoggingService() { - return logging_service; + return loggingService; } InputService& Services::getInputService() { - return input_service; + return inputService; } SceneService& Services::getSceneService() { - return scene_service; + return sceneService; } EventQueue& Services::getEventQueue() { - return event_service; + return eventService; } } // namespace afk diff --git a/src/services/assets/AssetService.cpp b/src/services/assets/AssetService.cpp index cdacc2a..febca7f 100644 --- a/src/services/assets/AssetService.cpp +++ b/src/services/assets/AssetService.cpp @@ -11,8 +11,6 @@ #include "services/assets/AssetService.h" #include -#include -#include #include #include "common/Exceptions.h" @@ -38,21 +36,16 @@ AssetService::AssetService() { } } -// Destructor -AssetService::~AssetService() { - // Todo cleanup -} - // Load image from disk and assign key void AssetService::loadImage(const std::string& key, const std::string& path) { Services::getLoggingService().log("[Asset Manager] Loading image: " + key); try { - loaded_image[key] = Texture(path); + loadedImage[key] = Texture(path); } catch (const std::runtime_error& e) { - throw FileIOException(e.what()); + throw FileIoException(e.what()); } catch (...) { - throw FileIOException("Could not load image " + key); + throw FileIoException("Could not load image " + key); } } @@ -61,11 +54,11 @@ void AssetService::loadAudio(const std::string& key, const std::string& path) { Services::getLoggingService().log("[Asset Manager] Loading audio: " + key); try { - loaded_audio[key] = Sound(path); + loadedAudio[key] = Sound(path); } catch (const std::runtime_error& e) { - throw FileIOException(e.what()); + throw FileIoException(e.what()); } catch (...) { - throw FileIOException("Could not load sound " + key); + throw FileIoException("Could not load sound " + key); } } @@ -76,11 +69,11 @@ void AssetService::loadFont(const std::string& key, Services::getLoggingService().log("[Asset Manager] Loading font: " + key); try { - loaded_font[key] = Font(path, size); + loadedFont[key] = Font(path, size); } catch (const std::runtime_error& e) { - throw FileIOException(e.what()); + throw FileIoException(e.what()); } catch (...) { - throw FileIOException("Could not load font " + key); + throw FileIoException("Could not load font " + key); } } @@ -89,18 +82,18 @@ void AssetService::loadStream(const std::string& key, const std::string& path) { Services::getLoggingService().log("[Asset Manager] Loading stream: " + key); try { - loaded_stream[key] = Stream(path); + loadedStream[key] = Stream(path); } catch (const std::runtime_error& e) { - throw FileIOException(e.what()); + throw FileIoException(e.what()); } catch (...) { - throw FileIOException("Could not load stream " + key); + throw FileIoException("Could not load stream " + key); } } // Get image reference const Texture& AssetService::getImage(const std::string& key) { try { - return loaded_image.at(key); + return loadedImage.at(key); } catch (const std::out_of_range&) { throw KeyLookupException("Could not find image " + key); } @@ -109,7 +102,7 @@ const Texture& AssetService::getImage(const std::string& key) { // Get audio reference const Sound& AssetService::getAudio(const std::string& key) { try { - return loaded_audio.at(key); + return loadedAudio.at(key); } catch (const std::out_of_range&) { throw KeyLookupException("Could not find sound " + key); } @@ -118,7 +111,7 @@ const Sound& AssetService::getAudio(const std::string& key) { // Get font reference const Font& AssetService::getFont(const std::string& key) { try { - return loaded_font.at(key); + return loadedFont.at(key); } catch (const std::out_of_range&) { throw KeyLookupException("Could not find font " + key); } @@ -127,7 +120,7 @@ const Font& AssetService::getFont(const std::string& key) { // Get stream reference const Stream& AssetService::getStream(const std::string& key) { try { - return loaded_stream.at(key); + return loadedStream.at(key); } catch (const std::out_of_range&) { throw KeyLookupException("Could not find stream " + key); } diff --git a/src/services/config/ConfigService.cpp b/src/services/config/ConfigService.cpp index cda526a..6caa5a3 100644 --- a/src/services/config/ConfigService.cpp +++ b/src/services/config/ConfigService.cpp @@ -19,7 +19,7 @@ namespace afk { // Constructor -ConfigService::ConfigService() : autosave(false) { +ConfigService::ConfigService() : autoSave(false) { Services::getLoggingService().log("[Config Service]: Starting up"); } @@ -34,19 +34,19 @@ void ConfigService::load(const std::string& path) { std::ifstream fileStream(path); if (!fileStream.is_open()) { - throw FileIOException("Could not open file from " + path); + throw FileIoException("Could not open file from " + path); } while (getline(fileStream, line)) { // Split string - int delimLoc = line.find("="); - if (delimLoc == -1) { + int delimiterLocation = line.find('='); + if (delimiterLocation == -1) { continue; } // Get values - std::string key = line.substr(0, delimLoc); - std::string value = line.substr(delimLoc + 1, line.length()); + std::string key = line.substr(0, delimiterLocation); + std::string value = line.substr(delimiterLocation + 1, line.length()); // Conversion settings[key] = value; @@ -59,12 +59,12 @@ void ConfigService::load(const std::string& path) { "[Setting Manager] Loaded settings from file " + path); // Set internal file name - file_name = path; + fileName = path; } // Save file void ConfigService::save() { - save(file_name); + save(fileName); } void ConfigService::save(const std::string& path) { @@ -75,7 +75,7 @@ void ConfigService::save(const std::string& path) { std::ofstream fileStream(path); if (!fileStream.is_open()) { - throw FileIOException("Could not open file from path " + path); + throw FileIoException("Could not open file from path " + path); } for (auto const& entry : this->settings) { @@ -85,9 +85,9 @@ void ConfigService::save(const std::string& path) { fileStream.close(); } -// Set autosave -void ConfigService::setAutosave(const bool autosave) { - this->autosave = autosave; +// Set auto save +void ConfigService::setAutoSave(const bool autoSave) { + this->autoSave = autoSave; } } // namespace afk diff --git a/src/services/display/DisplayService.cpp b/src/services/display/DisplayService.cpp index 6b5fd66..e8b101f 100644 --- a/src/services/display/DisplayService.cpp +++ b/src/services/display/DisplayService.cpp @@ -17,15 +17,12 @@ #include "common/Exceptions.h" #include "scene/Scene.h" -#include "common/Color.h" -#include "services/Services.h" - namespace afk { // Setup DisplayService -DisplayService::DisplayService() : clear_color(color::white) { +DisplayService::DisplayService() : clearColor(color::white) { // Set initial time - old_time = SDL_GetTicks(); + oldTime = SDL_GetTicks(); } // Cleanup window @@ -40,78 +37,78 @@ DisplayService::~DisplayService() { } } -void DisplayService::draw(Scene* current_scene) { +void DisplayService::draw(Scene* currentScene) { if (!window || !renderer) { return; } // Render a frame - SDL_SetRenderDrawColor(renderer, clear_color.r, clear_color.g, clear_color.b, - clear_color.a); + SDL_SetRenderDrawColor(renderer, clearColor.r, clearColor.g, clearColor.b, + clearColor.a); SDL_RenderClear(renderer); - current_scene->draw(); + currentScene->draw(); // Flip SDL_RenderPresent(renderer); // Update frame index - frames_array[frame_index] = SDL_GetTicks() - old_time; - old_time = SDL_GetTicks(); - frame_index = (frame_index + 1) % FRAME_BUFFER_SIZE; + framesArray[frameIndex] = SDL_GetTicks() - oldTime; + oldTime = SDL_GetTicks(); + frameIndex = (frameIndex + 1) % frameBufferSize; - float fps_total = 0; - for (Uint32 i = 0; i < FRAME_BUFFER_SIZE; ++i) { - fps_total += frames_array[i]; + float fpsTotal = 0; + for (unsigned int i : framesArray) { + fpsTotal += i; } // FPS = average - fps = 1000.0f / (fps_total / FRAME_BUFFER_SIZE); + fps = 1000.0f / (fpsTotal / frameBufferSize); } // Returns current display mode DisplayMode DisplayService::getDisplayMode() const { - return display_mode; + return displayMode; } // Gets draw width -Uint32 DisplayService::getDrawWidth() const { - return draw_w; +uint32_t DisplayService::getDrawWidth() const { + return drawW; } // Gets draw height -Uint32 DisplayService::getDrawHeight() const { - return draw_h; +uint32_t DisplayService::getDrawHeight() const { + return drawH; } // Gets translation x -Uint32 DisplayService::getTranslationX() const { - return translation_x; +uint32_t DisplayService::getTranslationX() const { + return translationX; } // Gets translation y -Uint32 DisplayService::getTranslationY() const { - return translation_y; +uint32_t DisplayService::getTranslationY() const { + return translationY; } // Gets scale width -Uint32 DisplayService::getDisplayServiceWidth() const { - return window_w; +uint32_t DisplayService::getDisplayServiceWidth() const { + return windowW; } // Gets scale height -Uint32 DisplayService::getDisplayServiceHeight() const { - return window_h; +uint32_t DisplayService::getDisplayServiceHeight() const { + return windowH; } // Gets scale x float DisplayService::getScaleX() const { - return scale_x; + return scaleX; } // Gets scale y float DisplayService::getScaleY() const { - return scale_y; + return scaleY; } // Hide mouse from display @@ -125,64 +122,64 @@ void DisplayService::showMouse() { } // Resize window -void DisplayService::resize(const Uint32 window_w, const Uint32 window_h) { +void DisplayService::resize(const uint32_t windowW, const uint32_t windowH) { // Get monitor width SDL_DisplayMode info; SDL_GetCurrentDisplayMode(0, &info); // Window mode - switch (display_mode) { - // Fullscreen windowed stretch - case DisplayMode::FULLSCREEN_WINDOW_STRETCH: + switch (displayMode) { + // Full screen windowed stretch + case DisplayMode::FullScreenWindowStretch: // Set flags SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); // Set up screen size and positions setWindowSize(info.w, info.h); - setScale(static_cast(window_w) / draw_w, - static_cast(window_h) / draw_h); + setScale(static_cast(windowW) / drawW, + static_cast(windowH) / drawH); setTranslation(0.0f, 0.0f); break; - // Fullscreen window center - case DisplayMode::FULLSCREEN_WINDOW_CENTER: + // Full screen window center + case DisplayMode::FullScreenWindowCenter: // Set flags SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); // Set up screen size and positions setWindowSize(info.w, info.h); setScale(1.0f, 1.0f); - setTranslation((window_w - scale_x * draw_w) / 2, - (window_h - scale_y * draw_h) / 2); + setTranslation((windowW - scaleX * drawW) / 2, + (windowH - scaleY * drawH) / 2); break; - // Fullscreen window center - case DisplayMode::FULLSCREEN_WINDOW_LETTERBOX: + // Full screen window center + case DisplayMode::FullScreenWindowLetterbox: // Set flags SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); // Set up screen size and positions setWindowSize(info.w, info.h); - setScale(std::min(static_cast(window_w) / draw_w, - static_cast(window_h) / draw_h), - std::min(static_cast(window_w) / draw_w, - static_cast(window_h) / draw_h)); - setTranslation((window_w - scale_x * draw_w) / 2, - (window_h - scale_y * draw_h) / 2); + setScale(std::min(static_cast(windowW) / drawW, + static_cast(windowH) / drawH), + std::min(static_cast(windowW) / drawW, + static_cast(windowH) / drawH)); + setTranslation((windowW - scaleX * drawW) / 2, + (windowH - scaleY * drawH) / 2); break; // Windowed - case DisplayMode::WINDOWED: + case DisplayMode::Windowed: // Set flags SDL_SetWindowFullscreen(window, 0); // Set up screen size and positions - setWindowSize(window_w, window_h); - setScale(static_cast(window_w) / draw_w, - static_cast(window_h) / draw_h); + setWindowSize(windowW, windowH); + setScale(static_cast(windowW) / drawW, + static_cast(windowH) / drawH); setTranslation(0.0f, 0.0f); break; @@ -193,31 +190,33 @@ void DisplayService::resize(const Uint32 window_w, const Uint32 window_h) { } // Set scale - SDL_RenderSetScale(renderer, draw_w, draw_h); + SDL_RenderSetScale(renderer, drawW, drawH); } // Set window size -void DisplayService::setWindowSize(const Uint32 width, const Uint32 height) { - window_w = width; - window_h = height; +void DisplayService::setWindowSize(const uint32_t width, + const uint32_t height) { + windowW = width; + windowH = height; } // Set buffer size -void DisplayService::setBufferSize(const Uint32 width, const Uint32 height) { - draw_w = width; - draw_h = height; +void DisplayService::setBufferSize(const uint32_t width, + const uint32_t height) { + drawW = width; + drawH = height; } // Set scale void DisplayService::setScale(const float width, const float height) { - scale_x = width; - scale_y = height; + scaleX = width; + scaleY = height; } // Set translation -void DisplayService::setTranslation(const Uint32 x, const Uint32 y) { - translation_x = x; - translation_y = y; +void DisplayService::setTranslation(const uint32_t x, const uint32_t y) { + translationX = x; + translationY = y; } // Set window @@ -229,7 +228,7 @@ void DisplayService::setTitle(const std::string& title) { void DisplayService::setIcon(const std::string& path) { SDL_Surface* icon = IMG_Load(path.c_str()); if (!icon) { - throw FileIOException("Could not load icon " + path); + throw FileIoException("Could not load icon " + path); } SDL_SetWindowIcon(window, icon); SDL_FreeSurface(icon); @@ -237,7 +236,7 @@ void DisplayService::setIcon(const std::string& path) { // Set clear colour void DisplayService::setBackgroundColor(const color::Color& color) { - clear_color = color; + clearColor = color; } // Get fps @@ -263,15 +262,15 @@ void DisplayService::setMode(const DisplayMode mode) { } // Set mode - display_mode = mode; + displayMode = mode; // Resize window - resize(window_w, window_h); + resize(windowW, windowH); // Create display window = SDL_CreateWindow("", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, - window_w, window_h, SDL_WINDOW_RESIZABLE); + windowW, windowH, SDL_WINDOW_RESIZABLE); if (!window) { throw InitException("Could not create window"); } diff --git a/src/services/events/EventQueue.cpp b/src/services/events/EventQueue.cpp index 57bce23..9fdec82 100644 --- a/src/services/events/EventQueue.cpp +++ b/src/services/events/EventQueue.cpp @@ -10,10 +10,8 @@ */ #include #include -#include #include "services/Services.h" -#include "services/events/EventQueue.h" namespace afk { @@ -45,37 +43,37 @@ void EventQueue::registerService(Service* service) { void EventQueue::unregisterService(Service* service) { Services::getLoggingService().log("[" + service->getName() + "] Shutting down"); - services.erase(std::remove(services.begin(), services.end(), service)); + services.erase(std::remove(services.begin(), services.end(), service), services.end()); } // Register user timer -SDL_TimerID EventQueue::registerTimer(const Uint32 time, const char code) { +SDL_TimerID EventQueue::registerTimer(const uint32_t time, const char code) { void* c = malloc(sizeof(code)); memcpy(c, &code, sizeof(code)); - SDL_TimerID timer_id = SDL_AddTimer(time, EventQueue::timerCallback, c); - return timer_id; + SDL_TimerID timerId = SDL_AddTimer(time, EventQueue::timerCallback, c); + return timerId; } // Unregister user timer -void EventQueue::unregisterTimer(const SDL_TimerID timer_id) { - SDL_RemoveTimer(timer_id); +void EventQueue::unregisterTimer(const SDL_TimerID timerId) { + SDL_RemoveTimer(timerId); } // Timer callback -Uint32 EventQueue::timerCallback(Uint32 interval, void* param) { +uint32_t EventQueue::timerCallback(uint32_t interval, void* param) { SDL_Event event; - SDL_UserEvent userevent; + SDL_UserEvent userEvent; char code = *(reinterpret_cast(param)); - userevent.type = SDL_USEREVENT; - userevent.code = code; - userevent.data1 = NULL; - userevent.data2 = NULL; + userEvent.type = SDL_USEREVENT; + userEvent.code = code; + userEvent.data1 = nullptr; + userEvent.data2 = nullptr; event.type = SDL_USEREVENT; - event.user = userevent; + event.user = userEvent; SDL_PushEvent(&event); return interval; diff --git a/src/services/input/InputService.cpp b/src/services/input/InputService.cpp index fa61fe1..64adb41 100644 --- a/src/services/input/InputService.cpp +++ b/src/services/input/InputService.cpp @@ -14,7 +14,7 @@ #include "common/Exceptions.h" #include "services/Services.h" -const float JOYSTICK_DEADZONE = 0.6f; +const float JOYSTICK_DEAD_ZONE = 0.6f; namespace afk { @@ -24,10 +24,10 @@ InputService::InputService() { Services::getEventQueue().registerService(this); // Set joystick enabled - joystick_state.enabled = SDL_NumJoysticks() > 0; + joystickState.enabled = SDL_NumJoysticks() > 0; // Open joystick if enabled - if (joystick_state.enabled) { + if (joystickState.enabled) { SDL_JoystickOpen(0); } } @@ -74,20 +74,20 @@ void InputService::notify(const SDL_Event& event) { // Update routine void InputService::update() { - mouse_state.update(); - keyboard_state.update(); - joystick_state.update(); + mouseState.update(); + keyboardState.update(); + joystickState.update(); } // Joystick button event -void InputService::onJoystickEvent(const Uint32 event_type, +void InputService::onJoystickEvent(const uint32_t eventType, const SDL_JoyButtonEvent event) { - switch (event_type) { + switch (eventType) { case SDL_JOYBUTTONDOWN: - joystick_state.button[event.button] = true; + joystickState.button[event.button] = true; break; case SDL_JOYBUTTONUP: - joystick_state.button[event.button] = false; + joystickState.button[event.button] = false; break; default: break; @@ -97,38 +97,38 @@ void InputService::onJoystickEvent(const Uint32 event_type, // Joystick axis event void InputService::onJoystickEvent(const SDL_JoyAxisEvent event) { // Translated axis - const int trans_axis = (JOY_MAX_AXES + event.axis) * 2; + const int transAxis = (JOY_MAX_AXES + event.axis) * 2; // Check if moved enough - if (event.value > JOYSTICK_DEADZONE) { - joystick_state.stick[trans_axis] = true; - } else if (event.value < -JOYSTICK_DEADZONE) { - joystick_state.stick[trans_axis + 1] = true; + if (event.value > JOYSTICK_DEAD_ZONE) { + joystickState.stick[transAxis] = true; + } else if (event.value < -JOYSTICK_DEAD_ZONE) { + joystickState.stick[transAxis + 1] = true; } else { - joystick_state.stick[trans_axis] = false; - joystick_state.stick[trans_axis + 1] = false; + joystickState.stick[transAxis] = false; + joystickState.stick[transAxis + 1] = false; } } -// Joystick reconfig event +// Joystick reconfigure event void InputService::onJoystickReconfigureEvent() { - joystick_state.enabled = SDL_NumJoysticks() > 0; + joystickState.enabled = SDL_NumJoysticks() > 0; // Open joystick if enabled - if (joystick_state.enabled) { + if (joystickState.enabled) { SDL_JoystickOpen(0); } } // Keyboard event -void InputService::onKeyboardEvent(const Uint32 event_type, +void InputService::onKeyboardEvent(const uint32_t eventType, const SDL_KeyboardEvent event) { - switch (event_type) { + switch (eventType) { case SDL_KEYDOWN: - keyboard_state.key[event.keysym.scancode] = true; + keyboardState.key[event.keysym.scancode] = true; break; case SDL_KEYUP: - keyboard_state.key[event.keysym.scancode] = false; + keyboardState.key[event.keysym.scancode] = false; break; default: break; @@ -137,29 +137,29 @@ void InputService::onKeyboardEvent(const Uint32 event_type, // Mouse axis handler void InputService::onMouseEvent(const SDL_MouseMotionEvent event) { - mouse_state.x = (event.x - Services::getDisplayService().getTranslationX()) / + mouseState.x = (event.x - Services::getDisplayService().getTranslationX()) / Services::getDisplayService().getScaleX(); - mouse_state.y = (event.y - Services::getDisplayService().getTranslationY()) / + mouseState.y = (event.y - Services::getDisplayService().getTranslationY()) / Services::getDisplayService().getScaleY(); } // Mouse axis handler void InputService::onMouseEvent(const SDL_MouseWheelEvent event) { - mouse_state.z = event.y; + mouseState.z = event.y; } // Mouse button handler -void InputService::onMouseEvent(const Uint32 event_type, +void InputService::onMouseEvent(const uint32_t eventType, const SDL_MouseButtonEvent event) { - switch (event_type) { + switch (eventType) { case SDL_MOUSEBUTTONUP: - if (event.button < static_cast(MouseButtons::MAX)) { - mouse_state.button[event.button] = false; + if (event.button < static_cast(MouseButtons::Max)) { + mouseState.button[event.button] = false; } break; case SDL_MOUSEBUTTONDOWN: - if (event.button < static_cast(MouseButtons::MAX)) { - mouse_state.button[event.button] = true; + if (event.button < static_cast(MouseButtons::Max)) { + mouseState.button[event.button] = true; } break; default: @@ -169,71 +169,71 @@ void InputService::onMouseEvent(const Uint32 event_type, // Get key just down state bool InputService::keyPressed(const Keys key) const { - if (key > Keys::MAX) { + if (key > Keys::Max) { return false; } - return keyboard_state.keyPressed[static_cast(key)]; + return keyboardState.keyPressed[static_cast(key)]; } // Get key just up state bool InputService::keyReleased(const Keys key) const { - if (key > Keys::MAX) { + if (key > Keys::Max) { return false; } - return keyboard_state.keyReleased[static_cast(key)]; + return keyboardState.keyReleased[static_cast(key)]; } // Get key down state bool InputService::keyDown(const Keys key) const { - if (key > Keys::MAX) { + if (key > Keys::Max) { return false; } - return keyboard_state.key[static_cast(key)]; + return keyboardState.key[static_cast(key)]; } // Get any key down state bool InputService::anyKeyDown() const { - return keyboard_state.anyKeyDown; + return keyboardState.anyKeyDown; } // Get last key pressed int InputService::lastKeyPressed() const { - return keyboard_state.lastKeyPressed; + return keyboardState.lastKeyPressed; } // Get last key pressed int InputService::lastKeyReleased() const { - return keyboard_state.lastKeyReleased; + return keyboardState.lastKeyReleased; } // Get mouse button just down state bool InputService::mousePressed(const MouseButtons button) const { - if (button > MouseButtons::MAX) { + if (button > MouseButtons::Max) { return false; } - return mouse_state.down[static_cast(button)]; + return mouseState.down[static_cast(button)]; } // Get mouse button just up state bool InputService::mouseReleased(const MouseButtons button) const { - if (button > MouseButtons::MAX) { + if (button > MouseButtons::Max) { return false; } - return mouse_state.up[static_cast(button)]; + return mouseState.up[static_cast(button)]; } // Get mouse button down state bool InputService::mouseDown(const MouseButtons button) const { - if (button > MouseButtons::MAX) { + if (button > MouseButtons::Max) { return false; } - return mouse_state.button[static_cast(button)]; + return mouseState.button[static_cast(button)]; } // Get mouse button down state bool InputService::mouseOver(const Vec2 position, const Vec2 size) const { - if (mouse_state.x < position.x || mouse_state.x > position.x + size.x || - mouse_state.y < position.y || mouse_state.y > position.y + size.y) { + if (mouseState.x < position.x || mouseState.x > position.x + size.x || + mouseState.y < position.y || mouseState.y > position.y + size.y) { return false; } return true; @@ -241,32 +241,32 @@ bool InputService::mouseOver(const Vec2 position, const Vec2 size) const { // Get mouse x position int InputService::mouseX() const { - return mouse_state.x; + return mouseState.x; } // Get mouse y position int InputService::mouseY() const { - return mouse_state.y; + return mouseState.y; } // Check if joystick enabled bool InputService::joyEnabled() const { - return joystick_state.enabled; + return joystickState.enabled; } // Get joy button just down state bool InputService::joyPressed(const JoystickButtons button) const { - return joystick_state.buttonPressed[static_cast(button)]; + return joystickState.buttonPressed[static_cast(button)]; } // Get joy button just up state bool InputService::joyReleased(const JoystickButtons button) const { - return joystick_state.buttonReleased[static_cast(button)]; + return joystickState.buttonReleased[static_cast(button)]; } // Get joy button down state bool InputService::joyDown(const JoystickButtons button) const { - return joystick_state.button[static_cast(button)]; + return joystickState.button[static_cast(button)]; } } // namespace afk diff --git a/src/services/scene/SceneService.cpp b/src/services/scene/SceneService.cpp index ba40b35..b2b0aed 100644 --- a/src/services/scene/SceneService.cpp +++ b/src/services/scene/SceneService.cpp @@ -14,19 +14,15 @@ #include "common/Exceptions.h" #include "scene/Scene.h" -#include "services/Services.h" namespace afk { // Register events SceneService::SceneService() - : current_scene(nullptr), - scene_id(""), - next_scene(""), - last_tick(SDL_GetTicks()) {} + : currentScene(nullptr), lastTick(SDL_GetTicks()) {} // Unregister events -SceneService::~SceneService() {} +SceneService::~SceneService() = default; // Update scene void SceneService::update() { @@ -34,64 +30,64 @@ void SceneService::update() { changeScene(); // Update scene - if (current_scene) { - Uint32 delta = SDL_GetTicks() - last_tick; - current_scene->update(delta); + if (currentScene) { + uint32_t delta = SDL_GetTicks() - lastTick; + currentScene->update(delta); } - last_tick = SDL_GetTicks(); + lastTick = SDL_GetTicks(); } // Update scene void SceneService::draw() { - Services::getDisplayService().draw(current_scene); + Services::getDisplayService().draw(currentScene); } // Get scene Scene* SceneService::getSceneService() { - return this->current_scene; + return this->currentScene; } // Change game screen void SceneService::changeScene() { // If the scene needs not to be changed - if (next_scene == "") { + if (nextScene.empty()) { return; } // Cleanup current scene - if (current_scene) { - current_scene->stop(); - current_scene->stopInternal(); + if (currentScene) { + currentScene->stop(); + currentScene->stopInternal(); } // Find scene auto it = std::find_if( scenes.begin(), scenes.end(), - [this](const SceneType& scene) { return scene.scene_id == next_scene; }); + [this](const SceneType& scene) { return scene.sceneId == nextScene; }); // Dad not found if (it == scenes.end()) { - throw SceneLookupException("Scene not found (" + next_scene + ")"); + throw SceneLookupException("Scene not found (" + nextScene + ")"); } // Create scene - current_scene = (*it).scene; - current_scene->start(); + currentScene = (*it).scene; + currentScene->start(); // Change the current scene ID - scene_id = next_scene; + sceneId = nextScene; // NULL the next scene ID - next_scene = ""; + nextScene = ""; } // Set next scene to load -void SceneService::setNextScene(const std::string& scene_id) { +void SceneService::setNextScene(const std::string& sceneId) { // If the user doesn't want to exit - if (next_scene != "exit") { + if (nextScene != "exit") { // Set the next scene - next_scene = scene_id; + nextScene = sceneId; } } diff --git a/src/systems/CollisionSystem.cpp b/src/systems/CollisionSystem.cpp new file mode 100644 index 0000000..adf61c8 --- /dev/null +++ b/src/systems/CollisionSystem.cpp @@ -0,0 +1,44 @@ +/** + * @file CollisionSystem.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Implementation of CollisionSystem + * @version 0.1 + * @date 2022-04-22 + * + * @copyright Copyright (c) 2022 + * + */ +#include "systems/CollisionSystem.h" + +#include "components/Collider.h" +#include "components/Transform.h" + +namespace afk::systems { + +void collisionSystem(Registry& registry) { + auto view = registry.view(); + + for (auto [entity, tran, collider] : view.each()) { + // Reset state + collider.colliding = false; + + for (auto [entityOther, tranOther, colliderOther] : view.each()) { + // Check if is entity + if (entity == entityOther) { + continue; + } + + // Check if colliding + if (tran.position.x > tranOther.position.x + tranOther.size.x || + tran.position.x + tran.size.x < tranOther.position.x || + tran.position.y > tranOther.position.y + tranOther.size.y || + tran.position.y + tran.size.y < tranOther.position.y) { + continue; + } + + collider.colliding = true; + } + } +} + +} // namespace afk::system \ No newline at end of file diff --git a/src/systems/ParticleSystem.cpp b/src/systems/ParticleSystem.cpp new file mode 100644 index 0000000..c01376c --- /dev/null +++ b/src/systems/ParticleSystem.cpp @@ -0,0 +1,115 @@ +/** + * @file ParticleSystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of updating and rendering particles + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#include "systems/ParticleSystem.h" + +#include "common/math.h" +#include "common/random.h" +#include "components/Particle.h" +#include "components/ParticleEmitter.h" +#include "components/Transform.h" +#include "primitives/Primitives.h" + +namespace afk::systems { + +/** + * @brief ParticleSystem + * + */ +void particleSystem(Registry& registry, uint32_t delta) { + auto particleView = registry.view(); + + int count = 0; + for (auto [entity, tran, particle] : particleView.each()) { + tran.size.x = math::lerp(particle.startSize, particle.endSize, + particle.age / particle.lifespan); + tran.size.y = tran.size.x; + + particle.age += delta; + if (particle.age > particle.lifespan) { + registry.destroy(entity); + } + + count++; + } + + auto systemView = registry.view(); + + for (auto [entity, tran, emitter] : systemView.each()) { + emitter.counter += delta; + + while (emitter.counter > emitter.frequency && + !emitter.templates.empty()) { + int index = random::randomInt(0, emitter.templates.size() - 1); + auto& [particle, physics] = emitter.templates.at(index); + + emitter.counter -= emitter.frequency; + + const float startX = + tran.position.x + random::randomFloat(0, tran.size.x); + const float startY = + tran.position.y + random::randomFloat(0, tran.size.y); + + const auto& particleId = registry.create(); + registry.emplace(particleId, particle); + registry.emplace(particleId, physics); + registry.emplace( + particleId, Vec3(startX, startY, tran.position.z), + Vec2(particle.startSize, particle.startSize)); + } + } +} + +void particleRenderSystem(Registry& registry, AssetService& assetService) { + auto view = registry.view(); + + for (auto [entity, tran, particle] : view.each()) { + float lifePercent = particle.age / particle.lifespan; + + // Lerp size + float size = + math::lerp(particle.startSize, particle.endSize, lifePercent); + + // Lerp color + uint8_t r = + math::lerp(particle.startColor.r, particle.endColor.r, lifePercent); + uint8_t g = + math::lerp(particle.startColor.g, particle.endColor.g, lifePercent); + uint8_t b = + math::lerp(particle.startColor.b, particle.endColor.b, lifePercent); + uint8_t a = + math::lerp(particle.startColor.a, particle.endColor.a, lifePercent); + color::Color color = {r, g, b, a}; + + // Switch over type + switch (particle.type) { + case ParticleType::Square: + primitives::rectfill(tran.position.x, tran.position.y, size, size, + color); + break; + case ParticleType::Circle: + primitives::circle(tran.position.x, tran.position.y, size, color); + break; + case ParticleType::Pixel: + primitives::pixel(tran.position.x, tran.position.y, color); + break; + case ParticleType::Image: { + auto texture = assetService.getImage(particle.texture); + texture.drawEx(tran.position.x, tran.position.y, tran.size.x, + tran.size.y, tran.angle); + break; + } + default: + break; + } + } +} + +} // namespace afk::systems diff --git a/src/systems/PhysicsSystem.cpp b/src/systems/PhysicsSystem.cpp new file mode 100644 index 0000000..6f72f75 --- /dev/null +++ b/src/systems/PhysicsSystem.cpp @@ -0,0 +1,35 @@ +/** + * @file PhysicsSystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of updating transforms + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#include "systems/PhysicsSystem.h" +#include "components/Physics.h" +#include "components/Transform.h" +#include "services/assets/AssetService.h" + +namespace afk::systems { + +/** + * @brief PhysicsSystem + * + */ +void physicsSystem(Registry& registry, uint32_t delta) { + auto view = registry.view(); + + const float deltaSeconds = static_cast(delta) / 1000.0f; + + for (auto [entity, tran, physics] : view.each()) { + tran.position.x += physics.velocity.x * deltaSeconds; + tran.position.y += physics.velocity.y * deltaSeconds; + physics.velocity.x += physics.acceleration.x * deltaSeconds; + physics.velocity.y += physics.acceleration.y * deltaSeconds; + } +} + +} // namespace afk::systems diff --git a/src/systems/RenderSystem.cpp b/src/systems/RenderSystem.cpp new file mode 100644 index 0000000..ff53522 --- /dev/null +++ b/src/systems/RenderSystem.cpp @@ -0,0 +1,31 @@ +/** + * @file RenderSystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of rendering components + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#include "systems/RenderSystem.h" +#include "components/Sprite.h" +#include "components/Transform.h" + +namespace afk::systems { + +/** + * @brief RenderSystem + * + */ +void renderSystem(Registry& registry, AssetService& assetService) { + auto view = registry.view(); + + for (auto [entity, tran, sprite] : view.each()) { + auto texture = assetService.getImage(sprite.texture); + texture.drawEx(tran.position.x, tran.position.y, tran.size.x, tran.size.y, + tran.angle); + } +} + +} // namespace afk::systems diff --git a/src/systems/UISystem.cpp b/src/systems/UISystem.cpp new file mode 100644 index 0000000..fe8b0de --- /dev/null +++ b/src/systems/UISystem.cpp @@ -0,0 +1,58 @@ +/** + * @file UISystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of rendering components + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#include "systems/UISystem.h" + +#include "components/Transform.h" +#include "components/ui/Button.h" +#include "components/ui/Label.h" +#include "primitives/Primitives.h" + +namespace afk::systems { + +/** + * @brief UISystem + * + */ +void uiSystem(Registry& registry, + AssetService& assetService, + InputService& inputService) { + auto viewLabels = registry.view(); + for (auto [entity, tran, label] : viewLabels.each()) { + auto font = assetService.getFont(label.font); + font.draw(tran.position.x, tran.position.y, label.text); + } + + auto viewButtons = registry.view(); + for (auto [entity, tran, button] : viewButtons.each()) { + // Draw button background + primitives::rectfill(tran.position.x, tran.position.y, tran.size.x, + tran.size.y, color::white); + + // Draw button border + primitives::rect(tran.position.x, tran.position.y, tran.size.x, tran.size.y, + color::black); + + // Draw text + auto font = assetService.getFont(button.font); + font.draw(tran.position.x, tran.position.y, button.text); + + if (button.onClick) { + if (inputService.mouseDown(MouseButtons::Left)) { + if (inputService.mouseOver(Vec2(tran.position.x, tran.position.y), + Vec2(tran.size.x, tran.size.y))) { + button.onClick(); + } + } + } + } +} + +} // namespace afk::systems diff --git a/src/ui/MessageBox.cpp b/src/ui/MessageBox.cpp index 25ca435..079c233 100644 --- a/src/ui/MessageBox.cpp +++ b/src/ui/MessageBox.cpp @@ -10,11 +10,12 @@ */ #include "ui/MessageBox.h" +#include #include "services/Services.h" namespace afk { -MessageBox::MessageBox(MessageBoxType type) : title(""), text(""), type(type) {} +MessageBox::MessageBox(MessageBoxType type) : type(type) {} // Set the title of the message box void MessageBox::setTitle(const std::string& title) { @@ -29,19 +30,19 @@ void MessageBox::setText(const std::string& text) { // Show the message box on screen int MessageBox::show() { SDL_Window* window = Services::getDisplayService().getWindow(); - int return_code = SDL_ShowSimpleMessageBox(resolveType(), title.c_str(), + int returnCode = SDL_ShowSimpleMessageBox(resolveType(), title.c_str(), text.c_str(), window); - return return_code; + return returnCode; } // Get type of box in SDL terms int MessageBox::resolveType() { switch (type) { - case MessageBoxType::ERROR: + case MessageBoxType::Error: return SDL_MESSAGEBOX_ERROR; - case MessageBoxType::INFO: + case MessageBoxType::Info: return SDL_MESSAGEBOX_INFORMATION; - case MessageBoxType::WARN: + case MessageBoxType::Warn: default: return SDL_MESSAGEBOX_WARNING; } From 7f840a74a4b1136f11fbb683df63eb83e22519d9 Mon Sep 17 00:00:00 2001 From: alegemaate Date: Sat, 23 Apr 2022 17:53:12 -0400 Subject: [PATCH 09/24] refactor: restructure project --- .gitignore | 13 +- .gitmodules | 3 + CMakeLists.txt | 134 +----- afk/CMakeLists.txt | 133 ++++++ {include => afk/include}/Game.h | 0 {include => afk/include}/assets/Font.h | 0 {include => afk/include}/assets/Sound.h | 0 {include => afk/include}/assets/Stream.h | 0 {include => afk/include}/assets/Texture.h | 0 {include => afk/include}/common/Color.h | 0 {include => afk/include}/common/Exceptions.h | 0 {include => afk/include}/common/Vec.h | 0 {include => afk/include}/common/math.h | 0 {include => afk/include}/common/random.h | 0 {include => afk/include}/common/str.h | 0 .../include}/components/Collider.h | 0 .../include}/components/Particle.h | 0 .../include}/components/ParticleEmitter.h | 0 {include => afk/include}/components/Physics.h | 0 {include => afk/include}/components/Sprite.h | 0 .../include}/components/Transform.h | 0 .../include}/components/components.h | 0 {include => afk/include}/components/ui.h | 0 .../include}/components/ui/Button.h | 0 .../include}/components/ui/Label.h | 0 {include => afk/include}/entities/Entity.h | 0 .../include}/primitives/Primitives.h | 0 {include => afk/include}/scene/Scene.h | 0 {include => afk/include}/services/Service.h | 0 {include => afk/include}/services/Services.h | 0 .../include}/services/assets/AssetService.h | 0 .../include}/services/audio/AudioService.h | 0 .../include}/services/config/ConfigService.h | 0 .../services/display/DisplayService.h | 0 .../include}/services/events/EventQueue.h | 0 .../include}/services/input/InputService.h | 0 .../include}/services/input/JoystickCodes.h | 0 .../include}/services/input/JoystickState.h | 0 .../include}/services/input/KeyboardKeys.h | 0 .../include}/services/input/KeyboardState.h | 0 .../include}/services/input/MouseState.h | 0 .../services/logging/DebugLoggingService.h | 0 .../services/logging/LoggingService.h | 0 .../include}/services/scene/SceneService.h | 0 .../include}/systems/CollisionSystem.h | 0 .../include}/systems/ParticleSystem.h | 0 .../include}/systems/PhysicsSystem.h | 0 .../include}/systems/RenderSystem.h | 0 {include => afk/include}/systems/UISystem.h | 0 {include => afk/include}/ui/MessageBox.h | 0 {src => afk/src}/Game.cpp | 0 {src => afk/src}/assets/Font.cpp | 0 {src => afk/src}/assets/Sound.cpp | 0 {src => afk/src}/assets/Stream.cpp | 0 {src => afk/src}/assets/Texture.cpp | 0 {src => afk/src}/common/Color.cpp | 0 {src => afk/src}/common/math.cpp | 0 {src => afk/src}/common/random.cpp | 0 {src => afk/src}/common/str.cpp | 0 {src => afk/src}/primitives/Primitives.cpp | 0 {src => afk/src}/scene/Scene.cpp | 0 {src => afk/src}/services/Services.cpp | 0 .../src}/services/assets/AssetService.cpp | 0 .../src}/services/audio/AudioService.cpp | 0 .../src}/services/config/ConfigService.cpp | 0 .../src}/services/display/DisplayService.cpp | 0 .../src}/services/events/EventQueue.cpp | 0 .../src}/services/input/InputService.cpp | 0 .../services/logging/DebugLoggingService.cpp | 0 .../src}/services/logging/LoggingService.cpp | 0 .../src}/services/scene/SceneService.cpp | 0 {src => afk/src}/systems/CollisionSystem.cpp | 0 {src => afk/src}/systems/ParticleSystem.cpp | 0 {src => afk/src}/systems/PhysicsSystem.cpp | 0 {src => afk/src}/systems/RenderSystem.cpp | 0 {src => afk/src}/systems/UISystem.cpp | 0 {src => afk/src}/ui/MessageBox.cpp | 0 examples/CMakeLists.txt | 115 +++-- examples/{ => src}/ex_collision.cpp | 0 examples/{ => src}/ex_display.cpp | 0 examples/{ => src}/ex_fps.cpp | 0 examples/{ => src}/ex_keyboard.cpp | 0 examples/{ => src}/ex_message_box.cpp | 0 examples/{ => src}/ex_mouse.cpp | 0 examples/{ => src}/ex_particles.cpp | 0 examples/{ => src}/ex_physics.cpp | 0 examples/{ => src}/ex_rotate.cpp | 0 examples/{ => src}/ex_sound.cpp | 0 examples/{ => src}/ex_sprite.cpp | 0 examples/{ => src}/ex_ui.cpp | 0 lib/cmake/Copyright.txt | 132 ++++++ lib/cmake/FindSDL2.cmake | 392 ++++++++++++++++++ lib/cmake/FindSDL2_gfx.cmake | 222 ++++++++++ lib/cmake/FindSDL2_image.cmake | 222 ++++++++++ lib/cmake/FindSDL2_mixer.cmake | 220 ++++++++++ lib/cmake/FindSDL2_net.cmake | 222 ++++++++++ lib/cmake/FindSDL2_ttf.cmake | 222 ++++++++++ lib/entt | 1 + lib/libs.cmake | 20 + 99 files changed, 1859 insertions(+), 192 deletions(-) create mode 100644 .gitmodules create mode 100644 afk/CMakeLists.txt rename {include => afk/include}/Game.h (100%) rename {include => afk/include}/assets/Font.h (100%) rename {include => afk/include}/assets/Sound.h (100%) rename {include => afk/include}/assets/Stream.h (100%) rename {include => afk/include}/assets/Texture.h (100%) rename {include => afk/include}/common/Color.h (100%) rename {include => afk/include}/common/Exceptions.h (100%) rename {include => afk/include}/common/Vec.h (100%) rename {include => afk/include}/common/math.h (100%) rename {include => afk/include}/common/random.h (100%) rename {include => afk/include}/common/str.h (100%) rename {include => afk/include}/components/Collider.h (100%) rename {include => afk/include}/components/Particle.h (100%) rename {include => afk/include}/components/ParticleEmitter.h (100%) rename {include => afk/include}/components/Physics.h (100%) rename {include => afk/include}/components/Sprite.h (100%) rename {include => afk/include}/components/Transform.h (100%) rename {include => afk/include}/components/components.h (100%) rename {include => afk/include}/components/ui.h (100%) rename {include => afk/include}/components/ui/Button.h (100%) rename {include => afk/include}/components/ui/Label.h (100%) rename {include => afk/include}/entities/Entity.h (100%) rename {include => afk/include}/primitives/Primitives.h (100%) rename {include => afk/include}/scene/Scene.h (100%) rename {include => afk/include}/services/Service.h (100%) rename {include => afk/include}/services/Services.h (100%) rename {include => afk/include}/services/assets/AssetService.h (100%) rename {include => afk/include}/services/audio/AudioService.h (100%) rename {include => afk/include}/services/config/ConfigService.h (100%) rename {include => afk/include}/services/display/DisplayService.h (100%) rename {include => afk/include}/services/events/EventQueue.h (100%) rename {include => afk/include}/services/input/InputService.h (100%) rename {include => afk/include}/services/input/JoystickCodes.h (100%) rename {include => afk/include}/services/input/JoystickState.h (100%) rename {include => afk/include}/services/input/KeyboardKeys.h (100%) rename {include => afk/include}/services/input/KeyboardState.h (100%) rename {include => afk/include}/services/input/MouseState.h (100%) rename {include => afk/include}/services/logging/DebugLoggingService.h (100%) rename {include => afk/include}/services/logging/LoggingService.h (100%) rename {include => afk/include}/services/scene/SceneService.h (100%) rename {include => afk/include}/systems/CollisionSystem.h (100%) rename {include => afk/include}/systems/ParticleSystem.h (100%) rename {include => afk/include}/systems/PhysicsSystem.h (100%) rename {include => afk/include}/systems/RenderSystem.h (100%) rename {include => afk/include}/systems/UISystem.h (100%) rename {include => afk/include}/ui/MessageBox.h (100%) rename {src => afk/src}/Game.cpp (100%) rename {src => afk/src}/assets/Font.cpp (100%) rename {src => afk/src}/assets/Sound.cpp (100%) rename {src => afk/src}/assets/Stream.cpp (100%) rename {src => afk/src}/assets/Texture.cpp (100%) rename {src => afk/src}/common/Color.cpp (100%) rename {src => afk/src}/common/math.cpp (100%) rename {src => afk/src}/common/random.cpp (100%) rename {src => afk/src}/common/str.cpp (100%) rename {src => afk/src}/primitives/Primitives.cpp (100%) rename {src => afk/src}/scene/Scene.cpp (100%) rename {src => afk/src}/services/Services.cpp (100%) rename {src => afk/src}/services/assets/AssetService.cpp (100%) rename {src => afk/src}/services/audio/AudioService.cpp (100%) rename {src => afk/src}/services/config/ConfigService.cpp (100%) rename {src => afk/src}/services/display/DisplayService.cpp (100%) rename {src => afk/src}/services/events/EventQueue.cpp (100%) rename {src => afk/src}/services/input/InputService.cpp (100%) rename {src => afk/src}/services/logging/DebugLoggingService.cpp (100%) rename {src => afk/src}/services/logging/LoggingService.cpp (100%) rename {src => afk/src}/services/scene/SceneService.cpp (100%) rename {src => afk/src}/systems/CollisionSystem.cpp (100%) rename {src => afk/src}/systems/ParticleSystem.cpp (100%) rename {src => afk/src}/systems/PhysicsSystem.cpp (100%) rename {src => afk/src}/systems/RenderSystem.cpp (100%) rename {src => afk/src}/systems/UISystem.cpp (100%) rename {src => afk/src}/ui/MessageBox.cpp (100%) rename examples/{ => src}/ex_collision.cpp (100%) rename examples/{ => src}/ex_display.cpp (100%) rename examples/{ => src}/ex_fps.cpp (100%) rename examples/{ => src}/ex_keyboard.cpp (100%) rename examples/{ => src}/ex_message_box.cpp (100%) rename examples/{ => src}/ex_mouse.cpp (100%) rename examples/{ => src}/ex_particles.cpp (100%) rename examples/{ => src}/ex_physics.cpp (100%) rename examples/{ => src}/ex_rotate.cpp (100%) rename examples/{ => src}/ex_sound.cpp (100%) rename examples/{ => src}/ex_sprite.cpp (100%) rename examples/{ => src}/ex_ui.cpp (100%) create mode 100644 lib/cmake/Copyright.txt create mode 100644 lib/cmake/FindSDL2.cmake create mode 100644 lib/cmake/FindSDL2_gfx.cmake create mode 100644 lib/cmake/FindSDL2_image.cmake create mode 100644 lib/cmake/FindSDL2_mixer.cmake create mode 100644 lib/cmake/FindSDL2_net.cmake create mode 100644 lib/cmake/FindSDL2_ttf.cmake create mode 160000 lib/entt create mode 100644 lib/libs.cmake diff --git a/.gitignore b/.gitignore index 184ef93..de958a3 100644 --- a/.gitignore +++ b/.gitignore @@ -44,12 +44,11 @@ CppCheckResults.xml CMakeFiles CMakeCache.txt Makefile -*.cmake -install_manifest.txt -bin -docs -lib +afk.cmake +cmake_install.cmake compile_commands.json -.idea -build +install_manifest.txt +docs/ +.idea/ +build/ Testing/ \ No newline at end of file diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..5c02c1b --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "lib/entt"] + path = lib/entt + url = https://github.com/skypjack/entt.git diff --git a/CMakeLists.txt b/CMakeLists.txt index bc89bbf..27713fe 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,130 +1,16 @@ -cmake_minimum_required(VERSION 3.11) +cmake_minimum_required(VERSION 3.14) -set(CMAKE_CXX_STANDARD 14) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/lib) -set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/lib) -set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/build) -set(CMAKE_EXPORT_COMPILE_COMMANDS on) - -project (afk VERSION 1.0.0 LANGUAGES CXX) - -# Add sources -file(GLOB_RECURSE SOURCES ${CMAKE_SOURCE_DIR}/src/*.cpp) -file(GLOB_RECURSE HEADERS ${CMAKE_SOURCE_DIR}/include/*.h) - -# Create lib -add_library(${PROJECT_NAME} STATIC ${SOURCES} ${HEADERS}) - -# Add compile options -target_compile_options(${PROJECT_NAME} PRIVATE -O2 -Wall -Wextra -pedantic) - -# Add include -target_include_directories(${PROJECT_NAME} PUBLIC - $ - $ - PRIVATE src) - -# Versioning -set_target_properties(${PROJECT_NAME} PROPERTIES - VERSION ${PROJECT_VERSION} - SOVERSION 1) - -# Find libs - -if(EMSCRIPTEN) - set(EnTT_DIR "C:/Users/alege/Documents/GitHub/emsdk/upstream/lib/cmake/EnTT") - find_package(EnTT REQUIRED) - -else(EMSCRIPTEN) - find_package(EnTT REQUIRED) - find_library(SDL_LIBRARY NAMES SDL2 REQUIRED) - find_library(SDL_MIXER_LIBRARY NAMES SDL2_mixer REQUIRED) - find_library(SDL_IMAGE_LIBRARY NAMES SDL2_image REQUIRED) - find_library(SDL_TTF_LIBRARY NAMES SDL2_ttf REQUIRED) - find_library(SDL_GFX_LIBRARY NAMES SDL2_gfx REQUIRED) - find_library(SDL_MAIN_LIBRARY NAMES SDL2main REQUIRED) -endif(EMSCRIPTEN) - -# Emscripten specific options -if(EMSCRIPTEN) - target_compile_options( - ${PROJECT_NAME} - PRIVATE - -sUSE_SDL=2 - -sUSE_SDL_IMAGE=2 - -sUSE_SDL_TTF=2 - -sUSE_SDL_MIXER=2 - -sUSE_SDL_GFX=2 - -sSDL2_IMAGE_FORMATS=["png"] - ) - target_link_libraries( - ${PROJECT_NAME} - -sWASM=1 - -sUSE_SDL=2 - -sUSE_SDL_IMAGE=2 - -sUSE_SDL_TTF=2 - -sUSE_SDL_MIXER=2 - -sUSE_SDL_GFX=2 - -sSDL2_IMAGE_FORMATS=["png"] - -sDEMANGLE_SUPPORT=1 - EnTT::EnTT - ) - target_link_libraries(${PROJECT_NAME} -sUSE_SDL=2 -fsanitize=address) +project (root VERSION 1.0.0 LANGUAGES CXX) -# All other system options -else(EMSCRIPTEN) - target_link_libraries( - ${PROJECT_NAME} - ${SDL_LIBRARY} - ${SDL_MIXER_LIBRARY} - ${SDL_IMAGE_LIBRARY} - ${SDL_TTF_LIBRARY} - ${SDL_GFX_LIBRARY} - ${SDL_MAIN_LIBRARY} - EnTT::EnTT - ) -endif(EMSCRIPTEN) - -# Install info -if (EMSCRIPTEN) - get_filename_component(EMSDK_DIR ${CMAKE_TOOLCHAIN_FILE} DIRECTORY) - set(EMSDK_DIR ${EMSDK_DIR}/../../../system) - message("Lib install directory set to ${EMSDK_DIR}") - - install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} - ARCHIVE DESTINATION ${EMSDK_DIR}/lib - LIBRARY DESTINATION ${EMSDK_DIR}/lib - RUNTIME DESTINATION ${EMSDK_DIR}/bin) - - install(DIRECTORY include/ DESTINATION ${EMSDK_DIR}/include/${PROJECT_NAME}) - -# Msys2 specific -elseif (WIN32) - install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} - ARCHIVE DESTINATION C:/msys64/mingw32/lib - LIBRARY DESTINATION C:/msys64/mingw32/lib - RUNTIME DESTINATION C:/msys64/mingw32/bin) - - install(DIRECTORY include/ DESTINATION C:/msys64/mingw32/include/${PROJECT_NAME}) - - install(EXPORT ${PROJECT_NAME} DESTINATION C:/msys64/mingw32/share/${PROJECT_NAME}/cmake) - export(TARGETS ${PROJECT_NAME} FILE ${PROJECT_NAME}.cmake) - -# Linux mac etc. -else() - include(GNUInstallDirs) - - install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) +# Config +set(CMAKE_EXPORT_COMPILE_COMMANDS on) +set(EXTERNAL_DIR ${PROJECT_SOURCE_DIR}/lib) - install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}) +# Submodule libs +add_subdirectory(${EXTERNAL_DIR}/entt) - install(EXPORT ${PROJECT_NAME} DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/${PROJECT_NAME}/cmake) - export(TARGETS ${PROJECT_NAME} FILE ${PROJECT_NAME}.cmake) -endif() +# Core lib +add_subdirectory(${PROJECT_SOURCE_DIR}/afk) # Examples -include(${CMAKE_SOURCE_DIR}/examples/CMakeLists.txt) \ No newline at end of file +add_subdirectory(${PROJECT_SOURCE_DIR}/examples) \ No newline at end of file diff --git a/afk/CMakeLists.txt b/afk/CMakeLists.txt new file mode 100644 index 0000000..ac3efc1 --- /dev/null +++ b/afk/CMakeLists.txt @@ -0,0 +1,133 @@ +cmake_minimum_required(VERSION 3.14) + +project (afk + VERSION 1.0.0 + LANGUAGES CXX +) + +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/build/lib) +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/build/lib) + +include(${EXTERNAL_DIR}/libs.cmake) + +# Sources +file(GLOB_RECURSE SOURCES ${PROJECT_SOURCE_DIR}/src/*.cpp) +file(GLOB_RECURSE HEADERS ${PROJECT_SOURCE_DIR}/include/*.h) + +# Lib +add_library(${PROJECT_NAME} + STATIC + ${SOURCES} + ${HEADERS} +) + +target_include_directories(${PROJECT_NAME} + PUBLIC + $ + $ +) + +target_compile_options(${PROJECT_NAME} + PRIVATE + -O2 + -Wall + -Wextra + -pedantic +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + VERSION ${PROJECT_VERSION} + SOVERSION 1 + CXX_STANDARD 17 + CXX_STANDARD_REQUIRED ON +) + +# Emscripten specific options +if(EMSCRIPTEN) + target_compile_options(${PROJECT_NAME} + PRIVATE + -sUSE_SDL=2 + -sUSE_SDL_IMAGE=2 + -sUSE_SDL_TTF=2 + -sUSE_SDL_MIXER=2 + -sUSE_SDL_GFX=2 + -sSDL2_IMAGE_FORMATS=["png"] + ) + + target_link_libraries(${PROJECT_NAME} + -sWASM=1 + -sUSE_SDL=2 + -sUSE_SDL_IMAGE=2 + -sUSE_SDL_TTF=2 + -sUSE_SDL_MIXER=2 + -sUSE_SDL_GFX=2 + -sSDL2_IMAGE_FORMATS=["png"] + -sDEMANGLE_SUPPORT=1 + imported::entt + ) + + target_link_libraries(${PROJECT_NAME} + -sUSE_SDL=2 + -fsanitize=address + ) + +# All other system options +else(EMSCRIPTEN) + target_link_libraries(${PROJECT_NAME} + PUBLIC + SDL2::Image + SDL2::Mixer + SDL2::TTF + SDL2::GFX + SDL2::Main + imported::entt + ) +endif(EMSCRIPTEN) + +# Install info +if (EMSCRIPTEN) + get_filename_component(EMSDK_DIR ${CMAKE_TOOLCHAIN_FILE} DIRECTORY) + set(EMSDK_DIR ${EMSDK_DIR}/../../../system) + message(STATUS "Lib install directory set to ${EMSDK_DIR}") + + set(CMAKE_INSTALL_LIBDIR ${EMSDK_DIR}/lib) + set(CMAKE_INSTALL_BINDIR ${EMSDK_DIR}/bin) + set(CMAKE_INSTALL_INCLUDEDIR ${EMSDK_DIR}/include) + set(CMAKE_INSTALL_DATAROOTDIR ${EMSDK_DIR}/share) + +elseif (WIN32) + get_filename_component(WIN32_BIN_PATH ${CMAKE_C_COMPILER} PATH) + set(WIN32_DIR ${WIN32_BIN_PATH}/../) + message(STATUS "Lib install directory set to ${WIN32_DIR}") + + set(CMAKE_INSTALL_LIBDIR ${WIN32_DIR}/lib) + set(CMAKE_INSTALL_BINDIR ${WIN32_DIR}/bin) + set(CMAKE_INSTALL_INCLUDEDIR ${WIN32_DIR}/include) + set(CMAKE_INSTALL_DATAROOTDIR ${WIN32_DIR}/share) +else() + include(GNUInstallDirs) +endif() + +install( + TARGETS ${PROJECT_NAME} + EXPORT ${PROJECT_NAME} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +install( + DIRECTORY include/ + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME} +) + +install( + EXPORT ${PROJECT_NAME} + DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/${PROJECT_NAME}/cmake +) + +export( + TARGETS ${PROJECT_NAME} + FILE ${PROJECT_NAME}.cmake +) \ No newline at end of file diff --git a/include/Game.h b/afk/include/Game.h similarity index 100% rename from include/Game.h rename to afk/include/Game.h diff --git a/include/assets/Font.h b/afk/include/assets/Font.h similarity index 100% rename from include/assets/Font.h rename to afk/include/assets/Font.h diff --git a/include/assets/Sound.h b/afk/include/assets/Sound.h similarity index 100% rename from include/assets/Sound.h rename to afk/include/assets/Sound.h diff --git a/include/assets/Stream.h b/afk/include/assets/Stream.h similarity index 100% rename from include/assets/Stream.h rename to afk/include/assets/Stream.h diff --git a/include/assets/Texture.h b/afk/include/assets/Texture.h similarity index 100% rename from include/assets/Texture.h rename to afk/include/assets/Texture.h diff --git a/include/common/Color.h b/afk/include/common/Color.h similarity index 100% rename from include/common/Color.h rename to afk/include/common/Color.h diff --git a/include/common/Exceptions.h b/afk/include/common/Exceptions.h similarity index 100% rename from include/common/Exceptions.h rename to afk/include/common/Exceptions.h diff --git a/include/common/Vec.h b/afk/include/common/Vec.h similarity index 100% rename from include/common/Vec.h rename to afk/include/common/Vec.h diff --git a/include/common/math.h b/afk/include/common/math.h similarity index 100% rename from include/common/math.h rename to afk/include/common/math.h diff --git a/include/common/random.h b/afk/include/common/random.h similarity index 100% rename from include/common/random.h rename to afk/include/common/random.h diff --git a/include/common/str.h b/afk/include/common/str.h similarity index 100% rename from include/common/str.h rename to afk/include/common/str.h diff --git a/include/components/Collider.h b/afk/include/components/Collider.h similarity index 100% rename from include/components/Collider.h rename to afk/include/components/Collider.h diff --git a/include/components/Particle.h b/afk/include/components/Particle.h similarity index 100% rename from include/components/Particle.h rename to afk/include/components/Particle.h diff --git a/include/components/ParticleEmitter.h b/afk/include/components/ParticleEmitter.h similarity index 100% rename from include/components/ParticleEmitter.h rename to afk/include/components/ParticleEmitter.h diff --git a/include/components/Physics.h b/afk/include/components/Physics.h similarity index 100% rename from include/components/Physics.h rename to afk/include/components/Physics.h diff --git a/include/components/Sprite.h b/afk/include/components/Sprite.h similarity index 100% rename from include/components/Sprite.h rename to afk/include/components/Sprite.h diff --git a/include/components/Transform.h b/afk/include/components/Transform.h similarity index 100% rename from include/components/Transform.h rename to afk/include/components/Transform.h diff --git a/include/components/components.h b/afk/include/components/components.h similarity index 100% rename from include/components/components.h rename to afk/include/components/components.h diff --git a/include/components/ui.h b/afk/include/components/ui.h similarity index 100% rename from include/components/ui.h rename to afk/include/components/ui.h diff --git a/include/components/ui/Button.h b/afk/include/components/ui/Button.h similarity index 100% rename from include/components/ui/Button.h rename to afk/include/components/ui/Button.h diff --git a/include/components/ui/Label.h b/afk/include/components/ui/Label.h similarity index 100% rename from include/components/ui/Label.h rename to afk/include/components/ui/Label.h diff --git a/include/entities/Entity.h b/afk/include/entities/Entity.h similarity index 100% rename from include/entities/Entity.h rename to afk/include/entities/Entity.h diff --git a/include/primitives/Primitives.h b/afk/include/primitives/Primitives.h similarity index 100% rename from include/primitives/Primitives.h rename to afk/include/primitives/Primitives.h diff --git a/include/scene/Scene.h b/afk/include/scene/Scene.h similarity index 100% rename from include/scene/Scene.h rename to afk/include/scene/Scene.h diff --git a/include/services/Service.h b/afk/include/services/Service.h similarity index 100% rename from include/services/Service.h rename to afk/include/services/Service.h diff --git a/include/services/Services.h b/afk/include/services/Services.h similarity index 100% rename from include/services/Services.h rename to afk/include/services/Services.h diff --git a/include/services/assets/AssetService.h b/afk/include/services/assets/AssetService.h similarity index 100% rename from include/services/assets/AssetService.h rename to afk/include/services/assets/AssetService.h diff --git a/include/services/audio/AudioService.h b/afk/include/services/audio/AudioService.h similarity index 100% rename from include/services/audio/AudioService.h rename to afk/include/services/audio/AudioService.h diff --git a/include/services/config/ConfigService.h b/afk/include/services/config/ConfigService.h similarity index 100% rename from include/services/config/ConfigService.h rename to afk/include/services/config/ConfigService.h diff --git a/include/services/display/DisplayService.h b/afk/include/services/display/DisplayService.h similarity index 100% rename from include/services/display/DisplayService.h rename to afk/include/services/display/DisplayService.h diff --git a/include/services/events/EventQueue.h b/afk/include/services/events/EventQueue.h similarity index 100% rename from include/services/events/EventQueue.h rename to afk/include/services/events/EventQueue.h diff --git a/include/services/input/InputService.h b/afk/include/services/input/InputService.h similarity index 100% rename from include/services/input/InputService.h rename to afk/include/services/input/InputService.h diff --git a/include/services/input/JoystickCodes.h b/afk/include/services/input/JoystickCodes.h similarity index 100% rename from include/services/input/JoystickCodes.h rename to afk/include/services/input/JoystickCodes.h diff --git a/include/services/input/JoystickState.h b/afk/include/services/input/JoystickState.h similarity index 100% rename from include/services/input/JoystickState.h rename to afk/include/services/input/JoystickState.h diff --git a/include/services/input/KeyboardKeys.h b/afk/include/services/input/KeyboardKeys.h similarity index 100% rename from include/services/input/KeyboardKeys.h rename to afk/include/services/input/KeyboardKeys.h diff --git a/include/services/input/KeyboardState.h b/afk/include/services/input/KeyboardState.h similarity index 100% rename from include/services/input/KeyboardState.h rename to afk/include/services/input/KeyboardState.h diff --git a/include/services/input/MouseState.h b/afk/include/services/input/MouseState.h similarity index 100% rename from include/services/input/MouseState.h rename to afk/include/services/input/MouseState.h diff --git a/include/services/logging/DebugLoggingService.h b/afk/include/services/logging/DebugLoggingService.h similarity index 100% rename from include/services/logging/DebugLoggingService.h rename to afk/include/services/logging/DebugLoggingService.h diff --git a/include/services/logging/LoggingService.h b/afk/include/services/logging/LoggingService.h similarity index 100% rename from include/services/logging/LoggingService.h rename to afk/include/services/logging/LoggingService.h diff --git a/include/services/scene/SceneService.h b/afk/include/services/scene/SceneService.h similarity index 100% rename from include/services/scene/SceneService.h rename to afk/include/services/scene/SceneService.h diff --git a/include/systems/CollisionSystem.h b/afk/include/systems/CollisionSystem.h similarity index 100% rename from include/systems/CollisionSystem.h rename to afk/include/systems/CollisionSystem.h diff --git a/include/systems/ParticleSystem.h b/afk/include/systems/ParticleSystem.h similarity index 100% rename from include/systems/ParticleSystem.h rename to afk/include/systems/ParticleSystem.h diff --git a/include/systems/PhysicsSystem.h b/afk/include/systems/PhysicsSystem.h similarity index 100% rename from include/systems/PhysicsSystem.h rename to afk/include/systems/PhysicsSystem.h diff --git a/include/systems/RenderSystem.h b/afk/include/systems/RenderSystem.h similarity index 100% rename from include/systems/RenderSystem.h rename to afk/include/systems/RenderSystem.h diff --git a/include/systems/UISystem.h b/afk/include/systems/UISystem.h similarity index 100% rename from include/systems/UISystem.h rename to afk/include/systems/UISystem.h diff --git a/include/ui/MessageBox.h b/afk/include/ui/MessageBox.h similarity index 100% rename from include/ui/MessageBox.h rename to afk/include/ui/MessageBox.h diff --git a/src/Game.cpp b/afk/src/Game.cpp similarity index 100% rename from src/Game.cpp rename to afk/src/Game.cpp diff --git a/src/assets/Font.cpp b/afk/src/assets/Font.cpp similarity index 100% rename from src/assets/Font.cpp rename to afk/src/assets/Font.cpp diff --git a/src/assets/Sound.cpp b/afk/src/assets/Sound.cpp similarity index 100% rename from src/assets/Sound.cpp rename to afk/src/assets/Sound.cpp diff --git a/src/assets/Stream.cpp b/afk/src/assets/Stream.cpp similarity index 100% rename from src/assets/Stream.cpp rename to afk/src/assets/Stream.cpp diff --git a/src/assets/Texture.cpp b/afk/src/assets/Texture.cpp similarity index 100% rename from src/assets/Texture.cpp rename to afk/src/assets/Texture.cpp diff --git a/src/common/Color.cpp b/afk/src/common/Color.cpp similarity index 100% rename from src/common/Color.cpp rename to afk/src/common/Color.cpp diff --git a/src/common/math.cpp b/afk/src/common/math.cpp similarity index 100% rename from src/common/math.cpp rename to afk/src/common/math.cpp diff --git a/src/common/random.cpp b/afk/src/common/random.cpp similarity index 100% rename from src/common/random.cpp rename to afk/src/common/random.cpp diff --git a/src/common/str.cpp b/afk/src/common/str.cpp similarity index 100% rename from src/common/str.cpp rename to afk/src/common/str.cpp diff --git a/src/primitives/Primitives.cpp b/afk/src/primitives/Primitives.cpp similarity index 100% rename from src/primitives/Primitives.cpp rename to afk/src/primitives/Primitives.cpp diff --git a/src/scene/Scene.cpp b/afk/src/scene/Scene.cpp similarity index 100% rename from src/scene/Scene.cpp rename to afk/src/scene/Scene.cpp diff --git a/src/services/Services.cpp b/afk/src/services/Services.cpp similarity index 100% rename from src/services/Services.cpp rename to afk/src/services/Services.cpp diff --git a/src/services/assets/AssetService.cpp b/afk/src/services/assets/AssetService.cpp similarity index 100% rename from src/services/assets/AssetService.cpp rename to afk/src/services/assets/AssetService.cpp diff --git a/src/services/audio/AudioService.cpp b/afk/src/services/audio/AudioService.cpp similarity index 100% rename from src/services/audio/AudioService.cpp rename to afk/src/services/audio/AudioService.cpp diff --git a/src/services/config/ConfigService.cpp b/afk/src/services/config/ConfigService.cpp similarity index 100% rename from src/services/config/ConfigService.cpp rename to afk/src/services/config/ConfigService.cpp diff --git a/src/services/display/DisplayService.cpp b/afk/src/services/display/DisplayService.cpp similarity index 100% rename from src/services/display/DisplayService.cpp rename to afk/src/services/display/DisplayService.cpp diff --git a/src/services/events/EventQueue.cpp b/afk/src/services/events/EventQueue.cpp similarity index 100% rename from src/services/events/EventQueue.cpp rename to afk/src/services/events/EventQueue.cpp diff --git a/src/services/input/InputService.cpp b/afk/src/services/input/InputService.cpp similarity index 100% rename from src/services/input/InputService.cpp rename to afk/src/services/input/InputService.cpp diff --git a/src/services/logging/DebugLoggingService.cpp b/afk/src/services/logging/DebugLoggingService.cpp similarity index 100% rename from src/services/logging/DebugLoggingService.cpp rename to afk/src/services/logging/DebugLoggingService.cpp diff --git a/src/services/logging/LoggingService.cpp b/afk/src/services/logging/LoggingService.cpp similarity index 100% rename from src/services/logging/LoggingService.cpp rename to afk/src/services/logging/LoggingService.cpp diff --git a/src/services/scene/SceneService.cpp b/afk/src/services/scene/SceneService.cpp similarity index 100% rename from src/services/scene/SceneService.cpp rename to afk/src/services/scene/SceneService.cpp diff --git a/src/systems/CollisionSystem.cpp b/afk/src/systems/CollisionSystem.cpp similarity index 100% rename from src/systems/CollisionSystem.cpp rename to afk/src/systems/CollisionSystem.cpp diff --git a/src/systems/ParticleSystem.cpp b/afk/src/systems/ParticleSystem.cpp similarity index 100% rename from src/systems/ParticleSystem.cpp rename to afk/src/systems/ParticleSystem.cpp diff --git a/src/systems/PhysicsSystem.cpp b/afk/src/systems/PhysicsSystem.cpp similarity index 100% rename from src/systems/PhysicsSystem.cpp rename to afk/src/systems/PhysicsSystem.cpp diff --git a/src/systems/RenderSystem.cpp b/afk/src/systems/RenderSystem.cpp similarity index 100% rename from src/systems/RenderSystem.cpp rename to afk/src/systems/RenderSystem.cpp diff --git a/src/systems/UISystem.cpp b/afk/src/systems/UISystem.cpp similarity index 100% rename from src/systems/UISystem.cpp rename to afk/src/systems/UISystem.cpp diff --git a/src/ui/MessageBox.cpp b/afk/src/ui/MessageBox.cpp similarity index 100% rename from src/ui/MessageBox.cpp rename to afk/src/ui/MessageBox.cpp diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index c6e1091..b51765a 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,72 +1,67 @@ -cmake_minimum_required(VERSION 3.11) +cmake_minimum_required(VERSION 3.14) -set(CMAKE_CXX_STANDARD 14) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/build) +include(${EXTERNAL_DIR}/libs.cmake) # Add include dir -include_directories(${CMAKE_SOURCE_DIR}/include) -include_directories(${CMAKE_SOURCE_DIR}/build) +include_directories(${PROJECT_SOURCE_DIR}/include) +include_directories(${PROJECT_SOURCE_DIR}/build) -# Find libs -if(EMSCRIPTEN) - set(EnTT_DIR "C:/Users/alege/Documents/GitHub/emsdk/upstream/lib/cmake/EnTT") - find_package(EnTT REQUIRED) +# Config +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/build) +set(EXAMPLES ex_display ex_sprite ex_rotate ex_fps ex_mouse ex_physics ex_sound ex_particles ex_keyboard ex_collision ex_message_box) -else(EMSCRIPTEN) - find_library(SDL_LIBRARY NAMES SDL2 REQUIRED) - find_library(SDL_MIXER_LIBRARY NAMES SDL2_mixer REQUIRED) - find_library(SDL_IMAGE_LIBRARY NAMES SDL2_image REQUIRED) - find_library(SDL_TTF_LIBRARY NAMES SDL2_ttf REQUIRED) - find_library(SDL_GFX_LIBRARY NAMES SDL2_gfx REQUIRED) - find_library(SDL_MAIN_LIBRARY NAMES SDL2main REQUIRED) - find_package(EnTT REQUIRED) -endif(EMSCRIPTEN) +# Build examples +foreach(EX_NAME ${EXAMPLES}) + add_executable(${EX_NAME} + ${CMAKE_CURRENT_LIST_DIR}/src/${EX_NAME}.cpp + ) + target_compile_options(${EX_NAME} + PRIVATE + -O2 + -Wall + -Wextra + -pedantic + -Wno-unused-parameter + ) -# Build examples -# ex_collision ex_ui -set(EXAMPLES ex_display ex_sprite ex_rotate ex_fps ex_mouse ex_physics ex_sound ex_particles ex_keyboard ex_collision ex_message_box) + set_target_properties(${EX_NAME} + PROPERTIES + CXX_STANDARD 17 + CXX_STANDARD_REQUIRED ON + ) -foreach(EX_NAME ${EXAMPLES}) - add_executable(${EX_NAME} ${CMAKE_CURRENT_LIST_DIR}/${EX_NAME}.cpp) - target_compile_options(${EX_NAME} PRIVATE -O2 -Wall -Wextra -pedantic -Wno-unused-parameter) - # Emscripten support if(EMSCRIPTEN) set(CMAKE_EXECUTABLE_SUFFIX ".html") - target_compile_options( - ${EX_NAME} - PRIVATE - -sUSE_SDL=2 - -sUSE_SDL_IMAGE=2 - -sUSE_SDL_TTF=2 - -sUSE_SDL_MIXER=2 - -sUSE_SDL_GFX=2 - -sSDL2_IMAGE_FORMATS=["png"] + target_compile_options(${EX_NAME} + PRIVATE + -sUSE_SDL=2 + -sUSE_SDL_IMAGE=2 + -sUSE_SDL_TTF=2 + -sUSE_SDL_MIXER=2 + -sUSE_SDL_GFX=2 + -sSDL2_IMAGE_FORMATS=["png"] ) - target_link_libraries( - ${EX_NAME} - -sWASM=1 - -sUSE_SDL=2 - -sUSE_SDL_IMAGE=2 - -sUSE_SDL_TTF=2 - -sUSE_SDL_MIXER=2 - -sUSE_SDL_GFX=2 - -sSDL2_IMAGE_FORMATS=["png"] + target_link_libraries(${EX_NAME} + -sWASM=1 + -sUSE_SDL=2 + -sUSE_SDL_IMAGE=2 + -sUSE_SDL_TTF=2 + -sUSE_SDL_MIXER=2 + -sUSE_SDL_GFX=2 + -sSDL2_IMAGE_FORMATS=["png"] -sDEMANGLE_SUPPORT=1 -sTOTAL_MEMORY=512MB -sDISABLE_EXCEPTION_CATCHING=0 - EnTT::EnTT + imported::entt afk ) - set_target_properties( - ${EX_NAME} - PROPERTIES - LINK_FLAGS - "--preload-file ${CMAKE_CURRENT_LIST_DIR}/assets@/assets --use-preload-plugins" + set_target_properties(${EX_NAME} + PROPERTIES + LINK_FLAGS "--preload-file ${CMAKE_CURRENT_LIST_DIR}/assets@/assets --use-preload-plugins" ) # Run of the mill executable @@ -74,16 +69,14 @@ foreach(EX_NAME ${EXAMPLES}) if(MINGW) target_link_libraries(${EX_NAME} -lmingw32) endif(MINGW) - - target_link_libraries( - ${EX_NAME} - -lm - ${SDL_MAIN_LIBRARY} - ${SDL_LIBRARY} - ${SDL_MIXER_LIBRARY} - ${SDL_IMAGE_LIBRARY} - ${SDL_TTF_LIBRARY} - ${SDL_GFX_LIBRARY} + + target_link_libraries(${EX_NAME} + -lm + SDL2::Main + SDL2::Image + SDL2::Mixer + SDL2::TTF + SDL2::GFX EnTT::EnTT afk ) @@ -91,4 +84,4 @@ foreach(EX_NAME ${EXAMPLES}) endforeach() # Export assets -file(COPY ${CMAKE_CURRENT_LIST_DIR}/assets/ DESTINATION ${CMAKE_SOURCE_DIR}/build/assets/) +file(COPY ${CMAKE_CURRENT_LIST_DIR}/assets/ DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/assets/) diff --git a/examples/ex_collision.cpp b/examples/src/ex_collision.cpp similarity index 100% rename from examples/ex_collision.cpp rename to examples/src/ex_collision.cpp diff --git a/examples/ex_display.cpp b/examples/src/ex_display.cpp similarity index 100% rename from examples/ex_display.cpp rename to examples/src/ex_display.cpp diff --git a/examples/ex_fps.cpp b/examples/src/ex_fps.cpp similarity index 100% rename from examples/ex_fps.cpp rename to examples/src/ex_fps.cpp diff --git a/examples/ex_keyboard.cpp b/examples/src/ex_keyboard.cpp similarity index 100% rename from examples/ex_keyboard.cpp rename to examples/src/ex_keyboard.cpp diff --git a/examples/ex_message_box.cpp b/examples/src/ex_message_box.cpp similarity index 100% rename from examples/ex_message_box.cpp rename to examples/src/ex_message_box.cpp diff --git a/examples/ex_mouse.cpp b/examples/src/ex_mouse.cpp similarity index 100% rename from examples/ex_mouse.cpp rename to examples/src/ex_mouse.cpp diff --git a/examples/ex_particles.cpp b/examples/src/ex_particles.cpp similarity index 100% rename from examples/ex_particles.cpp rename to examples/src/ex_particles.cpp diff --git a/examples/ex_physics.cpp b/examples/src/ex_physics.cpp similarity index 100% rename from examples/ex_physics.cpp rename to examples/src/ex_physics.cpp diff --git a/examples/ex_rotate.cpp b/examples/src/ex_rotate.cpp similarity index 100% rename from examples/ex_rotate.cpp rename to examples/src/ex_rotate.cpp diff --git a/examples/ex_sound.cpp b/examples/src/ex_sound.cpp similarity index 100% rename from examples/ex_sound.cpp rename to examples/src/ex_sound.cpp diff --git a/examples/ex_sprite.cpp b/examples/src/ex_sprite.cpp similarity index 100% rename from examples/ex_sprite.cpp rename to examples/src/ex_sprite.cpp diff --git a/examples/ex_ui.cpp b/examples/src/ex_ui.cpp similarity index 100% rename from examples/ex_ui.cpp rename to examples/src/ex_ui.cpp diff --git a/lib/cmake/Copyright.txt b/lib/cmake/Copyright.txt new file mode 100644 index 0000000..d17e35d --- /dev/null +++ b/lib/cmake/Copyright.txt @@ -0,0 +1,132 @@ +CMake - Cross Platform Makefile Generator +Copyright 2000-2019 Kitware, Inc. and Contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +* Neither the name of Kitware, Inc. nor the names of Contributors + may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------------------ + +The following individuals and institutions are among the Contributors: + +* Aaron C. Meadows +* Adriaan de Groot +* Aleksey Avdeev +* Alexander Neundorf +* Alexander Smorkalov +* Alexey Sokolov +* Alex Merry +* Alex Turbov +* Amine Ben Hassouna +* Andreas Pakulat +* Andreas Schneider +* André Rigland Brodtkorb +* Axel Huebl, Helmholtz-Zentrum Dresden - Rossendorf +* Benjamin Eikel +* Bjoern Ricks +* Brad Hards +* Christopher Harvey +* Christoph Grüninger +* Clement Creusot +* Daniel Blezek +* Daniel Pfeifer +* Enrico Scholz +* Eran Ifrah +* Esben Mose Hansen, Ange Optimization ApS +* Geoffrey Viola +* Google Inc +* Gregor Jasny +* Helio Chissini de Castro +* Ilya Lavrenov +* Insight Software Consortium +* Jan Woetzel +* Julien Schueller +* Kelly Thompson +* Laurent Montel +* Konstantin Podsvirov +* Mario Bensi +* Martin Gräßlin +* Mathieu Malaterre +* Matthaeus G. Chajdas +* Matthias Kretz +* Matthias Maennich +* Michael Hirsch, Ph.D. +* Michael Stürmer +* Miguel A. Figueroa-Villanueva +* Mike Jackson +* Mike McQuaid +* Nicolas Bock +* Nicolas Despres +* Nikita Krupen'ko +* NVIDIA Corporation +* OpenGamma Ltd. +* Patrick Stotko +* Per Øyvind Karlsen +* Peter Collingbourne +* Petr Gotthard +* Philip Lowman +* Philippe Proulx +* Raffi Enficiaud, Max Planck Society +* Raumfeld +* Roger Leigh +* Rolf Eike Beer +* Roman Donchenko +* Roman Kharitonov +* Ruslan Baratov +* Sebastian Holtermann +* Stephen Kelly +* Sylvain Joubert +* Thomas Sondergaard +* Tobias Hunger +* Todd Gamblin +* Tristan Carel +* University of Dundee +* Vadim Zhukov +* Will Dicharry + +See version control history for details of individual contributions. + +The above copyright and license notice applies to distributions of +CMake in source and binary form. Third-party software packages supplied +with CMake under compatible licenses provide their own copyright notices +documented in corresponding subdirectories or source files. + +------------------------------------------------------------------------------ + +CMake was initially developed by Kitware with the following sponsorship: + + * National Library of Medicine at the National Institutes of Health + as part of the Insight Segmentation and Registration Toolkit (ITK). + + * US National Labs (Los Alamos, Livermore, Sandia) ASC Parallel + Visualization Initiative. + + * National Alliance for Medical Image Computing (NAMIC) is funded by the + National Institutes of Health through the NIH Roadmap for Medical Research, + Grant U54 EB005149. + + * Kitware, Inc. diff --git a/lib/cmake/FindSDL2.cmake b/lib/cmake/FindSDL2.cmake new file mode 100644 index 0000000..598890f --- /dev/null +++ b/lib/cmake/FindSDL2.cmake @@ -0,0 +1,392 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +# Copyright 2019 Amine Ben Hassouna +# Copyright 2000-2019 Kitware, Inc. and Contributors +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: + +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# * Neither the name of Kitware, Inc. nor the names of Contributors +# may be used to endorse or promote products derived from this +# software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#[=======================================================================[.rst: +FindSDL2 +-------- + +Locate SDL2 library + +This module defines the following 'IMPORTED' targets: + +:: + + SDL2::Core (for compatibility with older versions) + SDL2::SDL2 (compatibility with CONFIG mode) + The SDL2 library, if found. + Libraries should link to SDL2::SDL2 + + SDL2::Main (for compatibility with older versions) + SDL2::SDL2main (compatibility with CONFIG mode) + The SDL2main library, if found. + Applications should link to SDL2::SDL2main instead of SDL2::SDL2 + + + +This module will set the following variables in your project: + +:: + + SDL2_LIBRARIES, the name of the library to link against + SDL2_INCLUDE_DIRS, where to find SDL.h + SDL2_FOUND, if false, do not try to link to SDL2 + SDL2MAIN_FOUND, if false, do not try to link to SDL2main + SDL2_VERSION_STRING, human-readable string containing the version of SDL2 + + + +This module responds to the following cache variables: + +:: + + SDL2_PATH + Set a custom SDL2 Library path (default: empty) + + SDL2_NO_DEFAULT_PATH + Disable search SDL2 Library in default path. + If SDL2_PATH (default: ON) + Else (default: OFF) + + SDL2_INCLUDE_DIR + SDL2 headers path. + + SDL2_LIBRARY + SDL2 Library (.dll, .so, .a, etc) path. + + SDL2MAIN_LIBRAY + SDL2main Library (.a) path. + + SDL2_BUILDING_LIBRARY + This flag is useful only when linking to SDL2_LIBRARIES insead of + SDL2::Main. It is required only when building a library that links to + SDL2_LIBRARIES, because only applications need main() (No need to also + link to SDL2main). + If this flag is defined, then no SDL2main will be added to SDL2_LIBRARIES + and no SDL2::Main target will be created. + + +Don't forget to include SDLmain.h and SDLmain.m in your project for the +OS X framework based version. (Other versions link to -lSDL2main which +this module will try to find on your behalf.) Also for OS X, this +module will automatically add the -framework Cocoa on your behalf. + + +Additional Note: If you see an empty SDL2_LIBRARY in your project +configuration, it means CMake did not find your SDL2 library +(SDL2.dll, libsdl2.so, SDL2.framework, etc). Set SDL2_LIBRARY to point +to your SDL2 library, and configure again. Similarly, if you see an +empty SDL2MAIN_LIBRARY, you should set this value as appropriate. These +values are used to generate the final SDL2_LIBRARIES variable and the +SDL2::Core and SDL2::Main targets, but when these values are unset, +SDL2_LIBRARIES, SDL2::Core and SDL2::Main does not get created. + + +$SDL2DIR is an environment variable that would correspond to the +./configure --prefix=$SDL2DIR used in building SDL2. l.e.galup 9-20-02 + + + +Created by Amine Ben Hassouna: + Adapt FindSDL.cmake to SDL2 (FindSDL2.cmake). + Add cache variables for more flexibility: + SDL2_PATH, SDL2_NO_DEFAULT_PATH (for details, see doc above). + Mark 'Threads' as a required dependency for non-OSX systems. + Modernize the FindSDL2.cmake module by creating specific targets: + SDL2::Core and SDL2::Main (for details, see doc above). + + +Original FindSDL.cmake module: + Modified by Eric Wing. Added code to assist with automated building + by using environmental variables and providing a more + controlled/consistent search behavior. Added new modifications to + recognize OS X frameworks and additional Unix paths (FreeBSD, etc). + Also corrected the header search path to follow "proper" SDL + guidelines. Added a search for SDLmain which is needed by some + platforms. Added a search for threads which is needed by some + platforms. Added needed compile switches for MinGW. + +On OSX, this will prefer the Framework version (if found) over others. +People will have to manually change the cache value of SDL2_LIBRARY to +override this selection or set the SDL2_PATH variable or the CMake +environment CMAKE_INCLUDE_PATH to modify the search paths. + +Note that the header path has changed from SDL/SDL.h to just SDL.h +This needed to change because "proper" SDL convention is #include +"SDL.h", not . This is done for portability reasons +because not all systems place things in SDL/ (see FreeBSD). +#]=======================================================================] + +# Define options for searching SDL2 Library in a custom path + +set(SDL2_PATH "" CACHE STRING "Custom SDL2 Library path") + +set(_SDL2_NO_DEFAULT_PATH OFF) +if(SDL2_PATH) + set(_SDL2_NO_DEFAULT_PATH ON) +endif() + +set(SDL2_NO_DEFAULT_PATH ${_SDL2_NO_DEFAULT_PATH} + CACHE BOOL "Disable search SDL2 Library in default path") +unset(_SDL2_NO_DEFAULT_PATH) + +set(SDL2_NO_DEFAULT_PATH_CMD) +if(SDL2_NO_DEFAULT_PATH) + set(SDL2_NO_DEFAULT_PATH_CMD NO_DEFAULT_PATH) +endif() + +# Search for the SDL2 include directory +find_path(SDL2_INCLUDE_DIR SDL.h + HINTS + ENV SDL2DIR + ${SDL2_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES SDL2 + # path suffixes to search inside ENV{SDL2DIR} + include/SDL2 include + PATHS ${SDL2_PATH} + DOC "Where the SDL2 headers can be found" +) + +set(SDL2_INCLUDE_DIRS "${SDL2_INCLUDE_DIR}") + +if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(VC_LIB_PATH_SUFFIX lib/x64) +else() + set(VC_LIB_PATH_SUFFIX lib/x86) +endif() + +# SDL-2.0 is the name used by FreeBSD ports... +# don't confuse it for the version number. +find_library(SDL2_LIBRARY + NAMES SDL2 SDL-2.0 + HINTS + ENV SDL2DIR + ${SDL2_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX} + PATHS ${SDL2_PATH} + DOC "Where the SDL2 Library can be found" +) + +set(SDL2_LIBRARIES "${SDL2_LIBRARY}") + +if(NOT SDL2_BUILDING_LIBRARY) + if(NOT SDL2_INCLUDE_DIR MATCHES ".framework") + # Non-OS X framework versions expect you to also dynamically link to + # SDL2main. This is mainly for Windows and OS X. Other (Unix) platforms + # seem to provide SDL2main for compatibility even though they don't + # necessarily need it. + + if(SDL2_PATH) + set(SDL2MAIN_LIBRARY_PATHS "${SDL2_PATH}") + endif() + + if(NOT SDL2_NO_DEFAULT_PATH) + set(SDL2MAIN_LIBRARY_PATHS + /sw + /opt/local + /opt/csw + /opt + "${SDL2MAIN_LIBRARY_PATHS}" + ) + endif() + + find_library(SDL2MAIN_LIBRARY + NAMES SDL2main + HINTS + ENV SDL2DIR + ${SDL2_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX} + PATHS ${SDL2MAIN_LIBRARY_PATHS} + DOC "Where the SDL2main library can be found" + ) + unset(SDL2MAIN_LIBRARY_PATHS) + endif() +endif() + +# SDL2 may require threads on your system. +# The Apple build may not need an explicit flag because one of the +# frameworks may already provide it. +# But for non-OSX systems, I will use the CMake Threads package. +if(NOT APPLE) + find_package(Threads QUIET) + if(NOT Threads_FOUND) + set(SDL2_THREADS_NOT_FOUND "Could NOT find Threads (Threads is required by SDL2).") + if(SDL2_FIND_REQUIRED) + message(FATAL_ERROR ${SDL2_THREADS_NOT_FOUND}) + else() + if(NOT SDL2_FIND_QUIETLY) + message(STATUS ${SDL2_THREADS_NOT_FOUND}) + endif() + return() + endif() + unset(SDL2_THREADS_NOT_FOUND) + endif() +endif() + +# MinGW needs an additional link flag, -mwindows +# It's total link flags should look like -lmingw32 -lSDL2main -lSDL2 -mwindows +if(MINGW) + set(MINGW32_LIBRARY mingw32 "-mwindows" CACHE STRING "link flags for MinGW") +endif() + +if(SDL2_LIBRARY) + # For SDL2main + if(SDL2MAIN_LIBRARY AND NOT SDL2_BUILDING_LIBRARY) + list(FIND SDL2_LIBRARIES "${SDL2MAIN_LIBRARY}" _SDL2_MAIN_INDEX) + if(_SDL2_MAIN_INDEX EQUAL -1) + set(SDL2_LIBRARIES "${SDL2MAIN_LIBRARY}" ${SDL2_LIBRARIES}) + endif() + unset(_SDL2_MAIN_INDEX) + endif() + + # For OS X, SDL2 uses Cocoa as a backend so it must link to Cocoa. + # CMake doesn't display the -framework Cocoa string in the UI even + # though it actually is there if I modify a pre-used variable. + # I think it has something to do with the CACHE STRING. + # So I use a temporary variable until the end so I can set the + # "real" variable in one-shot. + if(APPLE) + set(SDL2_LIBRARIES ${SDL2_LIBRARIES} -framework Cocoa) + endif() + + # For threads, as mentioned Apple doesn't need this. + # In fact, there seems to be a problem if I used the Threads package + # and try using this line, so I'm just skipping it entirely for OS X. + if(NOT APPLE) + set(SDL2_LIBRARIES ${SDL2_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) + endif() + + # For MinGW library + if(MINGW) + set(SDL2_LIBRARIES ${MINGW32_LIBRARY} ${SDL2_LIBRARIES}) + endif() + +endif() + +# Read SDL2 version +if(SDL2_INCLUDE_DIR AND EXISTS "${SDL2_INCLUDE_DIR}/SDL_version.h") + file(STRINGS "${SDL2_INCLUDE_DIR}/SDL_version.h" SDL2_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL_MAJOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_INCLUDE_DIR}/SDL_version.h" SDL2_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL_MINOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_INCLUDE_DIR}/SDL_version.h" SDL2_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL_PATCHLEVEL[ \t]+[0-9]+$") + string(REGEX REPLACE "^#define[ \t]+SDL_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_VERSION_MAJOR "${SDL2_VERSION_MAJOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_VERSION_MINOR "${SDL2_VERSION_MINOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_VERSION_PATCH "${SDL2_VERSION_PATCH_LINE}") + set(SDL2_VERSION_STRING ${SDL2_VERSION_MAJOR}.${SDL2_VERSION_MINOR}.${SDL2_VERSION_PATCH}) + unset(SDL2_VERSION_MAJOR_LINE) + unset(SDL2_VERSION_MINOR_LINE) + unset(SDL2_VERSION_PATCH_LINE) + unset(SDL2_VERSION_MAJOR) + unset(SDL2_VERSION_MINOR) + unset(SDL2_VERSION_PATCH) +endif() + +include(FindPackageHandleStandardArgs) + +set(SDL2_REQUIRED_VARS SDL2_LIBRARY SDL2_INCLUDE_DIR) +if(SDL2MAIN_LIBRARY) + list(APPEND SDL2_REQUIRED_VARS SDL2MAIN_LIBRARY SDL2_INCLUDE_DIR) +endif() + +find_package_handle_standard_args(SDL2 + REQUIRED_VARS ${SDL2_REQUIRED_VARS} + VERSION_VAR SDL2_VERSION_STRING) + +mark_as_advanced(SDL2_PATH + SDL2_NO_DEFAULT_PATH + SDL2_LIBRARY + SDL2MAIN_LIBRARY + SDL2_INCLUDE_DIR + SDL2_BUILDING_LIBRARY) + + +# SDL2:: targets (SDL2::Core and SDL2::Main) +if(SDL2_FOUND) + + # SDL2::Core target + if(SDL2_LIBRARY AND NOT TARGET SDL2::Core) + add_library(SDL2::Core UNKNOWN IMPORTED) + set_target_properties(SDL2::Core PROPERTIES + IMPORTED_LOCATION "${SDL2_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${SDL2_INCLUDE_DIR}") + + if(APPLE) + # For OS X, SDL2 uses Cocoa as a backend so it must link to Cocoa. + # For more details, please see above. + set_property(TARGET SDL2::Core APPEND PROPERTY + INTERFACE_LINK_OPTIONS -framework Cocoa) + else() + # For threads, as mentioned Apple doesn't need this. + # For more details, please see above. + set_property(TARGET SDL2::Core APPEND PROPERTY + INTERFACE_LINK_LIBRARIES Threads::Threads) + endif() + endif() + + # SDL2::Main target + # Applications should link to SDL2::Main instead of SDL2::Core + # For more details, please see above. + if(NOT SDL2_BUILDING_LIBRARY AND NOT TARGET SDL2::Main) + + if(SDL2_INCLUDE_DIR MATCHES ".framework" OR NOT SDL2MAIN_LIBRARY) + add_library(SDL2::Main INTERFACE IMPORTED) + set_property(TARGET SDL2::Main PROPERTY + INTERFACE_LINK_LIBRARIES SDL2::Core) + elseif(SDL2MAIN_LIBRARY) + # MinGW requires that the mingw32 library is specified before the + # libSDL2main.a static library when linking. + # The SDL2::MainInternal target is used internally to make sure that + # CMake respects this condition. + add_library(SDL2::MainInternal UNKNOWN IMPORTED) + set_property(TARGET SDL2::MainInternal PROPERTY + IMPORTED_LOCATION "${SDL2MAIN_LIBRARY}") + set_property(TARGET SDL2::MainInternal PROPERTY + INTERFACE_LINK_LIBRARIES SDL2::Core) + + add_library(SDL2::Main INTERFACE IMPORTED) + + if(MINGW) + # MinGW needs an additional link flag '-mwindows' and link to mingw32 + set_property(TARGET SDL2::Main PROPERTY + INTERFACE_LINK_LIBRARIES "mingw32" "-mwindows") + endif() + + set_property(TARGET SDL2::Main APPEND PROPERTY + INTERFACE_LINK_LIBRARIES SDL2::MainInternal) + endif() + + # compatibility targets + add_library(SDL2::SDL2 ALIAS SDL2::Core) + add_library(SDL2::SDL2main ALIAS SDL2::Main) + + endif() +endif() diff --git a/lib/cmake/FindSDL2_gfx.cmake b/lib/cmake/FindSDL2_gfx.cmake new file mode 100644 index 0000000..970a92d --- /dev/null +++ b/lib/cmake/FindSDL2_gfx.cmake @@ -0,0 +1,222 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +# Copyright 2019 Amine Ben Hassouna +# Copyright 2000-2019 Kitware, Inc. and Contributors +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: + +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# * Neither the name of Kitware, Inc. nor the names of Contributors +# may be used to endorse or promote products derived from this +# software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#[=======================================================================[.rst: +FindSDL2_gfx +-------------- + +Locate SDL2_gfx library + +This module defines the following 'IMPORTED' target: + +:: + + SDL2::GFX + The SDL2_gfx library, if found. + Have SDL2::Core as a link dependency. + + + +This module will set the following variables in your project: + +:: + + SDL2_GFX_LIBRARIES, the name of the library to link against + SDL2_GFX_INCLUDE_DIRS, where to find the headers + SDL2_GFX_FOUND, if false, do not try to link against + SDL2_GFX_VERSION_STRING - human-readable string containing the + version of SDL2_gfx + + + +This module responds to the following cache variables: + +:: + + SDL2_GFX_PATH + Set a custom SDL2_gfx Library path (default: empty) + + SDL2_GFX_NO_DEFAULT_PATH + Disable search SDL2_gfx Library in default path. + If SDL2_GFX_PATH (default: ON) + Else (default: OFF) + + SDL2_GFX_INCLUDE_DIR + SDL2_gfx headers path. + + SDL2_GFX_LIBRARY + SDL2_gfx Library (.dll, .so, .a, etc) path. + + +Additional Note: If you see an empty SDL2_GFX_LIBRARY in your project +configuration, it means CMake did not find your SDL2_gfx library +(SDL2_gfx.dll, libsdl2_gfx.so, etc). Set SDL2_GFX_LIBRARY to point +to your SDL2_gfx library, and configure again. This value is used to +generate the final SDL2_GFX_LIBRARIES variable and the SDL2::GFX target, +but when this value is unset, SDL2_GFX_LIBRARIES and SDL2::GFX does not +get created. + + +$SDL2GFXDIR is an environment variable that would correspond to the +./configure --prefix=$SDL2GFXDIR used in building SDL2_gfx. + +$SDL2DIR is an environment variable that would correspond to the +./configure --prefix=$SDL2DIR used in building SDL2. + + + +Created by Amine Ben Hassouna: + Adapt FindSDL_image.cmake to SDL2_gfx (FindSDL2_gfx.cmake). + Add cache variables for more flexibility: + SDL2_GFX_PATH, SDL2_GFX_NO_DEFAULT_PATH (for details, see doc above). + Add SDL2 as a required dependency. + Modernize the FindSDL2_gfx.cmake module by creating a specific target: + SDL2::GFX (for details, see doc above). + +Original FindSDL_image.cmake module: + Created by Eric Wing. This was influenced by the FindSDL.cmake + module, but with modifications to recognize OS X frameworks and + additional Unix paths (FreeBSD, etc). +#]=======================================================================] + +# SDL2 Library required +find_package(SDL2 QUIET) +if(NOT SDL2_FOUND) + set(SDL2_GFX_SDL2_NOT_FOUND "Could NOT find SDL2 (SDL2 is required by SDL2_gfx).") + if(SDL2_gfx_FIND_REQUIRED) + message(FATAL_ERROR ${SDL2_GFX_SDL2_NOT_FOUND}) + else() + if(NOT SDL2_gfx_FIND_QUIETLY) + message(STATUS ${SDL2_GFX_SDL2_NOT_FOUND}) + endif() + return() + endif() + unset(SDL2_GFX_SDL2_NOT_FOUND) +endif() + + +# Define options for searching SDL2_gfx Library in a custom path + +set(SDL2_GFX_PATH "" CACHE STRING "Custom SDL2_gfx Library path") + +set(_SDL2_GFX_NO_DEFAULT_PATH OFF) +if(SDL2_GFX_PATH) + set(_SDL2_GFX_NO_DEFAULT_PATH ON) +endif() + +set(SDL2_GFX_NO_DEFAULT_PATH ${_SDL2_GFX_NO_DEFAULT_PATH} + CACHE BOOL "Disable search SDL2_gfx Library in default path") +unset(_SDL2_GFX_NO_DEFAULT_PATH) + +set(SDL2_GFX_NO_DEFAULT_PATH_CMD) +if(SDL2_GFX_NO_DEFAULT_PATH) + set(SDL2_GFX_NO_DEFAULT_PATH_CMD NO_DEFAULT_PATH) +endif() + +# Search for the SDL2_gfx include directory +find_path(SDL2_GFX_INCLUDE_DIR SDL2_gfxPrimitives.h + HINTS + ENV SDL2GFXDIR + ENV SDL2DIR + ${SDL2_GFX_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES SDL2 + # path suffixes to search inside ENV{SDL2DIR} + # and ENV{SDL2GFXDIR} + include/SDL2 include + PATHS ${SDL2_GFX_PATH} + DOC "Where the SDL2_gfx headers can be found" +) + +if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(VC_LIB_PATH_SUFFIX lib/x64) +else() + set(VC_LIB_PATH_SUFFIX lib/x86) +endif() + +# Search for the SDL2_gfx library +find_library(SDL2_GFX_LIBRARY + NAMES SDL2_gfx + HINTS + ENV SDL2GFXDIR + ENV SDL2DIR + ${SDL2_GFX_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX} + PATHS ${SDL2_GFX_PATH} + DOC "Where the SDL2_gfx Library can be found" +) + +# Read SDL2_gfx version +if(SDL2_GFX_INCLUDE_DIR AND EXISTS "${SDL2_GFX_INCLUDE_DIR}/SDL2_gfxPrimitives.h") + file(STRINGS "${SDL2_GFX_INCLUDE_DIR}/SDL2_gfxPrimitives.h" SDL2_GFX_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL2_GFXPRIMITIVES_MAJOR[ \t]+[0-9]+$") + file(STRINGS "${SDL2_GFX_INCLUDE_DIR}/SDL2_gfxPrimitives.h" SDL2_GFX_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL2_GFXPRIMITIVES_MINOR[ \t]+[0-9]+$") + file(STRINGS "${SDL2_GFX_INCLUDE_DIR}/SDL2_gfxPrimitives.h" SDL2_GFX_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL2_GFXPRIMITIVES_MICRO[ \t]+[0-9]+$") + string(REGEX REPLACE "^#define[ \t]+SDL2_GFXPRIMITIVES_MAJOR[ \t]+([0-9]+)$" "\\1" SDL2_GFX_VERSION_MAJOR "${SDL2_GFX_VERSION_MAJOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL2_GFXPRIMITIVES_MINOR[ \t]+([0-9]+)$" "\\1" SDL2_GFX_VERSION_MINOR "${SDL2_GFX_VERSION_MINOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL2_GFXPRIMITIVES_MICRO[ \t]+([0-9]+)$" "\\1" SDL2_GFX_VERSION_PATCH "${SDL2_GFX_VERSION_PATCH_LINE}") + set(SDL2_GFX_VERSION_STRING ${SDL2_GFX_VERSION_MAJOR}.${SDL2_GFX_VERSION_MINOR}.${SDL2_GFX_VERSION_PATCH}) + unset(SDL2_GFX_VERSION_MAJOR_LINE) + unset(SDL2_GFX_VERSION_MINOR_LINE) + unset(SDL2_GFX_VERSION_PATCH_LINE) + unset(SDL2_GFX_VERSION_MAJOR) + unset(SDL2_GFX_VERSION_MINOR) + unset(SDL2_GFX_VERSION_PATCH) +endif() + +set(SDL2_GFX_LIBRARIES ${SDL2_GFX_LIBRARY}) +set(SDL2_GFX_INCLUDE_DIRS ${SDL2_GFX_INCLUDE_DIR}) + +include(FindPackageHandleStandardArgs) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_gfx + REQUIRED_VARS SDL2_GFX_LIBRARIES SDL2_GFX_INCLUDE_DIRS + VERSION_VAR SDL2_GFX_VERSION_STRING) + + +mark_as_advanced(SDL2_GFX_PATH + SDL2_GFX_NO_DEFAULT_PATH + SDL2_GFX_LIBRARY + SDL2_GFX_INCLUDE_DIR) + + +if(SDL2_GFX_FOUND) + + # SDL2::GFX target + if(SDL2_GFX_LIBRARY AND NOT TARGET SDL2::GFX) + add_library(SDL2::GFX UNKNOWN IMPORTED) + set_target_properties(SDL2::GFX PROPERTIES + IMPORTED_LOCATION "${SDL2_GFX_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${SDL2_GFX_INCLUDE_DIR}" + INTERFACE_LINK_LIBRARIES SDL2::Core) + endif() +endif() diff --git a/lib/cmake/FindSDL2_image.cmake b/lib/cmake/FindSDL2_image.cmake new file mode 100644 index 0000000..624e915 --- /dev/null +++ b/lib/cmake/FindSDL2_image.cmake @@ -0,0 +1,222 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +# Copyright 2019 Amine Ben Hassouna +# Copyright 2000-2019 Kitware, Inc. and Contributors +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: + +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# * Neither the name of Kitware, Inc. nor the names of Contributors +# may be used to endorse or promote products derived from this +# software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#[=======================================================================[.rst: +FindSDL2_image +-------------- + +Locate SDL2_image library + +This module defines the following 'IMPORTED' target: + +:: + + SDL2::Image + The SDL2_image library, if found. + Have SDL2::Core as a link dependency. + + + +This module will set the following variables in your project: + +:: + + SDL2_IMAGE_LIBRARIES, the name of the library to link against + SDL2_IMAGE_INCLUDE_DIRS, where to find the headers + SDL2_IMAGE_FOUND, if false, do not try to link against + SDL2_IMAGE_VERSION_STRING - human-readable string containing the + version of SDL2_image + + + +This module responds to the following cache variables: + +:: + + SDL2_IMAGE_PATH + Set a custom SDL2_image Library path (default: empty) + + SDL2_IMAGE_NO_DEFAULT_PATH + Disable search SDL2_image Library in default path. + If SDL2_IMAGE_PATH (default: ON) + Else (default: OFF) + + SDL2_IMAGE_INCLUDE_DIR + SDL2_image headers path. + + SDL2_IMAGE_LIBRARY + SDL2_image Library (.dll, .so, .a, etc) path. + + +Additional Note: If you see an empty SDL2_IMAGE_LIBRARY in your project +configuration, it means CMake did not find your SDL2_image library +(SDL2_image.dll, libsdl2_image.so, etc). Set SDL2_IMAGE_LIBRARY to point +to your SDL2_image library, and configure again. This value is used to +generate the final SDL2_IMAGE_LIBRARIES variable and the SDL2::Image target, +but when this value is unset, SDL2_IMAGE_LIBRARIES and SDL2::Image does not +get created. + + +$SDL2IMAGEDIR is an environment variable that would correspond to the +./configure --prefix=$SDL2IMAGEDIR used in building SDL2_image. + +$SDL2DIR is an environment variable that would correspond to the +./configure --prefix=$SDL2DIR used in building SDL2. + + + +Created by Amine Ben Hassouna: + Adapt FindSDL_image.cmake to SDL2_image (FindSDL2_image.cmake). + Add cache variables for more flexibility: + SDL2_IMAGE_PATH, SDL2_IMAGE_NO_DEFAULT_PATH (for details, see doc above). + Add SDL2 as a required dependency. + Modernize the FindSDL2_image.cmake module by creating a specific target: + SDL2::Image (for details, see doc above). + +Original FindSDL_image.cmake module: + Created by Eric Wing. This was influenced by the FindSDL.cmake + module, but with modifications to recognize OS X frameworks and + additional Unix paths (FreeBSD, etc). +#]=======================================================================] + +# SDL2 Library required +find_package(SDL2 QUIET) +if(NOT SDL2_FOUND) + set(SDL2_IMAGE_SDL2_NOT_FOUND "Could NOT find SDL2 (SDL2 is required by SDL2_image).") + if(SDL2_image_FIND_REQUIRED) + message(FATAL_ERROR ${SDL2_IMAGE_SDL2_NOT_FOUND}) + else() + if(NOT SDL2_image_FIND_QUIETLY) + message(STATUS ${SDL2_IMAGE_SDL2_NOT_FOUND}) + endif() + return() + endif() + unset(SDL2_IMAGE_SDL2_NOT_FOUND) +endif() + + +# Define options for searching SDL2_image Library in a custom path + +set(SDL2_IMAGE_PATH "" CACHE STRING "Custom SDL2_image Library path") + +set(_SDL2_IMAGE_NO_DEFAULT_PATH OFF) +if(SDL2_IMAGE_PATH) + set(_SDL2_IMAGE_NO_DEFAULT_PATH ON) +endif() + +set(SDL2_IMAGE_NO_DEFAULT_PATH ${_SDL2_IMAGE_NO_DEFAULT_PATH} + CACHE BOOL "Disable search SDL2_image Library in default path") +unset(_SDL2_IMAGE_NO_DEFAULT_PATH) + +set(SDL2_IMAGE_NO_DEFAULT_PATH_CMD) +if(SDL2_IMAGE_NO_DEFAULT_PATH) + set(SDL2_IMAGE_NO_DEFAULT_PATH_CMD NO_DEFAULT_PATH) +endif() + +# Search for the SDL2_image include directory +find_path(SDL2_IMAGE_INCLUDE_DIR SDL_image.h + HINTS + ENV SDL2IMAGEDIR + ENV SDL2DIR + ${SDL2_IMAGE_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES SDL2 + # path suffixes to search inside ENV{SDL2DIR} + # and ENV{SDL2IMAGEDIR} + include/SDL2 include + PATHS ${SDL2_IMAGE_PATH} + DOC "Where the SDL2_image headers can be found" +) + +if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(VC_LIB_PATH_SUFFIX lib/x64) +else() + set(VC_LIB_PATH_SUFFIX lib/x86) +endif() + +# Search for the SDL2_image library +find_library(SDL2_IMAGE_LIBRARY + NAMES SDL2_image + HINTS + ENV SDL2IMAGEDIR + ENV SDL2DIR + ${SDL2_IMAGE_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX} + PATHS ${SDL2_IMAGE_PATH} + DOC "Where the SDL2_image Library can be found" +) + +# Read SDL2_image version +if(SDL2_IMAGE_INCLUDE_DIR AND EXISTS "${SDL2_IMAGE_INCLUDE_DIR}/SDL_image.h") + file(STRINGS "${SDL2_IMAGE_INCLUDE_DIR}/SDL_image.h" SDL2_IMAGE_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL_IMAGE_MAJOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_IMAGE_INCLUDE_DIR}/SDL_image.h" SDL2_IMAGE_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL_IMAGE_MINOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_IMAGE_INCLUDE_DIR}/SDL_image.h" SDL2_IMAGE_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL_IMAGE_PATCHLEVEL[ \t]+[0-9]+$") + string(REGEX REPLACE "^#define[ \t]+SDL_IMAGE_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_IMAGE_VERSION_MAJOR "${SDL2_IMAGE_VERSION_MAJOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_IMAGE_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_IMAGE_VERSION_MINOR "${SDL2_IMAGE_VERSION_MINOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_IMAGE_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_IMAGE_VERSION_PATCH "${SDL2_IMAGE_VERSION_PATCH_LINE}") + set(SDL2_IMAGE_VERSION_STRING ${SDL2_IMAGE_VERSION_MAJOR}.${SDL2_IMAGE_VERSION_MINOR}.${SDL2_IMAGE_VERSION_PATCH}) + unset(SDL2_IMAGE_VERSION_MAJOR_LINE) + unset(SDL2_IMAGE_VERSION_MINOR_LINE) + unset(SDL2_IMAGE_VERSION_PATCH_LINE) + unset(SDL2_IMAGE_VERSION_MAJOR) + unset(SDL2_IMAGE_VERSION_MINOR) + unset(SDL2_IMAGE_VERSION_PATCH) +endif() + +set(SDL2_IMAGE_LIBRARIES ${SDL2_IMAGE_LIBRARY}) +set(SDL2_IMAGE_INCLUDE_DIRS ${SDL2_IMAGE_INCLUDE_DIR}) + +include(FindPackageHandleStandardArgs) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_image + REQUIRED_VARS SDL2_IMAGE_LIBRARIES SDL2_IMAGE_INCLUDE_DIRS + VERSION_VAR SDL2_IMAGE_VERSION_STRING) + + +mark_as_advanced(SDL2_IMAGE_PATH + SDL2_IMAGE_NO_DEFAULT_PATH + SDL2_IMAGE_LIBRARY + SDL2_IMAGE_INCLUDE_DIR) + + +if(SDL2_IMAGE_FOUND) + + # SDL2::Image target + if(SDL2_IMAGE_LIBRARY AND NOT TARGET SDL2::Image) + add_library(SDL2::Image UNKNOWN IMPORTED) + set_target_properties(SDL2::Image PROPERTIES + IMPORTED_LOCATION "${SDL2_IMAGE_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${SDL2_IMAGE_INCLUDE_DIR}" + INTERFACE_LINK_LIBRARIES SDL2::Core) + endif() +endif() diff --git a/lib/cmake/FindSDL2_mixer.cmake b/lib/cmake/FindSDL2_mixer.cmake new file mode 100644 index 0000000..a71f26a --- /dev/null +++ b/lib/cmake/FindSDL2_mixer.cmake @@ -0,0 +1,220 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +# Copyright 2019 Amine Ben Hassouna +# Copyright 2000-2019 Kitware, Inc. and Contributors +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: + +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# * Neither the name of Kitware, Inc. nor the names of Contributors +# may be used to endorse or promote products derived from this +# software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#[=======================================================================[.rst: +FindSDL2_mixer +-------------- + +Locate SDL2_mixer library + +This module defines the following 'IMPORTED' target: + +:: + + SDL2::Mixer + The SDL2_mixer library, if found. + Have SDL2::Core as a link dependency. + + + +This module will set the following variables in your project: + +:: + + SDL2_MIXER_LIBRARIES, the name of the library to link against + SDL2_MIXER_INCLUDE_DIRS, where to find the headers + SDL2_MIXER_FOUND, if false, do not try to link against + SDL2_MIXER_VERSION_STRING - human-readable string containing the + version of SDL2_mixer + +This module responds to the following cache variables: + +:: + + SDL2_MIXER_PATH + Set a custom SDL2_mixer Library path (default: empty) + + SDL2_MIXER_NO_DEFAULT_PATH + Disable search SDL2_mixer Library in default path. + If SDL2_MIXER_PATH (default: ON) + Else (default: OFF) + + SDL2_MIXER_INCLUDE_DIR + SDL2_mixer headers path. + + SDL2_MIXER_LIBRARY + SDL2_mixer Library (.dll, .so, .a, etc) path. + + +Additional Note: If you see an empty SDL2_MIXER_LIBRARY in your project +configuration, it means CMake did not find your SDL2_mixer library +(SDL2_mixer.dll, libsdl2_mixer.so, etc). Set SDL2_MIXER_LIBRARY to point +to your SDL2_mixer library, and configure again. This value is used to +generate the final SDL2_MIXER_LIBRARIES variable and the SDL2::Mixer target, +but when this value is unset, SDL2_MIXER_LIBRARIES and SDL2::Mixer does not +get created. + + +$SDL2MIXERDIR is an environment variable that would correspond to the +./configure --prefix=$SDL2MIXERDIR used in building SDL2_mixer. + +$SDL2DIR is an environment variable that would correspond to the +./configure --prefix=$SDL2DIR used in building SDL2. + + + +Created by Amine Ben Hassouna: + Adapt FindSDL_mixer.cmake to SDL2_mixer (FindSDL2_mixer.cmake). + Add cache variables for more flexibility: + SDL2_MIXER_PATH, SDL2_MIXER_NO_DEFAULT_PATH (for details, see doc above). + Add SDL2 as a required dependency. + Modernize the FindSDL2_mixer.cmake module by creating a specific target: + SDL2::Mixer (for details, see doc above). + +Original FindSDL_mixer.cmake module: + Created by Eric Wing. This was influenced by the FindSDL.cmake + module, but with modifications to recognize OS X frameworks and + additional Unix paths (FreeBSD, etc). +#]=======================================================================] + +# SDL2 Library required +find_package(SDL2 QUIET) +if(NOT SDL2_FOUND) + set(SDL2_MIXER_SDL2_NOT_FOUND "Could NOT find SDL2 (SDL2 is required by SDL2_mixer).") + if(SDL2_mixer_FIND_REQUIRED) + message(FATAL_ERROR ${SDL2_MIXER_SDL2_NOT_FOUND}) + else() + if(NOT SDL2_mixer_FIND_QUIETLY) + message(STATUS ${SDL2_MIXER_SDL2_NOT_FOUND}) + endif() + return() + endif() + unset(SDL2_MIXER_SDL2_NOT_FOUND) +endif() + + +# Define options for searching SDL2_mixer Library in a custom path + +set(SDL2_MIXER_PATH "" CACHE STRING "Custom SDL2_mixer Library path") + +set(_SDL2_MIXER_NO_DEFAULT_PATH OFF) +if(SDL2_MIXER_PATH) + set(_SDL2_MIXER_NO_DEFAULT_PATH ON) +endif() + +set(SDL2_MIXER_NO_DEFAULT_PATH ${_SDL2_MIXER_NO_DEFAULT_PATH} + CACHE BOOL "Disable search SDL2_mixer Library in default path") +unset(_SDL2_MIXER_NO_DEFAULT_PATH) + +set(SDL2_MIXER_NO_DEFAULT_PATH_CMD) +if(SDL2_MIXER_NO_DEFAULT_PATH) + set(SDL2_MIXER_NO_DEFAULT_PATH_CMD NO_DEFAULT_PATH) +endif() + +# Search for the SDL2_mixer include directory +find_path(SDL2_MIXER_INCLUDE_DIR SDL_mixer.h + HINTS + ENV SDL2MIXERDIR + ENV SDL2DIR + ${SDL2_MIXER_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES SDL2 + # path suffixes to search inside ENV{SDL2DIR} + # and ENV{SDL2MIXERDIR} + include/SDL2 include + PATHS ${SDL2_MIXER_PATH} + DOC "Where the SDL2_mixer headers can be found" +) + +if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(VC_LIB_PATH_SUFFIX lib/x64) +else() + set(VC_LIB_PATH_SUFFIX lib/x86) +endif() + +# Search for the SDL2_mixer library +find_library(SDL2_MIXER_LIBRARY + NAMES SDL2_mixer + HINTS + ENV SDL2MIXERDIR + ENV SDL2DIR + ${SDL2_MIXER_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX} + PATHS ${SDL2_MIXER_PATH} + DOC "Where the SDL2_mixer Library can be found" +) + +# Read SDL2_mixer version +if(SDL2_MIXER_INCLUDE_DIR AND EXISTS "${SDL2_MIXER_INCLUDE_DIR}/SDL_mixer.h") + file(STRINGS "${SDL2_MIXER_INCLUDE_DIR}/SDL_mixer.h" SDL2_MIXER_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL_MIXER_MAJOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_MIXER_INCLUDE_DIR}/SDL_mixer.h" SDL2_MIXER_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL_MIXER_MINOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_MIXER_INCLUDE_DIR}/SDL_mixer.h" SDL2_MIXER_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL_MIXER_PATCHLEVEL[ \t]+[0-9]+$") + string(REGEX REPLACE "^#define[ \t]+SDL_MIXER_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_MIXER_VERSION_MAJOR "${SDL2_MIXER_VERSION_MAJOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_MIXER_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_MIXER_VERSION_MINOR "${SDL2_MIXER_VERSION_MINOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_MIXER_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_MIXER_VERSION_PATCH "${SDL2_MIXER_VERSION_PATCH_LINE}") + set(SDL2_MIXER_VERSION_STRING ${SDL2_MIXER_VERSION_MAJOR}.${SDL2_MIXER_VERSION_MINOR}.${SDL2_MIXER_VERSION_PATCH}) + unset(SDL2_MIXER_VERSION_MAJOR_LINE) + unset(SDL2_MIXER_VERSION_MINOR_LINE) + unset(SDL2_MIXER_VERSION_PATCH_LINE) + unset(SDL2_MIXER_VERSION_MAJOR) + unset(SDL2_MIXER_VERSION_MINOR) + unset(SDL2_MIXER_VERSION_PATCH) +endif() + +set(SDL2_MIXER_LIBRARIES ${SDL2_MIXER_LIBRARY}) +set(SDL2_MIXER_INCLUDE_DIRS ${SDL2_MIXER_INCLUDE_DIR}) + +include(FindPackageHandleStandardArgs) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_mixer + REQUIRED_VARS SDL2_MIXER_LIBRARIES SDL2_MIXER_INCLUDE_DIRS + VERSION_VAR SDL2_MIXER_VERSION_STRING) + + +mark_as_advanced(SDL2_MIXER_PATH + SDL2_MIXER_NO_DEFAULT_PATH + SDL2_MIXER_LIBRARY + SDL2_MIXER_INCLUDE_DIR) + + +if(SDL2_MIXER_FOUND) + + # SDL2::Mixer target + if(SDL2_MIXER_LIBRARY AND NOT TARGET SDL2::Mixer) + add_library(SDL2::Mixer UNKNOWN IMPORTED) + set_target_properties(SDL2::Mixer PROPERTIES + IMPORTED_LOCATION "${SDL2_MIXER_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${SDL2_MIXER_INCLUDE_DIR}" + INTERFACE_LINK_LIBRARIES SDL2::Core) + endif() +endif() diff --git a/lib/cmake/FindSDL2_net.cmake b/lib/cmake/FindSDL2_net.cmake new file mode 100644 index 0000000..74c765b --- /dev/null +++ b/lib/cmake/FindSDL2_net.cmake @@ -0,0 +1,222 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +# Copyright 2019 Amine Ben Hassouna +# Copyright 2000-2019 Kitware, Inc. and Contributors +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: + +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# * Neither the name of Kitware, Inc. nor the names of Contributors +# may be used to endorse or promote products derived from this +# software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#[=======================================================================[.rst: +FindSDL2_net +------------ + +Locate SDL2_net library + +This module defines the following 'IMPORTED' target: + +:: + + SDL2::Net + The SDL2_net library, if found. + Have SDL2::Core as a link dependency. + + + +This module will set the following variables in your project: + +:: + + SDL2_NET_LIBRARIES, the name of the library to link against + SDL2_NET_INCLUDE_DIRS, where to find the headers + SDL2_NET_FOUND, if false, do not try to link against + SDL2_NET_VERSION_STRING - human-readable string containing the + version of SDL2_net + + + +This module responds to the following cache variables: + +:: + + SDL2_NET_PATH + Set a custom SDL2_net Library path (default: empty) + + SDL2_NET_NO_DEFAULT_PATH + Disable search SDL2_net Library in default path. + If SDL2_NET_PATH (default: ON) + Else (default: OFF) + + SDL2_NET_INCLUDE_DIR + SDL2_net headers path. + + SDL2_NET_LIBRARY + SDL2_net Library (.dll, .so, .a, etc) path. + + +Additional Note: If you see an empty SDL2_NET_LIBRARY in your project +configuration, it means CMake did not find your SDL2_net library +(SDL2_net.dll, libsdl2_net.so, etc). Set SDL2_NET_LIBRARY to point +to your SDL2_net library, and configure again. This value is used to +generate the final SDL2_NET_LIBRARIES variable and the SDL2::Net target, +but when this value is unset, SDL2_NET_LIBRARIES and SDL2::Net does not +get created. + + +$SDL2NETDIR is an environment variable that would correspond to the +./configure --prefix=$SDL2NETDIR used in building SDL2_net. + +$SDL2DIR is an environment variable that would correspond to the +./configure --prefix=$SDL2DIR used in building SDL2. + + + +Created by Amine Ben Hassouna: + Adapt FindSDL_net.cmake to SDL2_net (FindSDL2_net.cmake). + Add cache variables for more flexibility: + SDL2_NET_PATH, SDL2_NET_NO_DEFAULT_PATH (for details, see doc above). + Add SDL2 as a required dependency. + Modernize the FindSDL2_net.cmake module by creating a specific target: + SDL2::Net (for details, see doc above). + +Original FindSDL_net.cmake module: + Created by Eric Wing. This was influenced by the FindSDL.cmake + module, but with modifications to recognize OS X frameworks and + additional Unix paths (FreeBSD, etc). +#]=======================================================================] + +# SDL2 Library required +find_package(SDL2 QUIET) +if(NOT SDL2_FOUND) + set(SDL2_NET_SDL2_NOT_FOUND "Could NOT find SDL2 (SDL2 is required by SDL2_net).") + if(SDL2_net_FIND_REQUIRED) + message(FATAL_ERROR ${SDL2_NET_SDL2_NOT_FOUND}) + else() + if(NOT SDL2_net_FIND_QUIETLY) + message(STATUS ${SDL2_NET_SDL2_NOT_FOUND}) + endif() + return() + endif() + unset(SDL2_NET_SDL2_NOT_FOUND) +endif() + + +# Define options for searching SDL2_net Library in a custom path + +set(SDL2_NET_PATH "" CACHE STRING "Custom SDL2_net Library path") + +set(_SDL2_NET_NO_DEFAULT_PATH OFF) +if(SDL2_NET_PATH) + set(_SDL2_NET_NO_DEFAULT_PATH ON) +endif() + +set(SDL2_NET_NO_DEFAULT_PATH ${_SDL2_NET_NO_DEFAULT_PATH} + CACHE BOOL "Disable search SDL2_net Library in default path") +unset(_SDL2_NET_NO_DEFAULT_PATH) + +set(SDL2_NET_NO_DEFAULT_PATH_CMD) +if(SDL2_NET_NO_DEFAULT_PATH) + set(SDL2_NET_NO_DEFAULT_PATH_CMD NO_DEFAULT_PATH) +endif() + +# Search for the SDL2_net include directory +find_path(SDL2_NET_INCLUDE_DIR SDL_net.h + HINTS + ENV SDL2NETDIR + ENV SDL2DIR + ${SDL2_NET_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES SDL2 + # path suffixes to search inside ENV{SDL2DIR} + # and ENV{SDL2NETDIR} + include/SDL2 include + PATHS ${SDL2_NET_PATH} + DOC "Where the SDL2_net headers can be found" +) + +if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(VC_LIB_PATH_SUFFIX lib/x64) +else() + set(VC_LIB_PATH_SUFFIX lib/x86) +endif() + +# Search for the SDL2_net library +find_library(SDL2_NET_LIBRARY + NAMES SDL2_net + HINTS + ENV SDL2NETDIR + ENV SDL2DIR + ${SDL2_NET_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX} + PATHS ${SDL2_NET_PATH} + DOC "Where the SDL2_net Library can be found" +) + +# Read SDL2_net version +if(SDL2_NET_INCLUDE_DIR AND EXISTS "${SDL2_NET_INCLUDE_DIR}/SDL_net.h") + file(STRINGS "${SDL2_NET_INCLUDE_DIR}/SDL_net.h" SDL2_NET_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL_NET_MAJOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_NET_INCLUDE_DIR}/SDL_net.h" SDL2_NET_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL_NET_MINOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_NET_INCLUDE_DIR}/SDL_net.h" SDL2_NET_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL_NET_PATCHLEVEL[ \t]+[0-9]+$") + string(REGEX REPLACE "^#define[ \t]+SDL_NET_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_NET_VERSION_MAJOR "${SDL2_NET_VERSION_MAJOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_NET_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_NET_VERSION_MINOR "${SDL2_NET_VERSION_MINOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_NET_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_NET_VERSION_PATCH "${SDL2_NET_VERSION_PATCH_LINE}") + set(SDL2_NET_VERSION_STRING ${SDL2_NET_VERSION_MAJOR}.${SDL2_NET_VERSION_MINOR}.${SDL2_NET_VERSION_PATCH}) + unset(SDL2_NET_VERSION_MAJOR_LINE) + unset(SDL2_NET_VERSION_MINOR_LINE) + unset(SDL2_NET_VERSION_PATCH_LINE) + unset(SDL2_NET_VERSION_MAJOR) + unset(SDL2_NET_VERSION_MINOR) + unset(SDL2_NET_VERSION_PATCH) +endif() + +set(SDL2_NET_LIBRARIES ${SDL2_NET_LIBRARY}) +set(SDL2_NET_INCLUDE_DIRS ${SDL2_NET_INCLUDE_DIR}) + +include(FindPackageHandleStandardArgs) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_net + REQUIRED_VARS SDL2_NET_LIBRARIES SDL2_NET_INCLUDE_DIRS + VERSION_VAR SDL2_NET_VERSION_STRING) + + +mark_as_advanced(SDL2_NET_PATH + SDL2_NET_NO_DEFAULT_PATH + SDL2_NET_LIBRARY + SDL2_NET_INCLUDE_DIR) + + +if(SDL2_NET_FOUND) + + # SDL2::Net target + if(SDL2_NET_LIBRARY AND NOT TARGET SDL2::Net) + add_library(SDL2::Net UNKNOWN IMPORTED) + set_target_properties(SDL2::Net PROPERTIES + IMPORTED_LOCATION "${SDL2_NET_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${SDL2_NET_INCLUDE_DIR}" + INTERFACE_LINK_LIBRARIES SDL2::Core) + endif() +endif() diff --git a/lib/cmake/FindSDL2_ttf.cmake b/lib/cmake/FindSDL2_ttf.cmake new file mode 100644 index 0000000..2ab9a76 --- /dev/null +++ b/lib/cmake/FindSDL2_ttf.cmake @@ -0,0 +1,222 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +# Copyright 2019 Amine Ben Hassouna +# Copyright 2000-2019 Kitware, Inc. and Contributors +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: + +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# * Neither the name of Kitware, Inc. nor the names of Contributors +# may be used to endorse or promote products derived from this +# software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#[=======================================================================[.rst: +FindSDL2_ttf +------------ + +Locate SDL2_ttf library + +This module defines the following 'IMPORTED' target: + +:: + + SDL2::TTF + The SDL2_ttf library, if found. + Have SDL2::Core as a link dependency. + + + +This module will set the following variables in your project: + +:: + + SDL2_TTF_LIBRARIES, the name of the library to link against + SDL2_TTF_INCLUDE_DIRS, where to find the headers + SDL2_TTF_FOUND, if false, do not try to link against + SDL2_TTF_VERSION_STRING - human-readable string containing the + version of SDL2_ttf + + + +This module responds to the following cache variables: + +:: + + SDL2_TTF_PATH + Set a custom SDL2_ttf Library path (default: empty) + + SDL2_TTF_NO_DEFAULT_PATH + Disable search SDL2_ttf Library in default path. + If SDL2_TTF_PATH (default: ON) + Else (default: OFF) + + SDL2_TTF_INCLUDE_DIR + SDL2_ttf headers path. + + SDL2_TTF_LIBRARY + SDL2_ttf Library (.dll, .so, .a, etc) path. + + +Additional Note: If you see an empty SDL2_TTF_LIBRARY in your project +configuration, it means CMake did not find your SDL2_ttf library +(SDL2_ttf.dll, libsdl2_ttf.so, etc). Set SDL2_TTF_LIBRARY to point +to your SDL2_ttf library, and configure again. This value is used to +generate the final SDL2_TTF_LIBRARIES variable and the SDL2::TTF target, +but when this value is unset, SDL2_TTF_LIBRARIES and SDL2::TTF does not +get created. + + +$SDL2TTFDIR is an environment variable that would correspond to the +./configure --prefix=$SDL2TTFDIR used in building SDL2_ttf. + +$SDL2DIR is an environment variable that would correspond to the +./configure --prefix=$SDL2DIR used in building SDL2. + + + +Created by Amine Ben Hassouna: + Adapt FindSDL_ttf.cmake to SDL2_ttf (FindSDL2_ttf.cmake). + Add cache variables for more flexibility: + SDL2_TTF_PATH, SDL2_TTF_NO_DEFAULT_PATH (for details, see doc above). + Add SDL2 as a required dependency. + Modernize the FindSDL2_ttf.cmake module by creating a specific target: + SDL2::TTF (for details, see doc above). + +Original FindSDL_ttf.cmake module: + Created by Eric Wing. This was influenced by the FindSDL.cmake + module, but with modifications to recognize OS X frameworks and + additional Unix paths (FreeBSD, etc). +#]=======================================================================] + +# SDL2 Library required +find_package(SDL2 QUIET) +if(NOT SDL2_FOUND) + set(SDL2_TTF_SDL2_NOT_FOUND "Could NOT find SDL2 (SDL2 is required by SDL2_ttf).") + if(SDL2_ttf_FIND_REQUIRED) + message(FATAL_ERROR ${SDL2_TTF_SDL2_NOT_FOUND}) + else() + if(NOT SDL2_ttf_FIND_QUIETLY) + message(STATUS ${SDL2_TTF_SDL2_NOT_FOUND}) + endif() + return() + endif() + unset(SDL2_TTF_SDL2_NOT_FOUND) +endif() + + +# Define options for searching SDL2_ttf Library in a custom path + +set(SDL2_TTF_PATH "" CACHE STRING "Custom SDL2_ttf Library path") + +set(_SDL2_TTF_NO_DEFAULT_PATH OFF) +if(SDL2_TTF_PATH) + set(_SDL2_TTF_NO_DEFAULT_PATH ON) +endif() + +set(SDL2_TTF_NO_DEFAULT_PATH ${_SDL2_TTF_NO_DEFAULT_PATH} + CACHE BOOL "Disable search SDL2_ttf Library in default path") +unset(_SDL2_TTF_NO_DEFAULT_PATH) + +set(SDL2_TTF_NO_DEFAULT_PATH_CMD) +if(SDL2_TTF_NO_DEFAULT_PATH) + set(SDL2_TTF_NO_DEFAULT_PATH_CMD NO_DEFAULT_PATH) +endif() + +# Search for the SDL2_ttf include directory +find_path(SDL2_TTF_INCLUDE_DIR SDL_ttf.h + HINTS + ENV SDL2TTFDIR + ENV SDL2DIR + ${SDL2_TTF_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES SDL2 + # path suffixes to search inside ENV{SDL2DIR} + # and ENV{SDL2TTFDIR} + include/SDL2 include + PATHS ${SDL2_TTF_PATH} + DOC "Where the SDL2_ttf headers can be found" +) + +if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(VC_LIB_PATH_SUFFIX lib/x64) +else() + set(VC_LIB_PATH_SUFFIX lib/x86) +endif() + +# Search for the SDL2_ttf library +find_library(SDL2_TTF_LIBRARY + NAMES SDL2_ttf + HINTS + ENV SDL2TTFDIR + ENV SDL2DIR + ${SDL2_TTF_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX} + PATHS ${SDL2_TTF_PATH} + DOC "Where the SDL2_ttf Library can be found" +) + +# Read SDL2_ttf version +if(SDL2_TTF_INCLUDE_DIR AND EXISTS "${SDL2_TTF_INCLUDE_DIR}/SDL_ttf.h") + file(STRINGS "${SDL2_TTF_INCLUDE_DIR}/SDL_ttf.h" SDL2_TTF_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL_TTF_MAJOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_TTF_INCLUDE_DIR}/SDL_ttf.h" SDL2_TTF_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL_TTF_MINOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_TTF_INCLUDE_DIR}/SDL_ttf.h" SDL2_TTF_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL_TTF_PATCHLEVEL[ \t]+[0-9]+$") + string(REGEX REPLACE "^#define[ \t]+SDL_TTF_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_TTF_VERSION_MAJOR "${SDL2_TTF_VERSION_MAJOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_TTF_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_TTF_VERSION_MINOR "${SDL2_TTF_VERSION_MINOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_TTF_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_TTF_VERSION_PATCH "${SDL2_TTF_VERSION_PATCH_LINE}") + set(SDL2_TTF_VERSION_STRING ${SDL2_TTF_VERSION_MAJOR}.${SDL2_TTF_VERSION_MINOR}.${SDL2_TTF_VERSION_PATCH}) + unset(SDL2_TTF_VERSION_MAJOR_LINE) + unset(SDL2_TTF_VERSION_MINOR_LINE) + unset(SDL2_TTF_VERSION_PATCH_LINE) + unset(SDL2_TTF_VERSION_MAJOR) + unset(SDL2_TTF_VERSION_MINOR) + unset(SDL2_TTF_VERSION_PATCH) +endif() + +set(SDL2_TTF_LIBRARIES ${SDL2_TTF_LIBRARY}) +set(SDL2_TTF_INCLUDE_DIRS ${SDL2_TTF_INCLUDE_DIR}) + +include(FindPackageHandleStandardArgs) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_ttf + REQUIRED_VARS SDL2_TTF_LIBRARIES SDL2_TTF_INCLUDE_DIRS + VERSION_VAR SDL2_TTF_VERSION_STRING) + + +mark_as_advanced(SDL2_TTF_PATH + SDL2_TTF_NO_DEFAULT_PATH + SDL2_TTF_LIBRARY + SDL2_TTF_INCLUDE_DIR) + + +if(SDL2_TTF_FOUND) + + # SDL2::TTF target + if(SDL2_TTF_LIBRARY AND NOT TARGET SDL2::TTF) + add_library(SDL2::TTF UNKNOWN IMPORTED) + set_target_properties(SDL2::TTF PROPERTIES + IMPORTED_LOCATION "${SDL2_TTF_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${SDL2_TTF_INCLUDE_DIR}" + INTERFACE_LINK_LIBRARIES SDL2::Core) + endif() +endif() diff --git a/lib/entt b/lib/entt new file mode 160000 index 0000000..e5172a9 --- /dev/null +++ b/lib/entt @@ -0,0 +1 @@ +Subproject commit e5172a9240728cc271af7599c6f13580329f3618 diff --git a/lib/libs.cmake b/lib/libs.cmake new file mode 100644 index 0000000..a995d15 --- /dev/null +++ b/lib/libs.cmake @@ -0,0 +1,20 @@ +set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${EXTERNAL_DIR}/cmake) + +# sdl +if (NOT EMSCRIPTEN) + find_package(SDL2 REQUIRED) + find_package(SDL2_mixer REQUIRED) + find_package(SDL2_image REQUIRED) + find_package(SDL2_ttf REQUIRED) + find_package(SDL2_gfx REQUIRED) +endif(NOT EMSCRIPTEN) + +# entt +add_library (imported::entt INTERFACE IMPORTED) +set (ENTT_INCLUDE_PATH ${CMAKE_SOURCE_DIR}/lib/entt/single_include) +set_target_properties(imported::entt PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${ENTT_INCLUDE_PATH}") +target_link_libraries(imported::entt INTERFACE EnTT) + +list (APPEND EXTERNAL_INCLUDE_DIRS + ${ENTT_INCLUDE_PATH} +) \ No newline at end of file From d973720f76cff25df04cb1983095e760c85b39c4 Mon Sep 17 00:00:00 2001 From: alegemaate Date: Sat, 23 Apr 2022 18:01:39 -0400 Subject: [PATCH 10/24] fix: checkout submodules --- .github/workflows/build-linux.yml | 4 +++- .github/workflows/build-macos.yml | 4 +++- .github/workflows/build-web.yml | 4 +++- .github/workflows/build-windows.yml | 4 +++- .github/workflows/deploy-docs.yml | 4 +++- examples/CMakeLists.txt | 8 +++++--- 6 files changed, 20 insertions(+), 8 deletions(-) diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml index 216b137..10c259d 100644 --- a/.github/workflows/build-linux.yml +++ b/.github/workflows/build-linux.yml @@ -11,7 +11,9 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 + with: + submodules: true - name: Install Libraries run: | diff --git a/.github/workflows/build-macos.yml b/.github/workflows/build-macos.yml index d3b93b2..1fe705a 100644 --- a/.github/workflows/build-macos.yml +++ b/.github/workflows/build-macos.yml @@ -11,7 +11,9 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 + with: + submodules: true - name: Install Libraries run: | diff --git a/.github/workflows/build-web.yml b/.github/workflows/build-web.yml index 3711181..69d974f 100644 --- a/.github/workflows/build-web.yml +++ b/.github/workflows/build-web.yml @@ -11,7 +11,9 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 + with: + submodules: true - name: Setup Emscripten uses: mymindstorm/setup-emsdk@v7 diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml index ae3fd74..beb93d5 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -11,7 +11,9 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 + with: + submodules: true - name: Install Libraries run: | diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index b5d73ae..8a6ec81 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -11,7 +11,9 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 + with: + submodules: true - name: Setup Emscripten uses: mymindstorm/setup-emsdk@v7 diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index b51765a..6a7e319 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,10 +1,12 @@ cmake_minimum_required(VERSION 3.14) +project (examples + VERSION 1.0.0 + LANGUAGES CXX +) + include(${EXTERNAL_DIR}/libs.cmake) -# Add include dir -include_directories(${PROJECT_SOURCE_DIR}/include) -include_directories(${PROJECT_SOURCE_DIR}/build) # Config set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/build) From 5b7bed7733b0fea2301e08b630146229ab2d6466 Mon Sep 17 00:00:00 2001 From: alegemaate Date: Sat, 23 Apr 2022 19:30:32 -0400 Subject: [PATCH 11/24] fix: timesteps and particle system --- .vscode/c_cpp_properties.json | 2 +- afk/CMakeLists.txt | 77 ++++++++------------- afk/include/components/Particle.h | 38 +++------- afk/include/components/Physics.h | 4 +- afk/src/services/display/DisplayService.cpp | 11 ++- afk/src/services/scene/SceneService.cpp | 6 +- afk/src/systems/ParticleSystem.cpp | 12 ++-- examples/CMakeLists.txt | 49 +++---------- examples/src/ex_collision.cpp | 2 +- examples/src/ex_particles.cpp | 6 +- examples/src/ex_sound.cpp | 6 +- examples/src/ex_sprite.cpp | 4 +- examples/src/ex_ui.cpp | 4 +- 13 files changed, 74 insertions(+), 147 deletions(-) diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json index 9692d48..8c7266f 100644 --- a/.vscode/c_cpp_properties.json +++ b/.vscode/c_cpp_properties.json @@ -5,7 +5,7 @@ "intelliSenseMode": "gcc-x86", "cStandard": "c11", "cppStandard": "c++17", - "includePath": ["include"] + "includePath": ["afk/include"] } ], "version": 4 diff --git a/afk/CMakeLists.txt b/afk/CMakeLists.txt index ac3efc1..d112612 100644 --- a/afk/CMakeLists.txt +++ b/afk/CMakeLists.txt @@ -7,6 +7,8 @@ project (afk set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/build/lib) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/build/lib) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) include(${EXTERNAL_DIR}/libs.cmake) @@ -16,15 +18,15 @@ file(GLOB_RECURSE HEADERS ${PROJECT_SOURCE_DIR}/include/*.h) # Lib add_library(${PROJECT_NAME} - STATIC +STATIC ${SOURCES} ${HEADERS} ) target_include_directories(${PROJECT_NAME} - PUBLIC - $ - $ + PUBLIC + $ + $ ) target_compile_options(${PROJECT_NAME} @@ -39,38 +41,17 @@ set_target_properties(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION 1 - CXX_STANDARD 17 - CXX_STANDARD_REQUIRED ON ) # Emscripten specific options if(EMSCRIPTEN) - target_compile_options(${PROJECT_NAME} - PRIVATE - -sUSE_SDL=2 - -sUSE_SDL_IMAGE=2 - -sUSE_SDL_TTF=2 - -sUSE_SDL_MIXER=2 - -sUSE_SDL_GFX=2 - -sSDL2_IMAGE_FORMATS=["png"] - ) - - target_link_libraries(${PROJECT_NAME} - -sWASM=1 - -sUSE_SDL=2 - -sUSE_SDL_IMAGE=2 - -sUSE_SDL_TTF=2 - -sUSE_SDL_MIXER=2 - -sUSE_SDL_GFX=2 - -sSDL2_IMAGE_FORMATS=["png"] - -sDEMANGLE_SUPPORT=1 - imported::entt - ) - - target_link_libraries(${PROJECT_NAME} - -sUSE_SDL=2 - -fsanitize=address + set_target_properties(${PROJECT_NAME} + PROPERTIES + LINK_FLAGS + "-s DEMANGLE_SUPPORT=1 -s DISABLE_EXCEPTION_CATCHING=0 -s USE_SDL=2 -s USE_SDL_IMAGE=2 -s USE_SDL_TTF=2 -s USE_SDL_MIXER=2 -s USE_SDL_GFX=2 -s SDL2_IMAGE_FORMATS=[\"png\"]" ) + + target_link_libraries(${PROJECT_NAME} imported::entt) # All other system options else(EMSCRIPTEN) @@ -86,25 +67,21 @@ else(EMSCRIPTEN) endif(EMSCRIPTEN) # Install info -if (EMSCRIPTEN) - get_filename_component(EMSDK_DIR ${CMAKE_TOOLCHAIN_FILE} DIRECTORY) - set(EMSDK_DIR ${EMSDK_DIR}/../../../system) - message(STATUS "Lib install directory set to ${EMSDK_DIR}") - - set(CMAKE_INSTALL_LIBDIR ${EMSDK_DIR}/lib) - set(CMAKE_INSTALL_BINDIR ${EMSDK_DIR}/bin) - set(CMAKE_INSTALL_INCLUDEDIR ${EMSDK_DIR}/include) - set(CMAKE_INSTALL_DATAROOTDIR ${EMSDK_DIR}/share) - -elseif (WIN32) - get_filename_component(WIN32_BIN_PATH ${CMAKE_C_COMPILER} PATH) - set(WIN32_DIR ${WIN32_BIN_PATH}/../) - message(STATUS "Lib install directory set to ${WIN32_DIR}") - - set(CMAKE_INSTALL_LIBDIR ${WIN32_DIR}/lib) - set(CMAKE_INSTALL_BINDIR ${WIN32_DIR}/bin) - set(CMAKE_INSTALL_INCLUDEDIR ${WIN32_DIR}/include) - set(CMAKE_INSTALL_DATAROOTDIR ${WIN32_DIR}/share) +if (EMSCRIPTEN OR WIN32) + if (EMSCRIPTEN) + get_filename_component(EMSDK_DIR ${CMAKE_TOOLCHAIN_FILE} DIRECTORY) + set(BASE_DIR ${EMSDK_DIR}/../../../system) + elseif (WIN32) + get_filename_component(WIN32_BIN_PATH ${CMAKE_C_COMPILER} PATH) + set(BASE_DIR ${WIN32_BIN_PATH}/../) + endif(EMSCRIPTEN) + + message(STATUS "Lib install directory set to ${BASE_DIR}") + + set(CMAKE_INSTALL_LIBDIR ${BASE_DIR}/lib) + set(CMAKE_INSTALL_BINDIR ${BASE_DIR}/bin) + set(CMAKE_INSTALL_INCLUDEDIR ${BASE_DIR}/include) + set(CMAKE_INSTALL_DATAROOTDIR ${BASE_DIR}/share) else() include(GNUInstallDirs) endif() diff --git a/afk/include/components/Particle.h b/afk/include/components/Particle.h index 29da0c9..c29a287 100644 --- a/afk/include/components/Particle.h +++ b/afk/include/components/Particle.h @@ -27,24 +27,7 @@ enum class ParticleType : int { struct Particle { /// Constructor - explicit Particle(ParticleType type = ParticleType::Pixel) - : type(type), - startSize(1), - endSize(1), - age(0), - lifespan(1000), - startColor(color::black), - endColor(color::black){}; - - Particle(const Particle& part) - : type(part.type), - startSize(part.startSize), - endSize(part.endSize), - age(0), - lifespan(part.lifespan), - startColor(part.startColor), - endColor(part.endColor), - texture(part.texture){}; + Particle() = default; /** * @brief Set the type @@ -79,10 +62,7 @@ struct Particle { * * @param lifespan Number of ms to stay alive */ - void setLifespan(const float lifespan) { - this->lifespan = lifespan; - this->age = lifespan; - } + void setLifespan(const float lifespan) { this->lifespan = lifespan; } /** * @brief Set the particle color @@ -113,25 +93,25 @@ struct Particle { void setTexture(const std::string& texture) { this->texture = texture; } /// Type of particle - ParticleType type; + ParticleType type = ParticleType::Pixel; /// Starting size - float startSize; + float startSize = 1; /// Ending size - float endSize; + float endSize = 1; /// Current age - uint32_t age; + uint32_t age = 0; /// Max lifespan - float lifespan; + float lifespan = 1000; /// Start color - color::Color startColor; + color::Color startColor = color::black; /// End color - color::Color endColor; + color::Color endColor = color::black; /// String std::string texture; diff --git a/afk/include/components/Physics.h b/afk/include/components/Physics.h index 93c5dc4..1952c2d 100644 --- a/afk/include/components/Physics.h +++ b/afk/include/components/Physics.h @@ -17,13 +17,13 @@ namespace afk { struct Physics { /// Constructors + Physics() = default; + Physics(Vec2 velocity, Vec2 acceleration) : velocity(velocity), acceleration(acceleration) {} explicit Physics(Vec2 velocity) : velocity(velocity) {} - Physics() = default; - void setVelocity(Vec2 velocity) { this->velocity = velocity; } void setVelocity(float x, float y) { this->velocity = Vec2(x, y); } diff --git a/afk/src/services/display/DisplayService.cpp b/afk/src/services/display/DisplayService.cpp index e8b101f..2cb60db 100644 --- a/afk/src/services/display/DisplayService.cpp +++ b/afk/src/services/display/DisplayService.cpp @@ -20,10 +20,8 @@ namespace afk { // Setup DisplayService -DisplayService::DisplayService() : clearColor(color::white) { - // Set initial time - oldTime = SDL_GetTicks(); -} +DisplayService::DisplayService() + : clearColor(color::white), oldTime(SDL_GetTicks()) {} // Cleanup window DisplayService::~DisplayService() { @@ -53,8 +51,9 @@ void DisplayService::draw(Scene* currentScene) { SDL_RenderPresent(renderer); // Update frame index - framesArray[frameIndex] = SDL_GetTicks() - oldTime; - oldTime = SDL_GetTicks(); + uint32_t currentTime = SDL_GetTicks(); + framesArray[frameIndex] = currentTime - oldTime; + oldTime = currentTime; frameIndex = (frameIndex + 1) % frameBufferSize; float fpsTotal = 0; diff --git a/afk/src/services/scene/SceneService.cpp b/afk/src/services/scene/SceneService.cpp index b2b0aed..b2a4508 100644 --- a/afk/src/services/scene/SceneService.cpp +++ b/afk/src/services/scene/SceneService.cpp @@ -31,11 +31,11 @@ void SceneService::update() { // Update scene if (currentScene) { - uint32_t delta = SDL_GetTicks() - lastTick; + uint32_t currentTick = SDL_GetTicks(); + uint32_t delta = currentTick - lastTick; + lastTick = currentTick; currentScene->update(delta); } - - lastTick = SDL_GetTicks(); } // Update scene diff --git a/afk/src/systems/ParticleSystem.cpp b/afk/src/systems/ParticleSystem.cpp index c01376c..9d70e70 100644 --- a/afk/src/systems/ParticleSystem.cpp +++ b/afk/src/systems/ParticleSystem.cpp @@ -45,8 +45,7 @@ void particleSystem(Registry& registry, uint32_t delta) { for (auto [entity, tran, emitter] : systemView.each()) { emitter.counter += delta; - while (emitter.counter > emitter.frequency && - !emitter.templates.empty()) { + while (emitter.counter > emitter.frequency && !emitter.templates.empty()) { int index = random::randomInt(0, emitter.templates.size() - 1); auto& [particle, physics] = emitter.templates.at(index); @@ -60,9 +59,9 @@ void particleSystem(Registry& registry, uint32_t delta) { const auto& particleId = registry.create(); registry.emplace(particleId, particle); registry.emplace(particleId, physics); - registry.emplace( - particleId, Vec3(startX, startY, tran.position.z), - Vec2(particle.startSize, particle.startSize)); + registry.emplace(particleId, + Vec3(startX, startY, tran.position.z), + Vec2(particle.startSize, particle.startSize)); } } } @@ -74,8 +73,7 @@ void particleRenderSystem(Registry& registry, AssetService& assetService) { float lifePercent = particle.age / particle.lifespan; // Lerp size - float size = - math::lerp(particle.startSize, particle.endSize, lifePercent); + float size = math::lerp(particle.startSize, particle.endSize, lifePercent); // Lerp color uint8_t r = diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 6a7e319..cb031eb 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -10,62 +10,35 @@ include(${EXTERNAL_DIR}/libs.cmake) # Config set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/build) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) set(EXAMPLES ex_display ex_sprite ex_rotate ex_fps ex_mouse ex_physics ex_sound ex_particles ex_keyboard ex_collision ex_message_box) # Build examples foreach(EX_NAME ${EXAMPLES}) - add_executable(${EX_NAME} - ${CMAKE_CURRENT_LIST_DIR}/src/${EX_NAME}.cpp - ) + add_executable(${EX_NAME} ${CMAKE_CURRENT_LIST_DIR}/src/${EX_NAME}.cpp) target_compile_options(${EX_NAME} PRIVATE - -O2 - -Wall - -Wextra - -pedantic + -O2 + -Wall + -Wextra + -pedantic -Wno-unused-parameter - ) - - set_target_properties(${EX_NAME} - PROPERTIES - CXX_STANDARD 17 - CXX_STANDARD_REQUIRED ON ) # Emscripten support if(EMSCRIPTEN) set(CMAKE_EXECUTABLE_SUFFIX ".html") - target_compile_options(${EX_NAME} - PRIVATE - -sUSE_SDL=2 - -sUSE_SDL_IMAGE=2 - -sUSE_SDL_TTF=2 - -sUSE_SDL_MIXER=2 - -sUSE_SDL_GFX=2 - -sSDL2_IMAGE_FORMATS=["png"] - ) - - target_link_libraries(${EX_NAME} - -sWASM=1 - -sUSE_SDL=2 - -sUSE_SDL_IMAGE=2 - -sUSE_SDL_TTF=2 - -sUSE_SDL_MIXER=2 - -sUSE_SDL_GFX=2 - -sSDL2_IMAGE_FORMATS=["png"] - -sDEMANGLE_SUPPORT=1 - -sTOTAL_MEMORY=512MB - -sDISABLE_EXCEPTION_CATCHING=0 - imported::entt - afk - ) set_target_properties(${EX_NAME} PROPERTIES - LINK_FLAGS "--preload-file ${CMAKE_CURRENT_LIST_DIR}/assets@/assets --use-preload-plugins" + LINK_FLAGS + "--preload-file ${CMAKE_CURRENT_LIST_DIR}/assets@/assets --use-preload-plugins -s DEMANGLE_SUPPORT=1 -s DISABLE_EXCEPTION_CATCHING=0 -s USE_SDL=2 -s USE_SDL_IMAGE=2 -s USE_SDL_TTF=2 -s USE_SDL_MIXER=2 -s USE_SDL_GFX=2 -s SDL2_IMAGE_FORMATS=[\"png\"]" ) + target_link_libraries(${EX_NAME} imported::entt afk) + # Run of the mill executable else(EMSCRIPTEN) if(MINGW) diff --git a/examples/src/ex_collision.cpp b/examples/src/ex_collision.cpp index e6973f6..1df4ee7 100644 --- a/examples/src/ex_collision.cpp +++ b/examples/src/ex_collision.cpp @@ -71,7 +71,7 @@ class DemoScene : public afk::Scene { Scene::update(delta); } - void stop() { logger.log("Stopping!"); } + void stop() override { logger.log("Stopping!"); } private: afk::Entity lennaEntity1; diff --git a/examples/src/ex_particles.cpp b/examples/src/ex_particles.cpp index 1faf9dc..7e677a3 100644 --- a/examples/src/ex_particles.cpp +++ b/examples/src/ex_particles.cpp @@ -17,7 +17,7 @@ class DemoScene : public afk::Scene { public: - void start() { + void start() override { logger.log("Starting!"); display.setWindowSize(512, 512); @@ -75,7 +75,7 @@ class DemoScene : public afk::Scene { } } - void update(uint32_t delta) { + void update(uint32_t delta) override { Scene::update(delta); auto& smoke_transform = getComponent(emitterEntity3); @@ -83,7 +83,7 @@ class DemoScene : public afk::Scene { smoke_transform.position.y = input.mouseY(); } - void stop() { logger.log("Stopping!"); } + void stop() override { logger.log("Stopping!"); } private: afk::Entity emitterEntity1; diff --git a/examples/src/ex_sound.cpp b/examples/src/ex_sound.cpp index df2d70c..2e04182 100644 --- a/examples/src/ex_sound.cpp +++ b/examples/src/ex_sound.cpp @@ -13,7 +13,7 @@ class DemoScene : public afk::Scene { public: - void start() { + void start() override { logger.log("Starting!"); display.setWindowSize(512, 512); display.setBufferSize(512, 512); @@ -22,7 +22,7 @@ class DemoScene : public afk::Scene { assets.loadAudio("win", "assets/win.wav"); } - void update(uint32_t delta) { + void update(uint32_t delta) override { Scene::update(delta); if (input.mousePressed(afk::MouseButtons::Left)) { @@ -30,7 +30,7 @@ class DemoScene : public afk::Scene { } } - void stop() { logger.log("Stopping!"); } + void stop() override { logger.log("Stopping!"); } }; int main(int argv, char** args) { diff --git a/examples/src/ex_sprite.cpp b/examples/src/ex_sprite.cpp index 43cda24..98d602f 100644 --- a/examples/src/ex_sprite.cpp +++ b/examples/src/ex_sprite.cpp @@ -15,7 +15,7 @@ class DemoScene : public afk::Scene { public: - void start() { + void start() override { logger.log("Starting!"); display.setWindowSize(512, 512); @@ -31,7 +31,7 @@ class DemoScene : public afk::Scene { afk::Vec2(50, 50)); } - void stop() { logger.log("Stopping!"); } + void stop() override { logger.log("Stopping!"); } }; int main(int argv, char** args) { diff --git a/examples/src/ex_ui.cpp b/examples/src/ex_ui.cpp index 955b061..b4c4139 100644 --- a/examples/src/ex_ui.cpp +++ b/examples/src/ex_ui.cpp @@ -20,7 +20,7 @@ class DemoScene : public afk::Scene { public: - void start() { + void start() override { logger.log("Starting!"); display.setWindowSize(512, 512); @@ -76,7 +76,7 @@ class DemoScene : public afk::Scene { }); } - void stop() { logger.log("Stopping!"); } + void stop() override { logger.log("Stopping!"); } }; int main(int argv, char** args) { From e08c4c5b6f7fefaed9d2f8e534e604ed4335fc7d Mon Sep 17 00:00:00 2001 From: alegemaate Date: Sun, 24 Apr 2022 00:24:10 -0400 Subject: [PATCH 12/24] reafactor: simplify components --- .github/workflows/build-web.yml | 2 +- .github/workflows/deploy-docs.yml | 2 +- afk/include/common/Vec.h | 14 ++-- afk/include/components/Particle.h | 66 --------------- afk/include/components/ParticleEmitter.h | 20 ++--- afk/include/components/Physics.h | 20 +---- afk/include/components/Transform.h | 4 +- afk/include/services/display/DisplayService.h | 2 +- afk/src/services/display/DisplayService.cpp | 3 +- afk/src/systems/ParticleSystem.cpp | 6 +- examples/src/ex_particles.cpp | 81 ++++++++++++------- 11 files changed, 80 insertions(+), 140 deletions(-) diff --git a/.github/workflows/build-web.yml b/.github/workflows/build-web.yml index 69d974f..cec8354 100644 --- a/.github/workflows/build-web.yml +++ b/.github/workflows/build-web.yml @@ -16,7 +16,7 @@ jobs: submodules: true - name: Setup Emscripten - uses: mymindstorm/setup-emsdk@v7 + uses: mymindstorm/setup-emsdk@v11 with: actions-cache-folder: "emsdk-cache" diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 8a6ec81..43f1f52 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -16,7 +16,7 @@ jobs: submodules: true - name: Setup Emscripten - uses: mymindstorm/setup-emsdk@v7 + uses: mymindstorm/setup-emsdk@v11 with: actions-cache-folder: "emsdk-cache" diff --git a/afk/include/common/Vec.h b/afk/include/common/Vec.h index aa7cd7a..d002bb9 100644 --- a/afk/include/common/Vec.h +++ b/afk/include/common/Vec.h @@ -14,20 +14,20 @@ namespace afk { struct Vec2 { - Vec2() : x(0), y(0) {} + Vec2() = default; Vec2(float x, float y) : x(x), y(y) {} - float x; - float y; + float x = 0.0f; + float y = 0.0f; }; struct Vec3 { - Vec3() : x(0), y(0), z(0) {} + Vec3() = default; Vec3(float x, float y, float z) : x(x), y(y), z(z) {} - float x; - float y; - float z; + float x = 0.0f; + float y = 0.0f; + float z = 0.0f; }; } // namespace afk diff --git a/afk/include/components/Particle.h b/afk/include/components/Particle.h index c29a287..1c271f5 100644 --- a/afk/include/components/Particle.h +++ b/afk/include/components/Particle.h @@ -26,72 +26,6 @@ enum class ParticleType : int { }; struct Particle { - /// Constructor - Particle() = default; - - /** - * @brief Set the type - * - * @param type Type of particle - */ - void setType(ParticleType type) { this->type = type; } - - /** - * @brief Set the size of the particle in pixels - * - * @param size Size of particle - */ - void setSize(const float size) { - this->startSize = size; - this->endSize = size; - } - - /** - * @brief Set the size of particle over lifespan - * - * @param startSize Size to start at - * @param endSize Size to end at - */ - void setSize(const float startSize, const float endSize) { - this->startSize = startSize; - this->endSize = endSize; - } - - /** - * @brief Set the lifespan of particle in ms - * - * @param lifespan Number of ms to stay alive - */ - void setLifespan(const float lifespan) { this->lifespan = lifespan; } - - /** - * @brief Set the particle color - * - * @param color Color to set to - */ - void setColor(const color::Color& color) { - this->startColor = color; - this->endColor = color; - } - - /** - * @brief Set the particle color over lifespan - * - * @param startColor Starting color - * @param endColor Ending color - */ - void setColor(const color::Color& startColor, const color::Color& endColor) { - this->startColor = startColor; - this->endColor = endColor; - } - - /** - * @brief Set the texture id of the particle - * - * @param texture Texture id - */ - void setTexture(const std::string& texture) { this->texture = texture; } - /// Type of particle ParticleType type = ParticleType::Pixel; diff --git a/afk/include/components/ParticleEmitter.h b/afk/include/components/ParticleEmitter.h index 45841d2..2e24fa7 100644 --- a/afk/include/components/ParticleEmitter.h +++ b/afk/include/components/ParticleEmitter.h @@ -25,29 +25,25 @@ namespace afk { using ParticleTemplate = std::pair; struct ParticleEmitter { - /// Constructor - explicit ParticleEmitter(float frequency) - : frequency(frequency), counter(0){}; - /** * @brief Add a particle to the emitter pool * * @param particle Particle template to add * @return Particle& Reference to added particle */ - ParticleTemplate& addParticle() { - templates.emplace_back(std::make_pair(Particle(), Physics())); - return templates.back(); + ParticleTemplate& addPrefab() { + prefabs.emplace_back(std::make_pair(Particle(), Physics())); + return prefabs.back(); } - /// Particle templates - std::vector templates; - /// Frequency of emit - float frequency; + float frequency = 0.0f; /// Counter - float counter; + float counter = 0.0f; + + /// Particle prefabs + std::vector prefabs{}; }; } // namespace afk diff --git a/afk/include/components/Physics.h b/afk/include/components/Physics.h index 1952c2d..79a005b 100644 --- a/afk/include/components/Physics.h +++ b/afk/include/components/Physics.h @@ -16,27 +16,11 @@ namespace afk { struct Physics { - /// Constructors - Physics() = default; - - Physics(Vec2 velocity, Vec2 acceleration) - : velocity(velocity), acceleration(acceleration) {} - - explicit Physics(Vec2 velocity) : velocity(velocity) {} - - void setVelocity(Vec2 velocity) { this->velocity = velocity; } - - void setVelocity(float x, float y) { this->velocity = Vec2(x, y); } - - void setAcceleration(Vec2 acceleration) { this->acceleration = acceleration; } - - void setAcceleration(float x, float y) { this->acceleration = Vec2(x, y); } - /// X and Y velocity - Vec2 velocity; + Vec2 velocity = {0.0f, 0.0f}; /// X and Y acceleration - Vec2 acceleration; + Vec2 acceleration = {0.0f, 0.0f}; }; } // namespace afk diff --git a/afk/include/components/Transform.h b/afk/include/components/Transform.h index 22e5476..02650cd 100644 --- a/afk/include/components/Transform.h +++ b/afk/include/components/Transform.h @@ -17,10 +17,10 @@ namespace afk { struct Transform { /// Position on x y z plane - Vec3 position; + Vec3 position = {0.0f, 0.0f, 0.0f}; /// Size - Vec2 size; + Vec2 size = {0.0f, 0.0f}; /// Rotation float angle = 0.0f; diff --git a/afk/include/services/display/DisplayService.h b/afk/include/services/display/DisplayService.h index 7cba4af..787c3fe 100644 --- a/afk/include/services/display/DisplayService.h +++ b/afk/include/services/display/DisplayService.h @@ -267,7 +267,7 @@ class DisplayService { uint32_t frameIndex = 0; /// Clear color - color::Color clearColor; + color::Color clearColor = color::white; /** * @brief Sets the window scaling in percent diff --git a/afk/src/services/display/DisplayService.cpp b/afk/src/services/display/DisplayService.cpp index 2cb60db..f800c10 100644 --- a/afk/src/services/display/DisplayService.cpp +++ b/afk/src/services/display/DisplayService.cpp @@ -20,8 +20,7 @@ namespace afk { // Setup DisplayService -DisplayService::DisplayService() - : clearColor(color::white), oldTime(SDL_GetTicks()) {} +DisplayService::DisplayService() : oldTime(SDL_GetTicks()) {} // Cleanup window DisplayService::~DisplayService() { diff --git a/afk/src/systems/ParticleSystem.cpp b/afk/src/systems/ParticleSystem.cpp index 9d70e70..c8b462c 100644 --- a/afk/src/systems/ParticleSystem.cpp +++ b/afk/src/systems/ParticleSystem.cpp @@ -45,9 +45,9 @@ void particleSystem(Registry& registry, uint32_t delta) { for (auto [entity, tran, emitter] : systemView.each()) { emitter.counter += delta; - while (emitter.counter > emitter.frequency && !emitter.templates.empty()) { - int index = random::randomInt(0, emitter.templates.size() - 1); - auto& [particle, physics] = emitter.templates.at(index); + while (emitter.counter > emitter.frequency && !emitter.prefabs.empty()) { + int index = random::randomInt(0, emitter.prefabs.size() - 1); + auto& [particle, physics] = emitter.prefabs.at(index); emitter.counter -= emitter.frequency; diff --git a/examples/src/ex_particles.cpp b/examples/src/ex_particles.cpp index 7e677a3..1fc9a6f 100644 --- a/examples/src/ex_particles.cpp +++ b/examples/src/ex_particles.cpp @@ -29,49 +29,75 @@ class DemoScene : public afk::Scene { assets.loadImage("fuzzball", "assets/fuzzball.png"); emitterEntity1 = createEntity(); - auto& emitter1 = createComponent(emitterEntity1, 10); + auto& emitter1 = + createComponent(emitterEntity1, 10.0f); createComponent(emitterEntity1, afk::Vec3(256, 256, 0), afk::Vec2(30, 30)); for (int i = 0; i < 100; i++) { - auto& [particle, physics] = emitter1.addParticle(); - particle.setType(afk::ParticleType::Square); - particle.setLifespan(afk::random::randomInt(100, 1000)); - particle.setSize(10.0f, 3.0f); - particle.setColor(afk::color::rgb(128, 22, 22), - afk::color::rgb(100, 100, 100)); - physics.setVelocity(afk::random::randomFloat(-5.0f, 5.0f), - afk::random::randomFloat(-1.0f, -2.0f)); - physics.setAcceleration(0, 2.0f); + auto& [particle, physics] = emitter1.addPrefab(); + particle.type = afk::ParticleType::Square; + particle.lifespan = afk::random::randomInt(100, 1000); + particle.startSize = 10.0f, particle.endSize = 3.0f; + particle.startColor = afk::color::rgb(128, 22, 22); + particle.endColor = afk::color::rgb(100, 100, 100); + physics.velocity = {afk::random::randomFloat(-5.0f, 5.0f), + afk::random::randomFloat(-1.0f, -2.0f)}; + physics.acceleration = {0, 2.0f}; } emitterEntity2 = createEntity(); - auto& emitter2 = createComponent(emitterEntity2, 10); - createComponent(emitterEntity2, afk::Vec3(128, 256, 0), + auto& emitter2 = + createComponent(emitterEntity2, 10.0f); + createComponent(emitterEntity2, afk::Vec3(64, 256, 0), afk::Vec2(1, 1)); for (int i = 0; i < 100; i++) { - auto& [particle, physics] = emitter2.addParticle(); - particle.setType(afk::ParticleType::Circle); - particle.setLifespan(afk::random::randomInt(1000, 2000)); - particle.setSize(3.0f, 2.0f); - particle.setColor(afk::color::blue, afk::color::white); - physics.setVelocity(afk::random::randomFloat(-20.0, 20.0), -200.0f); - physics.setAcceleration(0, 200.0f); + auto& [particle, physics] = emitter2.addPrefab(); + particle.type = afk::ParticleType::Circle; + particle.lifespan = afk::random::randomInt(1000, 2000); + particle.startSize = 3.0f; + particle.endSize = 2.0f; + particle.startColor = afk::color::blue; + particle.endColor = afk::color::white; + physics.velocity = {afk::random::randomFloat(-20.0, 20.0), -200.0f}; + physics.acceleration = {0, 200.0f}; } emitterEntity3 = createEntity(); - auto& emitter3 = createComponent(emitterEntity3, 10); - createComponent(emitterEntity3, afk::Vec3(384, 256, 0), + auto& emitter3 = + createComponent(emitterEntity3, 10.0f); + createComponent(emitterEntity3, afk::Vec3(0, 0, 0), afk::Vec2(5, 5)); for (int i = 0; i < 400; i++) { - auto& [particle, physics] = emitter3.addParticle(); - particle.setType(afk::ParticleType::Image); - particle.setLifespan(afk::random::randomInt(800, 1500)); - particle.setSize(16.0f, 20.0f); - particle.setTexture("fuzzball"); - physics.setVelocity(afk::random::randomFloat(2.0f, 2.5f), -5.0f); + auto& [particle, physics] = emitter3.addPrefab(); + particle.type = afk::ParticleType::Image; + particle.lifespan = 3000; + particle.startSize = 24.0f; + particle.endSize = 48.0f; + particle.texture = "fuzzball"; + physics.velocity = {2.0f, -10.0f}; + physics.acceleration = {10.0f, 0}; + } + + emitterEntity4 = createEntity(); + auto& emitter4 = + createComponent(emitterEntity4, 10.0f); + createComponent(emitterEntity4, afk::Vec3(128, 256, 0), + afk::Vec2(1, 1)); + + for (int i = 0; i < 400; i++) { + auto& [particle, physics] = emitter4.addPrefab(); + particle.type = afk::ParticleType::Square; + particle.startColor = afk::color::rgba(128, 20, 20, 128); + particle.endColor = afk::color::rgba(200, 200, 200, 0); + particle.lifespan = afk::random::randomInt(400, 500); + particle.startSize = 3.0f; + particle.endSize = 1.0f; + physics.velocity = {afk::random::randomFloat(-40.0f, 40.0f), + afk::random::randomFloat(-40.0f, 40.0f)}; + physics.acceleration = {0, 200.0f}; } } @@ -89,6 +115,7 @@ class DemoScene : public afk::Scene { afk::Entity emitterEntity1; afk::Entity emitterEntity2; afk::Entity emitterEntity3; + afk::Entity emitterEntity4; }; int main(int argv, char** args) { From 48c71ebe6a033b7532af3a144bdecffa4a95e4df Mon Sep 17 00:00:00 2001 From: alegemaate Date: Sun, 24 Apr 2022 10:43:54 -0400 Subject: [PATCH 13/24] feat: add fps to particles example --- CMakeLists.txt | 4 ++-- afk/CMakeLists.txt | 5 ++--- afk/include/components/ui/Label.h | 16 ++++--------- afk/src/systems/UISystem.cpp | 2 +- examples/CMakeLists.txt | 1 - examples/src/ex_collision.cpp | 7 +++--- examples/src/ex_fps.cpp | 5 ++--- examples/src/ex_particles.cpp | 37 ++++++++++++++++++++++++++++++- 8 files changed, 50 insertions(+), 27 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 27713fe..59cfa25 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7,10 +7,10 @@ set(CMAKE_EXPORT_COMPILE_COMMANDS on) set(EXTERNAL_DIR ${PROJECT_SOURCE_DIR}/lib) # Submodule libs -add_subdirectory(${EXTERNAL_DIR}/entt) +add_subdirectory(${EXTERNAL_DIR}/entt EXCLUDE_FROM_ALL) # Core lib add_subdirectory(${PROJECT_SOURCE_DIR}/afk) # Examples -add_subdirectory(${PROJECT_SOURCE_DIR}/examples) \ No newline at end of file +add_subdirectory(${PROJECT_SOURCE_DIR}/examples EXCLUDE_FROM_ALL) \ No newline at end of file diff --git a/afk/CMakeLists.txt b/afk/CMakeLists.txt index d112612..3e32789 100644 --- a/afk/CMakeLists.txt +++ b/afk/CMakeLists.txt @@ -18,7 +18,7 @@ file(GLOB_RECURSE HEADERS ${PROJECT_SOURCE_DIR}/include/*.h) # Lib add_library(${PROJECT_NAME} -STATIC + STATIC ${SOURCES} ${HEADERS} ) @@ -31,7 +31,6 @@ target_include_directories(${PROJECT_NAME} target_compile_options(${PROJECT_NAME} PRIVATE - -O2 -Wall -Wextra -pedantic @@ -73,7 +72,7 @@ if (EMSCRIPTEN OR WIN32) set(BASE_DIR ${EMSDK_DIR}/../../../system) elseif (WIN32) get_filename_component(WIN32_BIN_PATH ${CMAKE_C_COMPILER} PATH) - set(BASE_DIR ${WIN32_BIN_PATH}/../) + set(BASE_DIR ${WIN32_BIN_PATH}/..) endif(EMSCRIPTEN) message(STATUS "Lib install directory set to ${BASE_DIR}") diff --git a/afk/include/components/ui/Label.h b/afk/include/components/ui/Label.h index 85e29e7..951774d 100644 --- a/afk/include/components/ui/Label.h +++ b/afk/include/components/ui/Label.h @@ -12,27 +12,19 @@ #define AFK_LABEL_H #include -#include +#include "../../common/Color.h" namespace afk { struct Label { - /// Constructor - Label() = default; - - Label(std::string text, std::string font) - : text(std::move(text)), font(std::move(font)) {} - /// Text of Label std::string text; + /// Color of text + color::Color color = color::black; + /// Font of label std::string font; - - /// Setters - void setText(const std::string& text) { this->text = text; } - - void setFont(const std::string& font) { this->font = font; } }; } // namespace afk diff --git a/afk/src/systems/UISystem.cpp b/afk/src/systems/UISystem.cpp index fe8b0de..7e929ab 100644 --- a/afk/src/systems/UISystem.cpp +++ b/afk/src/systems/UISystem.cpp @@ -27,7 +27,7 @@ void uiSystem(Registry& registry, auto viewLabels = registry.view(); for (auto [entity, tran, label] : viewLabels.each()) { auto font = assetService.getFont(label.font); - font.draw(tran.position.x, tran.position.y, label.text); + font.draw(tran.position.x, tran.position.y, label.text, label.color); } auto viewButtons = registry.view(); diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index cb031eb..370481c 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -20,7 +20,6 @@ foreach(EX_NAME ${EXAMPLES}) target_compile_options(${EX_NAME} PRIVATE - -O2 -Wall -Wextra -pedantic diff --git a/examples/src/ex_collision.cpp b/examples/src/ex_collision.cpp index 1df4ee7..18f0238 100644 --- a/examples/src/ex_collision.cpp +++ b/examples/src/ex_collision.cpp @@ -42,8 +42,7 @@ class DemoScene : public afk::Scene { labelEntity = createEntity(); createComponent(labelEntity, afk::Vec3(10, 5, 0)); auto& label = createComponent(labelEntity); - label.setText("FPS"); - label.setFont("freesans"); + label.font = "freesans"; } void update(uint32_t delta) override { @@ -63,9 +62,9 @@ class DemoScene : public afk::Scene { auto& collider = getComponent(lennaEntity1); if (collider.colliding) { - label.setText("Colliding!"); + label.text = "Colliding!"; } else { - label.setText("Not colliding"); + label.text = "Not colliding"; } Scene::update(delta); diff --git a/examples/src/ex_fps.cpp b/examples/src/ex_fps.cpp index 86f979b..7c6f503 100644 --- a/examples/src/ex_fps.cpp +++ b/examples/src/ex_fps.cpp @@ -38,8 +38,7 @@ class DemoScene : public afk::Scene { labelEntity = createEntity(); createComponent(labelEntity, afk::Vec3(10, 5, 0)); auto& label = createComponent(labelEntity); - label.setText("FPS"); - label.setFont("freesans"); + label.font = "freesans"; for (auto& sprite : sprites) { auto entity = createEntity(); @@ -59,7 +58,7 @@ class DemoScene : public afk::Scene { int fps = display.getFps(); auto& label = getComponent(labelEntity); - label.setText(std::to_string(fps)); + label.text = std::to_string(fps); for (unsigned int i = 0; i < NUM_SPRITE; i++) { auto& transform = getComponent(sprites[i]); diff --git a/examples/src/ex_particles.cpp b/examples/src/ex_particles.cpp index 1fc9a6f..f12b23b 100644 --- a/examples/src/ex_particles.cpp +++ b/examples/src/ex_particles.cpp @@ -13,6 +13,7 @@ #include "../include/common/Vec.h" #include "../include/common/random.h" #include "../include/components/components.h" +#include "../include/components/ui.h" #include "../include/scene/Scene.h" class DemoScene : public afk::Scene { @@ -27,7 +28,9 @@ class DemoScene : public afk::Scene { display.setBackgroundColor(afk::color::black); assets.loadImage("fuzzball", "assets/fuzzball.png"); + assets.loadFont("freesans", "assets/freesans.ttf", 24); + // Weird box thing emitterEntity1 = createEntity(); auto& emitter1 = createComponent(emitterEntity1, 10.0f); @@ -46,6 +49,7 @@ class DemoScene : public afk::Scene { physics.acceleration = {0, 2.0f}; } + // Water emitterEntity2 = createEntity(); auto& emitter2 = createComponent(emitterEntity2, 10.0f); @@ -60,10 +64,12 @@ class DemoScene : public afk::Scene { particle.endSize = 2.0f; particle.startColor = afk::color::blue; particle.endColor = afk::color::white; - physics.velocity = {afk::random::randomFloat(-20.0, 20.0), -200.0f}; + physics.velocity = {afk::random::randomFloat(-20.0, 20.0), + afk::random::randomFloat(-200.0f, -220.0f)}; physics.acceleration = {0, 200.0f}; } + // Smoke emitterEntity3 = createEntity(); auto& emitter3 = createComponent(emitterEntity3, 10.0f); @@ -87,6 +93,7 @@ class DemoScene : public afk::Scene { createComponent(emitterEntity4, afk::Vec3(128, 256, 0), afk::Vec2(1, 1)); + // Sparks for (int i = 0; i < 400; i++) { auto& [particle, physics] = emitter4.addPrefab(); particle.type = afk::ParticleType::Square; @@ -99,14 +106,39 @@ class DemoScene : public afk::Scene { afk::random::randomFloat(-40.0f, 40.0f)}; physics.acceleration = {0, 200.0f}; } + + // FPS label + fpsLabel = createEntity(); + createComponent(fpsLabel, afk::Vec3(10, 5, 0)); + auto& fpsLabelComponent = createComponent(fpsLabel); + fpsLabelComponent.font = "freesans"; + fpsLabelComponent.color = afk::color::white; + + countLabel = createEntity(); + createComponent(countLabel, afk::Vec3(10, 20, 0)); + auto& countLabelComponent = createComponent(countLabel); + countLabelComponent.font = "freesans"; + countLabelComponent.color = afk::color::white; } void update(uint32_t delta) override { Scene::update(delta); + // Move smoke to mouse auto& smoke_transform = getComponent(emitterEntity3); smoke_transform.position.x = input.mouseX(); smoke_transform.position.y = input.mouseY(); + + // Set fps label + int fps = display.getFps(); + auto& fpsLabelComponent = getComponent(fpsLabel); + fpsLabelComponent.text = "FPS: " + std::to_string(fps); + + // Set count label + int count = 0; + getRegistry().view().each([&count](auto&) { count++; }); + auto& countLabelComponent = getComponent(countLabel); + countLabelComponent.text = "Count: " + std::to_string(count); } void stop() override { logger.log("Stopping!"); } @@ -116,6 +148,9 @@ class DemoScene : public afk::Scene { afk::Entity emitterEntity2; afk::Entity emitterEntity3; afk::Entity emitterEntity4; + + afk::Entity fpsLabel; + afk::Entity countLabel; }; int main(int argv, char** args) { From e899b2008f4e43054db57237c9a703189516f330 Mon Sep 17 00:00:00 2001 From: alegemaate Date: Sun, 24 Apr 2022 10:59:46 -0400 Subject: [PATCH 14/24] docs: update build instructions --- .gitignore | 7 ------- README.md | 9 +++++++-- afk/CMakeLists.txt | 4 +--- examples/CMakeLists.txt | 10 ++++++---- 4 files changed, 14 insertions(+), 16 deletions(-) diff --git a/.gitignore b/.gitignore index de958a3..7d95a29 100644 --- a/.gitignore +++ b/.gitignore @@ -41,13 +41,6 @@ Icon .Trashes CppCheckResults.xml -CMakeFiles -CMakeCache.txt -Makefile -afk.cmake -cmake_install.cmake -compile_commands.json -install_manifest.txt docs/ .idea/ build/ diff --git a/README.md b/README.md index 628b626..0dff4e5 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,9 @@ sudo apt install libsdl2-dev libsdl2-image-dev libsdl2-ttf-dev libsdl2-mixer-dev ### Build ```bash -cmake . +mkdir build +cd build +cmake ../ ``` ```bash @@ -58,7 +60,9 @@ make ### Build Emscripten ```bash -emcmake cmake . +mkdir build +cd build +emcmake cmake ../ ``` ```bash @@ -68,5 +72,6 @@ make ### Install Library (works for emscripten) ```bash +cd build make install ``` diff --git a/afk/CMakeLists.txt b/afk/CMakeLists.txt index 3e32789..bf3f965 100644 --- a/afk/CMakeLists.txt +++ b/afk/CMakeLists.txt @@ -5,8 +5,6 @@ project (afk LANGUAGES CXX ) -set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/build/lib) -set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/build/lib) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -33,7 +31,7 @@ target_compile_options(${PROJECT_NAME} PRIVATE -Wall -Wextra - -pedantic + -pedantic ) set_target_properties(${PROJECT_NAME} diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 370481c..4e8f362 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -5,11 +5,12 @@ project (examples LANGUAGES CXX ) -include(${EXTERNAL_DIR}/libs.cmake) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +include(${EXTERNAL_DIR}/libs.cmake) # Config -set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/build) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(EXAMPLES ex_display ex_sprite ex_rotate ex_fps ex_mouse ex_physics ex_sound ex_particles ex_keyboard ex_collision ex_message_box) @@ -57,5 +58,6 @@ foreach(EX_NAME ${EXAMPLES}) endif(EMSCRIPTEN) endforeach() -# Export assets -file(COPY ${CMAKE_CURRENT_LIST_DIR}/assets/ DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/assets/) +# Export assets (one for pwd and one for running manually) +file(COPY ${CMAKE_CURRENT_LIST_DIR}/assets/ DESTINATION ${CMAKE_BINARY_DIR}/assets/) +file(COPY ${CMAKE_CURRENT_LIST_DIR}/assets/ DESTINATION ${CMAKE_BINARY_DIR}/examples/assets/) From a41cb6ebb552cea27bf36f1893fb5febfab3c060 Mon Sep 17 00:00:00 2001 From: alegemaate Date: Sun, 24 Apr 2022 15:54:44 -0400 Subject: [PATCH 15/24] fix: emscripten flags --- .vscode/settings.json | 2 +- .vscode/tasks.json | 7 ---- afk/CMakeLists.txt | 29 ++++++++-------- afk/include/entities/Entity.h | 2 +- afk/include/systems/RenderSystem.h | 2 +- examples/CMakeLists.txt | 55 +++++++++++++++++------------- 6 files changed, 48 insertions(+), 49 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 2361886..b704bce 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -118,5 +118,5 @@ "codecvt": "cpp" }, "cmake.configureOnOpen": true, - "sonarlint.pathToCompileCommands": "c:\\Users\\alege\\Documents\\GitHub\\AfkLib\\compile_commands.json" + "sonarlint.pathToCompileCommands": "c:\\Users\\alege\\Documents\\GitHub\\AfkLib\\build\\compile_commands.json" } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index cb16d03..40198eb 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -1,13 +1,6 @@ { "version": "2.0.0", "tasks": [ - { - "label": "Build", - "type": "shell", - "command": "make -j24", - "problemMatcher": ["$gcc"], - "group": "build" - }, { "type": "cppbuild", "label": "C/C++: g++.exe build active file", diff --git a/afk/CMakeLists.txt b/afk/CMakeLists.txt index bf3f965..1d036a2 100644 --- a/afk/CMakeLists.txt +++ b/afk/CMakeLists.txt @@ -42,27 +42,26 @@ set_target_properties(${PROJECT_NAME} # Emscripten specific options if(EMSCRIPTEN) - set_target_properties(${PROJECT_NAME} - PROPERTIES - LINK_FLAGS - "-s DEMANGLE_SUPPORT=1 -s DISABLE_EXCEPTION_CATCHING=0 -s USE_SDL=2 -s USE_SDL_IMAGE=2 -s USE_SDL_TTF=2 -s USE_SDL_MIXER=2 -s USE_SDL_GFX=2 -s SDL2_IMAGE_FORMATS=[\"png\"]" + target_compile_options(${PROJECT_NAME} + PUBLIC + -sUSE_SDL=2 + -sUSE_SDL_IMAGE=2 + -sUSE_SDL_TTF=2 + -sUSE_SDL_MIXER=2 + -sUSE_SDL_GFX=2 + -sSDL2_IMAGE_FORMATS=["png"] ) - - target_link_libraries(${PROJECT_NAME} imported::entt) + + set(SDL2_LIBRARIES "-s USE_SDL=2 -s USE_SDL_IMAGE=2 -s USE_SDL_TTF=2 -s USE_SDL_MIXER=2 -s USE_SDL_GFX=2") # All other system options else(EMSCRIPTEN) - target_link_libraries(${PROJECT_NAME} - PUBLIC - SDL2::Image - SDL2::Mixer - SDL2::TTF - SDL2::GFX - SDL2::Main - imported::entt - ) + set(SDL2_LIBRARIES "SDL2::Image SDL2::Mixer SDL2::TTF SDL2::GFX SDL2::Main") endif(EMSCRIPTEN) +# Link link libraries +target_link_libraries(${PROJECT_NAME} PUBLIC ${SDL2_LIBRARIES} imported::entt) + # Install info if (EMSCRIPTEN OR WIN32) if (EMSCRIPTEN) diff --git a/afk/include/entities/Entity.h b/afk/include/entities/Entity.h index 91360f6..1e992e0 100644 --- a/afk/include/entities/Entity.h +++ b/afk/include/entities/Entity.h @@ -11,7 +11,7 @@ #ifndef AFK_ENTITY_H #define AFK_ENTITY_H -#include +#include "../../lib/entt/src/entt/entt.hpp" namespace afk { diff --git a/afk/include/systems/RenderSystem.h b/afk/include/systems/RenderSystem.h index db249eb..9470595 100644 --- a/afk/include/systems/RenderSystem.h +++ b/afk/include/systems/RenderSystem.h @@ -11,7 +11,7 @@ #ifndef AFK_RENDERSYSTEM_H #define AFK_RENDERSYSTEM_H -#include +#include "../../lib/entt/src/entt/entt.hpp" #include "entities/Entity.h" #include "services/assets/AssetService.h" diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 4e8f362..fa17aaf 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -27,37 +27,44 @@ foreach(EX_NAME ${EXAMPLES}) -Wno-unused-parameter ) - # Emscripten support - if(EMSCRIPTEN) + # Emscripten specific options + if(EMSCRIPTEN) set(CMAKE_EXECUTABLE_SUFFIX ".html") - set_target_properties(${EX_NAME} - PROPERTIES - LINK_FLAGS - "--preload-file ${CMAKE_CURRENT_LIST_DIR}/assets@/assets --use-preload-plugins -s DEMANGLE_SUPPORT=1 -s DISABLE_EXCEPTION_CATCHING=0 -s USE_SDL=2 -s USE_SDL_IMAGE=2 -s USE_SDL_TTF=2 -s USE_SDL_MIXER=2 -s USE_SDL_GFX=2 -s SDL2_IMAGE_FORMATS=[\"png\"]" + target_compile_options(${EX_NAME} + PUBLIC + -sUSE_SDL=2 + -sUSE_SDL_IMAGE=2 + -sUSE_SDL_TTF=2 + -sUSE_SDL_MIXER=2 + -sUSE_SDL_GFX=2 ) - target_link_libraries(${EX_NAME} imported::entt afk) + set(SDL2_LIBRARIES + "--use-preload-plugins \ + --preload-file ${CMAKE_CURRENT_LIST_DIR}/assets@/assets \ + -s DISABLE_EXCEPTION_CATCHING=0 \ + -s DEMANGLE_SUPPORT=1 \ + -s USE_SDL=2 \ + -s USE_SDL_IMAGE=2 \ + -s USE_SDL_TTF=2 \ + -s USE_SDL_MIXER=2 \ + -s USE_SDL_GFX=2 \ + -s SDL2_IMAGE_FORMATS=[\"png\"]" + ) - # Run of the mill executable + # All other system options else(EMSCRIPTEN) - if(MINGW) - target_link_libraries(${EX_NAME} -lmingw32) - endif(MINGW) - - target_link_libraries(${EX_NAME} - -lm - SDL2::Main - SDL2::Image - SDL2::Mixer - SDL2::TTF - SDL2::GFX - EnTT::EnTT - afk - ) + set(SDL2_LIBRARIES "SDL2::Image SDL2::Mixer SDL2::TTF SDL2::GFX SDL2::Main") endif(EMSCRIPTEN) + + # Link libraries + if(MINGW) + target_link_libraries(${EX_NAME} -lmingw32) + endif(MINGW) + + target_link_libraries(${EX_NAME} PUBLIC ${SDL2_LIBRARIES} imported::entt afk) endforeach() -# Export assets (one for pwd and one for running manually) -file(COPY ${CMAKE_CURRENT_LIST_DIR}/assets/ DESTINATION ${CMAKE_BINARY_DIR}/assets/) +# Export assets file(COPY ${CMAKE_CURRENT_LIST_DIR}/assets/ DESTINATION ${CMAKE_BINARY_DIR}/examples/assets/) From b09a17875c17018ed99bd5b64f68855348400aa0 Mon Sep 17 00:00:00 2001 From: alegemaate Date: Sun, 24 Apr 2022 16:15:17 -0400 Subject: [PATCH 16/24] fix: cmake lib include method --- afk/CMakeLists.txt | 6 +++--- examples/CMakeLists.txt | 9 +++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/afk/CMakeLists.txt b/afk/CMakeLists.txt index 1d036a2..546147f 100644 --- a/afk/CMakeLists.txt +++ b/afk/CMakeLists.txt @@ -52,15 +52,15 @@ if(EMSCRIPTEN) -sSDL2_IMAGE_FORMATS=["png"] ) - set(SDL2_LIBRARIES "-s USE_SDL=2 -s USE_SDL_IMAGE=2 -s USE_SDL_TTF=2 -s USE_SDL_MIXER=2 -s USE_SDL_GFX=2") + set(SDL_LIBRARIES -sUSE_SDL=2 -sUSE_SDL_IMAGE=2 -sUSE_SDL_TTF=2 -sUSE_SDL_MIXER=2 -sUSE_SDL_GFX=2) # All other system options else(EMSCRIPTEN) - set(SDL2_LIBRARIES "SDL2::Image SDL2::Mixer SDL2::TTF SDL2::GFX SDL2::Main") + set(SDL_LIBRARIES SDL2::Image SDL2::Mixer SDL2::TTF SDL2::GFX SDL2::Main) endif(EMSCRIPTEN) # Link link libraries -target_link_libraries(${PROJECT_NAME} PUBLIC ${SDL2_LIBRARIES} imported::entt) +target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL_LIBRARIES} imported::entt) # Install info if (EMSCRIPTEN OR WIN32) diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index fa17aaf..6e074f5 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -40,7 +40,7 @@ foreach(EX_NAME ${EXAMPLES}) -sUSE_SDL_GFX=2 ) - set(SDL2_LIBRARIES + set(SDL_LIBRARIES "--use-preload-plugins \ --preload-file ${CMAKE_CURRENT_LIST_DIR}/assets@/assets \ -s DISABLE_EXCEPTION_CATCHING=0 \ @@ -55,16 +55,17 @@ foreach(EX_NAME ${EXAMPLES}) # All other system options else(EMSCRIPTEN) - set(SDL2_LIBRARIES "SDL2::Image SDL2::Mixer SDL2::TTF SDL2::GFX SDL2::Main") + set(SDL_LIBRARIES SDL2::Image SDL2::Mixer SDL2::TTF SDL2::GFX SDL2::Main) endif(EMSCRIPTEN) # Link libraries if(MINGW) - target_link_libraries(${EX_NAME} -lmingw32) + target_link_libraries(${EX_NAME} PRIVATE -lmingw32) endif(MINGW) - target_link_libraries(${EX_NAME} PUBLIC ${SDL2_LIBRARIES} imported::entt afk) + target_link_libraries(${EX_NAME} PRIVATE ${SDL_LIBRARIES} imported::entt afk) endforeach() # Export assets file(COPY ${CMAKE_CURRENT_LIST_DIR}/assets/ DESTINATION ${CMAKE_BINARY_DIR}/examples/assets/) + \ No newline at end of file From 6357daea87f9779ac2609061f99d536275e99456 Mon Sep 17 00:00:00 2001 From: alegemaate Date: Sun, 24 Apr 2022 16:49:46 -0400 Subject: [PATCH 17/24] feat: use ninja --- .github/workflows/build-linux.yml | 4 ++-- .github/workflows/build-macos.yml | 4 ++-- .github/workflows/build-web.yml | 4 ++-- .github/workflows/build-windows.yml | 20 ++++++++++---------- .github/workflows/deploy-docs.yml | 6 +++--- CMakeLists.txt | 2 +- afk/CMakeLists.txt | 3 +-- 7 files changed, 21 insertions(+), 22 deletions(-) diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml index 10c259d..b94c6a0 100644 --- a/.github/workflows/build-linux.yml +++ b/.github/workflows/build-linux.yml @@ -21,7 +21,7 @@ jobs: sudo apt install libsdl2-dev libsdl2-image-dev libsdl2-ttf-dev libsdl2-mixer-dev libsdl2-gfx-dev - name: Run CMake - run: cmake -G "Unix Makefiles" . + run: cmake -G "Ninja" . - name: Make - run: make -j4 + run: ninja diff --git a/.github/workflows/build-macos.yml b/.github/workflows/build-macos.yml index 1fe705a..f16e917 100644 --- a/.github/workflows/build-macos.yml +++ b/.github/workflows/build-macos.yml @@ -20,9 +20,9 @@ jobs: brew install sdl2 sdl2_image sdl2_gfx sdl2_ttf sdl2_mixer - name: Run CMake - run: cmake -G "Unix Makefiles" . + run: cmake -G "Ninja" . - name: Make run: | export CPLUS_INCLUDE_PATH="$CPLUS_INCLUDE_PATH:/usr/local/include" - make -j4 + ninja diff --git a/.github/workflows/build-web.yml b/.github/workflows/build-web.yml index cec8354..c47cd2d 100644 --- a/.github/workflows/build-web.yml +++ b/.github/workflows/build-web.yml @@ -21,7 +21,7 @@ jobs: actions-cache-folder: "emsdk-cache" - name: Run CMake - run: emcmake cmake -G "Unix Makefiles" . + run: emcmake cmake -G "Ninja" . - name: Make - run: emmake make -j4 + run: ninja diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml index beb93d5..3cfb074 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -8,6 +8,9 @@ jobs: build: name: Build Windows runs-on: windows-latest + defaults: + run: + shell: msys2 {0} steps: - name: Checkout @@ -15,17 +18,14 @@ jobs: with: submodules: true - - name: Install Libraries - run: | - Set-Item -Path Env:Path -Value ("C:/msys64/usr/bin;" + $Env:Path) - pacman --noconfirm -S mingw-w64-i686-gcc-libs mingw-w64-i686-SDL2 mingw-w64-i686-SDL2_mixer mingw-w64-i686-SDL2_image mingw-w64-i686-SDL2_ttf mingw-w64-i686-SDL2_gfx + - uses: msys2/setup-msys2@v2 + with: + msystem: MINGW64 + update: true + install: mingw-w64-i686-gcc-libs mingw-w64-i686-SDL2 mingw-w64-i686-SDL2_mixer mingw-w64-i686-SDL2_image mingw-w64-i686-SDL2_ttf mingw-w64-i686-SDL2_gfx - name: Run CMake - run: | - Set-Item -Path Env:Path -Value ("C:/msys64/mingw32/bin;" + $Env:Path) - cmake -G "MSYS Makefiles" . + run: cmake -G "Ninja" . - name: Make - run: | - Set-Item -Path Env:Path -Value ("C:/msys64/mingw32/bin;" + $Env:Path) - make -j4 + run: ninja diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 43f1f52..87ff4be 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -21,10 +21,10 @@ jobs: actions-cache-folder: "emsdk-cache" - name: Run CMake - run: emcmake cmake -G "Unix Makefiles" . + run: emcmake cmake -G "Ninja" . - name: Make - run: emmake make -j4 + run: ninja - name: Install graphviz run: sudo apt install graphviz @@ -35,7 +35,7 @@ jobs: doxyfile-path: "./Doxyfile" - name: Copy Bin to Docs - run: sudo cp -r ./bin ./docs/examples + run: sudo cp -r ./build/examples ./docs/examples - name: Deploy docs uses: peaceiris/actions-gh-pages@v3 diff --git a/CMakeLists.txt b/CMakeLists.txt index 59cfa25..1da40f4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -13,4 +13,4 @@ add_subdirectory(${EXTERNAL_DIR}/entt EXCLUDE_FROM_ALL) add_subdirectory(${PROJECT_SOURCE_DIR}/afk) # Examples -add_subdirectory(${PROJECT_SOURCE_DIR}/examples EXCLUDE_FROM_ALL) \ No newline at end of file +add_subdirectory(${PROJECT_SOURCE_DIR}/examples) \ No newline at end of file diff --git a/afk/CMakeLists.txt b/afk/CMakeLists.txt index 546147f..7fb31c2 100644 --- a/afk/CMakeLists.txt +++ b/afk/CMakeLists.txt @@ -65,8 +65,7 @@ target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL_LIBRARIES} imported::entt) # Install info if (EMSCRIPTEN OR WIN32) if (EMSCRIPTEN) - get_filename_component(EMSDK_DIR ${CMAKE_TOOLCHAIN_FILE} DIRECTORY) - set(BASE_DIR ${EMSDK_DIR}/../../../system) + set(BASE_DIR ${CMAKE_INSTALL_PREFIX}) elseif (WIN32) get_filename_component(WIN32_BIN_PATH ${CMAKE_C_COMPILER} PATH) set(BASE_DIR ${WIN32_BIN_PATH}/..) From 822005eeef013797b7062871d32adee51a4865b7 Mon Sep 17 00:00:00 2001 From: alegemaate Date: Sun, 24 Apr 2022 16:54:12 -0400 Subject: [PATCH 18/24] fix: revert to platform specific build tools --- .github/workflows/build-linux.yml | 4 ++-- .github/workflows/build-macos.yml | 6 ++++-- .github/workflows/build-web.yml | 6 ++++-- .github/workflows/build-windows.yml | 4 ++-- .github/workflows/deploy-docs.yml | 2 ++ 5 files changed, 14 insertions(+), 8 deletions(-) diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml index b94c6a0..10c259d 100644 --- a/.github/workflows/build-linux.yml +++ b/.github/workflows/build-linux.yml @@ -21,7 +21,7 @@ jobs: sudo apt install libsdl2-dev libsdl2-image-dev libsdl2-ttf-dev libsdl2-mixer-dev libsdl2-gfx-dev - name: Run CMake - run: cmake -G "Ninja" . + run: cmake -G "Unix Makefiles" . - name: Make - run: ninja + run: make -j4 diff --git a/.github/workflows/build-macos.yml b/.github/workflows/build-macos.yml index f16e917..bb0b5f5 100644 --- a/.github/workflows/build-macos.yml +++ b/.github/workflows/build-macos.yml @@ -15,14 +15,16 @@ jobs: with: submodules: true + - uses: seanmiddleditch/gha-setup-ninja@master + - name: Install Libraries run: | brew install sdl2 sdl2_image sdl2_gfx sdl2_ttf sdl2_mixer - name: Run CMake - run: cmake -G "Ninja" . + run: cmake -G "Unix Makefiles" . - name: Make run: | export CPLUS_INCLUDE_PATH="$CPLUS_INCLUDE_PATH:/usr/local/include" - ninja + make -j4 diff --git a/.github/workflows/build-web.yml b/.github/workflows/build-web.yml index c47cd2d..5516807 100644 --- a/.github/workflows/build-web.yml +++ b/.github/workflows/build-web.yml @@ -15,13 +15,15 @@ jobs: with: submodules: true + - uses: seanmiddleditch/gha-setup-ninja@master + - name: Setup Emscripten uses: mymindstorm/setup-emsdk@v11 with: actions-cache-folder: "emsdk-cache" - name: Run CMake - run: emcmake cmake -G "Ninja" . + run: emcmake cmake -G "Unix Makefiles" . - name: Make - run: ninja + run: make -j4 diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml index 3cfb074..6506888 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -25,7 +25,7 @@ jobs: install: mingw-w64-i686-gcc-libs mingw-w64-i686-SDL2 mingw-w64-i686-SDL2_mixer mingw-w64-i686-SDL2_image mingw-w64-i686-SDL2_ttf mingw-w64-i686-SDL2_gfx - name: Run CMake - run: cmake -G "Ninja" . + run: cmake -G "MSYS Makefiles" . - name: Make - run: ninja + run: make -j4 diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 87ff4be..3430deb 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -15,6 +15,8 @@ jobs: with: submodules: true + - uses: seanmiddleditch/gha-setup-ninja@master + - name: Setup Emscripten uses: mymindstorm/setup-emsdk@v11 with: From d6e22516e0c81e626ee6c325b6e3b4fc9554cb36 Mon Sep 17 00:00:00 2001 From: alegemaate Date: Sun, 24 Apr 2022 16:58:53 -0400 Subject: [PATCH 19/24] fix: install cmake msys --- .github/workflows/build-windows.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml index 6506888..8e7885b 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -22,7 +22,7 @@ jobs: with: msystem: MINGW64 update: true - install: mingw-w64-i686-gcc-libs mingw-w64-i686-SDL2 mingw-w64-i686-SDL2_mixer mingw-w64-i686-SDL2_image mingw-w64-i686-SDL2_ttf mingw-w64-i686-SDL2_gfx + install: cmake mingw-w64-i686-gcc-libs mingw-w64-i686-SDL2 mingw-w64-i686-SDL2_mixer mingw-w64-i686-SDL2_image mingw-w64-i686-SDL2_ttf mingw-w64-i686-SDL2_gfx - name: Run CMake run: cmake -G "MSYS Makefiles" . From 0de64c121fec67d4e50a356eb0de76111ce39a8e Mon Sep 17 00:00:00 2001 From: alegemaate Date: Sun, 24 Apr 2022 17:03:34 -0400 Subject: [PATCH 20/24] fix: windows makefiles --- .github/workflows/build-windows.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml index 8e7885b..4dce1c9 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -25,7 +25,7 @@ jobs: install: cmake mingw-w64-i686-gcc-libs mingw-w64-i686-SDL2 mingw-w64-i686-SDL2_mixer mingw-w64-i686-SDL2_image mingw-w64-i686-SDL2_ttf mingw-w64-i686-SDL2_gfx - name: Run CMake - run: cmake -G "MSYS Makefiles" . + run: cmake -G "Unix Makefiles" . - name: Make run: make -j4 From 0def886541b60164efa11bc5ac4021e81ef0f810 Mon Sep 17 00:00:00 2001 From: alegemaate Date: Sun, 24 Apr 2022 17:12:39 -0400 Subject: [PATCH 21/24] fix: use mingw 32 --- .github/workflows/build-windows.yml | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml index 4dce1c9..24d9ffa 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -13,19 +13,31 @@ jobs: shell: msys2 {0} steps: + - uses: msys2/setup-msys2@v2 + with: + msystem: mingw32 + update: true + install: >- + make + git + mingw-w64-i686-gcc-libs + mingw-w64-i686-SDL2 + mingw-w64-i686-SDL2_mixer + mingw-w64-i686-SDL2_image + mingw-w64-i686-SDL2_ttf + mingw-w64-i686-SDL2_gfx + pacboy: >- + toolchain:p + cmake:p + ninja:p + - name: Checkout uses: actions/checkout@v3 with: submodules: true - - uses: msys2/setup-msys2@v2 - with: - msystem: MINGW64 - update: true - install: cmake mingw-w64-i686-gcc-libs mingw-w64-i686-SDL2 mingw-w64-i686-SDL2_mixer mingw-w64-i686-SDL2_image mingw-w64-i686-SDL2_ttf mingw-w64-i686-SDL2_gfx - - - name: Run CMake - run: cmake -G "Unix Makefiles" . + - name: Run CMake + run: cmake -G Ninja . - name: Make run: make -j4 From 7c9710882f922237b9a7347f18d206cef5c6ffbf Mon Sep 17 00:00:00 2001 From: Allan Legemaate Date: Sun, 24 Apr 2022 17:43:22 -0400 Subject: [PATCH 22/24] feat: use 64 bit msys --- .github/workflows/build-linux.yml | 2 +- .github/workflows/build-macos.yml | 2 +- .github/workflows/build-web.yml | 2 +- .github/workflows/build-windows.yml | 19 +++++++++---------- .github/workflows/deploy-docs.yml | 2 +- .vscode/c_cpp_properties.json | 25 ++++++++++++++----------- .vscode/tasks.json | 2 +- README.md | 2 +- 8 files changed, 29 insertions(+), 27 deletions(-) diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml index 10c259d..d932bf3 100644 --- a/.github/workflows/build-linux.yml +++ b/.github/workflows/build-linux.yml @@ -21,7 +21,7 @@ jobs: sudo apt install libsdl2-dev libsdl2-image-dev libsdl2-ttf-dev libsdl2-mixer-dev libsdl2-gfx-dev - name: Run CMake - run: cmake -G "Unix Makefiles" . + run: cmake -G "Unix Makefiles" . -DCMAKE_BUILD_TYPE=Release - name: Make run: make -j4 diff --git a/.github/workflows/build-macos.yml b/.github/workflows/build-macos.yml index bb0b5f5..1405d20 100644 --- a/.github/workflows/build-macos.yml +++ b/.github/workflows/build-macos.yml @@ -22,7 +22,7 @@ jobs: brew install sdl2 sdl2_image sdl2_gfx sdl2_ttf sdl2_mixer - name: Run CMake - run: cmake -G "Unix Makefiles" . + run: cmake -G "Unix Makefiles" . -DCMAKE_BUILD_TYPE=Release - name: Make run: | diff --git a/.github/workflows/build-web.yml b/.github/workflows/build-web.yml index 5516807..bb50a8a 100644 --- a/.github/workflows/build-web.yml +++ b/.github/workflows/build-web.yml @@ -23,7 +23,7 @@ jobs: actions-cache-folder: "emsdk-cache" - name: Run CMake - run: emcmake cmake -G "Unix Makefiles" . + run: emcmake cmake -G "Unix Makefiles" . -DCMAKE_BUILD_TYPE=Release - name: Make run: make -j4 diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml index 24d9ffa..b01cac1 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -15,17 +15,16 @@ jobs: steps: - uses: msys2/setup-msys2@v2 with: - msystem: mingw32 update: true - install: >- + install: >- make git - mingw-w64-i686-gcc-libs - mingw-w64-i686-SDL2 - mingw-w64-i686-SDL2_mixer - mingw-w64-i686-SDL2_image - mingw-w64-i686-SDL2_ttf - mingw-w64-i686-SDL2_gfx + mingw-w64-x86_64-gcc-libs + mingw-w64-x86_64-SDL2 + mingw-w64-x86_64-SDL2_mixer + mingw-w64-x86_64-SDL2_image + mingw-w64-x86_64-SDL2_ttf + mingw-w64-x86_64-SDL2_gfx pacboy: >- toolchain:p cmake:p @@ -36,8 +35,8 @@ jobs: with: submodules: true - - name: Run CMake - run: cmake -G Ninja . + - name: Run CMake + run: cmake -G Ninja . -DCMAKE_BUILD_TYPE=Release - name: Make run: make -j4 diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 3430deb..af488b6 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -23,7 +23,7 @@ jobs: actions-cache-folder: "emsdk-cache" - name: Run CMake - run: emcmake cmake -G "Ninja" . + run: emcmake cmake -G "Unix Makefiles" . -DCMAKE_BUILD_TYPE=Release - name: Make run: ninja diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json index 8c7266f..e9dc57e 100644 --- a/.vscode/c_cpp_properties.json +++ b/.vscode/c_cpp_properties.json @@ -1,12 +1,15 @@ { - "configurations": [ - { - "name": "Default", - "intelliSenseMode": "gcc-x86", - "cStandard": "c11", - "cppStandard": "c++17", - "includePath": ["afk/include"] - } - ], - "version": 4 -} + "configurations": [ + { + "name": "Default", + "intelliSenseMode": "gcc-x86", + "cStandard": "c11", + "cppStandard": "c++17", + "includePath": [ + "afk/include" + ], + "compileCommands": "${workspaceFolder}/build/compile_commands.json" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 40198eb..c067766 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -4,7 +4,7 @@ { "type": "cppbuild", "label": "C/C++: g++.exe build active file", - "command": "C:\\msys64\\mingw32\\bin\\g++.exe", + "command": "g++.exe", "args": [ "-fdiagnostics-color=always", "-g", diff --git a/README.md b/README.md index 0dff4e5..d6683e1 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ Game framework ### Windows (MSYS2) ```bash -pacman -S mingw-w64-i686-gcc-libs mingw-w64-i686-SDL2 mingw-w64-i686-SDL2_mixer mingw-w64-i686-SDL2_image mingw-w64-i686-SDL2_ttf mingw-w64-i686-SDL2_gfx +pacman -S mingw-w64-x86_64-gcc-libs mingw-w64-x86_64-SDL2 mingw-w64-x86_64-SDL2_mixer mingw-w64-x86_64-SDL2_image mingw-w64-x86_64-SDL2_ttf mingw-w64-x86_64-SDL2_gfx ``` ### Mac OS From df4f5158421f172dd59e63cf3b3062dad9f0da14 Mon Sep 17 00:00:00 2001 From: Allan Legemaate Date: Mon, 25 Apr 2022 21:29:31 -0400 Subject: [PATCH 23/24] feat: use ninja again in windows build --- .github/workflows/build-windows.yml | 2 +- .vscode/c_cpp_properties.json | 26 ++++++++++++-------------- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml index b01cac1..0995952 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -39,4 +39,4 @@ jobs: run: cmake -G Ninja . -DCMAKE_BUILD_TYPE=Release - name: Make - run: make -j4 + run: ninja diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json index e9dc57e..aa7c728 100644 --- a/.vscode/c_cpp_properties.json +++ b/.vscode/c_cpp_properties.json @@ -1,15 +1,13 @@ { - "configurations": [ - { - "name": "Default", - "intelliSenseMode": "gcc-x86", - "cStandard": "c11", - "cppStandard": "c++17", - "includePath": [ - "afk/include" - ], - "compileCommands": "${workspaceFolder}/build/compile_commands.json" - } - ], - "version": 4 -} \ No newline at end of file + "configurations": [ + { + "name": "Default", + "intelliSenseMode": "gcc-x86", + "cStandard": "c11", + "cppStandard": "c++17", + "includePath": ["afk/include"], + "compileCommands": "${workspaceFolder}/build/compile_commands.json" + } + ], + "version": 4 +} From 4af0888c646fc3157e8c0e3621ae37eafb675e45 Mon Sep 17 00:00:00 2001 From: Allan Legemaate Date: Fri, 29 Apr 2022 23:28:18 -0400 Subject: [PATCH 24/24] feat: attach sprite to texture directly --- .gitmodules | 3 - CMakeLists.txt | 7 +-- afk/CMakeLists.txt | 65 +++++++++------------- afk/include/assets/Texture.h | 23 ++++---- afk/include/components/Sprite.h | 4 +- afk/include/entities/Entity.h | 2 +- afk/include/scene/Scene.h | 2 +- afk/include/services/assets/AssetService.h | 10 ++-- afk/include/systems/RenderSystem.h | 4 +- afk/src/assets/Texture.cpp | 29 ++++------ afk/src/scene/Scene.cpp | 2 +- afk/src/services/assets/AssetService.cpp | 19 +++++-- afk/src/systems/RenderSystem.cpp | 7 +-- examples/CMakeLists.txt | 37 +++--------- examples/src/ex_collision.cpp | 6 +- examples/src/ex_fps.cpp | 4 +- examples/src/ex_keyboard.cpp | 4 +- examples/src/ex_mouse.cpp | 4 +- examples/src/ex_physics.cpp | 4 +- examples/src/ex_rotate.cpp | 4 +- examples/src/ex_sprite.cpp | 4 +- lib/afk-config.cmake | 4 ++ lib/entt | 1 - lib/libs.cmake | 22 +++++--- 24 files changed, 123 insertions(+), 148 deletions(-) delete mode 100644 .gitmodules create mode 100644 lib/afk-config.cmake delete mode 160000 lib/entt diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 5c02c1b..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "lib/entt"] - path = lib/entt - url = https://github.com/skypjack/entt.git diff --git a/CMakeLists.txt b/CMakeLists.txt index 1da40f4..748f6e6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,14 +1,11 @@ -cmake_minimum_required(VERSION 3.14) +cmake_minimum_required(VERSION 3.16) -project (root VERSION 1.0.0 LANGUAGES CXX) +project (root) # Config set(CMAKE_EXPORT_COMPILE_COMMANDS on) set(EXTERNAL_DIR ${PROJECT_SOURCE_DIR}/lib) -# Submodule libs -add_subdirectory(${EXTERNAL_DIR}/entt EXCLUDE_FROM_ALL) - # Core lib add_subdirectory(${PROJECT_SOURCE_DIR}/afk) diff --git a/afk/CMakeLists.txt b/afk/CMakeLists.txt index 7fb31c2..09d60ed 100644 --- a/afk/CMakeLists.txt +++ b/afk/CMakeLists.txt @@ -1,6 +1,6 @@ -cmake_minimum_required(VERSION 3.14) +cmake_minimum_required(VERSION 3.16) -project (afk +project (afk VERSION 1.0.0 LANGUAGES CXX ) @@ -8,8 +8,6 @@ project (afk set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) -include(${EXTERNAL_DIR}/libs.cmake) - # Sources file(GLOB_RECURSE SOURCES ${PROJECT_SOURCE_DIR}/src/*.cpp) file(GLOB_RECURSE HEADERS ${PROJECT_SOURCE_DIR}/include/*.h) @@ -22,9 +20,11 @@ add_library(${PROJECT_NAME} ) target_include_directories(${PROJECT_NAME} - PUBLIC + PUBLIC $ $ + PRIVATE + ${EXTERNAL_INCLUDE_DIRS} ) target_compile_options(${PROJECT_NAME} @@ -43,63 +43,50 @@ set_target_properties(${PROJECT_NAME} # Emscripten specific options if(EMSCRIPTEN) target_compile_options(${PROJECT_NAME} - PUBLIC + PRIVATE -sUSE_SDL=2 -sUSE_SDL_IMAGE=2 -sUSE_SDL_TTF=2 -sUSE_SDL_MIXER=2 -sUSE_SDL_GFX=2 - -sSDL2_IMAGE_FORMATS=["png"] ) - set(SDL_LIBRARIES -sUSE_SDL=2 -sUSE_SDL_IMAGE=2 -sUSE_SDL_TTF=2 -sUSE_SDL_MIXER=2 -sUSE_SDL_GFX=2) - -# All other system options -else(EMSCRIPTEN) - set(SDL_LIBRARIES SDL2::Image SDL2::Mixer SDL2::TTF SDL2::GFX SDL2::Main) + set(EXTERNAL_INCLUDE_LIBS ${EXTERNAL_INCLUDE_LIBS} -sUSE_SDL=2 -sUSE_SDL_IMAGE=2 -sUSE_SDL_TTF=2 -sUSE_SDL_MIXER=2 -sUSE_SDL_GFX=2) endif(EMSCRIPTEN) # Link link libraries -target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL_LIBRARIES} imported::entt) +include(${EXTERNAL_DIR}/libs.cmake) + +target_link_libraries(${PROJECT_NAME} PRIVATE ${EXTERNAL_INCLUDE_LIBS}) # Install info -if (EMSCRIPTEN OR WIN32) - if (EMSCRIPTEN) - set(BASE_DIR ${CMAKE_INSTALL_PREFIX}) - elseif (WIN32) - get_filename_component(WIN32_BIN_PATH ${CMAKE_C_COMPILER} PATH) - set(BASE_DIR ${WIN32_BIN_PATH}/..) - endif(EMSCRIPTEN) - - message(STATUS "Lib install directory set to ${BASE_DIR}") - - set(CMAKE_INSTALL_LIBDIR ${BASE_DIR}/lib) - set(CMAKE_INSTALL_BINDIR ${BASE_DIR}/bin) - set(CMAKE_INSTALL_INCLUDEDIR ${BASE_DIR}/include) - set(CMAKE_INSTALL_DATAROOTDIR ${BASE_DIR}/share) -else() - include(GNUInstallDirs) -endif() +IF(MINGW) + get_filename_component(BINARY_PATH ${CMAKE_C_COMPILER} PATH) + set(CMAKE_INSTALL_PREFIX ${BINARY_PATH}/..) +endif(MINGW) + +include(GNUInstallDirs) +message(STATUS "Lib install directory set to ${CMAKE_INSTALL_PREFIX}") + install( TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_FULL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_FULL_LIBDIR} ) install( DIRECTORY include/ - DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME} + DESTINATION ${CMAKE_INSTALL_FULL_INCLUDEDIR}/${PROJECT_NAME} ) install( EXPORT ${PROJECT_NAME} - DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/${PROJECT_NAME}/cmake + DESTINATION ${CMAKE_INSTALL_FULL_LIBDIR}/cmake/${PROJECT_NAME} ) -export( - TARGETS ${PROJECT_NAME} - FILE ${PROJECT_NAME}.cmake -) \ No newline at end of file +install( + FILES ${EXTERNAL_DIR}/${PROJECT_NAME}-config.cmake + DESTINATION ${CMAKE_INSTALL_FULL_LIBDIR}/cmake/${PROJECT_NAME} +) diff --git a/afk/include/assets/Texture.h b/afk/include/assets/Texture.h index 4c9ed61..3cb3ab1 100644 --- a/afk/include/assets/Texture.h +++ b/afk/include/assets/Texture.h @@ -15,6 +15,7 @@ #include #include "../common/Color.h" +#include "../common/Vec.h" namespace afk { @@ -91,18 +92,11 @@ class Texture { TextureDrawMode mode = TextureDrawMode::Default) const; /** - * @brief Get the width of the texture + * @brief Get the size of the texture * - * @return Width of texture + * @return Size of texture */ - int getWidth() const; - - /** - * @brief Get the height of the texture - * - * @return Height of texture - */ - int getHeight() const; + Vec2 getSize(); /** * @brief Check if texture has been loaded @@ -112,6 +106,12 @@ class Texture { bool exists() const; private: + /** + * @brief Calculate and set size of texture + * + */ + void calculateSize(); + /** * @brief Helper which loads an SDL_Texture* from a file * @@ -123,6 +123,9 @@ class Texture { /// Pointer to referenced texture SDL_Texture* texture; + + /// Size of texture + Vec2 size; }; } // namespace afk diff --git a/afk/include/components/Sprite.h b/afk/include/components/Sprite.h index 5c6e7b5..66d65fc 100644 --- a/afk/include/components/Sprite.h +++ b/afk/include/components/Sprite.h @@ -11,13 +11,13 @@ #ifndef AFK_SPRITE_H #define AFK_SPRITE_H -#include +#include "../assets/Texture.h" namespace afk { struct Sprite { /// Texture of Sprite - std::string texture; + Texture texture; }; } // namespace afk diff --git a/afk/include/entities/Entity.h b/afk/include/entities/Entity.h index 1e992e0..91360f6 100644 --- a/afk/include/entities/Entity.h +++ b/afk/include/entities/Entity.h @@ -11,7 +11,7 @@ #ifndef AFK_ENTITY_H #define AFK_ENTITY_H -#include "../../lib/entt/src/entt/entt.hpp" +#include namespace afk { diff --git a/afk/include/scene/Scene.h b/afk/include/scene/Scene.h index 4a11ae0..c0fb127 100644 --- a/afk/include/scene/Scene.h +++ b/afk/include/scene/Scene.h @@ -19,7 +19,7 @@ #include "../common/Exceptions.h" #include "../components/Transform.h" -#include "../include/entities/Entity.h" +#include "../entities/Entity.h" #include "../services/Services.h" /** diff --git a/afk/include/services/assets/AssetService.h b/afk/include/services/assets/AssetService.h index f8b5134..41574f7 100644 --- a/afk/include/services/assets/AssetService.h +++ b/afk/include/services/assets/AssetService.h @@ -90,7 +90,7 @@ class AssetService { * @throws FileIOException Thrown if file can not be loaded * @see getImage */ - void loadImage(const std::string& key, const std::string& path); + const Texture& loadImage(const std::string& key, const std::string& path); /** * @brief Loads an audio file into memory from a given path. Font is assigned @@ -101,7 +101,7 @@ class AssetService { * @throws FileIOException Thrown if file can not be loaded * @see getAudioService */ - void loadAudio(const std::string& key, const std::string& path); + const Sound& loadAudio(const std::string& key, const std::string& path); /** * @brief Loads a font into memory from a given path. Audio file is assigned @@ -113,7 +113,9 @@ class AssetService { * @throws FileIOException Thrown if file can not be loaded * @see getFont */ - void loadFont(const std::string& key, const std::string& path, int size); + const Font& loadFont(const std::string& key, + const std::string& path, + int size); /** * @brief Loads an audio stream into memory from a given path. Stream is @@ -124,7 +126,7 @@ class AssetService { * @throws FileIOException Thrown if file can not be loaded * @see getStream */ - void loadStream(const std::string& key, const std::string& path); + const Stream& loadStream(const std::string& key, const std::string& path); private: /// Container that stores all Sound assets diff --git a/afk/include/systems/RenderSystem.h b/afk/include/systems/RenderSystem.h index 9470595..d980efa 100644 --- a/afk/include/systems/RenderSystem.h +++ b/afk/include/systems/RenderSystem.h @@ -11,7 +11,7 @@ #ifndef AFK_RENDERSYSTEM_H #define AFK_RENDERSYSTEM_H -#include "../../lib/entt/src/entt/entt.hpp" +#include #include "entities/Entity.h" #include "services/assets/AssetService.h" @@ -22,7 +22,7 @@ namespace afk::systems { * @brief RenderSystem * */ -void renderSystem(Registry& registry, AssetService& assetService); +void renderSystem(Registry& registry); } // namespace afk::systems diff --git a/afk/src/assets/Texture.cpp b/afk/src/assets/Texture.cpp index 9ab541f..9b6a3ee 100644 --- a/afk/src/assets/Texture.cpp +++ b/afk/src/assets/Texture.cpp @@ -28,6 +28,7 @@ Texture::Texture(const std::string& path) : texture(nullptr) { // Load texture from file void Texture::load(const std::string& path) { texture = loadTexture(path); + calculateSize(); } // Create texture with specified dimensions @@ -48,17 +49,15 @@ void Texture::create(const int width, const int height) { SDL_FreeSurface(tempSurface); texture = tempTexture; -} -// Return height of loaded texture -int Texture::getHeight() const { - if (!texture) { - return 0; - } + calculateSize(); +} - int h; - SDL_QueryTexture(texture, nullptr, nullptr, nullptr, &h); - return h; +// Calculate size of texture +void Texture::calculateSize() { + int w, h; + SDL_QueryTexture(texture, nullptr, nullptr, &w, &h); + this->size = Vec2(w, h); } // Return if it exists @@ -67,14 +66,8 @@ bool Texture::exists() const { } // Return width of loaded texture -int Texture::getWidth() const { - if (!texture) { - return 0; - } - - int w; - SDL_QueryTexture(texture, nullptr, nullptr, &w, nullptr); - return w; +Vec2 Texture::getSize() { + return size; } // Draw texture to screen @@ -85,7 +78,7 @@ void Texture::draw(const int x, const int y) const { SDL_Renderer* renderer = Services::getDisplayService().getRenderer(); - SDL_Rect target = {x, y, getWidth(), getHeight()}; + SDL_Rect target = {x, y, size.x, size.y}; SDL_RenderCopy(renderer, texture, nullptr, &target); } diff --git a/afk/src/scene/Scene.cpp b/afk/src/scene/Scene.cpp index a34a5ed..8afbf17 100644 --- a/afk/src/scene/Scene.cpp +++ b/afk/src/scene/Scene.cpp @@ -38,7 +38,7 @@ void Scene::update(uint32_t delta) { // Draw internal method void Scene::draw() { // Draw - systems::renderSystem(registry, assets); + systems::renderSystem(registry); systems::uiSystem(registry, assets, input); systems::particleRenderSystem(registry, assets); } diff --git a/afk/src/services/assets/AssetService.cpp b/afk/src/services/assets/AssetService.cpp index febca7f..183ffb9 100644 --- a/afk/src/services/assets/AssetService.cpp +++ b/afk/src/services/assets/AssetService.cpp @@ -37,11 +37,13 @@ AssetService::AssetService() { } // Load image from disk and assign key -void AssetService::loadImage(const std::string& key, const std::string& path) { +const Texture& AssetService::loadImage(const std::string& key, + const std::string& path) { Services::getLoggingService().log("[Asset Manager] Loading image: " + key); try { loadedImage[key] = Texture(path); + return loadedImage[key]; } catch (const std::runtime_error& e) { throw FileIoException(e.what()); } catch (...) { @@ -50,11 +52,13 @@ void AssetService::loadImage(const std::string& key, const std::string& path) { } // Load audio from disk and assign key -void AssetService::loadAudio(const std::string& key, const std::string& path) { +const Sound& AssetService::loadAudio(const std::string& key, + const std::string& path) { Services::getLoggingService().log("[Asset Manager] Loading audio: " + key); try { loadedAudio[key] = Sound(path); + return loadedAudio[key]; } catch (const std::runtime_error& e) { throw FileIoException(e.what()); } catch (...) { @@ -63,13 +67,14 @@ void AssetService::loadAudio(const std::string& key, const std::string& path) { } // Load font from disk and assign key -void AssetService::loadFont(const std::string& key, - const std::string& path, - const int size) { +const Font& AssetService::loadFont(const std::string& key, + const std::string& path, + const int size) { Services::getLoggingService().log("[Asset Manager] Loading font: " + key); try { loadedFont[key] = Font(path, size); + return loadedFont[key]; } catch (const std::runtime_error& e) { throw FileIoException(e.what()); } catch (...) { @@ -78,11 +83,13 @@ void AssetService::loadFont(const std::string& key, } // Load stream from disk and assign key -void AssetService::loadStream(const std::string& key, const std::string& path) { +const Stream& AssetService::loadStream(const std::string& key, + const std::string& path) { Services::getLoggingService().log("[Asset Manager] Loading stream: " + key); try { loadedStream[key] = Stream(path); + return loadedStream[key]; } catch (const std::runtime_error& e) { throw FileIoException(e.what()); } catch (...) { diff --git a/afk/src/systems/RenderSystem.cpp b/afk/src/systems/RenderSystem.cpp index ff53522..67bf541 100644 --- a/afk/src/systems/RenderSystem.cpp +++ b/afk/src/systems/RenderSystem.cpp @@ -18,13 +18,12 @@ namespace afk::systems { * @brief RenderSystem * */ -void renderSystem(Registry& registry, AssetService& assetService) { +void renderSystem(Registry& registry) { auto view = registry.view(); for (auto [entity, tran, sprite] : view.each()) { - auto texture = assetService.getImage(sprite.texture); - texture.drawEx(tran.position.x, tran.position.y, tran.size.x, tran.size.y, - tran.angle); + sprite.texture.drawEx(tran.position.x, tran.position.y, tran.size.x, + tran.size.y, tran.angle); } } diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 6e074f5..07f08ad 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,26 +1,21 @@ -cmake_minimum_required(VERSION 3.14) +cmake_minimum_required(VERSION 3.16) project (examples VERSION 1.0.0 LANGUAGES CXX ) -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) - -include(${EXTERNAL_DIR}/libs.cmake) - # Config set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(EXAMPLES ex_display ex_sprite ex_rotate ex_fps ex_mouse ex_physics ex_sound ex_particles ex_keyboard ex_collision ex_message_box) - + # Build examples foreach(EX_NAME ${EXAMPLES}) add_executable(${EX_NAME} ${CMAKE_CURRENT_LIST_DIR}/src/${EX_NAME}.cpp) target_compile_options(${EX_NAME} - PRIVATE + PRIVATE -Wall -Wextra -pedantic @@ -31,39 +26,21 @@ foreach(EX_NAME ${EXAMPLES}) if(EMSCRIPTEN) set(CMAKE_EXECUTABLE_SUFFIX ".html") - target_compile_options(${EX_NAME} - PUBLIC - -sUSE_SDL=2 - -sUSE_SDL_IMAGE=2 - -sUSE_SDL_TTF=2 - -sUSE_SDL_MIXER=2 - -sUSE_SDL_GFX=2 - ) - - set(SDL_LIBRARIES + set(EXTRA_LIBRARIES "--use-preload-plugins \ --preload-file ${CMAKE_CURRENT_LIST_DIR}/assets@/assets \ -s DISABLE_EXCEPTION_CATCHING=0 \ -s DEMANGLE_SUPPORT=1 \ - -s USE_SDL=2 \ - -s USE_SDL_IMAGE=2 \ - -s USE_SDL_TTF=2 \ - -s USE_SDL_MIXER=2 \ - -s USE_SDL_GFX=2 \ -s SDL2_IMAGE_FORMATS=[\"png\"]" ) - - # All other system options - else(EMSCRIPTEN) - set(SDL_LIBRARIES SDL2::Image SDL2::Mixer SDL2::TTF SDL2::GFX SDL2::Main) endif(EMSCRIPTEN) - # Link libraries + # Link libraries if(MINGW) target_link_libraries(${EX_NAME} PRIVATE -lmingw32) endif(MINGW) - - target_link_libraries(${EX_NAME} PRIVATE ${SDL_LIBRARIES} imported::entt afk) + + target_link_libraries(${EX_NAME} PRIVATE ${EXTRA_LIBRARIES} afk) endforeach() # Export assets diff --git a/examples/src/ex_collision.cpp b/examples/src/ex_collision.cpp index 18f0238..b396ff4 100644 --- a/examples/src/ex_collision.cpp +++ b/examples/src/ex_collision.cpp @@ -24,19 +24,19 @@ class DemoScene : public afk::Scene { display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_collision"); - assets.loadImage("lenna", "assets/lenna.png"); + auto& lennaTexture = assets.loadImage("lenna", "assets/lenna.png"); assets.loadFont("freesans", "assets/freesans.ttf", 12); lennaEntity1 = createEntity(); createComponent(lennaEntity1, afk::Vec3(10, 10, 0), afk::Vec2(40, 40)); - createComponent(lennaEntity1, "lenna"); + createComponent(lennaEntity1, lennaTexture); createComponent(lennaEntity1); lennaEntity2 = createEntity(); createComponent(lennaEntity2, afk::Vec3(10, 80, 0), afk::Vec2(40, 40)); - createComponent(lennaEntity2, "lenna"); + createComponent(lennaEntity2, lennaTexture); createComponent(lennaEntity2); labelEntity = createEntity(); diff --git a/examples/src/ex_fps.cpp b/examples/src/ex_fps.cpp index 7c6f503..a5aa457 100644 --- a/examples/src/ex_fps.cpp +++ b/examples/src/ex_fps.cpp @@ -33,7 +33,7 @@ class DemoScene : public afk::Scene { display.setTitle("ex_fps"); assets.loadFont("freesans", "assets/freesans.ttf", 64); - assets.loadImage("lenna", "assets/lenna.png"); + auto& lennaTexture = assets.loadImage("lenna", "assets/lenna.png"); labelEntity = createEntity(); createComponent(labelEntity, afk::Vec3(10, 5, 0)); @@ -42,7 +42,7 @@ class DemoScene : public afk::Scene { for (auto& sprite : sprites) { auto entity = createEntity(); - createComponent(entity, "lenna"); + createComponent(entity, lennaTexture); auto& transform = createComponent(entity); transform.size.x = SPRITE_SIZE; transform.size.y = SPRITE_SIZE; diff --git a/examples/src/ex_keyboard.cpp b/examples/src/ex_keyboard.cpp index 055828e..ff2c667 100644 --- a/examples/src/ex_keyboard.cpp +++ b/examples/src/ex_keyboard.cpp @@ -53,7 +53,9 @@ class DemoScene : public afk::Scene { afk::Entity id = createEntity(); createComponent(id, afk::Vec3(100, 100, 0), afk::Vec2(40, 40)); - createComponent(id, "lenna"); + + auto& lennaTexture = assets.getImage("lenna"); + createComponent(id, lennaTexture); entityIds.push_back(id); } diff --git a/examples/src/ex_mouse.cpp b/examples/src/ex_mouse.cpp index e432785..3f665c6 100644 --- a/examples/src/ex_mouse.cpp +++ b/examples/src/ex_mouse.cpp @@ -23,10 +23,10 @@ class DemoScene : public afk::Scene { display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_mouse"); - assets.loadImage("lenna", "assets/lenna.png"); + auto& lennaTexture = assets.loadImage("lenna", "assets/lenna.png"); lennaEntity = createEntity(); - createComponent(lennaEntity, "lenna"); + createComponent(lennaEntity, lennaTexture); createComponent(lennaEntity, afk::Vec3(100, 100, 0), afk::Vec2(30, 30)); } diff --git a/examples/src/ex_physics.cpp b/examples/src/ex_physics.cpp index 5035d35..6354f5a 100644 --- a/examples/src/ex_physics.cpp +++ b/examples/src/ex_physics.cpp @@ -43,10 +43,10 @@ class DemoScene : public afk::Scene { display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_physics"); - assets.loadImage("lenna", "assets/lenna.png"); + auto& lennaTexture = assets.loadImage("lenna", "assets/lenna.png"); lennaEntity = createEntity(); - createComponent(lennaEntity, "lenna"); + createComponent(lennaEntity, lennaTexture); createComponent(lennaEntity, afk::Vec3(0, 0, 0), afk::Vec2(40, 40)); createComponent(lennaEntity, afk::Vec2(100.0f, 400.0f)); diff --git a/examples/src/ex_rotate.cpp b/examples/src/ex_rotate.cpp index bc729a6..f40670b 100644 --- a/examples/src/ex_rotate.cpp +++ b/examples/src/ex_rotate.cpp @@ -24,10 +24,10 @@ class DemoScene : public afk::Scene { display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_sprite"); - assets.loadImage("lenna", "assets/lenna.png"); + auto& lennaTexture = assets.loadImage("lenna", "assets/lenna.png"); lennaEntity = createEntity(); - createComponent(lennaEntity, "lenna"); + createComponent(lennaEntity, lennaTexture); createComponent(lennaEntity, afk::Vec3(156, 156, 0), afk::Vec2(200, 200)); } diff --git a/examples/src/ex_sprite.cpp b/examples/src/ex_sprite.cpp index 98d602f..9762186 100644 --- a/examples/src/ex_sprite.cpp +++ b/examples/src/ex_sprite.cpp @@ -23,10 +23,10 @@ class DemoScene : public afk::Scene { display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_sprite"); - assets.loadImage("lenna", "assets/lenna.png"); + auto& lennaTexture = assets.loadImage("lenna", "assets/lenna.png"); auto sprite = createEntity(); - createComponent(sprite, "lenna"); + createComponent(sprite, lennaTexture); createComponent(sprite, afk::Vec3(0, 0, 0), afk::Vec2(50, 50)); } diff --git a/lib/afk-config.cmake b/lib/afk-config.cmake new file mode 100644 index 0000000..39986b3 --- /dev/null +++ b/lib/afk-config.cmake @@ -0,0 +1,4 @@ +# afk-config.cmake - package configuration file + +get_filename_component(SELF_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) +include(${SELF_DIR}/afk.cmake) \ No newline at end of file diff --git a/lib/entt b/lib/entt deleted file mode 160000 index e5172a9..0000000 --- a/lib/entt +++ /dev/null @@ -1 +0,0 @@ -Subproject commit e5172a9240728cc271af7599c6f13580329f3618 diff --git a/lib/libs.cmake b/lib/libs.cmake index a995d15..9ab02c6 100644 --- a/lib/libs.cmake +++ b/lib/libs.cmake @@ -1,5 +1,9 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${EXTERNAL_DIR}/cmake) + +set(EXTERNAL_INCLUDE_DIRS "") +set(EXTERNAL_INCLUDE_LIBS "") + # sdl if (NOT EMSCRIPTEN) find_package(SDL2 REQUIRED) @@ -7,14 +11,18 @@ if (NOT EMSCRIPTEN) find_package(SDL2_image REQUIRED) find_package(SDL2_ttf REQUIRED) find_package(SDL2_gfx REQUIRED) + + list (APPEND EXTERNAL_INCLUDE_LIBS + SDL2::Image + SDL2::Mixer + SDL2::TTF + SDL2::GFX + SDL2::Main + ) + endif(NOT EMSCRIPTEN) # entt -add_library (imported::entt INTERFACE IMPORTED) -set (ENTT_INCLUDE_PATH ${CMAKE_SOURCE_DIR}/lib/entt/single_include) -set_target_properties(imported::entt PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${ENTT_INCLUDE_PATH}") -target_link_libraries(imported::entt INTERFACE EnTT) +find_package(EnTT REQUIRED) -list (APPEND EXTERNAL_INCLUDE_DIRS - ${ENTT_INCLUDE_PATH} -) \ No newline at end of file +list (APPEND EXTERNAL_INCLUDE_LIBS EnTT::EnTT)