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
// Copyright 2016-2018 Mateusz Sieczko and other GilRs Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

use super::effect_source::{DistanceModel, EffectSource, EffectState, Magnitude};
use super::time::{Repeat, Ticks, TICK_DURATION};

use std::ops::{Deref, DerefMut};
use std::sync::mpsc::{self, Receiver, Sender};
use std::thread;
use std::time::{Duration, Instant};

use crate::gamepad::GamepadId;
use crate::Event;
use gilrs_core::FfDevice;

use vec_map::VecMap;

#[derive(Debug)]
pub(crate) enum Message {
    Create {
        id: usize,
        effect: Box<EffectSource>,
    },
    HandleCloned {
        id: usize,
    },
    HandleDropped {
        id: usize,
    },
    Play {
        id: usize,
    },
    Stop {
        id: usize,
    },
    Open {
        id: usize,
        device: FfDevice,
    },
    Close {
        id: usize,
    },
    SetListenerPosition {
        id: usize,
        position: [f32; 3],
    },
    SetGamepads {
        id: usize,
        gamepads: VecMap<()>,
    },
    AddGamepad {
        id: usize,
        gamepad_id: GamepadId,
    },
    SetRepeat {
        id: usize,
        repeat: Repeat,
    },
    SetDistanceModel {
        id: usize,
        model: DistanceModel,
    },
    SetPosition {
        id: usize,
        position: [f32; 3],
    },
    SetGain {
        id: usize,
        gain: f32,
    },
}

pub(crate) enum FfMessage {
    EffectCompleted { event: Event },
}

impl Message {
    // Whether to use trace level logging or debug
    fn use_trace_level(&self) -> bool {
        use self::Message::*;

        matches!(
            self,
            &SetListenerPosition { .. } | &HandleCloned { .. } | &HandleDropped { .. }
        )
    }
}

#[derive(Debug)]
struct Device {
    inner: FfDevice,
    position: [f32; 3],
}

struct Effect {
    source: EffectSource,
    /// Number of created effect's handles.
    count: usize,
}

impl Effect {
    fn inc(&mut self) -> usize {
        self.count += 1;
        self.count
    }

    fn dec(&mut self) -> usize {
        self.count -= 1;
        self.count
    }
}

impl From<EffectSource> for Effect {
    fn from(source: EffectSource) -> Self {
        Effect { source, count: 1 }
    }
}

impl Deref for Effect {
    type Target = EffectSource;

    fn deref(&self) -> &Self::Target {
        &self.source
    }
}

impl DerefMut for Effect {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.source
    }
}

impl From<FfDevice> for Device {
    fn from(inner: FfDevice) -> Self {
        Device {
            inner,
            position: [0.0, 0.0, 0.0],
        }
    }
}

pub(crate) fn run(tx: Sender<FfMessage>, rx: Receiver<Message>) {
    let mut effects = VecMap::<Effect>::new();
    let mut devices = VecMap::<Device>::new();
    let sleep_dur = Duration::from_millis(TICK_DURATION.into());
    let mut tick = Ticks(0);
    let mut completion_events = Vec::<Event>::new();

    loop {
        let t1 = Instant::now();
        while let Ok(ev) = rx.try_recv() {
            if ev.use_trace_level() {
                trace!("New ff event: {:?}", ev);
            } else {
                debug!("New ff event: {:?}", ev);
            }

            match ev {
                Message::Create { id, effect } => {
                    effects.insert(id, (*effect).into());
                }
                Message::Play { id } => {
                    if let Some(effect) = effects.get_mut(id) {
                        effect.source.state = EffectState::Playing { since: tick }
                    } else {
                        error!("{:?} with wrong ID", ev);
                    }
                }
                Message::Stop { id } => {
                    if let Some(effect) = effects.get_mut(id) {
                        effect.source.state = EffectState::Stopped
                    } else {
                        error!("{:?} with wrong ID", ev);
                    }
                }
                Message::Open { id, device } => {
                    devices.insert(id, device.into());
                }
                Message::Close { id } => {
                    devices.remove(id);
                }
                Message::SetListenerPosition { id, position } => {
                    if let Some(device) = devices.get_mut(id) {
                        device.position = position;
                    } else {
                        error!("{:?} with wrong ID", ev);
                    }
                }
                Message::HandleCloned { id } => {
                    if let Some(effect) = effects.get_mut(id) {
                        effect.inc();
                    } else {
                        error!("{:?} with wrong ID", ev);
                    }
                }
                Message::HandleDropped { id } => {
                    let mut drop = false;
                    if let Some(effect) = effects.get_mut(id) {
                        if effect.dec() == 0 {
                            drop = true;
                        }
                    } else {
                        error!("{:?} with wrong ID", ev);
                    }

                    if drop {
                        effects.remove(id);
                    }
                }
                Message::SetGamepads { id, gamepads } => {
                    if let Some(eff) = effects.get_mut(id) {
                        eff.source.devices = gamepads;
                    } else {
                        error!("Invalid effect id {} when changing gamepads.", id);
                    }
                }
                Message::AddGamepad { id, gamepad_id } => {
                    if let Some(eff) = effects.get_mut(id) {
                        eff.source.devices.insert(gamepad_id.0, ());
                    } else {
                        error!("Invalid effect id {} when changing gamepads.", id);
                    }
                }
                Message::SetRepeat { id, repeat } => {
                    if let Some(eff) = effects.get_mut(id) {
                        eff.source.repeat = repeat;
                    } else {
                        error!("Invalid effect id {} when changing repeat mode.", id);
                    }
                }
                Message::SetDistanceModel { id, model } => {
                    if let Some(eff) = effects.get_mut(id) {
                        eff.source.distance_model = model;
                    } else {
                        error!("Invalid effect id {} when changing distance model.", id);
                    }
                }
                Message::SetPosition { id, position } => {
                    if let Some(eff) = effects.get_mut(id) {
                        eff.source.position = position;
                    } else {
                        error!("Invalid effect id {}.", id);
                    }
                }
                Message::SetGain { id, gain } => {
                    if let Some(eff) = effects.get_mut(id) {
                        eff.source.gain = gain;
                    } else {
                        error!("Invalid effect id {} when changing effect gain.", id);
                    }
                }
            }
        }

        combine_and_play(&mut effects, &mut devices, tick, &mut completion_events);
        completion_events.iter().for_each(|ev| {
            let _ = tx.send(FfMessage::EffectCompleted { event: *ev });
        });
        completion_events.clear();

        let dur = Instant::now().duration_since(t1);
        if dur > sleep_dur {
            // TODO: Should we add dur - sleep_dur to next iteration's dur?
            warn!(
                "One iteration of a force feedback loop took more than {}ms!",
                TICK_DURATION
            );
        } else {
            thread::sleep(sleep_dur - dur);
        }
        tick.inc();
    }
}

pub(crate) fn init() -> (Sender<Message>, Receiver<FfMessage>) {
    let (tx, _rx) = mpsc::channel();
    let (_tx2, rx2) = mpsc::channel();

    // Wasm doesn't support threads and force feedback
    #[cfg(not(target_arch = "wasm32"))]
    std::thread::Builder::new()
        .name("gilrs".to_owned())
        .spawn(move || run(_tx2, _rx))
        .expect("failed to spawn thread");

    (tx, rx2)
}

fn combine_and_play(
    effects: &mut VecMap<Effect>,
    devices: &mut VecMap<Device>,
    tick: Ticks,
    completion_events: &mut Vec<Event>,
) {
    for (dev_id, dev) in devices {
        let mut magnitude = Magnitude::zero();
        for (_, ref mut effect) in effects.iter_mut() {
            if effect.devices.contains_key(dev_id) {
                magnitude += effect.combine_base_effects(tick, dev.position);
                completion_events.extend(effect.flush_completion_events());
            }
        }
        trace!(
            "({:?}) Setting ff state of {:?} to {:?}",
            tick,
            dev,
            magnitude
        );
        dev.inner.set_ff_state(
            magnitude.strong,
            magnitude.weak,
            Duration::from_millis(u64::from(TICK_DURATION) * 2),
        );
    }
}