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
use crate::entities::tee::jump::JumpType;
use crate::entities::tee::{Tee, TEE_PROXIMITY_SQUARED};
use crate::map::{coord, CantMove, Map, Tile, TuneZone};
use crate::state;
use crate::tuning::Tuning;
use bitflags::bitflags;
use twgame_core::twsnap::enums::{Direction, Sound};
use twgame_core::twsnap::flags::TeeFlags;
use twgame_core::twsnap::time::{Duration, Instant};
use twgame_core::twsnap::Position;
use twgame_core::twsnap::{vec2_from_bits, Velocity};
use twgame_core::{normalize, Input};
use vek::num_traits::Inv;
use vek::Vec2;

bitflags! {
    #[derive(Debug)]
    pub struct Core: u32 {
        /// no collision with other players due to solo part
        const SOLO = 1 << 0;
        /// tee collision disabled
        const TEE_COLLISION_OFF = 1 << 1;
        /// projectiles need to know when they possibly collide whether to hit other tees
        const WEAPON_HAMMER_OFF = 1 << 2;
        const WEAPON_SHOTGUN_OFF = 1 << 3;
        const WEAPON_GRENADE_OFF = 1 << 4;
        const WEAPON_LASER_OFF = 1 << 5;

        const TELEGUN_GUN = 1 << 6;
        const TELEGUN_LASER = 1 << 7;
        const TELEGUN_GRENADE = 1 << 8;

        /// keep finish state for teamrank finishes
        const FINISHED = 1 << 9;

        /// keep for own tee
        /// make hammer automatic when frozen on last tick
        const FROZEN_LAST_TICK = 1 << 10;
    }
}

/// variables accessible from other Tees. Stored in game state. All variables that can be influenced
/// by other entities need to be in this struct. Variables that are only influenced by the game
/// world are stored in the Tee struct.
#[derive(Debug)]
pub struct TeeCore {
    /// current position of the tee
    /// each tile has 32 sub tiles
    pos: Vec2<f32>,
    /// At the end of each tick the velocity is added to the pos. Positive y vel goes down. Positive
    /// x vel goes right
    vel: Vec2<f32>,

    core: Core,

    /// None if not frozen
    freeze: Option<Duration>,
    /// store last freeze tick to only freeze every second
    freeze_tick: Instant,

    /// stoppers, necessary for applying force // TODO: put this into Core?
    move_restrictions: CantMove,

    /// remember when we entered a hook releasing tele last. Other tees need to release the hook on
    /// us.
    last_hook_release: Instant,
}

impl TeeCore {
    pub fn new(pos: Vec2<f32>) -> Self {
        Self {
            pos,
            vel: Vec2::new(0.0, 0.0),
            core: Core::empty(),
            freeze: None,
            freeze_tick: Instant::zero(),
            move_restrictions: CantMove::empty(),
            last_hook_release: Instant::zero(),
        }
    }

    pub fn with_vel(pos: Vec2<f32>, vel: Vec2<f32>) -> Self {
        Self {
            pos,
            vel,
            core: Core::empty(),
            freeze: None,
            freeze_tick: Instant::zero(),
            move_restrictions: CantMove::empty(),
            last_hook_release: Instant::zero(),
        }
    }
}

impl TeeCore {
    pub(super) fn save_freeze_time(&self) -> i32 {
        self.freeze.map(|duration| duration.ticks()).unwrap_or(0)
    }
    pub(super) fn save_freeze_start(&self, now: Instant) -> i32 {
        now.snap_tick() - self.freeze_tick.snap_tick()
    }
    pub(super) fn load_freeze(&mut self, now: Instant, tee_info: &mut std::str::Split<char>) {
        let freeze_time = tee_info.next().unwrap().parse::<i32>().unwrap();
        if freeze_time != 0 {
            self.freeze = Some(Duration::from_ticks(freeze_time));
        } else {
            self.freeze = None;
        }
        let freeze_start = tee_info.next().unwrap().parse::<i32>().unwrap();
        self.freeze_tick = now - Duration::from_ticks(freeze_start);
    }
    pub(super) fn load_pos(&mut self, tee_info: &mut std::str::Split<char>) {
        self.pos.x = tee_info.next().unwrap().parse::<i32>().unwrap() as f32;
        self.pos.y = tee_info.next().unwrap().parse::<i32>().unwrap() as f32;
    }
    pub(super) fn load_vel(&mut self, tee_info: &mut std::str::Split<char>) {
        self.vel.x = tee_info.next().unwrap().parse::<f32>().unwrap();
        self.vel.y = tee_info.next().unwrap().parse::<f32>().unwrap();
    }
}

