twgame 0.11.0

DDNet physics implementation
Documentation
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
//! The state accessible to entities

//! # Team
//!
//! A team in twgame an isolated game world with accessors to all contained objects. Each entity,
//! which needs to access other entities during its tick method needs to hold a Team object. The
//! Team object act like a smart pointer and can be freely cloned, only increasing the reference count

use crate::entities::tee::TEE_PROXIMITY;
use crate::entities::tee::{Tee, TeeCore};
use crate::entities::{
    EntityItem, EntityItemNew, MapEntity, MapEntityItem, SpawnOrder, SpawnOrderEntity,
    SpawnableEntity,
};
use crate::ids::{PlayerUid, TeamId};
use crate::map::Map;
use crate::teams::{Activity, Client};
use crate::{coord, SnapOuter};
use bugs::Bugs;
use database::Database;
use entities::Entities;
use globals::Globals;
use rand_pcg::Lcg64Xsh32;
use slotmap::SecondaryMap;
use std::cell::RefCell;
use std::fmt::Write;
use std::mem;
use std::rc::Rc;
use std::sync::{mpsc, Arc};
use twgame_core::database::FinishTeam;
use twgame_core::database::{DatabaseWrite, SaveTeam};
use twgame_core::net_msg::ClPlayerInfo;
use twgame_core::normalize;
use twgame_core::twsnap;
use twgame_core::twsnap::time::{Duration, Instant};
use twgame_core::twsnap::{vec2_from_bits, Snap};
use twgame_core::Input;
use uuid::Uuid;
use vek::num_traits::clamp;
use vek::Vec2;

mod bugs;
mod database;
mod entities;
mod events;
mod globals;
mod players;
mod prng;
mod tee_order;
mod tees;

pub use bugs::{Bug, BugKind};
pub use events::Events;
pub use globals::TeamKind;
pub use players::PauseMode;
pub use players::Player;
pub use players::Players;
pub use players::SpawnMode;
pub use prng::Prng;
pub use tee_order::TeeOrder;
pub use tees::closest_point_on_line;
pub use tees::Tees;

/// The GameState that is stored in the Team. This has more privileges to change stuff than the
/// `GameState` passed to the entities.
#[derive(Debug)]
pub struct PrivilegedGameState {
    id: TeamId,

    inner: GameState,
    tee_order: TeeOrder,
    tees: Tees<Tee>,

    players: Players,

    /// entities included in the map. Keep them in `PrivilegedGameState`, because they hold state
    /// per team.
    map_entities: Vec<MapEntityItem>,
}

/// The GameState passed to Entities.
#[derive(Debug)]
pub struct GameState {
    /// current map
    pub map: Rc<Arc<Map>>,
    /// global variables
    // TODO: config
    pub globals: Globals,
    /// Accessor to the tee cores provided a `TeeUid`
    pub tee_cores: Tees<TeeCore>,
    /// iterator for tee_uids in the team either in spawn or in player_id order
    pub tee_order: TeeOrder,
    /// Accessor for adding entities in the next tick
    pub entities: Entities,
    /// Deterministic random number generator
    pub prng: Prng,
    /// Accessor for adding snap events like effects or sounds
    pub events: Events,
    /// Collect bugs used during the game
    pub bugs: Bugs,
    // TODO: database_queries => struct to initiate database queries
    pub database: Database,
}

impl PrivilegedGameState {
    pub fn new(
        map: Rc<Arc<Map>>,
        team_id: TeamId,
        team_kind: TeamKind,
        prng_description: Lcg64Xsh32,
        database_sender: mpsc::Sender<DatabaseWrite>,
    ) -> Self {
        let map_entities = map.entities.clone();
        Self {
            id: team_id,
            inner: GameState {
                map,
                tee_cores: Tees::new(),
                tee_order: TeeOrder::new(),
                entities: Entities::new(team_id),
                prng: Prng::new(team_id, prng_description),
                events: Events::new(),
                globals: Globals::new(team_id, team_kind),
                bugs: Bugs::new(),
                database: database::Database::new(database_sender),
            },
            tees: Tees::new(),
            tee_order: TeeOrder::new(),
            players: Players::new(),
            map_entities,
        }
    }

    pub fn create_new(&self, team_id: TeamId, compat: bool) -> Self {
        let mut team_kind = self.inner.globals.team_kind();
        if team_kind == TeamKind::Team0 {
            team_kind = TeamKind::NonTeam0;
        }

        Self {
            id: team_id,
            inner: GameState {
                map: self.inner.map.clone(),
                tee_cores: Tees::new(),
                tee_order: TeeOrder::new(),
                entities: if compat {
                    // shared EntityList in compat mode
                    Entities::new_compat(team_id, self.inner.entities.clone_next_tick())
                } else {
                    // separate EntityList
                    Entities::new(team_id)
                },
                prng: self.inner.prng.create_new(team_id),
                events: Events::new(),
                globals: Globals::new(team_id, team_kind),
                bugs: self.inner.bugs.create_new(),
                database: Database::new(self.inner.database.clone_sender()),
            },
            tees: Tees::new(),
            tee_order: TeeOrder::new(),
            players: Players::new(),
            map_entities: self.inner.map.entities.clone(),
        }
    }

