0
0
mirror of https://github.com/Nimac0/SDL_Minigame synced 2026-01-12 07:53:43 +00:00

Merge branch 'interactions-v2' into dev

This commit is contained in:
Nimac0 2025-04-09 21:13:16 +02:00
commit 7a3c845c40
27 changed files with 994 additions and 195 deletions

2
extern/SDL vendored

@ -1 +1 @@
Subproject commit e027b85cc457556071cbb2f3f1bcf8803c1bc001 Subproject commit f6864924f76e1a0b4abaefc76ae2ed22b1a8916e

View File

@ -35,85 +35,90 @@ class Entity
{ {
public: public:
/*! /*!
* \brief Used for rendering order (last is highest) or retrieving entities of group * \brief Used for rendering order (last is highest) or retrieving entities of group
* \todo Label used in singular entity shouldn't use plural * \todo Label used in singular entity shouldn't use plural
* \todo HEARTS are rendered above POWERUPS, missleading order * \todo HEARTS are rendered above POWERUPS, missleading order
* \todo PROJECTILE are rendered above POWERUPS, missleading order * \todo PROJECTILE are rendered above POWERUPS, missleading order
* \todo Generalize HEARTS as UI or similar * \todo Generalize HEARTS as UI or similar
*/ */
enum class GroupLabel enum class GroupLabel
{ {
MAPTILES, //!< Entity using TileComponent MAPTILES, //!< Entity using TileComponent
PLAYERS, //!< Primary entity in player controll PLAYERS, //!< Primary entity in player controll
ENEMIES, //!< \deprecated All players now grouped as Entity::PLAYERS ENEMIES, //!< \deprecated All players now grouped as Entity::PLAYERS
COLLIDERS, //!< Fixed collider entity, e.g. a wall COLLIDERS, //!< Fixed collider entity, e.g. a wall
PROJECTILE, //!< \todo Document PROJECTILE, //!< \todo Document
HEARTS, //!< \todo Document HEARTS, //!< \todo Document
POWERUPS //!< \todo Document POWERUPS //!< \todo Document
}; };
/*! /*!
* \todo Document * \todo Document
*/ */
explicit Entity(Manager& mManager) : explicit Entity(Manager& mManager) :
manager(mManager) { }; manager(mManager) { };
void update(uint_fast16_t diffTime) const; //!< Call each frame to update all components void update(uint_fast16_t diffTime) const; //!< Call each frame to update all components
bool isActive() const { return this->active; } //!< \sa destroy() bool isActive() const { return this->active; } //!< \sa destroy()
//! Mark for destruction for Manager::refresh() and disables collision //! Mark for destruction for Manager::refresh() and disables collision
//! \sa ColliderComponent //! \sa ColliderComponent
void destroy() { void destroy() {
this->active = false; this->active = false;
if (this->hasComponent<ColliderComponent>()) { if (this->hasComponent<ColliderComponent>()) {
this->getComponent<ColliderComponent>().removeCollision(); this->getComponent<ColliderComponent>().removeCollision();
} }
} }
bool hasGroup(Group mGroup); //!< \sa GroupLabel bool hasGroup(Group mGroup); //!< \sa GroupLabel
void addGroup(Group mGroup); //!< \sa GroupLabel void addGroup(Group mGroup); //!< \sa GroupLabel
void delGroup(Group mGroup); //!< \sa GroupLabel void delGroup(Group mGroup); //!< \sa GroupLabel
//! \returns bitset with true on position GroupLabel if the entity belongs to group //! \returns bitset with true on position GroupLabel if the entity belongs to group
//! \sa GroupLabel //! \sa GroupLabel
std::bitset<MAX_GROUPS> getGroupBitSet(); std::bitset<MAX_GROUPS> getGroupBitSet();
//! \sa Manager //! \sa Manager
Manager& getManager() { return manager; }; Manager& getManager() { return manager; };
template <typename T> bool hasComponent() const //! \sa Component template <typename T> bool hasComponent() const //! \sa Component
{ {
return componentBitSet[getComponentTypeID<T>()]; return componentBitSet[getComponentTypeID<T>()];
} }
//! \brief Adds specified type as component and calls Component::init() //! \brief Adds specified type as component and calls Component::init()
//! \param mArgs Constructor arguments of component //! \param mArgs Constructor arguments of component
template <typename T, typename...TArgs> T& addComponent(TArgs&&...mArgs) template <typename T, typename...TArgs> T& addComponent(TArgs&&...mArgs)
{ {
T* c(new T(std::forward<TArgs>(mArgs)...)); T* c(new T(std::forward<TArgs>(mArgs)...));
c->entity = this; c->entity = this;
std::unique_ptr<Component> uPtr{ c }; std::shared_ptr<Component> uPtr{ c };
this->components.emplace_back(std::move(uPtr)); this->components.at(getComponentTypeID<T>()) = std::move(uPtr);
componentArray[getComponentTypeID<T>()] = c; componentArray[getComponentTypeID<T>()] = c;
componentBitSet[getComponentTypeID<T>()] = true; componentBitSet[getComponentTypeID<T>()] = true;
c->init(); c->init();
return *c; return *c;
}; };
template <typename T> T& getComponent() const //!< \todo: rewrite to use optionals template <typename T> T& getComponent() const //!< \todo: rewrite to use optionals
{ {
auto ptr(componentArray[getComponentTypeID<T>()]); auto ptr(componentArray[getComponentTypeID<T>()]);
return *static_cast<T*>(ptr); return *static_cast<T*>(ptr);
} }
template <typename T> std::shared_ptr<T> getComponentAsPointer() const
{
return std::static_pointer_cast<T>(components.at(getComponentTypeID<T>()));
}
private: private:
Manager& manager; Manager& manager;
bool active = true; bool active = true;
std::vector<std::unique_ptr<Component>> components; std::array<std::shared_ptr<Component>, MAX_COMPONENTS> components;
ComponentArray componentArray = {}; ComponentArray componentArray = {};
ComponentBitSet componentBitSet; ComponentBitSet componentBitSet;
GroupBitSet groupBitSet; GroupBitSet groupBitSet;
}; };

21
include/EventManager.h Normal file
View File

@ -0,0 +1,21 @@
#pragma once
#include <functional>
#include <initializer_list>
#include <map>
#include <vector>
#include "SDL3/SDL_events.h"
#include "SDL3/SDL_init.h"
typedef std::function<SDL_AppResult(SDL_EventType, SDL_Event* const)> EventListener;
class EventManager {
public:
EventManager();
void registerListener(EventListener listener, std::initializer_list<Uint32> eventTypes);
SDL_AppResult handleEvent(SDL_Event* const event);
private:
std::map<Uint32, std::vector<EventListener>> eventListeners = std::map<Uint32, std::vector<EventListener>>();
};

