~starkingdoms/starkingdoms

ref: a032d20ee4fdccaa715bbde2cb73b318222ad6e1 starkingdoms/server/src/timer.rs -rw-r--r-- 40.2 KiB
a032d20e — c0repwn3r metrics 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
use crate::entity::EntityHandler;
use crate::module::{Module, AttachedModule, ModuleTemplate};
use crate::orbit::constants::{GAME_ORBITS_ENABLED, MARS_APHELION, MARS_ORBIT_TIME, MARS_PERIHELION, MOON_APOAPSIS, MOON_ORBIT_TIME, MOON_PERIAPSIS};
use crate::orbit::orbit::{calculate_point_on_orbit, calculate_world_position_of_orbit};
use crate::{
    entity::{get_entity_id, Entity},
    manager::{ClientHandlerMessage, ClientManager, PhysicsData},
    planet::Planets,
    SCALE,
};
use async_std::sync::RwLock;
use async_std::task::sleep;
use log::{warn, debug};
use nalgebra::{point, vector};
use protobuf::SpecialFields;
use rand::Rng;
use rapier2d_f64::prelude::{ColliderBuilder, MassProperties, PhysicsPipeline, RigidBodyBuilder, SharedShape};
use starkingdoms_protocol::{module::ModuleType, planet::PlanetType, player::Player};
use std::error::Error;
use std::{f64::consts::PI, sync::Arc, time::Duration};

pub const LATERAL_FORCE: f64 = 0.0002;
pub const MODULE_SPAWN: f64 = 3.0;
pub const MODULE_MAX: u32 = 10;