    pub(crate) fn entities_next_tick(&self) -> Rc<RefCell<Vec<(TeamId, EntityItemNew)>>> {
        self.inner.entities.clone_next_tick()
    }

    pub(crate) fn overwrite_prng(&mut self, prng_description: Lcg64Xsh32) {
        self.inner.prng.overwrite(prng_description);
    }

    pub(crate) fn supply_prng_compat_data(&mut self, compat_data: &str) {
        self.inner.prng.supply_compat_data(compat_data);
    }

    pub(crate) fn enable_prng_compat_data_collection(&mut self) {
        self.inner.prng.enable_compat_data_collection();
    }

    pub(crate) fn retrieve_prng_compat_data(&mut self) -> Option<String> {
        self.inner.prng.retrieve_compat_data()
    }

    pub(crate) fn retrieve_bugs(&self) -> Vec<Bug> {
        self.inner.bugs.retrieve_bugs()
    }

    pub(crate) fn clear_events(&mut self) {
        self.inner.events.clear();
    }

    pub(crate) fn snap(&self, team_id: TeamId, snapshot: &mut Snap) {
        for entity in self.map_entities.iter() {
            entity.snap(snapshot);
        }
        for (player_uid, player) in self.players.players.iter() {
            player.snap(team_id, player_uid, snapshot);
        }
        snapshot.events.extend_from_slice(&self.inner.events.events);
    }

    pub(crate) fn toggle_lock(&mut self) {
        self.inner.globals.toggle_lock();
    }

    pub(crate) fn set_lock(&mut self, locked: bool) {
        self.inner.globals.set_lock(locked);
    }

    pub(crate) fn is_locked(&self) -> bool {
        self.inner.globals.is_locked()
    }

    pub(crate) fn can_load(&self) -> bool {
        self.inner.globals.can_load()
    }

    fn match_tee(&mut self, player_name: &str) -> Option<(&mut Player, &mut Tee, &mut TeeCore)> {
        // find player by name
        for (player_uid, player) in self.players.players.iter_mut() {
            if player.name.as_str() == player_name {
                let tee = self
                    .tees
                    .get_tee_mut(player_uid)
                    .expect("handle tee not living during load");
                let tee_core = self
                    .inner
                    .tee_cores
                    .get_tee_mut(player_uid)
                    .expect("Tee exists, but TeeCore doesn't");
                return Some((player, tee, tee_core));
            }
        }
        None
    }

    pub(crate) fn load(&mut self, now: Instant, save_team: SaveTeam) {
        save_team.pretty_print();
        // TODO: test with old save codes
        // TODO: make sure that exactly the players are in the team, that are in the save game
        //       and only initiate loading when correct tees are in team.
        // TODO: maybe just create new Team object and replace this one with the loaded one on
        //       success
        // TODO: remove projectiles
        let mut items = save_team.buf().split('\n');
        let mut team_info = items.next().unwrap().split('\t');

        let _team_state: i32 = team_info.next().unwrap().parse().unwrap();
        let members_count: i32 = team_info.next().unwrap().parse().unwrap();
        let _highest_switch_number: i32 = team_info.next().unwrap().parse().unwrap();
        let team_locked: i32 = team_info.next().unwrap().parse().unwrap();
        let _practice: i32 = team_info
            .next()
            .map(|p| p.parse::<i32>().unwrap())
            .unwrap_or(0);
        let mut uuid = Uuid::new_v4();
        let mut start_time = None;
        for _ in 0..members_count {
            let mut tee_info = items.next().unwrap().split('\t');
            let player_name = tee_info.next().unwrap();
            if let Some((_player, tee, tee_core)) = self.match_tee(player_name) {
                uuid = tee.load(now, tee_core, tee_info);
                if let Some(tee_start) = tee.start_time() {
                    if let Some(team_start) = start_time {
                        if tee_start < team_start {
                            start_time = Some(tee_start)
                        }
                    } else {
                        start_time = Some(tee_start)
                    }
                }
            }
        }
        self.inner.globals.load(team_locked != 0, start_time);
        // TODO: only for debug
        let save = SaveTeam::from_string(self.save(now, uuid, false));
        // TODO: fail test if unsuccessful
        save.print_diff(&save_team);
    }

    pub(crate) fn can_save(&self) -> bool {
        self.inner.globals.can_save()
    }