View File

@ -7,9 +7,14 @@
#include <functional> #include <functional>
#include <vector> #include <vector>
#include "EventManager.h"
#include "InteractionManager.h"
#include "Manager.h" #include "Manager.h"
#include "SDL3/SDL_events.h"
#include "SDL3/SDL_init.h"
#include "Vector2D.h" #include "Vector2D.h"
#include "Entity.h" #include "Entity.h"
#include "InputManager.h"
#include "RenderManager.h" #include "RenderManager.h"
#include "ConfigLoader.h" #include "ConfigLoader.h"
#include "PickupManager.h" #include "PickupManager.h"
@ -25,18 +30,18 @@ class Game;
class GameInternal class GameInternal
{ {
public: public:
GameInternal(); GameInternal();
~GameInternal(); ~GameInternal();
SDL_AppResult init(); SDL_AppResult init();
void handleEvents(); SDL_AppResult handleEvent(SDL_Event* event);
void update(Uint64 frameTime); void update(Uint64 frameTime);
void render(); void render();
void clean(); void clean();
bool isRunning() const; bool isRunning() const;
void setRunning(bool running); // TODO: should be private/not accesible for game dev void setRunning(bool running); // TODO: should be private/not accesible for game dev
void stopGame(); void stopGame();
/* static */ SDL_Renderer* renderer = nullptr; /* static */ SDL_Renderer* renderer = nullptr;
/* static */ SDL_Event event; /* static */ SDL_Event event;
@ -44,29 +49,32 @@ public:
/* static */ PickupManager* pickupManager; /* static */ PickupManager* pickupManager;
/* static */ TextureManager* textureManager; /* static */ TextureManager* textureManager;
/* static */ SoundManager* soundManager; /* static */ SoundManager* soundManager;
/* static */ InputManager* inputManager;
RenderManager* renderManager;
EventManager* eventManager;
InteractionManager* interactionManager;
Manager manager; Manager manager;
RenderManager renderManager;
Map* map; // game specific, might not be needed for all types of games Map* map; // game specific, might not be needed for all types of games
ConfigLoader* config; ConfigLoader* config;
std::vector<Entity*>& tiles; std::vector<Entity*>& tiles;
std::vector<Entity*>& players; std::vector<Entity*>& players;
std::vector<Entity*>& projectiles; std::vector<Entity*>& projectiles;
std::vector<Entity*>& hearts; std::vector<Entity*>& hearts;
std::vector<Entity*>& powerups; std::vector<Entity*>& powerups;
// end moved globals // end moved globals
void refreshPlayers(); void refreshPlayers();
private: private:
Game* gameInstance; Game* gameInstance;
int counter = 0; int counter = 0;
bool running = true; bool running = true;
SDL_Window* window; SDL_Window* window;
Uint64 lastFrameTime = 0; Uint64 lastFrameTime = 0;
}; };

139
include/InputManager.h Normal file
View File

@ -0,0 +1,139 @@
#pragma once
#include <SDL3/SDL_events.h>
#include <SDL3/SDL_init.h>
#include <SDL3/SDL.h>
#include <map>
#include <string>
#include <functional>
#include <vector>
#include <iostream>
class InputManager {
public:
enum class EventType {
KeyDown,
KeyUp
};
enum class Key
{
UP,
DOWN,
LEFT,
RIGHT,
SPACE,
ENTER,
ESCAPE,
TAB,
BACKSPACE,
DELETE,
HOME,
END,
PAGE_UP,
PAGE_DOWN,
INSERT,
CAPS_LOCK,
LEFT_SHIFT,
RIGHT_SHIFT,
LEFT_CTRL,
RIGHT_CTRL,
LEFT_ALT,
RIGHT_ALT,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
NUM_0,
NUM_1,
NUM_2,
NUM_3,
NUM_4,
NUM_5,
NUM_6,
NUM_7,
NUM_8,
NUM_9,
LEFT_BRACKET,
RIGHT_BRACKET,
SEMICOLON,
APOSTROPHE,
COMMA,
PERIOD,
SLASH,
BACKSLASH,
GRAVE
};
struct InputAction {
std::string name;
std::vector<Key> bindings;
std::function<void(bool)> callback;
};
InputManager();
~InputManager();
void init(); // see if necessary
void processEvents();
void registerAction(const std::string& actionName, const std::vector<Key>& keys, std::function<void(bool)> callback, const std::string& context);
void setActiveContext(const std::string& context);
std::string getActiveContext() const;
//void rebindAction(const std::string& actionName, const std::vector<Key>& newBindings, const std::string& context);
//void removeBindings(const std::string& actionName, const std::string& context);
//std::vector<Key> getBindings(const std::string& actionName, const std::string& context) const;
std::vector<InputAction*> getActionsByKey(const Key key) const;
SDL_AppResult handleEvent(SDL_EventType type, SDL_Event* const event);
void initKeyMap();
private:
// TODO: flesh this out to avoid loops in process actions
// additionally to actionsByContext, not instead
std::map<std::string, std::map<Key, std::vector<InputAction*>>> actionsByContextAndKey;
std::map<Key, SDL_Scancode> keyMap;
std::string activeContext;
};
std::ostream& operator<<(std::ostream& os, InputManager::Key key);
std::ostream& operator<<(std::ostream& os, const InputManager::InputAction& action);
std::ostream& operator<<(std::ostream& os, const InputManager::InputAction* action);
std::ostream& operator<<(std::ostream& os, const std::vector<InputManager::InputAction>& actions);
std::ostream& operator<<(std::ostream& os, const std::vector<InputManager::InputAction*>& actions);

View File

@ -0,0 +1,28 @@
#pragma once
#include "Component.h"
#include "InteractionListener.h"
#include <functional>
class InteractionComponent : public Component, public InteractionListener
{
public:
/**
* @brief Constructor for the InteractionComponent.
* @param callback A function to be called when an interaction event is triggered. void* actor, void* data are passed to the callback function from InteractionEventdataStruct.
*/
InteractionComponent(std::function<void(void*,void*)> callback);
/**
* @brief Internal function to be called when an interaction event is triggered.
*/
void interact(void* actor, void* data) override;
/**
* @brief Internal function to use as reference for targeting.
*/
std::shared_ptr<Vector2D> getPosition() override;
private:
std::function<void(void*,void*)> interactionCallback;
};

View File

