73 lines
2.0 KiB
C++
73 lines
2.0 KiB
C++
#pragma once
|
|
|
|
#include "ActionFile.h"
|
|
|
|
#include <chrono>
|
|
#include <cstdint>
|
|
#include <map>
|
|
#include <optional>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
namespace Bilicraft
|
|
{
|
|
// Single-threaded cooperative scheduler. Only the owner may execute commands;
|
|
// enqueue/submit are safe from that owner's Yield callback, never other threads.
|
|
class ActionScheduler
|
|
{
|
|
public:
|
|
using Clock = std::chrono::steady_clock;
|
|
using TaskId = std::uint64_t;
|
|
enum class State { Ready, Running, Blocked };
|
|
struct TaskInfo
|
|
{
|
|
TaskId id;
|
|
std::string name;
|
|
State state;
|
|
std::size_t nextCommand;
|
|
std::size_t commandCount;
|
|
Clock::time_point wakeAt;
|
|
};
|
|
struct Work
|
|
{
|
|
ActionCommand command;
|
|
TaskId taskId; // 0 for an interactive command
|
|
bool interactive;
|
|
};
|
|
|
|
TaskId Enqueue(ActionProgram program, Clock::time_point now = Clock::now());
|
|
void WakeReady(Clock::time_point now);
|
|
void SubmitInteractive(ActionCommand command);
|
|
// Call only when no command is outstanding. Wait is handled here, never
|
|
// passed to the game executor. Timers don't preempt a running action.
|
|
std::optional<Work> Next(Clock::time_point now);
|
|
void Finish(bool success);
|
|
bool InteractivePending() const;
|
|
bool HasWork() const;
|
|
std::optional<Clock::time_point> NextWake() const;
|
|
std::vector<TaskInfo> Tasks() const;
|
|
std::vector<std::string> DrainEvents();
|
|
|
|
private:
|
|
struct Task
|
|
{
|
|
TaskId id;
|
|
ActionProgram program;
|
|
std::size_t pc = 0;
|
|
State state = State::Ready;
|
|
Clock::time_point wakeAt{};
|
|
std::uint64_t readyOrder = 0;
|
|
};
|
|
void RemoveActive(bool success);
|
|
std::map<TaskId, Task> tasks;
|
|
std::optional<TaskId> active;
|
|
std::optional<ActionCommand> interactive;
|
|
bool inFlight = false;
|
|
bool interactiveInFlight = false;
|
|
TaskId nextId = 1;
|
|
std::uint64_t nextOrder = 1;
|
|
std::size_t storedCommands = 0;
|
|
std::vector<std::string> events;
|
|
};
|
|
} // namespace Bilicraft
|