    pub(crate) fn save(&self, now: Instant, game_uuid: Uuid, add_time_penalty: bool) -> String {
        let mut f = String::with_capacity(4096);
        let team_state = 2;
        let members_count = self.inner.tee_order.member_count();
        let highest_switch_number = 0;
        let team_locked = self.is_locked() as i32;
        let practice = false as i32;

        write!(
            f,
            "{team_state}\t{members_count}\t{highest_switch_number}\t{team_locked}\t{practice}"
        )
        .unwrap();
        // TODO: go through all entities in spawn order instead of only Tees

        for tee_uid in self.tee_order.spawn_order() {
            // TODO: disallow save in team0 and when not all players exist
            let tee = self.tees.get_tee(tee_uid).unwrap();
            let tee_core = self.inner.tee_cores.get_tee(tee_uid).unwrap();
            let player = self.players.get(tee.player_uid()).unwrap();
            tee.format_save(now, player, tee_core, &mut f, game_uuid, add_time_penalty)
                .unwrap();
        }
        f
    }
}

impl GameState {
    fn evaluate_spawn_point(&self, point: Vec2<f32>) -> f32 {
        // TODO: Check if DDNet somehow handles infinity differently.
        // The division with zero could be an edge case.
        self.tee_order
            .spawn_order()
            .tees(&self.tee_cores)
            .map(|(_, tee)| 1.0 / point.distance(tee.pos()))
            .sum()
    }

    fn evaluate_spawn_points(&self, spawn_points: &[Vec2<i32>]) -> Option<(Vec2<i32>, f32)> {
        let mut best_spawn: Option<(Vec2<i32>, f32)> = None;
        for check_occupied in [true, false] {
            for spawn_point in spawn_points {
                let positions = [
                    Vec2::new(0, 0),
                    Vec2::new(-1, 0),
                    Vec2::new(0, -1),
                    Vec2::new(1, 0),
                    Vec2::new(0, 1),
                ];
                for p in positions.iter() {
                    let spawn_candidate = spawn_point + p;
                    let spawn_candidate_float =
                        coord::to_float(spawn_candidate) + Vec2::new(16.0, 16.0);
                    if self.map.is_solid(spawn_candidate) {
                        continue;
                    }

                    if check_occupied {
                        // try next spawn candidate around spawn point if any player already collides with spawn point
                        let occupied = self
                            .tee_order
                            .spawn_order()
                            .tees(&self.tee_cores)
                            .any(|(_, tee)| tee.collides_point(spawn_candidate_float));
                        if occupied {
                            continue;
                        }
                    }
                    let score = self.evaluate_spawn_point(spawn_candidate_float);
                    if let Some(s) = &best_spawn {
                        if s.1 > score {
                            best_spawn = Some((spawn_candidate, score));
                        }
                    } else {
                        best_spawn = Some((spawn_candidate, score));
                    }
                    break; // only try one unoccupied/viable spawn candidate per spawn point
                }
            }
            if best_spawn.is_some() {
                return best_spawn;
            }
        }
        // No possible spawn found
        None
    }

    /// Returns currently best spawn point, non-occupied if possible.
    /// Only returns None, if no spawn points exist in the map or all spawn points are inside walls.
    pub(crate) fn get_spawn_point(&self) -> Option<Vec2<f32>> {
        self.map
            .spawn_points
            .iter()
            .filter_map(|spawn_points| self.evaluate_spawn_points(spawn_points))
            .reduce(|a, b| if a.1 <= b.1 { a } else { b })
            .map(|(pos, _score)| coord::to_float(pos) + Vec2::new(16.0, 16.0))
    }

    pub(crate) fn select_tele_checkpoint_out(&mut self, now: Instant, tele_in: u8) -> Vec2<f32> {
        // first check if there is a tele_checkpoint_out for the current recorded checkpoint, if not check previous checkpoints
        for k in (1..=tele_in).rev() {
            if self.map.tele_checkpoint_outs[k as usize].is_empty() {
                continue;
            }
            let tele_out = self
                .prng
                .random_or_0(now, self.map.tele_checkpoint_outs[k as usize].len() as u32);
            return coord::to_float(self.map.tele_checkpoint_outs[k as usize][tele_out as usize])
                + Vec2::new(16.0, 16.0);
        }
        // If no tele_checkpoint_out have been found (or if there no recorded checkpoint), teleport to start.
        // Only panics if no spawn is available.
        self.get_spawn_point().unwrap()
    }

    pub fn create_explosion(&mut self, owner: PlayerUid, pos: Vec2<f32>, strength: f32) {
        let owner_solo = self
            .tee_cores
            .get_tee(owner)
            .map(|tee| tee.is_solo())
            .unwrap_or(false);
        let mut iter = self.tee_order.spawn_order().tees_mut(&mut self.tee_cores);
        while let Some((tee_uid, tee)) = iter.next() {
            if tee_uid != owner && (owner_solo || tee.is_solo()) // don't hit other tees when owner or other tee is solo
                || tee.pos().distance(pos) >= TEE_PROXIMITY + 135.0
            {
                continue;
            }
            let diff = tee.pos() - pos;
            let mut force_dir = Vec2::new(0.0, 1.0);
            let mut l = diff.magnitude();
            if l != 0.0 {
                force_dir = normalize(diff);
            }
            l = 1.0 - clamp((l - 48.0) / (135.0 - 48.0), 0.0, 1.0);
            let dmg = strength * l;
            if dmg as i32 == 0 {
                continue;
            }
            tee.impact(force_dir * dmg * 2.0, true);
        }

        self.events
            .add_event(twsnap::Events::Explosion(twsnap::events::Explosion {
                pos: vec2_from_bits(pos),
            }));
    }

    pub fn on_tee_start(&mut self, now: Instant) {
        if self.globals.team_kind() == TeamKind::Team0 {
            // in team0 player time is stored individually
            return;
        }
        if self.globals.start_time.is_none() {
            self.globals.start_time = Some(now);
        }
    }

    pub fn on_tee_finish(&mut self, now: Instant, start_time: Instant, tee_uid: PlayerUid) {
        if self.globals.team_kind() == TeamKind::Team0 {
            let time = now.duration_since(start_time).unwrap();
            // TODO: somehow get the name (probably need to store a PlayerCore for the name in
            //       GameState
            let Some(name) = Some("Zwelf") else { todo!() };
            self.database.add(DatabaseWrite::finish_tee(name, time));
            // check if player did go over start line
        } else if let Some(team_start_time) = self.globals.start_time {
            // check if all tees finished and initiate event
            self.globals.all_finished = self
                .tee_order
                .spawn_order()
                .tees_except(&self.tee_cores, tee_uid)
                .all(|(_, tee)| tee.has_finished());
            if self.globals.all_finished {
                let time = now.duration_since(team_start_time).unwrap();

                self.database.add(DatabaseWrite::FinishTeam(FinishTeam {
                    team: self.globals.team_id().to_i32(),
                    // TODO: get all player names in GameState again.
                    names: vec!["Zwelf".to_owned()],
                    time,
                }))
            }
        }
    }
}

pub(crate) trait AssociatedGameState {
    fn get_game_state(&self, team_id: TeamId) -> &PrivilegedGameState;
}

pub(crate) trait AssociatedGameStateMut: AssociatedGameState {
    fn get_game_state_mut(&mut self, team_id: TeamId) -> &mut PrivilegedGameState;
}

impl AssociatedGameState for PrivilegedGameState {
    fn get_game_state(&self, team_id: TeamId) -> &PrivilegedGameState {
        assert_eq!(team_id, self.id);
        self
    }
}

impl AssociatedGameStateMut for PrivilegedGameState {
    fn get_game_state_mut(&mut self, team_id: TeamId) -> &mut PrivilegedGameState {
        assert_eq!(team_id, self.id);
        self
    }
}

/// This struct represents one list of entities. It could contain multiple teams like in DDNet for
/// backwards compatible teleporters or only one team to have cleaner separation. The `EntityList`
/// also contains all `Players` that are relevant for the contained Tees.
#[derive(Debug)]
pub(crate) struct EntityList {
    /// all entities in spawn order including tees
    entities: Vec<(TeamId, EntityItem)>,

    next_tick: Rc<RefCell<Vec<(TeamId, EntityItemNew)>>>,
}

impl EntityList {
    pub(crate) fn new(entities_next_tick: Rc<RefCell<Vec<(TeamId, EntityItemNew)>>>) -> Self {
        Self {
            entities: vec![],
            next_tick: entities_next_tick,
        }
    }

    pub(crate) fn snap(
        &self,
        now: Instant,
        game_state_provider: &dyn AssociatedGameState,
        snapshot: &mut Snap,
    ) {
        for (team_id, entity) in self.entities.iter() {
            let game_state = game_state_provider.get_game_state(*team_id);
            entity.snap(now, &game_state.inner, snapshot, &game_state.tees);
        }
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.entities.is_empty()
    }

    pub(crate) fn on_swap_tees(
        &mut self,
        game_state: &mut PrivilegedGameState,
        team_id: TeamId,
        pid1: PlayerUid,
        pid2: PlayerUid,
    ) {
        for (tid, entity) in self.entities.iter_mut() {
            if team_id == *tid {
                entity.on_tee_swap(&mut game_state.tees, pid1, pid2);
            }
        }
    }
}

impl PrivilegedGameState {
    pub(crate) fn player_join(&mut self, now: Instant, player_uid: PlayerUid) -> PlayerUid {
        self.players.player_join(now, player_uid);
        player_uid
    }

    pub(crate) fn player_join_from_spectator(&mut self, player_uid: PlayerUid, player: Player) {
        self.players.player_join_from_spectator(player_uid, player);
    }

    pub(crate) fn player_join_from_other_team(
        &mut self,
        player_uid: PlayerUid,
        old_team: &mut PrivilegedGameState,
        from_entities: &mut EntityList,
        to_entities: Option<&mut EntityList>,
    ) {
        let mut player = old_team.players.player_leave(player_uid).unwrap();
        player.switch_team(old_team, self, from_entities, to_entities);
        self.players.player_join_from_other_team(player_uid, player);
    }

    pub(crate) fn player_join_team0_from_other_team(
        &mut self,
        player_uid: PlayerUid,
        mut player: Player,
    ) {
        if !player.tee {
            player.mark_spawn_at_end_of_tick(SpawnMode::Normal);
        }
        self.players.player_join_from_other_team(player_uid, player);
    }

    pub(crate) fn player_ready(&mut self, player_uid: PlayerUid) {
        // assumes that only tee position of existing players can be set
        let player = self.players.get_mut(player_uid).unwrap();
        player.in_game = true;
        player.mark_spawn_at_end_of_tick(SpawnMode::Normal);
    }

    pub(crate) fn player_input(&mut self, player_uid: PlayerUid, input: &Input) {
        // assumes that only tee position of existing players can be set
        let p = self.players.get_mut(player_uid).unwrap();
        p.input = input.clone();
        if let Some(tee) = self.tees.get_tee_mut(player_uid) {
            tee.received_input()
        }
    }

    pub(crate) fn start_info(&mut self, player_uid: PlayerUid, player_info: &ClPlayerInfo) {
        if let Some(p) = self.players.get_mut(player_uid) {
            p.on_player_info(player_info);
        }
    }

    pub(crate) fn change_info(&mut self, player_uid: PlayerUid, player_info: &ClPlayerInfo) {
        if let Some(p) = self.players.get_mut(player_uid) {
            p.on_player_info(player_info);
        }
    }

    pub(crate) fn player_leave(&mut self, player_uid: PlayerUid) -> Player {
        // assumes that only tee position of existing players can be set
        let player = self.players.player_leave(player_uid).unwrap();
        if let Some(tee) = self.tees.get_tee_mut(player_uid) {
            tee.mark_for_destroy();
        }
        player
    }

    /// # Panics
    ///
    /// if player doesn't exist
    pub(crate) fn tee_pos(&self, player_uid: PlayerUid) -> Option<Vec2<i32>> {
        let tee = self.inner.tee_cores.get_tee(player_uid)?;
        Some(tee.get_tee_pos())
    }

    /// # Panics
    ///
    /// if player doesn't exist
    pub(crate) fn set_tee_pos(
        &mut self,
        entity_list: &mut EntityList,
        now: Instant,
        player_uid: PlayerUid,
        pos: Option<Vec2<i32>>,
    ) {
        let player_tee = self.inner.tee_cores.get_tee_mut(player_uid);
        match (pos, player_tee) {
            (Some(pos), Some(tee)) => {
                tee.set_tee_pos(pos);
            }
            (Some(pos), None) => {
                let p = self.players.get_mut(player_uid).unwrap();
                p.tee = true;
                p.spawning = None;
                let input = p.input.clone();
                // spawn new tee
                self.spawn_tee(
                    entity_list,
                    player_uid,
                    now,
                    Vec2::new(pos.x as f32, pos.y as f32),
                    SpawnMode::Normal,
                    input,
                );
            }
            (None, Some(_)) => {
                self.kill_tee(now, player_uid, SpawnMode::Normal);
            }
            (None, None) => {}
        }
    }

    /// returns whether to kill remaining tees in team, because team was locked
    pub(crate) fn kill_tee(
        &mut self,
        now: Instant,
        player_uid: PlayerUid,
        spawn_mode: SpawnMode,
    ) -> bool {
        let Some(tee) = self.tees.get_tee_mut(player_uid) else {
            return false;
        };

        if !tee.is_marked_for_destroy() {
            let player = self.players.get_mut(player_uid).unwrap();
            tee.mark_for_destroy();
            player.mark_spawn_at_end_of_tick(spawn_mode);
            player.previous_die_tick = player.die_tick;
            player.die_tick = now;
            return true;
        }
        false
    }

    // TODO: rename to team0
    /// This tick function is called before the current tick tick `now: Instant` is advanced by one.
    pub(crate) fn tick_0_fire_direct(&mut self, now: Instant, snap_outer: &mut SnapOuter) {
        // order in the ddnet source code:
        //
        // ```
        // for player in players:
        //     GameServer->OnClientPredictedEarlyInput /* weapons? */
        // for player in players:
        //     GameServer->OnClientPredictedInput /* other inputs */
        for (player_uid, player) in self.players.players.iter_mut() {
            player.on_input();
            if player.tee {
                let Some(tee) = self.tees.get_tee_mut(player_uid) else {
                    // TODO: why is check for existence necessary?
                    continue;
                };
                // This conditional: https://github.com/ddnet/ddnet/blob/aecae3f7e51c0a44e45fa94d62bccf8bbfc155f2/src/game/server/player.cpp#L535
                if player.pause.is_none() && !player.input.spec_cam_active() {
                    tee.store_new_input(player.input.clone());
                }
                tee.on_direct_input(now, &mut self.inner, snap_outer);
            }
        }
    }
}
impl EntityList {
    fn add_new_entities(&mut self, _game_state_provider: &dyn AssociatedGameStateMut) {
        for (team_id, e) in self.next_tick.borrow_mut().drain(..) {
            let new = match e {
                EntityItemNew::Laser(laser) => EntityItem::Laser(laser),
                EntityItemNew::Projectile(projectile) => EntityItem::Projectile(projectile),
            };
            self.entities.push((team_id, new));
        }

        // make sure all the entities in the entity-list are in SpawnOrder
        // TODO:
        /*
        for es in self.entities.windows(2) {
            let team_1 = game_state_provider.get_game_state(es[0].0);
            let entity_1 = &es[0].1;
            let team_2 = game_state_provider.get_game_state(es[1].0);
            let entity_2 = &es[1].1;
            assert!(entity_1.spawn_order(&team_1.tees) <= entity_2.spawn_order(&team_2.tees));
        }
        */
    }
}
impl PrivilegedGameState {
    pub(crate) fn tick_1_map_entities(&mut self, now: Instant) {
        for entity in self.map_entities.iter_mut().rev() {
            entity.tick(now, &mut self.inner, &mut self.tees);
        }
    }
}

impl EntityList {
    /// This is the tick function where the rng is allowed to advance to keep.
    pub(crate) fn tick_2_main_logic(
        &mut self,
        now: Instant,
        game_state_provider: &mut dyn AssociatedGameStateMut,
        snap_outer: &mut SnapOuter,
    ) {
        // move entities from on_input (weapon projectiles)
        self.add_new_entities(game_state_provider);

        // GameServer->OnTick
        //     World.Tick
        //         for Entity in Entities:
        //             Entity.Tick /* handle entities */
        //                 CCharacter::Tick:
        //                     * DDRaceTick: Freeze, Unfreeze, Set tune zone from map
        //                     * CoreTick: Calculates velocity (collision) and hook
        //                     * Fire Weapon
        //                     * DDRacePostCoreTick: Endless hook, deep freeze, gun teleporter ...
        //         for Entity in Entities:
        //             Entity.TickDefered /* only relevant in CCharacter (moves player) */
        //         for Entity in Entities:
        //             Entities.remove(entity)
        //             Entity.Destroy

        for (team_id, entity) in self.entities.iter_mut().rev() {
            let game_state = game_state_provider.get_game_state_mut(*team_id);
            entity.tick(now, &mut game_state.inner, &mut game_state.tees, snap_outer);
        }
    }
}
impl PrivilegedGameState {
    // returns whether to dissolve team and move all tees into team0
    pub(crate) fn tick_3_should_dissolve(&self) -> bool {
        self.inner.globals.all_finished() && !self.inner.globals.is_locked()
    }

    pub(crate) fn tick_4_move_tees(&mut self, now: Instant) {
        for tee_uid in self.tee_order.spawn_order() {
            let tee = self.tees.get_tee_mut(tee_uid).unwrap();
            tee.post_tick(now, &mut self.inner);
        }
    }
}

impl EntityList {
    /// after calling this function, related GameStates should be checked whether they can be
    /// removed due to team being empty
    pub(crate) fn tick_5_remove_destroyed(
        &mut self,
        game_state_provider: &mut dyn AssociatedGameStateMut,
        clients: &mut SecondaryMap<PlayerUid, Client>,
        mut to_team0: Option<&mut PrivilegedGameState>,
    ) {
        self.add_new_entities(game_state_provider);

        // remove destroyed entities and also remove entities related to destroyed tees
        let mut removed_tees = vec![];
        self.entities.retain(|(team_id, entity)| {
            let game_state = game_state_provider.get_game_state_mut(*team_id);
            let mut remove = entity.is_marked_for_destroy(&game_state.tees);
            remove |= removed_tees.contains(&entity.player_uid());
            if remove {
                if let EntityItem::Tee(tee_uid) = entity {
                    removed_tees.push(*tee_uid);
                    game_state.tees.remove_tee(*tee_uid).expect("Tee existed");
                    game_state.tee_order.remove_tee(*tee_uid);
                    game_state
                        .inner
                        .tee_cores
                        .remove_tee(*tee_uid)
                        .expect("TeeCore existed");
                    game_state.inner.tee_order.remove_tee(*tee_uid);

                    // TODO: only reset hook if all team dies
                    game_state.tees.reset_hook(*tee_uid);

                    // move to team0 from unlocked teams
                    if game_state.inner.globals.killed_to_team0() {
                        // if player got Dropped out of the game, their Tee still exists here, but
                        // not the player_uid in Players
                        if let Some(player) = game_state.players.player_leave(*tee_uid) {
                            clients.get_mut(*tee_uid).unwrap().activity =
                                Activity::Playing(TeamId::team0());
                            // If the team0 can't be passed as argument, it's set to none. It then is
                            // accessible via the game_state_provider.
                            let team0 = to_team0.as_deref_mut().unwrap_or_else(|| {
                                game_state_provider.get_game_state_mut(TeamId::team0())
                            });
                            team0.player_join_team0_from_other_team(*tee_uid, player);
                        }
                    }
                }
            }
            !remove
        });
        //     DoActivityCheck /* in GameController.Tick() */
        // CGameControllerDDRace::Tick
    }
}