@ -0,0 +1,28 @@
#pragma once
#include "Entity.h"
#include "InteractionListener.h"
#include "InteractionManager.h"
#include "Vector2D.h"
#include <cstdint>
#include <memory>
/**
* @brief Struct to hold data for interaction events.
* This struct is used to pass data to the interaction manager when an interaction event is triggered.
*/
struct InteractionEventdataStruct {
/// Arbitray data to pass to the interaction listener. Can for example be an Entity ptr to represent the actor.
void* actor;
/// The data to pass to the interaction listener. Can be any type of pointer.
void* data;
/// The target of the interaction, e.g. InteractionComponent of an Entity. Is required if strategy is set to 0 (none)
std::weak_ptr<InteractionListener> target = std::weak_ptr<InteractionListener>();
/// Coordinates from which to base targeting on. Is required if strategy is not set to 0 (none)
std::shared_ptr<Vector2D> targetingReference = nullptr;
/// required without explicit target, defaults to none
/// @sa InteractionManager::TargetingStrategy
uint8_t strategy = 0; // int since enum would be impossibling user defined targetingStrategies
void triggerEvent();
};

View File

@ -0,0 +1,17 @@
#pragma once
#include "Vector2D.h"
#include <memory>
class InteractionListener {
public:
InteractionListener() { };
virtual ~InteractionListener() { };
virtual void interact(void* actor, void* data) = 0;
virtual std::shared_ptr<Vector2D> getPosition() // required for targeting strategy, return null to only allow explicit targeting
{
return nullptr;
}
};

View File

@ -0,0 +1,35 @@
#pragma once
#include "InteractionListener.h"
#include "SDL3/SDL_events.h"
#include "SDL3/SDL_init.h"
#include <cstdint>
#include <functional>
#include <memory>
#include <vector>
#include <ranges>
// TODO: ranges concept to avoid to<vector> in cpp
typedef std::function<std::shared_ptr<InteractionListener>(Vector2D*, std::vector<std::shared_ptr<InteractionListener>>)> TargetingFunc;
class InteractionManager {
public:
InteractionManager();
InteractionManager (const InteractionManager&) = delete;
InteractionManager& operator= (const InteractionManager&) = delete;
enum class TargetingStrategy : uint8_t {
none = 0,
closest,
manhattenDistance
};
SDL_AppResult handleInteract(SDL_EventType type, SDL_Event* const event);
void registerListener(std::weak_ptr<InteractionListener> listener);
uint8_t registerTargetingFunc(TargetingFunc func);
private:
std::vector<std::weak_ptr<InteractionListener>> listeners;
std::array<TargetingFunc, 256> targetingFuncs;
};

View File

@ -13,8 +13,8 @@ public:
PickupComponent(std::function<void (Entity*)> func); PickupComponent(std::function<void (Entity*)> func);
~PickupComponent() {}; ~PickupComponent() {};
void update(uint_fast16_t diffTime) override; void update(uint_fast16_t diffTime) override;
private: private:
std::function<void (Entity*)> pickupFunc; std::function<void (Entity*)> pickupFunc;
}; };

View File

@ -7,7 +7,7 @@ class RenderObject
public: public:
virtual void draw() = 0; virtual void draw() = 0;
RenderObject(int zIndex, RenderManager& renderManager); RenderObject(int zIndex, RenderManager* renderManager);
~RenderObject(); ~RenderObject();
int getZIndex() { return this->zIndex; }; int getZIndex() { return this->zIndex; };
@ -23,5 +23,5 @@ private:
int zIndex = 0; int zIndex = 0;
protected: protected:
RenderManager& renderManager; RenderManager* renderManager;
}; };

View File

@ -40,6 +40,11 @@ private:
const char* path; //!< empty string if texture has a texture enum value, otherwise the path of the texture const char* path; //!< empty string if texture has a texture enum value, otherwise the path of the texture
public: public:
//debug
Textures getTexture() { return this->textureEnum; }
SpriteComponent(Textures texture, int zIndex); SpriteComponent(Textures texture, int zIndex);
SpriteComponent(Textures texture, int xOffset, int yOffset, int zIndex); SpriteComponent(Textures texture, int xOffset, int yOffset, int zIndex);
SpriteComponent(const char* path, int xOffset, int yOffset, int zIndex); SpriteComponent(const char* path, int xOffset, int yOffset, int zIndex);

View File

@ -83,9 +83,15 @@ class TextureManager
*/ */
SDL_Texture* loadMapTileTexture(const char* path); SDL_Texture* loadMapTileTexture(const char* path);
std::string getTexturePath(Textures texture) {
return this->texture_references.at(texture);
}
private: private:
SDL_ScaleMode scaleMode = SDL_SCALEMODE_NEAREST; SDL_ScaleMode scaleMode = SDL_SCALEMODE_NEAREST;
Manager* manager; Manager* manager;
std::map<Textures, SDL_Texture*> texture_cache; std::map<Textures, SDL_Texture*> texture_cache;
std::map<std::string, SDL_Texture*> mapTile_texture_cache; std::map<std::string, SDL_Texture*> mapTile_texture_cache;
std::map<Textures, std::string> texture_references;
}; };

7
include/VEGO_Event.h Normal file
View File

@ -0,0 +1,7 @@
#pragma once
#include <SDL3/SDL_stdinc.h>
namespace vego {
extern Uint32 VEGO_Event_Interaction;
}

View File

@ -6,7 +6,9 @@
void Entity::update(uint_fast16_t diffTime) const void Entity::update(uint_fast16_t diffTime) const
{ {
for (auto const& c : components) c->update(diffTime); for (auto const& c : components)
if (c)
c->update(diffTime);
} }
bool Entity::hasGroup(Group mGroup) bool Entity::hasGroup(Group mGroup)

44
src/EventManager.cpp Normal file
View File

@ -0,0 +1,44 @@
#include "EventManager.h"
#include "SDL3/SDL_events.h"
#include "SDL3/SDL_init.h"
#include "SDL3/SDL_stdinc.h"
#include "VEGO_Event.h"
#include <algorithm>
#include <functional>
#include <ranges>
#include <vector>
Uint32 vego::VEGO_Event_Interaction;
EventManager::EventManager()
{
/// \TODO: from c++26 you (should be able to) can get the amount of name values in an enum
vego::VEGO_Event_Interaction = SDL_RegisterEvents(1); // TODO: error handling
}
void EventManager::registerListener(EventListener listener, std::initializer_list<Uint32> eventTypes)
{
std::ranges::for_each(eventTypes.begin(), eventTypes.end(), [this, &listener](const Uint32& eventType) {
if (!this->eventListeners.contains(eventType)) {
this->eventListeners.insert({eventType, std::vector<EventListener>()});
}
this->eventListeners.at(eventType).emplace_back(listener);
});
}
SDL_AppResult EventManager::handleEvent(SDL_Event* event)
{
SDL_EventType type = (SDL_EventType) event->type;
if (this->eventListeners.contains(type)) {
std::vector<SDL_AppResult> results;
for (auto& listener : this->eventListeners.at(type)) {
results.emplace_back(listener((SDL_EventType) event->type, event));
}
if (std::ranges::contains(results, SDL_APP_FAILURE))
return SDL_APP_FAILURE;
if (std::ranges::contains(results, SDL_APP_SUCCESS))
return SDL_APP_SUCCESS;
}
return SDL_APP_CONTINUE;
}