//noinspection ALL
pub async fn timer_main(
    mgr: ClientManager,
    physics_data_orig: Arc<RwLock<PhysicsData>>,
    entities: Arc<RwLock<EntityHandler>>,
) -> Result<(), Box<dyn Error>> {
    let mut pipeline = PhysicsPipeline::new();

    let mut time = 0.0;
    let mut module_timer = 0.0;

    {
        let mut data_handle = physics_data_orig.write().await;

        let mut rigid_body_set = data_handle.rigid_body_set.clone();
        let mut collider_set = data_handle.collider_set.clone();

        let _ = Planets::create_planets(
            &mut rigid_body_set,
            &mut collider_set,
            &mut entities.write().await.entities,
        );

        data_handle.rigid_body_set = rigid_body_set;
        data_handle.collider_set = collider_set;
    }

    #[allow(clippy::significant_drop_tightening)]
    // underdeveloped lint, TODO remove when its better
    loop {
        sleep(Duration::from_millis(5)).await;
        time += 5.0 / 1000.0; // 5ms, time is in seconds
        module_timer += 5.0 / 1000.0;

        let mut physics_data = physics_data_orig.write().await;

        // update orbits (but dont, actually, yet)
        // DO NOT SIMPLIFY EXPRESSION
        // IT MAY ALWAYS BE TRUE
        // THATS FINE
        if GAME_ORBITS_ENABLED {
            let mut planets = entities.write().await;
            let mut map = planets.entities.clone();

            // update earth (nothing changes, yet)
            let earth_id = planets.get_planet_id(PlanetType::Earth).ok_or("earth does not exist")?;
            if let Entity::Planet(earth) = map
                .get(&earth_id)
                .ok_or("earth does not exist")? {
                let new_earth_position = vector![earth.position.0, earth.position.1];

                // update moon
                let moon_id = planets.get_planet_id(PlanetType::Moon).ok_or("moon does not exist")?;
                if let Entity::Planet(moon) = map
                    .get_mut(&moon_id)
                    .ok_or("moon does not exist")? {
                    let new_moon_position = calculate_world_position_of_orbit(
                        calculate_point_on_orbit(MOON_PERIAPSIS, MOON_APOAPSIS, time / MOON_ORBIT_TIME),
                        new_earth_position,
                    );
                    let new_moon_position = new_moon_position / SCALE;
                    let moon_body = physics_data
                        .rigid_body_set
                        .get_mut(moon.body_handle)
                        .ok_or("moon does not exist")?;
                    moon_body.set_next_kinematic_translation(new_moon_position);
                    moon.position = (
                        moon_body.translation()[0],
                        moon_body.translation()[1],
                    );

                    // update mars
                    let mars_id = planets.get_planet_id(PlanetType::Mars).ok_or("mars does not exist")?;
                    if let Entity::Planet(mars) = map
                        .get_mut(&mars_id)
                        .ok_or("mars does not exist")? {
                        let new_mars_position = calculate_world_position_of_orbit(
                            calculate_point_on_orbit(MARS_PERIHELION, MARS_APHELION, time / MARS_ORBIT_TIME),
                            new_moon_position,
                        );
                        let new_mars_position = new_mars_position/SCALE;
                        let mars_body = physics_data
                            .rigid_body_set
                            .get_mut(mars.body_handle)
                            .ok_or("mars does not exist")?;
                        mars_body.set_next_kinematic_translation(new_mars_position);
                        mars.position = (
                            mars_body.translation()[0],
                            mars_body.translation()[1],
                        );
                    }
                }
            }
            planets.entities = map;
        }

        physics_data.tick(&mut pipeline);

        let mut protocol_players = vec![];

        {
            if module_timer > MODULE_SPAWN && entities.read().await.get_module_count() < MODULE_MAX
            {
                module_timer = 0.;

                let mut rigid_body_set = physics_data.rigid_body_set.clone();
                let mut collider_set = physics_data.collider_set.clone();

                let module_collider = ColliderBuilder::cuboid(18.75 / SCALE, 23.4375 / SCALE)
                    .translation(vector![0.0, 1.5625 / SCALE])
                    .mass_properties(MassProperties::new(point![0.0, 0.0], 0.000075, 0.005))
                    .build();
                let angle: f64 = {
                    let mut rng = rand::thread_rng();
                    rng.gen::<f64>() * PI * 2.
                };
                let module_body = RigidBodyBuilder::dynamic()
                    .translation(vector![
                        angle.cos() * 2050. / SCALE,
                        angle.sin() * 2050.0 / SCALE
                    ])
                    .build();
                let module_handler = rigid_body_set.insert(module_body);
                collider_set.insert_with_parent(
                    module_collider,
                    module_handler,
                    &mut rigid_body_set,
                );

                physics_data.rigid_body_set = rigid_body_set;
                physics_data.collider_set = collider_set;

                let module = Module {
                    handle: module_handler,
                    module_type: ModuleType::Cargo,
                    lifetime: 0.0,
                    flags: 0,
                    children: Vec::new(),
                };
                entities
                    .write()
                    .await
                    .entities
                    .insert(get_entity_id(), Entity::Module(module));
            }
            let mut entities = entities.write().await;
            for module in &mut entities.get_all_attached() {
                let module_handle = module.handle;
                let module_body = physics_data
                    .rigid_body_set
                    .get_mut(module_handle)
                    .ok_or("module does not exist")?;
                module_body.reset_forces(true);
                module_body.reset_torques(true);
                let grav_force = entities.gravity(
                    (module_body.translation().x, module_body.translation().y),
                    module_body.mass(),
                );
                module_body.apply_impulse(vector![grav_force.0, grav_force.1], true);


                for child in module.children.clone() {
                    if let Some(child) = child {
                        if child.can_detach {
                            let joint = physics_data.impulse_joint_set
                                .get(child.connection).ok_or("module joint does not exist 190")?;
                            if joint.impulses.magnitude() > 0.00012 {
                                let module: Option<AttachedModule>;
                                if let Some(Entity::AttachedModule(p_module)) =
                                    entities.entities.get_mut(&child.child)
                                {
                                    module = Some(p_module.clone());
                                } else {
                                    warn!("attempted to detach nonexistent module");
                                    continue;
                                }
                                let player_id = module.as_ref().ok_or("cannot detach module that doesn't exist")?.player_id;
                                AttachedModule::detach(
                                    &mut physics_data,
                                    &mut entities,
                                    player_id,
                                    &module.ok_or("cannot detach module that doesn't exist")?,
                                );
                            }
                        }
                    }
                }
                if module.module_type == ModuleType::LandingThruster {
                    let player = entities.get_player_from_id(module.player_id).ok_or("attached module not affiliated with player")?;
                    let player_angle;
                    let player_translation;
                    {
                        let player_body = physics_data.rigid_body_set.get(player.handle).ok_or("player body does not exist")?;
                        player_angle = player_body.rotation().angle();
                        player_translation = *player_body.translation();
                    }
                    let module_body = physics_data.rigid_body_set.get_mut(module_handle).ok_or("module body does not exist")?;
                    let relative_angle = (module_body.rotation().angle() - player_angle).abs();
                    let relative_pos = module_body.translation() - player_translation;
                    let relative_pos = vector![
                        relative_pos.x.mul_add((-player_angle).cos(), -relative_pos.y * (-player_angle).sin()),
                        relative_pos.x.mul_add((-player_angle).sin(), relative_pos.y * (-player_angle).cos())
                    ];
                    let rotation = module_body.rotation().angle();
                    if player.input.up {
                        if 3.*PI/4. < relative_angle && relative_angle < 5.*PI/4. {
                            module_body.add_force_at_point(vector![
                                -LATERAL_FORCE * 3. / SCALE * rotation.sin(),
                                 LATERAL_FORCE * 3. / SCALE * rotation.cos()
                            ], point![module_body.translation().x, module_body.translation().y], true);
                        }
                    }
                    if player.input.down {
                        if (0. < relative_angle && relative_angle < PI/4.)||(7.*PI/4. < relative_angle && relative_angle < 2.*PI) {
                            module_body.add_force_at_point(vector![
                                -LATERAL_FORCE * 3. / SCALE * rotation.sin(),
                                 LATERAL_FORCE * 3. / SCALE * rotation.cos()
                            ], point![module_body.translation().x, module_body.translation().y], true);
                        }
                    }
                    if player.input.left {
                        if 3.*PI/4. < relative_angle && relative_angle < 5.*PI/4. {
                            if relative_pos.x > 2.4 {
                                module_body.add_force_at_point(vector![
                                    -LATERAL_FORCE * 3. / SCALE * rotation.sin(),
                                     LATERAL_FORCE * 3. / SCALE * rotation.cos()
                                ], point![module_body.translation().x, module_body.translation().y], true);
                            }
                        }
                        if (0. < relative_angle && relative_angle < PI/4.)||(7.*PI/4. < relative_angle && relative_angle < 2.*PI) {
                            if relative_pos.x < -2.4 {
                                module_body.add_force_at_point(vector![
                                    -LATERAL_FORCE * 3. / SCALE * rotation.sin(),
                                     LATERAL_FORCE * 3. / SCALE * rotation.cos()
                                ], point![module_body.translation().x, module_body.translation().y], true);
                            }
                        }
                        if PI/4. < relative_angle && relative_angle < 3.*PI/4. {
                            if relative_pos.y < -2.4 {
                                module_body.add_force_at_point(vector![
                                    -LATERAL_FORCE * 3. / SCALE * rotation.sin(),
                                     LATERAL_FORCE * 3. / SCALE * rotation.cos()
                                ], point![module_body.translation().x, module_body.translation().y], true);
                            }
                        }
                        if 5.*PI/4. < relative_angle && relative_angle < 7.*PI/4. {
                            if relative_pos.y > 2.4 {
                                module_body.add_force_at_point(vector![
                                    -LATERAL_FORCE * 3. / SCALE * rotation.sin(),
                                     LATERAL_FORCE * 3. / SCALE * rotation.cos()
                                ], point![module_body.translation().x, module_body.translation().y], true);
                            }
                            if -2.4 < relative_pos.y && relative_pos.y < 2.4 {
                                module_body.add_force_at_point(vector![
                                    -LATERAL_FORCE * 3. / SCALE * rotation.sin(),
                                     LATERAL_FORCE * 3. / SCALE * rotation.cos()
                                ], point![module_body.translation().x, module_body.translation().y], true);
                            }
                        }
                    }
                    if player.input.right {
                        if 3.*PI/4. < relative_angle && relative_angle < 5.*PI/4. {
                            if relative_pos.x < -2.4 {
                                module_body.add_force_at_point(vector![
                                    -LATERAL_FORCE * 3. / SCALE * rotation.sin(),
                                     LATERAL_FORCE * 3. / SCALE * rotation.cos()
                                ], point![module_body.translation().x, module_body.translation().y], true);
                            }
                        }
                        if (0. < relative_angle && relative_angle < PI/4.)||(7.*PI/4. < relative_angle && relative_angle < 2.*PI) {
                            if relative_pos.x > 2.4 {
                                module_body.add_force_at_point(vector![
                                    -LATERAL_FORCE * 3. / SCALE * rotation.sin(),
                                     LATERAL_FORCE * 3. / SCALE * rotation.cos()
                                ], point![module_body.translation().x, module_body.translation().y], true);
                            }
                        }
                        if PI/4. < relative_angle && relative_angle < 3.*PI/4. {
                            if relative_pos.y > 2.4 {
                                module_body.add_force_at_point(vector![
                                    -LATERAL_FORCE * 3. / SCALE * rotation.sin(),
                                     LATERAL_FORCE * 3. / SCALE * rotation.cos()
                                ], point![module_body.translation().x, module_body.translation().y], true);
                            }
                            if -2.4 < relative_pos.y && relative_pos.y < 2.4 {
                                module_body.add_force_at_point(vector![
                                     LATERAL_FORCE * 3. / SCALE * rotation.sin(),
                                    -LATERAL_FORCE * 3. / SCALE * rotation.cos()
                                ], point![module_body.translation().x, module_body.translation().y], true);
                            }
                        }
                        if 5.*PI/4. < relative_angle && relative_angle < 7.*PI/4. {
                            if relative_pos.y < -2.4 {
                                module_body.add_force_at_point(vector![
                                    -LATERAL_FORCE * 3. / SCALE * rotation.sin(),
                                     LATERAL_FORCE * 3. / SCALE * rotation.cos()
                                ], point![module_body.translation().x, module_body.translation().y], true);
                            }
                        }
                    }
                }
            }
        }

        {
            let mut entities = entities.write().await;
            for (player_id, player) in &entities.get_players() {
                let player_handle = player.handle;
                let player_body = physics_data
                    .rigid_body_set
                    .get_mut(player_handle)
                    .ok_or("player body does not exist")?;
                player_body.reset_forces(true);
                player_body.reset_torques(true);
                let grav_force = entities.gravity(
                    (player_body.translation().x, player_body.translation().y),
                    player_body.mass(),
                );
                player_body.apply_impulse(vector![grav_force.0, grav_force.1], true);

                let mut left_top_thruster: f64 = 0.0;
                let mut right_top_thruster: f64 = 0.0;
                let mut left_bottom_thruster: f64 = 0.0;
                let mut right_bottom_thruster: f64 = 0.0;

                if player.input.right {
                    left_top_thruster -= 1.0;
                    right_bottom_thruster += 1.0;
                }
                if player.input.left {
                    right_top_thruster -= 1.0;
                    left_bottom_thruster += 1.0;
                }

                if player.input.up {
                    left_bottom_thruster -= 1.0;
                    right_bottom_thruster -= 1.0;
                }
                if player.input.down {
                    left_top_thruster += 1.0;
                    right_top_thruster += 1.0;
                }
                left_top_thruster = LATERAL_FORCE * left_top_thruster.clamp(-1.0, 1.0);
                right_top_thruster = LATERAL_FORCE * right_top_thruster.clamp(-1.0, 1.0);
                left_bottom_thruster = LATERAL_FORCE * left_bottom_thruster.clamp(-1.0, 1.0);
                right_bottom_thruster = LATERAL_FORCE * right_bottom_thruster.clamp(-1.0, 1.0);

                let rotation = player_body.rotation().clone().angle();
                let scale = SCALE;
                let left_top_thruster = vector![
                    -left_top_thruster / scale * rotation.sin(),
                    left_top_thruster / scale * rotation.cos()
                ];
                let right_top_thruster = vector![
                    -right_top_thruster / scale * rotation.sin(),
                    right_top_thruster / scale * rotation.cos()
                ];
                let left_bottom_thruster = vector![
                    -left_bottom_thruster / scale * rotation.sin(),
                    left_bottom_thruster / scale * rotation.cos()
                ];
                let right_bottom_thruster = vector![
                    -right_bottom_thruster / scale * rotation.sin(),
                    right_bottom_thruster / scale * rotation.cos()
                ];
                let top_left_point = point![
                    (-25. / scale).mul_add(rotation.cos(), 25. / scale * rotation.sin()),
                    (-25. / scale).mul_add(rotation.sin(), -25. / scale * rotation.cos())
                ] + player_body.translation();
                let top_right_point = point![
                    (25. / scale).mul_add(rotation.cos(), 25. / scale * rotation.sin()),
                    (25. / scale).mul_add(rotation.sin(), -25. / scale * rotation.cos())
                ] + player_body.translation();
                let bottom_left_point = point![
                    (-25. / scale).mul_add(rotation.cos(), -25. / scale * rotation.sin()),
                    (-25. / scale).mul_add(rotation.sin(), 25. / scale * rotation.cos())
                ] + player_body.translation();
                let bottom_right_point = point![
                    (25. / scale).mul_add(rotation.cos(), -25. / scale * rotation.sin()),
                    (25. / scale).mul_add(rotation.sin(), 25. / scale * rotation.cos())
                ] + player_body.translation();

                player_body.add_force_at_point(left_top_thruster, top_left_point, true);
                player_body.add_force_at_point(right_top_thruster, top_right_point, true);
                player_body.add_force_at_point(left_bottom_thruster, bottom_left_point, true);
                player_body.add_force_at_point(right_bottom_thruster, bottom_right_point, true);

                let translation = player_body.translation();

                let username;
                {
                    let usernames = mgr.usernames.read().await;
                    username = usernames
                        .get(player_id)
                        .ok_or("username does not exist")?
                        .clone();
                }

                protocol_players.push(Player {
                    rotation,
                    x: (translation.x * SCALE),
                    y: (translation.y * SCALE),
                    username,
                    special_fields: SpecialFields::default(),
                });

                for child in player.children.clone() {
                    if let Some(child) = child {
                        let joint = match physics_data.impulse_joint_set
                            .get(child.connection) {
                            Some(c) => c,
                            None => { warn!("module joint doesn't exist"); continue; }
                        };
                        // displays impulse on joint * 10000 so its visible, use to tune breaking
                        // force
                        //debug!("impulse: {}", joint.impulses.magnitude() * 10000.);
                        if joint.impulses.magnitude() > 0.00012 {
                            let module: Option<AttachedModule>;
                            if let Some(Entity::AttachedModule(p_module)) =
                                entities.entities.get_mut(&child.child)
                            {
                                module = Some(p_module.clone());
                            } else {
                                warn!("attempted to detach nonexistent module");
                                continue;
                            }
                            let player_id = module.as_ref().ok_or("cannot detach module that doesn't exist")?.player_id;
                            AttachedModule::detach(
                                &mut physics_data,
                                &mut entities,
                                player_id,
                                &module.ok_or("cannot detach module that doesn't exist")?,
                            );
                        }
                    }
                }
            }
        }
        {
            let mut entities = entities.write().await;
            for planet in &entities.get_planets() {
                let body = physics_data.rigid_body_set.get(planet.body_handle).ok_or("planet body not found")?;
                let collider = body.colliders()[1];
                let narrow = physics_data.narrow_phase.clone();
                for (collider1, collider2, intersecting) in narrow.intersections_with(collider) {
                    if intersecting {
                        if collider1 == collider {
                            let collider_handle = match physics_data.collider_set.get_mut(collider2).ok_or("body doesn't exist collider2") {
                                Ok(c) => c,
                                Err(s) => { warn!("{}", s); continue; }
                            };
                            let body_handle = collider_handle.parent().ok_or("collider not attached to body")?;
                            let entity = entities.get_entity_from_handle(body_handle).ok_or("entity body doesn't exist")?;
                            match entity {
                                Entity::Player(player) => {
                                    let tree = player.search_modules(&entities);
                                    for module in tree {
                                        if module.module_type == ModuleType::Cargo {
                                            let module_id = entities.get_id_from_attached(&module)
                                                .ok_or("module doesn't exist")?;
                                            let module_handle =physics_data.rigid_body_set.get(module.handle)
                                                .ok_or("attached module body does not exist")?.colliders()[0];
                                            let module_collider = physics_data.collider_set.get_mut(module_handle)
                                                .ok_or("attached module collider does not exist")?;
                                            if let Entity::AttachedModule(attached) = entities.entities.get_mut(&module_id)
                                                .ok_or("module doesn't exist")? {
                                                match planet.planet_type {
                                                    PlanetType::Mars => {
                                                        attached.module_type = ModuleType::Hub;
                                                        module_collider.set_shape(SharedShape::cuboid(25./SCALE, 25./SCALE));
                                                        module_collider.set_translation_wrt_parent(vector![0., 0.]);
                                                    }
                                                    PlanetType::Moon => {
                                                        attached.module_type = ModuleType::LandingThruster;
                                                        module_collider.set_shape(SharedShape::cuboid(25./SCALE, 18.75/SCALE));
                                                        module_collider.set_translation_wrt_parent(vector![0., 6.25/SCALE]);
                                                        AttachedModule::attach_new(&mut physics_data, &mut entities,
                                                                                   module_id, module.player_id,
                                                                                   &ModuleTemplate {
                                                                                       mass_properties: MassProperties::new(point![0.0, 0.0], 0.000075, 0.005),
                                                                                       module_type: ModuleType::LandingThrusterSuspension,
                                                                                   }, 2);
                                                    }
                                                    _ => {}
                                                };
                                            }
                                        }
                                    }
                                }
                                Entity::AttachedModule(module) => {
                                    let tree = entities.get_player_from_id(module.player_id).ok_or("player not found on attached")?
                                        .search_modules(&entities);
                                    for module in tree {
                                        if module.module_type == ModuleType::Cargo {
                                            let module_id = entities.get_id_from_attached(&module)
                                                .ok_or("attached module doesn't exist")?;
                                            let module_handle =physics_data.rigid_body_set.get(module.handle)
                                                .ok_or("attached module body does not exist")?.colliders()[0];
                                            let module_collider = physics_data.collider_set.get_mut(module_handle)
                                                .ok_or("attached module collider does not exist")?;
                                            if let Entity::AttachedModule(attached) = entities.entities.get_mut(&module_id)
                                                .ok_or("module doesn't exist")? {
                                                match planet.planet_type {
                                                    PlanetType::Mars => {
                                                        attached.module_type = ModuleType::Hub;
                                                        module_collider.set_shape(SharedShape::cuboid(25./SCALE, 25./SCALE));
                                                        module_collider.set_translation_wrt_parent(vector![0., 0.]);
                                                    }
                                                    PlanetType::Moon => {
                                                        attached.module_type = ModuleType::LandingThruster;
                                                        module_collider.set_shape(SharedShape::cuboid(25./SCALE, 18.75/SCALE));
                                                        module_collider.set_translation_wrt_parent(vector![0., 6.25/SCALE]);
                                                        AttachedModule::attach_new(&mut physics_data, &mut entities,
                                                                                   module_id, module.player_id,
                                                                                   &ModuleTemplate {
                                                                                       mass_properties: MassProperties::new(point![0.0, 0.0], 0.000075, 0.005),
                                                                                       module_type: ModuleType::LandingThrusterSuspension,
                                                                                   }, 2);
                                                    }
                                                    _ => {}
                                                };
                                            }
                                        }
                                    }
                                }
                                _ => {}
                            }
                        }
                    }
                }
            }
            for module in &mut entities.get_modules() {
                let module_handle = module.handle;
                let module_body = physics_data
                    .rigid_body_set
                    .get_mut(module_handle)
                    .ok_or("module does not exist")?;
                module_body.reset_forces(true);
                module_body.reset_torques(true);
                let grav_force = entities.gravity(
                    (module_body.translation().x, module_body.translation().y),
                    module_body.mass(),
                );
                module_body.apply_impulse(vector![grav_force.0, grav_force.1], true);
                let id = entities
                    .get_from_module(module)
                    .ok_or("module entity does not exist")?;
                if let Entity::Module(p_module) = entities
                    .entities
                    .get_mut(&id)
                    .ok_or("module does not exist")?
                {
                    p_module.lifetime += 5. / 1000.;
                }
                if module.lifetime > 80. {
                    let mut rigid_body_set = physics_data.rigid_body_set.clone();
                    let mut island_manager = physics_data.island_manager.clone();
                    let mut collider_set = physics_data.collider_set.clone();
                    let mut impulse_joint_set = physics_data.impulse_joint_set.clone();
                    let mut multibody_joint_set = physics_data.multibody_joint_set.clone();
                    rigid_body_set.remove(
                        module.handle,
                        &mut island_manager,
                        &mut collider_set,
                        &mut impulse_joint_set,
                        &mut multibody_joint_set,
                        true,
                    );
                    physics_data.rigid_body_set = rigid_body_set;
                    physics_data.collider_set = collider_set;
                    physics_data.island_manager = island_manager;
                    physics_data.impulse_joint_set = impulse_joint_set;
                    physics_data.multibody_joint_set = multibody_joint_set;
                    entities.entities.remove(&id);
                }
            }
        }

        let mut to_remove = vec![];

        let mut mgr_w = mgr.handlers.write().await;
        let mgr_r = mgr_w.clone();

        for (addr, client_thread) in &mgr_r {
            match client_thread.tx.send(ClientHandlerMessage::Tick).await {
                Ok(_) => {
                    match client_thread
                        .tx
                        .send(ClientHandlerMessage::PlayersUpdate {
                            players: protocol_players.clone(),
                        })
                        .await
                    {
                        Ok(_) => (),
                        Err(e) => {
                            warn!("unable to send position packet: {}", e);
                        }
                    };
                    let modules = entities.read().await.get_modules_id();
                    let entities = entities.read().await;
                    let this_player = entities.get_player_id(*addr);
                    let mut attached_modules: Vec<starkingdoms_protocol::module::AttachedModule> =
                        Vec::new();
                    let unattached_modules = entities.get_all_attached();
                    let mut unattached_modules: Vec<starkingdoms_protocol::module::Module> =
                        unattached_modules
                            .iter()
                            .filter(|m| match this_player {
                                Some(id) => {
                                    if m.player_id == id {
                                        #[allow(clippy::expect_used)]
                                        {
                                            attached_modules.push(
                                                m.to_protocol(
                                                    &entities,
                                                    &physics_data.rigid_body_set,
                                                )
                                                .expect("module does not exist"),
                                            );
                                        }
                                        false
                                    } else {
                                        true
                                    }
                                }
                                None => true,
                            })
                            .map(|m| {
                                let id;
                                let module;
                                #[allow(clippy::expect_used)]
                                {
                                    (id, module) =
                                        m.to_module_id(&entities).expect("unable to get module id");
                                }
                                //info!("{:?}", module);
                                let body;
                                #[allow(clippy::expect_used)]
                                {
                                    body = physics_data
                                        .rigid_body_set
                                        .get(module.handle)
                                        .expect("module body does not exist");
                                }
                                let children = module.children.iter().map(|c| {
                                    starkingdoms_protocol::module::Attachment {
                                        id: c.child,
                                        slot: 0,
                                        special_fields: SpecialFields::default(),
                                    }
                                }).collect();

                                starkingdoms_protocol::module::Module {
                                    module_type: module.module_type.into(),
                                    rotation: body.rotation().angle(),
                                    x: body.translation().x * SCALE,
                                    y: body.translation().y * SCALE,
                                    id,
                                    flags: module.flags,
                                    children,
                                    special_fields: SpecialFields::default(),
                                }
                            })
                            .collect();
                    let mut protocol_modules: Vec<starkingdoms_protocol::module::Module> = modules
                        .iter()
                        .map(|(id, module)| {
                            let body;

                            #[allow(clippy::expect_used)]
                            {
                                body = physics_data
                                    .rigid_body_set
                                    .get(module.handle)
                                    .expect("module body does not exist");
                            }

                            let children = module.children.iter().map(|c| {
                                starkingdoms_protocol::module::Attachment {
                                    id: c.child,
                                    slot: 0,
                                    special_fields: SpecialFields::default(),
                                }
                            }).collect();
                            starkingdoms_protocol::module::Module {
                                module_type: module.module_type.into(),
                                rotation: body.rotation().angle(),
                                x: body.translation().x * SCALE,
                                y: body.translation().y * SCALE,
                                id: *id,
                                flags: module.flags,
                                children,
                                special_fields: SpecialFields::default(),
                            }
                        })
                        .collect();
                    protocol_modules.append(&mut unattached_modules);
                    match client_thread
                        .tx
                        .send(ClientHandlerMessage::ModulesUpdate {
                            modules: protocol_modules.clone(),
                        })
                        .await
                    {
                        Ok(_) => (),
                        Err(e) => {
                            warn!("unable to send module position packet: {}", e);
                        }
                    };

                    match client_thread
                        .tx
                        .send(ClientHandlerMessage::ModuleTreeUpdate {
                            modules: attached_modules,
                        })
                        .await
                    {
                        Ok(_) => (),
                        Err(e) => {
                            warn!("unable to send module tree update packet: {}", e);
                        }
                    }

                    let planet_data = entities.to_protocol();
                    match client_thread.tx.send(planet_data).await {
                        Ok(_) => (),
                        Err(e) => {
                            warn!("unable to send earth packet: {}", e);
                        }
                    };
                }
                Err(e) => {
                    warn!("unable to update a client thread: {}", e);
                    to_remove.push(addr);
                }
            }
        }

        for pending_removal in to_remove {
            mgr_w.remove(pending_removal);
        }
    }
}