impl TeeCore {
    pub(super) fn snap(&self, now: Instant, snap_tee: &mut twgame_core::twsnap::items::Tee) {
        let (pos, vel) = self.get_pos_vel();
        snap_tee.pos = pos;
        snap_tee.vel = vel;
        if self.freeze.is_some() {
            snap_tee.flags.insert(TeeFlags::IN_FREEZE);
        }

        if let Some(freeze) = self.freeze {
            snap_tee.freeze_end = now + freeze;
            snap_tee.freeze_start = self.freeze_tick;
        }
        if self.is_solo() {
            snap_tee.flags.insert(TeeFlags::SOLO);
        }
    }

    /// round all floats to nearby values
    /// called CCharacterCore::Quantize in DDNet
    pub(crate) fn round(&mut self) {
        let (pos, vel) = self.get_pos_vel();
        self.pos.x = pos.x.to_bits() as f32;
        self.pos.y = pos.y.to_bits() as f32;

        self.vel.x = vel.x.to_bits() as f32 / 256.0;
        self.vel.y = vel.y.to_bits() as f32 / 256.0;
    }

    pub(crate) fn get_pos_vel(&self) -> (Position, Velocity) {
        let pos: Position = vec2_from_bits(self.pos.round());
        let vel: Velocity = vec2_from_bits((self.vel * 256.0).round());
        (pos, vel)
    }
}

/// CharacterCore::Tick
impl TeeCore {
    /// part of `Tee::core_tick`
    pub(crate) fn set_move_restrictions(&mut self, map: &Map) {
        // Move restrictions from stoppers
        self.move_restrictions = map.get_move_restrictions(self.pos);
    }
    pub(crate) fn apply_gravity(&mut self, tuning: &Tuning) {
        self.vel.y += tuning.gravity;
    }
    pub(super) fn on_jump(&mut self, events: &mut state::Events, tuning: &Tuning, jump: JumpType) {
        match jump {
            JumpType::GroundJump => {
                // TODO: m_TriggeredEvents |= COREEVENT_GROUND_JUMP
                events.create_sound(self.pos, Sound::PlayerJump);
                self.vel.y = -tuning.ground_jump_impulse;
            }
            JumpType::AirJump => {
                // TODO do instead: m_TriggeredEvents |= COREEVENT_AIR_JUMP
                events.create_sound(self.pos, Sound::PlayerAirjump);
                self.vel.y = -tuning.air_jump_impulse;
            }
        }
    }
    /// left/right (a/d) movement
    pub(crate) fn apply_directions(
        &mut self,
        tuning: &Tuning,
        is_grounded: bool,
        direction: Direction,
    ) {
        let max_speed: f32 = if is_grounded {
            tuning.ground_control_speed
        } else {
            tuning.air_control_speed
        };
        let accel: f32 = if is_grounded {
            tuning.ground_control_accel
        } else {
            tuning.air_control_accel
        };
        let friction: f32 = if is_grounded {
            tuning.ground_friction
        } else {
            tuning.air_friction
        };
        // add the speed modification according to players wanted direction
        self.vel.x = match direction {
            Direction::Left => Self::saturated_add(max_speed, self.vel.x, -accel),
            Direction::Right => Self::saturated_add(max_speed, self.vel.x, accel),
            Direction::None => self.vel.x * friction,
        };
    }
    pub(crate) fn cap_vel(&mut self) {
        if self.vel.magnitude() > 6000.0 {
            self.vel = normalize(self.vel) * 6000.0;
        }
    }

    /// Returns the pos where the tee would end up considering Collision, but not other Tees
    ///
    pub(crate) fn move_vel_ramp(&mut self, map: &Map, tune_zone: TuneZone) {
        let tuning = map.tuning(tune_zone);
        let vel_ramp = Tee::vel_ramp(
            self.vel.magnitude() * 50.0,
            tuning.velramp_start,
            tuning.velramp_range,
            tuning.velramp_curvature,
        );
        self.vel.x *= vel_ramp;

        let (new_pos, new_vel) = map.tee_move_box(self.pos, self.vel);
        self.pos = new_pos;
        self.vel = new_vel;

        self.vel.x *= vel_ramp.inv();
    }
}

impl TeeCore {
    pub fn pos(&self) -> Vec2<f32> {
        self.pos
    }
    pub fn vel(&self) -> Vec2<f32> {
        self.vel
    }

    /// apply force on tee. When the Tee is on stoppers, the velocity is capped to 0
    /// in directions where stoppers block movement
    pub(crate) fn impact(&mut self, force: Vec2<f32>, _pain: bool) {
        // TODO: put pain emoji
        self.vel = self.move_restrictions.apply_on_vel(self.vel + force);
    }
    pub(crate) fn is_on_stoppers(&self) -> bool {
        self.move_restrictions.contains(CantMove::DOWN)
    }

