]> git.tdb.fi Git - libs/game.git/blob - examples/bassteroids/source/physics.cpp
Remove destroyed entities from the physics simulation
[libs/game.git] / examples / bassteroids / source / physics.cpp
1 #include "physics.h"
2 #include <msp/core/algorithm.h>
3 #include <msp/game/transform.h>
4 #include "physicalentity.h"
5
6 using namespace std;
7 using namespace Msp;
8
9 Physics::Physics(Game::Stage &s):
10         System(s),
11         event_source(stage.get_event_bus()),
12         observer(stage.get_event_bus())
13 {
14         observer.observe<Game::Events::EntityCreated>([this](auto &e){ entity_added(e); });
15         observer.observe<Game::Events::EntityDestroyed>([this](auto &e){ entity_removed(e); });
16
17         stage.synthesize_initial_events(observer);
18 }
19
20 void Physics::entity_added(const Game::Events::EntityCreated &e)
21 {
22         if(Game::Handle<PhysicalEntity> physical = dynamic_handle_cast<PhysicalEntity>(e.entity))
23         {
24                 for(Game::Handle<Game::Entity> p=e.entity->get_parent(); p; p=p->get_parent())
25                         if(p->get_transform())
26                                 return;
27
28                 SimulatedEntity sim_body;
29                 sim_body.entity = physical;
30                 if(physical->is_fixture())
31                 {
32                         entities.insert(entities.begin()+fixture_count, sim_body);
33                         ++fixture_count;
34                 }
35                 else
36                         entities.push_back(sim_body);
37         }
38 }
39
40 void Physics::entity_removed(const Game::Events::EntityDestroyed &e)
41 {
42         if(Game::Handle<PhysicalEntity> physical = dynamic_handle_cast<PhysicalEntity>(e.entity))
43         {
44                 auto i = find_member(entities, physical, &SimulatedEntity::entity);
45                 if(i!=entities.end())
46                 {
47                         size_t index = distance(entities.begin(), i);
48                         if(index<fixture_count)
49                         {
50                                 if(index+1!=fixture_count)
51                                         *i = std::move(entities[fixture_count-1]);
52                                 entities[fixture_count-1] = std::move(entities.back());
53                         }
54                         else
55                                 *i = std::move(entities.back());
56                         entities.pop_back();
57                 }
58         }
59 }
60
61 void Physics::tick(Time::TimeDelta dt)
62 {
63         float dt_secs = dt/Time::sec;
64
65         for(unsigned i=0; i<fixture_count; ++i)
66                 copy_in<true>(entities[i]);
67         for(unsigned i=fixture_count; i<entities.size(); ++i)
68                 copy_in<false>(entities[i]);
69
70         step(dt_secs);
71
72         collisions.clear();
73         for(unsigned i=0; i<10; ++i)
74         {
75                 detect_collisions();
76                 solve_collisions();
77         }
78
79         apply_impulses();
80
81         for(unsigned i=0; i<fixture_count; ++i)
82                 copy_out<true>(entities[i]);
83         for(unsigned i=fixture_count; i<entities.size(); ++i)
84                 copy_out<false>(entities[i]);
85
86         for(const Collision &c: collisions)
87                 event_source.emit<Events::Collision>(entities[c.body1].entity->get_collider(), entities[c.body2].entity->get_collider());
88 }
89
90 template<bool is_fixture>
91 void Physics::copy_in(SimulatedEntity &entity)
92 {
93         Game::Handle<Game::Transform> transform = entity.entity->get_transform();
94         entity.position = transform->get_position().slice<2>(0);
95         const Geometry::Quaternion<float> &r = transform->get_rotation();
96         entity.rotation = Geometry::atan2<float>(2*(r.a*r.d+r.b*r.c), 1-2*(r.c*r.c+r.d*r.d));
97
98         if constexpr(is_fixture)
99         {
100                 entity.inverse_mass = 0.0f;
101                 entity.inverse_momi = 0.0f;
102         }
103         else
104         {
105                 Game::Handle<RigidBody> body = entity.entity->get_body();
106                 entity.inverse_mass = 1.0f/body->get_mass();
107                 entity.inverse_momi = 1.0f/body->get_moment_of_inertia();
108                 entity.external_force = body->get_force();
109                 entity.external_torque = body->get_torque();
110                 entity.velocity = body->get_velocity();
111                 entity.angular_velocity = body->get_angular_velocity();
112         }
113 }
114
115 template<bool is_fixture>
116 void Physics::copy_out(SimulatedEntity &entity)
117 {
118         Game::Handle<Game::Transform> transform = entity.entity->get_transform();
119         transform->set_position(compose(entity.position, 0.0f));
120         transform->set_rotation(Geometry::Quaternion<float>::rotation(entity.rotation, LinAl::Vector<float, 3>(0, 0, 1)));
121
122         if constexpr(!is_fixture)
123         {
124                 Game::Handle<RigidBody> body = entity.entity->get_body();
125                 body->set_velocity(entity.velocity);
126                 body->set_angular_velocity(entity.angular_velocity);
127                 body->clear_forces();
128         }
129 }
130
131 void Physics::step(float dt_secs)
132 {
133         for(unsigned i=fixture_count; i<entities.size(); ++i)
134         {
135                 SimulatedEntity &entity = entities[i];
136
137                 LinAl::Vector<float, 2> new_velocity = entity.velocity+entity.external_force*(dt_secs*entity.inverse_mass);
138                 entity.position += (entity.velocity+new_velocity)*(dt_secs/2);
139                 entity.velocity = new_velocity;
140
141                 Geometry::Angle<float> new_angular_velocity = entity.angular_velocity+Geometry::Angle<float>::from_radians(entity.external_torque*dt_secs*entity.inverse_momi);
142                 entity.rotation = wrap_positive(entity.rotation+(entity.angular_velocity+new_angular_velocity)*(dt_secs/2));
143                 entity.angular_velocity = new_angular_velocity;
144         }
145 }
146
147 void Physics::detect_collisions()
148 {
149         for(auto &c: collisions)
150                 c.depth = 0.0f;
151
152         for(unsigned i=fixture_count; i<entities.size(); ++i)
153         {
154                 Game::Handle<PhysicalEntity> entity1 = entities[i].entity;
155                 ColliderType type1 = entity1->get_collider()->get_type();
156                 for(unsigned j=0; j<i; ++j)
157                 {
158                         Game::Handle<PhysicalEntity> entity2 = entities[j].entity;
159                         ColliderType type2 = entity2->get_collider()->get_type();
160                         if(type1==ColliderType::CIRCLE && type2==ColliderType::CIRCLE)
161                                 collide_circle_circle(i, j);
162                         else if(type1==ColliderType::CIRCLE && type2==ColliderType::BOX)
163                                 collide_circle_box(i, j);
164                         else if(type1==ColliderType::BOX && type2==ColliderType::CIRCLE)
165                                 collide_circle_box(j, i);
166                 }
167         }
168 }
169
170 void Physics::solve_collisions()
171 {
172         for(auto &e: entities)
173         {
174                 e.position_adjust = LinAl::Vector<float, 2>();
175                 e.collision_count = 0;
176         }
177
178         for(const auto &c: collisions)
179         {
180                 if(!c.depth)
181                         continue;
182
183                 SimulatedEntity &entity1 = entities[c.body1];
184                 SimulatedEntity &entity2 = entities[c.body2];
185                 float inv_mass_sum = 1.0f/(entity1.inverse_mass+entity2.inverse_mass);
186                 LinAl::Vector<float, 2> delta = c.normal*c.depth*inv_mass_sum;
187                 if(c.body1>=fixture_count)
188                 {
189                         entity1.position_adjust += delta*entity1.inverse_mass;
190                         ++entity1.collision_count;
191                 }
192                 if(c.body2>=fixture_count)
193                 {
194                         entity2.position_adjust -= delta*entity1.inverse_mass;
195                         ++entity2.collision_count;
196                 }
197         }
198
199         for(auto &e: entities)
200                 if(e.collision_count)
201                         e.position += e.position_adjust/static_cast<float>(e.collision_count);
202 }
203
204 void Physics::apply_impulses()
205 {
206         for(const auto &c: collisions)
207         {
208                 SimulatedEntity &entity1 = entities[c.body1];
209                 SimulatedEntity &entity2 = entities[c.body2];
210                 LinAl::Vector<float, 2> r1 = c.point-entity1.position;
211                 LinAl::Vector<float, 2> r2 = c.point-entity2.position;
212                 LinAl::Vector<float, 2> v_p1 = entity1.velocity+LinAl::Vector<float, 2>(-r1.y, r1.x)*entity1.angular_velocity.radians();
213                 LinAl::Vector<float, 2> v_p2 = entity2.velocity+LinAl::Vector<float, 2>(-r2.y, r2.x)*entity2.angular_velocity.radians();
214                 LinAl::Vector<float, 2> v_rel = v_p2-v_p1;
215                 LinAl::Vector<float, 2> tangent = v_rel-c.normal*inner_product(v_rel, c.normal);
216                 float v_tan = tangent.norm();
217                 tangent = (v_tan>1e-5 ? normalize(tangent) : LinAl::Vector<float, 2>(-c.normal.y, c.normal.x));
218                 float restitution = 1.0f;
219                 float friction_coeff = 0.1f;
220                 float inv_mass_sum = entity1.inverse_mass+entity2.inverse_mass;
221                 float reaction = (1+restitution)*inner_product(v_rel, c.normal)/inv_mass_sum;
222                 float friction = min(reaction*friction_coeff, v_tan/inv_mass_sum);
223                 LinAl::Vector<float, 2> impulse = c.normal*reaction+tangent*friction;
224                 entity1.velocity += impulse*entity1.inverse_mass;
225                 entity2.velocity -= impulse*entity2.inverse_mass;
226                 entity1.angular_velocity += Geometry::Angle<float>::from_radians(entity1.inverse_momi*(r1.x*impulse.y-r1.y*impulse.x));
227                 entity2.angular_velocity -= Geometry::Angle<float>::from_radians(entity2.inverse_momi*(r2.x*impulse.y-r2.y*impulse.x));
228         }
229 }
230
231 Physics::Collision &Physics::get_collision(unsigned i, unsigned j)
232 {
233         for(auto &c: collisions)
234                 if((c.body1==i && c.body2==j) || (c.body1==j && c.body2==i))
235                         return c;
236
237         Collision &c = collisions.emplace_back();
238         c.body1 = i;
239         c.body2 = j;
240         return c;
241 }
242
243 void Physics::collide_circle_circle(unsigned i, unsigned j)
244 {
245         const LinAl::Vector<float, 2> &pos1 = entities[i].position;
246         const LinAl::Vector<float, 2> &pos2 = entities[j].position;
247         float r1 = entities[i].entity->get_collider()->get_radius();
248         float r2 = entities[j].entity->get_collider()->get_radius();
249
250         /* Points in the direction the first body needs to move in to clear the
251         penetration */
252         LinAl::Vector<float, 2> delta = pos1-pos2;
253         float d_sq = inner_product(delta, delta);
254         float r_sum = r1+r2;
255         if(d_sq<r_sum*r_sum)
256         {
257                 Collision &collision = get_collision(i, j);
258                 collision.normal = normalize(delta);
259                 collision.depth = r1+r2-sqrt(d_sq);
260                 collision.point = pos1-collision.normal*(r1-collision.depth/2);
261                 if(collision.body1!=i)
262                         collision.normal = -collision.normal;
263         }
264 }
265
266 void Physics::collide_circle_box(unsigned i, unsigned j)
267 {
268         const LinAl::Vector<float, 2> &pos1 = entities[i].position;
269         const LinAl::Vector<float, 2> &pos2 = entities[j].position;
270         float radius = entities[i].entity->get_collider()->get_radius();
271         LinAl::Vector<float, 2> half_size = entities[j].entity->get_collider()->get_size()/2.0f;
272
273         LinAl::Vector<float, 2> delta = pos1-pos2;
274         float c = cos(entities[j].rotation);
275         float s = sin(entities[j].rotation);
276         LinAl::Vector<float, 2> local_delta(c*delta.x+s*delta.y, c*delta.y-s*delta.x);
277         LinAl::Vector<float, 2> local_closest(clamp(local_delta.x, -half_size.x, half_size.x), clamp(local_delta.y, -half_size.y, half_size.y));
278         LinAl::Vector<float, 2> local_cdelta = local_delta-local_closest;
279         float d_sq = inner_product(local_cdelta, local_cdelta);
280
281         if(d_sq<radius*radius)
282         {
283                 Collision &collision = get_collision(i, j);
284                 if(d_sq>1e-10)
285                 {
286                         collision.normal = normalize(LinAl::Vector<float, 2>(c*local_cdelta.x-s*local_cdelta.y, c*local_cdelta.y+s*local_cdelta.x));
287                         collision.depth = radius-sqrt(d_sq);
288                 }
289                 else
290                 {
291                         LinAl::Vector<float, 2> inside_dist(half_size.x-abs(local_delta.x), half_size.y-abs(local_delta.y));
292                         if(inside_dist.x<inside_dist.y)
293                         {
294                                 collision.normal = LinAl::Vector<float, 2>(c, s) * (local_delta.x<0 ? -1.0f : 1.0f);
295                                 collision.depth = radius+inside_dist.x;
296                         }
297                         else
298                         {
299                                 collision.normal = LinAl::Vector<float, 2>(-s, c) * (local_delta.y<0 ? -1.0f : 1.0f);
300                                 collision.depth = radius+inside_dist.y;
301                         }
302                 }
303                 collision.point = pos1-collision.normal*(radius-collision.depth/2);
304                 if(collision.body1!=i)
305                         collision.normal = -collision.normal;
306         }
307 }