impl PrivilegedGameState {
    pub(crate) fn tick_6_is_empty(&self) -> bool {
        self.players.players.is_empty()
    }

    /// Called `PostTick` in DDNet
    pub(crate) fn post_tick(&mut self, entity_list: &mut EntityList, now: Instant) {
        //     for player in players
        //         player.tick: /* Handling of respawning and `/spec` and tune zone */
        // TODO: cleaner way other that moving out. Should remove Player abstraction?
        let mut players = Default::default();
        mem::swap(&mut self.players.players, &mut players);
        for (player_uid, p) in players.iter_mut() {
            p.tick(now, &self.tees, &self.inner.globals);
            if p.should_spawn(SpawnMode::Normal)
                && self.try_spawn_tee(
                    entity_list,
                    player_uid,
                    now,
                    SpawnMode::Normal,
                    p.input.clone(),
                )
            {
                // reaquire player, because of ownership
                p.spawned();
            }
        }
        //     for player in players
        //         player.post_tick /* PostPostTick() spawn with weak hook */
        for (player_uid, p) in players.iter_mut() {
            // Called CPlayer::PostPostTick in DDNet, spawns tee with weak hook in respect to other tees
            // spawning in this tick
            if p.should_spawn(SpawnMode::ForceWeak)
                && self.try_spawn_tee(
                    entity_list,
                    player_uid,
                    now,
                    SpawnMode::ForceWeak,
                    p.input.clone(),
                )
            {
                // reaquire player, because of ownership
                p.spawned();
            }
        }
        mem::swap(&mut self.players.players, &mut players);
        //     Handling of Switchers
        //         for switcher in switchers
        //             for player in players
        //                 HandleSwitcher
        // ```
        // TODO: switchers
    }

    pub(crate) fn spawn_tee(
        &mut self,
        entity_list: &mut EntityList,
        player_uid: PlayerUid,
        now: Instant,
        pos: Vec2<f32>,
        spawn_mode: SpawnMode,
        input: Input,
    ) {
        let spawn_order = SpawnOrder::new(player_uid, now, SpawnOrderEntity::Tee(spawn_mode));
        let mut tee_core = TeeCore::new(pos);
        let tee = Tee::new(player_uid, spawn_order, &mut tee_core, input);

        self.tees.add_tee(player_uid, tee);
        self.tee_order.add_tee(player_uid, spawn_order);
        entity_list
            .entities
            .push((self.id, EntityItem::Tee(player_uid)));
        self.inner.tee_cores.add_tee(player_uid, tee_core);
        self.inner.tee_order.add_tee(player_uid, spawn_order);
        self.inner
            .events
            .add_event(twsnap::Events::Spawn(twsnap::events::Spawn {
                pos: vec2_from_bits(pos),
            }));
    }

    /// spawn at empty spawn point
    pub(crate) fn try_spawn_tee(
        &mut self,
        entity_list: &mut EntityList,
        player_uid: PlayerUid,
        now: Instant,
        spawn_mode: SpawnMode,
        input: Input,
    ) -> bool {
        if let Some(pos) = self.inner.get_spawn_point() {
            self.spawn_tee(entity_list, player_uid, now, pos, spawn_mode, input);
            true
        } else {
            false
        }
    }

    pub(crate) fn move_player(
        &mut self,
        to: &mut Self,
        tee_uid: PlayerUid,
        from_entities: &mut EntityList,
        to_entities: Option<&mut EntityList>,
    ) {
        if let Some(tee) = self.tees.remove_tee(tee_uid) {
            let tee_core = self.inner.tee_cores.remove_tee(tee_uid).unwrap();
            // remove Tee from Accessible game state lookups
            self.inner.tee_order.remove_tee(tee_uid);
            self.tee_order.remove_tee(tee_uid);

            // remove all entities related to tee from entity list
            if to_entities.is_none() {
                // except for the tee if the target team has the same `EntityList`
                from_entities.entities.retain_mut(|(team_id, e)| {
                    if e.player_uid() == tee_uid {
                        if matches!(e, EntityItem::Tee(_)) {
                            *team_id = to.id();
                            true
                        } else {
                            false
                        }
                    } else {
                        true
                    }
                });
            } else {
                from_entities
                    .entities
                    .retain(|(_, e)| e.player_uid() != tee_uid);
            }

            let spawn_order = tee.spawn_order();

            to.inner.tee_cores.add_tee(tee.player_uid(), tee_core);
            to.tees.add_tee(tee_uid, tee);
            to.inner
                .tee_order
                .add_tee_from_other_team(tee_uid, spawn_order);
            to.tee_order.add_tee_from_other_team(tee_uid, spawn_order);
            // add tee to new entity list
            if let Some(to_entities) = to_entities {
                let pos = to_entities
                    .entities
                    .binary_search_by(|(_, e)| e.spawn_order(&to.tees).cmp(&spawn_order))
                    .unwrap_err();
                to_entities
                    .entities
                    .insert(pos, (to.id, EntityItem::Tee(tee_uid)));
            }
        }
    }