    /// kill immunity is given after finishing in a team, before all team members touched the finish
    /// line
    pub(crate) fn is_in_kill_area(&self, no_kill_immunity: bool, map: &Map) -> bool {
        map.is_tee_in_skippable_radius(self.pos, Tile::Kill)
            // kill immunity for finished tees in unfinished team
            // TODO: there are probably edge cases when tee starts again which differ
            && no_kill_immunity
            || map.is_out_of_map(coord::to_int(self.pos))
    }

    // TODO: can we do without this function? It doesn't consider the move restrictions
    pub(super) fn set_pos(&mut self, pos: Vec2<f32>) {
        self.pos = pos;
    }

    // TODO: can we do without this function? It doesn't consider the move restrictions
    pub(crate) fn set_vel(&mut self, vel: Vec2<f32>) {
        self.vel = vel;
    }

    pub(super) fn reset_vel(&mut self) {
        self.vel = Vec2::new(0.0, 0.0);
    }

    pub(super) fn apply_move_restrictions(&mut self) {
        self.vel = self.move_restrictions.apply_on_vel(self.vel);
    }

    /// adds modifier to current, not advancing over max or -max, max has to be non-negative
    pub(crate) fn saturated_add(max: f32, current: f32, modifier: f32) -> f32 {
        debug_assert!(max >= 0.0);
        if modifier < 0.0 {
            if current < -max {
                current
            } else {
                (-max).max(current + modifier)
            }
        } else if current > max {
            current
        } else {
            max.min(current + modifier)
        }
    }

    /// Applies force up to a limit
    pub(crate) fn satured_impact(&mut self, force: Vec2<f32>, max: f32) {
        self.vel = Vec2::new(
            Self::saturated_add(max, self.vel.x, force.x),
            Self::saturated_add(max, self.vel.y, force.y),
        );
        self.apply_move_restrictions()
    }

    pub(crate) fn freeze(&mut self, now: Instant, duration: Duration) -> bool {
        if duration == Duration::T0MS
            || !now
                .duration_passed_since(self.freeze_tick, Duration::from_secs(1) + Duration::T20MS)
        {
            return false;
        }
        self.freeze = Some(duration);
        self.freeze_tick = now;
        true
    }

    pub(crate) fn unfreeze(&mut self) {
        if self.freeze.is_some() {
            self.unfreeze_unchecked();
        }
    }

    pub(crate) fn is_frozen(&self) -> bool {
        self.freeze.is_some()
    }

    // unfreezes the tee, even if it isn't frozen right now making the [ddrace_tick] code a bit nicer
    fn unfreeze_unchecked(&mut self) {
        // TODO: select gun if active weapon was lost during freeze
        self.freeze = None;
        self.freeze_tick = Instant::zero();
        self.core.insert(Core::FROZEN_LAST_TICK);
    }

    pub(super) fn frozen_last_tick(&self) -> bool {
        self.core.contains(Core::FROZEN_LAST_TICK)
    }

    pub(super) fn reset_frozen_last_tick(&mut self) {
        self.core.remove(Core::FROZEN_LAST_TICK);
    }

    // in CCharacter::DDRaceTick
    pub(crate) fn input_apply_freeze(&mut self, mut input: Input, live_freeze: bool) -> Input {
        if live_freeze {
            input.direction = 0;
            input.jump = 0;
        }
        if let Some(duration) = self.freeze {
            self.freeze = duration.decrement();

            // clear input
            input.direction = 0;
            input.jump = 0;
            input.hook = 0;

            // TODO: figure out why we have to cancel freeze two ticks too early or if the
            //       implementation here is wrong
            if self.freeze == Some(Duration::T20MS) {
                self.unfreeze_unchecked();
            }
        }
        input
    }

    /// store that other tees hooking us should release their hook this tick
    pub(crate) fn other_tees_release_hook(&mut self, now: Instant) {
        self.last_hook_release = now;
    }

    /// retrieve if this Tee requested that hooks on it should be released with the above function
    pub(crate) fn last_hook_release(&self) -> Instant {
        self.last_hook_release
    }

    pub(crate) fn on_finish(&mut self) {
        self.core.insert(Core::FINISHED);
    }

    pub(crate) fn has_finished(&self) -> bool {
        self.core.contains(Core::FINISHED)
    }
}

impl TeeCore {
    pub(crate) fn enable_weapon_hit(&mut self) {
        self.core.remove(
            Core::WEAPON_HAMMER_OFF
                | Core::WEAPON_SHOTGUN_OFF
                | Core::WEAPON_GRENADE_OFF
                | Core::WEAPON_LASER_OFF,
        );
    }

    pub(crate) fn disable_weapon_hit(&mut self) {
        self.core.insert(
            Core::WEAPON_HAMMER_OFF
                | Core::WEAPON_SHOTGUN_OFF
                | Core::WEAPON_GRENADE_OFF
                | Core::WEAPON_LASER_OFF,
        );
    }

