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