View File

@ -1,9 +1,14 @@
#include "GameInternal.h" #include "GameInternal.h"
#include "CollisionHandler.h" #include "CollisionHandler.h"
#include "EventManager.h"
#include "InputManager.h"
#include "InteractionManager.h"
#include "RenderManager.h" #include "RenderManager.h"
#include <SDL3_mixer/SDL_mixer.h> #include <SDL3_mixer/SDL_mixer.h>
#include "SDL3/SDL_events.h"
#include "SDL3/SDL_init.h" #include "SDL3/SDL_init.h"
#include "SDL3/SDL_oldnames.h"
#include "SoundManager.h" #include "SoundManager.h"
#include "Entity.h" #include "Entity.h"
#include "HealthComponent.h" #include "HealthComponent.h"
@ -13,158 +18,165 @@
#include "GameFactory.h" #include "GameFactory.h"
#include <VEGO.h> #include <VEGO.h>
#include <VEGO_Event.h>
#include <functional>
#include "ConfigLoader.h" #include "ConfigLoader.h"
GameInternal::GameInternal() : GameInternal::GameInternal() :
manager(this), manager(this),
renderManager(), tiles(manager.getGroup((size_t)Entity::GroupLabel::MAPTILES)),
tiles(manager.getGroup((size_t)Entity::GroupLabel::MAPTILES)), players(manager.getGroup((size_t)Entity::GroupLabel::PLAYERS)),
players(manager.getGroup((size_t)Entity::GroupLabel::PLAYERS)), projectiles(manager.getGroup((size_t)Entity::GroupLabel::PROJECTILE)),
projectiles(manager.getGroup((size_t)Entity::GroupLabel::PROJECTILE)), hearts(manager.getGroup((size_t)Entity::GroupLabel::HEARTS)),
hearts(manager.getGroup((size_t)Entity::GroupLabel::HEARTS)), powerups(manager.getGroup((size_t)Entity::GroupLabel::POWERUPS))
powerups(manager.getGroup((size_t)Entity::GroupLabel::POWERUPS))
{}; {};
GameInternal::~GameInternal() = default; GameInternal::~GameInternal() = default;
SDL_AppResult GameInternal::init() SDL_AppResult GameInternal::init()
{ {
config = new ConfigLoader(); config = new ConfigLoader();
this->gameInstance = GameFactory::instance().create(this); this->gameInstance = GameFactory::instance().create(this);
config->setCustomConfig(this->gameInstance->setConfigFilePath()); config->setCustomConfig(this->gameInstance->setConfigFilePath());
config->init(); config->init();
json finalConfig = config->getFinalConfig();
json finalConfig = config->getFinalConfig();
GameInternal::pickupManager = new PickupManager(&manager); GameInternal::pickupManager = new PickupManager(&manager);
GameInternal::textureManager = new TextureManager(&manager); GameInternal::textureManager = new TextureManager(&manager);
GameInternal::soundManager = new SoundManager(); GameInternal::soundManager = new SoundManager();
GameInternal::collisionHandler = new CollisionHandler(manager); //why no pointer? GameInternal::collisionHandler = new CollisionHandler(manager); // why does this use a referrence, but AssetManager a pointer?
GameInternal::inputManager = new InputManager();
int flags = 0; GameInternal::inputManager->initKeyMap();
if (finalConfig.at("fullscreen"))
{
flags = SDL_WINDOW_FULLSCREEN;
}
if (!SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO)) GameInternal::renderManager = new RenderManager();
{ GameInternal::eventManager = new EventManager();
std::cout << "ERROR. Subsystem couldnt be initialized! " << SDL_GetError() << std::endl; GameInternal::interactionManager = new InteractionManager();
SDL_ClearError();
return SDL_APP_FAILURE;
}
if (Mix_Init(MIX_INIT_MP3) != MIX_INIT_MP3) { this->eventManager->registerListener(std::bind_front(&InputManager::handleEvent, this->inputManager), { SDL_EVENT_KEY_DOWN, SDL_EVENT_KEY_UP });
std::cout << "ERROR. Subsystem couldnt be initialized!" << std::endl; this->eventManager->registerListener(std::bind_front(&InteractionManager::handleInteract, VEGO_Game().interactionManager), { vego::VEGO_Event_Interaction });
return SDL_APP_FAILURE;
}
window = SDL_CreateWindow(finalConfig.at("title").get<std::string>().c_str(), int flags = 0;
finalConfig.at("screen_width"), finalConfig.at("screen_height"), flags); if (finalConfig.at("fullscreen"))
{
flags = SDL_WINDOW_FULLSCREEN;
}
if (!window) if (!SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO))
{ {
std::cout << "ERROR: Window couldnt be created! " << SDL_GetError() << std::endl; std::cout << "ERROR. Subsystem couldnt be initialized! " << SDL_GetError() << std::endl;
SDL_ClearError(); SDL_ClearError();
return SDL_APP_FAILURE; return SDL_APP_FAILURE;
} }
if (Mix_Init(MIX_INIT_MP3) != MIX_INIT_MP3) {
std::cout << "ERROR. Subsystem couldnt be initialized!" << std::endl;
return SDL_APP_FAILURE;
}
window = SDL_CreateWindow(finalConfig.at("title").get<std::string>().c_str(),
finalConfig.at("screen_width"), finalConfig.at("screen_height"), flags);
if (!window)
{
std::cout << "ERROR: Window couldnt be created! " << SDL_GetError() << std::endl;
SDL_ClearError();
return SDL_APP_FAILURE;
}
// bad // bad
SDL_Surface* icon; SDL_Surface* icon;
if((icon = SDL_LoadBMP(finalConfig.at("icon").get<std::string>().c_str()))) if((icon = SDL_LoadBMP(finalConfig.at("icon").get<std::string>().c_str())))
{ {
SDL_SetWindowIcon(window, icon); SDL_SetWindowIcon(window, icon);
} }
SDL_SetWindowIcon(window, icon); SDL_SetWindowIcon(window, icon);
renderer = SDL_CreateRenderer(window, NULL); renderer = SDL_CreateRenderer(window, NULL);
if (!renderer) if (!renderer)
{ {
std::cout << "ERROR: Renderer couldnt be created! " << SDL_GetError() << std::endl; std::cout << "ERROR: Renderer couldnt be created! " << SDL_GetError() << std::endl;
SDL_ClearError(); SDL_ClearError();
return SDL_APP_FAILURE; return SDL_APP_FAILURE;
} }
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
if (!Mix_OpenAudio(0, NULL)) if (!Mix_OpenAudio(0, NULL))
{ {
std::cout << "ERROR: Mixer couldnt be initialized! " << SDL_GetError() << std::endl; std::cout << "ERROR: Mixer couldnt be initialized! " << SDL_GetError() << std::endl;
SDL_ClearError(); SDL_ClearError();
return SDL_APP_FAILURE; return SDL_APP_FAILURE;
} }
Mix_Volume(-1, MIX_MAX_VOLUME); Mix_Volume(-1, MIX_MAX_VOLUME);
Mix_AllocateChannels(16); Mix_AllocateChannels(16);
// loading sounds // loading sounds
// assets->addSoundEffect("throw_egg", "assets/sound/throw_egg.wav"); // assets->addSoundEffect("throw_egg", "assets/sound/throw_egg.wav");
// assets->addSoundEffect("steps", "assets/sound/steps.wav"); // assets->addSoundEffect("steps", "assets/sound/steps.wav");
// loading music // loading music
// assets->addMusic("background_music", "assets/sound/background_music.mp3"); // assets->addMusic("background_music", "assets/sound/background_music.mp3");
this->gameInstance->init(); this->gameInstance->init();
return SDL_APP_CONTINUE; return SDL_APP_CONTINUE;
} }
void GameInternal::handleEvents() SDL_AppResult GameInternal::handleEvent(SDL_Event* event) {
{ SDL_AppResult result = this->eventManager->handleEvent(event);
SDL_PollEvent(&event);
switch (event.type) if (event->type == SDL_EVENT_QUIT) {
{ this->clean();
case SDL_EVENT_QUIT: this->setRunning(false); return result == SDL_APP_FAILURE ? SDL_APP_FAILURE : SDL_APP_SUCCESS;
break; }
default: return result;
break;
}
} }
void GameInternal::update(Uint64 frameTime) void GameInternal::update(Uint64 frameTime)
{ {
manager.refresh(); manager.refresh();
uint_fast16_t diffTime = frameTime - this->lastFrameTime; uint_fast16_t diffTime = frameTime - this->lastFrameTime;
manager.update(diffTime); manager.update(diffTime);
this->gameInstance->update(diffTime); // TODO: this might have to be split up into two update functions, before and after manager... this->gameInstance->update(diffTime); // TODO: this might have to be split up into two update functions, before and after manager...
this->lastFrameTime = frameTime; this->lastFrameTime = frameTime;
} }
void GameInternal::render() void GameInternal::render()
{ {
SDL_RenderClear(renderer); SDL_RenderClear(renderer);
this->renderManager.renderAll(); this->renderManager->renderAll();
SDL_RenderPresent(renderer); SDL_RenderPresent(renderer);
} }
void GameInternal::clean() void GameInternal::clean()
{ {
delete(textureManager); delete(textureManager);
SDL_DestroyRenderer(renderer); SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window); SDL_DestroyWindow(window);
SDL_Quit(); SDL_Quit();
std::cout << "Game Cleaned!" << std::endl; std::cout << "Game Cleaned!" << std::endl;
} }
bool GameInternal::isRunning() const bool GameInternal::isRunning() const
{ {
return running; return running;
} }
void GameInternal::setRunning(bool running) //TODO: might be depracted void GameInternal::setRunning(bool running) //TODO: might be depracted
{ {
this->running = running; this->running = running;
} }
void GameInternal::stopGame() void GameInternal::stopGame()
{ {
this->running = false; this->running = false;
} }

