Move system_scheduler to a separate file

This commit is contained in:
NukeBird 2025-02-20 00:09:58 +03:00
parent 5705238d57
commit d1bafb4c46
3 changed files with 53 additions and 48 deletions

52
system_scheduler.hpp Normal file
View file

@ -0,0 +1,52 @@
#pragma once
#include <functional>
#include <vector>
namespace zecsy
{
class system_scheduler final
{
public:
void add_system(float freq, auto&& func);
void add_system(int freq, auto&& func);
void update(float dt);
private:
struct system_handler
{
double interval;
double accumulator = 0.0f;
std::function<void(float)> callback;
};
std::vector<system_handler> systems;
};
inline void system_scheduler::add_system(float freq, auto&& func)
{
systems.emplace_back(1.0f / freq, 0.0f,
std::forward<decltype(func)>(func));
}
inline void system_scheduler::add_system(int freq, auto&& func)
{
add_system(float(freq), func);
}
inline void system_scheduler::update(float dt)
{
dt = std::max(0.0f, dt);
for(auto& s: systems)
{
s.accumulator += dt;
while(s.accumulator >= s.interval)
{
s.callback(dt);
s.accumulator -= s.interval;
}
}
}
} // namespace zecsy

View file

@ -3,6 +3,7 @@
#include <catch2/catch_all.hpp> #include <catch2/catch_all.hpp>
#include "../zecsy.hpp" #include "../zecsy.hpp"
#include "../system_scheduler.hpp"
using namespace zecsy; using namespace zecsy;

View file

@ -1,10 +1,8 @@
#pragma once #pragma once
#include <algorithm>
#include <concepts> #include <concepts>
#include <cstdint> #include <cstdint>
#include <cstdlib> #include <cstdlib>
#include <format> #include <format>
#include <functional>
#include <set> #include <set>
#include <stdexcept> #include <stdexcept>
#include <type_traits> #include <type_traits>
@ -29,52 +27,6 @@ namespace zecsy
return true; return true;
}(); }();
class system_scheduler final
{
public:
void add_system(float freq, auto&& func);
void add_system(int freq, auto&& func);
void update(float dt);
private:
struct system_handler
{
double interval;
double accumulator = 0.0f;
std::function<void(float)> callback;
};
std::vector<system_handler> systems;
};
inline void system_scheduler::add_system(float freq, auto&& func)
{
systems.emplace_back(1.0f / freq, 0.0f,
std::forward<decltype(func)>(func));
}
inline void system_scheduler::add_system(int freq, auto&& func)
{
add_system(float(freq), func);
}
inline void system_scheduler::update(float dt)
{
dt = std::max(0.0f, dt);
for(auto& s: systems)
{
s.accumulator += dt;
while(s.accumulator >= s.interval)
{
s.callback(dt);
s.accumulator -= s.interval;
}
}
}
class world final class world final
{ {
public: public: