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
// impls of `InterpolatableComponent` on things defined in `common`, since
// `common_net` is downstream of `common`, and an `InterpolationSystem` that
// applies them
use super::InterpolatableComponent;
use common::comp::{Ori, Pos, Vel};
use specs::Component;
use tracing::warn;
use vek::ops::{Lerp, Slerp};

#[derive(Debug)]
pub struct InterpBuffer<T> {
    pub buf: [(f64, T); 4],
    pub i: usize,
}

impl<T: Clone> InterpBuffer<T> {
    pub fn new(x: T) -> Self {
        Self {
            buf: [
                (0.0, x.clone()),
                (0.0, x.clone()),
                (0.0, x.clone()),
                (0.0, x),
            ],
            i: 0,
        }
    }

    fn push(&mut self, time: f64, x: T) {
        let InterpBuffer {
            ref mut buf,
            ref mut i,
        } = self;
        *i += 1;
        *i %= buf.len();
        buf[*i] = (time, x);
    }

    fn force_update(&mut self, time: f64, x: T) {
        for i in 0..self.buf.len() {
            self.buf[i] = (time, x.clone());
        }
    }

    fn update(&mut self, time: f64, x: T, force_update: bool) {
        if force_update {
            self.force_update(time, x);
        } else {
            self.push(time, x);
        }
    }
}

impl<T: 'static + Send + Sync> Component for InterpBuffer<T> {
    type Storage = specs::VecStorage<Self>;
}

// 0 is pure physics, 1 is pure extrapolation
const PHYSICS_VS_EXTRAPOLATION_FACTOR: f32 = 0.1;
const POSITION_INTERP_SANITY: Option<f32> = None;
const VELOCITY_INTERP_SANITY: Option<f32> = None;
const ENABLE_POSITION_HERMITE: bool = false;

impl InterpolatableComponent for Pos {
    type InterpData = InterpBuffer<Pos>;
    type ReadData = InterpBuffer<Vel>;

    fn new_data(x: Self) -> Self::InterpData { InterpBuffer::new(x) }

    fn update_component(&self, interp_data: &mut Self::InterpData, time: f64, force_update: bool) {
        interp_data.update(time, *self, force_update);
    }

    fn interpolate(self, interp_data: &Self::InterpData, t2: f64, vel: &InterpBuffer<Vel>) -> Self {
        // lerp to test interface, do hermite spline later
        let InterpBuffer { ref buf, ref i } = interp_data;
        let (t0, p0) = buf[(i + buf.len() - 1) % buf.len()];
        let (t1, p1) = buf[i % buf.len()];
        if (t1 - t0).abs() < f64::EPSILON {
            return self;
        }
        if POSITION_INTERP_SANITY
            .map_or(false, |limit| p0.0.distance_squared(p1.0) > limit.powf(2.0))
        {
            warn!("position delta exceeded sanity check, clamping");
            return p1;
        }
        let (t0prime, m0) = vel.buf[(i + vel.buf.len() - 1) % vel.buf.len()];
        let (t1prime, m1) = vel.buf[i % vel.buf.len()];
        let t = (t2 - t0) / (t1 - t0);
        let mut out = if ENABLE_POSITION_HERMITE
            && ((t0 - t0prime).abs() < f64::EPSILON && (t1 - t1prime).abs() < f64::EPSILON)
        {
            let h00 = |t: f64| (2.0 * t.powf(3.0) - 3.0 * t.powf(2.0) + 1.0) as f32;
            let h10 = |t: f64| (t.powf(3.0) - 2.0 * t.powf(2.0) + t) as f32;
            let h01 = |t: f64| (-2.0 * t.powf(3.0) + 3.0 * t.powf(2.0)) as f32;
            let h11 = |t: f64| (t.powf(3.0) - t.powf(2.0)) as f32;
            let dt = (t1 - t0) as f32;
            h00(t) * p0.0 + h10(t) * dt * m0.0 + h01(t) * p1.0 + h11(t) * dt * m1.0
        } else {
            if ENABLE_POSITION_HERMITE {
                warn!(
                    "timestamps for pos and vel don't match ({:?}, {:?}), falling back to lerp",
                    interp_data, vel
                );
            }
            Lerp::lerp_unclamped(p0.0, p1.0, t as f32)
        };

        if out.map(|x| x.is_nan()).reduce_or() {
            warn!("interpolation output is nan: {}, {}, {:?}", t2, t, buf);
            out = p1.0;
        }

        Pos(Lerp::lerp(self.0, out, PHYSICS_VS_EXTRAPOLATION_FACTOR))
    }
}

impl InterpolatableComponent for Vel {
    type InterpData = InterpBuffer<Vel>;
    type ReadData = ();

    fn new_data(x: Self) -> Self::InterpData { InterpBuffer::new(x) }

    fn update_component(&self, interp_data: &mut Self::InterpData, time: f64, force_update: bool) {
        interp_data.update(time, *self, force_update);
    }

    fn interpolate(self, interp_data: &Self::InterpData, t2: f64, _: &()) -> Self {
        let InterpBuffer { ref buf, ref i } = interp_data;
        let (t0, p0) = buf[(i + buf.len() - 1) % buf.len()];
        let (t1, p1) = buf[i % buf.len()];
        if (t1 - t0).abs() < f64::EPSILON {
            return self;
        }
        if VELOCITY_INTERP_SANITY
            .map_or(false, |limit| p0.0.distance_squared(p1.0) > limit.powf(2.0))
        {
            warn!("velocity delta exceeded sanity check, clamping");
            return p1;
        }
        let lerp_factor = 1.0 + ((t2 - t1) / (t1 - t0)) as f32;
        let mut out = Lerp::lerp_unclamped(p0.0, p1.0, lerp_factor);
        if out.map(|x| x.is_nan()).reduce_or() {
            warn!(
                "interpolation output is nan: {}, {}, {:?}",
                t2, lerp_factor, buf
            );
            out = p1.0;
        }

        Vel(Lerp::lerp(self.0, out, PHYSICS_VS_EXTRAPOLATION_FACTOR))
    }
}

impl InterpolatableComponent for Ori {
    type InterpData = InterpBuffer<Ori>;
    type ReadData = ();

    fn new_data(x: Self) -> Self::InterpData { InterpBuffer::new(x) }

    fn update_component(&self, interp_data: &mut Self::InterpData, time: f64, force_update: bool) {
        interp_data.update(time, *self, force_update);
    }

    fn interpolate(self, interp_data: &Self::InterpData, t2: f64, _: &()) -> Self {
        let InterpBuffer { ref buf, ref i } = interp_data;
        let (t0, p0) = buf[(i + buf.len() - 1) % buf.len()];
        let (t1, p1) = buf[i % buf.len()];
        if (t1 - t0).abs() < f64::EPSILON {
            return self;
        }
        let lerp_factor = 1.0 + ((t2 - t1) / (t1 - t0)) as f32;
        let mut out = Slerp::slerp_unclamped(p0.to_quat(), p1.to_quat(), lerp_factor);
        if out.into_vec4().map(|x| x.is_nan()).reduce_or() {
            warn!(
                "interpolation output is nan: {}, {}, {:?}",
                t2, lerp_factor, buf
            );
            out = p1.to_quat();
        }

        Ori::new(Slerp::slerp(self.to_quat(), out, PHYSICS_VS_EXTRAPOLATION_FACTOR).normalized())
    }
}