From e16fb5be90c889c371cbb0ca2444735c2e12073c Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Sun, 18 Feb 2018 12:35:45 -0500 Subject: Implemented map adjacency This brings along with it the ability to move to different maps, for which the PlayingSystem and PlayableComponent were introduced. The PlayingSystem is a general overseer system that handles big picture stuff like initializing the player and changing maps. The PlayableComponent represents the player. While the ControllableComponent is also likely to always only be on the player entity, the two are distinct by separation of concerns. This also required a refactoring of how collisions are processed, because of a bug where the player can move to a new map when horizontal collisions are checked, and vertical collisions are skipped, causing the player to clip through the ground because the normal force was never handled. --- src/systems/playing.cpp | 98 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 src/systems/playing.cpp (limited to 'src/systems/playing.cpp') diff --git a/src/systems/playing.cpp b/src/systems/playing.cpp new file mode 100644 index 0000000..2c6a419 --- /dev/null +++ b/src/systems/playing.cpp @@ -0,0 +1,98 @@ +#include "playing.h" +#include "game.h" +#include "components/transformable.h" +#include "components/animatable.h" +#include "components/playable.h" +#include "components/controllable.h" +#include "components/orientable.h" +#include "systems/mapping.h" +#include "systems/pondering.h" +#include "animation.h" + +void PlayingSystem::tick(double) +{ + // Check if we need to change the map + auto players = game_.getEntityManager().getEntitiesWithComponents< + PlayableComponent>(); + + for (id_type player : players) + { + auto& playable = game_.getEntityManager(). + getComponent(player); + + if (playable.changingMap) + { + // Change the map! + auto entities = game_.getEntityManager().getEntities(); + + for (id_type entity : entities) + { + if (entity != player) + { + game_.getEntityManager().deleteEntity(entity); + } + } + + game_.getSystemManager().getSystem(). + loadMap(playable.newMapId); + + auto& transformable = game_.getEntityManager(). + getComponent(player); + + transformable.setX(playable.newMapX); + transformable.setY(playable.newMapY); + + playable.changingMap = false; + + break; + } + } +} + +void PlayingSystem::initPlayer() +{ + id_type player = game_.getEntityManager().emplaceEntity(); + + AnimationSet playerGraphics {"res/Starla.png", 10, 12, 6}; + playerGraphics.emplaceAnimation("stillLeft", 3, 1, 1); + playerGraphics.emplaceAnimation("stillRight", 0, 1, 1); + playerGraphics.emplaceAnimation("walkingLeft", 4, 2, 10); + playerGraphics.emplaceAnimation("walkingRight", 1, 2, 10); + + game_.getEntityManager().emplaceComponent( + player, + std::move(playerGraphics), + "stillLeft"); + + game_.getEntityManager().emplaceComponent( + player, + 203, 44, 10, 12); + + game_.getSystemManager().getSystem().initializeBody( + player, + PonderableComponent::Type::freefalling); + + game_.getEntityManager().emplaceComponent(player); + game_.getEntityManager().emplaceComponent(player); + game_.getEntityManager().emplaceComponent(player); +} + +void PlayingSystem::changeMap( + size_t mapId, + double x, + double y) +{ + auto players = game_.getEntityManager().getEntitiesWithComponents< + PlayableComponent>(); + + for (id_type player : players) + { + auto& playable = game_.getEntityManager(). + getComponent(player); + + playable.changingMap = true; + playable.newMapId = mapId; + playable.newMapX = x; + playable.newMapY = y; + } +} -- cgit 1.4.1 From e4e2f2d2a7b6a282b9618aa0004d9453936f43c6 Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Sun, 18 Feb 2018 15:25:52 -0500 Subject: Added player death and event scheduling Also added ability to make sprites flicker, to freeze physics for an entity, and to freeze progression of a sprite's animation loop. --- CMakeLists.txt | 1 + res/maps.xml | 2 +- src/components/animatable.h | 33 +++++++++++++++++ src/components/playable.h | 9 +++++ src/components/ponderable.h | 22 ++++++++++++ src/components/schedulable.h | 21 +++++++++++ src/game.cpp | 2 ++ src/systems/animating.cpp | 19 ++++++++-- src/systems/controlling.cpp | 29 +++++++++++++++ src/systems/controlling.h | 5 +++ src/systems/mapping.cpp | 21 +++++++++++ src/systems/orienting.cpp | 18 ++++------ src/systems/playing.cpp | 85 +++++++++++++++++++++++++++++++++++++++++--- src/systems/playing.h | 9 ++++- src/systems/pondering.cpp | 16 +++++++++ src/systems/scheduling.cpp | 54 ++++++++++++++++++++++++++++ src/systems/scheduling.h | 22 ++++++++++++ 17 files changed, 348 insertions(+), 20 deletions(-) create mode 100644 src/components/schedulable.h create mode 100644 src/systems/scheduling.cpp create mode 100644 src/systems/scheduling.h (limited to 'src/systems/playing.cpp') diff --git a/CMakeLists.txt b/CMakeLists.txt index 155063e..34246ad 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -66,6 +66,7 @@ add_executable(Aromatherapy src/systems/mapping.cpp src/systems/orienting.cpp src/systems/playing.cpp + src/systems/scheduling.cpp ) set_property(TARGET Aromatherapy PROPERTY CXX_STANDARD 11) diff --git a/res/maps.xml b/res/maps.xml index 9d855a2..c561912 100644 --- a/res/maps.xml +++ b/res/maps.xml @@ -1,5 +1,5 @@ -00,0,0,0,0,0,0,0,0,0,19,0,0,0,0,0,20,0,0,0,0,0,0,0,18,9,8,10,8,11,8,10,10,8,11,8,9,10,21,0, +00,0,0,0,0,0,0,0,0,0,19,0,0,0,0,0,20,0,0,0,0,0,0,0,18,9,8,10,8,11,8,10,10,8,11,8,9,10,21,0, 0,0,0,0,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,18,8,8,17,0,0,0,0,0,0,0,0,0,0,0,0,0,22,21, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,18,8,8,8,8,17,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12, 0,19,0,0,0,0,0,0,0,0,0,0,0,18,8,8,17,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12, diff --git a/src/components/animatable.h b/src/components/animatable.h index ed0133e..ec72be0 100644 --- a/src/components/animatable.h +++ b/src/components/animatable.h @@ -51,12 +51,45 @@ public: animation_ = std::move(animation); } + inline bool isFlickering() const + { + return flickering_; + } + + inline void setFlickering(bool v) + { + flickering_ = v; + } + + inline size_t getFlickerTimer() const + { + return flickerTimer_; + } + + inline void setFlickerTimer(size_t v) + { + flickerTimer_ = v; + } + + inline bool isFrozen() const + { + return frozen_; + } + + inline void setFrozen(bool v) + { + frozen_ = v; + } + private: AnimationSet animationSet_; std::string animation_; size_t frame_ = 0; size_t countdown_ = 0; + bool flickering_ = false; + size_t flickerTimer_ = 0; + bool frozen_ = false; }; #endif /* end of include guard: SPRITE_RENDERABLE_H_D3AACBBF */ diff --git a/src/components/playable.h b/src/components/playable.h index a6e71b0..86a7ee7 100644 --- a/src/components/playable.h +++ b/src/components/playable.h @@ -2,14 +2,23 @@ #define PLAYABLE_H_DDC566C3 #include "component.h" +#include class PlayableComponent : public Component { public: + using MapChangeCallback = std::function; + bool changingMap = false; int newMapId = -1; double newMapX = 0; double newMapY = 0; + MapChangeCallback newMapCallback; + + int checkpointMapId = -1; + double checkpointX = 0; + double checkpointY = 0; + }; #endif /* end of include guard: PLAYABLE_H_DDC566C3 */ diff --git a/src/components/ponderable.h b/src/components/ponderable.h index e21cbab..78af25f 100644 --- a/src/components/ponderable.h +++ b/src/components/ponderable.h @@ -70,6 +70,26 @@ public: grounded_ = v; } + inline bool isFrozen() const + { + return frozen_; + } + + inline void setFrozen(bool v) + { + frozen_ = v; + } + + inline bool isCollidable() const + { + return collidable_; + } + + inline void setCollidable(bool v) + { + collidable_ = v; + } + private: double velX_ = 0.0; @@ -78,6 +98,8 @@ private: double accelY_ = 0.0; Type type_ = Type::vacuumed; bool grounded_ = false; + bool frozen_ = false; + bool collidable_ = true; }; #endif /* end of include guard: TANGIBLE_H_746DB3EE */ diff --git a/src/components/schedulable.h b/src/components/schedulable.h new file mode 100644 index 0000000..a92bbba --- /dev/null +++ b/src/components/schedulable.h @@ -0,0 +1,21 @@ +#ifndef SCHEDULABLE_H_1DA3FA2A +#define SCHEDULABLE_H_1DA3FA2A + +#include "component.h" +#include +#include +#include +#include "entity_manager.h" + +class SchedulableComponent : public Component { +public: + + using id_type = EntityManager::id_type; + + using Callback = std::function; + using Action = std::tuple; + + std::list actions; +}; + +#endif /* end of include guard: SCHEDULABLE_H_1DA3FA2A */ diff --git a/src/game.cpp b/src/game.cpp index f245e7c..3da23a3 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -10,6 +10,7 @@ #include "systems/mapping.h" #include "systems/orienting.h" #include "systems/playing.h" +#include "systems/scheduling.h" #include "animation.h" #include "consts.h" @@ -30,6 +31,7 @@ void key_callback(GLFWwindow* window, int key, int, int action, int) Game::Game() : world_("res/maps.xml") { systemManager_.emplaceSystem(*this); + systemManager_.emplaceSystem(*this); systemManager_.emplaceSystem(*this); systemManager_.emplaceSystem(*this); systemManager_.emplaceSystem(*this); diff --git a/src/systems/animating.cpp b/src/systems/animating.cpp index 22224c9..634af67 100644 --- a/src/systems/animating.cpp +++ b/src/systems/animating.cpp @@ -13,7 +13,10 @@ void AnimatingSystem::tick(double) auto& sprite = game_.getEntityManager(). getComponent(entity); - sprite.setCountdown(sprite.getCountdown() + 1); + if (!sprite.isFrozen()) + { + sprite.setCountdown(sprite.getCountdown() + 1); + } const Animation& anim = sprite.getAnimation(); if (sprite.getCountdown() >= anim.getDelay()) @@ -26,6 +29,11 @@ void AnimatingSystem::tick(double) sprite.setFrame(anim.getFirstFrame()); } } + + if (sprite.isFlickering()) + { + sprite.setFlickerTimer((sprite.getFlickerTimer() + 1) % 6); + } } } @@ -44,6 +52,12 @@ void AnimatingSystem::render(Texture& texture) auto& transform = game_.getEntityManager(). getComponent(entity); + double alpha = 1.0; + if (sprite.isFlickering() && (sprite.getFlickerTimer() < 3)) + { + alpha = 0.0; + } + Rectangle dstrect { static_cast(transform.getX()), static_cast(transform.getY()), @@ -55,7 +69,8 @@ void AnimatingSystem::render(Texture& texture) aset.getTexture(), texture, aset.getFrameRect(sprite.getFrame()), - dstrect); + dstrect, + alpha); } } diff --git a/src/systems/controlling.cpp b/src/systems/controlling.cpp index e1609bd..e65c09a 100644 --- a/src/systems/controlling.cpp +++ b/src/systems/controlling.cpp @@ -105,3 +105,32 @@ void ControllingSystem::input(int key, int action) { actions_.push(std::make_pair(key, action)); } + +void ControllingSystem::freeze(id_type entity) +{ + auto& controllable = game_.getEntityManager(). + getComponent(entity); + + controllable.setFrozen(true); +} + +void ControllingSystem::unfreeze(id_type entity) +{ + auto& controllable = game_.getEntityManager(). + getComponent(entity); + + if (controllable.isFrozen()) + { + controllable.setFrozen(false); + + auto& orienting = game_.getSystemManager().getSystem(); + + if (controllable.isHoldingLeft()) + { + orienting.moveLeft(entity); + } else if (controllable.isHoldingRight()) + { + orienting.moveRight(entity); + } + } +} diff --git a/src/systems/controlling.h b/src/systems/controlling.h index 01ed7a0..d6f0789 100644 --- a/src/systems/controlling.h +++ b/src/systems/controlling.h @@ -12,8 +12,13 @@ public: } void tick(double dt); + void input(int key, int action); + void freeze(id_type entity); + + void unfreeze(id_type entity); + private: std::queue> actions_; diff --git a/src/systems/mapping.cpp b/src/systems/mapping.cpp index 05167c1..a3a17ec 100644 --- a/src/systems/mapping.cpp +++ b/src/systems/mapping.cpp @@ -166,12 +166,33 @@ void MappingSystem::loadMap(size_t mapId) MappableComponent::Boundary::Type::wall); } else if (tile == 42) { + addBoundary( + mappable.getRightBoundaries(), + x * TILE_WIDTH, + y * TILE_HEIGHT, + (y+1) * TILE_HEIGHT, + MappableComponent::Boundary::Type::danger); + + addBoundary( + mappable.getLeftBoundaries(), + (x+1) * TILE_WIDTH, + y * TILE_HEIGHT, + (y+1) * TILE_HEIGHT, + MappableComponent::Boundary::Type::danger); + addBoundary( mappable.getDownBoundaries(), y * TILE_HEIGHT, x * TILE_WIDTH, (x+1) * TILE_WIDTH, MappableComponent::Boundary::Type::danger); + + addBoundary( + mappable.getUpBoundaries(), + (y+1) * TILE_HEIGHT, + x * TILE_WIDTH, + (x+1) * TILE_WIDTH, + MappableComponent::Boundary::Type::danger); } } } diff --git a/src/systems/orienting.cpp b/src/systems/orienting.cpp index 187bebc..2df8f87 100644 --- a/src/systems/orienting.cpp +++ b/src/systems/orienting.cpp @@ -93,24 +93,18 @@ void OrientingSystem::moveRight(id_type entity) void OrientingSystem::stopWalking(id_type entity) { - auto& ponderable = game_.getEntityManager(). - getComponent(entity); - auto& orientable = game_.getEntityManager(). getComponent(entity); orientable.setWalkState(OrientableComponent::WalkState::still); - if (ponderable.isGrounded()) - { - auto& animating = game_.getSystemManager().getSystem(); + auto& animating = game_.getSystemManager().getSystem(); - if (orientable.isFacingRight()) - { - animating.startAnimation(entity, "stillRight"); - } else { - animating.startAnimation(entity, "stillLeft"); - } + if (orientable.isFacingRight()) + { + animating.startAnimation(entity, "stillRight"); + } else { + animating.startAnimation(entity, "stillLeft"); } } diff --git a/src/systems/playing.cpp b/src/systems/playing.cpp index 2c6a419..40d9706 100644 --- a/src/systems/playing.cpp +++ b/src/systems/playing.cpp @@ -7,13 +7,18 @@ #include "components/orientable.h" #include "systems/mapping.h" #include "systems/pondering.h" +#include "systems/orienting.h" +#include "systems/scheduling.h" +#include "systems/controlling.h" #include "animation.h" +#include "muxer.h" void PlayingSystem::tick(double) { // Check if we need to change the map auto players = game_.getEntityManager().getEntitiesWithComponents< - PlayableComponent>(); + PlayableComponent, + TransformableComponent>(); for (id_type player : players) { @@ -44,6 +49,12 @@ void PlayingSystem::tick(double) playable.changingMap = false; + if (playable.newMapCallback) + { + playable.newMapCallback(); + playable.newMapCallback = nullptr; + } + break; } } @@ -66,7 +77,10 @@ void PlayingSystem::initPlayer() game_.getEntityManager().emplaceComponent( player, - 203, 44, 10, 12); + game_.getWorld().getStartingX(), + game_.getWorld().getStartingY(), + 10, + 12); game_.getSystemManager().getSystem().initializeBody( player, @@ -74,13 +88,20 @@ void PlayingSystem::initPlayer() game_.getEntityManager().emplaceComponent(player); game_.getEntityManager().emplaceComponent(player); - game_.getEntityManager().emplaceComponent(player); + + auto& playable = game_.getEntityManager(). + emplaceComponent(player); + + playable.checkpointMapId = game_.getWorld().getStartingMapId(); + playable.checkpointX = game_.getWorld().getStartingX(); + playable.checkpointY = game_.getWorld().getStartingY(); } void PlayingSystem::changeMap( size_t mapId, double x, - double y) + double y, + PlayableComponent::MapChangeCallback callback) { auto players = game_.getEntityManager().getEntitiesWithComponents< PlayableComponent>(); @@ -94,5 +115,61 @@ void PlayingSystem::changeMap( playable.newMapId = mapId; playable.newMapX = x; playable.newMapY = y; + playable.newMapCallback = std::move(callback); + } +} + +void PlayingSystem::die() +{ + playSound("res/Hit_Hurt5.wav", 0.25); + + auto players = game_.getEntityManager().getEntitiesWithComponents< + OrientableComponent, + ControllableComponent, + AnimatableComponent, + PonderableComponent, + PlayableComponent>(); + + for (id_type player : players) + { + auto& animatable = game_.getEntityManager(). + getComponent(player); + + auto& ponderable = game_.getEntityManager(). + getComponent(player); + + auto& controlling = game_.getSystemManager().getSystem(); + controlling.freeze(player); + + animatable.setFrozen(true); + animatable.setFlickering(true); + ponderable.setFrozen(true); + ponderable.setCollidable(false); + + auto& scheduling = game_.getSystemManager().getSystem(); + + scheduling.schedule(player, 0.75, [&] (id_type player) { + auto& playable = game_.getEntityManager(). + getComponent(player); + + changeMap( + playable.checkpointMapId, + playable.checkpointX, + playable.checkpointY, + [&, player] () { + animatable.setFrozen(false); + animatable.setFlickering(false); + ponderable.setFrozen(false); + ponderable.setCollidable(true); + + // Reset the walk state, and then potentially let the + // ControllingSystem set it again. + auto& orienting = game_.getSystemManager(). + getSystem(); + orienting.stopWalking(player); + + controlling.unfreeze(player); + }); + }); } } diff --git a/src/systems/playing.h b/src/systems/playing.h index c98a464..ff16808 100644 --- a/src/systems/playing.h +++ b/src/systems/playing.h @@ -2,6 +2,7 @@ #define PLAYING_H_70A54F7D #include "system.h" +#include "components/playable.h" class PlayingSystem : public System { public: @@ -14,7 +15,13 @@ public: void initPlayer(); - void changeMap(size_t mapId, double x, double y); + void changeMap( + size_t mapId, + double x, + double y, + PlayableComponent::MapChangeCallback callback = nullptr); + + void die(); }; diff --git a/src/systems/pondering.cpp b/src/systems/pondering.cpp index 2490dc9..d3601ac 100644 --- a/src/systems/pondering.cpp +++ b/src/systems/pondering.cpp @@ -27,6 +27,11 @@ void PonderingSystem::tick(double dt) auto& ponderable = game_.getEntityManager(). getComponent(entity); + if (ponderable.isFrozen()) + { + continue; + } + // Accelerate ponderable.setVelocityX( ponderable.getVelocityX() + ponderable.getAccelX() * dt); @@ -289,6 +294,17 @@ void PonderingSystem::tick(double dt) break; } } + + break; + } + + case Collision::Type::danger: + { + game_.getSystemManager().getSystem().die(); + + stopProcessing = true; + + break; } default: diff --git a/src/systems/scheduling.cpp b/src/systems/scheduling.cpp new file mode 100644 index 0000000..220efae --- /dev/null +++ b/src/systems/scheduling.cpp @@ -0,0 +1,54 @@ +#include "scheduling.h" +#include "game.h" +#include "components/schedulable.h" +#include "util.h" + +void SchedulingSystem::tick(double dt) +{ + auto entities = game_.getEntityManager().getEntitiesWithComponents< + SchedulableComponent>(); + + for (id_type entity : entities) + { + auto& schedulable = game_.getEntityManager(). + getComponent(entity); + + for (auto& action : schedulable.actions) + { + std::get<0>(action) -= dt; + + if (std::get<0>(action) < 0) + { + std::get<1>(action)(entity); + } + } + + erase_if(schedulable.actions, + [] (const SchedulableComponent::Action& action) { + return (std::get<0>(action) < 0); + }); + + if (schedulable.actions.empty()) + { + game_.getEntityManager().removeComponent(entity); + } + } +} + +void SchedulingSystem::schedule( + id_type entity, + double length, + std::function action) +{ + if (!game_.getEntityManager().hasComponent(entity)) + { + game_.getEntityManager().emplaceComponent(entity); + } + + auto& schedulable = game_.getEntityManager(). + getComponent(entity); + + schedulable.actions.emplace_back( + length, + std::move(action)); +} diff --git a/src/systems/scheduling.h b/src/systems/scheduling.h new file mode 100644 index 0000000..7950d62 --- /dev/null +++ b/src/systems/scheduling.h @@ -0,0 +1,22 @@ +#ifndef SCHEDULING_H_7B02E3E3 +#define SCHEDULING_H_7B02E3E3 + +#include "system.h" + +class SchedulingSystem : public System { +public: + + SchedulingSystem(Game& game) : System(game) + { + } + + void tick(double dt); + + void schedule( + id_type entity, + double length, + std::function action); + +}; + +#endif /* end of include guard: SCHEDULING_H_7B02E3E3 */ -- cgit 1.4.1 From 8016a7146fec3f6f43ca05723441750e5aae3d4d Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Sat, 28 Apr 2018 09:22:44 -0400 Subject: Restructured the way the world is loaded The World class was removed and replaced by the RealizingSystem and RealizableComponent. The realizable entity is intended to be a singleton and to represent the world. The Map class was also removed and integrated into the MappableComponent. These changes are to facilitate implementation of map objects without needing special intermediary objects (including the Map class). Now, map entities are created as soon as the world is created, and map object entities will be as well. They will simply be deactivated while the map is not active. Multiple players are now slightly better supported, which will be important in the future. This will likely become inefficient as the world becomes bigger, and some sort of sector-loading process will have to be designed. This also reduces the usefulness of EntityManager's entity-searching capabilities (which are not the most efficiently implemented currently anyway), and will likely in the future require some added functionality to better search subsets of entities. A lot of the components were also rewritten to use bare member variables instead of accessor methods, as they never had special functionality and just took up space. These components were also documented. --- CMakeLists.txt | 2 +- src/components/animatable.h | 146 +++++++++-------- src/components/mappable.h | 208 ++++++++++++------------ src/components/playable.h | 28 ++-- src/components/ponderable.h | 151 ++++++++---------- src/components/realizable.h | 67 ++++++++ src/components/transformable.h | 79 +++------ src/game.cpp | 6 +- src/game.h | 7 - src/map.h | 111 ------------- src/systems/animating.cpp | 93 ++++++----- src/systems/animating.h | 2 + src/systems/mapping.cpp | 127 +++++++-------- src/systems/mapping.h | 2 +- src/systems/orienting.cpp | 22 +-- src/systems/playing.cpp | 220 ++++++++++++------------- src/systems/playing.h | 9 +- src/systems/pondering.cpp | 354 +++++++++++++++++++++++------------------ src/systems/pondering.h | 2 + src/systems/realizing.cpp | 321 +++++++++++++++++++++++++++++++++++++ src/systems/realizing.h | 43 +++++ src/world.cpp | 155 ------------------ src/world.h | 41 ----- 23 files changed, 1155 insertions(+), 1041 deletions(-) create mode 100644 src/components/realizable.h delete mode 100644 src/map.h create mode 100644 src/systems/realizing.cpp create mode 100644 src/systems/realizing.h delete mode 100644 src/world.cpp delete mode 100644 src/world.h (limited to 'src/systems/playing.cpp') diff --git a/CMakeLists.txt b/CMakeLists.txt index 34246ad..81365c9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -53,7 +53,6 @@ add_executable(Aromatherapy src/entity_manager.cpp src/game.cpp src/animation.cpp - src/world.cpp src/util.cpp src/collision.cpp src/renderer/renderer.cpp @@ -67,6 +66,7 @@ add_executable(Aromatherapy src/systems/orienting.cpp src/systems/playing.cpp src/systems/scheduling.cpp + src/systems/realizing.cpp ) set_property(TARGET Aromatherapy PROPERTY CXX_STANDARD 11) diff --git a/src/components/animatable.h b/src/components/animatable.h index ec72be0..1a678ba 100644 --- a/src/components/animatable.h +++ b/src/components/animatable.h @@ -8,88 +8,86 @@ class AnimatableComponent : public Component { public: + /** + * Constructor for initializing the animation set, because it is not default + * constructible. + */ AnimatableComponent( - AnimationSet animationSet, - std::string animation) : - animationSet_(std::move(animationSet)), - animation_(std::move(animation)) + AnimationSet animationSet) : + animationSet(std::move(animationSet)) { } - inline size_t getFrame() const - { - return frame_; - } - - inline void setFrame(size_t v) - { - frame_ = v; - } - - inline size_t getCountdown() const - { - return countdown_; - } - - inline void setCountdown(size_t v) - { - countdown_ = v; - } - - inline const AnimationSet& getAnimationSet() const - { - return animationSet_; - } - + /** + * The animation set that this entity will use -- an object describing the + * different animations that can be used to render the entity. + * + * @managed_by RealizingSystem + */ + AnimationSet animationSet; + + /** + * The name of the currently active animation. + * + * @managed_by AnimatingSystem + */ + std::string animation; + + /** + * For prototypes, the name of the original animation. + * + * @managed_by RealizingSystem + */ + std::string origAnimation; + + /** + * Helper method for accessing the currently active animation. + */ inline const Animation& getAnimation() const { - return animationSet_.getAnimation(animation_); + return animationSet.getAnimation(animation); } - inline void setAnimation(std::string animation) - { - animation_ = std::move(animation); - } - - inline bool isFlickering() const - { - return flickering_; - } - - inline void setFlickering(bool v) - { - flickering_ = v; - } - - inline size_t getFlickerTimer() const - { - return flickerTimer_; - } - - inline void setFlickerTimer(size_t v) - { - flickerTimer_ = v; - } - - inline bool isFrozen() const - { - return frozen_; - } - - inline void setFrozen(bool v) - { - frozen_ = v; - } - -private: - - AnimationSet animationSet_; - std::string animation_; - size_t frame_ = 0; - size_t countdown_ = 0; - bool flickering_ = false; - size_t flickerTimer_ = 0; - bool frozen_ = false; + /** + * The frame of animation that is currently being rendered. + * + * @managed_by AnimatingSystem + */ + size_t frame = 0; + + /** + * The amount of time (in game frames) before the animation is advanced. + * + * @managed_by AnimatingSystem + */ + size_t countdown = 0; + + /** + * This option allows to give the sprite a "flickering" effect (as in, it is + * not rendered in some frames). + */ + bool flickering = false; + + /** + * Used for the flickering effect. + * + * @managed_by AnimatingSystem + */ + size_t flickerTimer = 0; + + /** + * If enabled, this will prevent the sprite's animation from progressing (but + * will not affect things such as placement on screen and flickering). + */ + bool frozen = false; + + /** + * If this flag is disabled, the entity will be ignored by the animating + * system. + * + * @managed_by RealizingSystem + */ + bool active = false; }; #endif /* end of include guard: SPRITE_RENDERABLE_H_D3AACBBF */ diff --git a/src/components/mappable.h b/src/components/mappable.h index 633cdf4..6f3d38e 100644 --- a/src/components/mappable.h +++ b/src/components/mappable.h @@ -2,14 +2,47 @@ #define MAPPABLE_H_0B0316FB #include +#include +#include +#include #include "component.h" #include "renderer/texture.h" #include "collision.h" -#include "map.h" +#include "entity_manager.h" class MappableComponent : public Component { public: + using id_type = EntityManager::id_type; + + /** + * Helper type that stores information about map adjacency. + */ + class Adjacent { + public: + + enum class Type { + wall, + wrap, + warp, + reverse + }; + + Adjacent( + Type type = Type::wall, + size_t mapId = 0) : + type(type), + mapId(mapId) + { + } + + Type type; + size_t mapId; + }; + + /** + * Helper type that stores information about collision boundaries. + */ class Boundary { public: @@ -20,121 +53,100 @@ public: double lower, double upper, Type type) : - axis_(axis), - lower_(lower), - upper_(upper), - type_(type) - { - } - - inline double getAxis() const - { - return axis_; - } - - inline double getLower() const - { - return lower_; - } - - inline double getUpper() const - { - return upper_; - } - - inline Type getType() const + axis(axis), + lower(lower), + upper(upper), + type(type) { - return type_; } - private: - - double axis_; - double lower_; - double upper_; - Type type_; + double axis; + double lower; + double upper; + Type type; }; - MappableComponent( - Texture tileset, - Texture font) : - tileset_(std::move(tileset)), - font_(std::move(font)) - { - } - + /** + * Helper types for efficient storage and lookup of collision boundaries. + */ using asc_boundaries_type = std::multimap< double, - Boundary, + const Boundary, std::less>; using desc_boundaries_type = std::multimap< double, - Boundary, + const Boundary, std::greater>; - inline size_t getMapId() const - { - return mapId_; - } - - inline void setMapId(size_t v) - { - mapId_ = v; - } - - inline desc_boundaries_type& getLeftBoundaries() - { - return leftBoundaries_; - } - - inline asc_boundaries_type& getRightBoundaries() - { - return rightBoundaries_; - } - - inline desc_boundaries_type& getUpBoundaries() - { - return upBoundaries_; - } - - inline asc_boundaries_type& getDownBoundaries() - { - return downBoundaries_; - } - - inline const Texture& getTileset() const - { - return tileset_; - } - - inline void setTileset(Texture v) - { - tileset_ = std::move(v); - } - - inline const Texture& getFont() const - { - return font_; - } - - inline void setFont(Texture v) + /** + * Constructor for initializing the tileset and font attributes, as they are + * not default constructible. + */ + MappableComponent( + Texture tileset, + Texture font) : + tileset(std::move(tileset)), + font(std::move(font)) { - font_ = std::move(v); } -private: - - size_t mapId_ = -1; - - desc_boundaries_type leftBoundaries_; - asc_boundaries_type rightBoundaries_; - desc_boundaries_type upBoundaries_; - asc_boundaries_type downBoundaries_; - Texture tileset_; - Texture font_; + /** + * The ID of the map in the world definition that this entity represents. + * + * @managed_by RealizingSystem + */ + size_t mapId; + + /** + * The title of the map, which is displayed at the bottom of the screen. + */ + std::string title; + + /** + * The map data. + * + * @managed_by RealizingSystem + */ + std::vector tiles; + + /** + * These objects describe the behavior of the four edges of the map. + * + * @managed_by RealizingSystem + */ + Adjacent leftAdjacent; + Adjacent rightAdjacent; + Adjacent upAdjacent; + Adjacent downAdjacent; + + /** + * Collision boundaries, for detecting when a ponderable entity is colliding + * with the environment. + * + * @managed_by MappingSystem + */ + desc_boundaries_type leftBoundaries; + asc_boundaries_type rightBoundaries; + desc_boundaries_type upBoundaries; + asc_boundaries_type downBoundaries; + + /** + * The list of entities representing the objects owned by the map. + * + * @managed_by RealizingSystem + */ + std::list objects; + + /** + * The tilesets for the map and the map name. + * + * TODO: These probably do not belong here. + */ + Texture tileset; + Texture font; }; #endif /* end of include guard: MAPPABLE_H_0B0316FB */ diff --git a/src/components/playable.h b/src/components/playable.h index 86a7ee7..94d4326 100644 --- a/src/components/playable.h +++ b/src/components/playable.h @@ -2,22 +2,30 @@ #define PLAYABLE_H_DDC566C3 #include "component.h" -#include +#include "entity_manager.h" class PlayableComponent : public Component { public: - using MapChangeCallback = std::function; + using id_type = EntityManager::id_type; - bool changingMap = false; - int newMapId = -1; - double newMapX = 0; - double newMapY = 0; - MapChangeCallback newMapCallback; + /** + * The entity ID of the map that the player is on. + * + * @managed_by PlayingSystem + */ + id_type mapId; - int checkpointMapId = -1; - double checkpointX = 0; - double checkpointY = 0; + /** + * The map ID and coordinates of the location that the player will spawn after + * dying. Note that the map ID here is a world description map ID, not an + * entity ID. + * + * @managed_by PlayingSystem + */ + size_t checkpointMapId; + double checkpointX; + double checkpointY; }; diff --git a/src/components/ponderable.h b/src/components/ponderable.h index 78af25f..fd7e775 100644 --- a/src/components/ponderable.h +++ b/src/components/ponderable.h @@ -6,100 +6,73 @@ class PonderableComponent : public Component { public: + /** + * List of different types of physical bodies. + * + * vacuumed - Default. + * freefalling - The body will be treated as if there were a downward force + * of gravity being exerted onto it. The body will also exhibit + * terminal velocity (that is, its downward velocity will be + * capped at a constant value). + */ enum class Type { vacuumed, freefalling }; - PonderableComponent(Type type) : type_(type) - { - } - - inline Type getType() const - { - return type_; - } - - inline double getVelocityX() const - { - return velX_; - } - - inline void setVelocityX(double v) - { - velX_ = v; - } - - inline double getVelocityY() const - { - return velY_; - } - - inline void setVelocityY(double v) - { - velY_ = v; - } - - inline double getAccelX() const - { - return accelX_; - } - - inline void setAccelX(double v) - { - accelX_ = v; - } - - inline double getAccelY() const - { - return accelY_; - } - - inline void setAccelY(double v) - { - accelY_ = v; - } - - inline bool isGrounded() const - { - return grounded_; - } - - inline void setGrounded(bool v) - { - grounded_ = v; - } - - inline bool isFrozen() const - { - return frozen_; - } - - inline void setFrozen(bool v) - { - frozen_ = v; - } - - inline bool isCollidable() const - { - return collidable_; - } - - inline void setCollidable(bool v) - { - collidable_ = v; - } - -private: - - double velX_ = 0.0; - double velY_ = 0.0; - double accelX_ = 0.0; - double accelY_ = 0.0; - Type type_ = Type::vacuumed; - bool grounded_ = false; - bool frozen_ = false; - bool collidable_ = true; + /** + * Constructor for initializing the body type, which is a constant. + */ + PonderableComponent(Type type) : type(type) + { + } + + /** + * The velocity of the body. + */ + double velX = 0.0; + double velY = 0.0; + + /** + * The acceleration of the body. + */ + double accelX = 0.0; + double accelY = 0.0; + + /** + * The type of physical body that the entity is meant to assume. The body will + * be acted upon differently based on this. See the enumeration above for more + * details. + * + * @managed_by PonderingSystem + */ + const Type type; + + /** + * Whether or not a freefalling body is in contact with the ground. + * + * @managed_by PonderingSystem + */ + bool grounded = false; + + /** + * If enabled, this will prevent the body from moving. + */ + bool frozen = false; + + /** + * If disabled, collision detection for this body will not be performed and + * other bodies will ignore it. + */ + bool collidable = true; + + /** + * If this flag is disabled, the entity will be ignored by the pondering + * system. + * + * @managed_by RealizingSystem + */ + bool active = false; }; #endif /* end of include guard: TANGIBLE_H_746DB3EE */ diff --git a/src/components/realizable.h b/src/components/realizable.h new file mode 100644 index 0000000..f6a7eb4 --- /dev/null +++ b/src/components/realizable.h @@ -0,0 +1,67 @@ +#ifndef REALIZABLE_H_36D8D71E +#define REALIZABLE_H_36D8D71E + +#include "component.h" +#include +#include +#include "entity_manager.h" + +class RealizableComponent : public Component { +public: + + using id_type = EntityManager::id_type; + + /** + * Path to the XML file containing the world definition. + * + * @managed_by RealizingSystem + */ + std::string worldFile; + + /** + * Starting map and player location for a new game. + * + * @managed_by RealizingSystem + */ + int startingMapId; + int startingX; + int startingY; + + /** + * The set of map entities loaded by this entity. It is only intended for + * there to be one realizable entity, so this should contain all loaded maps. + * The realizable entity has ownership of the loaded maps. + * + * @managed_by RealizingSystem + */ + std::set maps; + + /** + * A lookup table that translates a map ID to the entity representing that + * loaded map. + * + * @managed_by RealizingSystem + */ + std::map entityByMapId; + + /** + * The entity ID of the currently active map. + * + * @managed_by RealizingSystem + */ + id_type activeMap; + + /** + * Whether or not a map has been activated yet. + * + * @managed_by RealizingSystem + */ + bool hasActiveMap = false; + + /** + * The entity ID of the currently active player. + */ + id_type activePlayer; +}; + +#endif /* end of include guard: REALIZABLE_H_36D8D71E */ diff --git a/src/components/transformable.h b/src/components/transformable.h index 6ed2637..3296e49 100644 --- a/src/components/transformable.h +++ b/src/components/transformable.h @@ -6,64 +6,27 @@ class TransformableComponent : public Component { public: - TransformableComponent( - double x, - double y, - int w, - int h) : - x_(x), - y_(y), - w_(w), - h_(h) - { - } - - inline double getX() const - { - return x_; - } - - inline void setX(double v) - { - x_ = v; - } - - inline double getY() const - { - return y_; - } - - inline void setY(double v) - { - y_ = v; - } - - inline int getW() const - { - return w_; - } - - inline void setW(int v) - { - w_ = v; - } - - inline int getH() const - { - return h_; - } - - inline void setH(int v) - { - h_ = v; - } - -private: - - double x_; - double y_; - int w_; - int h_; + /** + * The coordinates of the entity. + */ + double x; + double y; + + /** + * The size of the entity. + */ + int w; + int h; + + /** + * For prototypes, the original coordinates and size of the entity. + * + * @managed_by RealizingSystem + */ + double origX; + double origY; + int origW; + int origH; }; #endif /* end of include guard: LOCATABLE_H_39E526CA */ diff --git a/src/game.cpp b/src/game.cpp index 3da23a3..b7dd200 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -11,6 +11,7 @@ #include "systems/orienting.h" #include "systems/playing.h" #include "systems/scheduling.h" +#include "systems/realizing.h" #include "animation.h" #include "consts.h" @@ -28,8 +29,9 @@ void key_callback(GLFWwindow* window, int key, int, int action, int) game.systemManager_.input(key, action); } -Game::Game() : world_("res/maps.xml") +Game::Game() { + systemManager_.emplaceSystem(*this); systemManager_.emplaceSystem(*this); systemManager_.emplaceSystem(*this); systemManager_.emplaceSystem(*this); @@ -38,8 +40,8 @@ Game::Game() : world_("res/maps.xml") systemManager_.emplaceSystem(*this); systemManager_.emplaceSystem(*this); + systemManager_.getSystem().initSingleton("res/maps.xml"); systemManager_.getSystem().initPlayer(); - systemManager_.getSystem().loadMap(world_.getStartingMapId()); glfwSwapInterval(1); glfwSetWindowUserPointer(renderer_.getWindow().getHandle(), this); diff --git a/src/game.h b/src/game.h index 43e08da..92a67d9 100644 --- a/src/game.h +++ b/src/game.h @@ -3,7 +3,6 @@ #include "entity_manager.h" #include "system_manager.h" -#include "world.h" #include "renderer/renderer.h" class Game { @@ -28,11 +27,6 @@ public: return systemManager_; } - inline const World& getWorld() - { - return world_; - } - friend void key_callback( GLFWwindow* window, int key, @@ -45,7 +39,6 @@ private: Renderer renderer_; EntityManager entityManager_; SystemManager systemManager_; - World world_; bool shouldQuit_ = false; }; diff --git a/src/map.h b/src/map.h deleted file mode 100644 index 6fe1e62..0000000 --- a/src/map.h +++ /dev/null @@ -1,111 +0,0 @@ -#ifndef MAP_H_74055FC0 -#define MAP_H_74055FC0 - -#include -#include -#include -#include -#include - -class Map { -public: - - class Adjacent { - public: - - enum class Type { - wall, - wrap, - warp, - reverse - }; - - Adjacent( - Type type = Type::wall, - int mapId = -1) : - type_(type), - mapId_(mapId) - { - } - - inline Type getType() const - { - return type_; - } - - inline int getMapId() const - { - return mapId_; - } - - private: - - Type type_; - int mapId_; - }; - - Map( - int id, - std::vector tiles, - std::string title, - Adjacent leftAdjacent, - Adjacent rightAdjacent, - Adjacent upAdjacent, - Adjacent downAdjacent) : - id_(id), - tiles_(std::move(tiles)), - title_(std::move(title)), - leftAdjacent_(std::move(leftAdjacent)), - rightAdjacent_(std::move(rightAdjacent)), - upAdjacent_(std::move(upAdjacent)), - downAdjacent_(std::move(downAdjacent)) - { - } - - inline size_t getId() const - { - return id_; - } - - inline const std::vector& getTiles() const - { - return tiles_; - } - - inline const std::string& getTitle() const - { - return title_; - } - - inline const Adjacent& getLeftAdjacent() const - { - return leftAdjacent_; - } - - inline const Adjacent& getRightAdjacent() const - { - return rightAdjacent_; - } - - inline const Adjacent& getUpAdjacent() const - { - return upAdjacent_; - } - - inline const Adjacent& getDownAdjacent() const - { - return downAdjacent_; - } - -private: - - int id_; - std::vector tiles_; - std::string title_; - Adjacent leftAdjacent_; - Adjacent rightAdjacent_; - Adjacent upAdjacent_; - Adjacent downAdjacent_; -}; - -#endif /* end of include guard: MAP_H_74055FC0 */ diff --git a/src/systems/animating.cpp b/src/systems/animating.cpp index 634af67..8543ba2 100644 --- a/src/systems/animating.cpp +++ b/src/systems/animating.cpp @@ -13,26 +13,29 @@ void AnimatingSystem::tick(double) auto& sprite = game_.getEntityManager(). getComponent(entity); - if (!sprite.isFrozen()) + if (sprite.active) { - sprite.setCountdown(sprite.getCountdown() + 1); - } - - const Animation& anim = sprite.getAnimation(); - if (sprite.getCountdown() >= anim.getDelay()) - { - sprite.setFrame(sprite.getFrame() + 1); - sprite.setCountdown(0); + if (!sprite.frozen) + { + sprite.countdown++; + } - if (sprite.getFrame() >= anim.getFirstFrame() + anim.getNumFrames()) + const Animation& anim = sprite.getAnimation(); + if (sprite.countdown >= anim.getDelay()) { - sprite.setFrame(anim.getFirstFrame()); + sprite.frame++; + sprite.countdown = 0; + + if (sprite.frame >= anim.getFirstFrame() + anim.getNumFrames()) + { + sprite.frame = anim.getFirstFrame(); + } } - } - if (sprite.isFlickering()) - { - sprite.setFlickerTimer((sprite.getFlickerTimer() + 1) % 6); + if (sprite.flickering) + { + sprite.flickerTimer = (sprite.flickerTimer + 1) % 6; + } } } } @@ -49,36 +52,52 @@ void AnimatingSystem::render(Texture& texture) auto& sprite = game_.getEntityManager(). getComponent(entity); - auto& transform = game_.getEntityManager(). - getComponent(entity); - - double alpha = 1.0; - if (sprite.isFlickering() && (sprite.getFlickerTimer() < 3)) + if (sprite.active) { - alpha = 0.0; - } + auto& transform = game_.getEntityManager(). + getComponent(entity); - Rectangle dstrect { - static_cast(transform.getX()), - static_cast(transform.getY()), - transform.getW(), - transform.getH()}; - - const AnimationSet& aset = sprite.getAnimationSet(); - game_.getRenderer().blit( - aset.getTexture(), - texture, - aset.getFrameRect(sprite.getFrame()), - dstrect, - alpha); + double alpha = 1.0; + if (sprite.flickering && (sprite.flickerTimer < 3)) + { + alpha = 0.0; + } + + Rectangle dstrect { + static_cast(transform.x), + static_cast(transform.y), + transform.w, + transform.h}; + + const AnimationSet& aset = sprite.animationSet; + game_.getRenderer().blit( + aset.getTexture(), + texture, + aset.getFrameRect(sprite.frame), + dstrect, + alpha); + } } } +void AnimatingSystem::initPrototype(id_type entity) +{ + auto& sprite = game_.getEntityManager(). + getComponent(entity); + + startAnimation(entity, sprite.origAnimation); + + sprite.countdown = 0; + sprite.flickering = false; + sprite.flickerTimer = 0; + sprite.frozen = false; +} + void AnimatingSystem::startAnimation(id_type entity, std::string animation) { auto& sprite = game_.getEntityManager(). getComponent(entity); - sprite.setAnimation(animation); - sprite.setFrame(sprite.getAnimation().getFirstFrame()); + sprite.animation = std::move(animation); + sprite.frame = sprite.getAnimation().getFirstFrame(); } diff --git a/src/systems/animating.h b/src/systems/animating.h index 548bff1..acc6191 100644 --- a/src/systems/animating.h +++ b/src/systems/animating.h @@ -16,6 +16,8 @@ public: void render(Texture& texture); + void initPrototype(id_type entity); + void startAnimation(id_type entity, std::string animation); }; diff --git a/src/systems/mapping.cpp b/src/systems/mapping.cpp index a3a17ec..af67aed 100644 --- a/src/systems/mapping.cpp +++ b/src/systems/mapping.cpp @@ -1,5 +1,7 @@ #include "mapping.h" #include "components/mappable.h" +#include "components/realizable.h" +#include "systems/realizing.h" #include "game.h" #include "consts.h" @@ -18,104 +20,95 @@ inline void addBoundary( void MappingSystem::render(Texture& texture) { - auto entities = game_.getEntityManager().getEntitiesWithComponents< - MappableComponent>(); + auto& realizable = game_.getEntityManager(). + getComponent( + game_.getSystemManager().getSystem().getSingleton()); - for (id_type entity : entities) - { - auto& mappable = game_.getEntityManager(). - getComponent(entity); + id_type map = realizable.activeMap; - const Map& map = game_.getWorld().getMap(mappable.getMapId()); + auto& mappable = game_.getEntityManager(). + getComponent(map); - for (int i = 0; i < MAP_WIDTH * MAP_HEIGHT; i++) - { - int x = i % MAP_WIDTH; - int y = i / MAP_WIDTH; - int tile = map.getTiles()[i]; - - if (tile > 0) - { - Rectangle dst { - x * TILE_WIDTH, - y * TILE_HEIGHT, - TILE_WIDTH, - TILE_HEIGHT}; - - Rectangle src { - (tile % TILESET_COLS) * TILE_WIDTH, - (tile / TILESET_COLS) * TILE_HEIGHT, - TILE_WIDTH, - TILE_HEIGHT}; - - game_.getRenderer().blit( - mappable.getTileset(), - texture, - std::move(src), - std::move(dst)); - } - } + for (int i = 0; i < MAP_WIDTH * MAP_HEIGHT; i++) + { + int x = i % MAP_WIDTH; + int y = i / MAP_WIDTH; + int tile = mappable.tiles[i]; - int startX = ((GAME_WIDTH / TILE_WIDTH) / 2) - (map.getTitle().size() / 2); - for (size_t i = 0; i < map.getTitle().size(); i++) + if (tile > 0) { - Rectangle src { - (map.getTitle()[i] % FONT_COLS) * TILE_WIDTH, - (map.getTitle()[i] / FONT_COLS) * TILE_HEIGHT, + Rectangle dst { + x * TILE_WIDTH, + y * TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT}; - Rectangle dst { - (startX + static_cast(i)) * TILE_WIDTH, - 24 * TILE_HEIGHT, + Rectangle src { + (tile % TILESET_COLS) * TILE_WIDTH, + (tile / TILESET_COLS) * TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT}; game_.getRenderer().blit( - mappable.getFont(), + mappable.tileset, texture, std::move(src), std::move(dst)); } } + + int startX = ((GAME_WIDTH / TILE_WIDTH) / 2) - (mappable.title.size() / 2); + + for (size_t i = 0; i < mappable.title.size(); i++) + { + Rectangle src { + (mappable.title[i] % FONT_COLS) * TILE_WIDTH, + (mappable.title[i] / FONT_COLS) * TILE_HEIGHT, + TILE_WIDTH, + TILE_HEIGHT}; + + Rectangle dst { + (startX + static_cast(i)) * TILE_WIDTH, + 24 * TILE_HEIGHT, + TILE_WIDTH, + TILE_HEIGHT}; + + game_.getRenderer().blit( + mappable.font, + texture, + std::move(src), + std::move(dst)); + } } -void MappingSystem::loadMap(size_t mapId) +void MappingSystem::generateBoundaries(id_type mapEntity) { - id_type mapEntity = game_.getEntityManager().emplaceEntity(); - auto& mappable = game_.getEntityManager(). - emplaceComponent(mapEntity, - Texture("res/tiles.png"), - Texture("res/font.bmp")); - - mappable.setMapId(mapId); - - const Map& map = game_.getWorld().getMap(mappable.getMapId()); + getComponent(mapEntity); addBoundary( - mappable.getLeftBoundaries(), + mappable.leftBoundaries, -WALL_GAP, 0, MAP_HEIGHT * TILE_HEIGHT, MappableComponent::Boundary::Type::adjacency); addBoundary( - mappable.getRightBoundaries(), + mappable.rightBoundaries, GAME_WIDTH + WALL_GAP, 0, MAP_HEIGHT * TILE_HEIGHT, MappableComponent::Boundary::Type::adjacency); addBoundary( - mappable.getUpBoundaries(), + mappable.upBoundaries, -WALL_GAP, 0, GAME_WIDTH, MappableComponent::Boundary::Type::adjacency); addBoundary( - mappable.getDownBoundaries(), + mappable.downBoundaries, MAP_HEIGHT * TILE_HEIGHT + WALL_GAP, 0, GAME_WIDTH, @@ -125,12 +118,12 @@ void MappingSystem::loadMap(size_t mapId) { size_t x = i % MAP_WIDTH; size_t y = i / MAP_WIDTH; - int tile = map.getTiles()[i]; + int tile = mappable.tiles[i]; if ((tile >= 5) && (tile <= 7)) { addBoundary( - mappable.getDownBoundaries(), + mappable.downBoundaries, y * TILE_HEIGHT, x * TILE_WIDTH, (x + 1) * TILE_WIDTH, @@ -138,28 +131,28 @@ void MappingSystem::loadMap(size_t mapId) } else if ((tile > 0) && (tile < 28)) { addBoundary( - mappable.getRightBoundaries(), + mappable.rightBoundaries, x * TILE_WIDTH, y * TILE_HEIGHT, (y+1) * TILE_HEIGHT, MappableComponent::Boundary::Type::wall); addBoundary( - mappable.getLeftBoundaries(), + mappable.leftBoundaries, (x+1) * TILE_WIDTH, y * TILE_HEIGHT, (y+1) * TILE_HEIGHT, MappableComponent::Boundary::Type::wall); addBoundary( - mappable.getDownBoundaries(), + mappable.downBoundaries, y * TILE_HEIGHT, x * TILE_WIDTH, (x+1) * TILE_WIDTH, MappableComponent::Boundary::Type::wall); addBoundary( - mappable.getUpBoundaries(), + mappable.upBoundaries, (y+1) * TILE_HEIGHT, x * TILE_WIDTH, (x+1) * TILE_WIDTH, @@ -167,28 +160,28 @@ void MappingSystem::loadMap(size_t mapId) } else if (tile == 42) { addBoundary( - mappable.getRightBoundaries(), + mappable.rightBoundaries, x * TILE_WIDTH, y * TILE_HEIGHT, (y+1) * TILE_HEIGHT, MappableComponent::Boundary::Type::danger); addBoundary( - mappable.getLeftBoundaries(), + mappable.leftBoundaries, (x+1) * TILE_WIDTH, y * TILE_HEIGHT, (y+1) * TILE_HEIGHT, MappableComponent::Boundary::Type::danger); addBoundary( - mappable.getDownBoundaries(), + mappable.downBoundaries, y * TILE_HEIGHT, x * TILE_WIDTH, (x+1) * TILE_WIDTH, MappableComponent::Boundary::Type::danger); addBoundary( - mappable.getUpBoundaries(), + mappable.upBoundaries, (y+1) * TILE_HEIGHT, x * TILE_WIDTH, (x+1) * TILE_WIDTH, diff --git a/src/systems/mapping.h b/src/systems/mapping.h index 53d054b..3c47419 100644 --- a/src/systems/mapping.h +++ b/src/systems/mapping.h @@ -12,7 +12,7 @@ public: void render(Texture& texture); - void loadMap(size_t mapId); + void generateBoundaries(id_type mapEntity); }; diff --git a/src/systems/orienting.cpp b/src/systems/orienting.cpp index 2df8f87..206ebf6 100644 --- a/src/systems/orienting.cpp +++ b/src/systems/orienting.cpp @@ -24,27 +24,27 @@ void OrientingSystem::tick(double) { case OrientableComponent::WalkState::still: { - ponderable.setVelocityX(0); + ponderable.velX = 0.0; break; } case OrientableComponent::WalkState::left: { - ponderable.setVelocityX(-WALK_SPEED); + ponderable.velX = -WALK_SPEED; break; } case OrientableComponent::WalkState::right: { - ponderable.setVelocityX(WALK_SPEED); + ponderable.velX = WALK_SPEED; break; } } - if (orientable.isJumping() && (ponderable.getVelocityY() > 0)) + if (orientable.isJumping() && (ponderable.velY > 0)) { orientable.setJumping(false); } @@ -63,7 +63,7 @@ void OrientingSystem::moveLeft(id_type entity) orientable.setWalkState(OrientableComponent::WalkState::left); auto& animating = game_.getSystemManager().getSystem(); - if (ponderable.isGrounded()) + if (ponderable.grounded) { animating.startAnimation(entity, "walkingLeft"); } else { @@ -83,7 +83,7 @@ void OrientingSystem::moveRight(id_type entity) orientable.setWalkState(OrientableComponent::WalkState::right); auto& animating = game_.getSystemManager().getSystem(); - if (ponderable.isGrounded()) + if (ponderable.grounded) { animating.startAnimation(entity, "walkingRight"); } else { @@ -113,7 +113,7 @@ void OrientingSystem::jump(id_type entity) auto& ponderable = game_.getEntityManager(). getComponent(entity); - if (ponderable.isGrounded()) + if (ponderable.grounded) { auto& orientable = game_.getEntityManager(). getComponent(entity); @@ -122,8 +122,8 @@ void OrientingSystem::jump(id_type entity) playSound("res/Randomize87.wav", 0.25); - ponderable.setVelocityY(JUMP_VELOCITY); - ponderable.setAccelY(JUMP_GRAVITY); + ponderable.velY = JUMP_VELOCITY; + ponderable.accelY = JUMP_GRAVITY; auto& animating = game_.getSystemManager().getSystem(); if (orientable.isFacingRight()) @@ -147,7 +147,7 @@ void OrientingSystem::stopJumping(id_type entity) auto& ponderable = game_.getEntityManager(). getComponent(entity); - ponderable.setAccelY(NORMAL_GRAVITY); + ponderable.accelY = NORMAL_GRAVITY; } } @@ -211,7 +211,7 @@ void OrientingSystem::drop(id_type entity) auto& ponderable = game_.getEntityManager(). getComponent(entity); - if (ponderable.isGrounded() + if (ponderable.grounded && (orientable.getDropState() == OrientableComponent::DropState::none)) { orientable.setDropState(OrientableComponent::DropState::ready); diff --git a/src/systems/playing.cpp b/src/systems/playing.cpp index 40d9706..b04f0cb 100644 --- a/src/systems/playing.cpp +++ b/src/systems/playing.cpp @@ -5,61 +5,17 @@ #include "components/playable.h" #include "components/controllable.h" #include "components/orientable.h" +#include "components/realizable.h" #include "systems/mapping.h" #include "systems/pondering.h" #include "systems/orienting.h" #include "systems/scheduling.h" #include "systems/controlling.h" +#include "systems/animating.h" +#include "systems/realizing.h" #include "animation.h" #include "muxer.h" -void PlayingSystem::tick(double) -{ - // Check if we need to change the map - auto players = game_.getEntityManager().getEntitiesWithComponents< - PlayableComponent, - TransformableComponent>(); - - for (id_type player : players) - { - auto& playable = game_.getEntityManager(). - getComponent(player); - - if (playable.changingMap) - { - // Change the map! - auto entities = game_.getEntityManager().getEntities(); - - for (id_type entity : entities) - { - if (entity != player) - { - game_.getEntityManager().deleteEntity(entity); - } - } - - game_.getSystemManager().getSystem(). - loadMap(playable.newMapId); - - auto& transformable = game_.getEntityManager(). - getComponent(player); - - transformable.setX(playable.newMapX); - transformable.setY(playable.newMapY); - - playable.changingMap = false; - - if (playable.newMapCallback) - { - playable.newMapCallback(); - playable.newMapCallback = nullptr; - } - - break; - } - } -} - void PlayingSystem::initPlayer() { id_type player = game_.getEntityManager().emplaceEntity(); @@ -72,15 +28,24 @@ void PlayingSystem::initPlayer() game_.getEntityManager().emplaceComponent( player, - std::move(playerGraphics), - "stillLeft"); + std::move(playerGraphics)); - game_.getEntityManager().emplaceComponent( + game_.getSystemManager().getSystem().startAnimation( player, - game_.getWorld().getStartingX(), - game_.getWorld().getStartingY(), - 10, - 12); + "stillLeft"); + + auto& realizing = game_.getSystemManager().getSystem(); + + auto& realizable = game_.getEntityManager(). + getComponent(realizing.getSingleton()); + + auto& transformable = game_.getEntityManager(). + emplaceComponent(player); + + transformable.x = realizable.startingX; + transformable.y = realizable.startingY; + transformable.w = 10; + transformable.h = 12; game_.getSystemManager().getSystem().initializeBody( player, @@ -92,84 +57,103 @@ void PlayingSystem::initPlayer() auto& playable = game_.getEntityManager(). emplaceComponent(player); - playable.checkpointMapId = game_.getWorld().getStartingMapId(); - playable.checkpointX = game_.getWorld().getStartingX(); - playable.checkpointY = game_.getWorld().getStartingY(); + playable.mapId = realizable.activeMap; + playable.checkpointMapId = realizable.startingMapId; + playable.checkpointX = realizable.startingX; + playable.checkpointY = realizable.startingY; + + realizing.enterActiveMap(player); + + realizable.activePlayer = player; } void PlayingSystem::changeMap( + id_type player, size_t mapId, double x, - double y, - PlayableComponent::MapChangeCallback callback) + double y) { - auto players = game_.getEntityManager().getEntitiesWithComponents< - PlayableComponent>(); + auto& playable = game_.getEntityManager(). + getComponent(player); - for (id_type player : players) + auto& transformable = game_.getEntityManager(). + getComponent(player); + + auto& animatable = game_.getEntityManager(). + getComponent(player); + + auto& ponderable = game_.getEntityManager(). + getComponent(player); + + auto& realizing = game_.getSystemManager().getSystem(); + + auto& realizable = game_.getEntityManager(). + getComponent(realizing.getSingleton()); + + id_type newMapEntity = realizable.entityByMapId[mapId]; + + if (playable.mapId != newMapEntity) { - auto& playable = game_.getEntityManager(). - getComponent(player); + if (playable.mapId == realizable.activeMap) + { + realizing.leaveActiveMap(player); + } else if (newMapEntity == realizable.activeMap) + { + realizing.enterActiveMap(player); + } - playable.changingMap = true; - playable.newMapId = mapId; - playable.newMapX = x; - playable.newMapY = y; - playable.newMapCallback = std::move(callback); + playable.mapId = newMapEntity; + } + + transformable.x = x; + transformable.y = y; + + if (realizable.activePlayer == player) + { + realizing.loadMap(newMapEntity); } } -void PlayingSystem::die() +void PlayingSystem::die(id_type player) { playSound("res/Hit_Hurt5.wav", 0.25); - auto players = game_.getEntityManager().getEntitiesWithComponents< - OrientableComponent, - ControllableComponent, - AnimatableComponent, - PonderableComponent, - PlayableComponent>(); + auto& animatable = game_.getEntityManager(). + getComponent(player); - for (id_type player : players) - { - auto& animatable = game_.getEntityManager(). - getComponent(player); - - auto& ponderable = game_.getEntityManager(). - getComponent(player); - - auto& controlling = game_.getSystemManager().getSystem(); - controlling.freeze(player); - - animatable.setFrozen(true); - animatable.setFlickering(true); - ponderable.setFrozen(true); - ponderable.setCollidable(false); - - auto& scheduling = game_.getSystemManager().getSystem(); - - scheduling.schedule(player, 0.75, [&] (id_type player) { - auto& playable = game_.getEntityManager(). - getComponent(player); - - changeMap( - playable.checkpointMapId, - playable.checkpointX, - playable.checkpointY, - [&, player] () { - animatable.setFrozen(false); - animatable.setFlickering(false); - ponderable.setFrozen(false); - ponderable.setCollidable(true); - - // Reset the walk state, and then potentially let the - // ControllingSystem set it again. - auto& orienting = game_.getSystemManager(). - getSystem(); - orienting.stopWalking(player); - - controlling.unfreeze(player); - }); - }); - } + auto& ponderable = game_.getEntityManager(). + getComponent(player); + + auto& controlling = game_.getSystemManager().getSystem(); + controlling.freeze(player); + + animatable.frozen = true; + animatable.flickering = true; + ponderable.frozen = true; + ponderable.collidable = false; + + auto& scheduling = game_.getSystemManager().getSystem(); + + scheduling.schedule(player, 0.75, [&] (id_type player) { + auto& playable = game_.getEntityManager(). + getComponent(player); + + changeMap( + player, + playable.checkpointMapId, + playable.checkpointX, + playable.checkpointY); + + animatable.frozen = false; + animatable.flickering = false; + ponderable.frozen = false; + ponderable.collidable = true; + + // Reset the walk state, and then potentially let the + // ControllingSystem set it again. + auto& orienting = game_.getSystemManager().getSystem(); + orienting.stopWalking(player); + + controlling.unfreeze(player); + }); } diff --git a/src/systems/playing.h b/src/systems/playing.h index ff16808..9ba403b 100644 --- a/src/systems/playing.h +++ b/src/systems/playing.h @@ -2,7 +2,6 @@ #define PLAYING_H_70A54F7D #include "system.h" -#include "components/playable.h" class PlayingSystem : public System { public: @@ -11,17 +10,15 @@ public: { } - void tick(double dt); - void initPlayer(); void changeMap( + id_type player, size_t mapId, double x, - double y, - PlayableComponent::MapChangeCallback callback = nullptr); + double y); - void die(); + void die(id_type player); }; diff --git a/src/systems/pondering.cpp b/src/systems/pondering.cpp index 02d5cfc..4ae6176 100644 --- a/src/systems/pondering.cpp +++ b/src/systems/pondering.cpp @@ -5,149 +5,153 @@ #include "components/transformable.h" #include "components/orientable.h" #include "components/mappable.h" +#include "components/realizable.h" +#include "components/playable.h" #include "systems/orienting.h" #include "systems/playing.h" +#include "systems/realizing.h" #include "consts.h" #include "collision.h" void PonderingSystem::tick(double dt) { + auto& realizable = game_.getEntityManager(). + getComponent( + game_.getSystemManager().getSystem().getSingleton()); + + id_type mapEntity = realizable.activeMap; + + auto& mappable = game_.getEntityManager(). + getComponent(mapEntity); + auto entities = game_.getEntityManager().getEntitiesWithComponents< PonderableComponent, TransformableComponent>(); - auto maps = game_.getEntityManager().getEntitiesWithComponents< - MappableComponent>(); - for (id_type entity : entities) { - auto& transformable = game_.getEntityManager(). - getComponent(entity); - auto& ponderable = game_.getEntityManager(). getComponent(entity); - if (ponderable.isFrozen()) + if (!ponderable.active || ponderable.frozen) { continue; } - // Accelerate - ponderable.setVelocityX( - ponderable.getVelocityX() + ponderable.getAccelX() * dt); + auto& transformable = game_.getEntityManager(). + getComponent(entity); - ponderable.setVelocityY( - ponderable.getVelocityY() + ponderable.getAccelY() * dt); + // Accelerate + ponderable.velX += ponderable.accelX * dt; + ponderable.velY += ponderable.accelY * dt; - if ((ponderable.getType() == PonderableComponent::Type::freefalling) - && (ponderable.getVelocityY() > TERMINAL_VELOCITY)) + if ((ponderable.type == PonderableComponent::Type::freefalling) + && (ponderable.velY > TERMINAL_VELOCITY)) { - ponderable.setVelocityY(TERMINAL_VELOCITY); + ponderable.velY = TERMINAL_VELOCITY; } - const double oldX = transformable.getX(); - const double oldY = transformable.getY(); - const double oldRight = oldX + transformable.getW(); - const double oldBottom = oldY + transformable.getH(); + const double oldX = transformable.x; + const double oldY = transformable.y; + const double oldRight = oldX + transformable.w; + const double oldBottom = oldY + transformable.h; - double newX = oldX + ponderable.getVelocityX() * dt; - double newY = oldY + ponderable.getVelocityY() * dt; + double newX = oldX + ponderable.velX * dt; + double newY = oldY + ponderable.velY * dt; - bool oldGrounded = ponderable.isGrounded(); - ponderable.setGrounded(false); + bool oldGrounded = ponderable.grounded; + ponderable.grounded = false; std::priority_queue collisions; // Find collisions - for (id_type mapEntity : maps) + if (newX < oldX) { - auto& mappable = game_.getEntityManager(). - getComponent(mapEntity); - - if (newX < oldX) + for (auto it = mappable.leftBoundaries.lower_bound(oldX); + (it != std::end(mappable.leftBoundaries)) && (it->first >= newX); + it++) { - for (auto it = mappable.getLeftBoundaries().lower_bound(oldX); - (it != std::end(mappable.getLeftBoundaries())) && (it->first >= newX); - it++) + if ((oldBottom > it->second.lower) + && (oldY < it->second.upper)) { - if ((oldBottom > it->second.getLower()) - && (oldY < it->second.getUpper())) - { - // We have a collision! - collisions.emplace( - mapEntity, - Direction::left, - it->second.getType(), - it->first, - it->second.getLower(), - it->second.getUpper()); - } + // We have a collision! + collisions.emplace( + mapEntity, + Direction::left, + it->second.type, + it->first, + it->second.lower, + it->second.upper); } - } else if (newX > oldX) + } + } else if (newX > oldX) + { + for (auto it = mappable.rightBoundaries.lower_bound(oldRight); + (it != std::end(mappable.rightBoundaries)) + && (it->first <= (newX + transformable.w)); + it++) { - for (auto it = mappable.getRightBoundaries().lower_bound(oldRight); - (it != std::end(mappable.getRightBoundaries())) - && (it->first <= (newX + transformable.getW())); - it++) + if ((oldBottom > it->second.lower) + && (oldY < it->second.upper)) { - if ((oldBottom > it->second.getLower()) - && (oldY < it->second.getUpper())) - { - // We have a collision! - collisions.emplace( - mapEntity, - Direction::right, - it->second.getType(), - it->first, - it->second.getLower(), - it->second.getUpper()); - } + // We have a collision! + collisions.emplace( + mapEntity, + Direction::right, + it->second.type, + it->first, + it->second.lower, + it->second.upper); } } + } - if (newY < oldY) + if (newY < oldY) + { + for (auto it = mappable.upBoundaries.lower_bound(oldY); + (it != std::end(mappable.upBoundaries)) && (it->first >= newY); + it++) { - for (auto it = mappable.getUpBoundaries().lower_bound(oldY); - (it != std::end(mappable.getUpBoundaries())) && (it->first >= newY); - it++) + if ((oldRight > it->second.lower) + && (oldX < it->second.upper)) { - if ((oldRight > it->second.getLower()) - && (oldX < it->second.getUpper())) - { - // We have a collision! - collisions.emplace( - mapEntity, - Direction::up, - it->second.getType(), - it->first, - it->second.getLower(), - it->second.getUpper()); - } + // We have a collision! + collisions.emplace( + mapEntity, + Direction::up, + it->second.type, + it->first, + it->second.lower, + it->second.upper); } - } else if (newY > oldY) + } + } else if (newY > oldY) + { + for (auto it = mappable.downBoundaries.lower_bound(oldBottom); + (it != std::end(mappable.downBoundaries)) + && (it->first <= (newY + transformable.h)); + it++) { - for (auto it = mappable.getDownBoundaries().lower_bound(oldBottom); - (it != std::end(mappable.getDownBoundaries())) - && (it->first <= (newY + transformable.getH())); - it++) + if ((oldRight > it->second.lower) + && (oldX < it->second.upper)) { - if ((oldRight > it->second.getLower()) - && (oldX < it->second.getUpper())) - { - // We have a collision! - collisions.emplace( - mapEntity, - Direction::down, - it->second.getType(), - it->first, - it->second.getLower(), - it->second.getUpper()); - } + // We have a collision! + collisions.emplace( + mapEntity, + Direction::down, + it->second.type, + it->first, + it->second.lower, + it->second.upper); } } } // Process collisions in order of priority + bool adjacentlyWarping = false; + Direction adjWarpDir; + size_t adjWarpMapId; + while (!collisions.empty()) { Collision collision = collisions.top(); @@ -157,8 +161,8 @@ void PonderingSystem::tick(double dt) if (!collision.isColliding( newX, newY, - transformable.getW(), - transformable.getH())) + transformable.w, + transformable.h)) { continue; } @@ -201,33 +205,33 @@ void PonderingSystem::tick(double dt) { auto& mappable = game_.getEntityManager(). getComponent(collision.getCollider()); - const Map& map = game_.getWorld().getMap(mappable.getMapId()); - auto& adj = [&] () -> const Map::Adjacent& { + + auto& adj = [&] () -> const MappableComponent::Adjacent& { switch (collision.getDirection()) { - case Direction::left: return map.getLeftAdjacent(); - case Direction::right: return map.getRightAdjacent(); - case Direction::up: return map.getUpAdjacent(); - case Direction::down: return map.getDownAdjacent(); + case Direction::left: return mappable.leftAdjacent; + case Direction::right: return mappable.rightAdjacent; + case Direction::up: return mappable.upAdjacent; + case Direction::down: return mappable.downAdjacent; } }(); - switch (adj.getType()) + switch (adj.type) { - case Map::Adjacent::Type::wall: + case MappableComponent::Adjacent::Type::wall: { touchedWall = true; break; } - case Map::Adjacent::Type::wrap: + case MappableComponent::Adjacent::Type::wrap: { switch (collision.getDirection()) { case Direction::left: { - newX = GAME_WIDTH + WALL_GAP - transformable.getW(); + newX = GAME_WIDTH + WALL_GAP - transformable.w; break; } @@ -241,8 +245,7 @@ void PonderingSystem::tick(double dt) case Direction::up: { - newY = MAP_HEIGHT * TILE_HEIGHT + WALL_GAP - - transformable.getH(); + newY = MAP_HEIGHT * TILE_HEIGHT + WALL_GAP - transformable.h; break; } @@ -256,46 +259,22 @@ void PonderingSystem::tick(double dt) } } - case Map::Adjacent::Type::warp: + case MappableComponent::Adjacent::Type::warp: { - double warpX = newX; - double warpY = newY; - - switch (collision.getDirection()) + if (game_.getEntityManager(). + hasComponent(entity)) { - case Direction::left: - { - warpX = GAME_WIDTH + WALL_GAP - transformable.getW(); - - break; - } - - case Direction::right: - { - warpX = -WALL_GAP; - - break; - } - - case Direction::up: - { - warpY = MAP_HEIGHT * TILE_HEIGHT - transformable.getH(); - - break; - } - - case Direction::down: - { - warpY = -WALL_GAP; - - break; - } + adjacentlyWarping = true; + adjWarpDir = collision.getDirection(); + adjWarpMapId = adj.mapId; } - game_.getSystemManager().getSystem(). - changeMap(adj.getMapId(), warpX, warpY); + break; + } - stopProcessing = true; + case MappableComponent::Adjacent::Type::reverse: + { + // TODO: not yet implemented. break; } @@ -306,7 +285,13 @@ void PonderingSystem::tick(double dt) case Collision::Type::danger: { - game_.getSystemManager().getSystem().die(); + if (game_.getEntityManager(). + hasComponent(entity)) + { + game_.getSystemManager().getSystem().die(entity); + + adjacentlyWarping = false; + } stopProcessing = true; @@ -333,15 +318,15 @@ void PonderingSystem::tick(double dt) case Direction::left: { newX = collision.getAxis(); - ponderable.setVelocityX(0.0); + ponderable.velX = 0.0; break; } case Direction::right: { - newX = collision.getAxis() - transformable.getW(); - ponderable.setVelocityX(0.0); + newX = collision.getAxis() - transformable.w; + ponderable.velX = 0.0; break; } @@ -349,16 +334,16 @@ void PonderingSystem::tick(double dt) case Direction::up: { newY = collision.getAxis(); - ponderable.setVelocityY(0.0); + ponderable.velY = 0.0; break; } case Direction::down: { - newY = collision.getAxis() - transformable.getH(); - ponderable.setVelocityY(0.0); - ponderable.setGrounded(true); + newY = collision.getAxis() - transformable.h; + ponderable.velY = 0.0; + ponderable.grounded = true; break; } @@ -367,8 +352,8 @@ void PonderingSystem::tick(double dt) } // Move - transformable.setX(newX); - transformable.setY(newY); + transformable.x = newX; + transformable.y = newY; // Perform cleanup for orientable entites if (game_.getEntityManager().hasComponent(entity)) @@ -377,9 +362,9 @@ void PonderingSystem::tick(double dt) getComponent(entity); // Handle changes in groundedness - if (ponderable.isGrounded() != oldGrounded) + if (ponderable.grounded != oldGrounded) { - if (ponderable.isGrounded()) + if (ponderable.grounded) { game_.getSystemManager().getSystem().land(entity); } else { @@ -394,6 +379,51 @@ void PonderingSystem::tick(double dt) orientable.setDropState(OrientableComponent::DropState::none); } } + + // Move to an adjacent map, if necessary + if (adjacentlyWarping) + { + double warpX = newX; + double warpY = newY; + + switch (adjWarpDir) + { + case Direction::left: + { + warpX = GAME_WIDTH + WALL_GAP - transformable.w; + + break; + } + + case Direction::right: + { + warpX = -WALL_GAP; + + break; + } + + case Direction::up: + { + warpY = MAP_HEIGHT * TILE_HEIGHT - transformable.h; + + break; + } + + case Direction::down: + { + warpY = -WALL_GAP; + + break; + } + } + + game_.getSystemManager().getSystem(). + changeMap( + entity, + adjWarpMapId, + warpX, + warpY); + } } } @@ -406,6 +436,20 @@ void PonderingSystem::initializeBody( if (type == PonderableComponent::Type::freefalling) { - ponderable.setAccelY(NORMAL_GRAVITY); + ponderable.accelY = NORMAL_GRAVITY; } } + +void PonderingSystem::initPrototype(id_type prototype) +{ + auto& ponderable = game_.getEntityManager(). + getComponent(prototype); + + ponderable.velX = 0.0; + ponderable.velY = 0.0; + ponderable.accelX = 0.0; + ponderable.accelY = 0.0; + ponderable.grounded = false; + ponderable.frozen = false; + ponderable.collidable = true; +} diff --git a/src/systems/pondering.h b/src/systems/pondering.h index d70525b..58e6496 100644 --- a/src/systems/pondering.h +++ b/src/systems/pondering.h @@ -16,6 +16,8 @@ public: void initializeBody(id_type entity, PonderableComponent::Type type); + void initPrototype(id_type prototype); + }; #endif /* end of include guard: PONDERING_H_F2530E0E */ diff --git a/src/systems/realizing.cpp b/src/systems/realizing.cpp new file mode 100644 index 0000000..09c38f3 --- /dev/null +++ b/src/systems/realizing.cpp @@ -0,0 +1,321 @@ +#include "realizing.h" +#include +#include +#include +#include "game.h" +#include "consts.h" +#include "components/realizable.h" +#include "components/mappable.h" +#include "components/animatable.h" +#include "components/playable.h" +#include "components/ponderable.h" +#include "components/transformable.h" +#include "systems/mapping.h" +#include "systems/animating.h" +#include "systems/pondering.h" + +inline xmlChar* getProp(xmlNodePtr node, const char* attr) +{ + xmlChar* key = xmlGetProp(node, reinterpret_cast(attr)); + if (key == nullptr) + { + throw std::invalid_argument("Error parsing world file"); + } + + return key; +} + +// TODO: neither the XML doc nor any of the emplaced entities are properly +// destroyed if this method throws an exception. +EntityManager::id_type RealizingSystem::initSingleton(std::string filename) +{ + id_type world = game_.getEntityManager().emplaceEntity(); + + auto& realizable = game_.getEntityManager(). + emplaceComponent(world); + + auto& mapping = game_.getSystemManager().getSystem(); + + xmlDocPtr doc = xmlParseFile(filename.c_str()); + if (doc == nullptr) + { + throw std::invalid_argument("Cannot find world file"); + } + + xmlNodePtr top = xmlDocGetRootElement(doc); + if (top == nullptr) + { + throw std::invalid_argument("Error parsing world file"); + } + + if (xmlStrcmp(top->name, reinterpret_cast("world"))) + { + throw std::invalid_argument("Error parsing world file"); + } + + xmlChar* key = nullptr; + + key = getProp(top, "startx"); + realizable.startingX = atoi(reinterpret_cast(key)); + xmlFree(key); + + key = getProp(top, "starty"); + realizable.startingY = atoi(reinterpret_cast(key)); + xmlFree(key); + + key = getProp(top, "startmap"); + realizable.startingMapId = atoi(reinterpret_cast(key)); + xmlFree(key); + + for (xmlNodePtr node = top->xmlChildrenNode; + node != nullptr; + node = node->next) + { + if (!xmlStrcmp(node->name, reinterpret_cast("map"))) + { + id_type map = game_.getEntityManager().emplaceEntity(); + + auto& mappable = game_.getEntityManager(). + emplaceComponent(map, + Texture("res/tiles.png"), + Texture("res/font.bmp")); + + key = getProp(node, "id"); + mappable.mapId = atoi(reinterpret_cast(key)); + xmlFree(key); + + key = getProp(node, "title"); + mappable.title = reinterpret_cast(key); + xmlFree(key); + + for (xmlNodePtr mapNode = node->xmlChildrenNode; + mapNode != nullptr; + mapNode = mapNode->next) + { + if (!xmlStrcmp( + mapNode->name, + reinterpret_cast("environment"))) + { + key = xmlNodeGetContent(mapNode); + if (key == nullptr) + { + throw std::invalid_argument("Error parsing world file"); + } + + mappable.tiles.clear(); + mappable.tiles.push_back(atoi(strtok( + reinterpret_cast(key), + ",\n"))); + + for (size_t i = 1; i < (MAP_WIDTH * MAP_HEIGHT); i++) + { + mappable.tiles.push_back(atoi(strtok(nullptr, ",\n"))); + } + + xmlFree(key); + } else if (!xmlStrcmp( + mapNode->name, + reinterpret_cast("adjacent"))) + { + key = getProp(mapNode, "type"); + std::string adjTypeStr(reinterpret_cast(key)); + xmlFree(key); + + MappableComponent::Adjacent::Type adjType; + if (adjTypeStr == "wall") + { + adjType = MappableComponent::Adjacent::Type::wall; + } else if (adjTypeStr == "wrap") + { + adjType = MappableComponent::Adjacent::Type::wrap; + } else if (adjTypeStr == "warp") + { + adjType = MappableComponent::Adjacent::Type::warp; + } else if (adjTypeStr == "reverseWarp") + { + adjType = MappableComponent::Adjacent::Type::reverse; + } else { + throw std::logic_error("Invalid adjacency type"); + } + + key = getProp(mapNode, "map"); + size_t adjMapId = atoi(reinterpret_cast(key)); + xmlFree(key); + + key = getProp(mapNode, "dir"); + std::string adjDir(reinterpret_cast(key)); + xmlFree(key); + + if (adjDir == "left") + { + mappable.leftAdjacent = {adjType, adjMapId}; + } else if (adjDir == "right") + { + mappable.rightAdjacent = {adjType, adjMapId}; + } else if (adjDir == "up") + { + mappable.upAdjacent = {adjType, adjMapId}; + } else if (adjDir == "down") + { + mappable.downAdjacent = {adjType, adjMapId}; + } else { + throw std::logic_error("Invalid adjacency direction"); + } + } + } + + mapping.generateBoundaries(map); + + realizable.maps.insert(map); + realizable.entityByMapId[mappable.mapId] = map; + } + } + + xmlFreeDoc(doc); + + loadMap(realizable.entityByMapId[realizable.startingMapId]); + + return world; +} + +EntityManager::id_type RealizingSystem::getSingleton() const +{ + std::set result = + game_.getEntityManager().getEntitiesWithComponents< + RealizableComponent>(); + + if (result.empty()) + { + throw std::logic_error("No realizable entity found"); + } else if (result.size() > 1) + { + throw std::logic_error("Multiple realizable entities found"); + } + + return *std::begin(result); +} + +void RealizingSystem::loadMap(id_type mapEntity) +{ + id_type world = getSingleton(); + + auto& realizable = game_.getEntityManager(). + getComponent(world); + + auto& animating = game_.getSystemManager().getSystem(); + auto& pondering = game_.getSystemManager().getSystem(); + + std::set players = + game_.getEntityManager().getEntitiesWithComponents< + PlayableComponent>(); + + if (realizable.hasActiveMap) + { + id_type oldMap = realizable.activeMap; + + auto& oldMappable = game_.getEntityManager(). + getComponent(oldMap); + + // Deactivate any map objects from the old map. + for (id_type prototype : oldMappable.objects) + { + leaveActiveMap(prototype); + } + + // Deactivate players that were on the old map. + for (id_type player : players) + { + auto& playable = game_.getEntityManager(). + getComponent(player); + + if (playable.mapId == oldMap) + { + leaveActiveMap(player); + } + } + } + + realizable.hasActiveMap = true; + realizable.activeMap = mapEntity; + + auto& mappable = game_.getEntityManager(). + getComponent(mapEntity); + + // Initialize the new map's objects. + for (id_type prototype : mappable.objects) + { + if (game_.getEntityManager(). + hasComponent(prototype)) + { + auto& transformable = game_.getEntityManager(). + getComponent(prototype); + + transformable.x = transformable.origX; + transformable.y = transformable.origY; + transformable.w = transformable.origW; + transformable.h = transformable.origH; + } + + if (game_.getEntityManager().hasComponent(prototype)) + { + animating.initPrototype(prototype); + } + + if (game_.getEntityManager().hasComponent(prototype)) + { + pondering.initPrototype(prototype); + } + + enterActiveMap(prototype); + } + + // Activate any players on the map. + for (id_type player : players) + { + auto& playable = game_.getEntityManager(). + getComponent(player); + + if (playable.mapId == mapEntity) + { + enterActiveMap(player); + } + } +} + +void RealizingSystem::enterActiveMap(id_type entity) +{ + if (game_.getEntityManager().hasComponent(entity)) + { + auto& animatable = game_.getEntityManager(). + getComponent(entity); + + animatable.active = true; + } + + if (game_.getEntityManager().hasComponent(entity)) + { + auto& ponderable = game_.getEntityManager(). + getComponent(entity); + + ponderable.active = true; + } +} + +void RealizingSystem::leaveActiveMap(id_type entity) +{ + if (game_.getEntityManager().hasComponent(entity)) + { + auto& animatable = game_.getEntityManager(). + getComponent(entity); + + animatable.active = false; + } + + if (game_.getEntityManager().hasComponent(entity)) + { + auto& ponderable = game_.getEntityManager(). + getComponent(entity); + + ponderable.active = false; + } +} diff --git a/src/systems/realizing.h b/src/systems/realizing.h new file mode 100644 index 0000000..c681892 --- /dev/null +++ b/src/systems/realizing.h @@ -0,0 +1,43 @@ +#ifndef REALIZING_H_6853748C +#define REALIZING_H_6853748C + +#include "system.h" + +class RealizingSystem : public System { +public: + + RealizingSystem(Game& game) : System(game) + { + } + + /** + * Creates the singleton realizable entity and initializes it with the + * provided world definition. + */ + id_type initSingleton(std::string filename); + + /** + * Helper method that returns the entity ID of the (assumed) singleton entity + * with a RealizableComponent. Throws an exception if the number of realizable + * entities is not exactly one. + */ + id_type getSingleton() const; + + /** + * Loads the given map. + */ + void loadMap(id_type mapEntity); + + /** + * Treats the given entity as part of the active map. + */ + void enterActiveMap(id_type entity); + + /** + * Stops treating the given entity as part of the active map. + */ + void leaveActiveMap(id_type entity); + +}; + +#endif /* end of include guard: REALIZING_H_6853748C */ diff --git a/src/world.cpp b/src/world.cpp deleted file mode 100644 index 3b6bd41..0000000 --- a/src/world.cpp +++ /dev/null @@ -1,155 +0,0 @@ -#include "world.h" -#include -#include -#include -#include "consts.h" - -inline xmlChar* getProp(xmlNodePtr node, const char* attr) -{ - xmlChar* key = xmlGetProp(node, reinterpret_cast(attr)); - if (key == nullptr) - { - throw std::invalid_argument("Error parsing world file"); - } - - return key; -} - -World::World(std::string filename) -{ - xmlDocPtr doc = xmlParseFile(filename.c_str()); - if (doc == nullptr) - { - throw std::invalid_argument("Cannot find world file"); - } - - xmlNodePtr top = xmlDocGetRootElement(doc); - if (top == nullptr) - { - throw std::invalid_argument("Error parsing world file"); - } - - if (xmlStrcmp(top->name, reinterpret_cast("world"))) - { - throw std::invalid_argument("Error parsing world file"); - } - - xmlChar* key = nullptr; - - key = getProp(top, "startx"); - startX_ = atoi(reinterpret_cast(key)); - xmlFree(key); - - key = getProp(top, "starty"); - startY_ = atoi(reinterpret_cast(key)); - xmlFree(key); - - key = getProp(top, "startmap"); - startMap_ = atoi(reinterpret_cast(key)); - xmlFree(key); - - for (xmlNodePtr node = top->xmlChildrenNode; - node != nullptr; - node = node->next) - { - if (!xmlStrcmp(node->name, reinterpret_cast("map"))) - { - key = getProp(node, "id"); - size_t mapId = atoi(reinterpret_cast(key)); - xmlFree(key); - - key = getProp(node, "title"); - std::string mapTitle(reinterpret_cast(key)); - xmlFree(key); - - std::vector mapTiles; - Map::Adjacent leftAdj; - Map::Adjacent rightAdj; - Map::Adjacent upAdj; - Map::Adjacent downAdj; - - for (xmlNodePtr mapNode = node->xmlChildrenNode; - mapNode != nullptr; - mapNode = mapNode->next) - { - if (!xmlStrcmp( - mapNode->name, - reinterpret_cast("environment"))) - { - key = xmlNodeGetContent(mapNode); - - mapTiles.clear(); - mapTiles.push_back(atoi(strtok(reinterpret_cast(key), ",\n"))); - for (size_t i = 1; i < (MAP_WIDTH * MAP_HEIGHT); i++) - { - mapTiles.push_back(atoi(strtok(nullptr, ",\n"))); - } - - xmlFree(key); - } else if (!xmlStrcmp( - mapNode->name, - reinterpret_cast("adjacent"))) - { - key = getProp(mapNode, "type"); - std::string adjTypeStr(reinterpret_cast(key)); - xmlFree(key); - - Map::Adjacent::Type adjType; - if (adjTypeStr == "wall") - { - adjType = Map::Adjacent::Type::wall; - } else if (adjTypeStr == "wrap") - { - adjType = Map::Adjacent::Type::wrap; - } else if (adjTypeStr == "warp") - { - adjType = Map::Adjacent::Type::warp; - } else if (adjTypeStr == "reverseWarp") - { - adjType = Map::Adjacent::Type::reverse; - } else { - throw std::logic_error("Invalid adjacency type"); - } - - key = getProp(mapNode, "map"); - int adjMapId = atoi(reinterpret_cast(key)); - xmlFree(key); - - key = getProp(mapNode, "dir"); - std::string adjDir(reinterpret_cast(key)); - xmlFree(key); - - if (adjDir == "left") - { - leftAdj = {adjType, adjMapId}; - } else if (adjDir == "right") - { - rightAdj = {adjType, adjMapId}; - } else if (adjDir == "up") - { - upAdj = {adjType, adjMapId}; - } else if (adjDir == "down") - { - downAdj = {adjType, adjMapId}; - } else { - throw std::logic_error("Invalid adjacency direction"); - } - } - } - - maps_.emplace( - std::piecewise_construct, - std::forward_as_tuple(mapId), - std::forward_as_tuple( - mapId, - std::move(mapTiles), - std::move(mapTitle), - leftAdj, - rightAdj, - upAdj, - downAdj)); - } - } - - xmlFreeDoc(doc); -} diff --git a/src/world.h b/src/world.h deleted file mode 100644 index b88adf4..0000000 --- a/src/world.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef WORLD_H_153C698B -#define WORLD_H_153C698B - -#include -#include -#include "map.h" - -class World { -public: - - explicit World(std::string filename); - - inline const Map& getMap(size_t id) const - { - return maps_.at(id); - } - - inline size_t getStartingMapId() const - { - return startMap_; - } - - inline int getStartingX() const - { - return startX_; - } - - inline int getStartingY() const - { - return startY_; - } - -private: - - std::map maps_; - size_t startMap_; - int startX_; - int startY_; -}; - -#endif /* end of include guard: WORLD_H_153C698B */ -- cgit 1.4.1 From 123192db10cdf5244f27d08256ece738f60a9e2c Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Fri, 4 May 2018 10:23:02 -0400 Subject: Unferried players while changing maps This fixes the third problem described in 8f1c4f1 -- that if a ferried body's transform is modified outside of the PonderingSystem, it will not be unferried as appropriate. This does still require that any future code that modifies a body's transform also unferries the body first. --- src/systems/playing.cpp | 8 +++----- src/systems/pondering.cpp | 26 +++++++++++++++++++------- src/systems/pondering.h | 14 ++++++++++++++ 3 files changed, 36 insertions(+), 12 deletions(-) (limited to 'src/systems/playing.cpp') diff --git a/src/systems/playing.cpp b/src/systems/playing.cpp index b04f0cb..acec4e7 100644 --- a/src/systems/playing.cpp +++ b/src/systems/playing.cpp @@ -79,11 +79,7 @@ void PlayingSystem::changeMap( auto& transformable = game_.getEntityManager(). getComponent(player); - auto& animatable = game_.getEntityManager(). - getComponent(player); - - auto& ponderable = game_.getEntityManager(). - getComponent(player); + auto& pondering = game_.getSystemManager().getSystem(); auto& realizing = game_.getSystemManager().getSystem(); @@ -105,6 +101,8 @@ void PlayingSystem::changeMap( playable.mapId = newMapEntity; } + pondering.unferry(player); + transformable.x = x; transformable.y = y; diff --git a/src/systems/pondering.cpp b/src/systems/pondering.cpp index ccfd66f..4aa47f2 100644 --- a/src/systems/pondering.cpp +++ b/src/systems/pondering.cpp @@ -655,7 +655,7 @@ void PonderingSystem::tick(double dt) } } - // Handle ferry passengers + // Ferry or unferry as necessary if ((ponderable.type == PonderableComponent::Type::freefalling) && (ponderable.grounded != oldGrounded)) { @@ -674,15 +674,11 @@ void PonderingSystem::tick(double dt) } else if (ponderable.ferried) { // The body is no longer being ferried - ponderable.ferried = false; - - auto& ferryPonder = game_.getEntityManager(). - getComponent(ponderable.ferry); - - ferryPonder.passengers.erase(entity); + unferry(entity); } } + // Update a ferry passenger's relative position if (ponderable.ferried) { auto& ferryTrans = game_.getEntityManager(). @@ -768,6 +764,22 @@ void PonderingSystem::initPrototype(id_type prototype) ponderable.passengers.clear(); } +void PonderingSystem::unferry(id_type entity) +{ + auto& ponderable = game_.getEntityManager(). + getComponent(entity); + + if (ponderable.ferried) + { + ponderable.ferried = false; + + auto& ferryPonder = game_.getEntityManager(). + getComponent(ponderable.ferry); + + ferryPonder.passengers.erase(entity); + } +} + void PonderingSystem::processCollision( id_type entity, id_type collider, diff --git a/src/systems/pondering.h b/src/systems/pondering.h index b195814..adc0cda 100644 --- a/src/systems/pondering.h +++ b/src/systems/pondering.h @@ -16,8 +16,22 @@ public: void initializeBody(id_type entity, PonderableComponent::Type type); + /** + * Initializes a ponderable map object from its prototype data. + * + * @requires entity is ponderable + * @requires entity is a map object + */ void initPrototype(id_type prototype); + /** + * Unferries an entity if it is a passenger of another entity. Use before + * moving a ponderable entity outside the PonderingSystem. + * + * @requires entity is ponderable + */ + void unferry(id_type entity); + private: struct CollisionResult -- cgit 1.4.1 From 5c82f052c26303318e81ddd76475c1d188cc74f4 Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Tue, 8 May 2018 21:09:36 -0400 Subject: Simplified positions/sizes with vectors Positions and sizes are now stored as vectors (of doubles and ints, respectively). This allows for at least minor code simplification in many places, and cleans up the CollisionParams code in PonderingSystem quite a bit. --- src/components/automatable.h | 4 +- src/components/playable.h | 4 +- src/components/ponderable.h | 10 +- src/components/realizable.h | 4 +- src/components/transformable.h | 13 +- src/systems/animating.cpp | 8 +- src/systems/automating.cpp | 3 +- src/systems/orienting.cpp | 14 +- src/systems/playing.cpp | 19 +-- src/systems/playing.h | 4 +- src/systems/pondering.cpp | 294 +++++++++++++++-------------------------- src/systems/pondering.h | 34 +++-- src/systems/realizing.cpp | 38 +++--- src/vector.h | 111 ++++++++++++++++ 14 files changed, 285 insertions(+), 275 deletions(-) create mode 100644 src/vector.h (limited to 'src/systems/playing.cpp') diff --git a/src/components/automatable.h b/src/components/automatable.h index b37945f..c1fd1a3 100644 --- a/src/components/automatable.h +++ b/src/components/automatable.h @@ -4,6 +4,7 @@ #include "component.h" #include #include +#include "vector.h" class AutomatableComponent : public Component { public: @@ -18,8 +19,7 @@ public: * The horizontal and vertical speed, in pixels/sec, that the entity should * move at. */ - double speedX; - double speedY; + vec2d speed; /** * The duration of the action in seconds. diff --git a/src/components/playable.h b/src/components/playable.h index 94d4326..b8af0f2 100644 --- a/src/components/playable.h +++ b/src/components/playable.h @@ -3,6 +3,7 @@ #include "component.h" #include "entity_manager.h" +#include "vector.h" class PlayableComponent : public Component { public: @@ -24,8 +25,7 @@ public: * @managed_by PlayingSystem */ size_t checkpointMapId; - double checkpointX; - double checkpointY; + vec2d checkpointPos; }; diff --git a/src/components/ponderable.h b/src/components/ponderable.h index eff20e9..c0312b4 100644 --- a/src/components/ponderable.h +++ b/src/components/ponderable.h @@ -4,6 +4,7 @@ #include #include "component.h" #include "entity_manager.h" +#include "vector.h" class PonderableComponent : public Component { public: @@ -45,14 +46,12 @@ public: /** * The velocity of the body. */ - double velX = 0.0; - double velY = 0.0; + vec2d vel = { 0.0, 0.0 }; /** * The acceleration of the body. */ - double accelX = 0.0; - double accelY = 0.0; + vec2d accel = { 0.0, 0.0 }; /** * The type of physical body that the entity is meant to assume. The body will @@ -89,8 +88,7 @@ public: * * @managed_by PonderingSystem */ - double relX; - double relY; + vec2d rel = { 0.0, 0.0 }; /** * The bodies that are being ferried by this body. diff --git a/src/components/realizable.h b/src/components/realizable.h index 0858e7a..b749aeb 100644 --- a/src/components/realizable.h +++ b/src/components/realizable.h @@ -5,6 +5,7 @@ #include #include #include "entity_manager.h" +#include "vector.h" class RealizableComponent : public Component { public: @@ -31,8 +32,7 @@ public: * @managed_by RealizingSystem */ int startingMapId; - int startingX; - int startingY; + vec2i startingPos; /** * The set of map entities loaded by this entity. It is only intended for diff --git a/src/components/transformable.h b/src/components/transformable.h index 6f3c2ef..bb21996 100644 --- a/src/components/transformable.h +++ b/src/components/transformable.h @@ -2,6 +2,7 @@ #define LOCATABLE_H_39E526CA #include "component.h" +#include "vector.h" class TransformableComponent : public Component { public: @@ -15,24 +16,20 @@ public: * so, use PonderingSystem::unferry on the body to ensure that it is not * ferried. */ - double x; - double y; + vec2d pos; /** * The size of the entity. */ - int w; - int h; + vec2i size; /** * For prototypes, the original coordinates and size of the entity. * * @managed_by RealizingSystem */ - double origX; - double origY; - int origW; - int origH; + vec2d origPos; + vec2i origSize; }; #endif /* end of include guard: LOCATABLE_H_39E526CA */ diff --git a/src/systems/animating.cpp b/src/systems/animating.cpp index 8543ba2..50a32fc 100644 --- a/src/systems/animating.cpp +++ b/src/systems/animating.cpp @@ -64,10 +64,10 @@ void AnimatingSystem::render(Texture& texture) } Rectangle dstrect { - static_cast(transform.x), - static_cast(transform.y), - transform.w, - transform.h}; + static_cast(transform.pos.x()), + static_cast(transform.pos.y()), + transform.size.w(), + transform.size.h()}; const AnimationSet& aset = sprite.animationSet; game_.getRenderer().blit( diff --git a/src/systems/automating.cpp b/src/systems/automating.cpp index 0d85957..61b97d9 100644 --- a/src/systems/automating.cpp +++ b/src/systems/automating.cpp @@ -54,8 +54,7 @@ void AutomatingSystem::tick(double dt) auto& ponderable = game_.getEntityManager(). getComponent(entity); - ponderable.velX = curAction.speedX; - ponderable.velY = curAction.speedY; + ponderable.vel = curAction.speed; automatable.remaining -= dt; } diff --git a/src/systems/orienting.cpp b/src/systems/orienting.cpp index 206ebf6..d73ddd2 100644 --- a/src/systems/orienting.cpp +++ b/src/systems/orienting.cpp @@ -24,27 +24,27 @@ void OrientingSystem::tick(double) { case OrientableComponent::WalkState::still: { - ponderable.velX = 0.0; + ponderable.vel.x() = 0.0; break; } case OrientableComponent::WalkState::left: { - ponderable.velX = -WALK_SPEED; + ponderable.vel.x() = -WALK_SPEED; break; } case OrientableComponent::WalkState::right: { - ponderable.velX = WALK_SPEED; + ponderable.vel.x() = WALK_SPEED; break; } } - if (orientable.isJumping() && (ponderable.velY > 0)) + if (orientable.isJumping() && (ponderable.vel.y() > 0)) { orientable.setJumping(false); } @@ -122,8 +122,8 @@ void OrientingSystem::jump(id_type entity) playSound("res/Randomize87.wav", 0.25); - ponderable.velY = JUMP_VELOCITY; - ponderable.accelY = JUMP_GRAVITY; + ponderable.vel.y() = JUMP_VELOCITY; + ponderable.accel.y() = JUMP_GRAVITY; auto& animating = game_.getSystemManager().getSystem(); if (orientable.isFacingRight()) @@ -147,7 +147,7 @@ void OrientingSystem::stopJumping(id_type entity) auto& ponderable = game_.getEntityManager(). getComponent(entity); - ponderable.accelY = NORMAL_GRAVITY; + ponderable.accel.y() = NORMAL_GRAVITY; } } diff --git a/src/systems/playing.cpp b/src/systems/playing.cpp index acec4e7..dabc9a5 100644 --- a/src/systems/playing.cpp +++ b/src/systems/playing.cpp @@ -42,10 +42,9 @@ void PlayingSystem::initPlayer() auto& transformable = game_.getEntityManager(). emplaceComponent(player); - transformable.x = realizable.startingX; - transformable.y = realizable.startingY; - transformable.w = 10; - transformable.h = 12; + transformable.pos = realizable.startingPos; + transformable.size.w() = 10; + transformable.size.h() = 12; game_.getSystemManager().getSystem().initializeBody( player, @@ -59,8 +58,7 @@ void PlayingSystem::initPlayer() playable.mapId = realizable.activeMap; playable.checkpointMapId = realizable.startingMapId; - playable.checkpointX = realizable.startingX; - playable.checkpointY = realizable.startingY; + playable.checkpointPos = realizable.startingPos; realizing.enterActiveMap(player); @@ -70,8 +68,7 @@ void PlayingSystem::initPlayer() void PlayingSystem::changeMap( id_type player, size_t mapId, - double x, - double y) + vec2d warpPos) { auto& playable = game_.getEntityManager(). getComponent(player); @@ -103,8 +100,7 @@ void PlayingSystem::changeMap( pondering.unferry(player); - transformable.x = x; - transformable.y = y; + transformable.pos = warpPos; if (realizable.activePlayer == player) { @@ -139,8 +135,7 @@ void PlayingSystem::die(id_type player) changeMap( player, playable.checkpointMapId, - playable.checkpointX, - playable.checkpointY); + playable.checkpointPos); animatable.frozen = false; animatable.flickering = false; diff --git a/src/systems/playing.h b/src/systems/playing.h index 9ba403b..31f79ab 100644 --- a/src/systems/playing.h +++ b/src/systems/playing.h @@ -2,6 +2,7 @@ #define PLAYING_H_70A54F7D #include "system.h" +#include "vector.h" class PlayingSystem : public System { public: @@ -15,8 +16,7 @@ public: void changeMap( id_type player, size_t mapId, - double x, - double y); + vec2d warpPos); void die(id_type player); diff --git a/src/systems/pondering.cpp b/src/systems/pondering.cpp index 7b3ab2d..ec83270 100644 --- a/src/systems/pondering.cpp +++ b/src/systems/pondering.cpp @@ -47,7 +47,7 @@ void PonderingSystem::initializeBody( if (type == PonderableComponent::Type::freefalling) { - ponderable.accelY = NORMAL_GRAVITY; + ponderable.accel.y() = NORMAL_GRAVITY; } } @@ -56,10 +56,10 @@ void PonderingSystem::initPrototype(id_type prototype) auto& ponderable = game_.getEntityManager(). getComponent(prototype); - ponderable.velX = 0.0; - ponderable.velY = 0.0; - ponderable.accelX = 0.0; - ponderable.accelY = 0.0; + ponderable.vel.x() = 0.0; + ponderable.vel.y() = 0.0; + ponderable.accel.x() = 0.0; + ponderable.accel.y() = 0.0; ponderable.grounded = false; ponderable.frozen = false; ponderable.collidable = true; @@ -102,19 +102,17 @@ void PonderingSystem::tickBody( // Accelerate if (!ponderable.frozen) { - ponderable.velX += ponderable.accelX * dt; - ponderable.velY += ponderable.accelY * dt; + ponderable.vel += ponderable.accel * dt; if ((ponderable.type == PonderableComponent::Type::freefalling) - && (ponderable.velY > TERMINAL_VELOCITY)) + && (ponderable.vel.y() > TERMINAL_VELOCITY)) { - ponderable.velY = TERMINAL_VELOCITY; + ponderable.vel.y() = TERMINAL_VELOCITY; } } // Move - double newX = transformable.x; - double newY = transformable.y; + vec2d newPos = transformable.pos; if (!ponderable.frozen) { @@ -123,19 +121,13 @@ void PonderingSystem::tickBody( auto& ferryTrans = game_.getEntityManager(). getComponent(ponderable.ferry); - newX = ferryTrans.x + ponderable.relX; - newY = ferryTrans.y + ponderable.relY; + newPos = ferryTrans.pos + ponderable.rel; } - newX += ponderable.velX * dt; - newY += ponderable.velY * dt; + newPos += ponderable.vel * dt; } - CollisionResult result = - moveBody( - entity, - newX, - newY); + CollisionResult result = moveBody(entity, newPos); // Perform cleanup for orientable entites bool groundedChanged = (ponderable.grounded != result.grounded); @@ -194,8 +186,7 @@ void PonderingSystem::tickBody( auto& ferryTrans = game_.getEntityManager(). getComponent(ponderable.ferry); - ponderable.relX = transformable.x - ferryTrans.x; - ponderable.relY = transformable.y - ferryTrans.y; + ponderable.rel = transformable.pos - ferryTrans.pos; } // Handle ferry passengers @@ -212,35 +203,34 @@ void PonderingSystem::tickBody( // Move to an adjacent map, if necessary if (result.adjacentlyWarping) { - double warpX = result.newX; - double warpY = result.newY; + vec2d warpPos = result.pos; switch (result.adjWarpDir) { case Direction::left: { - warpX = GAME_WIDTH + WALL_GAP - transformable.w; + warpPos.x() = GAME_WIDTH + WALL_GAP - transformable.size.w(); break; } case Direction::right: { - warpX = -WALL_GAP; + warpPos.x() = -WALL_GAP; break; } case Direction::up: { - warpY = MAP_HEIGHT * TILE_HEIGHT - transformable.h; + warpPos.y() = MAP_HEIGHT * TILE_HEIGHT - transformable.size.h(); break; } case Direction::down: { - warpY = -WALL_GAP; + warpPos.y() = -WALL_GAP; break; } @@ -250,15 +240,13 @@ void PonderingSystem::tickBody( changeMap( entity, result.adjWarpMapId, - warpX, - warpY); + warpPos); } } -CollisionResult PonderingSystem::moveBody( +PonderingSystem::CollisionResult PonderingSystem::moveBody( id_type entity, - double x, - double y) + vec2d newPos) { auto& ponderable = game_.getEntityManager(). getComponent(entity); @@ -266,26 +254,29 @@ CollisionResult PonderingSystem::moveBody( auto& transformable = game_.getEntityManager(). getComponent(entity); - const double oldX = transformable.x; - const double oldY = transformable.y; - const double oldRight = oldX + transformable.w; - const double oldBottom = oldY + transformable.h; - CollisionResult result; if (ponderable.collidable) { - result = detectCollisions(entity, x, y); + result = detectCollisions(entity, newPos); } else { - result.newX = x; - result.newY = y; + result.pos = newPos; } // Move if (!ponderable.frozen) { - transformable.x = result.newX; - transformable.y = result.newY; + transformable.pos = result.pos; + + if (result.blockedHoriz) + { + ponderable.vel.x() = 0.0; + } + + if (result.blockedVert) + { + ponderable.vel.y() = 0.0; + } } return result; @@ -311,21 +302,14 @@ namespace CollisionParams { return (colliderAxis > entityAxis); } - inline static double OldAxis(const TransformableComponent& transformable) + inline static double EntityAxis(const vec2d& pos, const vec2i& size) { - return HorizVert::AxisOldLower(transformable); + return HorizVert::AxisLower(pos); } - inline static double NewAxis( - const CollisionResult& result, - const TransformableComponent&) + inline static double ObjectAxis(const vec2d& pos, const vec2i& size) { - return HorizVert::AxisNewLower(result); - } - - inline static double ObjectAxis(const TransformableComponent& transformable) - { - return HorizVert::AxisOldUpper(transformable); + return HorizVert::AxisUpper(pos, size); } inline static bool Closer(double left, double right) @@ -352,21 +336,14 @@ namespace CollisionParams { return (colliderAxis < entityAxis); } - inline static double OldAxis(const TransformableComponent& transformable) + inline static double EntityAxis(const vec2d& pos, const vec2i& size) { - return HorizVert::AxisOldUpper(transformable); + return HorizVert::AxisUpper(pos, size); } - inline static double NewAxis( - const CollisionResult& result, - const TransformableComponent& transformable) + inline static double ObjectAxis(const vec2d& pos, const vec2i& size) { - return HorizVert::AxisNewUpper(result, transformable); - } - - inline static double ObjectAxis(const TransformableComponent& transformable) - { - return HorizVert::AxisOldLower(transformable); + return HorizVert::AxisLower(pos); } inline static bool Closer(double left, double right) @@ -375,121 +352,62 @@ namespace CollisionParams { } }; - class Horizontal { + template + class HorizVert { public: - inline static double AxisOldLower( - const TransformableComponent& transformable) + inline static double AxisLower(const vec2d& pos) { - return transformable.x; + return pos.coords[Axis]; } - inline static double AxisOldUpper( - const TransformableComponent& transformable) + inline static double AxisUpper(const vec2d& pos, const vec2i& size) { - return transformable.x + transformable.w; + return pos.coords[Axis] + size.coords[Axis]; } - inline static double AxisNewLower(const CollisionResult& result) + inline static double NonAxisLower(const vec2d& pos) { - return result.newX; + return pos.coords[NonAxis]; } - inline static double AxisNewUpper( - const CollisionResult& result, - const TransformableComponent& transformable) + inline static double NonAxisUpper(const vec2d& pos, const vec2i& size) { - return result.newX + transformable.w; + return pos.coords[NonAxis] + size.coords[NonAxis]; } - inline static double NonAxisOldLower( - const TransformableComponent& transformable) - { - return transformable.y; - } - - inline static double NonAxisOldUpper( - const TransformableComponent& transformable) - { - return transformable.y + transformable.h; - } - - inline static double NonAxisNewLower( - const CollisionResult& result, - const TransformableComponent& transformable) - { - return result.newY; - } - - inline static double NonAxisNewUpper( - const CollisionResult& result, - const TransformableComponent& transformable) - { - return result.newY + transformable.h; - } }; - class Vertical { - public: - - inline static double AxisOldLower( - const TransformableComponent& transformable) - { - return transformable.y; - } - - inline static double AxisOldUpper( - const TransformableComponent& transformable) - { - return transformable.y + transformable.h; - } + using Horizontal = HorizVert<0, 1>; + using Vertical = HorizVert<1, 0>; - inline static double AxisNewLower(const CollisionResult& result) - { - return result.newY; - } + template + class DetectCollisions : public AscDesc { + public: - inline static double AxisNewUpper( - const CollisionResult& result, - const TransformableComponent& transformable) - { - return result.newY + transformable.h; - } + static const Direction Dir = dir; - inline static double NonAxisOldLower( - const TransformableComponent& transformable) + inline static double EntityAxis(const vec2d& pos, const vec2i& size) { - return transformable.x; + return AscDesc::EntityAxis(pos, size); } - inline static double NonAxisOldUpper( - const TransformableComponent& transformable) + inline static double ObjectAxis(const vec2d& pos, const vec2i& size) { - return transformable.x + transformable.w; + return AscDesc::ObjectAxis(pos, size); } - inline static double NonAxisNewLower( - const CollisionResult& result, - const TransformableComponent& transformable) + inline static double EntityAxis(const TransformableComponent& transformable) { - return result.newX; + return AscDesc::EntityAxis(transformable.pos, transformable.size); } - inline static double NonAxisNewUpper( - const CollisionResult& result, - const TransformableComponent& transformable) + inline static double ObjectAxis(const TransformableComponent& transformable) { - return result.newX + transformable.w; + return AscDesc::ObjectAxis(transformable.pos, transformable.size); } }; - template - class DetectCollisions : public AscDesc { - public: - - static const Direction Dir = dir; - }; - class Left : public DetectCollisions> { public: @@ -531,23 +449,22 @@ namespace CollisionParams { }; }; -CollisionResult PonderingSystem::detectCollisions( +PonderingSystem::CollisionResult PonderingSystem::detectCollisions( id_type entity, - double x, - double y) + vec2d newPos) { auto& transformable = game_.getEntityManager(). getComponent(entity); CollisionResult result; - result.newX = x; - result.newY = transformable.y; + result.pos.x() = newPos.x(); + result.pos.y() = transformable.pos.y(); // Find horizontal collisions. - if (result.newX < transformable.x) + if (result.pos.x() < transformable.pos.x()) { detectCollisionsInDirection(entity, result); - } else if (result.newX > transformable.x) + } else if (result.pos.x() > transformable.pos.x()) { detectCollisionsInDirection(entity, result); } @@ -555,13 +472,13 @@ CollisionResult PonderingSystem::detectCollisions( // Find vertical collisions if (!result.stopProcessing) { - result.newY = y; + result.pos.y() = newPos.y(); result.touchedWall = false; - if (result.newY < transformable.y) + if (result.pos.y() < transformable.pos.y()) { detectCollisionsInDirection(entity, result); - } else if (result.newY > transformable.y) + } else if (result.pos.y() > transformable.pos.y()) { detectCollisionsInDirection(entity, result); } @@ -586,25 +503,25 @@ void PonderingSystem::detectCollisionsInDirection( getComponent(mapEntity); // Get old location. - auto& transformable = game_.getEntityManager(). + auto& transform = game_.getEntityManager(). getComponent(entity); bool boundaryCollision = false; auto boundaries = Param::MapBoundaries(mappable); - auto it = boundaries.lower_bound(Param::OldAxis(transformable)); + auto it = boundaries.lower_bound(Param::EntityAxis(transform)); // Find the axis distance of the closest environmental boundary. for (; (it != std::end(boundaries)) && Param::AtLeastInAxisSweep( it->first, - Param::NewAxis(result, transformable)); + Param::EntityAxis(result.pos, transform.size)); it++) { // Check that the boundary is in range for the other axis. - if ((Param::NonAxisNewUpper(result, transformable) > it->second.lower) && - (Param::NonAxisNewLower(result, transformable) < it->second.upper)) + if ((Param::NonAxisUpper(result.pos, transform.size) > it->second.lower) && + (Param::NonAxisLower(result.pos) < it->second.upper)) { // We have a collision! boundaryCollision = true; @@ -644,16 +561,16 @@ void PonderingSystem::detectCollisionsInDirection( // Check if the entity would move into the potential collider, if (Param::IsPastAxis( Param::ObjectAxis(colliderTrans), - Param::NewAxis(result, transformable)) && + Param::EntityAxis(result.pos, transform.size)) && // that it wasn't already colliding, !Param::IsPastAxis( Param::ObjectAxis(colliderTrans), - Param::OldAxis(transformable)) && + Param::EntityAxis(transform)) && // that the position on the non-axis is in range, - (Param::NonAxisOldUpper(colliderTrans) > - Param::NonAxisNewLower(result, transformable)) && - (Param::NonAxisOldLower(colliderTrans) < - Param::NonAxisNewUpper(result, transformable)) && + (Param::NonAxisUpper(colliderTrans.pos, colliderTrans.size) > + Param::NonAxisLower(result.pos)) && + (Param::NonAxisLower(colliderTrans.pos) < + Param::NonAxisUpper(result.pos, transform.size)) && // and that the collider is not farther away than the environmental // boundary. (!boundaryCollision || @@ -688,7 +605,7 @@ void PonderingSystem::detectCollisionsInDirection( // Check if the entity would still move into the potential collider. if (!Param::IsPastAxis( Param::ObjectAxis(colliderTrans), - Param::NewAxis(result, transformable))) + Param::EntityAxis(result.pos, transform.size))) { break; } @@ -702,8 +619,8 @@ void PonderingSystem::detectCollisionsInDirection( Param::Dir, colliderPonder.colliderType, Param::ObjectAxis(colliderTrans), - Param::NonAxisOldLower(colliderTrans), - Param::NonAxisOldUpper(colliderTrans), + Param::NonAxisLower(colliderTrans.pos), + Param::NonAxisUpper(colliderTrans.pos, colliderTrans.size), result); if (result.stopProcessing) @@ -724,8 +641,8 @@ void PonderingSystem::detectCollisionsInDirection( (it->first == boundaryAxis); it++) { - if ((Param::NonAxisNewUpper(result, transformable) > it->second.lower) && - (Param::NonAxisNewLower(result, transformable) < it->second.upper)) + if ((Param::NonAxisLower(result.pos) < it->second.upper) && + (Param::NonAxisUpper(result.pos, transform.size) > it->second.lower)) { processCollision( entity, @@ -756,9 +673,6 @@ void PonderingSystem::processCollision( double upper, CollisionResult& result) { - auto& ponderable = game_.getEntityManager(). - getComponent(entity); - auto& transformable = game_.getEntityManager(). getComponent(entity); @@ -823,29 +737,29 @@ void PonderingSystem::processCollision( { case Direction::left: { - result.newX = GAME_WIDTH + WALL_GAP - transformable.w; + result.pos.x() = GAME_WIDTH + WALL_GAP - transformable.size.w(); break; } case Direction::right: { - result.newX = -WALL_GAP; + result.pos.x() = -WALL_GAP; break; } case Direction::up: { - result.newY = - MAP_HEIGHT * TILE_HEIGHT + WALL_GAP - transformable.h; + result.pos.y() = + MAP_HEIGHT * TILE_HEIGHT + WALL_GAP - transformable.pos.h(); break; } case Direction::down: { - result.newY = -WALL_GAP; + result.pos.y() = -WALL_GAP; break; } @@ -905,33 +819,33 @@ void PonderingSystem::processCollision( { case Direction::left: { - result.newX = axis; - ponderable.velX = 0.0; + result.pos.x() = axis; + result.blockedHoriz = true; break; } case Direction::right: { - result.newX = axis - transformable.w; - ponderable.velX = 0.0; + result.pos.x() = axis - transformable.size.w(); + result.blockedHoriz = true; break; } case Direction::up: { - result.newY = axis; - ponderable.velY = 0.0; + result.pos.y() = axis; + result.blockedVert = true; break; } case Direction::down: { - result.newY = axis - transformable.h; + result.pos.y() = axis - transformable.size.h(); + result.blockedVert = true; result.groundEntity = collider; - ponderable.velY = 0.0; result.grounded = true; break; diff --git a/src/systems/pondering.h b/src/systems/pondering.h index abc6db2..273db67 100644 --- a/src/systems/pondering.h +++ b/src/systems/pondering.h @@ -4,19 +4,7 @@ #include "system.h" #include "components/ponderable.h" #include "direction.h" - -struct CollisionResult -{ - double newX; - double newY; - bool stopProcessing = false; - bool touchedWall = false; - bool adjacentlyWarping = false; - Direction adjWarpDir; - size_t adjWarpMapId; - bool grounded = false; - EntityManager::id_type groundEntity; -}; +#include "vector.h" class PonderingSystem : public System { public: @@ -47,7 +35,19 @@ public: private: - + struct CollisionResult + { + vec2d pos; + bool stopProcessing = false; + bool touchedWall = false; + bool blockedHoriz = false; + bool blockedVert = false; + bool adjacentlyWarping = false; + Direction adjWarpDir; + size_t adjWarpMapId; + bool grounded = false; + id_type groundEntity; + }; void tickBody( id_type entity, @@ -56,13 +56,11 @@ private: CollisionResult moveBody( id_type entity, - double x, - double y); + vec2d newPos); CollisionResult detectCollisions( id_type entity, - double x, - double y); + vec2d newPos); template void detectCollisionsInDirection( diff --git a/src/systems/realizing.cpp b/src/systems/realizing.cpp index 8e670ac..f9285ad 100644 --- a/src/systems/realizing.cpp +++ b/src/systems/realizing.cpp @@ -93,20 +93,20 @@ void parseAI( if (direction == "left") { - action.speedX = -speed; - action.speedY = 0; + action.speed.x() = -speed; + action.speed.y() = 0; } else if (direction == "right") { - action.speedX = speed; - action.speedY = 0; + action.speed.x() = speed; + action.speed.y() = 0; } else if (direction == "up") { - action.speedX = 0; - action.speedY = -speed; + action.speed.x() = 0; + action.speed.y() = -speed; } else if (direction == "down") { - action.speedX = 0; - action.speedY = speed; + action.speed.x() = 0; + action.speed.y() = speed; } action.dur = length / speed; @@ -186,11 +186,11 @@ EntityManager::id_type RealizingSystem::initSingleton( } key = getProp(top, "startx"); - realizable.startingX = atoi(reinterpret_cast(key)); + realizable.startingPos.x() = atoi(reinterpret_cast(key)); xmlFree(key); key = getProp(top, "starty"); - realizable.startingY = atoi(reinterpret_cast(key)); + realizable.startingPos.y() = atoi(reinterpret_cast(key)); xmlFree(key); key = getProp(top, "startmap"); @@ -260,11 +260,11 @@ EntityManager::id_type RealizingSystem::initSingleton( emplaceComponent(mapObject); key = getProp(mapNode, "x"); - transformable.origX = atoi(reinterpret_cast(key)); + transformable.origPos.x() = atoi(reinterpret_cast(key)); xmlFree(key); key = getProp(mapNode, "y"); - transformable.origY = atoi(reinterpret_cast(key)); + transformable.origPos.y() = atoi(reinterpret_cast(key)); xmlFree(key); // Set the sprite and size using the prototype definition. @@ -273,17 +273,17 @@ EntityManager::id_type RealizingSystem::initSingleton( xmlFree(key); key = getProp(prototypeNode, "width"); - transformable.origW = atoi(reinterpret_cast(key)); + transformable.origSize.w() = atoi(reinterpret_cast(key)); xmlFree(key); key = getProp(prototypeNode, "height"); - transformable.origH = atoi(reinterpret_cast(key)); + transformable.origSize.h() = atoi(reinterpret_cast(key)); xmlFree(key); AnimationSet objectAnim( spritePath.c_str(), - transformable.origW, - transformable.origH, + transformable.origSize.w(), + transformable.origSize.h(), 1); objectAnim.emplaceAnimation("static", 0, 1, 1); @@ -503,10 +503,8 @@ void RealizingSystem::loadMap(id_type mapEntity) auto& transformable = game_.getEntityManager(). getComponent(prototype); - transformable.x = transformable.origX; - transformable.y = transformable.origY; - transformable.w = transformable.origW; - transformable.h = transformable.origH; + transformable.pos = transformable.origPos; + transformable.size = transformable.origSize; } if (game_.getEntityManager().hasComponent(prototype)) diff --git a/src/vector.h b/src/vector.h new file mode 100644 index 0000000..3abd98a --- /dev/null +++ b/src/vector.h @@ -0,0 +1,111 @@ +#ifndef COORDINATES_H_A45D34FB +#define COORDINATES_H_A45D34FB + +template +class vec2 { +public: + + T coords[2]; + + vec2() = default; + + vec2(double x, double y) : coords{x, y} + { + } + + inline T& x() + { + return coords[0]; + } + + inline const T& x() const + { + return coords[0]; + } + + inline T& w() + { + return coords[0]; + } + + inline const T& w() const + { + return coords[0]; + } + + inline T& y() + { + return coords[1]; + } + + inline const T& y() const + { + return coords[1]; + } + + inline T& h() + { + return coords[1]; + } + + inline const T& h() const + { + return coords[1]; + } + + template + operator vec2() const + { + return vec2(x(), y()); + } + + vec2 operator+(const vec2& other) const + { + return vec2(x() + other.x(), y() + other.y()); + } + + vec2& operator+=(const vec2& other) + { + x() += other.x(); + y() += other.y(); + + return *this; + } + + vec2 operator-(const vec2& other) const + { + return vec2(x() - other.x(), y() - other.y()); + } + + vec2 operator-=(const vec2& other) + { + x() -= other.x(); + y() -= other.y(); + + return *this; + } + + vec2 operator-() const + { + return vec2(-x(), -y()); + } + + vec2 operator*(double s) const + { + return vec2(x() * s, y() * s); + } + + vec2& operator*=(double s) + { + x() *= s; + y() *= s; + + return *this; + } + +}; + +using vec2d = vec2; +using vec2i = vec2; + +#endif /* end of include guard: COORDINATES_H_A45D34FB */ -- cgit 1.4.1 From 046ee24a341468e9b3ea2983a731dbce18b52ac6 Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Sun, 13 May 2018 11:00:02 -0400 Subject: Integrated RealizableComponent into RealizingSystem --- scripts/checkpoint.lua | 2 +- src/components/realizable.h | 74 ------------------------------- src/game.cpp | 3 +- src/systems/mapping.cpp | 8 +--- src/systems/playing.cpp | 26 ++++------- src/systems/pondering.cpp | 8 +--- src/systems/realizing.cpp | 105 ++++++++++++++++++-------------------------- src/systems/realizing.h | 66 ++++++++++++++++++++++------ src/systems/scripting.cpp | 45 +++++++------------ src/systems/scripting.h | 2 +- 10 files changed, 127 insertions(+), 212 deletions(-) delete mode 100644 src/components/realizable.h (limited to 'src/systems/playing.cpp') diff --git a/scripts/checkpoint.lua b/scripts/checkpoint.lua index 452f81d..a5c8c54 100644 --- a/scripts/checkpoint.lua +++ b/scripts/checkpoint.lua @@ -1,7 +1,7 @@ checkpoint = {} function checkpoint.OnTouch(id, player) - curMap = entity.new(realizing():singleton():realizable().activeMap) + curMap = entity.new(realizing().activeMap) if not player:playable().checkpointMapObject or not curMap:mappable().mapId == player:playable().checkpointMapId or diff --git a/src/components/realizable.h b/src/components/realizable.h deleted file mode 100644 index b749aeb..0000000 --- a/src/components/realizable.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef REALIZABLE_H_36D8D71E -#define REALIZABLE_H_36D8D71E - -#include "component.h" -#include -#include -#include "entity_manager.h" -#include "vector.h" - -class RealizableComponent : public Component { -public: - - using id_type = EntityManager::id_type; - - /** - * Path to the XML file containing the world definition. - * - * @managed_by RealizingSystem - */ - std::string worldFile; - - /** - * Path to the XML file containing the map object prototype definitions. - * - * @managed_by RealizingSystem - */ - std::string prototypeFile; - - /** - * Starting map and player location for a new game. - * - * @managed_by RealizingSystem - */ - int startingMapId; - vec2i startingPos; - - /** - * The set of map entities loaded by this entity. It is only intended for - * there to be one realizable entity, so this should contain all loaded maps. - * The realizable entity has ownership of the loaded maps. - * - * @managed_by RealizingSystem - */ - std::set maps; - - /** - * A lookup table that translates a map ID to the entity representing that - * loaded map. - * - * @managed_by RealizingSystem - */ - std::map entityByMapId; - - /** - * The entity ID of the currently active map. - * - * @managed_by RealizingSystem - */ - id_type activeMap; - - /** - * Whether or not a map has been activated yet. - * - * @managed_by RealizingSystem - */ - bool hasActiveMap = false; - - /** - * The entity ID of the currently active player. - */ - id_type activePlayer; -}; - -#endif /* end of include guard: REALIZABLE_H_36D8D71E */ diff --git a/src/game.cpp b/src/game.cpp index f2992e1..c76349f 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -32,7 +32,6 @@ void key_callback(GLFWwindow* window, int key, int, int action, int) Game::Game(std::mt19937& rng) : rng_(rng) { - systemManager_.emplaceSystem(*this); systemManager_.emplaceSystem(*this); systemManager_.emplaceSystem(*this); systemManager_.emplaceSystem(*this); @@ -42,7 +41,7 @@ Game::Game(std::mt19937& rng) : rng_(rng) systemManager_.emplaceSystem(*this); systemManager_.emplaceSystem(*this); - systemManager_.getSystem().initSingleton( + systemManager_.emplaceSystem(*this, "res/maps.xml", "res/entities.xml"); diff --git a/src/systems/mapping.cpp b/src/systems/mapping.cpp index d78c8fe..1275e11 100644 --- a/src/systems/mapping.cpp +++ b/src/systems/mapping.cpp @@ -1,6 +1,5 @@ #include "mapping.h" #include "components/mappable.h" -#include "components/realizable.h" #include "systems/realizing.h" #include "game.h" #include "consts.h" @@ -20,11 +19,8 @@ inline void addBoundary( void MappingSystem::render(Texture& texture) { - auto& realizable = game_.getEntityManager(). - getComponent( - game_.getSystemManager().getSystem().getSingleton()); - - id_type map = realizable.activeMap; + id_type map = + game_.getSystemManager().getSystem().getActiveMap(); auto& mappable = game_.getEntityManager(). getComponent(map); diff --git a/src/systems/playing.cpp b/src/systems/playing.cpp index dabc9a5..6652099 100644 --- a/src/systems/playing.cpp +++ b/src/systems/playing.cpp @@ -5,7 +5,6 @@ #include "components/playable.h" #include "components/controllable.h" #include "components/orientable.h" -#include "components/realizable.h" #include "systems/mapping.h" #include "systems/pondering.h" #include "systems/orienting.h" @@ -36,13 +35,10 @@ void PlayingSystem::initPlayer() auto& realizing = game_.getSystemManager().getSystem(); - auto& realizable = game_.getEntityManager(). - getComponent(realizing.getSingleton()); - auto& transformable = game_.getEntityManager(). emplaceComponent(player); - transformable.pos = realizable.startingPos; + transformable.pos = realizing.getStartingPos(); transformable.size.w() = 10; transformable.size.h() = 12; @@ -56,13 +52,13 @@ void PlayingSystem::initPlayer() auto& playable = game_.getEntityManager(). emplaceComponent(player); - playable.mapId = realizable.activeMap; - playable.checkpointMapId = realizable.startingMapId; - playable.checkpointPos = realizable.startingPos; + playable.mapId = realizing.getActiveMap(); + playable.checkpointMapId = realizing.getStartingMapId(); + playable.checkpointPos = realizing.getStartingPos(); realizing.enterActiveMap(player); - realizable.activePlayer = player; + realizing.setActivePlayer(player); } void PlayingSystem::changeMap( @@ -77,20 +73,16 @@ void PlayingSystem::changeMap( getComponent(player); auto& pondering = game_.getSystemManager().getSystem(); - auto& realizing = game_.getSystemManager().getSystem(); - auto& realizable = game_.getEntityManager(). - getComponent(realizing.getSingleton()); - - id_type newMapEntity = realizable.entityByMapId[mapId]; + id_type newMapEntity = realizing.getEntityByMapId(mapId); if (playable.mapId != newMapEntity) { - if (playable.mapId == realizable.activeMap) + if (playable.mapId == realizing.getActiveMap()) { realizing.leaveActiveMap(player); - } else if (newMapEntity == realizable.activeMap) + } else if (newMapEntity == realizing.getActiveMap()) { realizing.enterActiveMap(player); } @@ -102,7 +94,7 @@ void PlayingSystem::changeMap( transformable.pos = warpPos; - if (realizable.activePlayer == player) + if (realizing.getActivePlayer() == player) { realizing.loadMap(newMapEntity); } diff --git a/src/systems/pondering.cpp b/src/systems/pondering.cpp index a3eb36d..d841679 100644 --- a/src/systems/pondering.cpp +++ b/src/systems/pondering.cpp @@ -6,7 +6,6 @@ #include "components/transformable.h" #include "components/orientable.h" #include "components/mappable.h" -#include "components/realizable.h" #include "components/playable.h" #include "systems/orienting.h" #include "systems/playing.h" @@ -485,11 +484,8 @@ void PonderingSystem::detectCollisionsInDirection( CollisionResult& result) { // Get map data. - auto& realizable = game_.getEntityManager(). - getComponent( - game_.getSystemManager().getSystem().getSingleton()); - - id_type mapEntity = realizable.activeMap; + id_type mapEntity = + game_.getSystemManager().getSystem().getActiveMap(); auto& mappable = game_.getEntityManager(). getComponent(mapEntity); diff --git a/src/systems/realizing.cpp b/src/systems/realizing.cpp index 2ee5897..7f5aefb 100644 --- a/src/systems/realizing.cpp +++ b/src/systems/realizing.cpp @@ -6,7 +6,6 @@ #include "game.h" #include "consts.h" #include "animation.h" -#include "components/realizable.h" #include "components/mappable.h" #include "components/animatable.h" #include "components/playable.h" @@ -30,25 +29,21 @@ inline xmlChar* getProp(xmlNodePtr node, const char* attr) } // TODO: neither the XML doc nor any of the emplaced entities are properly -// destroyed if this method throws an exception. -EntityManager::id_type RealizingSystem::initSingleton( +// destroyed if this constructor throws an exception. +RealizingSystem::RealizingSystem( + Game& game, std::string worldFile, - std::string prototypeFile) + std::string prototypeFile) : + System(game), + worldFile_(std::move(worldFile)), + prototypeFile_(std::move(prototypeFile)) { - id_type world = game_.getEntityManager().emplaceEntity(); - - auto& realizable = game_.getEntityManager(). - emplaceComponent(world); - - realizable.worldFile = worldFile; - realizable.prototypeFile = prototypeFile; - auto& mapping = game_.getSystemManager().getSystem(); xmlChar* key = nullptr; // Create a mapping between prototype names and the XML trees defining them. - xmlDocPtr protoXml = xmlParseFile(prototypeFile.c_str()); + xmlDocPtr protoXml = xmlParseFile(prototypeFile_.c_str()); if (protoXml == nullptr) { throw std::invalid_argument("Cannot find prototypes file"); @@ -82,7 +77,7 @@ EntityManager::id_type RealizingSystem::initSingleton( } // Create entities from the world definition. - xmlDocPtr doc = xmlParseFile(worldFile.c_str()); + xmlDocPtr doc = xmlParseFile(worldFile_.c_str()); if (doc == nullptr) { throw std::invalid_argument("Cannot find world file"); @@ -100,15 +95,15 @@ EntityManager::id_type RealizingSystem::initSingleton( } key = getProp(top, "startx"); - realizable.startingPos.x() = atoi(reinterpret_cast(key)); + startingPos_.x() = atoi(reinterpret_cast(key)); xmlFree(key); key = getProp(top, "starty"); - realizable.startingPos.y() = atoi(reinterpret_cast(key)); + startingPos_.y() = atoi(reinterpret_cast(key)); xmlFree(key); key = getProp(top, "startmap"); - realizable.startingMapId = atoi(reinterpret_cast(key)); + startingMapId_ = atoi(reinterpret_cast(key)); xmlFree(key); for (xmlNodePtr node = top->xmlChildrenNode; @@ -291,78 +286,62 @@ EntityManager::id_type RealizingSystem::initSingleton( mapping.generateBoundaries(map); - realizable.maps.insert(map); - realizable.entityByMapId[mappable.mapId] = map; + entityByMapId_[mappable.mapId] = map; } } xmlFreeDoc(doc); xmlFreeDoc(protoXml); - loadMap(realizable.entityByMapId[realizable.startingMapId]); - - return world; + activateMap(entityByMapId_[startingMapId_]); } -EntityManager::id_type RealizingSystem::getSingleton() const +void RealizingSystem::loadMap(id_type mapEntity) { - std::set result = - game_.getEntityManager().getEntitiesWithComponents< - RealizableComponent>(); - - if (result.empty()) - { - throw std::logic_error("No realizable entity found"); - } else if (result.size() > 1) - { - throw std::logic_error("Multiple realizable entities found"); - } - - return *std::begin(result); + deactivateMap(); + activateMap(mapEntity); } -void RealizingSystem::loadMap(id_type mapEntity) +void RealizingSystem::deactivateMap() { - id_type world = getSingleton(); + id_type oldMap = activeMap_; - auto& realizable = game_.getEntityManager(). - getComponent(world); + auto& oldMappable = game_.getEntityManager(). + getComponent(oldMap); - auto& animating = game_.getSystemManager().getSystem(); - auto& pondering = game_.getSystemManager().getSystem(); + // Deactivate any map objects from the old map. + for (id_type prototype : oldMappable.objects) + { + leaveActiveMap(prototype); + } + // Deactivate players that were on the old map. std::set players = game_.getEntityManager().getEntitiesWithComponents< PlayableComponent>(); - if (realizable.hasActiveMap) + for (id_type player : players) { - id_type oldMap = realizable.activeMap; - - auto& oldMappable = game_.getEntityManager(). - getComponent(oldMap); + auto& playable = game_.getEntityManager(). + getComponent(player); - // Deactivate any map objects from the old map. - for (id_type prototype : oldMappable.objects) + if (playable.mapId == oldMap) { - leaveActiveMap(prototype); + leaveActiveMap(player); } + } +} - // Deactivate players that were on the old map. - for (id_type player : players) - { - auto& playable = game_.getEntityManager(). - getComponent(player); +void RealizingSystem::activateMap(id_type mapEntity) +{ + auto& animating = game_.getSystemManager().getSystem(); + auto& pondering = game_.getSystemManager().getSystem(); - if (playable.mapId == oldMap) - { - leaveActiveMap(player); - } - } - } + std::set players = + game_.getEntityManager().getEntitiesWithComponents< + PlayableComponent>(); - realizable.hasActiveMap = true; - realizable.activeMap = mapEntity; + activeMap_ = mapEntity; auto& mappable = game_.getEntityManager(). getComponent(mapEntity); diff --git a/src/systems/realizing.h b/src/systems/realizing.h index 595c58f..ab5a150 100644 --- a/src/systems/realizing.h +++ b/src/systems/realizing.h @@ -2,29 +2,56 @@ #define REALIZING_H_6853748C #include +#include #include "system.h" +#include "vector.h" class RealizingSystem : public System { public: - RealizingSystem(Game& game) : System(game) - { - } - /** - * Creates the singleton realizable entity and initializes it with the - * provided world definition and map object prototype definition. + * Constructs the realizing system. + * + * Note that this must be constructed after the following system: + * - Mapping + * - Animating + * - Pondering + * - Scripting */ - id_type initSingleton( + RealizingSystem( + Game& game, std::string worldFile, std::string prototypeFile); - /** - * Helper method that returns the entity ID of the (assumed) singleton entity - * with a RealizableComponent. Throws an exception if the number of realizable - * entities is not exactly one. - */ - id_type getSingleton() const; + id_type getActiveMap() const + { + return activeMap_; + } + + int getStartingMapId() const + { + return startingMapId_; + } + + vec2i getStartingPos() const + { + return startingPos_; + } + + id_type getEntityByMapId(size_t mapId) const + { + return entityByMapId_.at(mapId); + } + + id_type getActivePlayer() const + { + return activePlayer_; + } + + void setActivePlayer(id_type entity) + { + activePlayer_ = entity; + } /** * Loads the given map. @@ -41,6 +68,19 @@ public: */ void leaveActiveMap(id_type entity); +private: + + void deactivateMap(); + + void activateMap(id_type mapEntity); + + std::string worldFile_; + std::string prototypeFile_; + int startingMapId_; + vec2i startingPos_; + std::map entityByMapId_; + id_type activeMap_; + id_type activePlayer_; }; #endif /* end of include guard: REALIZING_H_6853748C */ diff --git a/src/systems/scripting.cpp b/src/systems/scripting.cpp index dc1fff5..57c3fd5 100644 --- a/src/systems/scripting.cpp +++ b/src/systems/scripting.cpp @@ -2,7 +2,6 @@ #include "game.h" #include "components/runnable.h" #include "components/ponderable.h" -#include "components/realizable.h" #include "components/transformable.h" #include "components/playable.h" #include "components/mappable.h" @@ -24,9 +23,9 @@ ScriptingSystem::ScriptingSystem(Game& game) : System(game) { id_type entity = game_.getEntityManager().emplaceEntity(); - engine.open_libraries(sol::lib::base, sol::lib::coroutine); + engine_.open_libraries(sol::lib::base, sol::lib::coroutine); - engine.new_usertype( + engine_.new_usertype( "vec2d", sol::constructors(), "x", sol::property( @@ -36,13 +35,13 @@ ScriptingSystem::ScriptingSystem(Game& game) : System(game) [] (vec2d& v) -> double { return v.y(); }, [] (vec2d& v, double y) { v.y() = y; })); - engine.new_usertype( + engine_.new_usertype( "vec2i", sol::constructors(), "x", [] (vec2i& v) -> int& { return v.x(); }, "y", [] (vec2i& v) -> int& { return v.y(); }); - engine.new_usertype( + engine_.new_usertype( "entity", sol::constructors(), "id", &script_entity::id, @@ -66,62 +65,50 @@ ScriptingSystem::ScriptingSystem(Game& game) : System(game) return game_.getEntityManager(). getComponent(entity.id); }, - "realizable", - [&] (script_entity& entity) -> RealizableComponent& { - return game_.getEntityManager(). - getComponent(entity.id); - }, "prototypable", [&] (script_entity& entity) -> PrototypableComponent& { return game_.getEntityManager(). getComponent(entity.id); }); - engine.new_usertype( + engine_.new_usertype( "transformable", "pos", &TransformableComponent::pos); - engine.new_usertype( + engine_.new_usertype( "ponderable", "vel", &PonderableComponent::vel, "accel", &PonderableComponent::accel); - engine.new_usertype( + engine_.new_usertype( "mappable", "mapId", &MappableComponent::mapId); - engine.new_usertype( + engine_.new_usertype( "playable", "checkpointPos", &PlayableComponent::checkpointPos, "checkpointMapId", &PlayableComponent::checkpointMapId, "checkpointMapObject", &PlayableComponent::checkpointMapObject, "checkpointMapObjectIndex", &PlayableComponent::checkpointMapObjectIndex); - engine.new_usertype( - "realizable", - "activeMap", &RealizableComponent::activeMap); - - engine.new_usertype( + engine_.new_usertype( "prototypable", "mapObjectIndex", &PrototypableComponent::mapObjectIndex, "prototypeId", &PrototypableComponent::prototypeId); - engine.new_usertype( + engine_.new_usertype( "realizing", - "singleton", - [&] (RealizingSystem& realizing) -> script_entity { - return realizing.getSingleton(); - }); + "activeMap", sol::property(&RealizingSystem::getActiveMap)); - engine.set_function( + engine_.set_function( "realizing", [&] () { return game_.getSystemManager().getSystem(); }); - engine.script_file("scripts/common.lua"); - engine.script_file("scripts/movplat.lua"); - engine.script_file("scripts/checkpoint.lua"); + engine_.script_file("scripts/common.lua"); + engine_.script_file("scripts/movplat.lua"); + engine_.script_file("scripts/checkpoint.lua"); } void ScriptingSystem::tick(double dt) @@ -177,7 +164,7 @@ EntityManager::id_type ScriptingSystem::runScript( std::unique_ptr( new sol::thread( sol::thread::create( - engine.lua_state()))); + engine_.lua_state()))); runnable.callable = std::unique_ptr( diff --git a/src/systems/scripting.h b/src/systems/scripting.h index d5380f1..e330316 100644 --- a/src/systems/scripting.h +++ b/src/systems/scripting.h @@ -22,7 +22,7 @@ private: template id_type runScript(std::string event, id_type entity, Args&&... args); - sol::state engine; + sol::state engine_; }; #endif /* end of include guard: AUTOMATING_H_E6E5D76E */ -- cgit 1.4.1