implement threaded physics (decoupled from rendering thread) - not yet integrated
This commit is contained in:
@ -1,9 +1,14 @@
|
||||
#ifndef __PHYSICS_HPP_
|
||||
#define __PHYSICS_HPP_
|
||||
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <raylib.h>
|
||||
#include <raymath.h>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
#include "config.hpp"
|
||||
@ -105,14 +110,13 @@ private:
|
||||
#endif
|
||||
|
||||
public:
|
||||
auto AddMass(float mass, bool fixed, const State &state) -> void;
|
||||
auto AddMass(const State &state) -> void;
|
||||
|
||||
auto GetMass(const State &state) -> Mass &;
|
||||
|
||||
auto GetMass(const State &state) const -> const Mass &;
|
||||
|
||||
auto AddSpring(const State &massA, const State &massB, float spring_constant,
|
||||
float dampening_constant, float rest_length) -> void;
|
||||
auto AddSpring(const State &massA, const State &massB) -> void;
|
||||
|
||||
auto Clear() -> void;
|
||||
|
||||
@ -129,4 +133,58 @@ public:
|
||||
#endif
|
||||
};
|
||||
|
||||
class ThreadedPhysics {
|
||||
struct AddMass {
|
||||
State s;
|
||||
};
|
||||
struct AddSpring {
|
||||
State a;
|
||||
State b;
|
||||
};
|
||||
struct ClearGraph {};
|
||||
|
||||
using Command = std::variant<AddMass, AddSpring, ClearGraph>;
|
||||
|
||||
struct PhysicsState {
|
||||
std::mutex command_mtx;
|
||||
std::queue<Command> pending_commands;
|
||||
|
||||
std::mutex pos_mtx;
|
||||
std::vector<Mass> masses; // Read by renderer
|
||||
std::unordered_map<State, int> state_masses; // Read by renderer
|
||||
std::vector<Spring> springs; // Read by renderer
|
||||
std::unordered_map<std::pair<State, State>, int>
|
||||
state_springs; // Read by renderer
|
||||
|
||||
std::atomic<bool> running{true};
|
||||
};
|
||||
|
||||
private:
|
||||
PhysicsState state;
|
||||
std::thread physics;
|
||||
|
||||
public:
|
||||
ThreadedPhysics() : physics(PhysicsThread, std::ref(state)) {}
|
||||
|
||||
ThreadedPhysics(const ThreadedPhysics ©) = delete;
|
||||
ThreadedPhysics &operator=(const ThreadedPhysics ©) = delete;
|
||||
ThreadedPhysics(ThreadedPhysics &&move) = delete;
|
||||
ThreadedPhysics &operator=(ThreadedPhysics &&move) = delete;
|
||||
|
||||
~ThreadedPhysics() {
|
||||
state.running = false;
|
||||
physics.join();
|
||||
}
|
||||
|
||||
private:
|
||||
static auto PhysicsThread(PhysicsState &state) -> void;
|
||||
|
||||
public:
|
||||
};
|
||||
|
||||
// https://en.cppreference.com/w/cpp/utility/variant/visit
|
||||
template <class... Ts> struct overloads : Ts... {
|
||||
using Ts::operator()...;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
Reference in New Issue
Block a user