    pub(crate) fn can_hammer(&self) -> bool {
        !self.core.intersects(Core::SOLO | Core::WEAPON_HAMMER_OFF)
    }
    pub(crate) fn tee_collision_disabled(&self) -> bool {
        self.core.intersects(Core::SOLO | Core::TEE_COLLISION_OFF)
    }

    pub(crate) fn is_solo(&self) -> bool {
        self.core.intersects(Core::SOLO)
    }
    pub(crate) fn set_solo(&mut self, enabled: bool) {
        self.core.set(Core::SOLO, enabled);
    }

    pub(crate) fn can_be_ninjaed(&self) -> bool {
        !self.core.intersects(Core::SOLO | Core::TEE_COLLISION_OFF)
    }

    pub(crate) fn telegun_gun(&self) -> bool {
        self.core.intersects(Core::TELEGUN_GUN)
    }
    pub(crate) fn set_telegun_gun(&mut self, enabled: bool) {
        self.core.set(Core::TELEGUN_GUN, enabled);
    }
    pub(crate) fn telegun_laser(&self) -> bool {
        self.core.intersects(Core::TELEGUN_LASER)
    }
    pub(crate) fn set_telegun_laser(&mut self, enabled: bool) {
        self.core.set(Core::TELEGUN_LASER, enabled);
    }
    pub(crate) fn telegun_grenade(&self) -> bool {
        self.core.intersects(Core::TELEGUN_GRENADE)
    }
    pub(crate) fn set_telegun_grenade(&mut self, enabled: bool) {
        self.core.set(Core::TELEGUN_GRENADE, enabled);
    }
    pub(crate) fn save_tee_collision(&self) -> bool {
        !self.core.intersects(Core::TEE_COLLISION_OFF)
    }
    pub(crate) fn set_tee_collision(&mut self, enabled: bool) {
        self.core.set(Core::TEE_COLLISION_OFF, !enabled);
    }
    // https://github.com/ddnet/ddnet/blob/e63c9481e0a8b9a4885022e16c8aaa0b2a70b451/src/game/server/save.h#L34-L37
    pub(crate) fn save_weapon_hit(&self) -> i32 {
        let mut flags = 0;
        if self.core.intersects(Core::WEAPON_HAMMER_OFF) {
            flags |= 1;
        }
        if self.core.intersects(Core::WEAPON_SHOTGUN_OFF) {
            flags |= 2;
        }
        if self.core.intersects(Core::WEAPON_GRENADE_OFF) {
            flags |= 4;
        }
        if self.core.intersects(Core::WEAPON_LASER_OFF) {
            flags |= 8;
        }
        flags
    }
    pub(crate) fn load_weapon_hit(&mut self, flags: i32) {
        self.core.set(Core::WEAPON_HAMMER_OFF, flags & 1 != 0);
        self.core.set(Core::WEAPON_SHOTGUN_OFF, flags & 2 != 0);
        self.core.set(Core::WEAPON_GRENADE_OFF, flags & 4 != 0);
        self.core.set(Core::WEAPON_LASER_OFF, flags & 8 != 0);
    }
}

impl TeeCore {
    // returns, whether tee collides with the given point
    pub(crate) fn collides_point(&self, cood: Vec2<f32>) -> bool {
        self.pos.distance_squared(cood) <= TEE_PROXIMITY_SQUARED
    }
}

/// Functions useful for teehistorian
impl TeeCore {
    /// this Vec2 should not be confused with the index coordinates used in the map module
    pub(crate) fn get_tee_pos(&self) -> Vec2<i32> {
        Vec2::new(self.pos.x.round() as i32, self.pos.y.round() as i32)
    }

    pub(crate) fn set_tee_pos(&mut self, pos: Vec2<i32>) {
        self.pos = Vec2::new(pos.x as f32, pos.y as f32);
    }
}

#[cfg(test)]
mod test {
    use super::TeeCore;

    #[test]
    fn saturated_add() {
        assert_eq!(TeeCore::saturated_add(10.0, 5.0, 3.0), 8.0);
        assert_eq!(TeeCore::saturated_add(10.0, 5.0, 8.0), 10.0);
        assert_eq!(TeeCore::saturated_add(10.0, 13.0, 3.0), 13.0);
        assert_eq!(TeeCore::saturated_add(10.0, 13.0, -1.0), 12.0);
    }

    #[test]
    fn saturated_add_neg() {
        assert_eq!(TeeCore::saturated_add(10.0, -5.0, -3.0), -8.0);
        assert_eq!(TeeCore::saturated_add(10.0, -5.0, -8.0), -10.0);
        assert_eq!(TeeCore::saturated_add(10.0, -13.0, -3.0), -13.0);
        assert_eq!(TeeCore::saturated_add(10.0, -13.0, 1.0), -12.0);
    }
}