Timeout and Interval events

This commit is contained in:
2023-11-25 23:57:07 -06:00
parent 94941b1c14
commit 3920dd34a3
15 changed files with 418 additions and 10 deletions

View File

@@ -14,7 +14,6 @@ Scene::Scene(
game(game),
sceneInitializer(sceneInitializer)
{
}
void Scene::stage() {
@@ -23,18 +22,33 @@ void Scene::stage() {
}
void Scene::update() {
// Initialize new scene items
if(!hasInitialized) {
hasInitialized = true;
for(auto &item : sceneItems) {
item->init();
}
}
// Remove stale scene items.
auto itRemove = sceneItemsToRemove.begin();
while(itRemove != sceneItemsToRemove.end()) {
auto item = *itRemove;
auto it = std::find(sceneItems.begin(), sceneItems.end(), item);
if(it != sceneItems.end()) sceneItems.erase(it);
itRemove++;
}
sceneItemsToRemove.clear();
// Tick scene items.
float_t delta = getGame()->timeManager.delta;
if(paused) {
onPausedUpdate.emit(delta);
} else {
onUnpausedUpdate.emit(delta);
onTimeout.tick(delta);
onInterval.tick(delta);
}
}
@@ -48,5 +62,9 @@ std::shared_ptr<SceneItem> Scene::createSceneItem() {
return item;
}
void Scene::removeItem(const std::shared_ptr<SceneItem> item) {
sceneItemsToRemove.push_back(item);
}
Scene::~Scene() {
}

View File

@@ -6,19 +6,30 @@
#pragma once
#include "game/Game.hpp"
#include "scene/SceneItem.hpp"
#include "event/Event.hpp"
#include "time/event/IntervalEvent.hpp"
#include "time/event/TimeoutEvent.hpp"
namespace Dawn {
struct IntervalData {
float_t frequency;
float_t nextInvoke;
};
class Scene final : public std::enable_shared_from_this<Scene> {
private:
std::weak_ptr<Game> game;
const std::function<void(Scene&)> sceneInitializer;
std::vector<std::shared_ptr<SceneItem>> sceneItems;
std::vector<std::shared_ptr<SceneItem>> sceneItemsToRemove;
bool_t paused = false;
bool_t hasInitialized = false;
public:
Event<float_t> onUnpausedUpdate;
Event<float_t> onPausedUpdate;
TimeoutEvent onTimeout;
IntervalEvent onInterval;
/**
* Constructs a scene object.
@@ -57,6 +68,14 @@ namespace Dawn {
*/
std::shared_ptr<SceneItem> createSceneItem();
/**
* Removes a scene item from the scene. This remove will happen at the
* start of the next scene update.
*
* @param item Scene item to remove.
*/
void removeItem(const std::shared_ptr<SceneItem> item);
/**
* Returns a list of scene components that match the given type.
*

View File

@@ -30,6 +30,12 @@ void SceneItem::init() {
}
}
void SceneItem::remove() {
auto scene = getScene();
if(!scene) return;
scene->removeItem(shared_from_this());
}
SceneItem::~SceneItem() {
std::for_each(
components.begin(),

View File

@@ -42,6 +42,12 @@ namespace Dawn {
*/
std::shared_ptr<Scene> getScene();
/**
* Queues this scene item to be removed from the scene (on the next scene
* update).
*/
void remove();
/**
* Returns the scene that this item belongs to.
*