303
src/InputManager.cpp Normal file
View File

@ -0,0 +1,303 @@
#include "InputManager.h"
#include "InteractionEventdataStruct.h"
#include "SDL3/SDL_events.h"
#include "SDL3/SDL_init.h"
#include <iostream>
#include "SDL3/SDL_stdinc.h"
#include "VEGO.h"
#include "VEGO_Event.h"
std::ostream& operator<<(std::ostream& os, InputManager::Key key) {
static const std::unordered_map<InputManager::Key, std::string> keyToString {
{InputManager::Key::UP, "UP"},
{InputManager::Key::DOWN, "DOWN"},
{InputManager::Key::LEFT, "LEFT"},
{InputManager::Key::RIGHT, "RIGHT"},
{InputManager::Key::SPACE, "SPACE"},
{InputManager::Key::ENTER, "ENTER"},
{InputManager::Key::ESCAPE, "ESCAPE"},
{InputManager::Key::TAB, "TAB"},
{InputManager::Key::BACKSPACE, "BACKSPACE"},
{InputManager::Key::DELETE, "DELETE"},
{InputManager::Key::HOME, "HOME"},
{InputManager::Key::END, "END"},
{InputManager::Key::PAGE_UP, "PAGE_UP"},
{InputManager::Key::PAGE_DOWN, "PAGE_DOWN"},
{InputManager::Key::INSERT, "INSERT"},
{InputManager::Key::CAPS_LOCK, "CAPS_LOCK"},
{InputManager::Key::LEFT_SHIFT, "LEFT_SHIFT"},
{InputManager::Key::RIGHT_SHIFT, "RIGHT_SHIFT"},
{InputManager::Key::LEFT_CTRL, "LEFT_CTRL"},
{InputManager::Key::RIGHT_CTRL, "RIGHT_CTRL"},
{InputManager::Key::LEFT_ALT, "LEFT_ALT"},
{InputManager::Key::RIGHT_ALT, "RIGHT_ALT"},
{InputManager::Key::F1, "F1"},
{InputManager::Key::F2, "F2"},
{InputManager::Key::F3, "F3"},
{InputManager::Key::F4, "F4"},
{InputManager::Key::F5, "F5"},
{InputManager::Key::F6, "F6"},
{InputManager::Key::F7, "F7"},
{InputManager::Key::F8, "F8"},
{InputManager::Key::F9, "F9"},
{InputManager::Key::F10, "F10"},
{InputManager::Key::F11, "F11"},
{InputManager::Key::F12, "F12"},
{InputManager::Key::A, "A"},
{InputManager::Key::B, "B"},
{InputManager::Key::C, "C"},
{InputManager::Key::D, "D"},
{InputManager::Key::E, "E"},
{InputManager::Key::F, "F"},
{InputManager::Key::G, "G"},
{InputManager::Key::H, "H"},
{InputManager::Key::I, "I"},
{InputManager::Key::J, "J"},
{InputManager::Key::K, "K"},
{InputManager::Key::L, "L"},
{InputManager::Key::M, "M"},
{InputManager::Key::N, "N"},
{InputManager::Key::O, "O"},
{InputManager::Key::P, "P"},
{InputManager::Key::Q, "Q"},
{InputManager::Key::R, "R"},
{InputManager::Key::S, "S"},
{InputManager::Key::T, "T"},
{InputManager::Key::U, "U"},
{InputManager::Key::V, "V"},
{InputManager::Key::W, "W"},
{InputManager::Key::X, "X"},
{InputManager::Key::Y, "Y"},
{InputManager::Key::Z, "Z"},
{InputManager::Key::NUM_0, "NUM_0"},
{InputManager::Key::NUM_1, "NUM_1"},
{InputManager::Key::NUM_2, "NUM_2"},
{InputManager::Key::NUM_3, "NUM_3"},
{InputManager::Key::NUM_4, "NUM_4"},
{InputManager::Key::NUM_5, "NUM_5"},
{InputManager::Key::NUM_6, "NUM_6"},
{InputManager::Key::NUM_7, "NUM_7"},
{InputManager::Key::NUM_8, "NUM_8"},
{InputManager::Key::NUM_9, "NUM_9"},
{InputManager::Key::LEFT_BRACKET, "LEFT_BRACKET"},
{InputManager::Key::RIGHT_BRACKET, "RIGHT_BRACKET"},
{InputManager::Key::SEMICOLON, "SEMICOLON"},
{InputManager::Key::APOSTROPHE, "APOSTROPHE"},
{InputManager::Key::COMMA, "COMMA"},
{InputManager::Key::PERIOD, "PERIOD"},
{InputManager::Key::SLASH, "SLASH"},
{InputManager::Key::BACKSLASH, "BACKSLASH"},
{InputManager::Key::GRAVE, "GRAVE"}
};
auto it = keyToString.find(key);
if (it != keyToString.end()) {
os << it->second;
} else {
os << "UNKNOWN_KEY";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const InputManager::InputAction& action) {
os << action.name << " with binding(s): ";
for (auto& binding : action.bindings) {
os << binding << ", ";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const InputManager::InputAction* action) {
if (action) {
os << *action;
} else {
os << "NULL_ACTION";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const std::vector<InputManager::InputAction>& actions) {
os << "Actions: ";
if (actions.empty()) {
os << "None";
} else {
for (size_t i = 0; i < actions.size(); ++i) {
os << actions[i];
if (i < actions.size() - 1) {
os << " | ";
}
}
}
return os;
}
// TODO: find out why it doesnt work??
std::ostream& operator<<(std::ostream& os, const std::vector<InputManager::InputAction*>& actions) {
os << "Actions: ";
if (actions.empty()) {
os << "None";
} else {
for (size_t i = 0; i < actions.size(); ++i) {
if (actions[i]) {
os << *actions[i];
} else {
os << "NULL_ACTION";
}
if (i < actions.size() - 1) {
os << " | ";
}
}
}
return os;
}
// overloads end --------------------------------------------------------------------------------------
InputManager::InputManager() : activeContext("Default") {}
InputManager::~InputManager() {}
void InputManager::initKeyMap() {
keyMap = {
{Key::UP, SDL_SCANCODE_UP},
{Key::DOWN, SDL_SCANCODE_DOWN},
{Key::LEFT, SDL_SCANCODE_LEFT},
{Key::RIGHT, SDL_SCANCODE_RIGHT},
{Key::SPACE, SDL_SCANCODE_SPACE},
{Key::ENTER, SDL_SCANCODE_RETURN},
{Key::ESCAPE, SDL_SCANCODE_ESCAPE},
{Key::TAB, SDL_SCANCODE_TAB},
{Key::BACKSPACE, SDL_SCANCODE_BACKSPACE},
{Key::DELETE, SDL_SCANCODE_DELETE},
{Key::HOME, SDL_SCANCODE_HOME},
{Key::END, SDL_SCANCODE_END},
{Key::PAGE_UP, SDL_SCANCODE_PAGEUP},
{Key::PAGE_DOWN, SDL_SCANCODE_PAGEDOWN},
{Key::INSERT, SDL_SCANCODE_INSERT},
{Key::CAPS_LOCK, SDL_SCANCODE_CAPSLOCK},
{Key::LEFT_SHIFT, SDL_SCANCODE_LSHIFT},
{Key::RIGHT_SHIFT, SDL_SCANCODE_RSHIFT},
{Key::LEFT_CTRL, SDL_SCANCODE_LCTRL},
{Key::RIGHT_CTRL, SDL_SCANCODE_RCTRL},
{Key::LEFT_ALT, SDL_SCANCODE_LALT},
{Key::RIGHT_ALT, SDL_SCANCODE_RALT},
{Key::F1, SDL_SCANCODE_F1},
{Key::F2, SDL_SCANCODE_F2},
{Key::F3, SDL_SCANCODE_F3},
{Key::F4, SDL_SCANCODE_F4},
{Key::F5, SDL_SCANCODE_F5},
{Key::F6, SDL_SCANCODE_F6},
{Key::F7, SDL_SCANCODE_F7},
{Key::F8, SDL_SCANCODE_F8},
{Key::F9, SDL_SCANCODE_F9},
{Key::F10, SDL_SCANCODE_F10},
{Key::F11, SDL_SCANCODE_F11},
{Key::F12, SDL_SCANCODE_F12},
{Key::A, SDL_SCANCODE_A},
{Key::B, SDL_SCANCODE_B},
{Key::C, SDL_SCANCODE_C},
{Key::D, SDL_SCANCODE_D},
{Key::E, SDL_SCANCODE_E},
{Key::F, SDL_SCANCODE_F},
{Key::G, SDL_SCANCODE_G},
{Key::H, SDL_SCANCODE_H},
{Key::I, SDL_SCANCODE_I},
{Key::J, SDL_SCANCODE_J},
{Key::K, SDL_SCANCODE_K},
{Key::L, SDL_SCANCODE_L},
{Key::M, SDL_SCANCODE_M},
{Key::N, SDL_SCANCODE_N},
{Key::O, SDL_SCANCODE_O},
{Key::P, SDL_SCANCODE_P},
{Key::Q, SDL_SCANCODE_Q},
{Key::R, SDL_SCANCODE_R},
{Key::S, SDL_SCANCODE_S},
{Key::T, SDL_SCANCODE_T},
{Key::U, SDL_SCANCODE_U},
{Key::V, SDL_SCANCODE_V},
{Key::W, SDL_SCANCODE_W},
{Key::X, SDL_SCANCODE_X},
{Key::Y, SDL_SCANCODE_Y},
{Key::Z, SDL_SCANCODE_Z},
{Key::NUM_0, SDL_SCANCODE_0},
{Key::NUM_1, SDL_SCANCODE_1},
{Key::NUM_2, SDL_SCANCODE_2},
{Key::NUM_3, SDL_SCANCODE_3},
{Key::NUM_4, SDL_SCANCODE_4},
{Key::NUM_5, SDL_SCANCODE_5},
{Key::NUM_6, SDL_SCANCODE_6},
{Key::NUM_7, SDL_SCANCODE_7},
{Key::NUM_8, SDL_SCANCODE_8},
{Key::NUM_9, SDL_SCANCODE_9},
{Key::LEFT_BRACKET, SDL_SCANCODE_LEFTBRACKET},
{Key::RIGHT_BRACKET, SDL_SCANCODE_RIGHTBRACKET},
{Key::SEMICOLON, SDL_SCANCODE_SEMICOLON},
{Key::APOSTROPHE, SDL_SCANCODE_APOSTROPHE},
{Key::COMMA, SDL_SCANCODE_COMMA},
{Key::PERIOD, SDL_SCANCODE_PERIOD},
{Key::SLASH, SDL_SCANCODE_SLASH},
{Key::BACKSLASH, SDL_SCANCODE_BACKSLASH},
{Key::GRAVE, SDL_SCANCODE_GRAVE}
};
}
void InputManager::registerAction(const std::string& actionName, const std::vector<Key>& keys, std::function<void(bool)> callback, const std::string& context) {
InputAction* storedAction = new InputAction{actionName, keys, callback};
for (const auto& key : keys) {
actionsByContextAndKey[context][key].emplace_back(storedAction);
}
std::cout << "Registered action: " << storedAction << " in context: " << context << std::endl;
}
std::vector<InputManager::InputAction*> InputManager::getActionsByKey(const Key key) const {
std::vector<InputAction*> result;
for (const auto& [context, keyMap] : actionsByContextAndKey) {
auto it = keyMap.find(key);
if (it != keyMap.end()) {
result.insert(result.end(), it->second.begin(), it->second.end());
}
}
return result;
}
void InputManager::setActiveContext(const std::string& context) {
activeContext = context;
std::cout << "Active context set to: " << activeContext << std::endl;
}
std::string InputManager::getActiveContext() const {
return activeContext;
}
SDL_AppResult InputManager::handleEvent(SDL_EventType type, SDL_Event* const event) {
if (event->key.repeat) {
return SDL_APP_CONTINUE;
}
auto keyIt = std::ranges::find_if(keyMap, [&](const auto& pair)
{ return pair.second == event->key.scancode; });
if (keyIt != keyMap.end()) {
std::cout << "in != keymap.end" << std::endl;
Key pressedKey = keyIt->first;
auto keyActions = actionsByContextAndKey[activeContext];
auto it = keyActions.find(pressedKey);
if (it != keyActions.end()) {
for (auto& action : it->second) {
std::cout << "Action triggered: " << action->name << " in context: " << activeContext << std::endl;
action->callback(type == SDL_EVENT_KEY_UP);
}
}
}
return SDL_APP_CONTINUE;
}

View File

@ -0,0 +1,22 @@
#include "InteractionComponent.h"
#include "VEGO.h"
InteractionComponent::InteractionComponent(std::function<void(void*,void*)> callback) : interactionCallback(callback)
{
VEGO_Game().interactionManager->registerListener(this->entity->getComponentAsPointer<InteractionComponent>());
}
void InteractionComponent::interact(void* actor, void* data)
{
if (interactionCallback) {
interactionCallback(actor, data);
}
}
std::shared_ptr<Vector2D> InteractionComponent::getPosition() // required for targeting strategy, return null to only allow explicit targeting
{
if (entity->hasComponent<TransformComponent>()) {
return std::make_shared<Vector2D>(entity->getComponent<TransformComponent>().position);
}
return nullptr;
}

View File

@ -0,0 +1,16 @@
#include "InteractionEventdataStruct.h"
#include "VEGO.h"
#include "VEGO_Event.h"
void InteractionEventdataStruct::triggerEvent()
{
// TODO: if target is null && strategy is 0, error
SDL_Event event;
SDL_zero(event);
event.type = vego::VEGO_Event_Interaction;
event.user.data1 = this;
SDL_PushEvent(&event);
}

View File

@ -0,0 +1,90 @@
#include "InteractionManager.h"
#include "InteractionEventdataStruct.h"
#include "InteractionListener.h"
#include "SDL3/SDL_init.h"
#include "VEGO_Event.h"
#include "Vector2D.h"
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <iterator>
#include <memory>
#include <ranges>
#include <type_traits>
#include <vector>
InteractionManager::InteractionManager()
{
this->targetingFuncs.fill(nullptr);
this->targetingFuncs.at(static_cast<std::underlying_type<InteractionManager::TargetingStrategy>::type>(InteractionManager::TargetingStrategy::closest)) = [](Vector2D* reference, std::vector<std::shared_ptr<InteractionListener>> input) {
return std::shared_ptr<InteractionListener>();
};
this->targetingFuncs.at(static_cast<std::underlying_type<InteractionManager::TargetingStrategy>::type>(InteractionManager::TargetingStrategy::closest)) = [](Vector2D* reference, std::vector<std::shared_ptr<InteractionListener>> input) {
auto min = std::ranges::min_element(input, [&reference](std::shared_ptr<InteractionListener>& a, std::shared_ptr<InteractionListener>& b) {
std::shared_ptr<Vector2D> coordA = a->getPosition();
std::shared_ptr<Vector2D> coordB = b->getPosition();
if (coordB == nullptr) return true;
if (coordA == nullptr) return false;
return std::sqrt(std::pow(coordA->x - reference->x, 2) + std::pow(coordA->y - reference->y, 2)) < std::sqrt(std::pow(coordB->x - reference->x, 2) + std::pow(coordB->y - reference->y, 2));
});
return min == std::ranges::end(input) ? nullptr : *min;
};
this->targetingFuncs.at(static_cast<std::underlying_type<InteractionManager::TargetingStrategy>::type>(InteractionManager::TargetingStrategy::manhattenDistance)) = [](Vector2D* reference, std::vector<std::shared_ptr<InteractionListener>> input) {
auto min = std::ranges::min_element(input, [&reference](std::shared_ptr<InteractionListener>& a, std::shared_ptr<InteractionListener>& b) {
std::shared_ptr<Vector2D> coordA = a->getPosition();
std::shared_ptr<Vector2D> coordB = b->getPosition();
if (coordB == nullptr) return true;
if (coordA == nullptr) return false;
return (std::abs(coordA->x - reference->x) + std::abs(coordA->y - reference->y)) < (std::abs(coordB->x - reference->x) + std::abs(coordB->y - reference->y));
});
return min == std::ranges::end(input) ? nullptr : *min;
};
}
SDL_AppResult InteractionManager::handleInteract(SDL_EventType type, SDL_Event* const event)
{
if (type != vego::VEGO_Event_Interaction) { // error handling
return SDL_APP_CONTINUE;
}
InteractionEventdataStruct* data = static_cast<InteractionEventdataStruct*>(event->user.data1);
std::shared_ptr<InteractionListener> listener = data->target.lock();
if (data->strategy != static_cast<std::underlying_type<InteractionManager::TargetingStrategy>::type>(InteractionManager::TargetingStrategy::none)) {
listener = this->targetingFuncs.at(data->strategy)(
data->targetingReference.get(),
this->listeners
| std::views::transform(&std::weak_ptr<InteractionListener>::lock)
| std::views::filter(&std::shared_ptr<InteractionListener>::operator bool)
| std::ranges::to<std::vector>()
);
}
if (listener) {
listener->interact(data->actor, data->data);
}
return SDL_APP_CONTINUE;
}
void InteractionManager::registerListener(std::weak_ptr<InteractionListener> listener)
{
this->listeners.emplace_back(listener);
}
uint8_t InteractionManager::registerTargetingFunc(TargetingFunc func)
{
auto it = std::ranges::find_if(this->targetingFuncs, [](const auto& func) {
return !func;
});
(*it) = func;
return std::distance(this->targetingFuncs.begin(), it);
}

View File

@ -3,16 +3,20 @@
#include "CollisionHandler.h" #include "CollisionHandler.h"
#include "Entity.h" #include "Entity.h"
#include "HealthComponent.h" #include "HealthComponent.h"
#include "SpriteComponent.h"
#include "StatEffectsComponent.h" #include "StatEffectsComponent.h"
#include "Constants.h" #include "Constants.h"
#include "TextureManager.h"
#include "TransformComponent.h"
#include <cstdint> #include <cstdint>
#include "VEGO.h"
PickupComponent::PickupComponent(std::function<void (Entity*)> func) PickupComponent::PickupComponent(std::function<void (Entity*)> func)
{ {
this->pickupFunc = func; this->pickupFunc = func;
} }
void PickupComponent::update(uint_fast16_t diffTime) void PickupComponent::update(uint_fast16_t diffTime)
{ {
Entity* player; Entity* player;
if ((player = this->entity->getManager().getGame()->collisionHandler->getAnyIntersection<Entity*>( if ((player = this->entity->getManager().getGame()->collisionHandler->getAnyIntersection<Entity*>(

View File

@ -1,10 +1,10 @@
#include "RenderObject.h" #include "RenderObject.h"
#include "RenderManager.h" #include "RenderManager.h"
RenderObject::RenderObject(int zIndex, RenderManager& renderManager) : zIndex(zIndex), renderManager(renderManager) { RenderObject::RenderObject(int zIndex, RenderManager* renderManager) : zIndex(zIndex), renderManager(renderManager) {
renderManager.add(this); renderManager->add(this);
} }
RenderObject::~RenderObject() { RenderObject::~RenderObject() {
this->renderManager.remove(this); this->renderManager->remove(this);
} }

View File

@ -18,7 +18,7 @@
SpriteComponent::SpriteComponent(Textures texture, int zIndex) : RenderObject(zIndex, VEGO_Game().renderManager), textureXOffset(0), textureYOffset(0) SpriteComponent::SpriteComponent(Textures texture, int zIndex) : RenderObject(zIndex, VEGO_Game().renderManager), textureXOffset(0), textureYOffset(0)
{ {
this->textureEnum = texture; this->textureEnum = texture;
this->path = ""; this->path = "";
} }
SpriteComponent::SpriteComponent(Textures texture, int xOffset, int yOffset, int zIndex) : RenderObject(zIndex, VEGO_Game().renderManager), textureXOffset(xOffset), textureYOffset(yOffset) SpriteComponent::SpriteComponent(Textures texture, int xOffset, int yOffset, int zIndex) : RenderObject(zIndex, VEGO_Game().renderManager), textureXOffset(xOffset), textureYOffset(yOffset)

View File

@ -15,6 +15,9 @@ void TextureManager::addSingleTexture(Textures texture, const char* filePath) {
SDL_SetTextureScaleMode(sdlTexture, this->scaleMode); // linear scaling results in blurry images SDL_SetTextureScaleMode(sdlTexture, this->scaleMode); // linear scaling results in blurry images
this->texture_cache.emplace(texture, sdlTexture); this->texture_cache.emplace(texture, sdlTexture);
if (filePath != nullptr) {
this->texture_references.emplace(texture, std::string(filePath));
}
std::cout << "Loaded texture at " << filePath << std::endl; std::cout << "Loaded texture at " << filePath << std::endl;
} }

View File

@ -42,6 +42,9 @@ void TransformComponent::init()
void TransformComponent::update(uint_fast16_t diffTime) void TransformComponent::update(uint_fast16_t diffTime)
{ {
direction.x = direction.x > 0 ? 1 : direction.x < 0 ? -1 : 0;
direction.y = direction.y > 0 ? 1 : direction.y < 0 ? -1 : 0;
float multiplier = direction.x != 0 && direction.y != 0 ? 0.707 : 1; // normalizes vector; only works if directions are in increments of 45° float multiplier = direction.x != 0 && direction.y != 0 ? 0.707 : 1; // normalizes vector; only works if directions are in increments of 45°
Vector2D positionChange( Vector2D positionChange(
direction.x * this->getSpeed() * multiplier * diffTime * (1.f/1000), direction.x * this->getSpeed() * multiplier * diffTime * (1.f/1000),

View File

@ -27,7 +27,7 @@ SDL_AppResult SDL_AppIterate(void *appstate) {
return SDL_APP_SUCCESS; return SDL_APP_SUCCESS;
} }
vego::game->handleEvents(); // bad //vego::game->handleEvents(); // bad
Uint64 frameStart = SDL_GetTicks(); Uint64 frameStart = SDL_GetTicks();
@ -39,8 +39,9 @@ SDL_AppResult SDL_AppIterate(void *appstate) {
return SDL_APP_CONTINUE; return SDL_APP_CONTINUE;
} }
// triggers upon every event
SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event) { SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event) {
return SDL_APP_CONTINUE; return vego::game->handleEvent(event);
} }
void SDL_AppQuit(void *appstate, SDL_AppResult result) { void SDL_AppQuit(void *appstate, SDL_AppResult result) {