]> git.tdb.fi Git - libs/game.git/blob - examples/bassteroids/source/physics.h
Implement a simple physics system in Bassteroids
[libs/game.git] / examples / bassteroids / source / physics.h
1 #ifndef PHYSICS_H_
2 #define PHYSICS_H_
3
4 #include <msp/game/eventobserver.h>
5 #include <msp/game/events.h>
6 #include <msp/game/handle.h>
7 #include <msp/game/system.h>
8 #include <msp/geometry/angle.h>
9 #include <msp/linal/vector.h>
10
11 class PhysicalEntity;
12
13 class Physics: public Msp::Game::System
14 {
15 private:
16         struct SimulatedEntity
17         {
18                 Msp::Game::Handle<PhysicalEntity> entity;
19                 float inverse_mass = 1.0f;
20                 Msp::LinAl::Vector<float, 2> external_force;
21
22                 Msp::LinAl::Vector<float, 2> position;
23                 Msp::LinAl::Vector<float, 2> velocity;
24
25                 unsigned collision_count;
26                 Msp::LinAl::Vector<float, 2> position_adjust;
27         };
28
29         struct Collision
30         {
31                 std::uint16_t body1 = 0;
32                 std::uint16_t body2 = 0;
33                 Msp::LinAl::Vector<float, 2> point;
34                 float depth = 0.0f;
35                 Msp::LinAl::Vector<float, 2> normal;
36         };
37
38         Msp::Game::EventObserver observer;
39         std::vector<SimulatedEntity> entities;
40         unsigned fixture_count = 0;
41         std::vector<Collision> collisions;
42
43 public:
44         Physics(Msp::Game::Stage &);
45
46 private:
47         void entity_added(const Msp::Game::Events::EntityCreated &);
48
49 public:
50         void tick(Msp::Time::TimeDelta) override;
51
52 private:
53         template<bool>
54         void copy_in(SimulatedEntity &);
55
56         template<bool>
57         void copy_out(SimulatedEntity &);
58
59         void step(float);
60         void detect_collisions();
61         void solve_collisions();
62         void apply_impulses();
63
64         Collision &get_collision(unsigned, unsigned);
65         void collide_circle_circle(unsigned, unsigned);
66 };
67
68 #endif