]> git.tdb.fi Git - libs/game.git/blob - examples/bassteroids/source/physics.h
Add rotation to physics simulation
[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                 float moment_of_inertia = 1.0f;
21                 Msp::LinAl::Vector<float, 2> external_force;
22
23                 Msp::LinAl::Vector<float, 2> position;
24                 Msp::Geometry::Angle<float> rotation;
25                 Msp::LinAl::Vector<float, 2> velocity;
26                 Msp::Geometry::Angle<float> angular_velocity;
27
28                 unsigned collision_count;
29                 Msp::LinAl::Vector<float, 2> position_adjust;
30         };
31
32         struct Collision
33         {
34                 std::uint16_t body1 = 0;
35                 std::uint16_t body2 = 0;
36                 Msp::LinAl::Vector<float, 2> point;
37                 float depth = 0.0f;
38                 Msp::LinAl::Vector<float, 2> normal;
39         };
40
41         Msp::Game::EventObserver observer;
42         std::vector<SimulatedEntity> entities;
43         unsigned fixture_count = 0;
44         std::vector<Collision> collisions;
45
46 public:
47         Physics(Msp::Game::Stage &);
48
49 private:
50         void entity_added(const Msp::Game::Events::EntityCreated &);
51
52 public:
53         void tick(Msp::Time::TimeDelta) override;
54
55 private:
56         template<bool>
57         void copy_in(SimulatedEntity &);
58
59         template<bool>
60         void copy_out(SimulatedEntity &);
61
62         void step(float);
63         void detect_collisions();
64         void solve_collisions();
65         void apply_impulses();
66
67         Collision &get_collision(unsigned, unsigned);
68         void collide_circle_circle(unsigned, unsigned);
69         void collide_circle_box(unsigned, unsigned);
70 };
71
72 #endif