    pub(crate) fn swap_tees(&mut self, p1_uid: PlayerUid, p2_uid: PlayerUid) {
        // swap player tees
        let [t1, t2] = self.tees.get_tees_mut([p1_uid, p2_uid]).unwrap();
        t1.swap(t2);
        let [tee_core1, tee_core2] = self.inner.tee_cores.get_tees_mut([p1_uid, p2_uid]).unwrap();
        mem::swap(tee_core1, tee_core2);
    }

    // kill from user initiated
    pub(crate) fn kill(
        &mut self,
        player_uid: PlayerUid,
        now: Instant,
        within_kill_protection: bool,
    ) {
        let Some(p) = self.players.get_mut(player_uid) else {
            return;
        };
        if !p.tee {
            return;
        }
        let time = self
            .inner
            .globals
            .race_time(now, &self.tees, player_uid)
            .unwrap_or(Duration::T0MS);

        let kill_protection = time >= Duration::from_min(20);
        if kill_protection != within_kill_protection {
            return;
        }

        // TODO: create new team object on lock kill with new TeamUid?
        if p.kill_tee(now, &mut self.tees, SpawnMode::Normal)
            && self.inner.globals.kill_propagates()
        {
            for (p_uid, other_p) in self.players.players.iter_mut() {
                if p_uid == player_uid {
                    continue;
                }
                other_p.kill_tee(now, &mut self.tees, SpawnMode::ForceWeak);
            }
        }
    }

    pub(crate) fn pause(&mut self, player_uid: PlayerUid) {
        let Some(p) = self.players.get_mut(player_uid) else {
            return;
        };
        p.pause = match p.pause {
            None => Some(PauseMode::Pause),
            Some(PauseMode::Pause) => None,
        }
    }

    // helper function, when I only have &mut Team, and not an owned variant of Team
    pub(crate) fn move_all_to_keep_alive(
        &mut self,
        other: &mut Self,
        from_entities: &mut EntityList,
        mut to_entities: Option<&mut EntityList>,
        clients: &mut SecondaryMap<PlayerUid, Client>,
    ) {
        // TODO: no clone
        let player_uids: Vec<_> = self.players.players.keys().collect();
        for player_uid in player_uids {
            other.player_join_from_other_team(
                player_uid,
                self,
                from_entities,
                to_entities.as_deref_mut(),
            );
            clients.get_mut(player_uid).unwrap().activity = Activity::Playing(other.id);
        }
    }

    // TODO: whats the difference to move_all_to_keep_alive
    pub(crate) fn move_all_to(
        mut self,
        other: &mut Self,
        from_entities: &mut EntityList,
        mut to_entities: Option<&mut EntityList>,
        clients: &mut SecondaryMap<PlayerUid, Client>,
    ) {
        // TODO: no clone
        let player_uids: Vec<_> = self.players.players.keys().collect();
        for player_uid in player_uids {
            other.player_join_from_other_team(
                player_uid,
                &mut self,
                from_entities,
                to_entities.as_deref_mut(),
            );
            clients
                .get_mut(player_uid)
                .expect("player must be in a team when saving")
                .activity = Activity::Playing(other.id)
        }
    }

    pub(crate) fn reset(&mut self, now: Instant) {
        // remove all tees fromr the state
        self.tee_order.reset();
        self.tees.reset();
        self.inner.tee_order.reset();
        self.inner.tee_cores.reset();
        // kill all players
        for player in self.players.players.values_mut() {
            player.tee = false;
            player.previous_die_tick = player.die_tick;
            player.die_tick = now;
        }
        // reset map entities
        self.map_entities = self.inner.map.entities.clone();
    }

    pub(crate) fn id(&self) -> TeamId {
        self.id
    }
}

impl EntityList {
    pub(crate) fn reset(&mut self, team_id: TeamId) {
        self.entities.retain(|(id, _)| *id != team_id)
    }
}

// TODO: separate between teams:
//        - Team where restarting of individual tees is possible
//        - Team where joining is impossible after crossing the start line
//        - Team containing only a single Tee